问:
Share Image On Whatsapp Via URL
I am creating Images app from my WordPress website with json and i am using swift, i want to share image on whatsapp from my app , currently i tried this code it works but only with image name i want to share image from image url, is that possible ?

this is my code

```<code> let urlWhats = "whatsapp://app"
          if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed) {
              if let whatsappURL = URL(string: urlString) {

                  if UIApplication.shared.canOpenURL(whatsappURL as URL) {

                      if let image = UIImage(named: "splash") {
                        if let imageData = image.jpegData(compressionQuality: 1.0) {
                              let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")
                              do {
                                  try imageData.write(to: tempFile, options: .atomic)
                                  self.documentInteractionController = UIDocumentInteractionController(url: tempFile)
                                  self.documentInteractionController.uti = "net.whatsapp.image"
                                  self.documentInteractionController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)

                              } catch {
                                  print(error)
                              }
                          }
                      }

                  } else {
                      // Cannot open whatsapp
                  }
              }
          }
</code>```

Thanks

答:
Firstly you should download an image from URL

Create a function to get data

func data(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
    URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}
```

<hr>

<p>What to do for this -></p>

<pre class="lang-swift prettyprint-override"><code>let urlWhats = "whatsapp://app"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed) {
    if let whatsappURL = URL(string: urlString) {

        if UIApplication.shared.canOpenURL(whatsappURL as URL) {

            // Set your image's URL into here
            let url = URL(string: "https://your-image-url.com")!
            data(from: url) { data, response, error in
                guard let data = data, error == nil else { return }
                DispatchQueue.main.async() { [weak self] in

                    let image = UIImage(data: data)
                    if let imageData = image.jpegData(compressionQuality: 1.0) {
                        let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")
                        do {
                            try imageData.write(to: tempFile, options: .atomic)
                            self.documentInteractionController = UIDocumentInteractionController(url: tempFile)
                            self.documentInteractionController.uti = "net.whatsapp.image"
                            self.documentInteractionController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)

                        } catch {
                            print(error)
                        }
                    }
                }
            }

        } else {
            // Cannot open whatsapp
        }
    }
}
</code>```

Title: Share Image On Whatsapp Via URL

Body:
I am creating Images app from my WordPress website with json and i am using swift, i want to share image on whatsapp from my app , currently i tried this code it works but only with image name i want to share image from image url, is that possible ?

this is my code

 let urlWhats = "whatsapp://app"
          if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed) {
              if let whatsappURL = URL(string: urlString) {

                  if UIApplication.shared.canOpenURL(whatsappURL as URL) {

                      if let image = UIImage(named: "splash") {
                        if let imageData = image.jpegData(compressionQuality: 1.0) {
                              let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")
                              do {
                                  try imageData.write(to: tempFile, options: .atomic)
                                  self.documentInteractionController = UIDocumentInteractionController(url: tempFile)
                                  self.documentInteractionController.uti = "net.whatsapp.image"
                                  self.documentInteractionController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)

                              } catch {
                                  print(error)
                              }
                          }
                      }

                  } else {
                      // Cannot open whatsapp
                  }
              }
          }

Thanks

Body:
Firstly you should download an image from URL

Create a function to get data

func data(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) {
    URLSession.shared.dataTask(with: url, completionHandler: completion).resume()
}

What to do for this ->

let urlWhats = "whatsapp://app"
if let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed) {
    if let whatsappURL = URL(string: urlString) {

        if UIApplication.shared.canOpenURL(whatsappURL as URL) {

            // Set your image's URL into here
            let url = URL(string: "https://your-image-url.com")!
            data(from: url) { data, response, error in
                guard let data = data, error == nil else { return }
                DispatchQueue.main.async() { [weak self] in

                    let image = UIImage(data: data)
                    if let imageData = image.jpegData(compressionQuality: 1.0) {
                        let tempFile = URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Documents/whatsAppTmp.wai")
                        do {
                            try imageData.write(to: tempFile, options: .atomic)
                            self.documentInteractionController = UIDocumentInteractionController(url: tempFile)
                            self.documentInteractionController.uti = "net.whatsapp.image"
                            self.documentInteractionController.presentOpenInMenu(from: CGRect.zero, in: self.view, animated: true)

                        } catch {
                            print(error)
                        }
                    }
                }
            }

        } else {
            // Cannot open whatsapp
        }
    }
}


来源: stackexchange

问:
How do I open a MHTML file in Python?
I am trying to open a .mht file in my local system. But it is throwing me File Not Found Error even if the file exists. THis MHTML file is the output of the step recorder in Windows. I want to extract only the text in the file.

The function I used to open the file is:

```<code>with open(mi_file) as fp
</code>```

where mi_file is holding the file name.

The error I am getting is:

```<code>Traceback (most recent call last):
  File "C:/Users/swapn/PycharmProjects/StepRecorderAutomation/mhtml_parsing.py", line 40, in <module>
    with open(mi_file) as fp:
FileNotFoundError: [Errno 2] No such file or directory: 'Recording_20200528_1557.mht'
</code>```

Could someone please help me to find what am I doing wrong here?

答:
Can be solved by two options:

Option 1: Go to the file location and set that as working directory.

Option 2: Copy the full path of the file location and save it in mi_file.
mi_file = ('path of the file')

ContentLicense: CC BY-SA 4.0

Title: How do I open a MHTML file in Python?

Body:
I am trying to open a .mht file in my local system. But it is throwing me File Not Found Error even if the file exists. THis MHTML file is the output of the step recorder in Windows. I want to extract only the text in the file.

The function I used to open the file is:

with open(mi_file) as fp

where mi_file is holding the file name.

The error I am getting is:

Traceback (most recent call last):
  File "C:/Users/swapn/PycharmProjects/StepRecorderAutomation/mhtml_parsing.py", line 40, in <module>
    with open(mi_file) as fp:
FileNotFoundError: [Errno 2] No such file or directory: 'Recording_20200528_1557.mht'

Could someone please help me to find what am I doing wrong here?


问:
Eclipse has been too lagging when handle copy/paste or typing
When I copy/paste by Ctrl+C/Ctrl+V or typing code, my eclipse quite delay 3-4s to handle. Sometimes, it caused that my CPU has loaded 100%. I really need adivices for this issue.</p>

答:
it's maybe be a bit late for OP but i've experienced same behavior when using CTRL+C/CTRL+V (and CTRL+Space)

i've seen that ctlr may be used to perform hyperlinking. Then i mapped the hyperlinking modifier key to ALT (General-> Editors-> Text Editors -> Hyperlinking) and eclipse is not lagging anymore when i try using CTRL+C/CTRL+V


问:
Python - Threading, Timing, or function use?
I am having an issue formulating an idea on how to work this problem. Please help.

My project consists of an N x N grid with a series of blocks that are supposed to move in a random direction and random velocity within this grid (every .1 seconds, the location of the block is updated with the velocity). I have three "special" blocks that are expected to have individual movement functions. I will have other blocks (many of them) doing nothing but updating their location, and making sure they remain in the grid.

Now these three blocks have functions beyond movement, but each of these runs individually, waiting for the other block's special function to finish (block 2 will wait on block 1, Block 3 will wait on 2 and set it back to block 1, etc.) This queue of sorts will be running while the motion is happening. I want the motion to never stop. After each block's non-movement function runs n times, the code finishes.

My question is this: should I use threads to start and stop the non-movement functions, or is there a way to just set a time and set booleans that could use a class function after .1 seconds to continuously move the objects (and obviously loop over and over), and then use counts to end the program all together? If so, how would you write main function for this in Python? For all of this happening, does anyone think that Java would be significantly faster than Python in running this, especially if writing the data to a .txt file?

答:
If you put the calls to the special functions together in a single function, you get coordination (2) for free.

```<code>def run(n, blocks):
    for i in range(n):
        for b in blocks:
            b.special()
</code>```

As for the speed of Python versus Java, it depends on many things, such as the exact implementation. There is too little information to say.

ContentLicense: CC BY-SA 3.0

Body:
If you put the calls to the special functions together in a single function, you get coordination (2) for free.

def run(n, blocks):
    for i in range(n):
        for b in blocks:
            b.special()

As for the speed of Python versus Java, it depends on many things, such as the exact implementation. There is too little information to say.


问:
How to debug "precondition failure" in Xcode?
I'm building a SwiftUI App on Xcode 11 but is terminating immediately whenever I switch to a particular tab in the app.

Thing is, it always points to the Application Delegate file, which I think is not really the problem. I'm also getting this error in the console precondition failure: invalid input index: 2 and that's it, no more additional details on what file, array, or function this error is coming from.

Is there any way in Xcode to isolate which is causing this problem?

答:
I've run into this as well. I just want to share it in case someone finds it useful.

SHORT ANSWER

Wrapping my view into a NavigationView would raise the error. Using .navigationViewStyle(StackNavigationViewStyle()) solved my problem.

LONG ANSWER

I had something like this:

```<code>NavigationView {
    GeometryReader { proxy in
        VStack {
            Text("Dummy")
            Spacer()
            MyView()    // CONTAINS HAS A GEOMETRY READER TOO
                .frame(width: min(proxy.size.width, proxy.size.height),
                       height: min(proxy.size.width, proxy.size.height))
            Spacer()
            Text("Dummy")
        }
    }
}
</code>```

And then, MyView had a GeometryReader inside too. The code as described would fail. If NavigationView was removed, the precondition failure wouldn't happen.

I used .navigationViewStyle(StackNavigationViewStyle()) on NavigationView and that solved my issue.

Body:
I've run into this as well. I just want to share it in case someone finds it useful.

SHORT ANSWER

Wrapping my view into a NavigationView would raise the error. Using .navigationViewStyle(StackNavigationViewStyle()) solved my problem.

LONG ANSWER

I had something like this:

NavigationView {
    GeometryReader { proxy in
        VStack {
            Text("Dummy")
            Spacer()
            MyView()    // CONTAINS HAS A GEOMETRY READER TOO
                .frame(width: min(proxy.size.width, proxy.size.height),
                       height: min(proxy.size.width, proxy.size.height))
            Spacer()
            Text("Dummy")
        }
    }
}

And then, MyView had a GeometryReader inside too. The code as described would fail. If NavigationView was removed, the precondition failure wouldn't happen.

I used .navigationViewStyle(StackNavigationViewStyle()) on NavigationView and that solved my issue.


问:
Django Ckeditor and Youtube plugin not working
9 in my blog app and i'm trying to configure Youtube plugin for this i've tried to use many different tutorials on YT and similar solutrions from here and nothing wokred maybe there is another way to paste YT movie into my blog post?

settings.py

```<code>CKEDITOR_CONFIGS = {
'default': {
    'toolbar': 'Custom',
    'width': 'auto',
    'toolbar_Custom': [
        ['Bold','Italic','Underline','Link']
    ],
},
'special': {
    'toolbar': 'Special',
    'width': 'auto',
    'toolbar_Special': [
      ['Image','CodeSnippet', 'Youtube']
    ],
    'extraPlugins': ','.join(['codesnippet','youtube'])
}
}

STATIC_URL = '/static/'
STATIC_ROOT = '/static/'
</code>```

models.py

```<code>class Post(models.Model):
title = models.CharField(max_length=100)
content = RichTextUploadingField(null=True)
contentmedia = RichTextUploadingField(null=True,
                                      config_name='special',
                                      blank=True,
                                      external_plugin_resources=
                                      [('youtube', '/static/ckeditor/ckeditor/plugins/youtube/youtube/', 'plugin.js')], )
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('post-detail', kwargs={'pk': self.pk})
</code>```

config.js

```<code>CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
config.width = "auto";
config.display = "block";
config.extraPlugins = 'youtube';

};
</code>```

答:
Django can't view your static files that contain the plugin itself. In settings.py comment the line with STATIC_ROOT ( uncomment it when you need to register it in the collectstatic console ) and add the lines:
STATIC_DIR= os. path.join(BASE_DIR,'static')
STATICFILES_DIRS=[STATIC_DIR]</p>

Body:
9 in my blog app and i'm trying to configure Youtube plugin for this i've tried to use many different tutorials on YT and similar solutrions from here and nothing wokred maybe there is another way to paste YT movie into my blog post?

settings.py

CKEDITOR_CONFIGS = {
'default': {
    'toolbar': 'Custom',
    'width': 'auto',
    'toolbar_Custom': [
        ['Bold','Italic','Underline','Link']
    ],
},
'special': {
    'toolbar': 'Special',
    'width': 'auto',
    'toolbar_Special': [
      ['Image','CodeSnippet', 'Youtube']
    ],
    'extraPlugins': ','.join(['codesnippet','youtube'])
}
}

STATIC_URL = '/static/'
STATIC_ROOT = '/static/'

models.py

class Post(models.Model):
title = models.CharField(max_length=100)
content = RichTextUploadingField(null=True)
contentmedia = RichTextUploadingField(null=True,
                                      config_name='special',
                                      blank=True,
                                      external_plugin_resources=
                                      [('youtube', '/static/ckeditor/ckeditor/plugins/youtube/youtube/', 'plugin.js')], )
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)

def __str__(self):
    return self.title

def get_absolute_url(self):
    return reverse('post-detail', kwargs={'pk': self.pk})

config.js

CKEDITOR.editorConfig = function( config ) {
// Define changes to default configuration here. For example:
// config.language = 'fr';
// config.uiColor = '#AADC6E';
config.width = "auto";
config.display = "block";
config.extraPlugins = 'youtube';

};


问:
Display date of a given weekday based on CalendarWeek
I am working on a power app that would be somekind of a weekly  TimeSheet, let`s say.

Each row is a project and each column is a day/date from the week.
The user will be able to choose a calendar week.
Based on the chosen calendar week each column should change it`s header to the dates in this week.
e.g If CW 1 2020 => First column should change to 30.12.2019, second column to 31.12.2019, etc.

Basically what I need is formula that will get the CW and the weekday num (e.g CW 1, weekday 1) and calculate the date.

Thank you!

答:
Week Number

```<code>RoundDown((RoundUp(selec.SelectedDate-Date(Year(selec.SelectedDate-Weekday(selec.SelectedDate-1)+4);1;3);0)+
Weekday(Date(Year(selec.SelectedDate-Weekday(selec.SelectedDate-1)+4);1;3))+5)
/7;0)
</code>```

Weekday

```<code>Weekday( Now() )
</code>```

Body:
Week Number

RoundDown((RoundUp(selec.SelectedDate-Date(Year(selec.SelectedDate-Weekday(selec.SelectedDate-1)+4);1;3);0)+
Weekday(Date(Year(selec.SelectedDate-Weekday(selec.SelectedDate-1)+4);1;3))+5)
/7;0)

Weekday

Weekday( Now() )


问:
Tkinter and Python3 - How Can I justify a multiple lines text in a label widget?
I have a text composed by multiple lines in a ttk label. by default the text is displayed from the left border to right one without any kind of "justify" option. my goal is spread the text on all the label. I don't want to align the text on the right, on the left, on the center, etc.. I want to justify it, exatly when you justify a text in Microsoft Word. how can I reach my goal? </p>

答:
You can use the tkinter.ScrolledText module:

```<code>from tkinter import *
from tkinter.scrolledtext import *

win = Tk()

TEXT="""I have a text composed by multiple lines in a ttk label.
by default the text is displayed from the left border to right one without any kind of "justify" option.
My goal is spread the text on all the label. I don't want to align the text on the right, on the left, on the center, etc..
I want to justify it, exatly when you justify a text in Microsoft Word. how can I reach my goal?"""

text = ScrolledText(win, width=80, height=41, wrap=WORD) # create text zone
text.pack(expand=True, fill=BOTH) # pack it in the entire window
text.insert(1.0, TEXT)

win.mainloop()
</code>```

With adding tkinter.filedialog, you can make a real Notepad !

The Python IDLE was actually made like that.

Body:
You can use the tkinter.ScrolledText module:

from tkinter import *
from tkinter.scrolledtext import *

win = Tk()

TEXT="""I have a text composed by multiple lines in a ttk label.
by default the text is displayed from the left border to right one without any kind of "justify" option.
My goal is spread the text on all the label. I don't want to align the text on the right, on the left, on the center, etc..
I want to justify it, exatly when you justify a text in Microsoft Word. how can I reach my goal?"""

text = ScrolledText(win, width=80, height=41, wrap=WORD) # create text zone
text.pack(expand=True, fill=BOTH) # pack it in the entire window
text.insert(1.0, TEXT)

win.mainloop()

With adding tkinter.filedialog, you can make a real Notepad !

The Python IDLE was actually made like that.


问:
how to filter an object with RegExp and return a new object
I have an object:

```<code>object1 = {
dEabc: 1,
dEasdf: 2,
dEjfhs: 5,
bhsn: 7,
oki: 9
}

</code>```

My goal is to get a new object which contains only the keys with "dE", that means:

```<code>object1 = {
dEabc: 1,
dEasdf: 2,
dEjfhs: 5,
}
</code>```

is the object that I expected.

What I have tried is,
firstly I got all key from this object with

```<code>Object.keys(object);
</code>```

and then I used a RegExp to check if properties in the object with relevant keys.
if not I use

```<code>delete object[key];
</code>```

Any solutions?

答:
var obj= {
dEabc: 1,
dEasdf: 2,
dEjfhs: 5,
bhsn: 7,
oki: 9
}
let aa = Object.keys(obj).reduce((acc,ele)=>{return (ele.indexOf('dE') != -1) ? {...acc,...{[ele]:obj[ele]}} : acc},{});
console.log(aa); ```

Body:
I have an object:

object1 = {
dEabc: 1,
dEasdf: 2,
dEjfhs: 5,
bhsn: 7,
oki: 9
}

My goal is to get a new object which contains only the keys with "dE", that means:

object1 = {
dEabc: 1,
dEasdf: 2,
dEjfhs: 5,
}

is the object that I expected.

What I have tried is,
firstly I got all key from this object with

Object.keys(object);

and then I used a RegExp to check if properties in the object with relevant keys.
if not I use

delete object[key];

Any solutions?


问:
Pandas masking a specific column by date
I have a dataframe (df) with 2 main columns--one called 'TIMESTAMP' representing dates, and one called 'QC' reflecting quality control flags as ints. This df has about 40,000 rows so I do not want to iterate over each one.

I have a new dataframe (dfNew) with just two columns of several start and end date pairs. I want to go through my original df and for all rows where the TIMESTAMP falls in between any of the start-end date pairs listed in dfNew, I want to replace the QC value with -1. This dfNew has about 400 rows so I figured iterating here would not be too bad.

The df looks something like this:

```<code>TIMESTAMP       | QC
2019-05-04 00:22    5
2019-05-04 00:24    1
2019-05-09 03:30    3
</code>```

the dfNew looks something like this:

```<code>START         | END
20190504_0023   20190504_0024
</code>```

So I would want to replace QC=1 for the second row in df with QC=-1.

This is my code so far:

```<code>for index, row in dfNew.iterrows():
    df['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP'])
    start = datetime.datetime.strptime(row[0], "%Y%m%d_%H%M")
    end = datetime.datetime.strptime(row[1], "%Y%m%d_%H%M")
    masked = (df['TIMESTAMP'] >= start) & (df['TIMESTAMP'] <= end)
    df['QC'].mask(masked, -1)
</code>```

However for some reason, the mask is not working. No values get replaced with -1. I think it may have something to with the fact that I'm creating the mask using the TIMESTAMP column but trying to use that mask to replace values in the QC columns, but I cannot figure out what it is. Any thoughts would be appreciated!

答:
Boolean select

```<code>m=df.QC==1
</code>```

Use .loc accessor

```<code>df.loc[m,'QC']=-1
</code>```

Body:
I have a dataframe (df) with 2 main columns--one called 'TIMESTAMP' representing dates, and one called 'QC' reflecting quality control flags as ints. This df has about 40,000 rows so I do not want to iterate over each one.

I have a new dataframe (dfNew) with just two columns of several start and end date pairs. I want to go through my original df and for all rows where the TIMESTAMP falls in between any of the start-end date pairs listed in dfNew, I want to replace the QC value with -1. This dfNew has about 400 rows so I figured iterating here would not be too bad.

The df looks something like this:

TIMESTAMP       | QC
2019-05-04 00:22    5
2019-05-04 00:24    1
2019-05-09 03:30    3

the dfNew looks something like this:

START         | END
20190504_0023   20190504_0024

So I would want to replace QC=1 for the second row in df with QC=-1.

This is my code so far:

for index, row in dfNew.iterrows():
    df['TIMESTAMP'] = pd.to_datetime(df['TIMESTAMP'])
    start = datetime.datetime.strptime(row[0], "%Y%m%d_%H%M")
    end = datetime.datetime.strptime(row[1], "%Y%m%d_%H%M")
    masked = (df['TIMESTAMP'] >= start) & (df['TIMESTAMP'] <= end)
    df['QC'].mask(masked, -1)

However for some reason, the mask is not working. No values get replaced with -1. I think it may have something to with the fact that I'm creating the mask using the TIMESTAMP column but trying to use that mask to replace values in the QC columns, but I cannot figure out what it is. Any thoughts would be appreciated!

Body:
Boolean select

m=df.QC==1

Use .loc accessor

df.loc[m,'QC']=-1


问:
Making RSVG properly display text with a fractional size
I'm using librsvg 2.39.0 to render the following SVG file to PNG. Inkscape and Firefox render it without any issues:

```<code><?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="200" viewBox="0 0 20 10" version="1.1">
  <rect width="100%" height="100%" fill="#ffffff" />
  <text style="font-family: Helvetica;" stroke="none" x="7" y="5" font-size="1.6" fill="black">
    This is some text
  </text>
</svg>
</code>```

However, it looks like, with librsvg, the text characters get aligned to the user coordinate grid, and the kerning is completely broken:

The issue can be replicated in the console by installing the librsvg2-tools package and running rsvg-convert < input.svg > output.png.

Is there something wrong with the file? The W3C validator shows it as valid. How do I teach librsvg to accept a fractional font-size in user coordinates?

答: This works fine now with rsvg-convert 2.40.20</p>

Body:
I'm using librsvg 2.39.0 to render the following SVG file to PNG. Inkscape and Firefox render it without any issues:

<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" width="400" height="200" viewBox="0 0 20 10" version="1.1">
  <rect width="100%" height="100%" fill="#ffffff" />
  <text style="font-family: Helvetica;" stroke="none" x="7" y="5" font-size="1.6" fill="black">
    This is some text
  </text>
</svg>

However, it looks like, with librsvg, the text characters get aligned to the user coordinate grid, and the kerning is completely broken:

The issue can be replicated in the console by installing the librsvg2-tools package and running rsvg-convert < input.svg > output.png.

Is there something wrong with the file? The W3C validator shows it as valid. How do I teach librsvg to accept a fractional font-size in user coordinates?


问:
Android Studio debugger crashes/stops on breakpoint, when debugging on my Huawei phone
After the debugger reaches the breakpoint, the app process stops and after a little time (2-3 seconds) the debugger disconnect itself. But only if i debug with my Huawei phone (EMUI 10).

These are the last 3 lines from the log:

D/: [ZeroHung]zrhung_send_event: wp = 257, ret = 0

  D/:[ZeroHung]zrhung_send_event: wp = 258, ret = 0

  Disconnected from the target VM, address: 'localhost:8629', transport: 'socket'

If I debug the same app with the same breakpoint on an emulator, everything works fine. The debugger stops at the breakpoint, and doesn´t disconnect itself.

答:
How did you build this project? If you build it with ant or other tools, make sure to compile with debugging information enabled (debug = true for ant javac tasks). Obfuscation and bytecode detection during construction can also affect the possibility of debugging. If you run it in some non-standard JVM, it can also cause such problems
When performing remote debugging, make sure to start the target process using the correct JVM options recommended in the IntelliJ idea remote debugging configuration. Your wrapper configuration may pass them incorrectly</p>


问:
Warning: Instance created by `useForm` is not connect to any Form element
I have an application where built a form and i want to setDefaultValue for the form.
I used: const [form] = Form.useForm();. My form tag looks like bellow:

```<code><Form form={form} name="basic" onFinish={onFinish} onFinishFailed={onFinishFailed}>
</code>```

And i try to set defaultValue:

```<code>form.setFieldsValue({
  name: object.name,
});
</code>```

Here i get the next warning: Warning: Instance created by `useForm` is not connect to any Form element. Forget to pass `form` prop?

I saw many answers with this topic, but they solved the issue by adding form={form}. In my case it doesn't work. What could be the issue?

答:
If you are using Form component inside Modal component, pls remind set getContainer={false} to Modal component.

Here is the link: https://ant.design/components/modal/

Body:
I have an application where built a form and i want to setDefaultValue for the form.
I used: const [form] = Form.useForm();. My form tag looks like bellow:

<Form form={form} name="basic" onFinish={onFinish} onFinishFailed={onFinishFailed}>

And i try to set defaultValue:

form.setFieldsValue({
  name: object.name,
});

Here i get the next warning: Warning: Instance created by `useForm` is not connect to any Form element. Forget to pass `form` prop?

I saw many answers with this topic, but they solved the issue by adding form={form}. In my case it doesn't work. What could be the issue?


问:
Triggering :hover on second element when hovering on first using pure CSS
I have two elements and I'd like to trigger the hover of second element when the first element is hovered over.

Example:

#element1 {
  border: 1px solid rgba(80,80,80, .5);
}

#element2 {
  margin-top: 10px;
  padding-top: 10px;
  border: 1px solid rgba(80,80,80, .5);
}

/* suggested proposal */
#element1:hover >> #element2:hover {
   font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="element1">
  Hover over this element for more info
</div>

<div id="element2">
   Here is more info
</div></code>```

I'd like to know if it's possible yet OR if there any plans for this in CSS specification. If there's no proposals I can suggest something like #myElementId:hover >> #mySecondElementID:hover.

There are a few related questions to this but acknowledges that it is not possible and with the new follow feature people can follow for any updates.

Related Questions:

Triggering :hover on second element when hovering on first

Do not close. This is not the same as the other questions. It is asking about current status, future specification and gives a place to answer.

UPDATE:

It looks like I can select any element as the second element as long as it's sibling or a descendant of the first element.

Reference to combinators:

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

Update: The question is specifically about selecting a second element any where on the page. The current answers will work as long as the mentioned conditions are met.

答:
Use the adjacent sibling combinator(+).

#element1 {
  border: 1px solid rgba(80,80,80, .5);
}

#element2 {
  margin-top: 10px;
  padding-top: 10px;
  border: 1px solid rgba(80,80,80, .5);
}

#element1:hover + #element2{
   font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="element1">
  Hover over this element for more info
</div>

<div id="element2">
   Here is more info
</div></code>```

To effect both elements on hover...

#element1 {
  border: 1px solid rgba(80,80,80, .5);
}

#element2 {
  margin-top: 10px;
  padding-top: 10px;
  border: 1px solid rgba(80,80,80, .5);
}

#element1:hover,
#element1:hover + #element2{
   font-weight: bold;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="element1">
  Hover over this element for more info
</div>

<div id="element2">
   Here is more info
</div></code>```

Body:
I have two elements and I'd like to trigger the hover of second element when the first element is hovered over.

Example:

#element1 {
  border: 1px solid rgba(80,80,80, .5);
}

#element2 {
  margin-top: 10px;
  padding-top: 10px;
  border: 1px solid rgba(80,80,80, .5);
}

/* suggested proposal */
#element1:hover >> #element2:hover {
   font-weight: bold;
}

  Hover over this element for more info

   Here is more info

I'd like to know if it's possible yet OR if there any plans for this in CSS specification. If there's no proposals I can suggest something like #myElementId:hover >> #mySecondElementID:hover.

There are a few related questions to this but acknowledges that it is not possible and with the new follow feature people can follow for any updates.

Related Questions:

Triggering :hover on second element when hovering on first

Do not close. This is not the same as the other questions. It is asking about current status, future specification and gives a place to answer.

UPDATE:

It looks like I can select any element as the second element as long as it's sibling or a descendant of the first element.

Reference to combinators:

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

Update: The question is specifically about selecting a second element any where on the page. The current answers will work as long as the mentioned conditions are met.

Body:
Use the adjacent sibling combinator(+).

#element1 {
  border: 1px solid rgba(80,80,80, .5);
}

#element2 {
  margin-top: 10px;
  padding-top: 10px;
  border: 1px solid rgba(80,80,80, .5);
}

#element1:hover + #element2{
   font-weight: bold;
}

<div id="element1">
  Hover over this element for more info
</div>

<div id="element2">
   Here is more info
</div>

To effect both elements on hover...

#element1 {
  border: 1px solid rgba(80,80,80, .5);
}

#element2 {
  margin-top: 10px;
  padding-top: 10px;
  border: 1px solid rgba(80,80,80, .5);
}

#element1:hover,
#element1:hover + #element2{
   font-weight: bold;
}

<div id="element1">
  Hover over this element for more info
</div>

<div id="element2">
   Here is more info
</div>


问:
why WSO2 ID token returns 'groups' attributes as a comma seperated role string instead of list of role
I've two WSO2 IS 5.7.0 environments. The id tokens returned by https://localhost:9443/oauth2/token have slight difference. the first environment: the 'groups' attribute has values like the following:

```<code>"groups": [
    "FOTA_WEB_View_User",
    "FOTA_Engineer",
    "FOTA_Manager",
    "FOTA_WEB_Admin",
    "Internal/everyone",
    "_login",
    "FOTA_APP"
  ]
</code>```

but in the second environment, the 'groups' attribute has values like the following：

```<code>"groups": "BDA-AA-Flameout-Download,BDA-Diag-TempSensor-Download,BDA_Admin,BDA-AA-Superknock-Download,Internal/everyone,_login,BDA-AA-Flameout-View,BDA-AA-Superknock-View"
</code>```

Actually, the first is expected.

The configration seems the same, i.e. add a new service provider, and then add
Requested Claims. see below pictures.

答: A possible way to happen this is not configuring the MultiAttributeSeparator property in user-mgt.xml (/repository/conf/user-mgt.xml) file. This property is available in all UserStoreManager classes. In this case we need to set the value for the MultiAttributeSeparator property to comma (,) in the JDBCUserStoreManager properties since the user store is a JDBC database (MYSQL).

Body:
I've two WSO2 IS 5.7.0 environments. The id tokens returned by https://localhost:9443/oauth2/token have slight difference. the first environment: the 'groups' attribute has values like the following:

"groups": [
    "FOTA_WEB_View_User",
    "FOTA_Engineer",
    "FOTA_Manager",
    "FOTA_WEB_Admin",
    "Internal/everyone",
    "_login",
    "FOTA_APP"
  ]

but in the second environment, the 'groups' attribute has values like the following：

"groups": "BDA-AA-Flameout-Download,BDA-Diag-TempSensor-Download,BDA_Admin,BDA-AA-Superknock-Download,Internal/everyone,_login,BDA-AA-Flameout-View,BDA-AA-Superknock-View"

Actually, the first is expected.

The configration seems the same, i.e. add a new service provider, and then add
Requested Claims. see below pictures.


问:
MahApps.Metro IOException: Cannot locate resource 'styles/colors.xaml'
I've been using MahApps.Metro from NuGet for a while without any issues. However, recently I had a few issues with NuGet packages needing to be reinstalled.

In the end, I uninstalled all of the NuGet packages I needed and reinstalled them. As far as I can tell, everything works correctly now except that when I try to start the application, it immediately throws the above exception:

```<code>System.Windows.Markup.XamlParseException: ''Set property 'System.Windows.ResourceDictionary.Source' threw an exception.' Line number '34' and line position '18'.'

Inner Exception
IOException: Cannot locate resource 'styles/colors.xaml'.
</code>```

And if I check those specified lines, it is this <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />.

My App.xaml looks like this:

<Application.Resources>
    <ResourceDictionary>

        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />

        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
```

I have tried various things from other similar questions:

Changing "Colors" to "Colours"

Changing "Colors" to "colors"

Changing "Colors to "colours"

Restore NuGet packages

Uninstalled/reinstalled package

Tried x86, x64 and AnyCPU target platforms

Endless number of clean/rebuild solution with closing VS2017 inbetween

Checked StartupUri is correct

Ensured Assembly name and Default namespace are different (and have always been)

I'm completely at a loss as to what try next...

答: The one thing I hadn't tried was using an older version... And yep version 2.0.0 of MahApps.Metro changed how themes were done. Using version 1.6.5 fixes the issue or you need to follow the migration guide here: https://mahapps.com/docs/guides/migration-to-v2.0</p>

Body:
I've been using MahApps.Metro from NuGet for a while without any issues. However, recently I had a few issues with NuGet packages needing to be reinstalled.

In the end, I uninstalled all of the NuGet packages I needed and reinstalled them. As far as I can tell, everything works correctly now except that when I try to start the application, it immediately throws the above exception:

System.Windows.Markup.XamlParseException: ''Set property 'System.Windows.ResourceDictionary.Source' threw an exception.' Line number '34' and line position '18'.'

Inner Exception
IOException: Cannot locate resource 'styles/colors.xaml'.

And if I check those specified lines, it is this <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />.

My App.xaml looks like this:

<Application.Resources>
    <ResourceDictionary>

        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Controls.xaml" />
            <ResourceDictionary Source="pack://application:,,,/MahApps.Metro;component/Styles/Colors.xaml" />

        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

I have tried various things from other similar questions:

Changing "Colors" to "Colours"

Changing "Colors" to "colors"

Changing "Colors to "colours"

Restore NuGet packages

Uninstalled/reinstalled package

Tried x86, x64 and AnyCPU target platforms

Endless number of clean/rebuild solution with closing VS2017 inbetween

Checked StartupUri is correct

Ensured Assembly name and Default namespace are different (and have always been)

I'm completely at a loss as to what try next...


问:
React TypeScript error for size attribute of html input element
I am using create-react-app with the TypeScript template. When I write the following JSX/TSX code snippet

```<code>function MyInputFieldComponent() {
    return (
        <input type="text" size="100" placeholder="Full Name"/>
    );
}
</code>```

I get the following compiler error:

(JSX attribute) React.InputHTMLAttributes.size?:
  number | undefined

Type 'string' is not assignable to type 'number |
  undefined'.ts(2322)

index.d.ts(2094, 9): The expected type comes from
  property 'size' which is declared here on type
  'DetailedHTMLProps,
  HTMLInputElement>'

What is wrong here? Shouldn't I be able to set the html attribute "size" like any other attribute?

答:
```<code>function MyInputFieldComponent() {
    return (
        <input type="text" size={100} placeholder="Full Name"/>
    );
}
</code>```

Body:
I am using create-react-app with the TypeScript template. When I write the following JSX/TSX code snippet

function MyInputFieldComponent() {
    return (
        <input type="text" size="100" placeholder="Full Name"/>
    );
}

I get the following compiler error:

(JSX attribute) React.InputHTMLAttributes.size?:
  number | undefined

Type 'string' is not assignable to type 'number |
  undefined'.ts(2322)

index.d.ts(2094, 9): The expected type comes from
  property 'size' which is declared here on type
  'DetailedHTMLProps,
  HTMLInputElement>'

What is wrong here? Shouldn't I be able to set the html attribute "size" like any other attribute?


问:
How to have the main form listen out for a button click in a control
The app I am building kind of functions a bit like a website in that I have a main content area and a load of buttons along the side which then displays different content in the main content area.

The main content area I have is made up of a blank panel (pnlMainContent) which is then populated with a User Control when a button/tab is clicked.

The first User Control I have put in includes another button which should then populate the main content Panel with a different User Control.

How do I get the main form to listen out for the button click within the User Control so I can then clear the panel and populate it with another User Control?

As it stands, I can't see pnlMainContent from within the User Control.

答:
Inside your UserControl you need to create a custom event.  This is triggered when you perform your action in the user control.
Then the main form subscribes to this and is informed every time this action occurs.

Your user control

```<code>//Declare a delegate and Event.  Here called StatusUpdate
public delegate void StatusUpdateHandler(object sender, EventArgs e);
public event StatusUpdateHandler OnUpdateStatus;

//When button is clicked, this is trigged
private void Button1_Click(object sender, EventArgs e)
{
    //In here, you now trigger your custom event
    UpdateStatus();
}

private void UpdateStatus()
{
     //Create arguments.  You should also have custom one, or else return EventArgs.Empty();
     EventArgs args = new EventArgs();

     //Call any listeners
     OnUpdateStatus?.Invoke(this, args);

}
</code>```

Then in your main form subscribe to this event

```<code>yourUserControl.OnUpdateStatus += customControl_OnUpdateStatus;
...

private void customControl_OnUpdateStatus(object sender, EventArgs e)
{
     ///Handle your event here
}
</code>```

Body:
Inside your UserControl you need to create a custom event.  This is triggered when you perform your action in the user control.
Then the main form subscribes to this and is informed every time this action occurs.

Your user control

//Declare a delegate and Event.  Here called StatusUpdate
public delegate void StatusUpdateHandler(object sender, EventArgs e);
public event StatusUpdateHandler OnUpdateStatus;

//When button is clicked, this is trigged
private void Button1_Click(object sender, EventArgs e)
{
    //In here, you now trigger your custom event
    UpdateStatus();
}

private void UpdateStatus()
{
     //Create arguments.  You should also have custom one, or else return EventArgs.Empty();
     EventArgs args = new EventArgs();

     //Call any listeners
     OnUpdateStatus?.Invoke(this, args);

}

Then in your main form subscribe to this event

yourUserControl.OnUpdateStatus += customControl_OnUpdateStatus;
...

private void customControl_OnUpdateStatus(object sender, EventArgs e)
{
     ///Handle your event here
}


问:
Images/Sprites question in Cocos2d
Okay, so I have a background image of a desert for my app, it is in the .gif format, and is @2x. I have it scaled down like so:

```<code>background.scale = 0.5;
</code>```

and it appears fine. I have another image for a health bar that is in .png format, and is also @2x. I also have it scaled down like above. But the health bar is WAY pixelated on the edges, and the desert's edges are not AS pixelated, but WAY better. I've tried changing the health bar's format to .gif, that didn't do anything. And note: When I view the images in Preview/Xcode, they look just fine! Am I missing something? I use Inkscape, if that helps. Any help is appreciated. Thanks!

答: Generally, scaling in cocos2d is not recommended as it is low quality (as you observe) and it becomes a performance bottleneck (or it used to be, I don't know this could have changed). Why don't you just pre-scale the images to the exact dimensions you want and display them without scaling? If this is for a universal app, just pre-scale the images to each intended resolution and load them depending on the screen scale/size.</p>

Title: Images/Sprites question in Cocos2d

Body:
Okay, so I have a background image of a desert for my app, it is in the .gif format, and is @2x. I have it scaled down like so:

background.scale = 0.5;

and it appears fine. I have another image for a health bar that is in .png format, and is also @2x. I also have it scaled down like above. But the health bar is WAY pixelated on the edges, and the desert's edges are not AS pixelated, but WAY better. I've tried changing the health bar's format to .gif, that didn't do anything. And note: When I view the images in Preview/Xcode, they look just fine! Am I missing something? I use Inkscape, if that helps. Any help is appreciated. Thanks!


问:
KeyError pandas dataframe
The purpose of this script is to read a csv file then create a data frame out of it.

The file contains forex historical data.

The file has 7 columns Date, Time, Open, High, Low, Close and Volume, and around 600k rows.

Here is a data sample:

```<code>                        Open     High      Low    Close  Volume
Release Date
2020-02-05 01:50:00  109.450  109.452  109.449  109.451      79
2020-02-05 01:51:00  109.451  109.451  109.449  109.450      26
2020-02-05 01:52:00  109.451  109.453  109.449  109.449      29
2020-02-05 01:53:00  109.449  109.449  109.440  109.442      35
2020-02-05 01:54:00  109.443  109.443  109.432  109.432      49
2020-02-05 01:55:00  109.432  109.439  109.432  109.438      19
2020-02-05 01:56:00  109.439  109.450  109.439  109.449      56
2020-02-05 01:57:00  109.449  109.450  109.446  109.446      20
2020-02-05 01:58:00  109.446  109.451  109.446  109.448      33
2020-02-05 01:59:00  109.449  109.454  109.443  109.443      75
</code>```

After scraping the date and time the script must make some date time calculation like month and day.

Then, some technical analysis using TA-LIB library.

With every new step the code produces a dataframe.

All the new dataframes will be stored in a list.

The last step is to concatenate all these dataframes into one final dataframe.

Here is the code:

```<code>import pandas as pd
import talib

class Data:
    def __init__(self):
        self.dfs = []
        self.names = ['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']
        self.df = pd.DataFrame()
        self.Close = self.df['Close'].astype(float)

    def file(self, file):
        self.df = pd.read_csv(file, names=self.names,
                              parse_dates={'Release Date': ['Date', 'Time']})
        return self.dfs.append(self.df)

    def year(self):
        self.df['year'] = self.df['Release Date'].dt.year
        return self.dfs.append(self.df['year'])

    def month(self):
        self.df['month'] = self.df['Release Date'].dt.month
        return self.dfs.append(self.df['month'])

    def week(self):
        self.df['week'] = self.df['Release Date'].dt.week
        return self.dfs.append(self.df['week'])

    def day(self):
        self.df['day'] = self.df['Release Date'].dt.day
        return self.dfs.append(self.df['day'])

    def hour(self):
        self.df['hour'] = self.df['Release Date'].dt.hour
        return self.dfs.append(self.df['hour'])

    def minute(self):
        self.df['minute'] = self.df['Release Date'].dt.minute
        return self.dfs.append(self.df['minute'])

    def dema(self):
        self.df['DEMA'] = talib.DEMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['dema'])

    def ema(self):
        self.df['EMA'] = talib.EMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['ema'])

    def KAMA(self):
        self.df['KAMA'] = talib.KAMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['KAMA'])

    def ma(self):
        self.df['MA'] = talib.MA(self.Close, timeperiod=30, matype=0)
        return self.dfs.append(self.df['ma'])

    def action(self):
        self.year()
        self.month()
        self.week()
        self.day()
        self.hour()
        self.minute()
        self.dema()
        self.ema()
        self.KAMA()
        self.ma()

    def print(self):
        self.action()
        print(len(self.dfs))

x = Data()
x.file(r"D:\Projects\Project Forex\EURUSD.csv")
x.print()
</code>```

Here is the error:

```<code>Traceback (most recent call last):

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\core\indexes\base.py", line 2646, in get_loc
    return self._engine.get_loc(key)

  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'Close'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 74, in <module>
    x = Data()

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 10, in __init__
    self.Close = self.df['Close'].astype(float)

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\core\frame.py", line 2800, in __getitem__
    indexer = self.columns.get_loc(key)

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\core\indexes\base.py", line 2648, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))

  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'Close'
</code>```

答:
You have several problems that have been quickly mentioned by Serge in his comments.

You try to define self.Close as self.Close = self.df['Close'].astype(float)

but self.df is initialized as an empty dataframe so there is no column named 'Close'.

You then proceed to define:

```<code>    def dema(self):
        self.df['DEMA'] = talib.DEMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['dema'])

    def ema(self):
        self.df['EMA'] = talib.EMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['ema'])

    def ma(self):
        self.df['MA'] = talib.MA(self.Close, timeperiod=30, matype=0)
        return self.dfs.append(self.df['ma'])
</code>```

In these three cases you define a column using uppercase letters (e.g. 'MA')

But then try to append a column with a lowercase name (e.g. self.dfs.append(self.df['ma']))

Title: KeyError pandas dataframe

Body:
The purpose of this script is to read a csv file then create a data frame out of it.

The file contains forex historical data.

The file has 7 columns Date, Time, Open, High, Low, Close and Volume, and around 600k rows.

Here is a data sample:

                        Open     High      Low    Close  Volume
Release Date
2020-02-05 01:50:00  109.450  109.452  109.449  109.451      79
2020-02-05 01:51:00  109.451  109.451  109.449  109.450      26
2020-02-05 01:52:00  109.451  109.453  109.449  109.449      29
2020-02-05 01:53:00  109.449  109.449  109.440  109.442      35
2020-02-05 01:54:00  109.443  109.443  109.432  109.432      49
2020-02-05 01:55:00  109.432  109.439  109.432  109.438      19
2020-02-05 01:56:00  109.439  109.450  109.439  109.449      56
2020-02-05 01:57:00  109.449  109.450  109.446  109.446      20
2020-02-05 01:58:00  109.446  109.451  109.446  109.448      33
2020-02-05 01:59:00  109.449  109.454  109.443  109.443      75

After scraping the date and time the script must make some date time calculation like month and day.

Then, some technical analysis using TA-LIB library.

With every new step the code produces a dataframe.

All the new dataframes will be stored in a list.

The last step is to concatenate all these dataframes into one final dataframe.

Here is the code:

import pandas as pd
import talib

class Data:
    def __init__(self):
        self.dfs = []
        self.names = ['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']
        self.df = pd.DataFrame()
        self.Close = self.df['Close'].astype(float)

    def file(self, file):
        self.df = pd.read_csv(file, names=self.names,
                              parse_dates={'Release Date': ['Date', 'Time']})
        return self.dfs.append(self.df)

    def year(self):
        self.df['year'] = self.df['Release Date'].dt.year
        return self.dfs.append(self.df['year'])

    def month(self):
        self.df['month'] = self.df['Release Date'].dt.month
        return self.dfs.append(self.df['month'])

    def week(self):
        self.df['week'] = self.df['Release Date'].dt.week
        return self.dfs.append(self.df['week'])

    def day(self):
        self.df['day'] = self.df['Release Date'].dt.day
        return self.dfs.append(self.df['day'])

    def hour(self):
        self.df['hour'] = self.df['Release Date'].dt.hour
        return self.dfs.append(self.df['hour'])

    def minute(self):
        self.df['minute'] = self.df['Release Date'].dt.minute
        return self.dfs.append(self.df['minute'])

    def dema(self):
        self.df['DEMA'] = talib.DEMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['dema'])

    def ema(self):
        self.df['EMA'] = talib.EMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['ema'])

    def KAMA(self):
        self.df['KAMA'] = talib.KAMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['KAMA'])

    def ma(self):
        self.df['MA'] = talib.MA(self.Close, timeperiod=30, matype=0)
        return self.dfs.append(self.df['ma'])

    def action(self):
        self.year()
        self.month()
        self.week()
        self.day()
        self.hour()
        self.minute()
        self.dema()
        self.ema()
        self.KAMA()
        self.ma()

    def print(self):
        self.action()
        print(len(self.dfs))

x = Data()
x.file(r"D:\Projects\Project Forex\EURUSD.csv")
x.print()

Here is the error:

Traceback (most recent call last):

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\core\indexes\base.py", line 2646, in get_loc
    return self._engine.get_loc(key)

  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'Close'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 74, in <module>
    x = Data()

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 10, in __init__
    self.Close = self.df['Close'].astype(float)

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\core\frame.py", line 2800, in __getitem__
    indexer = self.columns.get_loc(key)

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\core\indexes\base.py", line 2648, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))

  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc

  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item

  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item

KeyError: 'Close'

Body:
You have several problems that have been quickly mentioned by Serge in his comments.

You try to define self.Close as self.Close = self.df['Close'].astype(float)

but self.df is initialized as an empty dataframe so there is no column named 'Close'.

You then proceed to define:

    def dema(self):
        self.df['DEMA'] = talib.DEMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['dema'])

    def ema(self):
        self.df['EMA'] = talib.EMA(self.Close, timeperiod=30)
        return self.dfs.append(self.df['ema'])

    def ma(self):
        self.df['MA'] = talib.MA(self.Close, timeperiod=30, matype=0)
        return self.dfs.append(self.df['ma'])

In these three cases you define a column using uppercase letters (e.g. 'MA')

But then try to append a column with a lowercase name (e.g. self.dfs.append(self.df['ma']))


问:
Wrong position of <video> element inside SVG foreignObject on Safari
I'm using <foreignObject> SVG element to embed a <video> element inside an SVG-based UI.

Everything is fine on all browsers but Safari, where the positioning of the video element is completely wrong respect to its <foreingObject> container.

I built a simple page to reproduce the issue, also available on Codepen:

  <svg viewBox='0 0 100 200' style='width: 200px; height: 400px; border: 1px solid black'>

    <foreignObject x='10' y='10' width='80' height='80'>

        bla bla bla

    </foreignObject>

    <foreignObject x='10' y='110' width='80' height='80'>

        <video xmlns='http://www.w3.org/1999/xhtml' width='100%' height='100%' playsinline autoplay src='https://file-examples.com/wp-content/uploads/2017/04/file_example_MP4_480_1_5MG.mp4'></video>

    </foreignObject>

  </svg>

```

Here there is the rendered page: on the left Chrome version, on the right the Safari one.

caniuse states that <foreignObject> is supported on Safari and actually the video element is displayed. But what's wrong with its positioning?

答:
Hard to believe, this is a bug in webkit. More hard to believe, this bug is open since ... 2009!!!

Having a look at comments on the bug page, it turns out that a possible workaround is to add position: fixed to the style of the div containing the video element.

Thanks to @Robert Longson for pointing me in the right direction.

Personal comment: I can't understand why caniuse declares foreignObject as supported on Safari when this bug is open for such a long time.

Body:
I'm using <foreignObject> SVG element to embed a <video> element inside an SVG-based UI.

Everything is fine on all browsers but Safari, where the positioning of the video element is completely wrong respect to its <foreingObject> container.

I built a simple page to reproduce the issue, also available on <a href="https://codepen.io/sertal70/pen/qBOLdNZ?__cf_chl_jschl_tk__=edf67f7539aa2af519989f94b66063f52f99da1e-1589902150-0-AXGuz9U9A1VyJN9RMYrS3O-bE77TWCtDZj8FWjPZ2suMaqzRmobTsSUmajyKdXhpehixtTozxYxSL1Hut0LcWLGTuZVS6hdSYKTS_SKTZLTYi_QE1dmrftTXQWjCobny_CET__5G--MOWBVDH0SaQf_E4WqkRikdE9UZZNg7nqfzwnu-Ds_8Mn9wL_jqf4MGw1p8Qs0PJ9185Q7EjMzdmnuCrgbZqV-jkbt4C0czhWxQddBHyJFPSp3JiNVOuDPDqsB9PvQoiBLvnYD8o7zgRJcKMNtSpV_phP8WIRuDvMq5QNbVmlBkyhB-8u-wz42cfT3xUdy5t46SoJ0_qeofD-hhnC3_GdyS7wu7aWHShVP8" rel="noreferrer">Codepen:

  <svg viewBox='0 0 100 200' style='width: 200px; height: 400px; border: 1px solid black'>

    <foreignObject x='10' y='10' width='80' height='80'>

        bla bla bla

    </foreignObject>

    <foreignObject x='10' y='110' width='80' height='80'>

        <video xmlns='http://www.w3.org/1999/xhtml' width='100%' height='100%' playsinline autoplay src='https://file-examples.com/wp-content/uploads/2017/04/file_example_MP4_480_1_5MG.mp4'></video>

    </foreignObject>

  </svg>

Here there is the rendered page: on the left Chrome version, on the right the Safari one.

caniuse states that <foreignObject> is supported on Safari and actually the video element is displayed. But what's wrong with its positioning?


问:
Rails DelayedJob run_at Time Zone discrepancy
I am using Rails Delayed Job to en queue jobs to run at a specific time. I am in IST TimeZone. Delayed Job run_at is also configured to use IST TimeZone.

Now I want to trigger a job at 5:00 pm IST. I am storing '05:00 pm' as a string in my table and parsing it before scheduling the job.

So,

```<code>Time.parse('05:00 pm')
</code>```

returns

```<code>2020-05-29 17:00:00 UTC
</code>```

If I parse using IST

```<code> Time.parse('05:00 pm').in_time_zone('Chennai')
 => Fri, 29 May 2020 22:30:00 IST +05:30
</code>```

But I want 05:00 pm to be parsed as

```<code>  2020-05-29 11:30:00 UTC
</code>```

so that my delayed job understands to run this job at 5:00 pm IST.

I can manually reduce 5:30 hours and enqueue but thats not the correct / optimized way I feel. Please suggest how can I do this?

答:
You can do something like
ActiveSupport::TimeZone.new('Chennai').parse("5 pm").utc

Or ideally you could store your time as "17:00:00 +0530", so it's clear you mean the time in IST. Then simply Time.parse("17:00:00 +0530").utc would work too.

Body:
I am using Rails Delayed Job to en queue jobs to run at a specific time. I am in IST TimeZone. Delayed Job run_at is also configured to use IST TimeZone.

Now I want to trigger a job at 5:00 pm IST. I am storing '05:00 pm' as a string in my table and parsing it before scheduling the job.

So,

Time.parse('05:00 pm')

returns

2020-05-29 17:00:00 UTC

If I parse using IST

 Time.parse('05:00 pm').in_time_zone('Chennai')
 => Fri, 29 May 2020 22:30:00 IST +05:30

But I want 05:00 pm to be parsed as

  2020-05-29 11:30:00 UTC

so that my delayed job understands to run this job at 5:00 pm IST.

I can manually reduce 5:30 hours and enqueue but thats not the correct / optimized way I feel. Please suggest how can I do this?


问:
OnBuffer props in react-native-video is not working
I am using react-native-video for playing videos from url. I am using onBuffer prop to show loader if the video is buffering. But in my case onBuffer is not working. If the video size is large then in case of a slow network or unstable network video is taking time to play, so I want to show loader if the video is not playing but in buffering mode. </p>

答:
I was doing this all stuff in my application on buffering state you can simply check the state on buffer and display loader like this. You have to use a combination of onLoadStart, onBuffer and onLoadEnd, Below is an example of how you can also build your custom loader and display while buffering.
If you don't want to use my loader or this animation stuff remove that thing and render your own loader.

```<code>    class VideoPlayer extends React.Component {
       constructor (props) {
       super(props)
       this.state = {
          paused: false,
          buffering: true,
          animated: new Animated.Value(0),
          progress: 0,
          duration: 0
    }
  }
  handleMainButtonTouch = () => {
    if (this.state.progress >= 1) {
      this.player.seek(0)
    }

    this.setState(state => {
      return {
        paused: !state.paused
      }
    })
  };
  handleProgressPress = e => {
    const position = e.nativeEvent.locationX
    const progress = (position / 250) * this.state.duration
    const isPlaying = !this.state.paused

    this.player.seek(progress)
  };

  handleProgress = progress => {
    this.setState({
      progress: progress.currentTime / this.state.duration
    })
  };
  onBuffer = ({isBuffering}) => {
    this.setState({ buffering: isBuffering })
    if (isBuffering) {
      this.triggerBufferAnimation()
    }
    if (this.loopingAnimation && isBuffering) {
      this.loopingAnimation.stopAnimation()
    }
  }
  onLoadStart = () => {
    this.triggerBufferAnimation()
  }

  handleLoad = ({duration}) => {
    this.setState({
      duration: duration
    })
  };

  triggerBufferAnimation = () => {
    this.loopingAnimation && this.loopingAnimation.stopAnimation()
    this.loopingAnimation = Animated.loop(
      Animated.timing(this.state.animated, {
        toValue: 1,
        duration: 1500
      })
    ).start()
  };
  render () {
    console.log('video player ', this.props)
    const { isShowingDetails, hideDetails, showDetails, thumbnailUrl, url } = this.props
    const { buffering } = this.state
    const BufferInterpolation = this.state.animated.interpolate({
      inputRange: [0, 1],
      outputRange: ['0deg', '600deg']
    })
    const rotateStyles = { transform: [{
      rotate: BufferInterpolation
    }]
    }
    return (
      <React.Fragment>
        <Video
          ref={ref => {
            this.player = ref;
          }}
          source={{ uri: url }}
          controls
          paused={this.state.paused}
          // poster={thumbnailUrl}
          onBuffer={this.onBuffer}
          onLoadStart={this.onLoadStart}
          onLoad={this.handleLoad}
          key={url}
          onProgress={this.handleProgress}
          style={styles.backgroundVideo}
          useTextureView={false}
          onVideoEnd={() => alert('Video ended')}
          bufferConfig={{
            minBufferMs: 15000,
            maxBufferMs: 50000,
            bufferForPlaybackMs: 2500,
            bufferForPlaybackAfterRebufferMs: 5000
          }}
        />
        <View
          color={Colors.appColor}
          style={styles.videoCover}
        >{
          buffering && <Animated.View style={rotateStyles}>
            <FontAwesome5 name='circle-notch' size={50} color='rgba(255, 255, 255, 0.6)' />
          </Animated.View>
        }</View>
      </React.Fragment>
    )
  }
}

export default VideoPlayer
const styles = StyleSheet.create({
  backgroundVideo: {
    height: undefined,
    width: '100%',
    backgroundColor: 'black',
    aspectRatio: 16 / 9,
    zIndex: 100
    // 2: 0
  },
  videoCover: {
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'transparent',
    zIndex: 10
  },
  controls: {
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    height: 20,
    left: 0,
    bottom: 5,
    right: 0,
    position: 'absolute',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-around',
    paddingHorizontal: 10,
    zIndex: 10
  },
  duration: {
    color: '#FFF',
    marginLeft: 15
  }
})
</code>```

Body:
I was doing this all stuff in my application on buffering state you can simply check the state on buffer and display loader like this. You have to use a combination of onLoadStart, onBuffer and onLoadEnd, Below is an example of how you can also build your custom loader and display while buffering.
If you don't want to use my loader or this animation stuff remove that thing and render your own loader.

    class VideoPlayer extends React.Component {
       constructor (props) {
       super(props)
       this.state = {
          paused: false,
          buffering: true,
          animated: new Animated.Value(0),
          progress: 0,
          duration: 0
    }
  }
  handleMainButtonTouch = () => {
    if (this.state.progress >= 1) {
      this.player.seek(0)
    }

    this.setState(state => {
      return {
        paused: !state.paused
      }
    })
  };
  handleProgressPress = e => {
    const position = e.nativeEvent.locationX
    const progress = (position / 250) * this.state.duration
    const isPlaying = !this.state.paused

    this.player.seek(progress)
  };

  handleProgress = progress => {
    this.setState({
      progress: progress.currentTime / this.state.duration
    })
  };
  onBuffer = ({isBuffering}) => {
    this.setState({ buffering: isBuffering })
    if (isBuffering) {
      this.triggerBufferAnimation()
    }
    if (this.loopingAnimation && isBuffering) {
      this.loopingAnimation.stopAnimation()
    }
  }
  onLoadStart = () => {
    this.triggerBufferAnimation()
  }

  handleLoad = ({duration}) => {
    this.setState({
      duration: duration
    })
  };

  triggerBufferAnimation = () => {
    this.loopingAnimation && this.loopingAnimation.stopAnimation()
    this.loopingAnimation = Animated.loop(
      Animated.timing(this.state.animated, {
        toValue: 1,
        duration: 1500
      })
    ).start()
  };
  render () {
    console.log('video player ', this.props)
    const { isShowingDetails, hideDetails, showDetails, thumbnailUrl, url } = this.props
    const { buffering } = this.state
    const BufferInterpolation = this.state.animated.interpolate({
      inputRange: [0, 1],
      outputRange: ['0deg', '600deg']
    })
    const rotateStyles = { transform: [{
      rotate: BufferInterpolation
    }]
    }
    return (
      <React.Fragment>
        <Video
          ref={ref => {
            this.player = ref;
          }}
          source={{ uri: url }}
          controls
          paused={this.state.paused}
          // poster={thumbnailUrl}
          onBuffer={this.onBuffer}
          onLoadStart={this.onLoadStart}
          onLoad={this.handleLoad}
          key={url}
          onProgress={this.handleProgress}
          style={styles.backgroundVideo}
          useTextureView={false}
          onVideoEnd={() => alert('Video ended')}
          bufferConfig={{
            minBufferMs: 15000,
            maxBufferMs: 50000,
            bufferForPlaybackMs: 2500,
            bufferForPlaybackAfterRebufferMs: 5000
          }}
        />
        <View
          color={Colors.appColor}
          style={styles.videoCover}
        >{
          buffering && <Animated.View style={rotateStyles}>
            <FontAwesome5 name='circle-notch' size={50} color='rgba(255, 255, 255, 0.6)' />
          </Animated.View>
        }</View>
      </React.Fragment>
    )
  }
}

export default VideoPlayer
const styles = StyleSheet.create({
  backgroundVideo: {
    height: undefined,
    width: '100%',
    backgroundColor: 'black',
    aspectRatio: 16 / 9,
    zIndex: 100
    // 2: 0
  },
  videoCover: {
    justifyContent: 'center',
    alignItems: 'center',
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    backgroundColor: 'transparent',
    zIndex: 10
  },
  controls: {
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    height: 20,
    left: 0,
    bottom: 5,
    right: 0,
    position: 'absolute',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-around',
    paddingHorizontal: 10,
    zIndex: 10
  },
  duration: {
    color: '#FFF',
    marginLeft: 15
  }
})


问:
Decoupling Silverlight client from service reference generated class
I am researching Prism v2 by going thru the quickstarts. And I have created a WCF service with the following signature:

```<code>namespace HelloWorld.Silverlight.Web
{
[ServiceContract(Namespace = "http://helloworld.org/messaging")]
[AspNetCompatibilityRequirements(RequirementsMode =
                                 AspNetCompatibilityRequirementsMode.Allowed)]
  public class HelloWorldMessageService
  {
    private string message = "Hello from WCF";

    [OperationContract]
    public void UpdateMessage(string message)
    {
      this.message = message;
    }

    [OperationContract]
    public string GetMessage()
    {
      return message;
    }
  }
}
</code>```

When I add a service reference to this service in my silverlight project it generates an interface and a class:

```<code>[System.ServiceModel.ServiceContractAttribute
        (Namespace="http://helloworld.org/messaging",
         ConfigurationName="Web.Services.HelloWorldMessageService")]
public interface HelloWorldMessageService {

  [System.ServiceModel.OperationContractAttribute
          (AsyncPattern=true,
      Action="http://helloworld.org/messaging/HelloWorldMessageService/UpdateMessage",
ReplyAction="http://helloworld.org/messaging/HelloWorldMessageService/UpdateMessageResponse")]
    System.IAsyncResult BeginUpdateMessage(string message, System.AsyncCallback callback, object asyncState);

    void EndUpdateMessage(System.IAsyncResult result);

    [System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://helloworld.org/messaging/HelloWorldMessageService/GetMessage", ReplyAction="http://helloworld.org/messaging/HelloWorldMessageService/GetMessageResponse")]
    System.IAsyncResult BeginGetMessage(System.AsyncCallback callback, object asyncState);

    string EndGetMessage(System.IAsyncResult result);
}

public partial class HelloWorldMessageServiceClient : System.ServiceModel.ClientBase<HelloWorld.Core.Web.Services.HelloWorldMessageService>, HelloWorld.Core.Web.Services.HelloWorldMessageService {
{
    // implementation
}
</code>```

I'm trying to decouple my application by passing around the interface instead of the concrete class. But I'm having difficulty finding examples of how to do this. When I try and call EndGetMessage and then update my UI I get an exception about updating the UI on the wrong thread. How can I update the UI from a background thread?

I tried but I get UnauthorizedAccessException : Invalid cross-thread access.

```<code>string messageresult = _service.EndGetMessage(result);

Application.Current.RootVisual.Dispatcher.BeginInvoke(() => this.Message = messageresult );
</code>```

The exception is thrown by Application.Current.RootVisual.

答:
Ok, I have been messing with this all day and the solution is really much more simple than that. I originally wanted to call the methods on the interface instead of the concreate class. The interface generated by proxy class generator only includes the BeginXXX and EndXXX methods and I was getting an exception when I called EndXXX.

Well, I just finished reading up on System.Threading.Dispatcher and I finally understand how to use it. Dispatcher is a member of any class that inherits from DispatcherObject, which the UI elements do. The Dispatcher operates on the UI thread, which for most WPF applications there is only 1 UI thread. There are exceptions, but I believe you have to do this explicitly so you'll know if you're doing it. Otherwise, you've only got a single UI thread. So it is safe to store a reference to a Dispatcher for use in non-UI classes.

In my case I'm using Prism and my Presenter needs to update the UI (not directly, but it is firing IPropertyChanged.PropertyChanged events). So what I have done is in my Bootstrapper when I set the shell to Application.Current.RootVisual I also store a reference to the Dispatcher like this:

```<code>public class Bootstrapper : UnityBootstrapper
{
    protected override IModuleCatalog GetModuleCatalog()
    {
    // setup module catalog
    }

    protected override DependencyObject CreateShell()
    {
        // calling Resolve instead of directly initing allows use of dependency injection
    Shell shell = Container.Resolve<Shell>();

        Application.Current.RootVisual = shell;

        Container.RegisterInstance<Dispatcher>(shell.Dispatcher);

        return shell;
    }
}
</code>```

Then my presenter has a ctor which accepts IUnityContainer as an argument (using DI) then I can do the following:

```<code>_service.BeginGetMessage(new AsyncCallback(GetMessageAsyncComplete), null);

private void GetMessageAsyncComplete(IAsyncResult result)
{
    string output = _service.EndGetMessage(result);
    Dispatcher dispatcher = _container.Resolve<Dispatcher>();
    dispatcher.BeginInvoke(() => this.Message = output);
}
</code>```

This is sooooo much simpler. I just didn't understand it before.

OwnerDisplayName: Mark J Miller

Body:
I am researching Prism v2 by going thru the quickstarts. And I have created a WCF service with the following signature:

namespace HelloWorld.Silverlight.Web
{
[ServiceContract(Namespace = "http://helloworld.org/messaging")]
[AspNetCompatibilityRequirements(RequirementsMode =
                                 AspNetCompatibilityRequirementsMode.Allowed)]
  public class HelloWorldMessageService
  {
    private string message = "Hello from WCF";

    [OperationContract]
    public void UpdateMessage(string message)
    {
      this.message = message;
    }

    [OperationContract]
    public string GetMessage()
    {
      return message;
    }
  }
}

When I add a service reference to this service in my silverlight project it generates an interface and a class:

[System.ServiceModel.ServiceContractAttribute
        (Namespace="http://helloworld.org/messaging",
         ConfigurationName="Web.Services.HelloWorldMessageService")]
public interface HelloWorldMessageService {

  [System.ServiceModel.OperationContractAttribute
          (AsyncPattern=true,
      Action="http://helloworld.org/messaging/HelloWorldMessageService/UpdateMessage",
ReplyAction="http://helloworld.org/messaging/HelloWorldMessageService/UpdateMessageResponse")]
    System.IAsyncResult BeginUpdateMessage(string message, System.AsyncCallback callback, object asyncState);

    void EndUpdateMessage(System.IAsyncResult result);

    [System.ServiceModel.OperationContractAttribute(AsyncPattern=true, Action="http://helloworld.org/messaging/HelloWorldMessageService/GetMessage", ReplyAction="http://helloworld.org/messaging/HelloWorldMessageService/GetMessageResponse")]
    System.IAsyncResult BeginGetMessage(System.AsyncCallback callback, object asyncState);

    string EndGetMessage(System.IAsyncResult result);
}

public partial class HelloWorldMessageServiceClient : System.ServiceModel.ClientBase<HelloWorld.Core.Web.Services.HelloWorldMessageService>, HelloWorld.Core.Web.Services.HelloWorldMessageService {
{
    // implementation
}

I'm trying to decouple my application by passing around the interface instead of the concrete class. But I'm having difficulty finding examples of how to do this. When I try and call EndGetMessage and then update my UI I get an exception about updating the UI on the wrong thread. How can I update the UI from a background thread?

I tried but I get UnauthorizedAccessException : Invalid cross-thread access.

string messageresult = _service.EndGetMessage(result);

Application.Current.RootVisual.Dispatcher.BeginInvoke(() => this.Message = messageresult );

The exception is thrown by Application.Current.RootVisual.

Body:
Ok, I have been messing with this all day and the solution is really much more simple than that. I originally wanted to call the methods on the interface instead of the concreate class. The interface generated by proxy class generator only includes the BeginXXX and EndXXX methods and I was getting an exception when I called EndXXX.

Well, I just finished reading up on System.Threading.Dispatcher and I finally understand how to use it. Dispatcher is a member of any class that inherits from DispatcherObject, which the UI elements do. The Dispatcher operates on the UI thread, which for most WPF applications there is only 1 UI thread. There are exceptions, but I believe you have to do this explicitly so you'll know if you're doing it. Otherwise, you've only got a single UI thread. So it is safe to store a reference to a Dispatcher for use in non-UI classes.

In my case I'm using Prism and my Presenter needs to update the UI (not directly, but it is firing IPropertyChanged.PropertyChanged events). So what I have done is in my Bootstrapper when I set the shell to Application.Current.RootVisual I also store a reference to the Dispatcher like this:

public class Bootstrapper : UnityBootstrapper
{
    protected override IModuleCatalog GetModuleCatalog()
    {
    // setup module catalog
    }

    protected override DependencyObject CreateShell()
    {
        // calling Resolve instead of directly initing allows use of dependency injection
    Shell shell = Container.Resolve<Shell>();

        Application.Current.RootVisual = shell;

        Container.RegisterInstance<Dispatcher>(shell.Dispatcher);

        return shell;
    }
}

Then my presenter has a ctor which accepts IUnityContainer as an argument (using DI) then I can do the following:

_service.BeginGetMessage(new AsyncCallback(GetMessageAsyncComplete), null);

private void GetMessageAsyncComplete(IAsyncResult result)
{
    string output = _service.EndGetMessage(result);
    Dispatcher dispatcher = _container.Resolve<Dispatcher>();
    dispatcher.BeginInvoke(() => this.Message = output);
}

This is sooooo much simpler. I just didn't understand it before.


问:
How do I detect if a new microphone is available?
It appears that if one has a mic available, then one can add an event listener for the StatusEvent. However, this only tells you if the mic has been allowed or disallowed.

What I'd really like to do is detect if the static Microphone.names property changes. I would have expected this property to be bindable.

If I right click and select "settings" immediately after plugging in a mic, I can see that flash has updated their list of available microphones. However, there seems to be no way in code for me to receive the same update.

The docs say "Calling Microphone.names requires an extensive examination of the hardware, and it may take several seconds to build the array." So I think polling this every few seconds is not a feasible option.

答:
I ran a little test script:

```<code>var ta:TextArea = new TextArea();
    ta.width = ta.height = 500;
    addChild(ta);
    var t:Timer = new Timer(5000);
    t.addEventListener(TimerEvent.TIMER, function(e:Event):void{
        var t0:uint = getTimer();

        var m:* = Microphone.getMicrophone();

        ta.text += "mic found: "+(m?true:false)+" "+(getTimer()-t0);

        t0 = getTimer();
        var o:* = Microphone.names;
        ta.text += "\t\ttime to get names: "+(getTimer()-t0)+"\n";

    });
    t.start();
</code>```

The results were all times with fewer than 10ms (getMicrophone was 0-3ms, names was 2-9ms), which seems pretty fast to me. I don't know, perhaps it's my computer, but it doesn't seem to be too intensive. As getMicrophone is all I need, there are no official warnings about its use, and it's marginally faster, I'm going to poll getMicrophone every few seconds or so to deal with this.

If anyone here cares to run this script and give some feedback on your results, it may help me and others make a better choice.

Body:
I ran a little test script:

var ta:TextArea = new TextArea();
    ta.width = ta.height = 500;
    addChild(ta);
    var t:Timer = new Timer(5000);
    t.addEventListener(TimerEvent.TIMER, function(e:Event):void{
        var t0:uint = getTimer();

        var m:* = Microphone.getMicrophone();

        ta.text += "mic found: "+(m?true:false)+" "+(getTimer()-t0);

        t0 = getTimer();
        var o:* = Microphone.names;
        ta.text += "\t\ttime to get names: "+(getTimer()-t0)+"\n";

    });
    t.start();

The results were all times with fewer than 10ms (getMicrophone was 0-3ms, names was 2-9ms), which seems pretty fast to me. I don't know, perhaps it's my computer, but it doesn't seem to be too intensive. As getMicrophone is all I need, there are no official warnings about its use, and it's marginally faster, I'm going to poll getMicrophone every few seconds or so to deal with this.

If anyone here cares to run this script and give some feedback on your results, it may help me and others make a better choice.


问:
Joining tables in SQL Server to get all the data
I have 3 tables as

```<code>Customer
Customer    |Name
1002        |ABB
2006        |Aberdeen C
.
.
</code>```

And Sales Revenue table

```<code>Customer|Inv.   |Product    |Sales Amount   |Gross Margin
1002    |600    |5      |8000       |125
1002    |601    |20     |0      |-10
1002    |602    |0      |320        |160
2006    |603    |7      |120        |0
.
.
</code>```

Account Receivable table

```<code>Customer|Inv.   |Product    |Balance    |Line Amount    |Amount
1002    |500    |0      |150        |NULL       |150
1002    |600    |5      |8000       |8000       |8000
1002    |601    |20     |0      |0      |0
1002    |602    |0      |0      |160        |160
2006    |603    |7      |120        |120        |0
.
.
</code>```

I want to create a view of customer by joining Sales Revenue and Account Receivable table as:

```<code>Customer|Name|Inv.|Product|Sales Amount |Gross Margin   |Balance    |Line Amount
1002    |ABB |500 |0      |NULL     |NULL       |150        |150
1002    |ABB |600 |5      |8000     |125        |8000       |8000
1002    |ABB |601 |20     |0        |-10        |0      |0
1002    |ABB |602 |0      |320      |160        |160        |160
2006    |ABB |603 |7      |120      |0      |120        |0
.
.
</code>```

I tried

```<code>CREATE  or alter   VIEW [dbo].[custmermasterview] as
SELECT [Customer]
      ,[Name]
      ,[Inv]
      ,[Sales Amount]
      ,[Gross Margin]
      ,[Balance]
      ,isnull([Line Amount],[Amount]) as LineAmount
      ,[dbo].[SalesRevenue].[product_key]

  FROM [PDI].[dbo].[Customer]
  LEFT JOIN [dbo].[SalesRevenue] ON
   ([PDI].[dbo].[Customer].[customer_key] = [dbo].[SalesRevenue].[customer_key] and
  LEFT JOIN [dbo].[AccountReceivables] ON
  ([dbo].[SalesRevenue].[Inv] = [dbo].[AccountReceivables].Inv)
</code>```

Obviously it's left joining with SalesRevenue, so records from AccountReceivables are not getting pulled.
How can I get the required output?

答:
You can add a subquery that gets all the invoices from both tables and join on that subquery:</p>

```<code>SELECT [Customer]
      ,[Name]
      ,[Inv]
      ,[Sales Amount]
      ,[Gross Margin]
      ,[Balance]
      ,isnull([Line Amount],[Amount]) as LineAmount
      ,[dbo].[SalesRevenue].[product_key]

  FROM [PDI].[dbo].[Customer]
  JOIN (    SELECT DISTINCT [customer_key] , inv, product
        FROM [dbo].[AccountReceivables]
        UNION
        SELECT DISTINCT [customer_key] , inv, product
        FROM [dbo].[SalesRevenue]
    ) all
  LEFT JOIN [dbo].[SalesRevenue] ON
    [dbo].[SalesRevenue].[customer_key] = all.[customer_key]
    and [SalesRevenue].inv = all.inv
    and [SalesRevenue].product = all.product

  LEFT JOIN [dbo].[AccountReceivables] ON
    all.[Inv] = [dbo].[AccountReceivables].Inv
    and [AccountReceivables].inv = all.inv
    and [AccountReceivables].product = all.product
</code>```

Body:
I have 3 tables as

Customer
Customer    |Name
1002        |ABB
2006        |Aberdeen C
.
.

And Sales Revenue table

Customer|Inv.   |Product    |Sales Amount   |Gross Margin
1002    |600    |5      |8000       |125
1002    |601    |20     |0      |-10
1002    |602    |0      |320        |160
2006    |603    |7      |120        |0
.
.

Account Receivable table

Customer|Inv.   |Product    |Balance    |Line Amount    |Amount
1002    |500    |0      |150        |NULL       |150
1002    |600    |5      |8000       |8000       |8000
1002    |601    |20     |0      |0      |0
1002    |602    |0      |0      |160        |160
2006    |603    |7      |120        |120        |0
.
.

I want to create a view of customer by joining Sales Revenue and Account Receivable table as:

Customer|Name|Inv.|Product|Sales Amount |Gross Margin   |Balance    |Line Amount
1002    |ABB |500 |0      |NULL     |NULL       |150        |150
1002    |ABB |600 |5      |8000     |125        |8000       |8000
1002    |ABB |601 |20     |0        |-10        |0      |0
1002    |ABB |602 |0      |320      |160        |160        |160
2006    |ABB |603 |7      |120      |0      |120        |0
.
.

I tried

CREATE  or alter   VIEW [dbo].[custmermasterview] as
SELECT [Customer]
      ,[Name]
      ,[Inv]
      ,[Sales Amount]
      ,[Gross Margin]
      ,[Balance]
      ,isnull([Line Amount],[Amount]) as LineAmount
      ,[dbo].[SalesRevenue].[product_key]

  FROM [PDI].[dbo].[Customer]
  LEFT JOIN [dbo].[SalesRevenue] ON
   ([PDI].[dbo].[Customer].[customer_key] = [dbo].[SalesRevenue].[customer_key] and
  LEFT JOIN [dbo].[AccountReceivables] ON
  ([dbo].[SalesRevenue].[Inv] = [dbo].[AccountReceivables].Inv)

Obviously it's left joining with SalesRevenue, so records from AccountReceivables are not getting pulled.
How can I get the required output?

Body:
You can add a subquery that gets all the invoices from both tables and join on that subquery:

SELECT [Customer]
      ,[Name]
      ,[Inv]
      ,[Sales Amount]
      ,[Gross Margin]
      ,[Balance]
      ,isnull([Line Amount],[Amount]) as LineAmount
      ,[dbo].[SalesRevenue].[product_key]

  FROM [PDI].[dbo].[Customer]
  JOIN (    SELECT DISTINCT [customer_key] , inv, product
        FROM [dbo].[AccountReceivables]
        UNION
        SELECT DISTINCT [customer_key] , inv, product
        FROM [dbo].[SalesRevenue]
    ) all
  LEFT JOIN [dbo].[SalesRevenue] ON
    [dbo].[SalesRevenue].[customer_key] = all.[customer_key]
    and [SalesRevenue].inv = all.inv
    and [SalesRevenue].product = all.product

  LEFT JOIN [dbo].[AccountReceivables] ON
    all.[Inv] = [dbo].[AccountReceivables].Inv
    and [AccountReceivables].inv = all.inv
    and [AccountReceivables].product = all.product


问:
uninitialized constant Mysql::error
I am trying to get my rails app to production but this is my first time.  I am running mysql 5.5 and gem 2.8.1.

When trying rake db:setup RAILS_ENV="production", I get the following:

```<code>rake aborted!
uninitialized constant Mysql::Error
</code>```

any help is much appreciated

i thought it might be useful to add the trace file for this error.  any help would be greatly appreciated:

```<code>rake db:setup RAILS_ENV="production" --trace
(in /Users/chris/rails_projects/sienab)
** Invoke db:setup (first_time)
** Invoke db:create (first_time)
** Invoke db:load_config (first_time)
** Invoke rails_env (first_time)
** Execute rails_env
** Execute db:load_config
** Execute db:create
rake aborted!
uninitialized constant Mysql::Error
/Library/Ruby/Gems/1.8/gems/activerecord-3.0.6/lib/active_record/railties/databases.rake:64:in `create_database'
/Library/Ruby/Gems/1.8/gems/activerecord-3.0.6/lib/active_record/railties/databases.rake:35
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:636:in `call'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:636:in `execute'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:631:in `each'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:631:in `execute'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:597:in `invoke_with_call_chain'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:607:in `invoke_prerequisites'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:604:in `each'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:604:in `invoke_prerequisites'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:596:in `invoke_with_call_chain'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:583:in `invoke'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2051:in `invoke_task'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `each'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2023:in `top_level'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2001:in `run'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/bin/rake:31
/usr/bin/rake:19:in `load'
/usr/bin/rake:19
</code>```

答:
As mentioned in Rails 3 Mysql Problems you should be using the mysql2 gem if possible.

Make sure to change mysql to mysql2 in both your Gemfile and your database.yml

Title: uninitialized constant Mysql::error

Body:
I am trying to get my rails app to production but this is my first time.  I am running mysql 5.5 and gem 2.8.1.

When trying rake db:setup RAILS_ENV="production", I get the following:

rake aborted!
uninitialized constant Mysql::Error

any help is much appreciated

i thought it might be useful to add the trace file for this error.  any help would be greatly appreciated:

rake db:setup RAILS_ENV="production" --trace
(in /Users/chris/rails_projects/sienab)
** Invoke db:setup (first_time)
** Invoke db:create (first_time)
** Invoke db:load_config (first_time)
** Invoke rails_env (first_time)
** Execute rails_env
** Execute db:load_config
** Execute db:create
rake aborted!
uninitialized constant Mysql::Error
/Library/Ruby/Gems/1.8/gems/activerecord-3.0.6/lib/active_record/railties/databases.rake:64:in `create_database'
/Library/Ruby/Gems/1.8/gems/activerecord-3.0.6/lib/active_record/railties/databases.rake:35
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:636:in `call'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:636:in `execute'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:631:in `each'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:631:in `execute'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:597:in `invoke_with_call_chain'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:607:in `invoke_prerequisites'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:604:in `each'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:604:in `invoke_prerequisites'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:596:in `invoke_with_call_chain'
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/1.8/monitor.rb:242:in `synchronize'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:590:in `invoke_with_call_chain'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:583:in `invoke'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2051:in `invoke_task'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `each'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2029:in `top_level'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2023:in `top_level'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2001:in `run'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:2068:in `standard_exception_handling'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/lib/rake.rb:1998:in `run'
/Library/Ruby/Gems/1.8/gems/rake-0.8.7/bin/rake:31
/usr/bin/rake:19:in `load'
/usr/bin/rake:19