问:
ImmutableJS with Redux's combineReducers
Getting warning: "Using Maps as children is not yet fully supported" when combining reducers (each with its own immutable.js Map) with #redux combineReducers.  What's a better store structure to avoid this?</p>

```<code>import reducer_2 from './action_handlers/two';
import reducer_3 from './action_handlers/three';
import { combineReducers } from 'redux';

let reducer = combineReducers({
    reducer_2,
    reducer_3
});

export default reducer;

//=====================
// ./action_handlers/two.js

const INITIAL_STATE_2 = new Map({
    foo: 'bar'
});
export default function reducer_2(state = INITIAL_STATE_2, action) {...}

//======================
// ./action_handlers/three.js

const INITIAL_STATE_3 = new Map({
    baz: 'bat'
});
export default function reducer_3(state = INITIAL_STATE_3, action) {...}

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

答:
You can't user combine reducer of redux
a combineReducers function that comes with Redux will not work as it doesn’t know how to read and create new versions of state.</p>

Body:
Getting warning: "Using Maps as children is not yet fully supported" when combining reducers (each with its own immutable.js Map) with #redux combineReducers.  What's a better store structure to avoid this?

import reducer_2 from './action_handlers/two';
import reducer_3 from './action_handlers/three';
import { combineReducers } from 'redux';

let reducer = combineReducers({
    reducer_2,
    reducer_3
});

export default reducer;

//=====================
// ./action_handlers/two.js

const INITIAL_STATE_2 = new Map({
    foo: 'bar'
});
export default function reducer_2(state = INITIAL_STATE_2, action) {...}

//======================
// ./action_handlers/three.js

const INITIAL_STATE_3 = new Map({
    baz: 'bat'
});
export default function reducer_3(state = INITIAL_STATE_3, action) {...}

//=======================


来源: stackexchange

问:
resize function firing multiple times
Im using the resize() method to run a function the will return on
  varied viewport sizes like 992,768, ect. problem is that the
  function is executing everytime causing a glitch in the DOM. example
  in codepen https://codepen.io/paul-solomon/pen/WBEgQe

```<code>//javascript

$(window).resize(function(){
nh_masonry.data.loadorder();
});

//css

.masonry_grid_quarter__container{
 margin-bottom: 8px;
 column-count:3;
 column-gap:8px;
}

@media screen and (max-width:992px){
.masonry_grid_quarter__container{
 column-count:2;
 }
}

@media screen and (max-width:768px){
 .masonry_grid_quarter__container{
  column-count:2;
  }
}

@media screen and (max-width:580px){
 .masonry_grid_quarter__container{
  column-count:1;
  }
 }
</code>```

expected result: resize function executes at specific viewports
actual result: executes resize multiple times creating a DOM glitch.

答:
You need a variable that keeps track of the current-state of the DOM.

Let's create a variable called currentViewPort that can have a value of "desktop", "tablet" or "mobile".

When the window resizes, we will toggle the value of currentViewPort. If currentViewPort is already matching our screen-layout, then we will not call the function again. It will only be called when we enter a different layout.

Here it is in action: https://codepen.io/anon/pen/GaGboG?editors=1111

```<code>   var App = (function ($) {

   var nh_masonry = {};
   var currentViewPort = ""
   //sets initial reorder variable
   nh_masonry.vars = { reorder : false}

   nh_masonry.onload = function () {
            // when the document is loaded sets the reorder variable to true
            // and also loads the order object method
            nh_masonry.vars.reorder = !nh_masonry.vars.reorder;
            nh_masonry.data.loadorder();

     $(window).resize(function(){
           // re-set layout after resize
           if($( window ).width() <= 992 && $( window ).width() > 768 && currentViewPort !== "desktop"){

             currentViewPort = "desktop"
             console.log("desktop");
              nh_masonry.data.loadorder();
              // nh_masonry.responsive.tablet();
              // nh_masonry.responsive.mobile();

           } else if ($( window ).width() == 768 && currentViewPort !== "tablet"){

             currentViewPort = "tablet"
             console.log("tablet");
              nh_masonry.data.loadorder();
              // nh_masonry.responsive.tablet();
              // nh_masonry.responsive.mobile();

           } else if ($( window ).width() < 768 && $( window ).width() >= 380 && currentViewPort !== "mobile"){
            currentViewPort = "mobile"
             console.log("mobile");
              nh_masonry.data.loadorder();
              // nh_masonry.responsive.tablet();
              // nh_masonry.responsive.mobile();
           }
         })
     };
</code>```

ContentLicense: CC BY-SA 4.0

Title: resize function firing multiple times

Body:
Im using the resize() method to run a function the will return on
  varied viewport sizes like 992,768, ect. problem is that the
  function is executing everytime causing a glitch in the DOM. example
  in codepen https://codepen.io/paul-solomon/pen/WBEgQe

//javascript

$(window).resize(function(){
nh_masonry.data.loadorder();
});

//css

.masonry_grid_quarter__container{
 margin-bottom: 8px;
 column-count:3;
 column-gap:8px;
}

@media screen and (max-width:992px){
.masonry_grid_quarter__container{
 column-count:2;
 }
}

@media screen and (max-width:768px){
 .masonry_grid_quarter__container{
  column-count:2;
  }
}

@media screen and (max-width:580px){
 .masonry_grid_quarter__container{
  column-count:1;
  }
 }

expected result: resize function executes at specific viewports
actual result: executes resize multiple times creating a DOM glitch.

Body:
You need a variable that keeps track of the current-state of the DOM.

Let's create a variable called currentViewPort that can have a value of "desktop", "tablet" or "mobile".

When the window resizes, we will toggle the value of currentViewPort. If currentViewPort is already matching our screen-layout, then we will not call the function again. It will only be called when we enter a different layout.

Here it is in action: https://codepen.io/anon/pen/GaGboG?editors=1111

   var App = (function ($) {

   var nh_masonry = {};
   var currentViewPort = ""
   //sets initial reorder variable
   nh_masonry.vars = { reorder : false}

   nh_masonry.onload = function () {
            // when the document is loaded sets the reorder variable to true
            // and also loads the order object method
            nh_masonry.vars.reorder = !nh_masonry.vars.reorder;
            nh_masonry.data.loadorder();

     $(window).resize(function(){
           // re-set layout after resize
           if($( window ).width() <= 992 && $( window ).width() > 768 && currentViewPort !== "desktop"){

             currentViewPort = "desktop"
             console.log("desktop");
              nh_masonry.data.loadorder();
              // nh_masonry.responsive.tablet();
              // nh_masonry.responsive.mobile();

           } else if ($( window ).width() == 768 && currentViewPort !== "tablet"){

             currentViewPort = "tablet"
             console.log("tablet");
              nh_masonry.data.loadorder();
              // nh_masonry.responsive.tablet();
              // nh_masonry.responsive.mobile();

           } else if ($( window ).width() < 768 && $( window ).width() >= 380 && currentViewPort !== "mobile"){
            currentViewPort = "mobile"
             console.log("mobile");
              nh_masonry.data.loadorder();
              // nh_masonry.responsive.tablet();
              // nh_masonry.responsive.mobile();
           }
         })
     };


问:
Python .count String function - Counting an exact word occurrence from string or line
I want to count the word occurrence from a string. But I only want to count the exact occurrence, not from a substring.

For eg. If the string which I want to count is -> "This is good" and If the word I want to count the occurrence is "is", I only want to get occurrence of is to be 1 not 2. But my code counts "is" from "This" word. How can I do this. Sorry for my poor english.

text = "This is good"
text.count("is")

>>> 2
```

<pre class="lang-py prettyprint-override"><code>text = "This is good"
text.count("is")

>>> 1
</code>```

答:
You can use regular expression, it'll help you to find substring divided with any word boundary:</p>

```<code>import re

text = "This is good is\tis\t"
occurences = sum(1 for _ in re.finditer(r"\bis\b", text))
</code>```

Body:
I want to count the word occurrence from a string. But I only want to count the exact occurrence, not from a substring.

For eg. If the string which I want to count is -> "This is good" and If the word I want to count the occurrence is "is", I only want to get occurrence of is to be 1 not 2. But my code counts "is" from "This" word. How can I do this. Sorry for my poor english.

text = "This is good"
text.count("is")

>>> 2

text = "This is good"
text.count("is")

>>> 1

Body:
You can use regular expression, it'll help you to find substring divided with any word boundary:

import re

text = "This is good is\tis\t"
occurences = sum(1 for _ in re.finditer(r"\bis\b", text))


问:
Can I run a 64-bit VMware image on a 32-bit machine?
Can I run a 64-bit VMware image on a 32-bit machine?

I've googled this, but there doesn't seem to be a conclusive answer.

I know that it would have to be completely emulated and would run like a dog - but slow performance isn't necessarily an issue as I'm just interested in testing some of my background services code on 64-bit platforms.

答:
If you have 32-bit hardware, no, you cannot run a 64-bit guest OS. "VMware software does not emulate an instruction set for different hardware not physically present".

However, QEMU can emulate a 64-bit processor, so you could convert the VMWare machine and run it with this

From this 2008-era blog post (mirrored by archive.org):

```<code>$ cd /path/to/vmware/guestos
$ for i in \`ls *[0-9].vmdk\`; do qemu-img convert -f vmdk $i -O raw {i/vmdk/raw};done
$ cat *.raw >> guestos.img
</code>```

To run it,

```<code>qemu -m 256 -hda guestos.img
</code>```

The downside? Most of us runs VMware without preallocation space for the virtual disk. So, when we make a conversion from VMware to QEMU, the raw file will be the total space WITH preallocation. I am still testing with -f qcow format will it solve the
  problem or not. Such as:

```<code>for i in `ls *[0-9].vmdk`; do qemu-img convert -f vmdk $i -O qcow ${i/vmdk/qcow}; done && cat *.qcow >> debian.img
</code>```

OwnerDisplayName: John Sibly

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: ceretullis

Body:
If you have 32-bit hardware, no, you cannot run a 64-bit guest OS. "VMware software does not emulate an instruction set for different hardware not physically present".

However, QEMU can emulate a 64-bit processor, so you could convert the VMWare machine and run it with this

From this 2008-era blog post (mirrored by archive.org):

$ cd /path/to/vmware/guestos
$ for i in \`ls *[0-9].vmdk\`; do qemu-img convert -f vmdk $i -O raw {i/vmdk/raw};done
$ cat *.raw >> guestos.img

To run it,

qemu -m 256 -hda guestos.img

The downside? Most of us runs VMware without preallocation space for the virtual disk. So, when we make a conversion from VMware to QEMU, the raw file will be the total space WITH preallocation. I am still testing with -f qcow format will it solve the
  problem or not. Such as:

for i in `ls *[0-9].vmdk`; do qemu-img convert -f vmdk $i -O qcow ${i/vmdk/qcow}; done && cat *.qcow >> debian.img

OwnerDisplayName: dbr


问:
Is there an implicit default constructor in C++?
In the book I'm reading at the moment (C++ Without Fear) it says that if you don't declare a default constructor for a class, the compiler supplies one for you, which "zeroes out each data member". I've experimented with this, and I'm not seeing any zeroing -out behaviour. I also can't find anything that mentions this on Google. Is this just an error or a quirk of a specific compiler?</p>

答:
If you do not define a constructor, the compiler will define a default constructor for you.

Construction

The implementation of this

default constructor is:

default construct the base class (if the base class does not have a default constructor, this is a compilation failure)

default construct each member variable in the order of declaration. (If a member does not have a default constructor, this is a compilation failure).

Note:

The POD data (int,float,pointer, etc.) do not have an explicit constructor but the default action is to do nothing (in the vane of C++ philosophy; we do not want to pay for something unless we explicitly ask for it).

Copy

If no destructor/copy Constructor/Copy Assignment operator is defined the compiler builds one of those for you (so a class always has a destructor/Copy Constructor/Assignment Operator (unless you cheat and explicitly declare one but don't define it)).

The default implementation is:

Destructor:

If user-defined destructor is defined, execute the code provided.

Call the destructor of each member in reverse order of declaration

Call the destructor of the base class.

Copy Constructor:

Call the Base class Copy Constructor.

Call the copy constructor for each member variable in the order of declaration.

Copy Assignment Operator:

Call the base class assignment operator

Call the copy assignment operator of each member variable in the order of declaration.

Return a reference to this.

Note Copy Construction/Assignment operator of POD Data is just copying the data (Hence the shallow copy problem associated with RAW pointers).

Move

If no destructor/copy Constructor/Copy Assignment/Move Constructor/Move Assignment operator is defined the compiler builds the move operators for you one of those for you.

The default implementation is:

Implicitly-declared move constructor
If no user-defined move constructors are provided for a class type (struct, class, or union), and all of the following is true:

Move Constructor:

Call the Base class Copy Constructor.

Call the move constructor for each member variable in the order of declaration.

Move Assignment Operator:

Call the base class assignment operator

Call the move assignment operator of each member variable in the order of declaration.

Return a reference to this.

OwnerDisplayName: Skilldrick

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Martin York

LastEditorDisplayName: Martin York


问:
Putting applets into a HTML, but how?
I wrote an applet which is called "IdrawApplet.java" and a HTML which is supposed to contain this applet. But somehow when I run the HTML it says that it can't find my java-Class.
This is a "Dynamic-Web-Project". It has a "WebContent"-Folder which contains both, the HTML and the java-Class.

As you will see I tried to insert the applet in two different ways. By putting it in a "applet"-Tag and a "object"-Tag (as suggested) on SELFHTML.org:

```<code><!-- <applet code= "IdrawApplet.class"
        codebase= "../applets"
        width= 320 height= 180></applet> -->

        <object classid="java:IdrawApplet.class"
        codebase="../applets"
        width="800" height="600"></object>
</code>```

Thanks in advance...

答:
The proper way (which is also the HTML5 way) to embed a Java applet is:

```<code><object type="application/x-java-applet" width="320" height="180">
    <param name="code" value="MyJavaClass">
    fallback content
</object>
</code>```

However, IE doesn't support the standard way so you need to use IE conditional comments (in an HTML5-compatible way) like this:

```<code><!--[if !IE]>-->
    <object type="application/x-java-applet" width="320" height="180">
        <param name="code" value="MyJavaClass">
        fallback content
    </object>
<!--<![endif]-->
<!--[if IE]>
    <object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width="320" height="180">
        <param name="code" value="MyJavaClass">
        fallback content
    </object>
<![endif]-->
</code>```

Note that for the value of the code param, it doesn't require the .class extension. Just the class name is preferable.

For IE, you can also specify a codebase attribute if you want to provide a location to a cab file where IE can fetch Java if you don't have it. However, if you want to specify the path to the directory the .class file is in, you do that (for any browser) with the codebase param.

As for enabling scripting with "mayscript", you shouldn't need to do that these days. But, if you need to for some reason, you do it with a mayscript param (not attribute) and set its value to true.

Note that the fallback content will only show when a handler for application/x-java-applet isn't present or is disabled. It won't show for a missing .class file as the Java plug-in still loads.

Title: Putting applets into a HTML, but how?

Body:
I wrote an applet which is called "IdrawApplet.java" and a HTML which is supposed to contain this applet. But somehow when I run the HTML it says that it can't find my java-Class.
This is a "Dynamic-Web-Project". It has a "WebContent"-Folder which contains both, the HTML and the java-Class.

As you will see I tried to insert the applet in two different ways. By putting it in a "applet"-Tag and a "object"-Tag (as suggested) on SELFHTML.org:

        <object classid="java:IdrawApplet.class"
        codebase="../applets"
        width="800" height="600"></object>

Thanks in advance...

Body:
The proper way (which is also the HTML5 way) to embed a Java applet is:

<object type="application/x-java-applet" width="320" height="180">
    <param name="code" value="MyJavaClass">
    fallback content
</object>

However, IE doesn't support the standard way so you need to use IE conditional comments (in an HTML5-compatible way) like this:

<!--[if !IE]>-->
    <object type="application/x-java-applet" width="320" height="180">
        <param name="code" value="MyJavaClass">
        fallback content
    </object>
<!--<![endif]-->
<!--[if IE]>
    <object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width="320" height="180">
        <param name="code" value="MyJavaClass">
        fallback content
    </object>
<![endif]-->

Note that for the value of the code param, it doesn't require the .class extension. Just the class name is preferable.

For IE, you can also specify a codebase attribute if you want to provide a location to a cab file where IE can fetch Java if you don't have it. However, if you want to specify the path to the directory the .class file is in, you do that (for any browser) with the codebase param.

As for enabling scripting with "mayscript", you shouldn't need to do that these days. But, if you need to for some reason, you do it with a mayscript param (not attribute) and set its value to true.

Note that the fallback content will only show when a handler for application/x-java-applet isn't present or is disabled. It won't show for a missing .class file as the Java plug-in still loads.


问:
Count word frequency of all words in a file
I have a text file, from which I have removed symbols and stop words.

I have also tokenized it (broken it into a list of all words) in case operations are easier with a list.

I would like to create a .csv file with frequencies of all words (long format) in descending order. How could I go about it?

I have thought about looping through the list thus:

```<code>longData = pandas.DataFrame([], index=[], columns=['Frequency'])
for word in tokenizedFile:
    if word in longData.index:
         longData.loc[word]=longData.loc[word]+1
    else:
         wordFrame = pandas.DataFrame([1], index=[word])
         longData.append(wordFrame)
</code>```

but that seems pretty inefficient and wasteful.

答:
if you text is a list of strings like these above:

```<code>from sklearn.feature_extraction import text

texts = [
        'this is the first text',
        'this is the secound text',
        'and this is the last text the have two word text'

        ]

#istantiate.
cv = text.CountVectorizer()

cv.fit(texts)

vectors = cv.transform(texts).toarray()
</code>```

you will need explore more the parameters.

Body:
I have a text file, from which I have removed symbols and stop words.

I have also tokenized it (broken it into a list of all words) in case operations are easier with a list.

I would like to create a .csv file with frequencies of all words (long format) in descending order. How could I go about it?

I have thought about looping through the list thus:

longData = pandas.DataFrame([], index=[], columns=['Frequency'])
for word in tokenizedFile:
    if word in longData.index:
         longData.loc[word]=longData.loc[word]+1
    else:
         wordFrame = pandas.DataFrame([1], index=[word])
         longData.append(wordFrame)

but that seems pretty inefficient and wasteful.

Body:
if you text is a list of strings like these above:

from sklearn.feature_extraction import text

texts = [
        'this is the first text',
        'this is the secound text',
        'and this is the last text the have two word text'

        ]

#istantiate.
cv = text.CountVectorizer()

cv.fit(texts)

vectors = cv.transform(texts).toarray()

you will need explore more the parameters.


问:
How to select right template for class
As an input, I'm given a number, which is a bit-width of a variable. For ex. if it's 5, I need to use char(which is 8), if I'm given 14, i need to use 16-bit int.
I'm free to use STD lib and all of standards up to C++17.

I've created class, but I can't find how can I create instance without enclosing brackets. I don't know how can I create such object without specifying class template, not even as a pointer.

template<typename T>
class Kompresor{
...
};

int main(int agrc, char* argv[]){

    size_t max_value = argv[1];
    size_t copy = max_value + 1;
    int byte_width = 0;
    while(copy > 0){
        copy = copy >> 1;
        ++byte_width;
    }
    // This works
    // Problem is brackets, can't use kompresor outside scope
    if(byte_width < 9){
        Kompresor<char> Kompresor();
    }else if(byte_width < 17){
        Kompresor<int16_t> Kompresor();
    }
    // This dosen't
    Kompresor<>* k;
    k = new Kompresor<char>();

    return 0;
}
```

I need to use object throughout program, and writing same code in all of enclosing brackets is just code redundancy.

答:
Create a template function to do the full job, and dispatch in main:

```<code>template <typename T>
void DoJob()
{
    Kompresor<T> k;
    // ...
}
</code>```

and in main

```<code>int main()
{
    std::size_t size = /*...*/

    switch (size)
    {
        case 8: DoJob<char>(); break;
        case 16: DoJob<std::uint16_t>(); break;
        case 32: DoJob<std::uint32_t>(); break;
        case 64: DoJob<std::uint64_t>(); break;
        default: throw std::runtime_error("unsupported");
    }

}
</code>```

Title: How to select right template for class

Body:
As an input, I'm given a number, which is a bit-width of a variable. For ex. if it's 5, I need to use char(which is 8), if I'm given 14, i need to use 16-bit int.
I'm free to use STD lib and all of standards up to C++17.

I've created class, but I can't find how can I create instance without enclosing brackets. I don't know how can I create such object without specifying class template, not even as a pointer.

template<typename T>
class Kompresor{
...
};

int main(int agrc, char* argv[]){

    size_t max_value = argv[1];
    size_t copy = max_value + 1;
    int byte_width = 0;
    while(copy > 0){
        copy = copy >> 1;
        ++byte_width;
    }
    // This works
    // Problem is brackets, can't use kompresor outside scope
    if(byte_width < 9){
        Kompresor<char> Kompresor();
    }else if(byte_width < 17){
        Kompresor<int16_t> Kompresor();
    }
    // This dosen't
    Kompresor<>* k;
    k = new Kompresor<char>();

    return 0;
}

I need to use object throughout program, and writing same code in all of enclosing brackets is just code redundancy.

Body:
Create a template function to do the full job, and dispatch in main:

template <typename T>
void DoJob()
{
    Kompresor<T> k;
    // ...
}

and in main

int main()
{
    std::size_t size = /*...*/

    switch (size)
    {
        case 8: DoJob<char>(); break;
        case 16: DoJob<std::uint16_t>(); break;
        case 32: DoJob<std::uint32_t>(); break;
        case 64: DoJob<std::uint64_t>(); break;
        default: throw std::runtime_error("unsupported");
    }

}


问:
Creating a currency converter in Swift
I am trying to make a currency converter in Swift. I saw this post: Need API for currency converting and How to make an HTTP request in Swift?.

So when I combined them together:

```<code>let url = NSURL(string: "http://download.finance.yahoo.com/d/quotes.csv?s=USDEUR=X&f=nl1d1t1");

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
     println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

task.resume()
</code>```

It returns me a output as such:

```<code>Optional("USD to EUR",0.7987,"11/20/2014","3:45am")
</code>```

But I want to access the currency exchange rate. How do I do that? I am not sure how to do that?

答:
I've made a simpler currency converter in Swift 5. If you're interested, check it out in my GitHub: https://github.com/ThiagoAM/CurrencyConverter

The usage is really simple:

```<code>class ViewController: UIViewController {

// Creates the Currency Converter instance:
let currencyConverter = CurrencyConverter()

override func viewDidLoad() {
    super.viewDidLoad()

    // Updates the exchange rates:
    currencyConverter.updateExchangeRates(completion: {
        // The code inside here runs after all the data is fetched.

        // Now you can convert any currency:
        // • Example_1 (USD to EUR):
        let doubleResult = self.currencyConverter.convert(10, valueCurrency: .USD, outputCurrency: .EUR)
        print("••• 10 USD = \(doubleResult!) EUR •••")

        // • Example_2 (EUR to GBP) - Returning a formatted String:
        let formattedResult = self.currencyConverter.convertAndFormat(10, valueCurrency: .EUR, outputCurrency: .GBP, numberStyle: .decimal, decimalPlaces: 4)
        print("••• Formatted Result (10 EUR to GBP): \(formattedResult!) •••")
    })
}
</code>```

}

If you want to learn how to make it, you can study the Swift code here: https://github.com/ThiagoAM/CurrencyConverter/blob/master/CurrencyConverter.swift

It's basically a XML parser that fetches the data from the following source: https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml

Title: Creating a currency converter in Swift

Body:
I am trying to make a currency converter in Swift. I saw this post: Need API for currency converting and How to make an HTTP request in Swift?.

So when I combined them together:

let url = NSURL(string: "http://download.finance.yahoo.com/d/quotes.csv?s=USDEUR=X&f=nl1d1t1");

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
     println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

task.resume()

It returns me a output as such:

Optional("USD to EUR",0.7987,"11/20/2014","3:45am")

But I want to access the currency exchange rate. How do I do that? I am not sure how to do that?

Body:
I've made a simpler currency converter in Swift 5. If you're interested, check it out in my GitHub: https://github.com/ThiagoAM/CurrencyConverter

The usage is really simple:

class ViewController: UIViewController {

// Creates the Currency Converter instance:
let currencyConverter = CurrencyConverter()

override func viewDidLoad() {
    super.viewDidLoad()

    // Updates the exchange rates:
    currencyConverter.updateExchangeRates(completion: {
        // The code inside here runs after all the data is fetched.

        // Now you can convert any currency:
        // • Example_1 (USD to EUR):
        let doubleResult = self.currencyConverter.convert(10, valueCurrency: .USD, outputCurrency: .EUR)
        print("••• 10 USD = \(doubleResult!) EUR •••")

        // • Example_2 (EUR to GBP) - Returning a formatted String:
        let formattedResult = self.currencyConverter.convertAndFormat(10, valueCurrency: .EUR, outputCurrency: .GBP, numberStyle: .decimal, decimalPlaces: 4)
        print("••• Formatted Result (10 EUR to GBP): \(formattedResult!) •••")
    })
}

}

If you want to learn how to make it, you can study the Swift code here: https://github.com/ThiagoAM/CurrencyConverter/blob/master/CurrencyConverter.swift

It's basically a XML parser that fetches the data from the following source: https://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml


问:
How to concatenate string in _bstr_t and wchar_t?
I have _bstr_t string and I have wchar_t and one unsigned int variables which I want to put to the string...

```<code>_bstr_t strCnn("Driver={SQL Server};Server=some_host,some_port;Database=some_db;User ID=some_user;Password=some_psw;");

wchar_t *host,
unsigned int port,
wchar_t *db_name,
wchar_t *user,
wchar_t *password,
</code>```

These 5 variables I pass to the function which does connection. Can you please guide me how to insert them to connection string.

I tried this way:

```<code>    wstring ws(host);
    string host_str(ws.begin(), ws.end());
    wstring ws_db(db_name);
    string db_str(ws_db.begin(), ws_db.end());
    wstring ws_user(user);
    string user_str(ws_user.begin(), ws_user.end());
    wstring ws_psw(password);
    string psw_str(ws_psw.begin(), ws_psw.end());

    std::string port_str = std::to_string(port);
    _bstr_t strCnn("Driver={SQL Server};Server="+host_str+","+port_str+";Database="+db_str+";User ID="+user_str+";Password="+psw_str+";");
</code>```

But it says:

```<code>Error E0289 no instance of constructor "_bstr_t::_bstr_t" matches the argument list
Error C2664 '_bstr_t::_bstr_t(const _bstr_t &) throw()': cannot convert argument 1 from 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'const char *'
</code>```

答:
Perhaps the easiest way would be to use std::wstringstream.

Your code could then look something like:

```<code>    std::wstringstream ws;
    ws << "Driver={SQL Server};Server=" << host << "," << port << ";Database=" << db << ";User ID=" << user << ";Password=" << pswr <<";";
    _bstr_t strCnn(ws.str().c_str());
</code>```

The constructor of _bstr_t takes a const wchar_t* so no need to do any intermediary conversions.

Body:
I have _bstr_t string and I have wchar_t and one unsigned int variables which I want to put to the string...

_bstr_t strCnn("Driver={SQL Server};Server=some_host,some_port;Database=some_db;User ID=some_user;Password=some_psw;");

wchar_t *host,
unsigned int port,
wchar_t *db_name,
wchar_t *user,
wchar_t *password,

These 5 variables I pass to the function which does connection. Can you please guide me how to insert them to connection string.

I tried this way:

    wstring ws(host);
    string host_str(ws.begin(), ws.end());
    wstring ws_db(db_name);
    string db_str(ws_db.begin(), ws_db.end());
    wstring ws_user(user);
    string user_str(ws_user.begin(), ws_user.end());
    wstring ws_psw(password);
    string psw_str(ws_psw.begin(), ws_psw.end());

    std::string port_str = std::to_string(port);
    _bstr_t strCnn("Driver={SQL Server};Server="+host_str+","+port_str+";Database="+db_str+";User ID="+user_str+";Password="+psw_str+";");

But it says:

Error E0289 no instance of constructor "_bstr_t::_bstr_t" matches the argument list
Error C2664 '_bstr_t::_bstr_t(const _bstr_t &) throw()': cannot convert argument 1 from 'std::basic_string<char,std::char_traits<char>,std::allocator<char>>' to 'const char *'

Body:
Perhaps the easiest way would be to use std::wstringstream.

Your code could then look something like:

    std::wstringstream ws;
    ws << "Driver={SQL Server};Server=" << host << "," << port << ";Database=" << db << ";User ID=" << user << ";Password=" << pswr <<";";
    _bstr_t strCnn(ws.str().c_str());

The constructor of _bstr_t takes a const wchar_t* so no need to do any intermediary conversions.


问:
Reading json file in pyspark with out changing old schema
I received the json every day with 10 attributes but some days if any attribute has no value they will send the 9 attributes and 10th attribute has not there in json. How can I read the json file in pyspark without changing old table schema</p>

答:
It seems like you should enforce a schema when reading the files.
I'm assuming you have something like this:

```<code>df = spark.read.json(path_to_json_files)
</code>```

In order to preserve all the attributes/fields, use the schema like so:

```<code>df = spark.read.schema(file_schema).json(path_to_json_files)
</code>```

To get the file_schema you can use an old file(s) that you know every attribute is available:

```<code>file_schema = spark.read.json(full_json_file).schema
</code>```

Body:
It seems like you should enforce a schema when reading the files.
I'm assuming you have something like this:

df = spark.read.json(path_to_json_files)

In order to preserve all the attributes/fields, use the schema like so:

df = spark.read.schema(file_schema).json(path_to_json_files)

To get the file_schema you can use an old file(s) that you know every attribute is available:

file_schema = spark.read.json(full_json_file).schema


问:
Sum and joined column data in same query
I am using Oracle DB and have the following query which throws the error:

ORA-00937: not a single-group group function

Query:

```<code>select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText';
</code>```

If I try to access the following individually, it works. As in calling sum separately, ct.CREAT_TS separately and so on.

The issue seems to be calling sum in this query. I plan to capture the output in an Object (Java if relevant). I expected the query to output  following. Is it possible to achieve this?

```<code>CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   8
2019-04-02 02:56:14.530000    SOME_EVENT 2
</code>```

After Given answers, getting following results where the sum value is split per column:

```<code>CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   2
2019-04-02 02:56:14.530000    SOME_EVENT 2   6
</code>```

答:
You need to include group by clause.

```<code>select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText'
    group by ct.CREAT_TS, ev.EVENT;
</code>```

Body:
I am using Oracle DB and have the following query which throws the error:

ORA-00937: not a single-group group function

Query:

select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText';

If I try to access the following individually, it works. As in calling sum separately, ct.CREAT_TS separately and so on.

The issue seems to be calling sum in this query. I plan to capture the output in an Object (Java if relevant). I expected the query to output  following. Is it possible to achieve this?

CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   8
2019-04-02 02:56:14.530000    SOME_EVENT 2

After Given answers, getting following results where the sum value is split per column:

CREAT_TS                      EVENT          sum(ct.TOT_CT)
2019-04-02 01:33:46.227000    SOME_EVENT 1   2
2019-04-02 02:56:14.530000    SOME_EVENT 2   6

Body:
You need to include group by clause.

select sum(ct.TOT_CT), ct.CREAT_TS, ev.EVENT
    from REF_CT ct
    inner join EVENT ev on ev.EVENT_TYPE_ID = ct.EVENT_TYPE_ID
    where ct.TX = 'SomeText'
    group by ct.CREAT_TS, ev.EVENT;


问:
Tensorflow Agent that choose random action
I want to create agent using tensorflow. I have 9 categories of action: roll, roll left, roll right, brake ... etc. The output from tensorflow pipeline is array[9]. Base on that I will simulate pushing combination of WSAD. Sometimes however I want to choose random action but not completely random but based on dense softmax output. Function that does exactly what I want is numpy.random.multinomial. However tensorflow.random.multinomial returns only index of chosen action not tensor with dimensions same as input. I tried to save actions and feed them later in teach phase to agent however example which I based on would need to feed action during playing phase which I dont want.
I know that this is possible using tensorflow.cond and tesorflow.equal but pipeline will look like mess and Iam not sure about performance. Is other words is there in tensorflow function that behaves like numpy.random.multinomial or there is a reason why  there is none and architecture of my agent is not correct?

Agent itself:

 class agentY():
    def __init__(self,lr,s_size,a_size,h_size):
        self.state_in = tf.placeholder(shape = [None]+list(s_size),dtype=tf.float32)
        conv1         = tf.layers.conv2d(self.state_in,32,4,strides=(4, 4))
        max_pool1     = tf.layers.max_pooling2d(conv1,32,4)
        flatten       = tf.layers.flatten(max_pool1)
        hidden        = tf.layers.dense(flatten,4096,activation=tf.nn.tanh)

        hidden_action       = tf.layers.dense(hidden,2048, activation=tf.nn.elu)
        self.action         = tf.layers.dense(hidden_action,9, activation=tf.nn.softmax)

        self.action_in      = tf.placeholder(shape =[None,9],dtype=tf.float32, name='acin')
        cross_entropy       = tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.action_in,
                                                                  logits=self.action)
        optimizer             = tf.train.AdamOptimizer(lr)
        grads_and_vars = optimizer.compute_gradients(cross_entropy)

        self.gradients = [grad for grad, variable in grads_and_vars]
        self.gradient_placeholders = []
        grads_and_vars_feed = []
        for grad, variable in grads_and_vars:
            gradient_placeholder = tf.placeholder(tf.float32, shape=grad.get_shape())
            self.gradient_placeholders.append(gradient_placeholder)
            grads_and_vars_feed.append((gradient_placeholder, variable))
        self.training_op = optimizer.apply_gradients(grads_and_vars_feed)
```

<p>Playing phase:</p>

<pre class="lang-py prettyprint-override"><code>    state = get_state()
    action = sess.run([myAgent.action], feed_dict={myAgent.state_in:[state]}) #
    action = numpy.random.multinomial(1,action[0][0])
    if do_action:
        releaseKeys();
        update_pressed_keys(categoriesToKeys(action))

    reward = reward + delta_time
    current_rewards.append(reward)
    current_gradients.append(myAgent.gradients)
</code>```

Teach phase:

    def teach_agent(agent, all_rewards, all_gradients,sess):
        rewards = np.array(discount_and_normalize_rewards(all_rewards,0.99))
        test = []
        feed_dict = {}
        for var_index, gradient_placeholder in enumerate(agent.gradient_placeholders):
            mean_gradients = np.mean([reward * all_gradients[game_index][step][var_index]
                                      for game_index, rewards in enumerate(all_rewards)
                                          for step, reward in enumerate(rewards)], axis=0)
            feed_dict[gradient_placeholder] = mean_gradients
        sess.run(agent.training_op, feed_dict=feed_dict)
```

Teach phase is not yet tested. This code is based on book  "Hands-On Machine Learning with Scikit-Learn and TensorFlow"

答:
I managed to run tensorflow.nn.softmax_cross_entropy_with_logits_v2() with labels and logits with shape [None,1] where this tensor is index of action (category). I had a GPU-side crash and realized that I was wrong entire time and forgot about one of the most important function: one-hot encoding. I used multinomial to compute index and than one-hot encoded result. The example below:

import tensorflow as tf
import numpy as np

p = tf.placeholder(shape = [None,4],dtype=tf.float32)
t = tf.nn.softmax(p)
t1      = tf.random.categorical(tf.log(t),1)
t2 = tf.one_hot(t1, 4,
           on_value=1.0, off_value=0.0,
           axis=-1)

with tf.Session() as sess:
    inArray = [[0.8,0.5,0.1,0.2]]
    index, outArray = sess.run([t1,t2],feed_dict={p:inArray})
    print("Index:",index)
    print("Array:",outArray)
```

<p>This was of course rookie mistake, Iam new to ML and had hard time understading tensor flow.
Now Agent looks like that:</p>

<pre class="lang-py prettyprint-override"><code>class agentY():
    def __init__(self,lr,s_size,a_size,h_size):
        self.state_in = tf.placeholder(shape = [None]+list(s_size),dtype=tf.float32)
        conv1         = tf.layers.conv2d(self.state_in,32,4,strides=(4, 4))
        max_pool1     = tf.layers.max_pooling2d(conv1,32,4)
        flatten       = tf.layers.flatten(max_pool1)
        hidden        = tf.layers.dense(flatten,4096,activation=tf.nn.tanh)

        hidden_action       = tf.layers.dense(hidden,2048, activation=tf.nn.elu)
        self.action_logits  = tf.layers.dense(hidden_action,9, activation=tf.nn.softmax)
        self.action_out     = tf.one_hot(tf.multinomial(self.action_logits,1), 9,on_value=1.0, off_value=0.0,axis=-1)
        cross_entropy       = tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.action_out,
                                                                  logits=self.action_logits)
        optimizer             = tf.train.AdamOptimizer(lr)
        grads_and_vars = optimizer.compute_gradients(cross_entropy)

        self.gradients = [grad for grad, variable in grads_and_vars]
        self.gradient_placeholders = []
        grads_and_vars_feed = []
        for grad, variable in grads_and_vars:
            gradient_placeholder = tf.placeholder(tf.float32, shape=grad.get_shape())
            self.gradient_placeholders.append(gradient_placeholder)
            grads_and_vars_feed.append((gradient_placeholder, variable))
        self.training_op = optimizer.apply_gradients(grads_and_vars_feed)

tf.reset_default_graph()
testAgent = agentY(0.1,(300,400,1),9,11)
</code>```

The problem now is that Iam harvesting gradients every Agent decision. It take enormous amount of RAM and Iam sure not recomended. Take a look below:

while True:
    time0 = time.time()
    #-----------------zzx
    if collectData:
        state = get_state()
        action_out, gradients = sess.run([myAgent.action_out,myAgent.gradients], feed_dict={myAgent.state_in:[state]})

        if do_action:
            releaseKeys();
            update_pressed_keys(categoriesToKeys(action))

        reward = reward + delta_time
        current_rewards.append(reward)
        current_gradients.append(gradients)
```

I later will use these gradients in function teach_agent() to introduce reward into Agent's network. (teach_agent is posted in original post). Before I return to book and will try to understand next example of Q-Learning Agent could somebody (if this is possible) in easy way explain other way for Q-Learning or Reinforce Learning?

Body:
I want to create agent using tensorflow. I have 9 categories of action: roll, roll left, roll right, brake ... etc. The output from tensorflow pipeline is array[9]. Base on that I will simulate pushing combination of WSAD. Sometimes however I want to choose random action but not completely random but based on dense softmax output. Function that does exactly what I want is numpy.random.multinomial. However tensorflow.random.multinomial returns only index of chosen action not tensor with dimensions same as input. I tried to save actions and feed them later in teach phase to agent however example which I based on would need to feed action during playing phase which I dont want.
I know that this is possible using tensorflow.cond and tesorflow.equal but pipeline will look like mess and Iam not sure about performance. Is other words is there in tensorflow function that behaves like numpy.random.multinomial or there is a reason why  there is none and architecture of my agent is not correct?

Agent itself:

 class agentY():
    def __init__(self,lr,s_size,a_size,h_size):
        self.state_in = tf.placeholder(shape = [None]+list(s_size),dtype=tf.float32)
        conv1         = tf.layers.conv2d(self.state_in,32,4,strides=(4, 4))
        max_pool1     = tf.layers.max_pooling2d(conv1,32,4)
        flatten       = tf.layers.flatten(max_pool1)
        hidden        = tf.layers.dense(flatten,4096,activation=tf.nn.tanh)

        hidden_action       = tf.layers.dense(hidden,2048, activation=tf.nn.elu)
        self.action         = tf.layers.dense(hidden_action,9, activation=tf.nn.softmax)

        self.action_in      = tf.placeholder(shape =[None,9],dtype=tf.float32, name='acin')
        cross_entropy       = tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.action_in,
                                                                  logits=self.action)
        optimizer             = tf.train.AdamOptimizer(lr)
        grads_and_vars = optimizer.compute_gradients(cross_entropy)

        self.gradients = [grad for grad, variable in grads_and_vars]
        self.gradient_placeholders = []
        grads_and_vars_feed = []
        for grad, variable in grads_and_vars:
            gradient_placeholder = tf.placeholder(tf.float32, shape=grad.get_shape())
            self.gradient_placeholders.append(gradient_placeholder)
            grads_and_vars_feed.append((gradient_placeholder, variable))
        self.training_op = optimizer.apply_gradients(grads_and_vars_feed)

Playing phase:

    state = get_state()
    action = sess.run([myAgent.action], feed_dict={myAgent.state_in:[state]}) #
    action = numpy.random.multinomial(1,action[0][0])
    if do_action:
        releaseKeys();
        update_pressed_keys(categoriesToKeys(action))

    reward = reward + delta_time
    current_rewards.append(reward)
    current_gradients.append(myAgent.gradients)

Teach phase:

    def teach_agent(agent, all_rewards, all_gradients,sess):
        rewards = np.array(discount_and_normalize_rewards(all_rewards,0.99))
        test = []
        feed_dict = {}
        for var_index, gradient_placeholder in enumerate(agent.gradient_placeholders):
            mean_gradients = np.mean([reward * all_gradients[game_index][step][var_index]
                                      for game_index, rewards in enumerate(all_rewards)
                                          for step, reward in enumerate(rewards)], axis=0)
            feed_dict[gradient_placeholder] = mean_gradients
        sess.run(agent.training_op, feed_dict=feed_dict)

Teach phase is not yet tested. This code is based on book  "Hands-On Machine Learning with Scikit-Learn and TensorFlow"

Body:
I managed to run tensorflow.nn.softmax_cross_entropy_with_logits_v2() with labels and logits with shape [None,1] where this tensor is index of action (category). I had a GPU-side crash and realized that I was wrong entire time and forgot about one of the most important function: one-hot encoding. I used multinomial to compute index and than one-hot encoded result. The example below:

import tensorflow as tf
import numpy as np

p = tf.placeholder(shape = [None,4],dtype=tf.float32)
t = tf.nn.softmax(p)
t1      = tf.random.categorical(tf.log(t),1)
t2 = tf.one_hot(t1, 4,
           on_value=1.0, off_value=0.0,
           axis=-1)

with tf.Session() as sess:
    inArray = [[0.8,0.5,0.1,0.2]]
    index, outArray = sess.run([t1,t2],feed_dict={p:inArray})
    print("Index:",index)
    print("Array:",outArray)

This was of course rookie mistake, Iam new to ML and had hard time understading tensor flow.
Now Agent looks like that:

class agentY():
    def __init__(self,lr,s_size,a_size,h_size):
        self.state_in = tf.placeholder(shape = [None]+list(s_size),dtype=tf.float32)
        conv1         = tf.layers.conv2d(self.state_in,32,4,strides=(4, 4))
        max_pool1     = tf.layers.max_pooling2d(conv1,32,4)
        flatten       = tf.layers.flatten(max_pool1)
        hidden        = tf.layers.dense(flatten,4096,activation=tf.nn.tanh)

        hidden_action       = tf.layers.dense(hidden,2048, activation=tf.nn.elu)
        self.action_logits  = tf.layers.dense(hidden_action,9, activation=tf.nn.softmax)
        self.action_out     = tf.one_hot(tf.multinomial(self.action_logits,1), 9,on_value=1.0, off_value=0.0,axis=-1)
        cross_entropy       = tf.nn.softmax_cross_entropy_with_logits_v2(labels=self.action_out,
                                                                  logits=self.action_logits)
        optimizer             = tf.train.AdamOptimizer(lr)
        grads_and_vars = optimizer.compute_gradients(cross_entropy)

        self.gradients = [grad for grad, variable in grads_and_vars]
        self.gradient_placeholders = []
        grads_and_vars_feed = []
        for grad, variable in grads_and_vars:
            gradient_placeholder = tf.placeholder(tf.float32, shape=grad.get_shape())
            self.gradient_placeholders.append(gradient_placeholder)
            grads_and_vars_feed.append((gradient_placeholder, variable))
        self.training_op = optimizer.apply_gradients(grads_and_vars_feed)

tf.reset_default_graph()
testAgent = agentY(0.1,(300,400,1),9,11)

The problem now is that Iam harvesting gradients every Agent decision. It take enormous amount of RAM and Iam sure not recomended. Take a look below:

while True:
    time0 = time.time()
    #-----------------zzx
    if collectData:
        state = get_state()
        action_out, gradients = sess.run([myAgent.action_out,myAgent.gradients], feed_dict={myAgent.state_in:[state]})

        if do_action:
            releaseKeys();
            update_pressed_keys(categoriesToKeys(action))

        reward = reward + delta_time
        current_rewards.append(reward)
        current_gradients.append(gradients)

I later will use these gradients in function teach_agent() to introduce reward into Agent's network. (teach_agent is posted in original post). Before I return to book and will try to understand next example of Q-Learning Agent could somebody (if this is possible) in easy way explain other way for Q-Learning or Reinforce Learning?


问:
How to refresh or update a fragment after deleting from the database
I am new to android development, and i'm trying to build a simple hymn book,
I'm using bottom navigation, i use fragments on each tab to display numbers and titles of each hymn.
In my favourite fragments i have a list of favourite songs displayed using recycler view fetch from the database.
I use on long click listener to delete songs from the favorite table in the database, but any time i delete a
song my favorite fragment doesn't get refreshed or undated with current items. Please, how can I refresh or update
my favourite fragment anytime i delete a song. thank you!   </p>

<p>'''Favourite Adapter''</p>

```<code>import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

import static android.content.Context.MODE_PRIVATE;

public class FavouriteAdapter extends RecyclerView.Adapter<FavouriteAdapter.ViewHolder> {

    private Context favContext;
    private ArrayList<String> favNumbers = new ArrayList<>();
    private ArrayList<String> favTitles  = new ArrayList<>();

    public FavouriteAdapter(Context favContext, ArrayList<String> favNumbers, ArrayList<String> favTitles) {
        this.favContext = favContext;
        this.favNumbers = favNumbers;
        this.favTitles = favTitles;
    }

    @Override
    public FavouriteAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.favourite_list_items, parent, false);

        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final FavouriteAdapter.ViewHolder holder, final int position) {

        holder.textViewFavNum.setText(favNumbers.get(position));
        holder.textViewFavTitle.setText(favTitles.get(position));
        final String hymn_no = favNumbers.get(position);
        holder.itemView.setTag(favNumbers.get(position));

        holder.favParentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i;
                i = new Intent(view.getContext(), Songs.class);
                i.putExtra("numId", favNumbers.get(position));
                i.putExtra("titleName", favTitles.get(position));
                favContext.startActivity(i);

            }
        });

      holder.favParentLayout.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(final View view) {
                new AlertDialog.Builder(view.getContext())
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle("Are you sure?")
                        .setMessage("Do you want to delete from favorites?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int which) {

                                try{

                                    SQLiteDatabase favHymns = favContext.openOrCreateDatabase("Songs", MODE_PRIVATE, null);

                                    favHymns.execSQL("DELETE FROM favorites where hymnNum = '"+hymn_no+"'");

                                    Toast.makeText(favContext.getApplicationContext(), "hymn deleted ", Toast.LENGTH_LONG).show();

                                }catch(Exception e){
                                    e.printStackTrace();
                                }

                            }

                        })

                        .setNegativeButton("No", null)
                        .show();

                return true;

            }

        });

    }

    @Override
    public int getItemCount() {

        return favNumbers.size();

    }

    @Override
    public long getItemId(int position){
        return position;
    }

    @Override
    public int getItemViewType(int position){
        return position;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView textViewFavNum;
        public TextView textViewFavTitle;
        RelativeLayout favParentLayout;
        public ViewHolder(View itemView) {
            super(itemView);

            textViewFavNum = (TextView) itemView.findViewById(R.id.textViewFavNum);
            textViewFavTitle = (TextView) itemView.findViewById(R.id.textViewFavTitle);
            favParentLayout  =  (RelativeLayout) itemView.findViewById(R.id.favParentLayout);
        }
    }
}

'''favourite fragment'''

    import android.app.FragmentManager;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    import android.widget.Toast;

    import java.util.ArrayList;
    import java.util.logging.Handler;

    import static android.content.Context.MODE_PRIVATE;

    /**
     * A simple {@link Fragment} subclass.
     */
    public class Favourites extends Fragment {

        private RecyclerView recyclerView;
        private RecyclerView.Adapter adapter;
        private ArrayList<String> favSongNumbers = new ArrayList<>();
        private ArrayList<String> favSongTitles  = new ArrayList<>();
        private TextView favMessage;

        public Favourites() {
            // Required empty public constructor
        }

        View view;
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            if(view == null) {
                view = inflater.inflate(R.layout.fragment_favourites, container, false);
                favMessage = (TextView) view.findViewById(R.id.favMessage);
                recyclerView = (RecyclerView) view.findViewById(R.id.favRecyclerView);
                //  adapter.setHasStableIds(true);

                Toast.makeText(this.getActivity(), "Long press to delete hymns from favorites", Toast.LENGTH_LONG).show();

                initFavSongs();

            }

            return view;
        }

        private void initFavSongs(){

            try{

                favMessage.setText("");

                SQLiteDatabase favHymns = this.getActivity().openOrCreateDatabase("Songs", MODE_PRIVATE, null);

                Cursor c = favHymns.rawQuery("SELECT  hymnNum, hymnTitle FROM favorites", null);

                int hymnNumIndex = c.getColumnIndex("hymnNum");
                int hymnTitleIndex = c.getColumnIndex("hymnTitle");

                if(c.moveToFirst()) {

                    while (c != null) {

                        favSongNumbers.add(Integer.toString(c.getInt(hymnNumIndex)) + ". ");
                        favSongTitles.add(" " + c.getString(hymnTitleIndex));

                        c.moveToNext();
                    }

                }else{
                    favMessage.setText("Oops!No favorite songs added yet.");
                }

            }catch (Exception e){

                e.printStackTrace();

            }

            initRecyclerView();
        }

        private void initRecyclerView(){

            adapter = new FavouriteAdapter(this.getActivity(), favSongNumbers, favSongTitles);
            recyclerView.setAdapter(adapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
        }

    }
</code>```

答:
Pass a listener to the adapter and invoke it at the time of item delete from database. Then update your list and as well as your adapter.Like this way:

First create a listener:

```<code>public interface UpdateListener {

        void onValueChangedListener();
    }
</code>```

Initialize the listener in Adapter class that comes from fragment.

```<code>private UpdateListener updateListener;

     public FavouriteAdapter(Context favContext, ArrayList<String> favNumbers, ArrayList<String> favTitles,UpdateListener updateListener ) {
            this.favContext = favContext;
            this.favNumbers = favNumbers;
            this.favTitles = favTitles;
    this.updateListener=updateListener;

        }

    holder.favParentLayout.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(final View view) {
                    new AlertDialog.Builder(view.getContext())
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .setTitle("Are you sure?")
                            .setMessage("Do you want to delete from favorites?")
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int which) {

                                    try{

                                        SQLiteDatabase favHymns = favContext.openOrCreateDatabase("Songs", MODE_PRIVATE, null);

                                        favHymns.execSQL("DELETE FROM favorites where hymnNum = '"+hymn_no+"'");

                                        Toast.makeText(favContext.getApplicationContext(), "hymn deleted ", Toast.LENGTH_LONG).show();
// when any item delete from database notify the fragment through this
  //  listener for updating your adapter
    updateListener.onValueChangedListener();

                                    }catch(Exception e){
                                        e.printStackTrace();
                                    }

                                }

                            })

                            .setNegativeButton("No", null)
                            .show();

                    return true;

                }

            });
</code>```

// this method is needed for updating your adapter

```<code>public void update(ArrayList<String> favNumbers, ArrayList<String> favTitles){
this.favNumbers = favNumbers;
                this.favTitles = favTitles;
}
</code>```

Implement the listener in your fragment and reinitialize your list.

```<code>public class Favourites extends Fragment implements UpdateListener {

    private void initRecyclerView(){
// pass listener
        adapter = new FavouriteAdapter(this.getActivity(), favSongNumbers, favSongTitles,this);

    }

private void updateFavSongs(){

favSongNumbers.clear;
favSongTitles.clear;

            try{

                favMessage.setText("");

                SQLiteDatabase favHymns = this.getActivity().openOrCreateDatabase("Songs", MODE_PRIVATE, null);

                Cursor c = favHymns.rawQuery("SELECT  hymnNum, hymnTitle FROM favorites", null);

                int hymnNumIndex = c.getColumnIndex("hymnNum");
                int hymnTitleIndex = c.getColumnIndex("hymnTitle");

                if(c.moveToFirst()) {

                    while (c != null) {

                        favSongNumbers.add(Integer.toString(c.getInt(hymnNumIndex)) + ". ");
                        favSongTitles.add(" " + c.getString(hymnTitleIndex));

                        c.moveToNext();
                    }

                }else{
                    favMessage.setText("Oops!No favorite songs added yet.");
                }

            }catch (Exception e){

                e.printStackTrace();

            }
         adapter.update(favSongNumbers,favSongTitles);
         adapter.notifyDataSetChanged()

        }
    @Override
        public void onValueChangedListener(){
                    updateFavSongs();

    }
    }
</code>```

Body:
I am new to android development, and i'm trying to build a simple hymn book,
I'm using bottom navigation, i use fragments on each tab to display numbers and titles of each hymn.
In my favourite fragments i have a list of favourite songs displayed using recycler view fetch from the database.
I use on long click listener to delete songs from the favorite table in the database, but any time i delete a
song my favorite fragment doesn't get refreshed or undated with current items. Please, how can I refresh or update
my favourite fragment anytime i delete a song. thank you!

'''Favourite Adapter''

import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

import static android.content.Context.MODE_PRIVATE;

public class FavouriteAdapter extends RecyclerView.Adapter<FavouriteAdapter.ViewHolder> {

    private Context favContext;
    private ArrayList<String> favNumbers = new ArrayList<>();
    private ArrayList<String> favTitles  = new ArrayList<>();

    public FavouriteAdapter(Context favContext, ArrayList<String> favNumbers, ArrayList<String> favTitles) {
        this.favContext = favContext;
        this.favNumbers = favNumbers;
        this.favTitles = favTitles;
    }

    @Override
    public FavouriteAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.favourite_list_items, parent, false);

        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(final FavouriteAdapter.ViewHolder holder, final int position) {

        holder.textViewFavNum.setText(favNumbers.get(position));
        holder.textViewFavTitle.setText(favTitles.get(position));
        final String hymn_no = favNumbers.get(position);
        holder.itemView.setTag(favNumbers.get(position));

        holder.favParentLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i;
                i = new Intent(view.getContext(), Songs.class);
                i.putExtra("numId", favNumbers.get(position));
                i.putExtra("titleName", favTitles.get(position));
                favContext.startActivity(i);

            }
        });

      holder.favParentLayout.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(final View view) {
                new AlertDialog.Builder(view.getContext())
                        .setIcon(android.R.drawable.ic_dialog_alert)
                        .setTitle("Are you sure?")
                        .setMessage("Do you want to delete from favorites?")
                        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int which) {

                                try{

                                    SQLiteDatabase favHymns = favContext.openOrCreateDatabase("Songs", MODE_PRIVATE, null);

                                    favHymns.execSQL("DELETE FROM favorites where hymnNum = '"+hymn_no+"'");

                                    Toast.makeText(favContext.getApplicationContext(), "hymn deleted ", Toast.LENGTH_LONG).show();

                                }catch(Exception e){
                                    e.printStackTrace();
                                }

                            }

                        })

                        .setNegativeButton("No", null)
                        .show();

                return true;

            }

        });

    }

    @Override
    public int getItemCount() {

        return favNumbers.size();

    }

    @Override
    public long getItemId(int position){
        return position;
    }

    @Override
    public int getItemViewType(int position){
        return position;
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        public TextView textViewFavNum;
        public TextView textViewFavTitle;
        RelativeLayout favParentLayout;
        public ViewHolder(View itemView) {
            super(itemView);

            textViewFavNum = (TextView) itemView.findViewById(R.id.textViewFavNum);
            textViewFavTitle = (TextView) itemView.findViewById(R.id.textViewFavTitle);
            favParentLayout  =  (RelativeLayout) itemView.findViewById(R.id.favParentLayout);
        }
    }
}

'''favourite fragment'''

    import android.app.FragmentManager;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.app.FragmentTransaction;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.TextView;
    import android.widget.Toast;

    import java.util.ArrayList;
    import java.util.logging.Handler;

    import static android.content.Context.MODE_PRIVATE;

    /**
     * A simple {@link Fragment} subclass.
     */
    public class Favourites extends Fragment {

        private RecyclerView recyclerView;
        private RecyclerView.Adapter adapter;
        private ArrayList<String> favSongNumbers = new ArrayList<>();
        private ArrayList<String> favSongTitles  = new ArrayList<>();
        private TextView favMessage;

        public Favourites() {
            // Required empty public constructor
        }

        View view;
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            if(view == null) {
                view = inflater.inflate(R.layout.fragment_favourites, container, false);
                favMessage = (TextView) view.findViewById(R.id.favMessage);
                recyclerView = (RecyclerView) view.findViewById(R.id.favRecyclerView);
                //  adapter.setHasStableIds(true);

                Toast.makeText(this.getActivity(), "Long press to delete hymns from favorites", Toast.LENGTH_LONG).show();

                initFavSongs();

            }

            return view;
        }

        private void initFavSongs(){

            try{

                favMessage.setText("");

                SQLiteDatabase favHymns = this.getActivity().openOrCreateDatabase("Songs", MODE_PRIVATE, null);

                Cursor c = favHymns.rawQuery("SELECT  hymnNum, hymnTitle FROM favorites", null);

                int hymnNumIndex = c.getColumnIndex("hymnNum");
                int hymnTitleIndex = c.getColumnIndex("hymnTitle");

                if(c.moveToFirst()) {

                    while (c != null) {

                        favSongNumbers.add(Integer.toString(c.getInt(hymnNumIndex)) + ". ");
                        favSongTitles.add(" " + c.getString(hymnTitleIndex));

                        c.moveToNext();
                    }

                }else{
                    favMessage.setText("Oops!No favorite songs added yet.");
                }

            }catch (Exception e){

                e.printStackTrace();

            }

            initRecyclerView();
        }

        private void initRecyclerView(){

            adapter = new FavouriteAdapter(this.getActivity(), favSongNumbers, favSongTitles);
            recyclerView.setAdapter(adapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
        }

    }

Body:
Pass a listener to the adapter and invoke it at the time of item delete from database. Then update your list and as well as your adapter.Like this way:

First create a listener:

public interface UpdateListener {

        void onValueChangedListener();
    }

Initialize the listener in Adapter class that comes from fragment.

private UpdateListener updateListener;

     public FavouriteAdapter(Context favContext, ArrayList<String> favNumbers, ArrayList<String> favTitles,UpdateListener updateListener ) {
            this.favContext = favContext;
            this.favNumbers = favNumbers;
            this.favTitles = favTitles;
    this.updateListener=updateListener;

        }

    holder.favParentLayout.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(final View view) {
                    new AlertDialog.Builder(view.getContext())
                            .setIcon(android.R.drawable.ic_dialog_alert)
                            .setTitle("Are you sure?")
                            .setMessage("Do you want to delete from favorites?")
                            .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int which) {

                                    try{

                                        SQLiteDatabase favHymns = favContext.openOrCreateDatabase("Songs", MODE_PRIVATE, null);

                                        favHymns.execSQL("DELETE FROM favorites where hymnNum = '"+hymn_no+"'");

                                        Toast.makeText(favContext.getApplicationContext(), "hymn deleted ", Toast.LENGTH_LONG).show();
// when any item delete from database notify the fragment through this
  //  listener for updating your adapter
    updateListener.onValueChangedListener();

                                    }catch(Exception e){
                                        e.printStackTrace();
                                    }

                                }

                            })

                            .setNegativeButton("No", null)
                            .show();

                    return true;

                }

            });

// this method is needed for updating your adapter

public void update(ArrayList<String> favNumbers, ArrayList<String> favTitles){
this.favNumbers = favNumbers;
                this.favTitles = favTitles;
}

Implement the listener in your fragment and reinitialize your list.

public class Favourites extends Fragment implements UpdateListener {

    private void initRecyclerView(){
// pass listener
        adapter = new FavouriteAdapter(this.getActivity(), favSongNumbers, favSongTitles,this);

    }

private void updateFavSongs(){

favSongNumbers.clear;
favSongTitles.clear;

            try{

                favMessage.setText("");

                SQLiteDatabase favHymns = this.getActivity().openOrCreateDatabase("Songs", MODE_PRIVATE, null);

                Cursor c = favHymns.rawQuery("SELECT  hymnNum, hymnTitle FROM favorites", null);

                int hymnNumIndex = c.getColumnIndex("hymnNum");
                int hymnTitleIndex = c.getColumnIndex("hymnTitle");

                if(c.moveToFirst()) {

                    while (c != null) {

                        favSongNumbers.add(Integer.toString(c.getInt(hymnNumIndex)) + ". ");
                        favSongTitles.add(" " + c.getString(hymnTitleIndex));

                        c.moveToNext();
                    }

                }else{
                    favMessage.setText("Oops!No favorite songs added yet.");
                }

            }catch (Exception e){

                e.printStackTrace();

            }
         adapter.update(favSongNumbers,favSongTitles);
         adapter.notifyDataSetChanged()

        }
    @Override
        public void onValueChangedListener(){
                    updateFavSongs();

    }
    }


问:
Transactionscope throwing exception this platform does not support distributed transactions while opening connection object
TransactionScope is throwing a exception in .net core 2.2

In this example I created a scope of TransactioScop.
Opening SQL transaction for one database which is working fine.

After the first transaction I´m calling commit which will commit the SQL transaction.
I try to open call transaction for another database while creating a transaction and the system is throwing an exception

This platform does not support distributed transactions.

tried to remove SQL transaction

c#

```<code>using (TransactionScope scop =new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
    _db1UOW.Begin(); //creating sql transaction
    await _db1UOW.IDenialDetailsRepositorydb1.InsertDenialDetails(denialsDetails);
    await _db1UOW.IRuleDetailsRepositorydb1.InsertRulesDetails(rulesDetails);
    _db1UOW.Commit(); //commitng sql transaction

    _db2UOW.Begin(); //creating sql transaction (but while opening connection object its throwing exception as This platform does not support distributed transactions)
    await _db2UOW.IRuleDetailsRepository.GetRulesDetails();
    await _db2UOW.IDenialDetailsRepository.InsertDenialDetails(denialsDetails);
    var data = await _db2UOW.IRuleDetailsRepository.InsertRulesDetails(rulesDetails);
    _db2UOW.Commit(); //commitng sql transaction
    scop.Complete();
}
</code>```

Message

```<code>"This platform does not support distributed transactions."  at System.Transactions.Distributed.DistributedTransactionManager.GetDistributedTransactionFromTransmitterPropagationToken(Byte[] propagationToken)
   at System.Transactions.TransactionInterop.GetDistributedTransactionFromTransmitterPropagationToken(Byte[] propagationToken)
   at System.Transactions.TransactionStatePSPEOperation.PSPEPromote(InternalTransaction tx)
   at System.Transactions.TransactionStateDelegatedBase.EnterState(InternalTransaction tx)
   at System.Transactions.EnlistableStates.Promote(InternalTransaction tx)
   at System.Transactions.Transaction.Promote()
   at System.Transactions.TransactionInterop.ConvertToDistributedTransaction(Transaction transaction)
   at System.Transactions.TransactionInterop.GetExportCookie(Transaction transaction, Byte[] whereabouts)
   at System.Data.SqlClient.SqlInternalConnection.GetTransactionCookie(Transaction transaction, Byte[] whereAbouts)
   at System.Data.SqlClient.SqlInternalConnection.EnlistNonNull(Transaction tx)
   at System.Data.SqlClient.SqlInternalConnection.Enlist(Transaction tx)
   at System.Data.SqlClient.SqlInternalConnectionTds.Activate(Transaction transaction)
   at System.Data.ProviderBase.DbConnectionPool.PrepareConnection(DbConnection owningObject, DbConnectionInternal obj, Transaction transaction)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()
</code>```

答:
.NET Core doesn't support Distributed Transactions because it would require a different transaction manager on each platform.  It may appear in the future (here's the issue in-progress), but for now any Transaction that would require two different resource managers will throw this exception.

Instead you can coordinate separate transactions.  Have two separate transactions complete their work, and then commit them both.  There is a possibility that the first commit succeeds and the second one fails, but for SQL Server (with one exception), that would be a very rare occurance.  Something like:

```<code>_db1UOW.Begin(); //creating sql transaction
await _db1UOW.IDenialDetailsRepositorydb1.InsertDenialDetails(denialsDetails);
await _db1UOW.IRuleDetailsRepositorydb1.InsertRulesDetails(rulesDetails);

_db2UOW.Begin(); //creating sql transaction
await _db2UOW.IRuleDetailsRepository.GetRulesDetails();
await _db2UOW.IDenialDetailsRepository.InsertDenialDetails(denialsDetails);
var data = await _db2UOW.IRuleDetailsRepository.InsertRulesDetails(rulesDetails);

_db1UOW.Commit(); //commitng sql transaction
try
{
    _db2UOW.Commit(); //commitng sql transaction
}
catch (Exception ex)
{
     LogError("Second transaction failed to commit after first one committed.  Administrators may need to fix stuff");
     throw;
}
</code>```

Or if the two databases are on the same server you can use cross-database queries with a single SqlConnection to enlist the changes in a single SQL Server transaction.

Body:
TransactionScope is throwing a exception in .net core 2.2

In this example I created a scope of TransactioScop.
Opening SQL transaction for one database which is working fine.

After the first transaction I´m calling commit which will commit the SQL transaction.
I try to open call transaction for another database while creating a transaction and the system is throwing an exception

This platform does not support distributed transactions.

tried to remove SQL transaction

c#

using (TransactionScope scop =new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
{
    _db1UOW.Begin(); //creating sql transaction
    await _db1UOW.IDenialDetailsRepositorydb1.InsertDenialDetails(denialsDetails);
    await _db1UOW.IRuleDetailsRepositorydb1.InsertRulesDetails(rulesDetails);
    _db1UOW.Commit(); //commitng sql transaction

    _db2UOW.Begin(); //creating sql transaction (but while opening connection object its throwing exception as This platform does not support distributed transactions)
    await _db2UOW.IRuleDetailsRepository.GetRulesDetails();
    await _db2UOW.IDenialDetailsRepository.InsertDenialDetails(denialsDetails);
    var data = await _db2UOW.IRuleDetailsRepository.InsertRulesDetails(rulesDetails);
    _db2UOW.Commit(); //commitng sql transaction
    scop.Complete();
}

Message

"This platform does not support distributed transactions."  at System.Transactions.Distributed.DistributedTransactionManager.GetDistributedTransactionFromTransmitterPropagationToken(Byte[] propagationToken)
   at System.Transactions.TransactionInterop.GetDistributedTransactionFromTransmitterPropagationToken(Byte[] propagationToken)
   at System.Transactions.TransactionStatePSPEOperation.PSPEPromote(InternalTransaction tx)
   at System.Transactions.TransactionStateDelegatedBase.EnterState(InternalTransaction tx)
   at System.Transactions.EnlistableStates.Promote(InternalTransaction tx)
   at System.Transactions.Transaction.Promote()
   at System.Transactions.TransactionInterop.ConvertToDistributedTransaction(Transaction transaction)
   at System.Transactions.TransactionInterop.GetExportCookie(Transaction transaction, Byte[] whereabouts)
   at System.Data.SqlClient.SqlInternalConnection.GetTransactionCookie(Transaction transaction, Byte[] whereAbouts)
   at System.Data.SqlClient.SqlInternalConnection.EnlistNonNull(Transaction tx)
   at System.Data.SqlClient.SqlInternalConnection.Enlist(Transaction tx)
   at System.Data.SqlClient.SqlInternalConnectionTds.Activate(Transaction transaction)
   at System.Data.ProviderBase.DbConnectionPool.PrepareConnection(DbConnection owningObject, DbConnectionInternal obj, Transaction transaction)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection)
   at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions)
   at System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
   at System.Data.SqlClient.SqlConnection.Open()

Body:
.NET Core doesn't support Distributed Transactions because it would require a different transaction manager on each platform.  It may appear in the future (here's the issue in-progress), but for now any Transaction that would require two different resource managers will throw this exception.

Instead you can coordinate separate transactions.  Have two separate transactions complete their work, and then commit them both.  There is a possibility that the first commit succeeds and the second one fails, but for SQL Server (with one exception), that would be a very rare occurance.  Something like:

_db1UOW.Begin(); //creating sql transaction
await _db1UOW.IDenialDetailsRepositorydb1.InsertDenialDetails(denialsDetails);
await _db1UOW.IRuleDetailsRepositorydb1.InsertRulesDetails(rulesDetails);

_db2UOW.Begin(); //creating sql transaction
await _db2UOW.IRuleDetailsRepository.GetRulesDetails();
await _db2UOW.IDenialDetailsRepository.InsertDenialDetails(denialsDetails);
var data = await _db2UOW.IRuleDetailsRepository.InsertRulesDetails(rulesDetails);

_db1UOW.Commit(); //commitng sql transaction
try
{
    _db2UOW.Commit(); //commitng sql transaction
}
catch (Exception ex)
{
     LogError("Second transaction failed to commit after first one committed.  Administrators may need to fix stuff");
     throw;
}

Or if the two databases are on the same server you can use cross-database queries with a single SqlConnection to enlist the changes in a single SQL Server transaction.


问:
Parsing failing on python for nested avro structure
I have an avro structure which is expecting array structure. I have created the avro structure but the parsing my data into that avro schema is failing

Avro schema

```<code>{
  "namespace": "com",
  "type": "record",
  "name": "customers",
  "fields": [
    {
      "name": "customer",
      "type": {
        "type": "array",
        "items": {
          "name": "cust",
          "type": "record",
          "fields": [
            {
              "name": "age",
              "type": ["long","null"]
            },
            {
              "name": "amount",
              "type": [ "long","null"]
            }
          ]
        }
      }
    }
  ]
}
</code>```

Python Code

list= [[34,2000],[53,8000]]

for l in list

```<code>    writer.append({"customer":{ "age": long(l[0]), "amount": long(l[1])}})
</code>```

is my parsing wrong? should I add any datum object to array?

答:
Your schema defines the customers record as having an array of cust records. Therefore, your data should be structured like so:

```<code>{"customer": [cust1, cust2, ...]}
</code>```

and to expand further:

```<code>{"customer": [{"age": X1, "amount": Y1}, {"age": X2, "amount": Y2}, ...]}
</code>```

So you can keep your schema as is, but you will need to change the data you are inserting to match the format above. Alternatively, you could keep your data as is, but you would need to change the schema to the following:

```<code>{
  "namespace": "com",
  "type": "record",
  "name": "customers",
  "fields": [
    {
      "name": "customer",
      "type": {
        "name": "cust",
        "type": "record",
        "fields": [
          {
            "name": "age",
            "type": ["long","null"]
          },
          {
            "name": "amount",
            "type": [ "long","null"]
          }
        ]
      }
    }
  ]
}
</code>```

Body:
I have an avro structure which is expecting array structure. I have created the avro structure but the parsing my data into that avro schema is failing

Avro schema

{
  "namespace": "com",
  "type": "record",
  "name": "customers",
  "fields": [
    {
      "name": "customer",
      "type": {
        "type": "array",
        "items": {
          "name": "cust",
          "type": "record",
          "fields": [
            {
              "name": "age",
              "type": ["long","null"]
            },
            {
              "name": "amount",
              "type": [ "long","null"]
            }
          ]
        }
      }
    }
  ]
}

Python Code

list= [[34,2000],[53,8000]]

for l in list

    writer.append({"customer":{ "age": long(l[0]), "amount": long(l[1])}})

is my parsing wrong? should I add any datum object to array?

Body:
Your schema defines the customers record as having an array of cust records. Therefore, your data should be structured like so:

{"customer": [cust1, cust2, ...]}

and to expand further:

{"customer": [{"age": X1, "amount": Y1}, {"age": X2, "amount": Y2}, ...]}

So you can keep your schema as is, but you will need to change the data you are inserting to match the format above. Alternatively, you could keep your data as is, but you would need to change the schema to the following:

{
  "namespace": "com",
  "type": "record",
  "name": "customers",
  "fields": [
    {
      "name": "customer",
      "type": {
        "name": "cust",
        "type": "record",
        "fields": [
          {
            "name": "age",
            "type": ["long","null"]
          },
          {
            "name": "amount",
            "type": [ "long","null"]
          }
        ]
      }
    }
  ]
}


问:
How to replace elements in list/array with dictionary values?
I have following code:

```<code># dict for replacements
replacements = {'*': 0, ' ': 1, 'A': 2, 'B': 3}
# open and read file
file = open(file, "r")
lines = file.readlines()
file.close()
# row and col count
rows = len(lines)
cols = len(lines[0]) - 1
# create array
maze_array = np.zeros((rows, cols), dtype=str)
# add lines to array
for index, line in enumerate(lines):
    for i in range(0, len(line) - 1):
        maze_array[index][i] = line[i]
return maze_array
</code>```

This opens a file where the content is just '*', ' ', 'A' or 'B'. From that file I read the lines and get the number of rows as well as columns. Then I create a pseudo array where I add the lines to get following output:

```<code>[['*' ' ' '*' ... '*' ' ' '*']
['*' ' ' '*' ... ' ' 'B' '*']
['*' '*' '*' ... '*' '*' '*']]
</code>```

When I print out the variable lines above, I get following output:

```<code>['*****************************************************************\n', '...']
</code>```

Now my goal is to replace the '*', ' ', 'A' or 'B' with the values from the dictionary (0, 1, 2 or 3). How can I reach my goal?

Body:
I have following code:

# dict for replacements
replacements = {'*': 0, ' ': 1, 'A': 2, 'B': 3}
# open and read file
file = open(file, "r")
lines = file.readlines()
file.close()
# row and col count
rows = len(lines)
cols = len(lines[0]) - 1
# create array
maze_array = np.zeros((rows, cols), dtype=str)
# add lines to array
for index, line in enumerate(lines):
    for i in range(0, len(line) - 1):
        maze_array[index][i] = line[i]
return maze_array

This opens a file where the content is just '*', ' ', 'A' or 'B'. From that file I read the lines and get the number of rows as well as columns. Then I create a pseudo array where I add the lines to get following output:

[['*' ' ' '*' ... '*' ' ' '*']
['*' ' ' '*' ... ' ' 'B' '*']
['*' '*' '*' ... '*' '*' '*']]

When I print out the variable lines above, I get following output:

['*****************************************************************\n', '...']

Now my goal is to replace the '*', ' ', 'A' or 'B' with the values from the dictionary (0, 1, 2 or 3). How can I reach my goal?

Body:
You can use a list comprehension. Below is an example

lst = [['*', ' ', '*', '*', ' ', '*'],
       ['*', ' ', '*', ' ', 'B', '*'],
       ['*', '*', '*','*', '*', '*']]

replacements = {'*': 0, ' ': 1, 'A': 2, 'B': 3}

new_lst = [[replacements[i] for i in sublst] for sublst in lst]
# [[0, 1, 0, 0, 1, 0], [0, 1, 0, 1, 3, 0], [0, 0, 0, 0, 0, 0]]