问:
How to import Python file?
Sorry, this is definitely a duplicate, but I can't find the answer. I'm working in Python 3 and this is the structure of my app:

```<code>/home
  common.py
  australia/
    new-south-wales/
      fetch.py
</code>```

I am in the home/ directory, running fetch.py. How can I import functions from common.py in that script?

I've set up fetch.py as follows:

```<code>from common import writeFile
</code>```

But I get the following error:

```<code>File "australia/new-south-wales/fetch.py", line 8, in <module>
    from common import writeFile
ModuleNotFoundError: No module named 'common'
</code>```

If I just do python -c "from common import writeFile" I don't see an error.

Shouldn't the interpreter look in the current directory for modules?

答:
From the description I'm assuming you're not running this as complete python package, just as separate files.

What you can do is use complete modules. This means adding empty __init__.py to directories with your code. You'll also have to change the name of new-south-wales to new_south_wales, since it needs to be a valid module name.

Assuming home is the name of your app, you should end up with:

```<code>home/
  __init__.py
  common.py
  australia/
    __init__.py
    new_south_wales/
      __init__.py
      fetch.py
</code>```

Next, you'll need a startup script for your app - this means either something simple like:

```<code>#!/usr/bin/env python
from australia.new_south_wales import fetch
fetch.your_main_function()
</code>```

Or you can add a setup.py with a full package description. If you specify entry points and the script will be automatically created.

Now that you're starting your code in context of a package, your fetch.py can do:

```<code>from ..common import writeFile
</code>```

Title: How to import Python file?

Body:
Sorry, this is definitely a duplicate, but I can't find the answer. I'm working in Python 3 and this is the structure of my app:

/home
  common.py
  australia/
    new-south-wales/
      fetch.py

I am in the home/ directory, running fetch.py. How can I import functions from common.py in that script?

I've set up fetch.py as follows:

from common import writeFile

But I get the following error:

File "australia/new-south-wales/fetch.py", line 8, in <module>
    from common import writeFile
ModuleNotFoundError: No module named 'common'

If I just do python -c "from common import writeFile" I don't see an error.

Shouldn't the interpreter look in the current directory for modules?

Body:
From the description I'm assuming you're not running this as complete python package, just as separate files.

What you can do is use complete modules. This means adding empty __init__.py to directories with your code. You'll also have to change the name of new-south-wales to new_south_wales, since it needs to be a valid module name.

Assuming home is the name of your app, you should end up with:

home/
  __init__.py
  common.py
  australia/
    __init__.py
    new_south_wales/
      __init__.py
      fetch.py

Next, you'll need a startup script for your app - this means either something simple like:

#!/usr/bin/env python
from australia.new_south_wales import fetch
fetch.your_main_function()

Or you can add a setup.py with a full package description. If you specify entry points and the script will be automatically created.

Now that you're starting your code in context of a package, your fetch.py can do:

from ..common import writeFile


来源: stackexchange

问:
CanvasRenderer.js:80 Uncaught TypeError: THREE.RenderableVertex is not a constructor
CanvasRenderer.js:80 Uncaught TypeError: THREE.RenderableVertex is not a constructor

This error were in the CanvasRenderer.js,I searched for the answer for long ,well there's no similar quertion.I just want to see the difference between WebGLRenderer and CanvasRenderer,but I meet this error.

答: You need to include the Projector.js file, which is not in the main Three.js build. THREE.RenderableVertex is defined in that file (no idea why).

ContentLicense: CC BY-SA 3.0


问:
Express sending assets with wrong MIME type
Using Express to serve a Vue.js webpack app, I am receiving the following error after deploy:

Is my code for serving the app is the issue here?

```<code>app.use(helmet())

app.use(express.static(path.resolve(__dirname, '../client/dist/static')));

app.all('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../client/dist', 'index.html'));
})
</code>```

Otherwise isn't express.static supposed to automatically assign content types to the static files?

答:
For some reason, had to now specify a mount path:</p>

```<code>app.use('/static', express.static(path.resolve(__dirname, '../client/dist/static')));
</code>```

Body:
Using Express to serve a Vue.js webpack app, I am receiving the following error after deploy:

Is my code for serving the app is the issue here?

app.use(helmet())

app.use(express.static(path.resolve(__dirname, '../client/dist/static')));

app.all('*', (req, res) => {
  res.sendFile(path.resolve(__dirname, '../client/dist', 'index.html'));
})

Otherwise isn't express.static supposed to automatically assign content types to the static files?

Body:
For some reason, had to now specify a mount path:

app.use('/static', express.static(path.resolve(__dirname, '../client/dist/static')));


问:
Best way to connect react to php
I am wondering what is the best way to connect backend wrote in php to front end code in ReactJS.

What is an option for that idea?

I am sure that when application have on backend laravel then I can use laravel-mix to use react on frontend, but is there any alternatives?

Maybe implement react to symfony, CakePHP or maybe just only simple PHP can run react on frontend.

I'm working on react application right now it is running on nodeJS but It is important for me to use PHP and MySQL on backend.

So I am looking for the easiest and cleanest solution.
Thank You for help.

答:
You should separate your frontend and backend stacks, with a REST interface in between. With the architecture, you will have more control of your both frontend and backend to choose your favorite tools, languages etc. For instance, you can work on React.js + Webpack + Babel for your frontend and Laravel / Symfony for the backend. </p>

<p>Please see this article with more details and advantages of doing this way. </p>

Title: Best way to connect react to php

Body:
You should separate your frontend and backend stacks, with a REST interface in between. With the architecture, you will have more control of your both frontend and backend to choose your favorite tools, languages etc. For instance, you can work on React.js + Webpack + Babel for your frontend and Laravel / Symfony for the backend.

Please see this article with more details and advantages of doing this way.


问:
Why won't web audio api oscillator play in Safari Mobile?
I have been trying to get an oscillator to play in a mobile browser on IOS (won't work in Chrome or Safari) and I am struggling. From the research I have done I have found that you must create the oscillator (and maybe even the context) on a touch event. What I have working on desktop is an oscillator that connects to a gain node and plays a sound on a mouseenter event on a span element. Then on a mouseout event it disconnects from the gain node so that on the next mouseenter event it will connect again thus being able to create a new sound every time a character is hovered on.

```<code>$(".hover-letters span").on("touchend mouseenter", function(){
    audioVariables($(this));
});

$(".hover-letters span").on("touchstart mouseout", function(){
    oscillator.disconnect(gainNode);
});

function audioVariables(element){
    resizeWindowWidth = parseInt($(window).width());
    frequency = mouseX/(resizeWindowWidth/600);
    type = element.parent().data("type");
    sound();
}

var firstLetterInteraction = true;

function sound() {
  if (firstLetterInteraction === true){
    audioCtx = new(window.AudioContext || window.webkitAudioContext)();
    oscillator = audioCtx.createOscillator();
    gainNode = audioCtx.createGain();
    oscillator.start();
  }

  oscillator.connect(gainNode);
  gainNode.connect(audioCtx.destination);

  oscillator.frequency.value = frequency;
  oscillator.type = type;

  firstLetterInteraction = false;
};
</code>```

For some reason the sound just won't play on IOS and is not showing any errors. I'm beginning to wonder if this is possible as even examples such as CaptureWiz example here:

How do I make Javascript beep?

and the example given on the Web Audio API site: http://webaudioapi.com/samples/oscillator/ do not work for me on mobile. Anybody have any ideas?

答:
This works for the oscillator</p>

```<code><script>
  var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
  var oscillator = audioCtx.createOscillator();
  var gainNode = audioCtx.createGain();
  oscillator.connect(gainNode);
  gainNode.connect(audioCtx.destination);
  oscillator.type = 'sine';
  oscillator.frequency.value = 300;
  gainNode.gain.value = 7.5;
</script>

<button onclick="oscillator.start();">play</button>
</code>```

Body:
I have been trying to get an oscillator to play in a mobile browser on IOS (won't work in Chrome or Safari) and I am struggling. From the research I have done I have found that you must create the oscillator (and maybe even the context) on a touch event. What I have working on desktop is an oscillator that connects to a gain node and plays a sound on a mouseenter event on a span element. Then on a mouseout event it disconnects from the gain node so that on the next mouseenter event it will connect again thus being able to create a new sound every time a character is hovered on.

$(".hover-letters span").on("touchend mouseenter", function(){
    audioVariables($(this));
});

$(".hover-letters span").on("touchstart mouseout", function(){
    oscillator.disconnect(gainNode);
});

function audioVariables(element){
    resizeWindowWidth = parseInt($(window).width());
    frequency = mouseX/(resizeWindowWidth/600);
    type = element.parent().data("type");
    sound();
}

var firstLetterInteraction = true;

function sound() {
  if (firstLetterInteraction === true){
    audioCtx = new(window.AudioContext || window.webkitAudioContext)();
    oscillator = audioCtx.createOscillator();
    gainNode = audioCtx.createGain();
    oscillator.start();
  }

  oscillator.connect(gainNode);
  gainNode.connect(audioCtx.destination);

  oscillator.frequency.value = frequency;
  oscillator.type = type;

  firstLetterInteraction = false;
};

For some reason the sound just won't play on IOS and is not showing any errors. I'm beginning to wonder if this is possible as even examples such as CaptureWiz example here:

How do I make Javascript beep?

and the example given on the Web Audio API site: http://webaudioapi.com/samples/oscillator/ do not work for me on mobile. Anybody have any ideas?

Body:
This works for the oscillator

<script>
  var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
  var oscillator = audioCtx.createOscillator();
  var gainNode = audioCtx.createGain();
  oscillator.connect(gainNode);
  gainNode.connect(audioCtx.destination);
  oscillator.type = 'sine';
  oscillator.frequency.value = 300;
  gainNode.gain.value = 7.5;
</script>

<button onclick="oscillator.start();">play</button>


问:
-alias is not recognized as an internal or external command windows
How can I fix this? I typed in the command prompt for Windows 10:

```<code>-alias androiddebugkey
</code>```

And this is the result:

-alias is not recognized as an internal or external command windows

答:
you may need using cmder which lets you add aliases just like linux.
and it only for alias xxxxxx but not -alias xxxxx

Body:
How can I fix this? I typed in the command prompt for Windows 10:

-alias androiddebugkey

And this is the result:

-alias is not recognized as an internal or external command windows


问:
how create JHipster application with Hazelcast
I want to create JHipster Application using Hazelcast. Can anyone give me some tips before starting?

Best regrds

Ismael

答:
Take a look at https://hazelcast.com/partner/jhipster/

You will find a link to a sample JHipster app that uses Hazelcast as Hibernate L2 cache, web session clustering etc.


问:
Xamarin/Android - java.lang.reflect.InvocationTargetException
I get this stacktrace in google play console (new vitals section) for many devices (Got 224 occurrences) but i really don't now how can i find the root cause of this error:

```<code>java.lang.RuntimeException:
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.reflect.InvocationTargetException:
  at java.lang.reflect.Method.invoke(Native Method:0)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
</code>```

Has anyone ever had this ? How can i find the root cause ?

Thanks

答:
I can't tell you what the problem with your app is, but I can shed some light on why you get such an opaque stacktrace.

In mid May 2017, Google changed the way crash data was collected. Previously, the only way crash data was collected was by reporting each individual crash. After the app crashed, users would be prompted to 'Report' the crash data next time the app was opened.

Now, users can opt-in to having crash data sent automatically, without having to deliberately report each individual crash (though the old system is still in place).

For some reason, crashes reported in Xamarin Android apps under the new system are missing a large part of the stack trace that was previously available under the old model. The underlying reason is related to the way exceptions triggered from within the Zygote part of Android are specialised instances of the java.lang.Error and java.lang.Exception classes, which somehow don't inherit from java.lang.Throwable which is what Xamarin uses.

There's a long and detailed discussion within the Xamarin bugzilla system here, https://bugzilla.xamarin.com/show_bug.cgi?id=56653. A key paragraph reads:

At present, it looks like Zygote and company are special-casing java.lang.Exception and java.lang.Error behavior. JavaProxyThrowable instead inherits from java.lang.Throwable -- the base class of Error and Exception -- and Zygote/etc. don't appear to support this.

Either way, the Xamarin developers have modified their systems and we just have to wait until the new version comes out.

In the meantime, you'll need to turn to other crash reporting systems like HockeyApp or Crashlytics to find out what's causing your specific problem.

Body:
I get this stacktrace in google play console (new vitals section) for many devices (Got 224 occurrences) but i really don't now how can i find the root cause of this error:

java.lang.RuntimeException:
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: java.lang.reflect.InvocationTargetException:
  at java.lang.reflect.Method.invoke(Native Method:0)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)

Has anyone ever had this ? How can i find the root cause ?

Thanks


问:
Fingerprint scanner in C# UWP application

Background

I want to make my question as specific as possible but still give a broad background of why I'm asking...
My goal is to create a brand new cross platform application which incorporates fingerprint recognition via the use of a reasonably high quality / accurate scanner. The requirements state that the application must allow lots of people to quickly be identified in quick succession (e.g. a line at a checkout). As well as do other stuff like communicate with a cloud based app etc...

I acquired a reasonably priced scanner (USB Hamster Pro 20 - Secugen) and obtained the .NET SDK and device drivers from the hardware vendor.

Initially I had imagined a Xamarin app but since device drivers are only available for Windows, Linux and Android I thought I would just settle for Windows. And as its a brand new app why not use UWP and take the benefits of UWP and Windows Store etc... . I want to develop this application in C#.NET and ideally target something like a surface pro tablet.

Upon inspection of the 3rd party dll provided with the SDK, I noticed that to enable Auto-On (event based scanning), a method signature requires the handle of the window which will receive the message of the event from the device driver. The docs say to override WndProc of the receiving "window" to handle the events.

Question

With this SDK(dll) am I forced to use WinForms or WPF? Is there something fancy I can do to capture these events from within a UWP or Console app?

Similar Questions

During my research, I found these similar questions on SO and (I think) they suggest that UWP is out of the question.

Message pump in .NET Windows service

How to receive simplest Windows message on UWP XAML MVVM app?

答:
UWP cannot receive window event messages, request your vendor to provide a library targeting UWP.

Or, more practical, I would suggest doing this in two steps,

First write a WinForm/WPF app that handles the scanner messages (by overriding WndProc), the window can be hidden so user won't even know there is another desktop app running.

After the WinForm/WPF is finished, wire it up with the UWP app, using various communication channels between a classic desktop application and a UWP app.


问:
Get Redux Form Values For Unknown Form
I have a component that contains related fields for composition in different forms. Sometimes it belongs to a FieldArray. The value of one fields must affect the presentation of another field.

Is there a clean way to access field values in this scenario?

```<code>const MyReusableFields = () => {
  return (
    <div>
      <Field
        component={TextField}
        name="fieldA"
      />
      {fieldA === 'something' && // How can he get fieldA's value here?
        <Field
          component={TextField}
          name="fieldB"
        />
      }
    </div>
  );
};
</code>```

I don't think I can use formValueSelector or getFormValues because I don't know the name of the form. Even if I knew the name of the form, I don't know the exact field name because under FieldArray it will have an unknowable prefix.

I'm imagining some ugly code searching through state, but I would prefer to use a pattern supported by the framework if it exists.

答:
I think I may have roughly answered your question here https://github.com/erikras/redux-form/issues/3103#issuecomment-312556081

If you are creating a UI widget for which there are a small number of inter-related fields Fields is perhaps what you want.

It is worth noting, that you can inject the form name from this.context._reduxForm.form - you can make a withFormName HOC to wrap connect and use ownProps.form inside connect to select the values you're looking for.

After this, it becomes architectural questions for you...

For example you seem to state that you don't know the field names because you don't know the context in which the Fields will be. But fieldNames are absolute unless you're using Form sections. For example a Field with name "hello" inside a field array will store it's value under store.form.formName.hello - not under the array prefixed value - unless you pass those prefixes to the component and manually do the prefixing (that's why fields.map returns field names).

The point is that you generally must know the names up front because you're the one specifying them to the Field/Fields components. If you are using FormSections, all three components have a name prop that will return the name taking into account the FormSection context.

For these reasons I cannot really see why you cannot use form value selectors or Fields to create conditional form value filling. Indeed, these really are the only standard ways that you can know the values for conditional rendering of fields.

Note if you use Fields you won't get proper registering/deregistering in the way you do with conditional field rendering but this may or may not matter to you.

Title: Get Redux Form Values For Unknown Form

Body:
I have a component that contains related fields for composition in different forms. Sometimes it belongs to a FieldArray. The value of one fields must affect the presentation of another field.

Is there a clean way to access field values in this scenario?

const MyReusableFields = () => {
  return (

      <Field
        component={TextField}
        name="fieldA"
      />
      {fieldA === 'something' && // How can he get fieldA's value here?
        <Field
          component={TextField}
          name="fieldB"
        />
      }

  );
};

I don't think I can use formValueSelector or getFormValues because I don't know the name of the form. Even if I knew the name of the form, I don't know the exact field name because under FieldArray it will have an unknowable prefix.

I'm imagining some ugly code searching through state, but I would prefer to use a pattern supported by the framework if it exists.


问:
What is the equivilent of whatis in powershell
I have learned the basics of using UNIX but I am now trying to learn how to use powershell. Most of the commands are similar or easy to find the equivalent of. However, I have not found the equivalent of whatis. Is there an equivalent? I have tried searching online but the search engines take "whatis" as being "what is". Is there anybody that knows what the equivalent is or if there is an equvalent at all?</p>

答:
use Get-Help to display help about cmdlets and concepts. It is your best friend when you can't remember commands

```<code>Get-Help <cmdlet>
</code>```

I would also suggest Get-Alias to see which UNIX commands map to PowerShell cmdlets

You can even create you own aliases. You can add whatis to map to get help.

```<code>New-Alias whatis Get-Help
</code>```

which would then allow you to do

```<code>whatis <cmdlet>
</code>```

For good measure, the second best command to get familiar with is

```<code>Get-Command
</code>```

Using Get-Command along side Get-Help will help (pun intended) you get up to speed with PowerShell. I do suggest using a filter with Get-Commad as the list tends to be very long. It allows wildcard filters

```<code>Get-Command *-command
</code>```

Body:
use Get-Help to display help about cmdlets and concepts. It is your best friend when you can't remember commands

Get-Help <cmdlet>

I would also suggest Get-Alias to see which UNIX commands map to PowerShell cmdlets

You can even create you own aliases. You can add whatis to map to get help.

New-Alias whatis Get-Help

which would then allow you to do

whatis <cmdlet>

For good measure, the second best command to get familiar with is

Get-Command

Using Get-Command along side Get-Help will help (pun intended) you get up to speed with PowerShell. I do suggest using a filter with Get-Commad as the list tends to be very long. It allows wildcard filters

Get-Command *-command


问:
Django ContentFile get_available_name() got an unexpected keyword argument 'max_length'
When I try to save an image object to an ImageField I get the following error:

get_available_name() got an unexpected keyword argument 'max_length'

The code looks like this:

```<code>imagen_url = form.cleaned_data['imagen_url']
respuesta = requests.get(imagen_url)
imagen = Image.open(StringIO(respuesta.content))
stringio_obj = StringIO()
imagen.save(stringio_obj, format="JPEG")
final_image = stringio_obj.getvalue()
carta.creador = request.user
carta.ultima_revision = datetime.today()
carta.save()
print("carta_id: %s" % carta.id)  # Works correctly till here

archivo_imagen = ContentFile(final_image, "0_" + carta.nombre)  # Guarda la original con un 0 adelante
carta.imagen_base.save("0_" + carta.nombre, archivo_imagen, save=True)
</code>```

When I try ty to save the ContentFile object to the model`s ImageField, it doesn't work. It used to work in a lower version of Django, but since I shifted to django 1.10, it stopped working.

The model is simple, it looks like this:

```<code>def ubicar_img_base(instance, filename):
    nombre_archivo = "0_" + slugify(instance.nombre) + ".jpeg"
    path = "/".join([instance.grupo.nombre, nombre_archivo])
    return path

class CartaMagicPy(models.Model):
    imagen_base = models.ImageField(null=True, upload_to=ubicar_img_base)
</code>```

Any advice will help

答: Ok, hope this is useful to someone sometime: I solved it updating boto and storages. This would sound familiar to you if you use amazon AWS.

Body:
When I try to save an image object to an ImageField I get the following error:

get_available_name() got an unexpected keyword argument 'max_length'

The code looks like this:

imagen_url = form.cleaned_data['imagen_url']
respuesta = requests.get(imagen_url)
imagen = Image.open(StringIO(respuesta.content))
stringio_obj = StringIO()
imagen.save(stringio_obj, format="JPEG")
final_image = stringio_obj.getvalue()
carta.creador = request.user
carta.ultima_revision = datetime.today()
carta.save()
print("carta_id: %s" % carta.id)  # Works correctly till here

archivo_imagen = ContentFile(final_image, "0_" + carta.nombre)  # Guarda la original con un 0 adelante
carta.imagen_base.save("0_" + carta.nombre, archivo_imagen, save=True)

When I try ty to save the ContentFile object to the model`s ImageField, it doesn't work. It used to work in a lower version of Django, but since I shifted to django 1.10, it stopped working.

The model is simple, it looks like this:

def ubicar_img_base(instance, filename):
    nombre_archivo = "0_" + slugify(instance.nombre) + ".jpeg"
    path = "/".join([instance.grupo.nombre, nombre_archivo])
    return path

class CartaMagicPy(models.Model):
    imagen_base = models.ImageField(null=True, upload_to=ubicar_img_base)

Any advice will help


问:
jQuery equivalent of getting the context of a Canvas
I have the following working code:

```<code>ctx = document.getElementById("canvas").getContext('2d');
</code>```

Is there any way to re-write it to use $? Doing this fails:

```<code>ctx = $("#canvas").getContext('2d');
</code>```

答:
The script works before it finds "canvas"</p>

```<code> $(document).ready(function() {
   ctx = $("#canvas");
});
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have the following working code:

ctx = document.getElementById("canvas").getContext('2d');

Is there any way to re-write it to use $? Doing this fails:

ctx = $("#canvas").getContext('2d');

Body:
The script works before it finds "canvas"

 $(document).ready(function() {
   ctx = $("#canvas");
});


问:
How do I grab console output from a program running in a screen session?
I'm currently in the process of hacking together a bit of bash and python3 to integrate my Minecraft server with my friends Discord. I managed to power through most of the planned features with nary a hitch, however now I've gotten myself stuck halfway into the chat integration. I can send messages from the Discord to the server no problem, but I have no idea how to read the console output of the server instance, which is running in a screen session.

I would appreciate some pointers in the right direction, if you know how this sort of thing is done. Ideally I would like a solution that is capable of running asynchronously, so I don't have to do a whole lot of busy-waiting to check for messages.

P.S.: Sorry if this belongs on superuser instead, I wasn't sure where to put it.

答: Well, the ideal solution would be to write a bukkit plugin/forge mod to do this, rather than doing this entirely from outside the actual server. That being said, however, your best bet is probably watching the log files, as JNevill says in the comment.


问:
Session ID vs token
We are building an iOS application that will use our API to interact with our existing website. The website uses standard PHP sessions to keep track of logged in users.

How do we handle user log-in in the application? Do we use sessions + session ID's as we are doing on the website or another method?

I've seen API tokens mentioned a lot but I've yet to find a solid description that explains the difference between Session ID's and API tokens, or is an API token just another name for a session ID?

答:
Sessions are basically for authorization when using an application after access tokens have been confirmed. This has been well covered in this post.
What is an API token</p>

Title: Session ID vs token


问:
Troubleshooting the websocket limit in Azure, active connections
I'm in the process of troubleshooting an App Service that is using websockets.
It's running on service plan Basic which allows for 350 websockets.
This is the only app on that plan that uses websockets.

The problem is that after abou 20 hours I get 503 responses saying I reached my websocket limit.

The setup right now has 3 clients connecting to the service.

In the process of investigating websocket leakage in my app I would like to track the number of websockets in use.

Is there anywhere, from my app or in Azure portal, where I can see the number of active websocket connections?

Follow up:

I've logged the websocket connections as Amor suggested.
The HTTP part of my app is still working, I can get dynamic results from the app which now reports what websocket connections are active and how many has been created since start.

After restarting the app service and configured one client to reconnect indefinetely.

It worked fine until the "total websocket connections" reached 350. At this time I shut down the client.

The limit should be 350 concurrent connections but it looks like it is 350 in total since start.
Most (at least 340) of these connections were initiated by a single client which disposed each connection before starting a new one, it has been shutdown once the limit was reached.

I've been suggested to upgrade from Basic to Standard since standard doesn't have the artificial limitation. The only reason I can see this work would be if there is a bug in the websocket limitation for the Basic plan.

Update 2

In parallel I've been in contact with Microsoft Developer Support and they noticed what appears to be that the sockets are stuck in IIS whereas not in Kestrel. The cause of this is still being investigated.

Support could show me graphs of the connection usage over time which clearly showed how the limit was reached.

I'll keep this question updated in case there was some error in my code.

答:
I suggest you define a variable to count the connections. If a web socket connection is opened, just increase the number of connections. If a web socket connection is closed, decrease the number of connections. Code below is for your reference.

Count the connections for ASP.NET SignalR.

```<code>public class MyHub : Hub
{
    private int _connectionCount = 0;

    public override Task OnConnected()
    {
        _connectionCount++;
        return base.OnConnected();
    }

    public override Task OnReconnected()
    {
        _connectionCount++;
        return base.OnReconnected();
    }

    public override Task OnDisconnected(bool stopCalled)
    {
        _connectionCount--;
        return base.OnDisconnected(stopCalled);
    }
}
</code>```

Count the connections in traditional ASP.NET.

```<code>public class WSChatController : ApiController
{
    private int _connectionCount = 0;

    public HttpResponseMessage Get()
    {
        if (HttpContext.Current.IsWebSocketRequest)
        {
            HttpContext.Current.AcceptWebSocketRequest(ProcessWSChat);
        }
        return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
    }

    private async Task ProcessWSChat(AspNetWebSocketContext context)
    {
        WebSocket socket = context.WebSocket;
        while (true)
        {
            ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
            WebSocketReceiveResult result = await socket.ReceiveAsync(
                buffer, CancellationToken.None);
            if (socket.State == WebSocketState.Open)
            {
                _connectionCount++;
                //Process the request
            }
            else
            {
                _connectionCount--;
                break;
            }
        }
    }
}
</code>```

Body:
I suggest you define a variable to count the connections. If a web socket connection is opened, just increase the number of connections. If a web socket connection is closed, decrease the number of connections. Code below is for your reference.

Count the connections for ASP.NET SignalR.

public class MyHub : Hub
{
    private int _connectionCount = 0;

    public override Task OnConnected()
    {
        _connectionCount++;
        return base.OnConnected();
    }

    public override Task OnReconnected()
    {
        _connectionCount++;
        return base.OnReconnected();
    }

    public override Task OnDisconnected(bool stopCalled)
    {
        _connectionCount--;
        return base.OnDisconnected(stopCalled);
    }
}

Count the connections in traditional ASP.NET.

public class WSChatController : ApiController
{
    private int _connectionCount = 0;

    public HttpResponseMessage Get()
    {
        if (HttpContext.Current.IsWebSocketRequest)
        {
            HttpContext.Current.AcceptWebSocketRequest(ProcessWSChat);
        }
        return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols);
    }

    private async Task ProcessWSChat(AspNetWebSocketContext context)
    {
        WebSocket socket = context.WebSocket;
        while (true)
        {
            ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]);
            WebSocketReceiveResult result = await socket.ReceiveAsync(
                buffer, CancellationToken.None);
            if (socket.State == WebSocketState.Open)
            {
                _connectionCount++;
                //Process the request
            }
            else
            {
                _connectionCount--;
                break;
            }
        }
    }
}


问:
neo4j cypher store array property during csv import
I need to import data from a csv of the form

```<code>id;name;targetset
1;"somenode",[1,3,5,8]
2,"someothernode",[3,8]
</code>```

into the graph and I need to have targetset stored as collection (array) using cypher. I tried

```<code>USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM "file:/mytable.csv" AS row FIELDTERMINATOR ';'
CREATE (:MyNode {id: row.id, name: row.name, targetset: row.targetset});
</code>```

but it stores targetset as a string, e.g. "[1,3,5,8]". There does not seem to be a function to convert array-encoding-strings to actual arrays, like there is toInt to convert strings to integers. Is there still another possibility?

答:
APOC Procedures will be your best bet here. Use the function apoc.convert.fromJsonList().

An example of use:

```<code>WITH "[1,3,5,8]" as arr
RETURN apoc.convert.fromJsonList(arr)
</code>```

Body:
I need to import data from a csv of the form

id;name;targetset
1;"somenode",[1,3,5,8]
2,"someothernode",[3,8]

into the graph and I need to have targetset stored as collection (array) using cypher. I tried

USING PERIODIC COMMIT
LOAD CSV WITH HEADERS FROM "file:/mytable.csv" AS row FIELDTERMINATOR ';'
CREATE (:MyNode {id: row.id, name: row.name, targetset: row.targetset});

but it stores targetset as a string, e.g. "[1,3,5,8]". There does not seem to be a function to convert array-encoding-strings to actual arrays, like there is toInt to convert strings to integers. Is there still another possibility?

Body:
APOC Procedures will be your best bet here. Use the function apoc.convert.fromJsonList().

An example of use:

WITH "[1,3,5,8]" as arr
RETURN apoc.convert.fromJsonList(arr)


问:
Sending message from child process to parent process when creating child_process with exec()
I have a parent process in Node.JS which creates a child process through calling exec.
I want to wait until the child process finish and return the status of the child process.

I don't want to use spawn or fork.

I'm creating the child_process with require('child_process').exec

I need the child process to send message to the parent process through IPC:

```<code>function foo()
{
    const exec = require('child_process').exec;

     const cmd = `cd /usr/lib/bin' && db-migrate --config "config/${environmentName}.json" -e ${environmentName} -v true up  --force-exit`;

    const child = exec(cmd, (error, stdout, stderr) => {
         //...
    });

    child.on('exit', (code) => {
       //from here i want to know if there was a problem in child process
       //can I use IPC to send messages?
    });
     //wants to return the child status code from here
 return child_status_code;
}
</code>```

How can i solve this problem?

How can I use IPC from child process to parent process?

答:
If there is a IPC channel created in process, you are able to send message from child to parent by "process.send“. It is addressed in documentation of Nodejs.
The IPC channel is only available by "fork". "fork" has the first parameter is module path.</p>

Body:
I have a parent process in Node.JS which creates a child process through calling exec.
I want to wait until the child process finish and return the status of the child process.

I don't want to use spawn or fork.

I'm creating the child_process with require('child_process').exec

I need the child process to send message to the parent process through IPC:

function foo()
{
    const exec = require('child_process').exec;

     const cmd = `cd /usr/lib/bin' && db-migrate --config "config/${environmentName}.json" -e ${environmentName} -v true up  --force-exit`;

    const child = exec(cmd, (error, stdout, stderr) => {
         //...
    });

    child.on('exit', (code) => {
       //from here i want to know if there was a problem in child process
       //can I use IPC to send messages?
    });
     //wants to return the child status code from here
 return child_status_code;
}

How can i solve this problem?

How can I use IPC from child process to parent process?


问:
Trying to hide all bbcode-generated divs within a span, but it isn't working
Here's an example of the html:

```<code><!-- Working Example-->
<span class='prv' style='cursor: pointer; cursor: hand';>
    This text is shown...
</span>
<span class='cnt' style='cursor: pointer; cursor: hand';>
    This text will be hidden on load and shown when the 'prv' class is clicked.
</span>
<!-- Broken Example-->
<span class='prv' style='cursor: pointer; cursor: hand';>
    This text is shown...</span>
<span class='cnt' style='cursor: pointer; cursor: hand';>
    <div class="bbcode_center" style="text-align:center">
        This text isn't hidden even though I want it to be.
    </div>
</span>
</code>```

In the working example, there aren't any bbcode tags, so no bbcode class divs are generated - but I can't just get rid of the bbcode tags because I need them displayed.

Here the jquery code:

```<code>function run_on_load() {
    $('.cnt').hide();
    //$('.cnt').children().hide(); <- Tried this too
}
$('.prv').click(function() {
    $('.prv').hide();
    $('.cnt').show();
});
$('.cnt').click(function() {
    $('.cnt').hide();
    $('.prv').show();
});
</code>```

This all works for the first example, but hides nothing in the second example. How do I make it so that the jquery code hides everything within the 'cnt' class span indiscriminately?

Also, the span in the broken example isn't clickable, apparently for the same reason. Is there a way to make all divs within the span clickable, like having a jquery findall type function add the clickable style to each individual bbcode class div?

Edit: To be clear, what happens in the working example is exactly what I want: 'prv' (the preview text) is shown, and when it is clicked it hides itself and instead shows 'cnt' (the full content/text). The only issue with the broken example is that nothing within bbcode divs in 'cnt' is ever hidden when I want it all hidden indiscriminately.

答:
What you're looking for is to wrap the .hide() inside a $(document).ready(function() {}).

$(document).ready(function() {
  $('.cnt').hide();
});

$('.prv').click(function() {
  $('.prv').hide();
  $('.cnt').show();
});

$('.cnt').click(function() {
  $('.cnt').hide();
  $('.prv').show();
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class='prv' style='cursor: pointer; cursor: hand'>
    This text is shown...
</span>
<span class='cnt' style='cursor: pointer; cursor: hand'>
    <div class="bbcode_center" style="text-align:center">
        This text isn't hidden even though I want it to be.
    </div>
</span></code>```

This way, clicking on the preview hides the preview and shows the full content, and clicking on the full content hides it and shows the preview.

Hope this helps! :)

Body:
Here's an example of the html:

    This text is shown...

    This text will be hidden on load and shown when the 'prv' class is clicked.

    This text is shown...

        This text isn't hidden even though I want it to be.

In the working example, there aren't any bbcode tags, so no bbcode class divs are generated - but I can't just get rid of the bbcode tags because I need them displayed.

Here the jquery code:

function run_on_load() {
    $('.cnt').hide();
    //$('.cnt').children().hide(); <- Tried this too
}
$('.prv').click(function() {
    $('.prv').hide();
    $('.cnt').show();
});
$('.cnt').click(function() {
    $('.cnt').hide();
    $('.prv').show();
});

This all works for the first example, but hides nothing in the second example. How do I make it so that the jquery code hides everything within the 'cnt' class span indiscriminately?

Also, the span in the broken example isn't clickable, apparently for the same reason. Is there a way to make all divs within the span clickable, like having a jquery findall type function add the clickable style to each individual bbcode class div?

Edit: To be clear, what happens in the working example is exactly what I want: 'prv' (the preview text) is shown, and when it is clicked it hides itself and instead shows 'cnt' (the full content/text). The only issue with the broken example is that nothing within bbcode divs in 'cnt' is ever hidden when I want it all hidden indiscriminately.

Body:
What you're looking for is to wrap the .hide() inside a $(document).ready(function() {}).

$(document).ready(function() {
  $('.cnt').hide();
});

$('.prv').click(function() {
  $('.prv').hide();
  $('.cnt').show();
});

$('.cnt').click(function() {
  $('.cnt').hide();
  $('.prv').show();
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class='prv' style='cursor: pointer; cursor: hand'>
    This text is shown...
</span>
<span class='cnt' style='cursor: pointer; cursor: hand'>
    <div class="bbcode_center" style="text-align:center">
        This text isn't hidden even though I want it to be.
    </div>
</span>

This way, clicking on the preview hides the preview and shows the full content, and clicking on the full content hides it and shows the preview.

Hope this helps! :)


问:
How to check whether an element is Present inside another element or not in Jquery?
I have an html code which add elements  dynamically.
On button click i wanted to check whether the elements present inside the
div or not

HTML :

```<code><div id="mainDiv">
<span class="child">span1</span>
</div>
<button id="check"></button>
</code>```

JQuery:

```<code>$(function() {
$("#check").click(function(){
   // exist or not
});
</code>```

答:
You are looking for child element inside parent. It means you know the parent element already exists. So, you should use jQuery context selector as

```<code>$(function() {
    $("#check").click(function(){
        // exist or not
        if($('.child', '#mainDiv').length) {
            console.log('Yes!! element exists');
        } else {
            console.log('Nope!!');
        }
    });
});
</code>```

You can also use $('#mainDiv').find('.child').length to check if it contains the element with class child.

You can find more details on context selectors at http://www.tutorialsteacher.com/jquery/jquery-selectors

Body:
I have an html code which add elements  dynamically.
On button click i wanted to check whether the elements present inside the
div or not

HTML :

span1

<button id="check"></button>

JQuery:

$(function() {
$("#check").click(function(){
   // exist or not
});

Body:
You are looking for child element inside parent. It means you know the parent element already exists. So, you should use jQuery context selector as

$(function() {
    $("#check").click(function(){
        // exist or not
        if($('.child', '#mainDiv').length) {
            console.log('Yes!! element exists');
        } else {
            console.log('Nope!!');
        }
    });
});

You can also use $('#mainDiv').find('.child').length to check if it contains the element with class child.

You can find more details on context selectors at http://www.tutorialsteacher.com/jquery/jquery-selectors


问:
No User Info saved with Office 365 Login (ADAL.js)
I am using ADAL.js library for authenticating my Excel add-in via Office 365 Login. I am using an Azure AD application for this and have granted the required permissions too. The settings I have used with ADAL.js are below:

```<code>var config = {
    tenant: tenant,
    clientId: clientId,
    redirectUri: redirectUrl,
    postLogoutRedirectUri: logoutUrl,
    extraQueryParameter: 'scope=openid+profile',
    cacheLocation: 'localStorage'
};
</code>```

The login works fine. It redirects properly to the add-in homepage but the user information is not retrievable using the getCachedUser function. All I get is a null value. Am I doing something wrong here?

答:
Instead of using the adal library, Microsoft recommend using the office-js-helpers to authorize external services with the implicit flow.

Here is a code spinet to authenticate with Azure AD app:

```<code>var authenticator = new OfficeHelpers.Authenticator();

// register Microsoft (Azure AD 2.0 Converged auth) endpoint using
authenticator.endpoints.registerMicrosoftAuth('client id here');

// register Azure AD 1.0 endpoint using
authenticator.endpoints.registerAzureADAuth('client id here', 'tenant here');
</code>```

Authentication

```<code>// for the default AzureAD endpoint
authenticator
    .authenticate(OfficeHelpers.DefaultEndpoints.AzureAD)
    .then(function (token) { /* Microsoft Token */ })
    .catch(OfficeHelpers.Utilities.log);
</code>```

Getting a cached token

```<code>authenticator
    .authenticate('name of endpoint')
    .then(function(token) {
    /*
        `token` is either cached or newly obtained upon expiry.
    */
    })
    .catch(OfficeHelpers.Utilities.log);

authenticator
    .authenticate('name of endpoint', true /* force re-authentication */)
    .then(function(token) {
    /*
        `token` is newly obtained.
    */
    })
    .catch(OfficeHelpers.Utilities.log);

// get the cached token if any. returns null otherwise.
var token = authenticator.tokens.get('name of endpoint');
</code>```

More detail about this library, you can refer this link. And below document is also helpful about authorize in Office add-in:

Authorize external services in your Office Add-in

Body:
I am using ADAL.js library for authenticating my Excel add-in via Office 365 Login. I am using an Azure AD application for this and have granted the required permissions too. The settings I have used with ADAL.js are below:

var config = {
    tenant: tenant,
    clientId: clientId,
    redirectUri: redirectUrl,
    postLogoutRedirectUri: logoutUrl,
    extraQueryParameter: 'scope=openid+profile',
    cacheLocation: 'localStorage'
};

The login works fine. It redirects properly to the add-in homepage but the user information is not retrievable using the getCachedUser function. All I get is a null value. Am I doing something wrong here?

Body:
Instead of using the adal library, Microsoft recommend using the office-js-helpers to authorize external services with the implicit flow.

Here is a code spinet to authenticate with Azure AD app:

var authenticator = new OfficeHelpers.Authenticator();

// register Microsoft (Azure AD 2.0 Converged auth) endpoint using
authenticator.endpoints.registerMicrosoftAuth('client id here');

// register Azure AD 1.0 endpoint using
authenticator.endpoints.registerAzureADAuth('client id here', 'tenant here');

Authentication

// for the default AzureAD endpoint
authenticator
    .authenticate(OfficeHelpers.DefaultEndpoints.AzureAD)
    .then(function (token) { /* Microsoft Token */ })
    .catch(OfficeHelpers.Utilities.log);

Getting a cached token

authenticator
    .authenticate('name of endpoint')
    .then(function(token) {
    /*
        `token` is either cached or newly obtained upon expiry.
    */
    })
    .catch(OfficeHelpers.Utilities.log);

authenticator
    .authenticate('name of endpoint', true /* force re-authentication */)
    .then(function(token) {
    /*
        `token` is newly obtained.
    */
    })
    .catch(OfficeHelpers.Utilities.log);

// get the cached token if any. returns null otherwise.
var token = authenticator.tokens.get('name of endpoint');

More detail about this library, you can refer this link. And below document is also helpful about authorize in Office add-in:

Authorize external services in your Office Add-in


问:
IE.document.all returns null element vba
Does anyone know why this ExplorerButton.Click returns a 424 object reference error on run? HTML modules were correctly imported to be able to read the html related commands:

```<code>Private Sub Generate_Click()

Dim IE As New InternetExplorer
Dim ExplorerInput As HTMLInputElement
Dim ExplorerButton As HTMLInputElement

'Loading Page
IE.navigate "https://www.earthpoint.us/ExcelToKml.aspx"
'Show Window
IE.Visible = True
'Wait for loade
WaitIE IE
'Select document
Set IEDoc = IE.document

'Select Button
 Set ExplorerButton = IEDoc.all.Item("FileUpload1")
'Click button
ExplorerButton.Click --> ERROR 424

End Sub

Sub WaitIE(IE As InternetExplorer)
   'Loop until load
   Do Until IE.readyState = READYSTATE_COMPLETE
      DoEvents
   Loop
End Sub
</code>```

I indicated the error with --> ERROR 424. I must be miss-referencing the page... When I looked up tutorials like this one http://qwazerty.developpez.com/tutoriels/vba/ie-et-vba-excel/ , which is really well brought about, this is how the reference was adressed and it seemed to work for him (and for me on the page he mentions). So I guess I must be omitting something when defining the button element. Any help much appreciated!

Thanks!
D.

答:
I think you've forgotten to declare the IEDoc variable like this :

```<code>Dim IEDoc As HTMLDocument
</code>```

Try this and it will work !

Body:
Does anyone know why this ExplorerButton.Click returns a 424 object reference error on run? HTML modules were correctly imported to be able to read the html related commands:

Private Sub Generate_Click()

Dim IE As New InternetExplorer
Dim ExplorerInput As HTMLInputElement
Dim ExplorerButton As HTMLInputElement

'Loading Page
IE.navigate "https://www.earthpoint.us/ExcelToKml.aspx"
'Show Window
IE.Visible = True
'Wait for loade
WaitIE IE
'Select document
Set IEDoc = IE.document

'Select Button
 Set ExplorerButton = IEDoc.all.Item("FileUpload1")
'Click button
ExplorerButton.Click --> ERROR 424

End Sub

Sub WaitIE(IE As InternetExplorer)
   'Loop until load
   Do Until IE.readyState = READYSTATE_COMPLETE
      DoEvents
   Loop
End Sub

I indicated the error with --> ERROR 424. I must be miss-referencing the page... When I looked up tutorials like this one http://qwazerty.developpez.com/tutoriels/vba/ie-et-vba-excel/ , which is really well brought about, this is how the reference was adressed and it seemed to work for him (and for me on the page he mentions). So I guess I must be omitting something when defining the button element. Any help much appreciated!

Thanks!
D.

Body:
I think you've forgotten to declare the IEDoc variable like this :

Dim IEDoc As HTMLDocument

Try this and it will work !


问:
Is there a way of limiting stdlib functions' visibility in Kotlin?
Kotlin comes with many standard library functions, a lot of which are visible by default without actually importing them. So functions like listOf, arrayListOf, ArrayList<T>(), ... are de facto inserted into global namespace. Is there a compiler flag that would disable this behavior?

答:
Sadly, you can't. just as you can't prohibit the auto-imported java.lang package in java.

You don't need to worry about the auto-imported top-level functions. If you don't use any top-level functions, there is no Class Reference/Method Reference emitted to the Java byte code. And all of the *arrayOf functions will be transformed to Java array creation, for example:

```<code>Kotlin          |        Java
------------------------------------
byteArrayOf     |    new byte[]
------------------------------------
shortArrayOf    |    new short[]
------------------------------------
intArrayOf      |    new int[]
------------------------------------
longArrayOf     |    new long[]
------------------------------------
floatArrayOf    |    new float[]
------------------------------------
doubleArrayOf   |    new double[]
------------------------------------
charArrayOf     |    new char[]
------------------------------------
booleanArrayOf  |    new boolean[]
------------------------------------
arrayOf<T>      |    new T[]
------------------------------------
</code>```

Body:
Sadly, you can't. just as you can't prohibit the auto-imported java.lang package in java.

You don't need to worry about the auto-imported top-level functions. If you don't use any top-level functions, there is no Class Reference/Method Reference emitted to the Java byte code. And all of the *arrayOf functions will be transformed to Java array creation, for example:

Kotlin          |        Java
------------------------------------
byteArrayOf     |    new byte[]
------------------------------------
shortArrayOf    |    new short[]
------------------------------------
intArrayOf      |    new int[]
------------------------------------
longArrayOf     |    new long[]
------------------------------------
floatArrayOf    |    new float[]
------------------------------------
doubleArrayOf   |    new double[]
------------------------------------
charArrayOf     |    new char[]
------------------------------------
booleanArrayOf  |    new boolean[]
------------------------------------
arrayOf<T>      |    new T[]
------------------------------------


问:
Issue with :last-child on a list item Menu
Here's my updated JSFIDDLE: https://jsfiddle.net/axosonns/2/

HTML:

```<code><ul class="whatever">
  <li><a href="#">Menu1</a></li>
  <li><a href="#">Menu2</a></li>
  <li><a href="#">Menu3</a></li>
  <li><a href="#">Menu4</a></li>
</ul>
</code>```

CSS:

```<code>.whatever li {
  display: inline-block;
}
.whatever li>a {
  background: grey;
  padding: 10px 15px;
}
.whatever li>a:last-child {
  padding: 10px 0 10px 15px;
  background-color: red;
}
</code>```

The last-child css code isn't working. I want only the last menu to have padding: 0px;

What am I doing wrong?

答:
Your question is a little unclear. If you're trying to make the whole colored-background area clickable, you were on the right track - use padding on the a, not the li. You can still target the one you need, just tweak the selectors a little. Here's a fork with that.

.whatever li {
  display: inline-block;
}

.whatever li a {
  background: grey;
  display: block;
  padding: 10px 15px;
}
.whatever li:last-child a {
  padding: 10px 0 10px 15px;
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="whatever">
  <li>Menu1</li>
  <li>Menu2</li>
  <li>Menu3</li>
  <li>Menu4</li>
</ul></code>```

Body:
Here's my updated JSFIDDLE: https://jsfiddle.net/axosonns/2/

HTML:

Menu1

Menu2

Menu3

Menu4

CSS:

.whatever li {
  display: inline-block;
}
.whatever li>a {
  background: grey;
  padding: 10px 15px;
}
.whatever li>a:last-child {
  padding: 10px 0 10px 15px;
  background-color: red;
}

The last-child css code isn't working. I want only the last menu to have padding: 0px;

What am I doing wrong?

Body:
Your question is a little unclear. If you're trying to make the whole colored-background area clickable, you were on the right track - use padding on the a, not the li. You can still target the one you need, just tweak the selectors a little. Here's a fork with that.

.whatever li {
  display: inline-block;
}

.whatever li a {
  background: grey;
  display: block;
  padding: 10px 15px;
}
.whatever li:last-child a {
  padding: 10px 0 10px 15px;
  background-color: red;
}

<ul class="whatever">
  <li><a href="#">Menu1</a></li>
  <li><a href="#">Menu2</a></li>
  <li><a href="#">Menu3</a></li>
  <li><a href="#">Menu4</a></li>
</ul>


问:
Reset select2 value and show placeholder
How do I set the placeholder on value reset by select2. In my example If locations or grade select boxes are clicked and my select2 has a value than the value of select2 should reset and show the default placeholder. This script is resetting the value but won't show the placeholder</p>

```<code>$("#locations, #grade ").change(function() {
   $('#e6').select2('data', {
     placeholder: "Studiengang wählen",
     id: null,
     text: ''
   });
});

$("#e6").select2({
   placeholder: "Studiengang wählen",
   width: 'resolve',
   id: function(e) {
     return e.subject;
   },
   minimumInputLength: 2,
   ajax: {
     url: "index.php?option=com_unis&task=search.locator&tmpl=component&<?php echo JSession::getFormToken() ?>=1",
     dataType: 'json',
     data: function(term, page) {
       return {
         q: term, // search term
         g: $('#grade option:selected').val(),
         o: $('#locations option:selected').val()
       };
     },
     results: function(data, page) {
       return {
         results: data
       };
     }
   },
   formatResult: subjectFormatResult,
   formatSelection: subjectFormatSelection,
   dropdownCssClass: "bigdrop",
   escapeMarkup: function(m) {
     return m;
   }
});
</code>```

答:
as of v.4.0.x...

to clear the values, but also restore the placeholder use...

```<code>.html('<option></option>');  // defaults to placeholder
</code>```

if it's empty, it will select the first option item instead which may not be what you want

```<code>.html(''); // defaults to whatever item is first
</code>```

frankly...Select2 is such a pain in the butt, it amazes me it hasn't been replaced.

Body:
How do I set the placeholder on value reset by select2. In my example If locations or grade select boxes are clicked and my select2 has a value than the value of select2 should reset and show the default placeholder. This script is resetting the value but won't show the placeholder

$("#locations, #grade ").change(function() {
   $('#e6').select2('data', {
     placeholder: "Studiengang wählen",
     id: null,
     text: ''
   });
});

$("#e6").select2({
   placeholder: "Studiengang wählen",
   width: 'resolve',
   id: function(e) {
     return e.subject;
   },
   minimumInputLength: 2,
   ajax: {
     url: "index.php?option=com_unis&task=search.locator&tmpl=component&<?php echo JSession::getFormToken() ?>=1",
     dataType: 'json',
     data: function(term, page) {
       return {
         q: term, // search term
         g: $('#grade option:selected').val(),
         o: $('#locations option:selected').val()
       };
     },
     results: function(data, page) {
       return {
         results: data
       };
     }
   },
   formatResult: subjectFormatResult,
   formatSelection: subjectFormatSelection,
   dropdownCssClass: "bigdrop",
   escapeMarkup: function(m) {
     return m;
   }
});

Body:
as of v.4.0.x...

to clear the values, but also restore the placeholder use...

.html('<option></option>');  // defaults to placeholder

if it's empty, it will select the first option item instead which may not be what you want

.html(''); // defaults to whatever item is first

frankly...Select2 is such a pain in the butt, it amazes me it hasn't been replaced.


问:
Web audio API does not play sound Continuously
I am trying to buffer MP3 songs using node js and socket io in real time. I basically divide the MP3 into segments of bytes and send it over to the client side where the web audio API will receive it, decode it and start to play it. The issue here is that the sound does not play continuously, there is a something like a 0.5 seconds gap between every buffered segment. How can I solve this problem

```<code>// buffer is a 2 seconds decoded audio ready to be played
// the function is called  when a new buffer is recieved
function stream(buffer)
{
    // creates a new buffer source and connects it to the Audio context
    var source = context.createBufferSource();
    source.buffer = buffer;
    source.connect(context.destination);
    source.loop = false;
    // sets it and updates the time
    source.start(time + context.currentTime);

    time += buffer.duration; // time is global variable initially set to zero
}
</code>```

The part where stream is called

```<code>    // where stream bufferQ is an array of decoded MP3 data
    // so the stream function is called after every 3 segments that are recieved
     // the Web audio Api plays it with gaps between the sound
    if(bufferQ.length == 3)
    {
        for(var i = 0, n = bufferQ.length ; i < n; i++)
        {
              stream(bufferQ.splice(0,1)[0]);
        }
    }
</code>```

should I use a different API other than the web audio API or is there a way to schedule my buffer so that it would be played continuously ?

答:
It's an issue with mp3 files, each mp3 file has a few frames of silence at the start and end.
If you use wav files or time the start and stop of each file properly you can fix it</p>

Body:
I am trying to buffer MP3 songs using node js and socket io in real time. I basically divide the MP3 into segments of bytes and send it over to the client side where the web audio API will receive it, decode it and start to play it. The issue here is that the sound does not play continuously, there is a something like a 0.5 seconds gap between every buffered segment. How can I solve this problem

// buffer is a 2 seconds decoded audio ready to be played
// the function is called  when a new buffer is recieved
function stream(buffer)
{
    // creates a new buffer source and connects it to the Audio context
    var source = context.createBufferSource();
    source.buffer = buffer;
    source.connect(context.destination);
    source.loop = false;
    // sets it and updates the time
    source.start(time + context.currentTime);

    time += buffer.duration; // time is global variable initially set to zero
}

The part where stream is called

    // where stream bufferQ is an array of decoded MP3 data
    // so the stream function is called after every 3 segments that are recieved
     // the Web audio Api plays it with gaps between the sound
    if(bufferQ.length == 3)
    {
        for(var i = 0, n = bufferQ.length ; i < n; i++)
        {
              stream(bufferQ.splice(0,1)[0]);
        }
    }

should I use a different API other than the web audio API or is there a way to schedule my buffer so that it would be played continuously ?


问:
Average Interval based on boundaries given by other vectors - "R"
Allow me to give an Excel example.

Imagine the following data as Excel columns:

A1=5 | A2=3 |  A3=7  | A4=11 |  A5=23 |  A6=15  | A7=17    then   B1=1 | B2=4    also     C1=3 | C2=7

I would like to create a column "D" that calculates an average of column "A" with criteria based on columns B and C. So, in this example D1=(Average of A1 to A3) based on B1=1 and C1=3... then D2=(Average of A4 to A7), based on B2=4 and C2=7.

The way this can be done on Excel is D1 = AVERAGE(INDIRECT(CONCATENATE("A",B1)):INDIRECT(CONCATENATE("A",C1))) and of course D2 = AVERAGE(INDIRECT(CONCATENATE("A",B2)):INDIRECT(CONCATENATE("A",C2)))

So D1 concatenation will fuse "A" with "1" because B1=1 and fuse "A" with "3" because C1=3
same with D2 ...... Average(A4:A7)

This seems impossible with R because I can't see how you can fuse a number with a column to locate a specific cell and then feed it to the mean function to average a specific range.

I think answering this one will provide many tools that go well beyond this problem.

Edit:

Thank you Chi Pak

答:
A vector of values, like in column A:

```<code>set.seed(1)
A <- sample(1:100,10)

[1] 66 13 27 38  2 37 82 32 45 55
</code>```

A data.frame of values, like in columns B and C:

```<code>df <- data.frame( B = c(1,4), C = c(3,7))

  B C
1 1 3
2 4 7
</code>```

This has 2 rows and 2 columns with column names B and C.

To calculate the average in column A by rows specified by columns B and C, use sapply, which the R equivalent of a fast for loop. I use iter from the library iterators to loop through rows of the data.frame:

```<code>install.packages("iterators")
library(iterators)
sapply(iter(df,by="row"),function(x) mean(A[x$B:x$C]))

[1] 35.33333 39.75000
</code>```

Body:
A vector of values, like in column A:

set.seed(1)
A <- sample(1:100,10)

[1] 66 13 27 38  2 37 82 32 45 55

A data.frame of values, like in columns B and C:

df <- data.frame( B = c(1,4), C = c(3,7))

  B C
1 1 3
2 4 7

This has 2 rows and 2 columns with column names B and C.

To calculate the average in column A by rows specified by columns B and C, use sapply, which the R equivalent of a fast for loop. I use iter from the library iterators to loop through rows of the data.frame:

install.packages("iterators")
library(iterators)
sapply(iter(df,by="row"),function(x) mean(A[x$B:x$C]))

[1] 35.33333 39.75000


问:
SessionCookies n asp.net
I am new to ASP.Net i dont understand the concept of sessioncookies

```<code>What is a sessioncookie,what are the advantages of sessioncookie
whats is sessioncookie is all about,
how to create a sessioncookie,
how to retreive values from sessioncookies,
how to store values in sessioncookies.
</code>```

i searched in net but i dont get clear idea about the sessioncookie concept can anyone pls clarify whats is sessioncookies and its concepts and provide some code samples if possible.

Thanks

答:
Take a look at this:

http://www.codeproject.com/KB/aspnet/ExploringSession.aspx

Title: SessionCookies n asp.net

Body:
I am new to ASP.Net i dont understand the concept of sessioncookies

What is a sessioncookie,what are the advantages of sessioncookie
whats is sessioncookie is all about,
how to create a sessioncookie,
how to retreive values from sessioncookies,
how to store values in sessioncookies.

i searched in net but i dont get clear idea about the sessioncookie concept can anyone pls clarify whats is sessioncookies and its concepts and provide some code samples if possible.

Thanks


问:
"str is undefined" on findRecord
I have a problem with model and serializer. I've looked at the documentation and can't find a solution. My app is connected to a django rest api.

Django response:

```<code>{
    "id": 1,
    "url": "http://localhost:8000/users/1/",
    "username": "username",
    "email": "xxx@email.com",
    "is_staff": true
}
</code>```

The model:

```<code>export default DS.Model.extend({
    url : DS.attr('string'),
    username : DS.attr('string'),
    email : DS.attr('string'),
});
</code>```

I've modified the response with a serializer to include "data":

```<code>export default DS.JSONAPISerializer.extend({
    primaryKey: 'id',
    normalizeFindRecordResponse(store, type, payload, id) {
        console.log('payload',payload)
        return {
            data: {
                'id': id,
                'url': payload.url,
                'username': payload.username,
                'email': payload.email,
            }
        } ;
    }
});
</code>```

The route:

```<code>export default Ember.Route.extend({
    model() {
        return this.store.findRecord('users', 1);
    }
});
</code>```

Another version of the route same error:

```<code>export default Ember.Route.extend({
    model() {
        this.store.findRecord('users', '1').then(function(user){
            console.log('user', user);
        }).catch(function(e){
            console.log('e', e);
        });
    }
});
</code>```

Finally Ember inspector has the model but all values as undefined and "str is undefined" on console.

Image of ember inspector

答:
1.normalizeFindRecordResponse is not returning valid JSONAPI format,
The below is the valid format,

```<code>{
  "data": {
    "type": "articles",
    "id": "1",
    "attributes": {
      // ... this article's attributes
    }
  }
}
</code>```

As you can see, you are missing type, attributes key.

2.Your model file name should be user.js in singular.

3.this.store.findRecord('users', 1) - here you need to use singluar form of the model so this.store.findRecord('user', 1)

4.In your another attempt you are missing the return statement in model hook.

Title: "str is undefined" on findRecord

Body:
I have a problem with model and serializer. I've looked at the documentation and can't find a solution. My app is connected to a django rest api.

Django response:

{
    "id": 1,
    "url": "http://localhost:8000/users/1/",
    "username": "username",
    "email": "xxx@email.com",
    "is_staff": true
}

The model:

export default DS.Model.extend({
    url : DS.attr('string'),
    username : DS.attr('string'),
    email : DS.attr('string'),
});

I've modified the response with a serializer to include "data":

export default DS.JSONAPISerializer.extend({
    primaryKey: 'id',
    normalizeFindRecordResponse(store, type, payload, id) {
        console.log('payload',payload)
        return {
            data: {
                'id': id,
                'url': payload.url,
                'username': payload.username,
                'email': payload.email,
            }
        } ;
    }
});

The route:

export default Ember.Route.extend({
    model() {
        return this.store.findRecord('users', 1);
    }
});

Another version of the route same error:

export default Ember.Route.extend({
    model() {
        this.store.findRecord('users', '1').then(function(user){
            console.log('user', user);
        }).catch(function(e){
            console.log('e', e);
        });
    }
});

Finally Ember inspector has the model but all values as undefined and "str is undefined" on console.

Image of ember inspector

Body:
1.normalizeFindRecordResponse is not returning valid JSONAPI format,
The below is the valid format,

{
  "data": {
    "type": "articles",
    "id": "1",
    "attributes": {
      // ... this article's attributes
    }
  }
}

As you can see, you are missing type, attributes key.

2.Your model file name should be user.js in singular.

3.this.store.findRecord('users', 1) - here you need to use singluar form of the model so this.store.findRecord('user', 1)

4.In your another attempt you are missing the return statement in model hook.


问:
Connection String error while using ADOMD.NET to connect to Azure Analysis
I am trying to retrieve data from Azure Analysis Services using ADOMD.NET from a deployed model in cloud. The code snippet is as below, but i am getting an error that the ConnectionString in invalid.</p>

```<code>using Microsoft.AnalysisServices.AdomdClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test_Analysis_Service_retrieval
{
    class Program
    {
        static void Main(string[] args)
        {
            string queryString = @"SELECT [MAP_CUST_NAME] FROM [AAS_MAPLOOKUP] where [MAP_ACT_NO] = '120000810';";
            string connectionString = @"Data Source=asazure://westus.asazure.windows.net/bbacloud;UserName=xyz@gmail.com;Password=ABC@123;";

            using (AdomdConnection connection = new AdomdConnection(connectionString))
            {
                CellSet AASOutput = null;
                System.Xml.XmlReader reader = null;
                try
                {
                    string s = connection.ConnectionString;
                    Console.WriteLine(s);
                    connection.Open();
                    AdomdCommand command = new AdomdCommand(queryString, connection);
                    command.CommandTimeout = 100000;
                    reader = command.ExecuteXmlReader();
                    Console.WriteLine(reader.ReadOuterXml());
                }
                catch(Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                    connection.Close();
                }
            }
        }
    }
}
</code>```

答:
Turns out that this issue is due to the RTM version of AdomdClient not actually supporting the RTM version of Azure Analysis Services.  As a result, the following Nuget Package is required:

https://github.com/ogaudefroy/Unofficial.Microsoft.AnalysisServices.AdomdClient

Once you remove / uninstall the version 12 ( the RTM version ) of Microsoft.AnalysisServices.AdomdClient.12.0.2000.8 and install the above AdomdClient everything works just fine.  In short, the v12 version doesn't have the code built in to parse asazure:// Data Sources

Highly annoying with no documentation on Microsoft's site nor support relating to the problem.  However this will address your question.

Body:
I am trying to retrieve data from Azure Analysis Services using ADOMD.NET from a deployed model in cloud. The code snippet is as below, but i am getting an error that the ConnectionString in invalid.

using Microsoft.AnalysisServices.AdomdClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test_Analysis_Service_retrieval
{
    class Program
    {
        static void Main(string[] args)
        {
            string queryString = @"SELECT [MAP_CUST_NAME] FROM [AAS_MAPLOOKUP] where [MAP_ACT_NO] = '120000810';";
            string connectionString = @"Data Source=asazure://westus.asazure.windows.net/bbacloud;UserName=xyz@gmail.com;Password=ABC@123;";

            using (AdomdConnection connection = new AdomdConnection(connectionString))
            {
                CellSet AASOutput = null;
                System.Xml.XmlReader reader = null;
                try
                {
                    string s = connection.ConnectionString;
                    Console.WriteLine(s);
                    connection.Open();
                    AdomdCommand command = new AdomdCommand(queryString, connection);
                    command.CommandTimeout = 100000;
                    reader = command.ExecuteXmlReader();
                    Console.WriteLine(reader.ReadOuterXml());
                }
                catch(Exception e)
                {
                    Console.WriteLine(e.Message);
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }
                    connection.Close();
                }
            }
        }
    }
}


问:
When to use what encoding on tables
I recently had to changed mysql from latin-1 to utf-8 to handle Russian characters. They were originally showing up as ?????.

I also had to change a couple of tables in my database to utf8mb4. I originally had these set to utf8 but this did not have enough bits to handle certain characters.

I have to make a change to a production database and want to ensure that i do not have any issues a few months down the line with a particular encoding type.

So my question is when do i use what encoding on a table?

答:
You have multiple questions.

The "???" probably came from converting from latin1 to utf8 incorrectly.  The data is now lost, since only '?' remains.  SELECT HEX(...) ... to confirm that all you get is 3F (?) where you should get something useful.

See "question marks" in Trouble with utf8 characters; what I see is not what I stored .

utf8mb4 and utf8 handle Cyrillic (Russian) identically, so the CHARACTER SET is not the issue with respect to the "???".

If you have an original copy of the data, then probably you want the 3rd item in here -- "CHARACTER SET latin1, but have utf8 bytes in it; leave bytes alone while fixing charset".  That is what I call the two-step ALTER.

As for avoiding future issues...  See "Best Practice" in my first link.  If all you need is European (including Russian), either utf8 or utf8mb4 will suffice.  But if you want Emoji or all of Chinese, then go with utf8mb4.

Also, note that you must specify what charset the client is using; this is a common omission, and was probably part of what got you in trouble in the first place.

Title: When to use what encoding on tables


问:
failed to launch jenkins slave
I am trying to setup a jenkins clusters on our servers. After configuring a slave node, then trying to launch that slave from the master, it failed to start.

error log

```<code>[07/03/17 11:12:19] [SSH] Checking java version of java
[07/03/17 11:12:19] [SSH] java -version returned 1.5.0.
[07/03/17 11:12:19] [SSH] Starting sftp client.
[07/03/17 11:12:19] [SSH] Copying latest slave.jar...
[07/03/17 11:12:19] [SSH] Copied 717,563 bytes.
Expanded the channel window size to 4MB
[07/03/17 11:12:19] [SSH] Starting slave process: cd "/app/taiji/build/jenkins2" && java  -jar slave.jar
Exception in thread "main" java.lang.ClassFormatError: hudson.remoting.Launcher (unrecognized class file version)
   at java.lang.VMClassLoader.defineClass(libgcj.so.10)
   at java.lang.ClassLoader.defineClass(libgcj.so.10)
   at java.security.SecureClassLoader.defineClass(libgcj.so.10)
   at java.net.URLClassLoader.findClass(libgcj.so.10)
   at java.lang.ClassLoader.loadClass(libgcj.so.10)
   at java.lang.ClassLoader.loadClass(libgcj.so.10)
   at gnu.java.lang.MainThread.run(libgcj.so.10)
Slave JVM has terminated. Exit code=1
[07/03/17 11:12:19] Launch failed - cleaning up connection
[07/03/17 11:12:19] [SSH] Connection closed.
</code>```

One thing I have noticed is that it seems to have problems with mismatching java versions.

It seems to return java version 1.5. but I have both checked slave and master server. It has currently Java 1.8 installed.

```<code>ldndsr000004921$ java -version
java version "1.8.0_66"
Java(TM) SE Runtime Environment (build 1.8.0_66-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.66-b17, mixed mode)
</code>```

the jenkins system environment as below:

Please advise?

答:
this is due to javPath is not setup properly. I was able to fix it by specifying javaPath to correct java version.

After setting up, the jenkins agent is able to start successfully as below

```<code>[07/04/17 03:18:56] [SSH] Starting sftp client.
[07/04/17 03:18:56] [SSH] Copying latest slave.jar...
[07/04/17 03:18:56] [SSH] Copied 717,563 bytes.
Expanded the channel window size to 4MB
[07/04/17 03:18:56] [SSH] Starting slave process: cd "/app/taiji/build/jenkins2" && /app/phoenix/jdk1.8.0_66/bin/java  -jar slave.jar
<===[JENKINS REMOTING CAPACITY]===>channel started
Slave.jar version: 3.4.1
This is a Unix agent
Evacuated stdout
Agent successfully connected and online
</code>```

Title: failed to launch jenkins slave

Body:
I am trying to setup a jenkins clusters on our servers. After configuring a slave node, then trying to launch that slave from the master, it failed to start.

error log

[07/03/17 11:12:19] [SSH] Checking java version of java
[07/03/17 11:12:19] [SSH] java -version returned 1.5.0.
[07/03/17 11:12:19] [SSH] Starting sftp client.
[07/03/17 11:12:19] [SSH] Copying latest slave.jar...
[07/03/17 11:12:19] [SSH] Copied 717,563 bytes.
Expanded the channel window size to 4MB
[07/03/17 11:12:19] [SSH] Starting slave process: cd "/app/taiji/build/jenkins2" && java  -jar slave.jar
Exception in thread "main" java.lang.ClassFormatError: hudson.remoting.Launcher (unrecognized class file version)
   at java.lang.VMClassLoader.defineClass(libgcj.so.10)
   at java.lang.ClassLoader.defineClass(libgcj.so.10)
   at java.security.SecureClassLoader.defineClass(libgcj.so.10)
   at java.net.URLClassLoader.findClass(libgcj.so.10)
   at java.lang.ClassLoader.loadClass(libgcj.so.10)
   at java.lang.ClassLoader.loadClass(libgcj.so.10)
   at gnu.java.lang.MainThread.run(libgcj.so.10)
Slave JVM has terminated. Exit code=1
[07/03/17 11:12:19] Launch failed - cleaning up connection
[07/03/17 11:12:19] [SSH] Connection closed.

One thing I have noticed is that it seems to have problems with mismatching java versions.

It seems to return java version 1.5. but I have both checked slave and master server. It has currently Java 1.8 installed.

ldndsr000004921$ java -version
java version "1.8.0_66"
Java(TM) SE Runtime Environment (build 1.8.0_66-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.66-b17, mixed mode)

the jenkins system environment as below:

Please advise?

Body:
this is due to javPath is not setup properly. I was able to fix it by specifying javaPath to correct java version.

After setting up, the jenkins agent is able to start successfully as below

[07/04/17 03:18:56] [SSH] Starting sftp client.
[07/04/17 03:18:56] [SSH] Copying latest slave.jar...
[07/04/17 03:18:56] [SSH] Copied 717,563 bytes.
Expanded the channel window size to 4MB
[07/04/17 03:18:56] [SSH] Starting slave process: cd "/app/taiji/build/jenkins2" && /app/phoenix/jdk1.8.0_66/bin/java  -jar slave.jar
<===[JENKINS REMOTING CAPACITY]===>channel started
Slave.jar version: 3.4.1
This is a Unix agent
Evacuated stdout
Agent successfully connected and online


问:
Concatenate two std::vectors in one line using C++11
Is there a way, using C++11, to concatenate two std::vectors in one code line, with the first defined in a local variable, the second returned from a function:

```<code>#include <vector>
#include <iostream>
#include <iterator>

std::vector<int> getNewVector()
{
    return {4,5,6};
}

int main(int argc, char** argv)
{
  std::vector<int> dest;
  std::vector<int> src{1,2,3};

  dest = src + getNewVector(); //Error: no operator "+" matches these operands

  return 0;
}
</code>```

EDIT: differently from this question, that is not using C++11, I would like to know if the new C++11 standard give some useful functionality that would help my task.
As an example, I've used the + operator even if it's not working, but just to give an idea of what I'm looking for.

答:
overloaded operator + takes 2x vectors, solution without library boost

```<code>#include <vector>
#include <iostream>
template<typename T>
std::vector<T> operator+(std::vector<T> vec1, const std::vector<T>&& vec2)
{
    vec1.insert(vec1.end(), vec2.begin(), vec2.end());
    return vec1;
}
std::vector<int> getNewVector()
{
    return{ 4,5,6 };
}
template<typename T>
void displayVectors(const std::vector<T>& src, const std::vector<T>& dest, const std::vector<T>&& getNewVector)
{
    std::cout << "src { ";
    for (const auto& itr : src)
        std::cout << itr << " ";
    std::cout << "}" << std::endl;
    std::cout << "getNewVector() { ";
    for (const auto& itr : getNewVector)
        std::cout << itr << " ";
    std::cout << "}" << std::endl;
    std::cout << "dest { ";
    for (const auto& itr : dest)
        std::cout << itr << " ";
    std::cout << "}" << std::endl;
}
int main(int argc, char** argv)
{
    std::vector<int> dest;
    std::vector<int> src{ 1,2,3 };
    displayVectors(src, dest, getNewVector());
    dest = src + getNewVector();
    std::cout << "After operation" << std::endl;
    displayVectors(src, dest, getNewVector());
    return 0;
}
</code>```

or with move sematics

```<code>#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
template<typename T>
std::vector<T> operator+(std::vector<T> vec1, const std::vector<T>&& vec2)
{
    std::move(vec2.begin(), vec2.end(), std::back_inserter(vec1));
    return vec1;
}
std::vector<int> getNewVector()
{
    return{ 4,5,6 };
}
template<typename T>
void displayVectors(const std::vector<T>& src, const std::vector<T>& dest)
{
    std::cout << "src { ";
    for (const auto& itr : src)
        std::cout << itr << " ";
    std::cout << "}" << std::endl;
    std::cout << "dest { ";
    for (const auto& itr : dest)
        std::cout << itr << " ";
    std::cout << "}" << std::endl;
}
int main(int argc, char** argv)
{
    std::vector<int> dest;
    std::vector<int> src{ 1,2,3 };
    displayVectors(src, dest);
    dest = src + getNewVector();
    std::cout << "After operation" << std::endl;
    displayVectors(src, dest);
    return 0;
}
</code>```

Body:
Is there a way, using C++11, to concatenate two std::vectors in one code line, with the first defined in a local variable, the second returned from a function:

#include <vector>
#include <iostream>
#include <iterator>

std::vector<int> getNewVector()
{
    return {4,5,6};
}

int main(int argc, char** argv)
{
  std::vector<int> dest;
  std::vector<int> src{1,2,3};

  dest = src + getNewVector(); //Error: no operator "+" matches these operands

  return 0;
}

EDIT: differently from this question, that is not using C++11, I would like to know if the new C++11 standard give some useful functionality that would help my task.
As an example, I've used the + operator even if it's not working, but just to give an idea of what I'm looking for.

Body:
overloaded operator + takes 2x vectors, solution without library boost

#include <vector>
#include <iostream>
template<typename T>
std::vector<T> operator+(std::vector<T> vec1, const std::vector<T>&& vec2)
{
    vec1.insert(vec1.end(), vec2.begin(), vec2.end());
    return vec1;
}
std::vector<int> getNewVector()
{
    return{ 4,5,6 };
}
template<typename T>
void displayVectors(const std::vector<T>& src, const std::vector<T>& dest, const std::vector<T>&& getNewVector)
{
    std::cout << "src { ";
    for (const auto& itr : src)
        std::cout << itr << " ";
    std::cout << "}" << std::endl;
    std::cout << "getNewVector() { ";
    for (const auto& itr : getNewVector)
        std::cout << itr << " ";
    std::cout << "}" << std::endl;
    std::cout << "dest { ";
    for (const auto& itr : dest)
        std::cout << itr << " ";
    std::cout << "}" << std::endl;
}
int main(int argc, char** argv)
{
    std::vector<int> dest;
    std::vector<int> src{ 1,2,3 };
    displayVectors(src, dest, getNewVector());
    dest = src + getNewVector();
    std::cout << "After operation" << std::endl;
    displayVectors(src, dest, getNewVector());
    return 0;
}

or with move sematics

#include <vector>
#include <iostream>
#include <algorithm>
#include <iterator>
template<typename T>
std::vector<T> operator+(std::vector<T> vec1, const std::vector<T>&& vec2)
{
    std::move(vec2.begin(), vec2.end(), std::back_inserter(vec1));
    return vec1;
}
std::vector<int> getNewVector()
{
    return{ 4,5,6 };
}
template<typename T>
void displayVectors(const std::vector<T>& src, const std::vector<T>& dest)
{
    std::cout << "src { ";
    for (const auto& itr : src)
        std::cout << itr << " ";
    std::cout << "}" << std::endl;
    std::cout << "dest { ";
    for (const auto& itr : dest)
        std::cout << itr << " ";
    std::cout << "}" << std::endl;
}
int main(int argc, char** argv)
{
    std::vector<int> dest;
    std::vector<int> src{ 1,2,3 };
    displayVectors(src, dest);
    dest = src + getNewVector();
    std::cout << "After operation" << std::endl;
    displayVectors(src, dest);
    return 0;
}


问:
UnicodeEncodeError when using the compile function
Using python 3.2 in Windows 7 I am getting the following in IDLE:

```<code>>>compile('pass', r'c:\temp\工具\module1.py', 'exec')
UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character
</code>```

Can anybody explain why the compile statement tries to convert the unicode filename using mbcs?  I know that sys.getfilesystemencoding returns 'mbcs' in Windows, but I thought that this is not used when unicode file names are provided.

for example:

```<code>f = open(r'c:\temp\工具\module1.py')
</code>```

works.

For a more complete test save the following in a utf8 encoded file and run it using the standard python.exe version 3.2

```<code># -*- coding: utf8 -*-
fname = r'c:\temp\工具\module1.py'
# I do have the a file named fname but you can comment out the following two lines
f = open(fname)
print('ok')
cmp = compile('pass', fname, 'exec')
print(cmp)
</code>```

Output:

```<code>ok
Traceback (most recent call last):
  File "module8.py", line 6, in <module>
    cmp = compile('pass', fname, 'exec')
UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: inval
id character
</code>```

答:
I think you could try to change the "\" in the path of file into "/"，just like

compile('pass', r'c:\temp\工具\module1.py', 'exec')

compile('pass', r'c:/temp/工具/module1.py', 'exec')

I have met a problem just like you, I used this method to solve the problem. I hope it can work with yours.

Body:
Using python 3.2 in Windows 7 I am getting the following in IDLE:

>>compile('pass', r'c:\temp\工具\module1.py', 'exec')
UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character

Can anybody explain why the compile statement tries to convert the unicode filename using mbcs?  I know that sys.getfilesystemencoding returns 'mbcs' in Windows, but I thought that this is not used when unicode file names are provided.

for example:

f = open(r'c:\temp\工具\module1.py')

works.

For a more complete test save the following in a utf8 encoded file and run it using the standard python.exe version 3.2

# -*- coding: utf8 -*-
fname = r'c:\temp\工具\module1.py'
# I do have the a file named fname but you can comment out the following two lines
f = open(fname)
print('ok')
cmp = compile('pass', fname, 'exec')
print(cmp)

Output:

ok
Traceback (most recent call last):
  File "module8.py", line 6, in <module>
    cmp = compile('pass', fname, 'exec')
UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: inval
id character


问:
List index out of range in perceptron example
I have this piece of code that aims to change the value of a cell of a 2D array to a 1 or a 0 according to whether or not it is equal to Iris-versicolor.

```<code>for row in data:
    if (row[4] == "Iris-versicolor"):
        row[4] == 1
    else:
        row[4] == 0
</code>```

The issue is that it gives me an error on the line of the if statement saying "IndexError : list index out of range". I understand the error (I think) saying that I'm trying to access a cell that doesn't exist, except that I have checked and my data array does have a 5th column (indexed as 4) and I don't see where else the error can come from.

Any help is greatly appreciated,

Mindoo

Edit: Here is a link to the database I'm using.
Its the well known Iris database.

答:
If your data is list of lists

```<code>for row in data:
    if len(row) >= 4:
        if (row[4] == "Iris-versicolor"):
            row[4] = 1
        else:
            row[4] = 0
</code>```

Checking if row has minimum of 5 elements before accessing it.

Body:
I have this piece of code that aims to change the value of a cell of a 2D array to a 1 or a 0 according to whether or not it is equal to Iris-versicolor.

for row in data:
    if (row[4] == "Iris-versicolor"):
        row[4] == 1
    else:
        row[4] == 0

The issue is that it gives me an error on the line of the if statement saying "IndexError : list index out of range". I understand the error (I think) saying that I'm trying to access a cell that doesn't exist, except that I have checked and my data array does have a 5th column (indexed as 4) and I don't see where else the error can come from.

Any help is greatly appreciated,

Mindoo

Edit: Here is a link to the database I'm using.
Its the well known Iris database.

Body:
If your data is list of lists

for row in data:
    if len(row) >= 4:
        if (row[4] == "Iris-versicolor"):
            row[4] = 1
        else:
            row[4] = 0

Checking if row has minimum of 5 elements before accessing it.


问:
Simple custom gradient with gradient_override_map
I want to use a function that creates weights for a normal dense layer, it basically behaves like an initialization function, only that it "initializes" before every new forward pass.

The flow for my augmented linear layer looks like this:

```<code>input = (x, W)
W_new = g(x,W)
output = tf.matmul(x,W_new)
</code>```

However, g(x,W) is not differentiable, as it involves some sampling. Luckily it also doesn't have any parameters I want to learn so I just try to do the forward and backward pass, as if I would have never replaced W.
Now I need to tell the automatic differentiation to not backpropagate through g(). I do this with:

```<code>W_new = tf.stop_gradient(g(x,W))
</code>```

Unfortunately this does not work, as it complains about non-matching shapes.
What does work is the following:

```<code>input = (x, W)
W_new = W + tf.stop_gradient(g(x,W) - W)
output = tf.matmul(x,W_new)
</code>```

as suggested here: https://stackoverflow.com/a/36480182

Now the forward pass seems to be OK, but I don't know how to override the gradient for the backward pass. I know, that I have to use: gradient_override_map for this, but could not transfer applications I have seen to my particular usecase (I am still quite new to TF).
However, I am not sure how to do this and if there isn't an easier way. I assume something similar has to be done in the first forward pass in a given model, where all weights are initialized while we don't have to backpropagate through the init functions as well.

Any help would be very much appreciated!

答:
Hey @jhj I too faced the same problem fortunately I found this gist. Hope this helps :)

Sample working -

import tensorflow as tf

from tensorflow.python.framework import ops

import numpy as np

Define custom py_func which takes also a grad op as argument:

def py_func(func, inp, Tout, stateful=True, name=None, grad=None):

```<code># Need to generate a unique name to avoid duplicates:
rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8))

tf.RegisterGradient(rnd_name)(grad)  # see _MySquareGrad for grad example
g = tf.get_default_graph()
with g.gradient_override_map({"PyFunc": rnd_name, "PyFuncStateless": rnd_name}):
    return tf.py_func(func, inp, Tout, stateful=stateful, name=name)
</code>```

Def custom square function using np.square instead of tf.square:

def mysquare(x, name=None):

```<code>with ops.name_scope(name, "Mysquare", [x]) as name:
    sqr_x = py_func(np.square,
                    [x],
                    [tf.float32],
                    name=name,
                    grad=_MySquareGrad)  # <-- here's the call to the gradient
    return sqr_x[0]
</code>```

Actual gradient:

def _MySquareGrad(op, grad):

```<code>x = op.inputs[0]
return grad * 20 * x  # add a "small" error just to see the difference:
</code>```

with tf.Session() as sess:

```<code>x = tf.constant([1., 2.])
y = mysquare(x)
tf.global_variables_initializer().run()

print(x.eval(), y.eval(), tf.gradients(y, x)[0].eval())
</code>```

Body:
I want to use a function that creates weights for a normal dense layer, it basically behaves like an initialization function, only that it "initializes" before every new forward pass.

The flow for my augmented linear layer looks like this:

input = (x, W)
W_new = g(x,W)
output = tf.matmul(x,W_new)

However, g(x,W) is not differentiable, as it involves some sampling. Luckily it also doesn't have any parameters I want to learn so I just try to do the forward and backward pass, as if I would have never replaced W.
Now I need to tell the automatic differentiation to not backpropagate through g(). I do this with:

W_new = tf.stop_gradient(g(x,W))

Unfortunately this does not work, as it complains about non-matching shapes.
What does work is the following:

input = (x, W)
W_new = W + tf.stop_gradient(g(x,W) - W)
output = tf.matmul(x,W_new)

as suggested here: https://stackoverflow.com/a/36480182

Now the forward pass seems to be OK, but I don't know how to override the gradient for the backward pass. I know, that I have to use: gradient_override_map for this, but could not transfer applications I have seen to my particular usecase (I am still quite new to TF).
However, I am not sure how to do this and if there isn't an easier way. I assume something similar has to be done in the first forward pass in a given model, where all weights are initialized while we don't have to backpropagate through the init functions as well.

Any help would be very much appreciated!

Body:
Hey @jhj I too faced the same problem fortunately I found this gist. Hope this helps :)

Sample working -

import tensorflow as tf

from tensorflow.python.framework import ops

import numpy as np

Define custom py_func which takes also a grad op as argument:

def py_func(func, inp, Tout, stateful=True, name=None, grad=None):

# Need to generate a unique name to avoid duplicates:
rnd_name = 'PyFuncGrad' + str(np.random.randint(0, 1E+8))

tf.RegisterGradient(rnd_name)(grad)  # see _MySquareGrad for grad example
g = tf.get_default_graph()
with g.gradient_override_map({"PyFunc": rnd_name, "PyFuncStateless": rnd_name}):
    return tf.py_func(func, inp, Tout, stateful=stateful, name=name)

Def custom square function using np.square instead of tf.square:

def mysquare(x, name=None):

with ops.name_scope(name, "Mysquare", [x]) as name:
    sqr_x = py_func(np.square,
                    [x],
                    [tf.float32],
                    name=name,
                    grad=_MySquareGrad)  # <-- here's the call to the gradient
    return sqr_x[0]

Actual gradient:

def _MySquareGrad(op, grad):

x = op.inputs[0]
return grad * 20 * x  # add a "small" error just to see the difference:

with tf.Session() as sess:

x = tf.constant([1., 2.])
y = mysquare(x)
tf.global_variables_initializer().run()

print(x.eval(), y.eval(), tf.gradients(y, x)[0].eval())