问:
Spring Boot: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean
I am totally new to Spring and started to do the official guides from this site:
https://spring.io/guides

I'd like to do this guide:
https://spring.io/guides/gs/scheduling-tasks/

I get the following Exception:

```<code>2014-02-14 16:25:21.614  INFO 9032 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.scheduling.annotation.SchedulingConfiguration' of type [class org.springframework.scheduling.annotation.SchedulingConfiguration$$EnhancerByCGLIB$$5b48d763] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-02-14 16:25:21.638  INFO 9032 --- [           main] .c.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/work/Spring/SpringTutorial/target/classes/, file:/C:/work/apache-maven-3.0.3/repo/javax/servlet/javax.servlet-api/3.0.1/javax.servlet-api-3.0.1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter/1.0.0.RC1/spring-boot-starter-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot/1.0.0.RC1/spring-boot-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-core/4.0.0.RELEASE/spring-core-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-context/4.0.0.RELEASE/spring-context-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-autoconfigure/1.0.0.RC1/spring-boot-autoconfigure-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-logging/1.0.0.RC1/spring-boot-starter-logging-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jcl-over-slf4j/1.7.5/jcl-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jul-to-slf4j/1.7.5/jul-to-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/log4j-over-slf4j/1.7.5/log4j-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-classic/1.0.13/logback-classic-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-core/1.0.13/logback-core-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-web/1.0.0.RC1/spring-boot-starter-web-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-tomcat/1.0.0.RC1/spring-boot-starter-tomcat-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-core/7.0.47/tomcat-embed-core-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-logging-juli/7.0.47/tomcat-embed-logging-juli-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-aop/4.0.0.RELEASE/spring-aop-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-beans/4.0.0.RELEASE/spring-beans-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-webmvc/4.0.0.RELEASE/spring-webmvc-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-expression/4.0.0.RELEASE/spring-expression-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-databind/2.3.1/jackson-databind-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-annotations/2.3.0/jackson-annotations-2.3.0.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-core/2.3.1/jackson-core-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/commons-lang/commons-lang/2.2/commons-lang-2.2.jar]
Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:140)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:124)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:658)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:355)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:920)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
    at hu.kumite.Application.main(Application.java:17)
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:190)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:163)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)
    ... 7 more
</code>```

The application starter class is this:

```<code>@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(ScheduledTasks.class, args);
    }
}
</code>```

As you can see, the main method contains a commented line. I've already done a tutorial, namely this one: https://spring.io/guides/gs/consuming-rest/
It's up and running. But I can't run the ScheduledTasks app, which is the following:

```<code>@EnableScheduling
public class ScheduledTasks {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("The time is now " + dateFormat.format(new Date()));
    }
}
</code>```

I use Eclipse and run the Application.java's main as an Application.
Could someone please help me?

答:
Clear repository is one possible solution.

Windows -> delete all subfolders in the maven repository:

C:\Users\YourUserName.m2\repository

Body:
I am totally new to Spring and started to do the official guides from this site:
https://spring.io/guides

I'd like to do this guide:
https://spring.io/guides/gs/scheduling-tasks/

I get the following Exception:

2014-02-14 16:25:21.614  INFO 9032 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.scheduling.annotation.SchedulingConfiguration' of type [class org.springframework.scheduling.annotation.SchedulingConfiguration$$EnhancerByCGLIB$$5b48d763] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2014-02-14 16:25:21.638  INFO 9032 --- [           main] .c.l.ClasspathLoggingApplicationListener : Application failed to start with classpath: [file:/C:/work/Spring/SpringTutorial/target/classes/, file:/C:/work/apache-maven-3.0.3/repo/javax/servlet/javax.servlet-api/3.0.1/javax.servlet-api-3.0.1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter/1.0.0.RC1/spring-boot-starter-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot/1.0.0.RC1/spring-boot-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-core/4.0.0.RELEASE/spring-core-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-context/4.0.0.RELEASE/spring-context-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-autoconfigure/1.0.0.RC1/spring-boot-autoconfigure-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-logging/1.0.0.RC1/spring-boot-starter-logging-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jcl-over-slf4j/1.7.5/jcl-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/slf4j-api/1.7.5/slf4j-api-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/jul-to-slf4j/1.7.5/jul-to-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/org/slf4j/log4j-over-slf4j/1.7.5/log4j-over-slf4j-1.7.5.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-classic/1.0.13/logback-classic-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/ch/qos/logback/logback-core/1.0.13/logback-core-1.0.13.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-web/1.0.0.RC1/spring-boot-starter-web-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/boot/spring-boot-starter-tomcat/1.0.0.RC1/spring-boot-starter-tomcat-1.0.0.RC1.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-core/7.0.47/tomcat-embed-core-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/apache/tomcat/embed/tomcat-embed-logging-juli/7.0.47/tomcat-embed-logging-juli-7.0.47.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/aopalliance/aopalliance/1.0/aopalliance-1.0.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-aop/4.0.0.RELEASE/spring-aop-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-beans/4.0.0.RELEASE/spring-beans-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-webmvc/4.0.0.RELEASE/spring-webmvc-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/org/springframework/spring-expression/4.0.0.RELEASE/spring-expression-4.0.0.RELEASE.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-databind/2.3.1/jackson-databind-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-annotations/2.3.0/jackson-annotations-2.3.0.jar, file:/C:/work/apache-maven-3.0.3/repo/com/fasterxml/jackson/core/jackson-core/2.3.1/jackson-core-2.3.1.jar, file:/C:/work/apache-maven-3.0.3/repo/commons-lang/commons-lang/2.2/commons-lang-2.2.jar]
Exception in thread "main" org.springframework.context.ApplicationContextException: Unable to start embedded container; nested exception is org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:140)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:476)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:124)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:658)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:355)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:920)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:909)
    at hu.kumite.Application.main(Application.java:17)
Caused by: org.springframework.context.ApplicationContextException: Unable to start EmbeddedWebApplicationContext due to missing EmbeddedServletContainerFactory bean.
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.getEmbeddedServletContainerFactory(EmbeddedWebApplicationContext.java:190)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.createEmbeddedServletContainer(EmbeddedWebApplicationContext.java:163)
    at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.onRefresh(EmbeddedWebApplicationContext.java:137)
    ... 7 more

The application starter class is this:

@ComponentScan
@EnableAutoConfiguration
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(ScheduledTasks.class, args);
    }
}

As you can see, the main method contains a commented line. I've already done a tutorial, namely this one: https://spring.io/guides/gs/consuming-rest/
It's up and running. But I can't run the ScheduledTasks app, which is the following:

@EnableScheduling
public class ScheduledTasks {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRate = 5000)
    public void reportCurrentTime() {
        System.out.println("The time is now " + dateFormat.format(new Date()));
    }
}

I use Eclipse and run the Application.java's main as an Application.
Could someone please help me?


来源: stackexchange

问:
Output audio file not created correctly, or has unknown duration time
I am currently trying to record some utterances, in which the record session should start when a key is pressed and held down, and stop when it is released. I made the python script for recording and storing the data..

```<code>from pynput import keyboard
import time
import pyaudio
import wave

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
frames = []

def callback(in_data, frame_count, time_info, status):
    return (in_data, pyaudio.paContinue)

class MyListener(keyboard.Listener):
    def __init__(self):
        super(MyListener, self).__init__(self.on_press, self.on_release)
        self.key_pressed = None

        self.stream = p.open(format=FORMAT,
                             channels=CHANNELS,
                             rate=RATE,
                             input=True,
                             frames_per_buffer=CHUNK,
                             stream_callback = self.callback)
        print self.stream.is_active()

    def on_press(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = True

    def on_release(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = False

    def callback(self,in_data, frame_count, time_info, status):
        if self.key_pressed == True:
            return (in_data, pyaudio.paContinue)
        elif self.key_pressed == False:
            return (in_data, pyaudio.paComplete)
        else:
            return (in_data,pyaudio.paAbort)

listener = MyListener()
listener.start()
started = False

while True:
    time.sleep(0.1)
    if listener.key_pressed == True and started == False:
        started = True
        listener.stream.start_stream()
        print "start Stream"

    elif listener.key_pressed == False and started == True:
        print "Something coocked"
        listener.stream.stop_stream()
        listener.stream.close()
        p.terminate()

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

        started = False
</code>```

Problem with the script is the audio file doesn't seem to record anything, the duration of the file when i play it is unknown?..

I am not sure i understand what could be wrong here..?

Update:

new version with output:

```<code>from pynput import keyboard
import time
import pyaudio
import StringIO
import multiprocessing
from multiprocessing import Process, Queue, queues
import wave

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
frames = []

stream_queue = Queue()

class MyListener(keyboard.Listener):
    def __init__(self):
        super(MyListener, self).__init__(on_press=self.on_press, on_release=self.on_release)
        self.key_pressed = None

        self.stream = p.open(format=FORMAT,
                             channels=CHANNELS,
                             rate=RATE,
                             input=True,
                             frames_per_buffer=CHUNK,
                             stream_callback = self.callback)

        print ("Stream active? " + str(self.stream.is_active()))

    def on_press(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = True

    def on_release(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = False

    def callback(self,in_data, frame_count, time_info, status):
        print "callback"
        if self.key_pressed == True:
            #stream_queue.put(in_data)
            frames.append(data)
            return (in_data, pyaudio.paContinue)

        elif self.key_pressed == False:
            #stream_queue.put(in_data)
            frames.append(data)
            return (in_data, pyaudio.paComplete)

        else:
            return (in_data,pyaudio.paAbort)

listener = MyListener()
listener.start()
started = False

while True:
    time.sleep(0.1)
    if listener.key_pressed == True and started == False:
        started = True
        listener.stream.start_stream()
        print ("Start stream -  Key is down")

    elif listener.key_pressed == True and started == True:
        print("stream has started and key is still down")
        print("Stream is active? " + str(listener.stream.is_active()))
        print("Stream is stopped? " + str(listener.stream.is_stopped()))
        print("Stream is time? " + str(listener.stream.get_time()))

    elif listener.key_pressed == False and started == True:
        print("Key has been released")
        listener.stream.stop_stream()
        listener.stream.close()
        print("stream has been closed")
        p.terminate()

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

        started = False
</code>```

output:

```<code>python File2.py
Stream active? True
callback
Start stream -  Key is down
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134638.797766
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134638.902259
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.006739
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.111282
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.215573
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.320448
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.424682
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.528631
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.633699
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.738129
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.842747
Key has been released
stream has been closed
^CTraceback (most recent call last):
  File "File2.py", line 67, in <module>
    time.sleep(0.1)
KeyboardInterrupt
MacBook-Pro:~$ play output.wav

output.wav:

 File Size: 44
  Encoding: Signed PCM
  Channels: 2 @ 16-bit
Samplerate: 44100Hz
Replaygain: off
  Duration: unknown

In:0.00% 00:00:00.00 [00:00:00.00] Out:0     [      |      ]        Clip:0
Done.
</code>```

Things that seems weird to me is

The stream is not active after the listener.stream.start_stream()

callback print message callback is only being printed once, but should be printed each time the callback stores data to the frames, which only apparently happen once.

the output.wav file duration is unknown? why?

答:
You have not filled up your list, frames.

you should do this to populate your list:

```<code>for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)
</code>```

Because you are using an empty list here:

```<code>wf.writeframes(b''.join(frames))
</code>```

I hope this works for you.

Cheers!

ContentLicense: CC BY-SA 3.0

Body:
I am currently trying to record some utterances, in which the record session should start when a key is pressed and held down, and stop when it is released. I made the python script for recording and storing the data..

from pynput import keyboard
import time
import pyaudio
import wave

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
frames = []

def callback(in_data, frame_count, time_info, status):
    return (in_data, pyaudio.paContinue)

class MyListener(keyboard.Listener):
    def __init__(self):
        super(MyListener, self).__init__(self.on_press, self.on_release)
        self.key_pressed = None

        self.stream = p.open(format=FORMAT,
                             channels=CHANNELS,
                             rate=RATE,
                             input=True,
                             frames_per_buffer=CHUNK,
                             stream_callback = self.callback)
        print self.stream.is_active()

    def on_press(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = True

    def on_release(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = False

    def callback(self,in_data, frame_count, time_info, status):
        if self.key_pressed == True:
            return (in_data, pyaudio.paContinue)
        elif self.key_pressed == False:
            return (in_data, pyaudio.paComplete)
        else:
            return (in_data,pyaudio.paAbort)

listener = MyListener()
listener.start()
started = False

while True:
    time.sleep(0.1)
    if listener.key_pressed == True and started == False:
        started = True
        listener.stream.start_stream()
        print "start Stream"

    elif listener.key_pressed == False and started == True:
        print "Something coocked"
        listener.stream.stop_stream()
        listener.stream.close()
        p.terminate()

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

        started = False

Problem with the script is the audio file doesn't seem to record anything, the duration of the file when i play it is unknown?..

I am not sure i understand what could be wrong here..?

Update:

new version with output:

from pynput import keyboard
import time
import pyaudio
import StringIO
import multiprocessing
from multiprocessing import Process, Queue, queues
import wave

CHUNK = 8192
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

p = pyaudio.PyAudio()
frames = []

stream_queue = Queue()

class MyListener(keyboard.Listener):
    def __init__(self):
        super(MyListener, self).__init__(on_press=self.on_press, on_release=self.on_release)
        self.key_pressed = None

        self.stream = p.open(format=FORMAT,
                             channels=CHANNELS,
                             rate=RATE,
                             input=True,
                             frames_per_buffer=CHUNK,
                             stream_callback = self.callback)

        print ("Stream active? " + str(self.stream.is_active()))

    def on_press(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = True

    def on_release(self, key):
        if key == keyboard.Key.cmd_l:
            self.key_pressed = False

    def callback(self,in_data, frame_count, time_info, status):
        print "callback"
        if self.key_pressed == True:
            #stream_queue.put(in_data)
            frames.append(data)
            return (in_data, pyaudio.paContinue)

        elif self.key_pressed == False:
            #stream_queue.put(in_data)
            frames.append(data)
            return (in_data, pyaudio.paComplete)

        else:
            return (in_data,pyaudio.paAbort)

listener = MyListener()
listener.start()
started = False

while True:
    time.sleep(0.1)
    if listener.key_pressed == True and started == False:
        started = True
        listener.stream.start_stream()
        print ("Start stream -  Key is down")

    elif listener.key_pressed == True and started == True:
        print("stream has started and key is still down")
        print("Stream is active? " + str(listener.stream.is_active()))
        print("Stream is stopped? " + str(listener.stream.is_stopped()))
        print("Stream is time? " + str(listener.stream.get_time()))

    elif listener.key_pressed == False and started == True:
        print("Key has been released")
        listener.stream.stop_stream()
        listener.stream.close()
        print("stream has been closed")
        p.terminate()

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)
        wf.writeframes(b''.join(frames))
        wf.close()

        started = False

output:

python File2.py
Stream active? True
callback
Start stream -  Key is down
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134638.797766
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134638.902259
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.006739
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.111282
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.215573
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.320448
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.424682
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.528631
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.633699
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.738129
stream has started and key is still down
Stream is active? False
Stream is stopped? False
Stream is time? 134639.842747
Key has been released
stream has been closed
^CTraceback (most recent call last):
  File "File2.py", line 67, in <module>
    time.sleep(0.1)
KeyboardInterrupt
MacBook-Pro:~$ play output.wav

output.wav:

 File Size: 44
  Encoding: Signed PCM
  Channels: 2 @ 16-bit
Samplerate: 44100Hz
Replaygain: off
  Duration: unknown

In:0.00% 00:00:00.00 [00:00:00.00] Out:0     [      |      ]        Clip:0
Done.

Things that seems weird to me is

The stream is not active after the listener.stream.start_stream()

callback print message callback is only being printed once, but should be printed each time the callback stores data to the frames, which only apparently happen once.

the output.wav file duration is unknown? why?

Body:
You have not filled up your list, frames.

you should do this to populate your list:

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)
    frames.append(data)

Because you are using an empty list here:

wf.writeframes(b''.join(frames))

I hope this works for you.

Cheers!


问:
BeautifulSoup cannot find a HTML tag that contains certain text
I just want to use regex to retrieve all elements which has "//" in my HTML string, and I follow the answer from this question: Using BeautifulSoup to find a HTML tag that contains certain text

And then I code a similar one:

```<code>from BeautifulSoup import BeautifulSoup
import re

html_text = \
"""
<html>
    <!--<![endif]-->
    <head>
        <link rel="stylesheet" href="//abc.com/xyz" />
        <meta rel="stylesheet" href="//foo.com/bar" />
    </head>
</html>
"""

soup = BeautifulSoup(html_text)

for elem in soup(text=re.compile(r'//')):
    print elem
</code>```

I expect that I would have the result like:

```<code>//abc.com/xyz
//foo.com/bar
</code>```

But I receive nothing. I don't know why their test case works but mine, is there any error or did I miss something in my script?

答:
Wrong attributes set

```<code>soup = BeautifulSoup(html_text, 'lxml')

for elem in soup(href=re.compile(r'//')):
    print elem.get('href')
</code>```

Extract method for the question in comment, you need to parse the data after found out which tag contains the data.

```<code>def has_requires_chars(tag):
    value_list = []
    attrs_value = tag.attrs.values()
    for avalue in attrs_value:
        if type(avalue) is list:
            value_list = value_list + avalue
        else:
            value_list.append(avalue)
    for value in value_list:
        if "//" in value:
            return True
    return False

soup = BeautifulSoup(html_text, 'lxml')
for elem in soup.find_all(has_requires_chars):
    print elem
</code>```

Body:
I just want to use regex to retrieve all elements which has "//" in my HTML string, and I follow the answer from this question: Using BeautifulSoup to find a HTML tag that contains certain text

And then I code a similar one:

from BeautifulSoup import BeautifulSoup
import re

html_text = \
"""

        <link rel="stylesheet" href="//abc.com/xyz" />
        <meta rel="stylesheet" href="//foo.com/bar" />

"""

soup = BeautifulSoup(html_text)

for elem in soup(text=re.compile(r'//')):
    print elem

I expect that I would have the result like:

//abc.com/xyz
//foo.com/bar

But I receive nothing. I don't know why their test case works but mine, is there any error or did I miss something in my script?

Body:
Wrong attributes set

soup = BeautifulSoup(html_text, 'lxml')

for elem in soup(href=re.compile(r'//')):
    print elem.get('href')

Extract method for the question in comment, you need to parse the data after found out which tag contains the data.

def has_requires_chars(tag):
    value_list = []
    attrs_value = tag.attrs.values()
    for avalue in attrs_value:
        if type(avalue) is list:
            value_list = value_list + avalue
        else:
            value_list.append(avalue)
    for value in value_list:
        if "//" in value:
            return True
    return False

soup = BeautifulSoup(html_text, 'lxml')
for elem in soup.find_all(has_requires_chars):
    print elem


问:
Removing .txt from my file name and sheet name
Pleas help guys!! In the section of code below (which works great btw), I keep getting .txt in the actually file name and sheet name. I have been looking at what I need to take out to solve this but I can't work it out. I am pretty new to VBA so I am doing my best Please help?!</p>

```<code> 'Opens the folder to location to select txt file
  fileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
    If fileToOpen <> False Then
    Workbooks.OpenText fileName:=fileToOpen, _
    DataType:=xlDelimited, Tab:=True
    End If
 'Creates the file name based on txt file name
  fileName = Mid(fileToOpen, InStrRev(fileToOpen, "\") + 1)
 'Creates the sheet name based on the active txt file
  sheetName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)

 'Rename the original text file
   ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
  Limited\" & "DNU_" & fileName & ".txt")
</code>```

答:
Maybe you could just use your sheetname as the filename too, as you already remove the ".txt" from the sheetname.</p>

```<code>'Opens the folder to location to select txt file
  fileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
    If fileToOpen <> False Then
    Workbooks.OpenText fileName:=fileToOpen, _
    DataType:=xlDelimited, Tab:=True
    End If

 'Creates the sheet name based on the active txt file
  sheetName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)

 'Rename the original text file
   ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
  Limited\" & "DNU_" & sheetName & ".txt")
</code>```

Body:
Pleas help guys!! In the section of code below (which works great btw), I keep getting .txt in the actually file name and sheet name. I have been looking at what I need to take out to solve this but I can't work it out. I am pretty new to VBA so I am doing my best Please help?!

 'Opens the folder to location to select txt file
  fileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
    If fileToOpen <> False Then
    Workbooks.OpenText fileName:=fileToOpen, _
    DataType:=xlDelimited, Tab:=True
    End If
 'Creates the file name based on txt file name
  fileName = Mid(fileToOpen, InStrRev(fileToOpen, "\") + 1)
 'Creates the sheet name based on the active txt file
  sheetName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)

 'Rename the original text file
   ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
  Limited\" & "DNU_" & fileName & ".txt")

Body:
Maybe you could just use your sheetname as the filename too, as you already remove the ".txt" from the sheetname.

'Opens the folder to location to select txt file
  fileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
    If fileToOpen <> False Then
    Workbooks.OpenText fileName:=fileToOpen, _
    DataType:=xlDelimited, Tab:=True
    End If

 'Creates the sheet name based on the active txt file
  sheetName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)

 'Rename the original text file
   ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
  Limited\" & "DNU_" & sheetName & ".txt")


问:
Doctrine2 (Doctrine 2.1) eager loading in Symfony2
Let's say I have two entities in my Symfony2 project : Category and Article (a category having many articles).

In my CategoryRepository, I have this method:

```<code>findAllDummy(){
  return $this->createQueryBuilder('c')
              ->leftJoin('c.Articles a')
              ->getQuery()->getResult();
}
</code>```

If I remember well, in Symfony1.4 (and the corresponding version of Doctrine), the returned objects would have their 'articles' attribute filled by the corresponding Article objects.
Now, in Symfony2, Proxy objects are returned.

So if I loop through a specific category's articles, As many queries as iterations will be executed.

```<code>foreach($category->getArticles() as $article){
  echo $article->getDoctrine()
               ->getRepository('')getTitle();
}
</code>```

I understand this is Doctrine2.1's default lazy loading behavior.

Question 1: how is this a better solution?
N queries instead of 1.

I tried to force eager loading by doing the following:

```<code>findAllDummy(){
  return $this->createQueryBuilder('c')
              ->leftJoin('c.articles a')
              ->getQuery()
              ->setFetchMode('Category', 'articles', 'EAGER')
              ->getResult();
}
</code>```

But the result remains the same.

Question 2: how to force eager loading in Doctrine2?

答:
As it says in the doctrine docs, eager loading in this case won't make any difference because you have one-to-many relationship between Category and Article.

For one-to-many relations, changing the fetch mode to eager will cause to execute one query for every root entity loaded. This gives no improvement over the lazy fetch mode which will also initialize the associations on a one-by-one basis once they are accessed.

So contrary to what @Crozin has said, you can still do eager loading in DQL.
If you have a one-to-one or many-to-one relationship, eager loading will solve the problem of making extra queries. However to solve your problem in this case you should use ->addSelect('a') as @Crozin mentioned.

Body:
Let's say I have two entities in my Symfony2 project : Category and Article (a category having many articles).

In my CategoryRepository, I have this method:

findAllDummy(){
  return $this->createQueryBuilder('c')
              ->leftJoin('c.Articles a')
              ->getQuery()->getResult();
}

If I remember well, in Symfony1.4 (and the corresponding version of Doctrine), the returned objects would have their 'articles' attribute filled by the corresponding Article objects.
Now, in Symfony2, Proxy objects are returned.

So if I loop through a specific category's articles, As many queries as iterations will be executed.

foreach($category->getArticles() as $article){
  echo $article->getDoctrine()
               ->getRepository('')getTitle();
}

I understand this is Doctrine2.1's default lazy loading behavior.

Question 1: how is this a better solution?
N queries instead of 1.

I tried to force eager loading by doing the following:

findAllDummy(){
  return $this->createQueryBuilder('c')
              ->leftJoin('c.articles a')
              ->getQuery()
              ->setFetchMode('Category', 'articles', 'EAGER')
              ->getResult();
}

But the result remains the same.

Question 2: how to force eager loading in Doctrine2?


问:
How to force a li item to be 100% of the parent container's width in IE 7?
I'm applying a background color to my list items. But in IE7, my child list items are not being rendered the full width of the parent UL item. Instead, it appears that they act like inline elements (their width only extends to the boundary of the text that makes up their content), even though I've set the child li elements to display:block;

It presents correctly in all browsers I've tested except IE7. So I'm thinking their might be a specific workaround for this browser, yes?

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <style type="text/css">
  .menu.top {height:30px; overflow:hidden; color:#f9f9f9; text-transform:uppercase; font-size:.85em;margin:101px 0 20px 0; padding-left:30px; border-radius: 15px; -moz-border-radius:15px;background:blue;}
/*category flyout menus */
.menu.top.cat {overflow:visible; }
.menu.top ul {margin:0; padding:0;white-space:nowrap;background:blue; position: relative; list-style: none; z-index: 50;}
.menu.top ul ul li {display:block;width:100%;clear:both;float:none;background:#777;}
.menu.top ul ul { position: absolute; visibility: hidden; list-style: none; z-index: 9999; }
.menu.top ul ul li {display:block;width:100%}
.menu.top ul a {white-space:nowrap;color:#fff;line-height:30px; padding:0 10px; display: block; }
.menu.top ul ul ul { position: absolute; top: 0; }
.menu.top ul li:hover ul, .menu.top ul a:hover ul, .menu.top ul :hover ul :hover ul, .menu.top ul :hover ul :hover ul :hover ul { visibility: visible;}
.menu.top ul :hover ul ul, .menu.top ul :hover ul :hover ul ul { visibility: hidden; }
.menu.top ul a:hover {background:url(spot2.gif);background:url(bar-bg.png) repeat-x, url(spot2.gif) repeat;color:#333; text-decoration:none;}
.menu.top ul.children li.current-cat a {color:#333;}  </style>
 </head>
<body>
    <div class='menu top cat'>
        <ul class='catparent'>
            <li class="cat-item"><a href="#" >Best Camera's Under $100</a>
                <ul class='children'>
                    <li class="cat-item"><a href="#">Blue Cameras under $100</a></li>
                    <li class="cat-item"><a href="#">Red Cameras</a></li>
                </ul>
            </li>
            <li class="cat-item"><a href="#">Cameras by Review Rating</a></li>
            <li class="cat-item"><a href="#">Best Camera's Under $200</a>
                <ul class='children'>
                    <li class="cat-item"><a href="#">best lightweight cameras under $200</a></li>
                    <li class="cat-item"><a href="#">best black cameras under $200</a></li>
                </ul>
            </li>
        </ul>
    </div>
</body>
</html>
</code>```

答:
I cannot reproduce your issue, but I am using IE8 in compatibility so I cannot test on the original IE7.

But I believe I know what you issue is, in case you are still having problems.
Try replacing this line

```<code>.menu.top ul ul li { clear: both;}
</code>```

with this:

```<code>.menu.top ul ul li { float:none}
</code>```

Possible scenario:
The list items in the sub-menus are taking this CSS

```<code>.menu.top ul li {margin:0; padding:0; position: relative; float: left;}
</code>```

which may be conflicting with the clear property on IE7 and taking priority over it for some reason.

So the css would like the folowing:

```<code>menu.top {height:30px; overflow:hidden; color:#f9f9f9; text-transform:uppercase; font-size:.85em;margin:101px 0 20px 0; padding-left:30px; border-radius: 15px; -moz-border-radius:15px;background:blue;}
/*category flyout menus */
.menu.top.cat {overflow:visible; }
.menu.top ul {margin:0; padding:0;white-space:nowrap;background:blue; position: relative; list-style: none; z-index: 50;}
.menu.top ul li {display:block;width:100%;float:left;background:#777;} /* added float to this rule again, and removed the clear property */
.menu.top ul ul { position: absolute; visibility: hidden; list-style: none; z-index: 9999; }
.menu.top ul ul li {display:block;width:100%}
.menu.top ul ul ul {left:150px;}
.menu.top ul ul li { float:none} /* modified this rule*/
.menu.top ul a {white-space:nowrap;color:#fff;line-height:30px; padding:0 10px; display: block; }
.menu.top ul ul ul { position: absolute; top: 0; }
.menu.top ul li:hover ul, .menu.top ul a:hover ul, .menu.top ul :hover ul :hover ul, .menu.top ul :hover ul :hover ul :hover ul { visibility: visible;}
.menu.top ul :hover ul ul, .menu.top ul :hover ul :hover ul ul { visibility: hidden; }
.menu.top ul a:hover {background:url(spot2.gif);background:url(bar-bg.png) repeat-x, url(spot2.gif) repeat;color:#333; text-decoration:none;}
.menu.top ul.children li.current-cat a {color:#333;}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm applying a background color to my list items. But in IE7, my child list items are not being rendered the full width of the parent UL item. Instead, it appears that they act like inline elements (their width only extends to the boundary of the text that makes up their content), even though I've set the child li elements to display:block;

It presents correctly in all browsers I've tested except IE7. So I'm thinking their might be a specific workaround for this browser, yes?

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

  <title> New Document </title>

Best Camera's Under $100

Blue Cameras under $100

Red Cameras

Cameras by Review Rating

Best Camera's Under $200

best lightweight cameras under $200

best black cameras under $200

Body:
I cannot reproduce your issue, but I am using IE8 in compatibility so I cannot test on the original IE7.

But I believe I know what you issue is, in case you are still having problems.
Try replacing this line

.menu.top ul ul li { clear: both;}

with this:

.menu.top ul ul li { float:none}

Possible scenario:
The list items in the sub-menus are taking this CSS

.menu.top ul li {margin:0; padding:0; position: relative; float: left;}

which may be conflicting with the clear property on IE7 and taking priority over it for some reason.

So the css would like the folowing:

menu.top {height:30px; overflow:hidden; color:#f9f9f9; text-transform:uppercase; font-size:.85em;margin:101px 0 20px 0; padding-left:30px; border-radius: 15px; -moz-border-radius:15px;background:blue;}
/*category flyout menus */
.menu.top.cat {overflow:visible; }
.menu.top ul {margin:0; padding:0;white-space:nowrap;background:blue; position: relative; list-style: none; z-index: 50;}
.menu.top ul li {display:block;width:100%;float:left;background:#777;} /* added float to this rule again, and removed the clear property */
.menu.top ul ul { position: absolute; visibility: hidden; list-style: none; z-index: 9999; }
.menu.top ul ul li {display:block;width:100%}
.menu.top ul ul ul {left:150px;}
.menu.top ul ul li { float:none} /* modified this rule*/
.menu.top ul a {white-space:nowrap;color:#fff;line-height:30px; padding:0 10px; display: block; }
.menu.top ul ul ul { position: absolute; top: 0; }
.menu.top ul li:hover ul, .menu.top ul a:hover ul, .menu.top ul :hover ul :hover ul, .menu.top ul :hover ul :hover ul :hover ul { visibility: visible;}
.menu.top ul :hover ul ul, .menu.top ul :hover ul :hover ul ul { visibility: hidden; }
.menu.top ul a:hover {background:url(spot2.gif);background:url(bar-bg.png) repeat-x, url(spot2.gif) repeat;color:#333; text-decoration:none;}
.menu.top ul.children li.current-cat a {color:#333;}


问:
EntityFramework LINQ query returned same values
Help understand please  why that query returns same values but if i use anonymous type it return correct result

```<code>//same values
var deviceMessageList1 = _deviceMessageRepository.Fromdevicemessages
                .Where(m => m.DeviceId == deviceId).Take(1000).ToList();
//different values
            var deviceMessageList2 = _deviceMessageRepository.Fromdevicemessages
                .Where(m => m.DeviceId == deviceId).Take(1000).Select(x=> new { Message = x.Message }).ToList();
</code>```

[]

答:
I've made a few assumptions:

I assume your entity class is called Fromdevicemessage

I assume that Message is a String property

.Select() in LINQ does not influence which items are retrieved. It only influences how the retrieved items are presented.

If you know SQL, you will see that SELECT in SQL works exactly the same (which is why the LINQ method is intentionally called Select, as it works the same, functionally speaking)

It helps if you understand the intention of every method, I'll comment it in:

```<code>var deviceMessageList1 =_deviceMessageRepository.Fromdevicemessages

     .Where(m => m.DeviceId == deviceId)  //Only return the items which have their DevicedId set to [deviceId]
     .Take(1000)                          //Give me the first 1000 items
     .ToList()                            //Make a list from these 1000 items
</code>```

Notice that you have only specified which rows you want to retrieve. You have not specified how you want the output to be formatted.

By default, you will receive objects of the corresponding entity type Fromdevicemessage.

The list you see at the end is therefore a List<Fromdevicemessage>.

```<code>var deviceMessageList1 =_deviceMessageRepository.Fromdevicemessages

     .Where(m => m.DeviceId == deviceId)       //Only return the items which have their DevicedId set to [deviceId]
     .Take(1000)                               //Give me the first 1000 items
     .Select(x => x.Message)                   //For each retrieved item, instead of the item itself, only give me its Message (= string)
     .ToList()                                 //Make a list from these 1000 strings
</code>```

Notice what the Select statement adds. It basically tells you that you do not want the full Fromdevicemessage object, but only want the Message property. You're basically telling the compiler the following:

For each Fromdevicemessage object that is currently retrieved, render me its Message property.

You were originally working with a collection of Fromdevicemessage objects. But the .Select() statement converted that collection into a collection of String objects.

Simplified, the Select() method converts every object in the source collection, based on your mapping (e.g. x => x.Message), and returns you the list of mapped values.

The list you see at the end is therefore a List<String>.

I cheated a little bit...

In case you hadn't noticed, I changed your Select statement.

Your version:

```<code>.Select( x => new { Message = x.Message } )
</code>```

My version:

```<code>.Select( x => x.Message )
</code>```

Both are valid code, but they work a bit differently.

Your version converts the retrieved items into anonymous objects. The resulting list will therefore be a list of anonymous objects.

My version converts the retrieved items into String objects. The resulting list will therefore be a list of strings.

There are cases where creating an anonymous type is useful. Most commonly, it is useful if you want to return multiple values (e.g. both the Message and Recipient properties).

However, your example only retrieves a single property. In this case, there is no benefit to using anonymous types. Using anonymous types when you want to retrieve a single property makes the code more complex for no good reason or benefit.

You are making yourself responsible for later unwrapping that anonymous type and reading its Message property.

It's easier to simply handle the strings directly, rather than wrapping them in an anonymous type. That means you have one less wrapped layer to worry about.

Update after your comment

Taking a closer look at the image you linked; is your question specifically why the debug values (when you hover over the results like you do in the picture) are different?

What you see in the little popup (before expanding) is essentially the .ToString() output of the variable you're inspecting.

The first example consists of a List<Fromdevicemessage>. Since Fromdevicemessage is a custom class you've built (and I assume you did not override its .ToString() method, the default ouput will be the name of the class, not its contents.

That's just how it works. If you override the .ToString() method in your Fromdevicemessage class, then you can change what it looks like.

```<code>public override string ToString()
{
     return $"Message : {this.Message}";
}
</code>```

In the second example, you are dealing with a List of anonymous types. Anonymous types have a custom .ToString() method, which already shows you the content of the object rather than its classname (since anonymous objects have no classname, at least as far as a developer can see).

Body:
Help understand please  why that query returns same values but if i use anonymous type it return correct result

//same values
var deviceMessageList1 = _deviceMessageRepository.Fromdevicemessages
                .Where(m => m.DeviceId == deviceId).Take(1000).ToList();
//different values
            var deviceMessageList2 = _deviceMessageRepository.Fromdevicemessages
                .Where(m => m.DeviceId == deviceId).Take(1000).Select(x=> new { Message = x.Message }).ToList();

[]

Body:
I've made a few assumptions:

I assume your entity class is called Fromdevicemessage

I assume that Message is a String property

.Select() in LINQ does not influence which items are retrieved. It only influences how the retrieved items are presented.

If you know SQL, you will see that SELECT in SQL works exactly the same (which is why the LINQ method is intentionally called Select, as it works the same, functionally speaking)

It helps if you understand the intention of every method, I'll comment it in:

var deviceMessageList1 =_deviceMessageRepository.Fromdevicemessages

     .Where(m => m.DeviceId == deviceId)  //Only return the items which have their DevicedId set to [deviceId]
     .Take(1000)                          //Give me the first 1000 items
     .ToList()                            //Make a list from these 1000 items

Notice that you have only specified which rows you want to retrieve. You have not specified how you want the output to be formatted.

By default, you will receive objects of the corresponding entity type Fromdevicemessage.

The list you see at the end is therefore a List<Fromdevicemessage>.

var deviceMessageList1 =_deviceMessageRepository.Fromdevicemessages

     .Where(m => m.DeviceId == deviceId)       //Only return the items which have their DevicedId set to [deviceId]
     .Take(1000)                               //Give me the first 1000 items
     .Select(x => x.Message)                   //For each retrieved item, instead of the item itself, only give me its Message (= string)
     .ToList()                                 //Make a list from these 1000 strings

Notice what the Select statement adds. It basically tells you that you do not want the full Fromdevicemessage object, but only want the Message property. You're basically telling the compiler the following:

For each Fromdevicemessage object that is currently retrieved, render me its Message property.

You were originally working with a collection of Fromdevicemessage objects. But the .Select() statement converted that collection into a collection of String objects.

Simplified, the Select() method converts every object in the source collection, based on your mapping (e.g. x => x.Message), and returns you the list of mapped values.

The list you see at the end is therefore a List<String>.

I cheated a little bit...

In case you hadn't noticed, I changed your Select statement.

Your version:

.Select( x => new { Message = x.Message } )

My version:

.Select( x => x.Message )

Both are valid code, but they work a bit differently.

Your version converts the retrieved items into anonymous objects. The resulting list will therefore be a list of anonymous objects.

My version converts the retrieved items into String objects. The resulting list will therefore be a list of strings.

There are cases where creating an anonymous type is useful. Most commonly, it is useful if you want to return multiple values (e.g. both the Message and Recipient properties).

However, your example only retrieves a single property. In this case, there is no benefit to using anonymous types. Using anonymous types when you want to retrieve a single property makes the code more complex for no good reason or benefit.

You are making yourself responsible for later unwrapping that anonymous type and reading its Message property.

It's easier to simply handle the strings directly, rather than wrapping them in an anonymous type. That means you have one less wrapped layer to worry about.

Update after your comment

Taking a closer look at the image you linked; is your question specifically why the debug values (when you hover over the results like you do in the picture) are different?

What you see in the little popup (before expanding) is essentially the .ToString() output of the variable you're inspecting.

The first example consists of a List<Fromdevicemessage>. Since Fromdevicemessage is a custom class you've built (and I assume you did not override its .ToString() method, the default ouput will be the name of the class, not its contents.

That's just how it works. If you override the .ToString() method in your Fromdevicemessage class, then you can change what it looks like.

public override string ToString()
{
     return $"Message : {this.Message}";
}

In the second example, you are dealing with a List of anonymous types. Anonymous types have a custom .ToString() method, which already shows you the content of the object rather than its classname (since anonymous objects have no classname, at least as far as a developer can see).


问:
App installation failed: Could not write to the device
In Xcode 6.3, I got this error when trying to run an iOS project written in Swift on a real device.

App installation failed

could not write to the device.

I tried to clean the project and run again, but the same error occurs.

How can I fix this error?

答: Also this the error shown if your machine running Xcode is low on space.</p>

ContentLicense: CC BY-SA 4.0


问:
How to load a view XIB as a subview into a view controller XIB
I have a custom view I made with an IB file since it's quite complex: (RotatorView.xib/.h/.m).
I want to add the RotatorView as a subview to a view controller.  I can do this programmatically using:

```<code>NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"RotatorView"
                                               owner:self options:nil];
</code>```

But I'd rather not do that. It would be better for my design if I could add the RotatorView to the canvas of a View Controller in Interface Builder.  That way I could use IB to manage the properties of each instance of RotatorView instead of setting properties programmatically in each class.  Is there a way that I can add my custom view with XIB to a parent view controller?   Do I have to build an IB plugin to do this?

答:
You can add a UIView control to the canvas in IB and change its class name to match your custom view class name.
Although this will save you from calling loadNibNamed method programmatically, but you'll not be able to set the custom properties directly from IB.

The only solution for doing this is to build an IB plugin, but unfortunately it seems you can't make Cocoa Touch IB plugins because you can't make Cocoa Touch frameworks.

Body:
I have a custom view I made with an IB file since it's quite complex: (RotatorView.xib/.h/.m).
I want to add the RotatorView as a subview to a view controller.  I can do this programmatically using:

NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"RotatorView"
                                               owner:self options:nil];

But I'd rather not do that. It would be better for my design if I could add the RotatorView to the canvas of a View Controller in Interface Builder.  That way I could use IB to manage the properties of each instance of RotatorView instead of setting properties programmatically in each class.  Is there a way that I can add my custom view with XIB to a parent view controller?   Do I have to build an IB plugin to do this?


问:
Django custom save and update
I have a custom save method for a model.

```<code>class Ticket(models.Model):
    show = models.ForeignKey(Show)
    seat = models.ForeignKey(Seat)
    ref = models.CharField(max_length=100)
    paid = models.BooleanField(default=False)

    class Meta:
        unique_together = ('show', 'seat')

    def save(self, *args, **kwargs):
        if self.paid:
            do_something()
</code>```

In the view I would like to update multiple Ticket objects:

```<code>Ticket.objects.filter(ref='ref').update(paid=True)
</code>```

But, since this won't call the custom save method. The method do_something() won't be processed. Is there any way to solve this problem?

答:
The obvious solution would be:

```<code>for ticket in Ticket.objects.filter(ref='ref'):
    ticket.paid = True
    ticket.save()
</code>```

If you are doing the update for performance reasons you don't want to give up, you could do:

```<code>new_paid_tickets = Ticket.objects.filter(ref='ref')
new_paid_tickets.update(paid=True)
for ticket in new_paid_tickets:
    do_something()
</code>```

Title: Django custom save and update

Body:
I have a custom save method for a model.

class Ticket(models.Model):
    show = models.ForeignKey(Show)
    seat = models.ForeignKey(Seat)
    ref = models.CharField(max_length=100)
    paid = models.BooleanField(default=False)

    class Meta:
        unique_together = ('show', 'seat')

    def save(self, *args, **kwargs):
        if self.paid:
            do_something()

In the view I would like to update multiple Ticket objects:

Ticket.objects.filter(ref='ref').update(paid=True)

But, since this won't call the custom save method. The method do_something() won't be processed. Is there any way to solve this problem?

Body:
The obvious solution would be:

for ticket in Ticket.objects.filter(ref='ref'):
    ticket.paid = True
    ticket.save()

If you are doing the update for performance reasons you don't want to give up, you could do:

new_paid_tickets = Ticket.objects.filter(ref='ref')
new_paid_tickets.update(paid=True)
for ticket in new_paid_tickets:
    do_something()


问:
I want to extract the tag name using sql from table with XML stored as clob. (ORACLE)
Sample XML as below:

```<code><Root>
...
<XMLNSC>
...
<SOAP-ENV:Envelope>
...
<SOAP-ENV:Body>
<typesNS0:getABCD xmlns:typesNS0="http://xxx.xx/xxxxxx/xxxxxxxxx/x/" xmlns:xalan="http://xml.apache.org/xslt">
</code>```

last tag typesNS0:getABCD want to select

答:
You may run below script if you want get exact tag value; </p>

```<code>DECLARE
vs_Xml VARCHAR2(32000):= '<Root xmlns:SOAP-ENV="http://a.b.org/">
<XMLNSC />
<SOAP-ENV:Envelope/>
<SOAP-ENV:Body/>
<typesNS0:getABCD xmlns:typesNS0="http://xxx.xx/xxxxxx/xxxxxxxxx/x/"    xmlns:xalan="http://xml.apache.org/xslt">123</typesNS0:getABCD>
</Root>';

vx_ParameterList   XMLTYPE;
vx_Parameter       XMLTYPE;
vn_ParameterIndex  NUMBER;
vs_Key             VARCHAR2(64);
vs_XPath           VARCHAR2(255);
vs_Value           VARCHAR2(10000);

BEGIN
vx_ParameterList := xmltype(vs_Xml);
vn_ParameterIndex := 1;
vs_XPath := '/Root';

WHILE vx_ParameterList.existsNode(vs_XPath || '[' || vn_ParameterIndex || ']') = 1 LOOP
vx_Parameter := vx_ParameterList.extract(vs_XPath || '[' || vn_ParameterIndex || ']');

 vs_Value := vx_Parameter.extract('//typesNS0:getABCD/text()','xmlns:typesNS0="http://xxx.xx/xxxxxx/xxxxxxxxx/x/"').GetStringVal();
vn_ParameterIndex := vn_ParameterIndex + 1;

dbms_output.put_line(vs_Value);
END LOOP;

END;
</code>```

Body:
Sample XML as below:

<Root>
...
<XMLNSC>
...
<SOAP-ENV:Envelope>
...
<SOAP-ENV:Body>
<typesNS0:getABCD xmlns:typesNS0="http://xxx.xx/xxxxxx/xxxxxxxxx/x/" xmlns:xalan="http://xml.apache.org/xslt">

last tag typesNS0:getABCD want to select

Body:
You may run below script if you want get exact tag value;

DECLARE
vs_Xml VARCHAR2(32000):= '<Root xmlns:SOAP-ENV="http://a.b.org/">
<XMLNSC />
<SOAP-ENV:Envelope/>
<SOAP-ENV:Body/>
<typesNS0:getABCD xmlns:typesNS0="http://xxx.xx/xxxxxx/xxxxxxxxx/x/"    xmlns:xalan="http://xml.apache.org/xslt">123</typesNS0:getABCD>
</Root>';

vx_ParameterList   XMLTYPE;
vx_Parameter       XMLTYPE;
vn_ParameterIndex  NUMBER;
vs_Key             VARCHAR2(64);
vs_XPath           VARCHAR2(255);
vs_Value           VARCHAR2(10000);

BEGIN
vx_ParameterList := xmltype(vs_Xml);
vn_ParameterIndex := 1;
vs_XPath := '/Root';

WHILE vx_ParameterList.existsNode(vs_XPath || '[' || vn_ParameterIndex || ']') = 1 LOOP
vx_Parameter := vx_ParameterList.extract(vs_XPath || '[' || vn_ParameterIndex || ']');

 vs_Value := vx_Parameter.extract('//typesNS0:getABCD/text()','xmlns:typesNS0="http://xxx.xx/xxxxxx/xxxxxxxxx/x/"').GetStringVal();
vn_ParameterIndex := vn_ParameterIndex + 1;

dbms_output.put_line(vs_Value);
END LOOP;

END;


问:
DigitalOcean Droplet IP address not working
I created my first droplet, but when I try to navigate to the provided IP address like http://my_ip_address, it shows This site can’t be reached in the browser.

This is the tutorial I used to create the droplet, and I got my web app from github.

Do I also need to install a webserver like Apache? The tutorial didn't say anything about needing to do that.

答:
Port 3000 is blocked by Digital Oceans firewall. Available ports are 22, 80 and 443. You could also try</p>

```<code>sudo ufw allow 3000/tcp
</code>```

Body:
Port 3000 is blocked by Digital Oceans firewall. Available ports are 22, 80 and 443. You could also try

sudo ufw allow 3000/tcp


问:
DynamoDB most efficient date type
I see that DynamoDB is essentially limited to three data types: String, Number, and Binary.  That seems to leave two options for storing a date or timestamp:

String of an 8601 date/time format or Unix timestamp

Number of a Unix timestamp

I will need to 'sort' results by using this date/timestamp as a range key and using scanIndexForward.  Is it possible to say which approach would be more efficient?

答: I just did a DescribeTable on one of my DynamoDB tables and noticed that DynamoDB itself stores the CreationDateTime of the table as a UNIX timestamp floating point number. I guess they did that for a reason.</p>

Title: DynamoDB most efficient date type


问:
IE 11 cookies in Developer tools
Is there an equivalent to Chrome's cookie view in IE 11 ?

Chrome's cookie viewer: Resources->Cookies.
Closest IE11 has is this : Network -> Go to url -> click on details - > Cookies.

IE 11 Wiki has this under removed features: "Ability to view all cookies at once via Developer Tools".

答:
You can use console of IE to edit any value of cookie

Now first hit below commond

```<code>document.cookie
</code>```

It will return you some key values. Now use below command to edit or create new key values

```<code>document.cookie="YOURKEY=YOURVALUE"
</code>```

Hope it will help you :)

Note :- It will works, if the cookie is not marked as HTTPOnly

Title: IE 11 cookies in Developer tools

Body:
You can use console of IE to edit any value of cookie

Now first hit below commond

document.cookie

It will return you some key values. Now use below command to edit or create new key values

document.cookie="YOURKEY=YOURVALUE"

Hope it will help you :)

Note :- It will works, if the cookie is not marked as HTTPOnly


问:
insert into table1 select * from another table2 , then delete the row from table2
I am trying to  insert rows into table1 select * from table2 and finally delete the rows from table2  using function in oracle sql developer. I am not getting how to do it.

follwing is my function:

```<code>create or replace FUNCTION DELETEROW(GODOWN_DIST_CODE IN
TEST_TABLE.GODOWN_DIST_CODE%TYPE)  return varchar2
AS
returned_value varchar2(50);
BEGIN
begin
INSERT INTO TEST_TABLE_BACKUP SELECT * FROM TEST_TABLE WHERE
GODOWN_DIST_CODE=GODOWN_DIST_CODE;
DELETE TEST_TABLE WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

INSERT INTO NEW_TABLE_BACKUP SELECT * FROM NEW_TABLE WHERE GODOWN_DIST_CODE
= GODOWN_DIST_CODE;
DELETE FROM NEW_TABLE WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

exception
 WHEN no_data_found THEN
      returned_value := '#';
end;
RETURN returned_value;
END;
</code>```

答:
As per our discussion, i propose this solution for you. Even though i dont find any need of having a FUNCTION am showing the exmaple using a FUNCTION. Also I had written your delete logic to a Procedure and depending on the success of delete statement, a Return value is caputured in variable var and sending as OUT paramater which you can use.

Function:

```<code>CREATE OR REPLACE FUNCTION confirm_ckh
   RETURN VARCHAR
AS
BEGIN
   RETURN ('#');
END;
</code>```

Procedure:

```<code>CREATE OR REPLACE PROCEDURE DELETEROW (
   GODOWN_DIST_CODE   IN TEST_TABLE.GODOWN_DIST_CODE%TYPE,
   var OUT varchar2) <-- Out parameter to get the return value
AS

BEGIN
   BEGIN
      INSERT INTO TEST_TABLE_BACKUP
         SELECT *
           FROM TEST_TABLE
          WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

      IF SQL%ROWCOUNT > 0
      THEN
         DBMS_OUTPUT.put_line ('Insert Success TEST_TABLE_BACKUP');
         var:=confirm_ckh;
      END IF;

      DELETE TEST_TABLE
       WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

      IF SQL%ROWCOUNT > 0
      THEN
         DBMS_OUTPUT.put_line ('Deleted records from TEST_TABLE ');
         var:=confirm_ckh;
      END IF;

      INSERT INTO NEW_TABLE_BACKUP
         SELECT *
           FROM NEW_TABLE
          WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

      IF SQL%ROWCOUNT > 0
      THEN
         DBMS_OUTPUT.put_line ('Insert Success for NEW_TABLE_BACKUP');
         var:=confirm_ckh;
      END IF;

      DELETE FROM NEW_TABLE
            WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

      IF SQL%ROWCOUNT > 0
      THEN
         DBMS_OUTPUT.put_line ('Deleted records from NEW_TABLE ');
         var:=confirm_ckh;
      END IF;
   EXCEPTION
      WHEN NO_DATA_FOUND
      THEN
         null;
   END;
END;
</code>```

Body:
I am trying to  insert rows into table1 select * from table2 and finally delete the rows from table2  using function in oracle sql developer. I am not getting how to do it.

follwing is my function:

create or replace FUNCTION DELETEROW(GODOWN_DIST_CODE IN
TEST_TABLE.GODOWN_DIST_CODE%TYPE)  return varchar2
AS
returned_value varchar2(50);
BEGIN
begin
INSERT INTO TEST_TABLE_BACKUP SELECT * FROM TEST_TABLE WHERE
GODOWN_DIST_CODE=GODOWN_DIST_CODE;
DELETE TEST_TABLE WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

INSERT INTO NEW_TABLE_BACKUP SELECT * FROM NEW_TABLE WHERE GODOWN_DIST_CODE
= GODOWN_DIST_CODE;
DELETE FROM NEW_TABLE WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

exception
 WHEN no_data_found THEN
      returned_value := '#';
end;
RETURN returned_value;
END;

Body:
As per our discussion, i propose this solution for you. Even though i dont find any need of having a FUNCTION am showing the exmaple using a FUNCTION. Also I had written your delete logic to a Procedure and depending on the success of delete statement, a Return value is caputured in variable var and sending as OUT paramater which you can use.

Function:

CREATE OR REPLACE FUNCTION confirm_ckh
   RETURN VARCHAR
AS
BEGIN
   RETURN ('#');
END;

Procedure:

CREATE OR REPLACE PROCEDURE DELETEROW (
   GODOWN_DIST_CODE   IN TEST_TABLE.GODOWN_DIST_CODE%TYPE,
   var OUT varchar2) <-- Out parameter to get the return value
AS

BEGIN
   BEGIN
      INSERT INTO TEST_TABLE_BACKUP
         SELECT *
           FROM TEST_TABLE
          WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

      IF SQL%ROWCOUNT > 0
      THEN
         DBMS_OUTPUT.put_line ('Insert Success TEST_TABLE_BACKUP');
         var:=confirm_ckh;
      END IF;

      DELETE TEST_TABLE
       WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

      IF SQL%ROWCOUNT > 0
      THEN
         DBMS_OUTPUT.put_line ('Deleted records from TEST_TABLE ');
         var:=confirm_ckh;
      END IF;

      INSERT INTO NEW_TABLE_BACKUP
         SELECT *
           FROM NEW_TABLE
          WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

      IF SQL%ROWCOUNT > 0
      THEN
         DBMS_OUTPUT.put_line ('Insert Success for NEW_TABLE_BACKUP');
         var:=confirm_ckh;
      END IF;

      DELETE FROM NEW_TABLE
            WHERE GODOWN_DIST_CODE = GODOWN_DIST_CODE;

      IF SQL%ROWCOUNT > 0
      THEN
         DBMS_OUTPUT.put_line ('Deleted records from NEW_TABLE ');
         var:=confirm_ckh;
      END IF;
   EXCEPTION
      WHEN NO_DATA_FOUND
      THEN
         null;
   END;
END;


问:
Hybrid App platform & technology
I'm a full stack developer with PHP, HTML5, CSS3, Javascript, Jquery, Angular and with enthusiast to lear any new technology.

Now i got a hybrid mobile app project(simpler with few curd operations and web services) and plus it will be web app as well, which i need to deliver as soon as possible. So my question is to choosing the right tool for the right job.

Hybrid App can be build with

Platform: Phonegap or cordova, where cordova is extension of phonegap as per my
understanding.

Technologies: Plain html/css/jquery mobile or using
some of the framework like ionic with angular.

So i want to know which tools and technology for building a hybrid app are preferable good and easy to learn faster.

答:
You can build Hybrid mobile apps using a phonegap,Cordova,IBM mobilefirst, IONIc.

I prefer IONIc. This is real good and amazing.
Everything is built in, including UI,Plugins to access native functions.

You can use IONIC 2 and Angular 2.

Title: Hybrid App platform & technology


问:
How to use expr inside regsub in TCL?
Suppose, set s1 "some4number"

I want to change it to some5number.

I was hoping that this would work :

```<code>regsub {(\d)(\S+)} $s1 "[expr \\1 + 1]\\2"
</code>```

But it errors out. What would be the ideal way to do this in TCL ?

答:
The Tcler's Wiki has many neat things. One of them is this:

```<code># There are times when looking at this I think that the abyss is staring back
proc regsub-eval {re string cmd} {
    subst [regsub $re [string map {[ \\[ ] \\] $ \\$ \\ \\\\} $string] \[$cmd\]]
}
</code>```

With that, we can do this:

```<code>set s1 "some4number"
# Note: RE changed to use forward lookahead
set s2 [regsub-eval {\d(?=\S+)} $s1 {expr & + 1}]
# ==> some5number
</code>```

But this will become less awful in the future with 8.7 (in development). Here's what you'd do with an apply-term helper:

```<code>set s2 [regsub -command {(\d)(\S+)} $s1 {apply {{- 1 2} {
    return "[expr {$1 + 1}]$2"
}}}]
</code>```

With a helper procedure instead:

```<code>proc incrValueHelper {- 1 2} {
    return "[expr {$1 + 1}]$2"
}
set s2 [regsub -command {(\d)(\S+)} $s1 incrValueHelper]
</code>```

Title: How to use expr inside regsub in TCL?

Body:
Suppose, set s1 "some4number"

I want to change it to some5number.

I was hoping that this would work :

regsub {(\d)(\S+)} $s1 "[expr \\1 + 1]\\2"

But it errors out. What would be the ideal way to do this in TCL ?

Body:
The Tcler's Wiki has many neat things. One of them is this:

# There are times when looking at this I think that the abyss is staring back
proc regsub-eval {re string cmd} {
    subst [regsub $re [string map {[ \\[ ] \\] $ \\$ \\ \\\\} $string] \[$cmd\]]
}

With that, we can do this:

set s1 "some4number"
# Note: RE changed to use forward lookahead
set s2 [regsub-eval {\d(?=\S+)} $s1 {expr & + 1}]
# ==> some5number

But this will become less awful in the future with 8.7 (in development). Here's what you'd do with an apply-term helper:

set s2 [regsub -command {(\d)(\S+)} $s1 {apply {{- 1 2} {
    return "[expr {$1 + 1}]$2"
}}}]

With a helper procedure instead:

proc incrValueHelper {- 1 2} {
    return "[expr {$1 + 1}]$2"
}
set s2 [regsub -command {(\d)(\S+)} $s1 incrValueHelper]


问:
Not able to place google maps covering the page
I am a complete newbie to html and css and I am creating a game where I want to use a couple of grids/columns to display a place and timer and the rest of the page to be filled with Map. I dont know how to acheive it. If I try the pixels
it doesnt occupy the entire screen and I am sure it would be a problem if it was to be done in mobile

Here is my code

```<code>  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-3" style="background-color:orange;">
      {{ countDownTimer }}
      </div>
      <div class="col-sm-9" style="background-color:pink;">
        {{ puzzle.name}} , {{ puzzle.country }}
      </div>
    </div>
    <div class="row">
      <div class="col-sm-12" id="map" style="width:100%; height:100%;"></div>
    </div>
  </div>
</code>```

答:
Here is a working solution of what you are trying to achieve: http://jsfiddle.net/4mtyu/2758/

```<code><div class="container-fluid">
  <div class="row">
    <div class="col-sm-3" style="background-color:orange;">
      {{ countDownTimer }}
    </div>
    <div class="col-sm-9" style="background-color:pink;">
      {{ puzzle.name}} , {{ puzzle.country }}
    </div>
  </div>
</div>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
<div id="map_div"></div>
</code>```

CSS:

```<code>html,
body,
#map_div {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

#map_div {
  position: relative;
}

h1,
p {
  margin: 0;
  padding: 0;
}
</code>```

more info here :

Set Google Maps Container DIV width and height 100%

https://developer.mozilla.org/en-US/docs/Web/CSS/Reference

Body:
I am a complete newbie to html and css and I am creating a game where I want to use a couple of grids/columns to display a place and timer and the rest of the page to be filled with Map. I dont know how to acheive it. If I try the pixels
it doesnt occupy the entire screen and I am sure it would be a problem if it was to be done in mobile

Here is my code

      {{ countDownTimer }}

        {{ puzzle.name}} , {{ puzzle.country }}

Body:
Here is a working solution of what you are trying to achieve: http://jsfiddle.net/4mtyu/2758/

<div class="container-fluid">
  <div class="row">
    <div class="col-sm-3" style="background-color:orange;">
      {{ countDownTimer }}
    </div>
    <div class="col-sm-9" style="background-color:pink;">
      {{ puzzle.name}} , {{ puzzle.country }}
    </div>
  </div>
</div>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?v=3&amp;sensor=false"></script>
<div id="map_div"></div>

CSS:

html,
body,
#map_div {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}

#map_div {
  position: relative;
}

h1,
p {
  margin: 0;
  padding: 0;
}

more info here :

Set Google Maps Container DIV width and height 100%

https://developer.mozilla.org/en-US/docs/Web/CSS/Reference


问:
HTTP Error 503. The service is unavailable
I'm struggling to setup the environment in IIS8, I searched a lot but couldn't find a right solution.

I checked the error logs, but no idea.

C:\Windows\System32\LogFiles\HTTPERR

2013-10-09 09:28:39 192.168.43.205 60172 192.168.43.205 80 HTTP/1.1
  GET / 503 2 AppOffline qa.hti.local

2013-10-09 09:28:39 192.168.43.205 60192 192.168.43.205 80 HTTP/1.1
  GET /favicon.ico 503 2 AppOffline qa.hti.local

Then in Event Viewer:

WARNINGS:

A listener channel for protocol 'http' in worker process '11188'
  serving application pool 'qa.hti.local' reported a listener channel
  failure.  The data field contains the error number.

A listener channel for protocol 'http' in worker process '7492'
  serving application pool 'qa.hti.local' reported a listener channel
  failure.  The data field contains the error number.

A listener channel for protocol 'http' in worker process '9088'
  serving application pool 'qa.hti.local' reported a listener channel
  failure.  The data field contains the error number.

A listener channel for protocol 'http' in worker process '9964'
  serving application pool 'qa.hti.local' reported a listener channel
  failure.  The data field contains the error number.

A listener channel for protocol 'http' in worker process '7716'
  serving application pool 'qa.hti.local' reported a listener channel
  failure.  The data field contains the error number.

I don't understand what the warning means.

ERROR: Application pool 'qa.hti.local' is being automatically disabled due to a series of failures in the process(es) serving that
  application pool.

Note: I learned that consecutive 5 failures leads to APP Pool crash, and this can increased.  I also tried increasing this but no success.

Please share your thoughts.

答: I had the same problem and solved it by adding the domain account the application pool was using as an identity to the local group of Administrators on a web server. Perhaps it would also do the trick to grant access to the application directory for the application pool identity account, as @Lisa-Berlin stated above.</p>


问:
Django ORM Cannot filter by reversed foreign key
I have a weird behaviour on my production server. When I try to filter by reversed foreign key then I receive an error that it is not possible, but locally it works fine, e.g.:

```<code>class Foo(models.Model):
    pass

class Bar(models.Model):
    name = models.CharField()
    foo = models.ForeignKey('Foo', related_name='bars', blank=True, null=True, default=None)
</code>```

Now trying to do:

```<code>Foo.objects.filter(bars__name=xyz)
</code>```

will result with

Cannot resolve keyword 'bars' into field. Choices are: ...

I use Ubuntu 16.04 and django 1.8.7

EDIT 1:
can it be related to the fact that ForeignKeys are defined using string representation?

EDIT 2:
I have found relation which is defined using class not string, so it doesn't work for such relations as well.

Basically model Foo has many ForeignKey relations. Few in Foo, few in target models. These in target models do not exist on production when running query from Foo perspective. These in Foo can be used as query params.

EDIT 3:
I have received more detailed information of server configuration and when exactly error occurs.

Info about the production setup where the issue is seen:

apache version: 2.4.18-2ubuntu3.3

libapache2-mod-wsgi version: 4.3.0-1.1build1

Apache mpm_event config:

```<code>StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0
</code>```

Relevant part of apache site config:

```<code>WSGIDaemonProcess some_name group=some_name maximum-requests=1000 processes=2 threads=15 user=some_name
WSGIProcessGroup some_name
WSGIScriptAlias / "/usr/lib/python2.7/dist-packages/some_name/wsgi.py"
WSGIPassAuthorization On
</code>```

Basically error does not happen with every request. When it appears then it comes from one worker. Restarting apache fixes errors for some time.

One of the thoughts is that there may be a race condition in loading django models.

答:
You must use related_query_name in your query filter. By default in Django 1.8 it's model name, so set custom related_query_name or change your code to this:</p>

```<code>Foo.objects.filter(bar__name=xyz)
</code>```

Body:
I have a weird behaviour on my production server. When I try to filter by reversed foreign key then I receive an error that it is not possible, but locally it works fine, e.g.:

class Foo(models.Model):
    pass

class Bar(models.Model):
    name = models.CharField()
    foo = models.ForeignKey('Foo', related_name='bars', blank=True, null=True, default=None)

Now trying to do:

Foo.objects.filter(bars__name=xyz)

will result with

Cannot resolve keyword 'bars' into field. Choices are: ...

I use Ubuntu 16.04 and django 1.8.7

EDIT 1:
can it be related to the fact that ForeignKeys are defined using string representation?

EDIT 2:
I have found relation which is defined using class not string, so it doesn't work for such relations as well.

Basically model Foo has many ForeignKey relations. Few in Foo, few in target models. These in target models do not exist on production when running query from Foo perspective. These in Foo can be used as query params.

EDIT 3:
I have received more detailed information of server configuration and when exactly error occurs.

Info about the production setup where the issue is seen:

apache version: 2.4.18-2ubuntu3.3

libapache2-mod-wsgi version: 4.3.0-1.1build1

Apache mpm_event config:

StartServers 2
MinSpareThreads 25
MaxSpareThreads 75
ThreadLimit 64
ThreadsPerChild 25
MaxRequestWorkers 150
MaxConnectionsPerChild 0

Relevant part of apache site config:

WSGIDaemonProcess some_name group=some_name maximum-requests=1000 processes=2 threads=15 user=some_name
WSGIProcessGroup some_name
WSGIScriptAlias / "/usr/lib/python2.7/dist-packages/some_name/wsgi.py"
WSGIPassAuthorization On

Basically error does not happen with every request. When it appears then it comes from one worker. Restarting apache fixes errors for some time.

One of the thoughts is that there may be a race condition in loading django models.

Body:
You must use related_query_name in your query filter. By default in Django 1.8 it's model name, so set custom related_query_name or change your code to this:

Foo.objects.filter(bar__name=xyz)


问:
Flask migration python2 to 3 ImportError: cannot import name
I have a flask server with the following architecture

```<code>.
├── doc
│   ├── apidoc.json
│   ├── docAPI
│   └── generation_doc
├── images
│   ├── parking
│   └── user
├── log
│   └── file.log
├── README.md
├── requirements.txt
├── run_server.py
├── server
│   ├── controllers
│   ├── __init__.py
│   ├── models
│   ├── myServerUtils
│   ├── __pycache__
│   └── routes
└── venv
    ├── bin
    ├── include
    ├── lib
    └── pip-selfcheck.json
</code>```

Everything is running fine under python2. But I have to migrate to python3.
After changing the requirements of python-mysql to pymysql and refactoring how the imports are done, here is the error I get.

```<code>/home/myUser/Documents/myServer/backend/venv/bin/python /home/myUser/Documents/myServer/backend/run_server.py
Traceback (most recent call last):
  File "/home/myUser/Documents/myServer/backend/run_server.py", line 4, in <module>
    from server import app
  File "/home/myUser/Documents/myServer/backend/server/__init__.py", line 26, in <module>
    from .controllers import *
  File "/home/myUser/Documents/myServer/backend/server/controllers/__init__.py", line 1, in <module>
    from .user import *
  File "/home/myUser/Documents/myServer/backend/server/controllers/user.py", line 3, in <module>
    from .. import UserTable
ImportError: cannot import name 'UserTable'

Process finished with exit code 1
</code>```

The imports in the file controllers/user.py are

```<code>from .. import db
from .. import return_error
from .. import UserTable
from .. import ErrorType
from .. import Logger
from .. import ParkingTable
from .. import ParkingBookedTable
from .. import reset_password as mail_reset_password
from .. import app
from flask import request, jsonify, send_file
import exrex, hashlib
from validate_email import validate_email
from datetime import datetime
import uuid
import os
import time
</code>```

and here are the imports from models/users.py where UserTable is defined

```<code>from .. import db
from .. import ErrorType
from validate_email import validate_email
import uuid
import time
</code>```

Thanks by advance!

[EDIT]: To add a complement of information regarding the answer of dmitrybelyakov, the problem was coming from my IDE that had optimised the imports and messed up some of them.
Rolling back on my git and setting my imports correctly did the job.

答: I don't have a definitive answer, but I would start by checking if there are any circular imports happening. </p>

Body:
I have a flask server with the following architecture

.
├── doc
│   ├── apidoc.json
│   ├── docAPI
│   └── generation_doc
├── images
│   ├── parking
│   └── user
├── log
│   └── file.log
├── README.md
├── requirements.txt
├── run_server.py
├── server
│   ├── controllers
│   ├── __init__.py
│   ├── models
│   ├── myServerUtils
│   ├── __pycache__
│   └── routes
└── venv
    ├── bin
    ├── include
    ├── lib
    └── pip-selfcheck.json

Everything is running fine under python2. But I have to migrate to python3.
After changing the requirements of python-mysql to pymysql and refactoring how the imports are done, here is the error I get.

/home/myUser/Documents/myServer/backend/venv/bin/python /home/myUser/Documents/myServer/backend/run_server.py
Traceback (most recent call last):
  File "/home/myUser/Documents/myServer/backend/run_server.py", line 4, in <module>
    from server import app
  File "/home/myUser/Documents/myServer/backend/server/__init__.py", line 26, in <module>
    from .controllers import *
  File "/home/myUser/Documents/myServer/backend/server/controllers/__init__.py", line 1, in <module>
    from .user import *
  File "/home/myUser/Documents/myServer/backend/server/controllers/user.py", line 3, in <module>
    from .. import UserTable
ImportError: cannot import name 'UserTable'

Process finished with exit code 1

The imports in the file controllers/user.py are

from .. import db
from .. import return_error
from .. import UserTable
from .. import ErrorType
from .. import Logger
from .. import ParkingTable
from .. import ParkingBookedTable
from .. import reset_password as mail_reset_password
from .. import app
from flask import request, jsonify, send_file
import exrex, hashlib
from validate_email import validate_email
from datetime import datetime
import uuid
import os
import time

and here are the imports from models/users.py where UserTable is defined

from .. import db
from .. import ErrorType
from validate_email import validate_email
import uuid
import time

Thanks by advance!

[EDIT]: To add a complement of information regarding the answer of dmitrybelyakov, the problem was coming from my IDE that had optimised the imports and messed up some of them.
Rolling back on my git and setting my imports correctly did the job.


问:
How to find a text inside SQL Server procedures / triggers?
I have a linkedserver that will change. Some procedures call the linked server like this: [10.10.100.50].dbo.SPROCEDURE_EXAMPLE. We have triggers also doing this kind of work. We need to find all places that uses [10.10.100.50] to change it.

In SQL Server Management Studio Express, I didn't find a feature like "find in whole database" in Visual Studio. Can a special sys-select help me find what I need?

答:
```<code>SELECT ROUTINE_TYPE, ROUTINE_NAME, ROUTINE_DEFINITION
FROM INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_DEFINITION LIKE '%Your Text%'
</code>```

OwnerDisplayName: Victor Rodrigues


问:
SQL Dynamic Column Query

Possible Duplicate:

  Is there a way to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

I have a table of "Events", and each event has a a list of 1-4 (essentially variable #) "Users". So let's say I get all events for today, and then I want to list the users as a dynamic number of columns, rather than repeated rows.

Right now I have

```<code>SELECT E.EventID, E.Time, U.Name FROM Events
INNER JOIN Users U ON E.UserID = U.UserID
WHERE Date = '12/20/2010'
</code>```

This brings me results like:

```<code>EventID, Time, Name
211, '4:00am', 'Joe'
211, '4:00am', 'Phil'
211, "4:00am', 'Billy'
218, '7:00am', 'Sally'
218, '7:00am', 'Susan'
</code>```

I can work with this and it's acceptable, however the duplication for EventID and Time (there are more columns in my actual query) seems wasteful to me. What I would really like in the output is this:

```<code>EventID, Time, Name1, Name2, Name3
211, '4:00am', 'Joe', 'Phil', 'Billy'
218, '7:00am', 'Sally', 'Susan', NULL
</code>```

I have tried looking at tutorials for PIVOTs (I have SQL 2008), but I don't know if they conceptually match what I'm trying to do. Most of them are using "MIN" or "MAX".

Maybe this can't be done? My other alternative is to get a list of Events for today, and then loop through that, finding a recordset of Users for that Event. I would prefer to grab it all in one query though.

Any ideas?

答:
Returning a variable number of columns would be harder to deal with in code. The result set you are currently getting is easy to transform into an object that you can worth with in code.

What are you trying to do with the output?

Title: SQL Dynamic Column Query

Body:
Possible Duplicate:

  Is there a way to create a SQL Server function to "join" multiple rows from a subquery into a single delimited field?

I have a table of "Events", and each event has a a list of 1-4 (essentially variable #) "Users". So let's say I get all events for today, and then I want to list the users as a dynamic number of columns, rather than repeated rows.

Right now I have

SELECT E.EventID, E.Time, U.Name FROM Events
INNER JOIN Users U ON E.UserID = U.UserID
WHERE Date = '12/20/2010'

This brings me results like:

EventID, Time, Name
211, '4:00am', 'Joe'
211, '4:00am', 'Phil'
211, "4:00am', 'Billy'
218, '7:00am', 'Sally'
218, '7:00am', 'Susan'

I can work with this and it's acceptable, however the duplication for EventID and Time (there are more columns in my actual query) seems wasteful to me. What I would really like in the output is this:

EventID, Time, Name1, Name2, Name3
211, '4:00am', 'Joe', 'Phil', 'Billy'
218, '7:00am', 'Sally', 'Susan', NULL

I have tried looking at tutorials for PIVOTs (I have SQL 2008), but I don't know if they conceptually match what I'm trying to do. Most of them are using "MIN" or "MAX".

Maybe this can't be done? My other alternative is to get a list of Events for today, and then loop through that, finding a recordset of Users for that Event. I would prefer to grab it all in one query though.

Any ideas?


问:
List of oEmbed providers
I am trying to find out all the oEmbed providers out there. I went to the oEmbed spec site and they have a few, but I found out a few other that weren't specified, like 5min video:

```<code>Provider: 5min
URL scheme: http://www.5min.com/video/*
API Endpoint: http://api.5min.com/oembed.{format}
Docs: http://www.5min.com/APIDocs/Embed.aspx
</code>```

Nothing better than to ask the developer community in StackOverflow.

答: embedo does that, its lightweight and easy api. You can try it for your case https://shobhitsharma.github.io/embedo

Title: List of oEmbed providers

Body:
I am trying to find out all the oEmbed providers out there. I went to the oEmbed spec site and they have a few, but I found out a few other that weren't specified, like 5min video:

Provider: 5min
URL scheme: http://www.5min.com/video/*
API Endpoint: http://api.5min.com/oembed.{format}
Docs: http://www.5min.com/APIDocs/Embed.aspx

Nothing better than to ask the developer community in StackOverflow.


问:
Convert model.ckpt to usable model
I'm training an inception model from scratch using the scripts provided here.
The output of the training are these files:

```<code>checkpoint
events.out.tfevents.1499334145.fdbf-Dell
model.ckpt-5000.data-00000-of-00001
model.ckpt-5000.index
model.ckpt-5000.meta
...
model.ckpt-25000.data-00000-of-00001
model.ckpt-25000.index
model.ckpt-25000.meta
</code>```

Does someone have a script to convert these files in something I can use to classify my images? I have already tried to modify the inception_train.py file to output the graph.pb, but nothing happens...

Any help would be appreciated, thank you!

答:
How to use your checkpoint directly is explained here.

To create a .pb file, you'll have to freeze the graph, as explained here.

To create the initial .pb (or .pbtxt) file needed for freeze_graph, you can use tf.train.write_graph()

Title: Convert model.ckpt to usable model

Body:
I'm training an inception model from scratch using the scripts provided here.
The output of the training are these files:

checkpoint
events.out.tfevents.1499334145.fdbf-Dell
model.ckpt-5000.data-00000-of-00001
model.ckpt-5000.index
model.ckpt-5000.meta
...
model.ckpt-25000.data-00000-of-00001
model.ckpt-25000.index
model.ckpt-25000.meta

Does someone have a script to convert these files in something I can use to classify my images? I have already tried to modify the inception_train.py file to output the graph.pb, but nothing happens...

Any help would be appreciated, thank you!


问:
Rails root path with locale but without query string
I want to apply i18n to the root path of my application. The Rails i18n guides suggests:

Of course, you need to take special care of the root URL (usually "homepage" or "dashboard") of your application. A URL like http://localhost:3001/nl will not work automatically, because the root to: "books#index" declaration in your routes.rb doesn't take locale into account. (And rightly so: there's only one "root" URL.)

You would probably need to map URLs like these:

```<code># config/routes.rb
get "/:locale" => "dashboard#index"
</code>```

However this configuration doesn't work nicely when using URL helpers. The following produces a URL with a query string:

```<code>root_path(locale: "fr") # => "/?locale=fr"
</code>```

But I want to produce a URL with the locale in the path:

```<code>/fr
</code>```

答:
By defining a root and locale_root:

```<code># config/routes.rb
root to: "dashboard#index"

scope "/:locale" do
  get "/", to: "dashboard#index", as: :locale_root
end
</code>```

You can then use the locale_root_path and locale_root_url helpers:

```<code>locale_root_path(locale: "fr") # => "/fr"
</code>```

Body:
I want to apply i18n to the root path of my application. The Rails i18n guides suggests:

Of course, you need to take special care of the root URL (usually "homepage" or "dashboard") of your application. A URL like http://localhost:3001/nl will not work automatically, because the root to: "books#index" declaration in your routes.rb doesn't take locale into account. (And rightly so: there's only one "root" URL.)

You would probably need to map URLs like these:

# config/routes.rb
get "/:locale" => "dashboard#index"

However this configuration doesn't work nicely when using URL helpers. The following produces a URL with a query string:

root_path(locale: "fr") # => "/?locale=fr"

But I want to produce a URL with the locale in the path:

/fr

Body:
By defining a root and locale_root:

# config/routes.rb
root to: "dashboard#index"

scope "/:locale" do
  get "/", to: "dashboard#index", as: :locale_root
end

You can then use the locale_root_path and locale_root_url helpers:

locale_root_path(locale: "fr") # => "/fr"


问:
Total running on dynamics columns
I have a table that looks something like the following :

```<code>          W1  W2 w3
Gold      10    2    3
Silver     3    1    1
</code>```

but i need a result :

```<code>          W1  W2  w3
Gold      10  12  15
Silver     3  4  5
</code>```

Is there any way i can get that result?

My sql query :

```<code>SELECT
   week1=[1],week2=[2],week3=[3]
FROM
(
    SELECT
    [week]=DATEPART(ISO_WEEK,ta.enddate),ta.price
    FROM
    table1 ta where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
) src
PIVOT
(
    SUM(price) FOR week IN (
        [1],[2],[3])
) piv
</code>```

答:
Calculate the running total before pivoting the data

```<code>SELECT element,
       week1=[1],week2=[2],week3=[3]
FROM
(
SELECT [week] = DATEPART(ISO_WEEK,ta.enddate),
       price = sum(ta.price)Over(Partition by element Order by enddate),
       element
FROM table1 ta
where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
) src
PIVOT
(
 SUM(price) FOR week IN ( [1],[2],[3])
) piv
</code>```

for older versions

```<code>SELECT element,
       week1=[1],week2=[2],week3=[3]
FROM
(
SELECT [week] = DATEPART(ISO_WEEK,ta.enddate),
       cs.price,
       element
FROM table1 ta
cross apply(select sum(price) from table1 tb
            where ta.element = tb.element and ta.enddate >= tb.enddate ) cs (price)
where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
) src
PIVOT
(
 SUM(price) FOR week IN ( [1],[2],[3])
) piv
</code>```

Title: Total running on dynamics columns

Body:
I have a table that looks something like the following :

          W1  W2 w3
Gold      10    2    3
Silver     3    1    1

but i need a result :

          W1  W2  w3
Gold      10  12  15
Silver     3  4  5

Is there any way i can get that result?

My sql query :

SELECT
   week1=[1],week2=[2],week3=[3]
FROM
(
    SELECT
    [week]=DATEPART(ISO_WEEK,ta.enddate),ta.price
    FROM
    table1 ta where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
) src
PIVOT
(
    SUM(price) FOR week IN (
        [1],[2],[3])
) piv

Body:
Calculate the running total before pivoting the data

SELECT element,
       week1=[1],week2=[2],week3=[3]
FROM
(
SELECT [week] = DATEPART(ISO_WEEK,ta.enddate),
       price = sum(ta.price)Over(Partition by element Order by enddate),
       element
FROM table1 ta
where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
) src
PIVOT
(
 SUM(price) FOR week IN ( [1],[2],[3])
) piv

for older versions

SELECT element,
       week1=[1],week2=[2],week3=[3]
FROM
(
SELECT [week] = DATEPART(ISO_WEEK,ta.enddate),
       cs.price,
       element
FROM table1 ta
cross apply(select sum(price) from table1 tb
            where ta.element = tb.element and ta.enddate >= tb.enddate ) cs (price)
where ta.enddate BETWEEN '2016/01/01' AND '2016/12/31'
) src
PIVOT
(
 SUM(price) FOR week IN ( [1],[2],[3])
) piv