问:
Using ramda.js, how to replace a value in a nested structure?
I'm trying to leverage the technique shown here for replacing values in an object with ramda.js. Unlike the linked reference, my object has many more nesting layers, and so it fails.

In the following example, we have an object that details attractions in cities. First it specifies the cities, the we dive in into nyc, then to zoos, then StatenIslandZoo, and finally we get to zooInfo that holds two records for two animals. In each one, we have the aniaml's name in the value associated with the animal key. I want to correct the value's string by replacing it with another string and return a new copy of the entire cityAttractions object.

const cityAttractions = {
    "cities": {
        "nyc": {
            "towers": ["One World Trade Center", "Central Park Tower", "Empire State Building"],
            "zoos": {
                "CentralParkZoo": {},
                "BronxZoo": {},
                "StatenIslandZoo": {
                    "zooInfo": [
                        {
                            "animal": "zebra_typo", // <- replace with "zebra"
                            "weight": 100
                        },
                        {
                            "animal": "wrongstring_lion", // <- replace with "lion"
                            "weight": 1005
                        }
                    ]
                }
            }
        },
        "sf": {},
        "dc": {}
    }
}
```
<p>So I defined a function very similar to this one:</p>
<pre class="lang-js prettyprint-override"><code>const R = require("ramda")

const myAlter = (myPath, whereValueEquals, replaceWith, obj) => R.map(
    R.when(R.pathEq(myPath, whereValueEquals), R.assocPath(myPath, replaceWith)),
    obj
)
</code>```

And then called myAlter() and stored the ouput into altered:

const altered = myAlter(["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo", "animal"], "zebra_typo", "zebra", cityAttractions)
```
<p>But when checking, I realize no replacement had happend:</p>
<pre class="lang-js prettyprint-override"><code>console.log(altered.cities.nyc.zoos.StatenIslandZoo.zooInfo)
// [
//   { animal: 'zebra_typo', weight: 100 },
//   { animal: 'wrongstring_lion', weight: 1005 }
// ]
</code>```

Some troubleshooting

If I we go back and examine the original cityAttractions object, then we can first extract just the level of cityAttractions.cities.nyc.zoos.StatenIslandZoo.zooInfo, then acting on that with myAlter() does work.

const ZooinfoExtraction = R.path(["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo"])(cityAttractions)
console.log(ZooinfoExtraction)
// [
//   { animal: 'zebra_typo', weight: 100 },
//   { animal: 'wrongstring_lion', weight: 1005 }
// ]

console.log(myAlter(["animal"], "zebra_typo", "zebra", ZooinfoExtraction))
// here it works!
// [
//   { animal: 'zebra', weight: 100 },
//   { animal: 'wrongstring_lion', weight: 1005 }
// ]
```
<p>So for some reason, <code>myAlter()</code> works on the extracted <code>ZooinfoExtraction</code> but not on the original <code>cityAttractions</code>. Which is a problem because I need the entire original structure (just replacing the specified values).</p>
<hr />
<p>EDIT - <em>troubleshooting 2</em></p>
<hr />
<p>I guess the problem relies in the fact that</p>
<pre class="lang-js prettyprint-override"><code>R.path(["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo", "animal"], cityAttractions)
</code>```

returns undefined.

答:
There main problem is that the animal property is part of an array item. Since array index should be a number, the path for Zebra is actually:

```<code>["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo", 0, "animal"]
</code>```

However, this will force you to know the actual index.

In addition, mapping an array returns a clone of the array (with the changes), and not the entire structure.

To solve this problem, you can use a lens (R.lensPath in this case) with R.over to return an updated clone of the entire structure.

Example:

const { curry, over, lensPath, map, when, pathEq, assoc } = R

const alterAnimal = curry((path, subPath, whereValueEquals, replaceWith, obj) =>
  over(
    lensPath(path),
    map(when(pathEq(subPath, whereValueEquals), assoc(subPath, replaceWith))),
    obj
  ))

const cityAttractions = {"cities":{"nyc":{"towers":["One World Trade Center","Central Park Tower","Empire State Building"],"zoos":{"CentralParkZoo":{},"BronxZoo":{},"StatenIslandZoo":{"zooInfo":[{"animal":"zebra_typo","weight":100},{"animal":"wrongstring_lion","weight":1005}]}}},"sf":{},"dc":{}}}

const altered = alterAnimal(
  ["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo"],
  ["animal"],
  "zebra_typo",
  "zebra",
  cityAttractions
)

console.log(altered)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper {max-height: 100% !important; top: 0}</code>```

```
</div>
</div>
</p>
<p>Since you transform an object's property value, you can also use <code>R.evolve</code>, and supply an update function that can cover all cases. For example:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const { curry, over, lensPath, map, evolve, flip, prop, __ } = R

const alterObj = curry((updateFn, prop, path, obj) =>
  over(
    lensPath(path),
    map(evolve({
      [prop]: updateFn
    })),
    obj
  ))

const replacements = {
  'zebra_typo': 'zebra',
  'wrongstring_lion': 'lion',
}

const alterAnimals = alterObj(prop(__, replacements))

const cityAttractions = {"cities":{"nyc":{"towers":["One World Trade Center","Central Park Tower","Empire State Building"],"zoos":{"CentralParkZoo":{},"BronxZoo":{},"StatenIslandZoo":{"zooInfo":[{"animal":"zebra_typo","weight":100},{"animal":"wrongstring_lion","weight":1005}]}}},"sf":{},"dc":{}}}

const altered = alterAnimals(
  "animal",
  ["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo"],
  cityAttractions
)

console.log(altered)</code>```

.as-console-wrapper {max-height: 100% !important; top: 0}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script></code>```

Body:
I'm trying to leverage the technique shown here for replacing values in an object with ramda.js. Unlike the linked reference, my object has many more nesting layers, and so it fails.

In the following example, we have an object that details attractions in cities. First it specifies the cities, the we dive in into nyc, then to zoos, then StatenIslandZoo, and finally we get to zooInfo that holds two records for two animals. In each one, we have the aniaml's name in the value associated with the animal key. I want to correct the value's string by replacing it with another string and return a new copy of the entire cityAttractions object.

const cityAttractions = {
    "cities": {
        "nyc": {
            "towers": ["One World Trade Center", "Central Park Tower", "Empire State Building"],
            "zoos": {
                "CentralParkZoo": {},
                "BronxZoo": {},
                "StatenIslandZoo": {
                    "zooInfo": [
                        {
                            "animal": "zebra_typo", // <- replace with "zebra"
                            "weight": 100
                        },
                        {
                            "animal": "wrongstring_lion", // <- replace with "lion"
                            "weight": 1005
                        }
                    ]
                }
            }
        },
        "sf": {},
        "dc": {}
    }
}

So I defined a function very similar to this one:

const R = require("ramda")

const myAlter = (myPath, whereValueEquals, replaceWith, obj) => R.map(
    R.when(R.pathEq(myPath, whereValueEquals), R.assocPath(myPath, replaceWith)),
    obj
)

And then called myAlter() and stored the ouput into altered:

const altered = myAlter(["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo", "animal"], "zebra_typo", "zebra", cityAttractions)

But when checking, I realize no replacement had happend:

console.log(altered.cities.nyc.zoos.StatenIslandZoo.zooInfo)
// [
//   { animal: 'zebra_typo', weight: 100 },
//   { animal: 'wrongstring_lion', weight: 1005 }
// ]

Some troubleshooting

If I we go back and examine the original cityAttractions object, then we can first extract just the level of cityAttractions.cities.nyc.zoos.StatenIslandZoo.zooInfo, then acting on that with myAlter() does work.

const ZooinfoExtraction = R.path(["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo"])(cityAttractions)
console.log(ZooinfoExtraction)
// [
//   { animal: 'zebra_typo', weight: 100 },
//   { animal: 'wrongstring_lion', weight: 1005 }
// ]

console.log(myAlter(["animal"], "zebra_typo", "zebra", ZooinfoExtraction))
// here it works!
// [
//   { animal: 'zebra', weight: 100 },
//   { animal: 'wrongstring_lion', weight: 1005 }
// ]

So for some reason, myAlter() works on the extracted ZooinfoExtraction but not on the original cityAttractions. Which is a problem because I need the entire original structure (just replacing the specified values).

EDIT - troubleshooting 2

I guess the problem relies in the fact that

R.path(["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo", "animal"], cityAttractions)

returns undefined.

Body:
There main problem is that the animal property is part of an array item. Since array index should be a number, the path for Zebra is actually:

["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo", 0, "animal"]

However, this will force you to know the actual index.

In addition, mapping an array returns a clone of the array (with the changes), and not the entire structure.

To solve this problem, you can use a lens (R.lensPath in this case) with R.over to return an updated clone of the entire structure.

Example:

const { curry, over, lensPath, map, when, pathEq, assoc } = R

const alterAnimal = curry((path, subPath, whereValueEquals, replaceWith, obj) =>
  over(
    lensPath(path),
    map(when(pathEq(subPath, whereValueEquals), assoc(subPath, replaceWith))),
    obj
  ))

const cityAttractions = {"cities":{"nyc":{"towers":["One World Trade Center","Central Park Tower","Empire State Building"],"zoos":{"CentralParkZoo":{},"BronxZoo":{},"StatenIslandZoo":{"zooInfo":[{"animal":"zebra_typo","weight":100},{"animal":"wrongstring_lion","weight":1005}]}}},"sf":{},"dc":{}}}

const altered = alterAnimal(
  ["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo"],
  ["animal"],
  "zebra_typo",
  "zebra",
  cityAttractions
)

console.log(altered)

.as-console-wrapper {max-height: 100% !important; top: 0}

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Since you transform an object's property value, you can also use R.evolve, and supply an update function that can cover all cases. For example:

const { curry, over, lensPath, map, evolve, flip, prop, __ } = R

const alterObj = curry((updateFn, prop, path, obj) =>
  over(
    lensPath(path),
    map(evolve({
      [prop]: updateFn
    })),
    obj
  ))

const replacements = {
  'zebra_typo': 'zebra',
  'wrongstring_lion': 'lion',
}

const alterAnimals = alterObj(prop(__, replacements))

const cityAttractions = {"cities":{"nyc":{"towers":["One World Trade Center","Central Park Tower","Empire State Building"],"zoos":{"CentralParkZoo":{},"BronxZoo":{},"StatenIslandZoo":{"zooInfo":[{"animal":"zebra_typo","weight":100},{"animal":"wrongstring_lion","weight":1005}]}}},"sf":{},"dc":{}}}

const altered = alterAnimals(
  "animal",
  ["cities", "nyc", "zoos", "StatenIslandZoo", "zooInfo"],
  cityAttractions
)

console.log(altered)

.as-console-wrapper {max-height: 100% !important; top: 0}

<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.28.0/ramda.min.js" integrity="sha512-t0vPcE8ynwIFovsylwUuLPIbdhDj6fav2prN9fEu/VYBupsmrmk9x43Hvnt+Mgn2h5YPSJOk7PMo9zIeGedD1A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


来源: stackexchange

问:
A comprehensive survey of the types of things in R; 'mode' and 'class' and 'typeof' are insufficient
The language R confuses me. Entities have modes and classes, but even this is insufficient to fully describe the entity.

This answer says

In R every 'object' has a mode and a class.

So I did these experiments:

```<code>> class(3)
[1] "numeric"
> mode(3)
[1] "numeric"
> typeof(3)
[1] "double"
</code>```

Fair enough so far, but then I passed in a vector instead:

```<code>> mode(c(1,2))
[1] "numeric"
> class(c(1,2))
[1] "numeric"
> typeof(c(1,2))
[1] "double"
</code>```

That doesn't make sense. Surely a vector of integers should have a different class, or different mode, than a single integer? My questions are:

Does everything in R have (exactly one) class ?

Does everything in R have (exactly one) mode ?

What, if anything, does 'typeof' tell us?

What other information is needed to fully describe an entity? (Where is the 'vectorness' stored, for example?)

Update: Apparently, a literal 3 is just a vector of length 1. There are no scalars. OK But... I tried mode("string") and got "character", leading me to think that a string was a vector of characters. But if that was true, then this should be true, but it's not! c('h','i') == "hi"

答:
This question deals with the confusion around all kinds of "types" in R. After reading this and quite a few other sites, in my opinion one comment by @RichieCotton best solves the confusion. It took me quite a while to encounter this comment and I want to highlight it by adding it as an answer.

[...] at this point, mode and storage.mode are legacy features left over from S. You should only ever need to care about class() and typeof().

So while reading other answers keep this in mind and focus on typeof and class. Unfortunately, in other posts it does not become obvious that mode and storage.mode should not be used. It would have saved me a lot of time reading this comment first.

ContentLicense: CC BY-SA 4.0

Body:
The language R confuses me. Entities have modes and classes, but even this is insufficient to fully describe the entity.

This answer says

In R every 'object' has a mode and a class.

So I did these experiments:

> class(3)
[1] "numeric"
> mode(3)
[1] "numeric"
> typeof(3)
[1] "double"

Fair enough so far, but then I passed in a vector instead:

> mode(c(1,2))
[1] "numeric"
> class(c(1,2))
[1] "numeric"
> typeof(c(1,2))
[1] "double"

That doesn't make sense. Surely a vector of integers should have a different class, or different mode, than a single integer? My questions are:

Does everything in R have (exactly one) class ?

Does everything in R have (exactly one) mode ?

What, if anything, does 'typeof' tell us?

What other information is needed to fully describe an entity? (Where is the 'vectorness' stored, for example?)

Update: Apparently, a literal 3 is just a vector of length 1. There are no scalars. OK But... I tried mode("string") and got "character", leading me to think that a string was a vector of characters. But if that was true, then this should be true, but it's not! c('h','i') == "hi"


问:
Variables get corrupted
I’m developing an iPhone App using Objective-C, based on Apple’s UIKit.

I’ve created some class instance in UIViewController and found my class instance pointer get corrupted randomly. Due to class instance pointer corrupted, I always get an EXC_BAD_ACCESS crash like this:
    Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
    Exception Codes: KERN_INVALID_ADDRESS at 0xa095633c
    Crashed Thread:  0

It shows that when my code is trying to access the class instance, it’s already turned into a ridiculous address:0xa095633c, which is beyond memory space and even binary image space.

Does any have any suggestion what kind of incorrect coding could possibly lead to class instance get corrupted?

答:
Did you try to retain the object when assigning to a variable?

A quick example:

```<code>variable = [[[UIViewController alloc] init] retain];
</code>```

Another solution could be to declare an instance variable as property with the attribute "retain":

```<code>@property(nonatomic, retain) UIViewController *variable;
</code>```

ContentLicense: CC BY-SA 3.0

Title: Variables get corrupted

Body:
Did you try to retain the object when assigning to a variable?

A quick example:

variable = [[[UIViewController alloc] init] retain];

Another solution could be to declare an instance variable as property with the attribute "retain":

@property(nonatomic, retain) UIViewController *variable;


问:
How to change between iframes in Selenium and Python
I was trying to understand how to change between iframes in selenium webdriver, but I could not figure it out.
In the image ahead, is the iframe that I want to switch to:

Snapshot:

答:
The website is Power BI based, so to switch within the  so you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

You can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='PowerBi Report Viewer']")))
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='PowerBi Report Viewer']")))
</code>```

Note : You have to add the following imports :

```<code> from selenium.webdriver.support.ui import WebDriverWait
 from selenium.webdriver.common.by import By
 from selenium.webdriver.support import expected_conditions as EC
</code>```

Reference

You can find a couple of relevant discussions in:

Switch to an iframe through Selenium and python

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element while trying to click Next button with selenium

selenium in python : NoSuchElementException: Message: no such element: Unable to locate element

Body:
The website is Power BI based, so to switch within the <iframe> so you have to:

Induce WebDriverWait for the desired frame to be available and switch to it.

You can use either of the following Locator Strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='PowerBi Report Viewer']")))

Using XPATH:

WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='PowerBi Report Viewer']")))

Note : You have to add the following imports :

 from selenium.webdriver.support.ui import WebDriverWait
 from selenium.webdriver.common.by import By
 from selenium.webdriver.support import expected_conditions as EC

Reference

You can find a couple of relevant discussions in:

Switch to an iframe through Selenium and python

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element while trying to click Next button with selenium

selenium in python : NoSuchElementException: Message: no such element: Unable to locate element


问:
Can not use Vulkan Subgroup operations in Android Studio
I'm writing a Vulkan compute shader in Android studio and launching it on Android phone. The problem I'm experiencing is next - I can not use any subgroup operations like subgroupAdd and subgroupElect. When I'm trying to use these functions I have an error like this:

reduce_vec.comp:35: error: 'subgroup op' : requires SPIR-V 1.3

I have checked - my Android phone supports subgroups, and my shader accepts such extensions:

```<code>#extension GL_KHR_shader_subgroup_arithmetic: enable
#extension GL_KHR_shader_subgroup_basic: enable
</code>```

The problem is pretty much straightforward, I need to update my SPIR-V. But according to my findings, SPIR-V that comes automatically with Android studio is not something I can update easily.

Did someone experience a similar issue before? What was your solution? Thanks in advance!

答:
Android solution

You can pass arguments to the Android shaderc compiler in your Gradle DSL:

https://developer.android.com/ndk/guides/graphics/shader-compilers

You need glslcArgs to contain --target-env=vulkan1.1

Flexible solution

Build your own compilation pipeline to compile from source into SPIR-V, and then include the SPIR-V binary files directly into your Android project.

There are multiple language front-ends that can generate SPIR-V, for GLSL the Khronos tools are here:

https://github.com/KhronosGroup/glslang

Body:
I'm writing a Vulkan compute shader in Android studio and launching it on Android phone. The problem I'm experiencing is next - I can not use any subgroup operations like subgroupAdd and subgroupElect. When I'm trying to use these functions I have an error like this:

reduce_vec.comp:35: error: 'subgroup op' : requires SPIR-V 1.3

I have checked - my Android phone supports subgroups, and my shader accepts such extensions:

#extension GL_KHR_shader_subgroup_arithmetic: enable
#extension GL_KHR_shader_subgroup_basic: enable

The problem is pretty much straightforward, I need to update my SPIR-V. But according to my findings, SPIR-V that comes automatically with Android studio is not something I can update easily.

Did someone experience a similar issue before? What was your solution? Thanks in advance!


问:
Is it possible to add a grouping label to a corrplot?
Is it possible to add a label that applies to a few variables in a corrplot? This is an example of what I'm after. In that case it is the word "Petals" on the y-axis.

Below is the code to make the rest of the plot.

```<code>library(corrplot)

library(Hmisc)

iris_c <- iris[, c(1:4)]

test <- rcorr(as.matrix(iris_c))

corrplot(test$r, type="lower", order= "original",
         p.mat = test$P, sig.level = 0.01, insig = "blank",
         col= colorRampPalette(c("blue","white", "red"))(100), tl.col = 'black', cl.ratio = 0.8, tl.srt = 45,  diag = FALSE, method = "square")
</code>```

答:
You can use title() to adjust axis labels, which is what you're looking for here. After running your code above, just run:

title(ylab = "Petals")
```

Body:
Is it possible to add a label that applies to a few variables in a corrplot? This is an example of what I'm after. In that case it is the word "Petals" on the y-axis.

Below is the code to make the rest of the plot.

library(corrplot)

library(Hmisc)

iris_c <- iris[, c(1:4)]

test <- rcorr(as.matrix(iris_c))

corrplot(test$r, type="lower", order= "original",
         p.mat = test$P, sig.level = 0.01, insig = "blank",
         col= colorRampPalette(c("blue","white", "red"))(100), tl.col = 'black', cl.ratio = 0.8, tl.srt = 45,  diag = FALSE, method = "square")


问:
Discrepancies on excel cell color reading and setting
I have a requirement to read the color of an excel sheet(sheet#1) cell and use that color while writing another excel sheet (sheet#2).
This sheet#1 is something like a template sheet with many other settings which is used to write the sheet#2.
This sheet#2 is a larger sheet with data and the columns will be colored as per the sheet#1.
And this is what I tried in a nut shell.

Used openpyxl to read the cell color..

```<code>df=pd.read_excel(excel_file, sheet_name='Sheet2')

wb = load_workbook(excel_file,data_only=True)
sh = wb['Sheet2']
lst_color=[]
for i in range(2,len(df.index)+2):
    color_index = str(sh['C'+str(i)].fill.start_color.index)
    if color_index.isnumeric() :
        color_in_hex = styles.colors.COLOR_INDEX[int(color_index)][2:] # First two bytes are Alpha
    else :
        color_in_hex = color_index[2:] # First two bytes are Alpha
    lst_color.append('#' + color_in_hex)
df.Color_Val=lst_color

print(df)
</code>```

And this is what I get as the colors..

Color_Name & XLSXWrite_Value are columns based on the xlsxwriter
And C column I have filled wiht corresponding colors in excel sheet.
for the xlswriter, this link shows what RGB codes to be passed for the corresponding colors.
https://xlsxwriter.readthedocs.io/working_with_colors.html

And then Color_val column is prepared with the above logic.

```<code>     Color_Name XLSXWriter_Value Color_Val
0      black          #000000   #FFFFFF
1       blue          #0000FF   #0070C0
2      green          #008000   #00B050
3     orange          #FF6600   #FFC000
4     purple          #800080   #7030A0
5        red          #FF0000   #FF0000
6      white          #FFFFFF   #000000
7     yellow          #FFFF00   #FFFF00
</code>```

So, what we get is totally different RGB color values.
(for Yellow & Red, it is same. White & black, they are reversed.)
Obviously, when I write the 2nd excel sheet with these RGB values (Color_Val), It will not get the same colors.

FYI : I use xlsxwriter for writing excel sheet.

```<code>writer = pd.ExcelWriter(dataFolder + 'tmp_12_test126.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer,sheet_name='Sheet1',index=False)

# Get the xlsxwriter workbook and worksheet objects.
worksheet = writer.sheets['Sheet1']
workbook  = writer.book

# Start iterating through the columns and the rows to apply the format
for col in range(df.shape[1]):
    for row in range(df.shape[0]):
        if len(col_format[col]) > 0 :
            worksheet.write(row+1,col,df.iloc[row,col],workbook.add_format(col_format[col]))

# Finally write the file
writer.save()
</code>```

This col_format list will look like something like the below.

```<code>col_format=[{},{'bg_color': '#FFFFFF', 'num_format': '@'}]
</code>```

So, what can I do to fulfill my requirement.

答:
I don't think you need to access the fill.start_color.index property since that is rarely used to hold a color index in the xlsx format (Note 1). Instead what you probably need is the fill.start_color.rgb.

color_index = str(sh['C'+str(i)].fill.start_color.rbg)
```

If in doubt you can check the fill.start_color.type first. It should be 'rgb'. Also, you won't need the if color_index.isnumeric(): check anymore.

One thing to look out for is to make sure that the template cells have a solid (i.e., non-patterned) fill. If it has a pattern fill then the background/foreground (start_color/end_color) color roles are reversed. However, since you are creating the template file it should be easy to specify a solid fill.

Note 1, for completeness: The color index is used to hold the default index 64 background color in solid fills; used for compatibility with older xls files; and used for some non-cell formatting like comments.

Body:
I have a requirement to read the color of an excel sheet(sheet#1) cell and use that color while writing another excel sheet (sheet#2).
This sheet#1 is something like a template sheet with many other settings which is used to write the sheet#2.
This sheet#2 is a larger sheet with data and the columns will be colored as per the sheet#1.
And this is what I tried in a nut shell.

Used openpyxl to read the cell color..

df=pd.read_excel(excel_file, sheet_name='Sheet2')

wb = load_workbook(excel_file,data_only=True)
sh = wb['Sheet2']
lst_color=[]
for i in range(2,len(df.index)+2):
    color_index = str(sh['C'+str(i)].fill.start_color.index)
    if color_index.isnumeric() :
        color_in_hex = styles.colors.COLOR_INDEX[int(color_index)][2:] # First two bytes are Alpha
    else :
        color_in_hex = color_index[2:] # First two bytes are Alpha
    lst_color.append('#' + color_in_hex)
df.Color_Val=lst_color

print(df)

And this is what I get as the colors..

Color_Name & XLSXWrite_Value are columns based on the xlsxwriter
And C column I have filled wiht corresponding colors in excel sheet.
for the xlswriter, this link shows what RGB codes to be passed for the corresponding colors.
https://xlsxwriter.readthedocs.io/working_with_colors.html

And then Color_val column is prepared with the above logic.

     Color_Name XLSXWriter_Value Color_Val
0      black          #000000   #FFFFFF
1       blue          #0000FF   #0070C0
2      green          #008000   #00B050
3     orange          #FF6600   #FFC000
4     purple          #800080   #7030A0
5        red          #FF0000   #FF0000
6      white          #FFFFFF   #000000
7     yellow          #FFFF00   #FFFF00

So, what we get is totally different RGB color values.
(for Yellow & Red, it is same. White & black, they are reversed.)
Obviously, when I write the 2nd excel sheet with these RGB values (Color_Val), It will not get the same colors.

FYI : I use xlsxwriter for writing excel sheet.

writer = pd.ExcelWriter(dataFolder + 'tmp_12_test126.xlsx', engine='xlsxwriter')

# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer,sheet_name='Sheet1',index=False)

# Get the xlsxwriter workbook and worksheet objects.
worksheet = writer.sheets['Sheet1']
workbook  = writer.book

# Start iterating through the columns and the rows to apply the format
for col in range(df.shape[1]):
    for row in range(df.shape[0]):
        if len(col_format[col]) > 0 :
            worksheet.write(row+1,col,df.iloc[row,col],workbook.add_format(col_format[col]))

# Finally write the file
writer.save()

This col_format list will look like something like the below.

col_format=[{},{'bg_color': '#FFFFFF', 'num_format': '@'}]

So, what can I do to fulfill my requirement.

Body:
I don't think you need to access the fill.start_color.index property since that is rarely used to hold a color index in the xlsx format (Note 1). Instead what you probably need is the fill.start_color.rgb.

color_index = str(sh['C'+str(i)].fill.start_color.rbg)

If in doubt you can check the fill.start_color.type first. It should be 'rgb'. Also, you won't need the if color_index.isnumeric(): check anymore.

One thing to look out for is to make sure that the template cells have a solid (i.e., non-patterned) fill. If it has a pattern fill then the background/foreground (start_color/end_color) color roles are reversed. However, since you are creating the template file it should be easy to specify a solid fill.

Note 1, for completeness: The color index is used to hold the default index 64 background color in solid fills; used for compatibility with older xls files; and used for some non-cell formatting like comments.


Title: MySQL server version for the right syntax to use near ''?

Body:
When upload the sql to phpmyadmin after edit a 1000+ lien and the

MySQL said:
Documentation#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1489

Static analysis:
1 errors were found during analysis.
8 values were expected, but found 4. (near "(" at position 114466)

INSERT INTO `cities` (`id`, `name`, `state_id`, `cost`, `status`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'Adrar', 1, 1400.00, 1, '2022-02-08 03:05:34', '2022-02-08 03:05:34', NULL),
(2, 'Akabli', 1, 1400.00, 1, '2022-02-08 03:06:01', '2022-02-08 03:06:01', NULL),
(3, 'Aougrout', 1, 1400.00, 1, '2022-02-08 03:06:18', '2022-02-08 03:06:18', NULL),
(4, 'Aoulef', 1, 1400.00, 1, '2022-02-08 03:06:36', '2022-02-08 03:06:36', NULL),
(5, 'Bouda', 1, 1400.00, 1, '2022-02-08 03:06:58', '2022-02-08 03:06:58', NULL),
(6, 'Charouine', 1, 1400.00, 1, '2022-02-08 03:07:07', '2022-02-08 03:07:07', NULL),
(7, 'Deldoul', 1, 1400.00, 1, '2022-02-08 03:07:12', '2022-02-08 03:07:12', NULL),
(8, 'Fenoughil', 1, 1400.00, 1, '2022-02-08 03:07:19', '2022-02-08 03:07:19', NULL),
(9, 'In Zghmir', 1, 1400.00, 1, '2022-02-08 03:07:23', '2022-02-08 03:07:23', NULL),
(10, 'Ksar Kaddour', 1, 1400.00, 1, '2022-02-08 03:07:30', '2022-02-08 03:07:30', NULL),
(11, 'Metarfa', 1, 1400.00, 1, '2022-02-08 03:07:35', '2022-02-08 03:07:35', NULL),
(12, 'Ouled Ahmed Tammi', 1, 1400.00, 1, '2022-02-08 03:07:40', '2022-02-08 03:07:40', NULL),
(13, 'Ouled Aïssa', 1, 1400.00, 1, '2022-02-08 03:07:47', '2022-02-08 03:07:47', NULL),
(14, 'Ouled Saïd', 1, 1400.00, 1, '2022-02-08 03:07:55', '2022-02-08 03:07:55', NULL),
(15, 'Reggane', 1, 1400.00, 1, '2022-02-08 03:08:02', '2022-02-08 03:08:02', NULL),
(16, 'Sali', 1, 1400.00, 1, '2022-02-08 03:08:26', '2022-02-08 03:08:26', NULL),
(17, 'Sebaa', 1, 1400.00, 1, '2022-02-08 03:08:36', '2022-02-08 03:08:36', NULL),
(18, 'Talmine', 1, 1400.00, 1, '2022-02-08 03:08:41', '2022-02-08 03:08:41', NULL),
(19, 'Tamantit', 1, 1400.00, 1, '2022-02-08 03:08:48', '2022-02-08 03:08:48', NULL),
(20, 'Tamekten', 1, 1400.00, 1, '2022-02-08 03:08:54', '2022-02-08 03:08:54', NULL),
(21, 'Tamest', 1, 1400.00, 1, '2022-02-08 03:09:02', '2022-02-08 03:09:02', NULL),
(22, 'Timimoun', 1, 1400.00, 1, '2022-02-08 03:09:08', '2022-02-08 03:09:08', NULL),
(23, 'Tinerkouk', 1, 1400.00, 1, '2022-02-08 03:09:13', '2022-02-08 03:09:13', NULL),
(24, 'Tit', 1, 1400.00, 1, '2022-02-08 03:09:18', '2022-02-08 03:09:18', NULL),
(25, 'Tsabit', 1, 1400.00, 1, '2022-02-08 03:09:24', '2022-02-08 03:09:24', NULL),
(26, 'Zaouiet Kounta', 1, 1400.00, 1, '2022-02-08 03:09:30', '2022-02-08 03:09:30', NULL),
(27, 'Abou El Hassan', 2, 900.00, 1, '2022-02-08 03:10:04', '2022-02-08 03:10:04', NULL),
(28, 'Bénairia', 2, 900.00, 1, '2022-02-08 03:12:00', '2022-02-08 03:12:00', NULL),
(29, 'Beni Bouateb', 2, 900.00, 1, '2022-02-08 03:12:08', '2022-02-08 03:12:08', NULL),
(30, 'Beni Haoua', 2, 900.00, 1, '2022-02-08 03:12:14', '2022-02-08 03:12:14', NULL),
(31, 'Beni Rached', 2, 900.00, 1, '2022-02-08 03:12:23', '2022-02-08 03:12:23', NULL),
(32, 'Boukadir', 2, 900.00, 1, '2022-02-08 03:12:34', '2022-02-08 03:12:34', NULL),
(33, 'Bouzeghaia', 2, 900.00, 1, '2022-02-08 03:12:52', '2022-02-08 03:12:52', NULL),

(1432, 'Tamzoura', 46, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1433, 'Terga', 46, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1434, 'Berriane', 47, 1050.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1435, 'Bounoura', 47, 1050.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1436, 'Dhayet Bendhahoua', 47, 1050.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1437, 'El Atteuf', 47, 1050.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1438, 'El Guerrara', 47, 1050.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1439, 'El Menia', 47, 1050.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1440, 'Ghardaïa', 47, 1050.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1441, 'Hassi Fehal', 47, 1050.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1442, 'Hassi Gara', 47, 1050.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1443, 'Mansoura', 47, 1050.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1444, 'Metlili', 47, 1050.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1445, 'Sebseb', 47, 1050.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1446, 'Zelfana', 47, 1050.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1447, 'Aïn Rahma', 48, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1448, 'Aïn Tarek', 48, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1449, 'Ammi Moussa', 48, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1450, 'Belassel Bouzegza', 48, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1451, 'Bendaoud', 48, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1452, 'Beni Dergoun', 48, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1453, 'Beni Zentis', 48, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1454, 'Dar Ben Abdellah', 48, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),

(1479, 'Sidi M Hamed Ben Ali', 48, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1480, 'Sidi M Hamed Benaouda', 48, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1481, 'Sidi Saada', 48, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1482, 'Souk El Had', 48, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1483, 'Yellel', 48, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL),
(1484, 'Zemmora', 48, 900.00, 1, '2022-02-08 03:14:07', '2022-02-08 03:14:07', NULL);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `cities`
--
ALTER TABLE `cities`
  ADD PRIMARY KEY (`id`),

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `cities`
--
ALTER TABLE `cities`
  MODIFY `id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=43;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Body:
FIXED

THE ERROR IS

(1311, 'Gouraya', ( 750.00, 1,

"("


问:
gVim: How to load multiple files in buffer?
Im in windows and is new in using gvim. I am using the Nerdtree plugin for project navigations. Right now I open files from the nerd tree, vim will then load this opened files in the buffer. I find it easier to switch throug multiple files using the :b command, it gets more convenient after opening more files as more is loaded in the buffer.

But I think it will be more convenient if there is a way to load all files in a directory in the buffer at the same time instead of loading one by one when opening them.

答:
```<code>vim mydir/*
</code>```

Should do the trick

Edit:

Oops, windows.  I just found this similar thread quickly, which might be of some help.

Open files in existing Gvim in multiple (new) tabs

Body:
vim mydir/*

Should do the trick

Edit:

Oops, windows.  I just found this similar thread quickly, which might be of some help.

Open files in existing Gvim in multiple (new) tabs


问:
Load color asset from custom bundle in Swift
I am attempting to load a color asset from a custom bundle I created.  (Essentially just created a folder and added .bundle to the end).  It appears the code to find the bundle works just fine, but I can't actually extract anything (more specifically colors) out of my bundle.  They simply all return nil.

Here is my code..

```<code>    guard let bundleURL = Bundle.main.url(forResource: "TestTheme", withExtension: "bundle") else { return }
    guard let bundle = Bundle(url: bundleURL) else { return }
    let color = UIColor(named: "NavigationBarTint", in: bundle, compatibleWith: nil)
    self.navigationController?.navigationBar.tintColor = color
</code>```

as for the contents of my bundle, I created a color asset in XCode and added a few colors.  Went to the asset's location in Finder and just copy/pasted the asset into my bundle.  So all that exists in my 'TestTheme' bundle is a single color asset with 4 colors, one of them being the NavigationBarTint.

Is there some step I'm missing here?  All other research seems to point to this being all thats required but I'm getting all nil values.

Thanks

答:
Maybe this could help you the idea is to add the colors in the asset and after that to create a public extension for Color

 static let orange = Color("CustomOrange")
 static let yellow = Color("CustomYellow")```

This way you can use later Color.orange or Color.yellow and they will take the custom color you have set on

Body:
I am attempting to load a color asset from a custom bundle I created.  (Essentially just created a folder and added .bundle to the end).  It appears the code to find the bundle works just fine, but I can't actually extract anything (more specifically colors) out of my bundle.  They simply all return nil.

Here is my code..

    guard let bundleURL = Bundle.main.url(forResource: "TestTheme", withExtension: "bundle") else { return }
    guard let bundle = Bundle(url: bundleURL) else { return }
    let color = UIColor(named: "NavigationBarTint", in: bundle, compatibleWith: nil)
    self.navigationController?.navigationBar.tintColor = color

as for the contents of my bundle, I created a color asset in XCode and added a few colors.  Went to the asset's location in Finder and just copy/pasted the asset into my bundle.  So all that exists in my 'TestTheme' bundle is a single color asset with 4 colors, one of them being the NavigationBarTint.

Is there some step I'm missing here?  All other research seems to point to this being all thats required but I'm getting all nil values.

Thanks

Body:
Maybe this could help you the idea is to add the colors in the asset and after that to create a public extension for Color

 static let orange = Color("CustomOrange")
 static let yellow = Color("CustomYellow")

This way you can use later Color.orange or Color.yellow and they will take the custom color you have set on


问:
How to take confidence interval of statsmodels.tsa.holtwinters-ExponentialSmoothing Models in python?
I did time series forecasting analysis with ExponentialSmoothing in python. I used statsmodels.tsa.holtwinters.

```<code>model = ExponentialSmoothing(df, seasonal='mul', seasonal_periods=12).fit()
pred = model.predict(start=df.index[0], end=122)

plt.plot(df_fc.index, df_fc, label='Train')
plt.plot(pred.index, pred, label='Holt-Winters')
plt.legend(loc='best')
</code>```

I want to take confidence interval of the model result. But I couldn't find any function about this in "statsmodels.tsa.holtwinters - ExponentialSmoothing". How to I do that?

答:
From this answer from a GitHub issue, it is clear that you should be using the new ETSModel class, and not the old (but still present for compatibility) ExponentialSmoothing.
ETSModel includes more parameters and more functionality than ExponentialSmoothing.

To calculate confidence intervals, I suggest you to use the simulate method of ETSResults:

from statsmodels.tsa.exponential_smoothing.ets import ETSModel
import pandas as pd

# Build model.
ets_model = ETSModel(
    endog=y, # y should be a pd.Series
    seasonal='mul',
    seasonal_periods=12,
)
ets_result = ets_model.fit()

# Simulate predictions.
n_steps_prediction = y.shape[0]
n_repetitions = 500

df_simul = ets_result.simulate(
    nsimulations=n_steps_prediction,
    repetitions=n_repetitions,
    anchor='start',
)

# Calculate confidence intervals.
upper_ci = df_simul.quantile(q=0.9, axis='columns')
lower_ci = df_simul.quantile(q=0.1, axis='columns')
```

Basically, calling the simulate method you get a DataFrame with n_repetitions columns, and with n_steps_prediction steps (in this case, the same number of items in your training data-set y).
Then, you calculate the confidence intervals with DataFrame quantile method (remember the axis='columns' option).
You could also calculate other statistics from the df_simul.

I also checked the source code: simulate is internally called by the forecast method to predict steps in the future. So, you could also predict steps in the future and their confidence intervals with the same approach: just use anchor='end', so that the simulations will start from the last step in y.

To be fair, there is also a more direct approach to calculate the confidence intervals: the get_prediction method (which uses simulate internally). But I do not really like its interface, it is not flexible enough for me, I did not find a way to specify the desired confidence intervals. The approach with the simulate method is pretty easy to understand, and very flexible, in my opinion.

If you want further details on how this kind of simulations are performed, read this chapter from the excellent Forecasting: Principles and Practice online book.

Body:
I did time series forecasting analysis with ExponentialSmoothing in python. I used statsmodels.tsa.holtwinters.

model = ExponentialSmoothing(df, seasonal='mul', seasonal_periods=12).fit()
pred = model.predict(start=df.index[0], end=122)

plt.plot(df_fc.index, df_fc, label='Train')
plt.plot(pred.index, pred, label='Holt-Winters')
plt.legend(loc='best')

I want to take confidence interval of the model result. But I couldn't find any function about this in "statsmodels.tsa.holtwinters - ExponentialSmoothing". How to I do that?

Body:
From this answer from a GitHub issue, it is clear that you should be using the new ETSModel class, and not the old (but still present for compatibility) ExponentialSmoothing.
ETSModel includes more parameters and more functionality than ExponentialSmoothing.

To calculate confidence intervals, I suggest you to use the simulate method of ETSResults:

from statsmodels.tsa.exponential_smoothing.ets import ETSModel
import pandas as pd

# Build model.
ets_model = ETSModel(
    endog=y, # y should be a pd.Series
    seasonal='mul',
    seasonal_periods=12,
)
ets_result = ets_model.fit()

# Simulate predictions.
n_steps_prediction = y.shape[0]
n_repetitions = 500

df_simul = ets_result.simulate(
    nsimulations=n_steps_prediction,
    repetitions=n_repetitions,
    anchor='start',
)

# Calculate confidence intervals.
upper_ci = df_simul.quantile(q=0.9, axis='columns')
lower_ci = df_simul.quantile(q=0.1, axis='columns')

Basically, calling the simulate method you get a DataFrame with n_repetitions columns, and with n_steps_prediction steps (in this case, the same number of items in your training data-set y).
Then, you calculate the confidence intervals with DataFrame quantile method (remember the axis='columns' option).
You could also calculate other statistics from the df_simul.

I also checked the source code: simulate is internally called by the forecast method to predict steps in the future. So, you could also predict steps in the future and their confidence intervals with the same approach: just use anchor='end', so that the simulations will start from the last step in y.

To be fair, there is also a more direct approach to calculate the confidence intervals: the get_prediction method (which uses simulate internally). But I do not really like its interface, it is not flexible enough for me, I did not find a way to specify the desired confidence intervals. The approach with the simulate method is pretty easy to understand, and very flexible, in my opinion.

If you want further details on how this kind of simulations are performed, read this chapter from the excellent Forecasting: Principles and Practice online book.


问:
Transform complex json files using ADF
I want to transform multiple complex JSON files into one complex JSON file using Azure Data Factory dataflow.

The multiple complex input JSON files are in the following format:

{
  "creationDate": "2022-01-19T17:00:17Z",
  "count": 2,
  "data": [
    {
      "id": "",
      "name": "Project A",
      "url": "",
      "state": "Open",
      "revision": 1,
      "visibility": "private",
      "lastUpdateTime": "2019-09-23T08:44:45.103Z"
    },
    {
      "id": "",
      "name": "Project B",
      "url": "",
      "state": "Done",
      "revision": 1,
      "visibility": "private",
      "lastUpdateTime": "2019-12-31T09:38:49.16Z"
    }
  ]
}
```
<p>We want to transform those files to one single json file in the format:</p>
<pre class="lang-json prettyprint-override"><code>[
  {
    "date": "2022-01-14",
    "count": 2,
    "projects": [
      {
        "name": "Project A",
        "state": "",
        "lastUpdateTime": ""
      },
      {
        "name": "Project B",
        "state": "",
        "lastUpdateTime": ""
      }
    ]
  },
  {
    "date": "2022-01-17",
    "count": 3,
    "projects": [
      {
        "name": "Project A",
        "state": "",
        "lastUpdateTime": ""
      },
      {
        "name": "Project B",
        "state": "",
        "lastUpdateTime": ""
      },
      {
        "name": "Project C",
        "state": "",
        "lastUpdateTime": ""
      }
    ]
  }
]
</code>```

We were using the derived column with the expression @(name=data.name, state=data.state).

Can someone help us how to do this? We tried a lot of things like derived column, first flattening but we can't get it as we like...

Thanks!

答:
The solution on the end was pretty close on what we had.

So our final solution is as follow:

First flatten with Unroll by set to data. We also mapped the creationDate to date.

Create a derived column called projects with as expression @(name=name,state=state,lastUpdateTime=lastUpdateTime,url=url)

Group activity with a Group by on date. Set Aggregates for count on first(count) and (this was the solution) set projects to collect(projects).

Select activity which will select the columns date, count and projects.

Sort activity with a sort on date Ascending.

Sink with file name option to output to single file and partion option set to single partion

Note:
Because we have a sink to one big json file (output to single file). The sorting wasn't correct written to json. If we debugged (data preview) the dataflow everything was correct. Strange behavior. When we changed the Sort activity the option Partion option to Single partion the json file had the right sort order.

Title: Transform complex json files using ADF

Body:
I want to transform multiple complex JSON files into one complex JSON file using Azure Data Factory dataflow.

The multiple complex input JSON files are in the following format:

{
  "creationDate": "2022-01-19T17:00:17Z",
  "count": 2,
  "data": [
    {
      "id": "",
      "name": "Project A",
      "url": "",
      "state": "Open",
      "revision": 1,
      "visibility": "private",
      "lastUpdateTime": "2019-09-23T08:44:45.103Z"
    },
    {
      "id": "",
      "name": "Project B",
      "url": "",
      "state": "Done",
      "revision": 1,
      "visibility": "private",
      "lastUpdateTime": "2019-12-31T09:38:49.16Z"
    }
  ]
}

We want to transform those files to one single json file in the format:

[
  {
    "date": "2022-01-14",
    "count": 2,
    "projects": [
      {
        "name": "Project A",
        "state": "",
        "lastUpdateTime": ""
      },
      {
        "name": "Project B",
        "state": "",
        "lastUpdateTime": ""
      }
    ]
  },
  {
    "date": "2022-01-17",
    "count": 3,
    "projects": [
      {
        "name": "Project A",
        "state": "",
        "lastUpdateTime": ""
      },
      {
        "name": "Project B",
        "state": "",
        "lastUpdateTime": ""
      },
      {
        "name": "Project C",
        "state": "",
        "lastUpdateTime": ""
      }
    ]
  }
]

We were using the derived column with the expression @(name=data.name, state=data.state).

Can someone help us how to do this? We tried a lot of things like derived column, first flattening but we can't get it as we like...

Thanks!


问:
lock a div between two divs on scroll down with jquery and elementor
I want to have a div who is fixed when i scroll down. But i want that i reach another div, the div who is fixed set herself to position static.

This part of code works for me, but the problem is, that when i scroll-up, the div doesn't want to be fixed again.

This is my code :

```

Please ask me some questions if you want some complementary informations !

Thanks you for your helps

答:
I don't really understand what you want, but I think you really want to check this out.

p {
  display: block;
  margin: 10px 5px;
}

div {
  display: block;
  margin: 10px 5px;
  padding: 5px 10px;
  background: #FF0000;
  position: sticky;
  top: 0px;
  color: #fff;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="sticky_div"><h1>DIV 1</h1></div>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<div class="sticky_div"><h1>DIV 2</h1></div>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<div class="sticky_div"><h1>DIV 3</h1></div>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<div class="sticky_div"><h1>DIV 4</h1></div>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<div class="sticky_div"><h1>DIV 5</h1></div>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<div class="sticky_div"><h1>DIV 6</h1></div></code>```

Body:
I want to have a div who is fixed when i scroll down. But i want that i reach another div, the div who is fixed set herself to position static.

This part of code works for me, but the problem is, that when i scroll-up, the div doesn't want to be fixed again.

This is my code :

Please ask me some questions if you want some complementary informations !

Thanks you for your helps

Body:
I don't really understand what you want, but I think you really want to check this out.

p {
  display: block;
  margin: 10px 5px;
}

div {
  display: block;
  margin: 10px 5px;
  padding: 5px 10px;
  background: #FF0000;
  position: sticky;
  top: 0px;
  color: #fff;
}

<div class="sticky_div"><h1>DIV 1</h1></div>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<div class="sticky_div"><h1>DIV 2</h1></div>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<div class="sticky_div"><h1>DIV 3</h1></div>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<div class="sticky_div"><h1>DIV 4</h1></div>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<div class="sticky_div"><h1>DIV 5</h1></div>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<p>CONTENT FROM DIV</p><br>
<div class="sticky_div"><h1>DIV 6</h1></div>


问:
Select rows if string begins with certain characters in pandas
I have a csv file as the given picture bellow

I'm trying to find any word that will start with letter A and G or any list that I want

but my code returns an error any Ideas what I'm doing wrong ?
this is my code

```<code>if len(sys.argv) == 1:
    print("please provide a CSV file to analys")
else:
    fileinput = sys.argv[1]

wdata = pd.read_csv(fileinput)

print( list(filter(startswith("a","g"), wdata)) )

</code>```

答:
it is very easy and handy. you can just use str.startwith in this way:

```<code>df[df.Words.str.startswith('G')]

df[df.Words.str.startswith('A')]
</code>```

Body:
I have a csv file as the given picture bellow

I'm trying to find any word that will start with letter A and G or any list that I want

but my code returns an error any Ideas what I'm doing wrong ?
this is my code

if len(sys.argv) == 1:
    print("please provide a CSV file to analys")
else:
    fileinput = sys.argv[1]

wdata = pd.read_csv(fileinput)

print( list(filter(startswith("a","g"), wdata)) )

Body:
it is very easy and handy. you can just use str.startwith in this way:

df[df.Words.str.startswith('G')]

df[df.Words.str.startswith('A')]


问:
Can i pass multiple parameters to a bind variable in a SQL query in Oracle with equal to sign?
The user will select multiple pick value from screen like 100, 101, 102 etc. and those values need to be passed to the below query and generate the output for further processing.

How can I pass multiple values to a bind parameter in a query having a equal to sign?

```<code>SELECT tab1.PICKLIST_KEY icrggq_0, NULL icrggq_1, 0 icrggq_2
  FROM tab1
 WHERE dc_code = 942
   AND tab1.pick_value = :p_pick_value;
</code>```

There are hundreds of queries like this and we will not be able to modify all of them manually. Is it possible to be done by plsql procedure or function ? We are receiving the multiple values through front end Oracle Forms screen.

答:
You can't (not that way, that is), but you could "split" those comma-separated values into rows and then use them as a subquery. Something like this:

```<code>SELECT tab1.picklist_key icrggq_0, NULL icrggq_1, 0 icrggq_2
  FROM tab1
 WHERE     dc_code = 942
       AND tab1.pick_value IN
              (    SELECT REGEXP_SUBSTR ( :p_pick_value, '[^,]+', 1, LEVEL)
                     FROM DUAL
               CONNECT BY REGEXP_COUNT ( :p_pic_value, ',') + 1)
</code>```

Body:
The user will select multiple pick value from screen like 100, 101, 102 etc. and those values need to be passed to the below query and generate the output for further processing.

How can I pass multiple values to a bind parameter in a query having a equal to sign?

SELECT tab1.PICKLIST_KEY icrggq_0, NULL icrggq_1, 0 icrggq_2
  FROM tab1
 WHERE dc_code = 942
   AND tab1.pick_value = :p_pick_value;

There are hundreds of queries like this and we will not be able to modify all of them manually. Is it possible to be done by plsql procedure or function ? We are receiving the multiple values through front end Oracle Forms screen.

Body:
You can't (not that way, that is), but you could "split" those comma-separated values into rows and then use them as a subquery. Something like this:

SELECT tab1.picklist_key icrggq_0, NULL icrggq_1, 0 icrggq_2
  FROM tab1
 WHERE     dc_code = 942
       AND tab1.pick_value IN
              (    SELECT REGEXP_SUBSTR ( :p_pick_value, '[^,]+', 1, LEVEL)
                     FROM DUAL
               CONNECT BY REGEXP_COUNT ( :p_pic_value, ',') + 1)


问:
how to get name twice via mysql left join
I have two tables. One is for member info, the other is for board info.
I want to display both 'writer' and 'viewer' with name but I can only show one of them by 'LEFT JOIN'

```<code>SELECT * FROM `table_a`
idx name
1   Admin
2   Superman
3   Ironman
4   Batman

SELECT * FROM `table_bbs`
idx writer  title       viewer
1   1       Hi All          0
2   1       hello           2
3   2       My name is      3
4   3       Do not click    4

SELECT bbs.writer, a.name, bbs.title, bbs.viewer FROM `table_bbs` AS bbs
    LEFT JOIN table_a AS a ON a.idx = bbs.writer;
writer  name    title           viewer
1   Admin       Hi All          0
1   Admin       hello           2
2   Superman    My name is      3
3   Ironman     Do not click    4
</code>```

How can I get the name of viewer as well?

答:
if viewer data is get from table_a</p>
```<code>SELECT bbs.writer, a.name as writer_name, bbs.title, bbs.viewer, b.name as viewer_name FROM `table_bbs` AS bbs
    LEFT JOIN table_a AS a ON a.idx = bbs.writer
    LEFT JOIN table_a AS b ON b.idx = bbs.viewer
</code>```

Body:
I have two tables. One is for member info, the other is for board info.
I want to display both 'writer' and 'viewer' with name but I can only show one of them by 'LEFT JOIN'

SELECT * FROM `table_a`
idx name
1   Admin
2   Superman
3   Ironman
4   Batman

SELECT * FROM `table_bbs`
idx writer  title       viewer
1   1       Hi All          0
2   1       hello           2
3   2       My name is      3
4   3       Do not click    4

SELECT bbs.writer, a.name, bbs.title, bbs.viewer FROM `table_bbs` AS bbs
    LEFT JOIN table_a AS a ON a.idx = bbs.writer;
writer  name    title           viewer
1   Admin       Hi All          0
1   Admin       hello           2
2   Superman    My name is      3
3   Ironman     Do not click    4

How can I get the name of viewer as well?

Body:
if viewer data is get from table_a

SELECT bbs.writer, a.name as writer_name, bbs.title, bbs.viewer, b.name as viewer_name FROM `table_bbs` AS bbs
    LEFT JOIN table_a AS a ON a.idx = bbs.writer
    LEFT JOIN table_a AS b ON b.idx = bbs.viewer


问:
Set dropdown select by value
Is it possible to set selected specific item of dropdown in Google apps script (Gmail add-on) from the action?

Example: I have one dropdown with 5 items (10, 20, 30, 40, 50) and one button. Default selected item of dropdown is 10 (dropdown.AddItem(10, 10, true)). When I click button I want to change selected item of dropdown to 40. Is it possible to do?

UPDATED:

```<code>function onHomepage(e) {
  var max = CardService.newSelectionInput()
      .setType(CardService.SelectionInputType.DROPDOWN)
      .setTitle('Max')
      .setFieldName('max_field')
      .setOnChangeAction(CardService.newAction()
        .setFunctionName('maxHandler'));

  for (let i = 10; i <= 100; i += 10) {
    var selected = false;
    if (i === 10)
      selected = true;
    max.addItem(i + "$", i, selected);
  }

  var _btn = CardService.newTextButton()
      .setText('Button')
      .setTextButtonStyle(CardService.TextButtonStyle.FILLED)
      .setOnClickAction(CardService.newAction()
        .setFunctionName('btnClicked'));

  var btn = CardService.newButtonSet()
      .addButton(_btn);

  var section = CardService.newCardSection()
    .addWidget(max)
    .addWidget(btn);

  return CardService.newCardBuilder()
    .setName('cardName')
    .addSection(section)
    .build();
}

function btnClicked(e) {
  var selectedMax = e.formInput.max_field;
  console.log(selectedMax);

  // TODO: set selected dropdown for 40$ item
}
</code>```

答:
You need re-render the card on button click:

```<code>function onHomepage(e) {
  return createCard(10)
}

function btnClicked(e) {
  var selectedMax = e.formInput.max_field;

  return createCard(40)
}

function createCard(value) {
  var max = CardService.newSelectionInput()
      .setType(CardService.SelectionInputType.DROPDOWN)
      .setTitle('Max')
      .setFieldName('max_field')
      .setOnChangeAction(CardService.newAction()
        .setFunctionName('maxHandler'));

  for (let i = 10; i <= 100; i += 10) {
    var selected = false;
    if (i === value)
      selected = true;
    max.addItem(i + "$", i, selected);
  }

  var _btn = CardService.newTextButton()
      .setText('Button')
      .setTextButtonStyle(CardService.TextButtonStyle.FILLED)
      .setOnClickAction(CardService.newAction()
        .setFunctionName('btnClicked'));

  var btn = CardService.newButtonSet()
      .addButton(_btn);

  var section = CardService.newCardSection()
    .addWidget(max)
    .addWidget(btn);

  return CardService.newCardBuilder()
    .setName('cardName')
    .addSection(section)
    .build();
}
</code>```

Just separate out your card creation code from onHomepage() into a different function (for example createCard() and call it from both onHomepage() and from btnClicked().

Title: Set dropdown select by value

Body:
Is it possible to set selected specific item of dropdown in Google apps script (Gmail add-on) from the action?

Example: I have one dropdown with 5 items (10, 20, 30, 40, 50) and one button. Default selected item of dropdown is 10 (dropdown.AddItem(10, 10, true)). When I click button I want to change selected item of dropdown to 40. Is it possible to do?

UPDATED:

function onHomepage(e) {
  var max = CardService.newSelectionInput()
      .setType(CardService.SelectionInputType.DROPDOWN)
      .setTitle('Max')
      .setFieldName('max_field')
      .setOnChangeAction(CardService.newAction()
        .setFunctionName('maxHandler'));

  for (let i = 10; i <= 100; i += 10) {
    var selected = false;
    if (i === 10)
      selected = true;
    max.addItem(i + "$", i, selected);
  }

  var _btn = CardService.newTextButton()
      .setText('Button')
      .setTextButtonStyle(CardService.TextButtonStyle.FILLED)
      .setOnClickAction(CardService.newAction()
        .setFunctionName('btnClicked'));

  var btn = CardService.newButtonSet()
      .addButton(_btn);

  var section = CardService.newCardSection()
    .addWidget(max)
    .addWidget(btn);

  return CardService.newCardBuilder()
    .setName('cardName')
    .addSection(section)
    .build();
}

function btnClicked(e) {
  var selectedMax = e.formInput.max_field;
  console.log(selectedMax);

  // TODO: set selected dropdown for 40$ item
}

Body:
You need re-render the card on button click:

function onHomepage(e) {
  return createCard(10)
}

function btnClicked(e) {
  var selectedMax = e.formInput.max_field;

  return createCard(40)
}

function createCard(value) {
  var max = CardService.newSelectionInput()
      .setType(CardService.SelectionInputType.DROPDOWN)
      .setTitle('Max')
      .setFieldName('max_field')
      .setOnChangeAction(CardService.newAction()
        .setFunctionName('maxHandler'));

  for (let i = 10; i <= 100; i += 10) {
    var selected = false;
    if (i === value)
      selected = true;
    max.addItem(i + "$", i, selected);
  }

  var _btn = CardService.newTextButton()
      .setText('Button')
      .setTextButtonStyle(CardService.TextButtonStyle.FILLED)
      .setOnClickAction(CardService.newAction()
        .setFunctionName('btnClicked'));

  var btn = CardService.newButtonSet()
      .addButton(_btn);

  var section = CardService.newCardSection()
    .addWidget(max)
    .addWidget(btn);

  return CardService.newCardBuilder()
    .setName('cardName')
    .addSection(section)
    .build();
}

Just separate out your card creation code from onHomepage() into a different function (for example createCard() and call it from both onHomepage() and from btnClicked().


问:
Efficient object storage in a file in Java
I am writing a Spotify-like app for an assignment.I have a Song and a Playlist class and I have files where I would store the data. In the constructor of the Spotify Server, the files are supposed to be read and their data transformed into Song and Playlist objects, which the client would then be able to play.
For example, when the Server is run for the first time, the files are empty and there are no songs and playlists. An administrator/user adds several songs and playlists. They are stored in those files. The application is terminated. When the Server is run again, the songs and playlists that have been added in all previous sessions (and stored in files) are loaded and a user can play them.
The question is what technique should I use to store the object data in the most efficient way.
I have considered the following options:

A database - I haven't studied how to make one and that's not the idea of the assignment.

JSON - I know that JSON is an effective way to store and send information in the network. But here, I won't be sending the information across the network. The server will read it from its local hardware. If I use JSON, I will make use of the GSON library.

Serialization - I could do it the traditional way. Make Song and Playlist implement Serializable and store the information in the files.

 The structure of the classes is as follows:

public class Song{
   private final UUID id;
   private final String artist;
   private final String name;
   private final int duration;
   private int timesListenedTo = 0;
   private final Path filePath; // a non-changing path to the .wav audio file of the song
}
```
<pre class="lang-java prettyprint-override"><code>public class Playlist{
   private List<Song> songs; // I could replace this with a List<String> or List<UUID> if considered more efficient
   private final String name;
}
</code>```

 What is the most resource-efficient approach for my task? My priorities in order are:

Minimal CPU usage

Minimal memory usage

Code complexity (the least important)

答: you can convert the data object to bytes array and write it to a file,but if you think the java native api have a little slow ,you can try protobuf,wish you can get your way</p>

Body:
I am writing a Spotify-like app for an assignment.I have a Song and a Playlist class and I have files where I would store the data. In the constructor of the Spotify Server, the files are supposed to be read and their data transformed into Song and Playlist objects, which the client would then be able to play.
For example, when the Server is run for the first time, the files are empty and there are no songs and playlists. An administrator/user adds several songs and playlists. They are stored in those files. The application is terminated. When the Server is run again, the songs and playlists that have been added in all previous sessions (and stored in files) are loaded and a user can play them.
The question is what technique should I use to store the object data in the most efficient way.
I have considered the following options:

A database - I haven't studied how to make one and that's not the idea of the assignment.

JSON - I know that JSON is an effective way to store and send information in the network. But here, I won't be sending the information across the network. The server will read it from its local hardware. If I use JSON, I will make use of the GSON library.

Serialization - I could do it the traditional way. Make Song and Playlist implement Serializable and store the information in the files.

 The structure of the classes is as follows:

public class Song{
   private final UUID id;
   private final String artist;
   private final String name;
   private final int duration;
   private int timesListenedTo = 0;
   private final Path filePath; // a non-changing path to the .wav audio file of the song
}

public class Playlist{
   private List<Song> songs; // I could replace this with a List<String> or List<UUID> if considered more efficient
   private final String name;
}

 What is the most resource-efficient approach for my task? My priorities in order are:

Minimal CPU usage

Minimal memory usage

Code complexity (the least important)


问:
What is the best way to access elements of parent control from a child control?
I have a parent control (main form) and a child control (user control). The child control has some code, which determines what functions the application can perform (e.g. save files, write logs etc.). I need to show/hide, enable/disable main menu items of the main form according to the functionality. As I can't just write MainMenu.MenuItem1.Visible = false; (the main menu is not visible from the child control), I fire an event in the child control and handle this event on the main form. The problem is I need to pass what elements of the menu need to be shown/hidden. To do this I created an enum, showing what to do with the item

```<code>public enum ItemMode
{
    TRUE, FALSE, NONE
}
</code>```

Then I created my eventargs which have 6 parameters of type ItemMode (there are 6 menu items I need to manage). So any time I need to show the 1st item, hide the 2nd and do nothing with the rest I have to write something like this

```<code>e = new ItemModeEventArgs(ItemMode.TRUE, ItemMode.FALSE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE);
FireMyEvent(e);
</code>```

This seems like too much code to me and what's more, what if I need to manage 10 items in future? Then I will have to rewrite all the constructors just to add 4 more NONEs.

I believe there's a better way of doing this, but I just can't figure out what it is.

答:
The chain child->parent can be reversed. In such scenario requests will be passed from the mainform to its child controls.

Controls participating in the command processing must implement a special interface:

```<code>  interface ICommandHandler
  {
        bool CanInvoke(int commandId);
        void InvokeCommand(int commandId);
        bool UpdateCommand(int commandId, MenuItem item);
  }
</code>```

The advantage of this approach is that only active controls must be traversed, not all the children.
The weak point - UpdateCommand() method, which could be called from Application.Idle event or timer.

hope this helps

Body:
I have a parent control (main form) and a child control (user control). The child control has some code, which determines what functions the application can perform (e.g. save files, write logs etc.). I need to show/hide, enable/disable main menu items of the main form according to the functionality. As I can't just write MainMenu.MenuItem1.Visible = false; (the main menu is not visible from the child control), I fire an event in the child control and handle this event on the main form. The problem is I need to pass what elements of the menu need to be shown/hidden. To do this I created an enum, showing what to do with the item

public enum ItemMode
{
    TRUE, FALSE, NONE
}

Then I created my eventargs which have 6 parameters of type ItemMode (there are 6 menu items I need to manage). So any time I need to show the 1st item, hide the 2nd and do nothing with the rest I have to write something like this

e = new ItemModeEventArgs(ItemMode.TRUE, ItemMode.FALSE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE, ItemMode.NONE);
FireMyEvent(e);

This seems like too much code to me and what's more, what if I need to manage 10 items in future? Then I will have to rewrite all the constructors just to add 4 more NONEs.

I believe there's a better way of doing this, but I just can't figure out what it is.

Body:
The chain child->parent can be reversed. In such scenario requests will be passed from the mainform to its child controls.

Controls participating in the command processing must implement a special interface:

  interface ICommandHandler
  {
        bool CanInvoke(int commandId);
        void InvokeCommand(int commandId);
        bool UpdateCommand(int commandId, MenuItem item);
  }

The advantage of this approach is that only active controls must be traversed, not all the children.
The weak point - UpdateCommand() method, which could be called from Application.Idle event or timer.

hope this helps


答:
To display the full output, use np.set_printoptions:

```<code>import numpy as np
import sys

np.set_printoptions(threshold=sys.maxsize)
T = np.random.rand(100, 100)
print(T)
</code>```

To save the matrix in a file, use np.savetxt:

```<code>np.savetxt('out.txt', T)
</code>```

Title: Print all elements of a large matrix using Python

Body:
I have a 100x100 matrix but when I try to print it, it shows only few elements and not all of them. How do I generate all the elements in the output window or perhaps save in a .txt file?

import numpy as np
T=np.random.rand(100,100)
print(T)

Output:

[[0.2594114  0.82053856 0.34180207 ... 0.22343847 0.60514364 0.03521541]
 [0.92437952 0.03159018 0.97917483 ... 0.43370336 0.18015657 0.05756589]
 [0.876843   0.32627662 0.13961996 ... 0.07525198 0.03746563 0.80880022]
 ...
 [0.33922583 0.85408368 0.78105249 ... 0.59302032 0.99109042 0.28213881]
 [0.68913619 0.38941733 0.02607893 ... 0.33107884 0.26118189 0.09754887]
 [0.99950824 0.51556755 0.7743047  ... 0.03109424 0.91644689 0.35999142]]

Body:
To display the full output, use np.set_printoptions:

import numpy as np
import sys

np.set_printoptions(threshold=sys.maxsize)
T = np.random.rand(100, 100)
print(T)

To save the matrix in a file, use np.savetxt:

np.savetxt('out.txt', T)


问:
How to convert two dimensional array of string into one of type int?
How can I convert a double array of type String to a double array of type int ?

```<code>    @PostMapping("/hole/coordinate")
    @ResponseBody
    public String saveCoordinate(@RequestBody Map<String, Object> params) {
        System.out.println("params = " + params);
        System.out.println("params = " + params.get("coordinate"));

        return "success";
    }
</code>```

System.out.println(params.get("coordinate")); store
[[445, 292], [585, 331], [612, 223], [205, 532]]
There are m 2 elements of the double array.
ex) [a,b],[c,d].....m
At this time, I want to receive the result in the data type of int[][], not String.

I was wondering how can I convert from String to int[][].

I tried like below

```<code>int[] arr= Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();
for (int i : arr) {
    System.out.println("i = " + i);
}
</code>```

but it give me

```<code>4
4
5
2
9
2
...
</code>```

Best Regards!

答:
You can try the below code if you are trying to convert String to int[]

```<code>import java.util.stream.*;
public class MyClass {
    public static void main(String args[]) {
      String str = "[[445, 292], [585, 331], [612, 223], [205, 532]]";
      int[] arr= Stream.of(str.replaceAll("[\\[\\]\\ ]", "").split(",")).mapToInt(Integer::parseInt).toArray();
        for (int i : arr) {
            System.out.println("i = " + i);
        }
    }
}
</code>```

It prints below values as output:

```<code>i = 445
i = 292
i = 585
i = 331
i = 612
i = 223
i = 205
i = 532
</code>```

Body:
How can I convert a double array of type String to a double array of type int ?

    @PostMapping("/hole/coordinate")
    @ResponseBody
    public String saveCoordinate(@RequestBody Map<String, Object> params) {
        System.out.println("params = " + params);
        System.out.println("params = " + params.get("coordinate"));

        return "success";
    }

System.out.println(params.get("coordinate")); store
[[445, 292], [585, 331], [612, 223], [205, 532]]
There are m 2 elements of the double array.
ex) [a,b],[c,d].....m
At this time, I want to receive the result in the data type of int[][], not String.

I was wondering how can I convert from String to int[][].

I tried like below

int[] arr= Stream.of(str.replaceAll("[\\[\\]\\, ]", "").split("")).mapToInt(Integer::parseInt).toArray();
for (int i : arr) {
    System.out.println("i = " + i);
}

but it give me

4
4
5
2
9
2
...

Best Regards!

Body:
You can try the below code if you are trying to convert String to int[]

import java.util.stream.*;
public class MyClass {
    public static void main(String args[]) {
      String str = "[[445, 292], [585, 331], [612, 223], [205, 532]]";
      int[] arr= Stream.of(str.replaceAll("[\\[\\]\\ ]", "").split(",")).mapToInt(Integer::parseInt).toArray();
        for (int i : arr) {
            System.out.println("i = " + i);
        }
    }
}

It prints below values as output:

i = 445
i = 292
i = 585
i = 331
i = 612
i = 223
i = 205
i = 532


问:
Mock repository that depends on DBContext using FakeItEasy
I'm developing an application with .NET Core and EF. I'm trying to implement some unit test using FakeItEasy and NUnit. Here's my problem.
I've a DbContext as this one:

```<code>public class PostgresDbContext : IdentityDbContext<User, IdentityRole<int>, int> {
    // Add DbSets
    public virtual DbSet<Institution> Institutions { get; set; }

    public virtual DbSet<Employee> Employees { get; set; }
...
</code>```

Then I've a repository that uses PostgresDbContext:

```<code>    public class UserRepository {
    private readonly PostgresDbContext _dbContext;

    public UserRepository(PostgresDbContext dbContext) {
        _dbContext = dbContext;
    }
    ...
</code>```

And finally I've a service (the class that I'm trying to test) which uses UserRepository.

```<code>    public class AuthService : BaseServiceAbstract {
    private readonly SignInManager<User> _signInManager;
    private readonly UserRepository _userRepository;

    public AuthService(SignInManager<User> signInManager, UserRepository userRepository) {
        _signInManager = signInManager;
        _userRepository = userRepository;
    }
</code>```

The problem is when I try to Mock UserRepository in the following method:

```<code>    [Test, Description("Should login when provided with right credentials")]
    public void Login() {
        var user = new Employee {Name = "user"};
        var signInManger = A.Fake<SignInManager<User>>();
        var userRepository = A.Fake<UserRepository>();

        _authService = new AuthService(signInManger, userRepository);

        A.CallTo(() => userRepository.FindUserByUsername("user"))
            .Returns(user);

        _authService.Login("user", "password");
    }
</code>```

I throws me the error:

```<code>FakeItEasy.Core.FakeCreationException :
Failed to create fake of type DAL.Repositories.UserRepository:

The constructors with the following signatures were not tried:
(*DAL.PostgresDbContext)

Types marked with * could not be resolved. Please provide a Dummy Factory to enable these constructors.
</code>```

Any idea?

答:
To create a fake UserRepository, FakeItEasy needs an instance of PostgresDbContext. So it tries to create a fake one, but doesn't succeed (I don't have enough details to determine why exactly). Anyway, mocking a DbContext is always difficult.

Instead of mocking UserRepository directly, consider introducing a IUserRepository interface, implemented by UserRepository, and inject that in your AuthService. Mocking interfaces is generally much easier than mocking classes.

In general, you should avoid making your classes depend on other concrete classes. They should depend on abstractions instead. This will make your life much easier when writing unit tests.

Body:
I'm developing an application with .NET Core and EF. I'm trying to implement some unit test using FakeItEasy and NUnit. Here's my problem.
I've a DbContext as this one:

public class PostgresDbContext : IdentityDbContext<User, IdentityRole<int>, int> {
    // Add DbSets
    public virtual DbSet<Institution> Institutions { get; set; }

    public virtual DbSet<Employee> Employees { get; set; }
...

Then I've a repository that uses PostgresDbContext:

    public class UserRepository {
    private readonly PostgresDbContext _dbContext;

    public UserRepository(PostgresDbContext dbContext) {
        _dbContext = dbContext;
    }
    ...

And finally I've a service (the class that I'm trying to test) which uses UserRepository.

    public class AuthService : BaseServiceAbstract {
    private readonly SignInManager<User> _signInManager;
    private readonly UserRepository _userRepository;

    public AuthService(SignInManager<User> signInManager, UserRepository userRepository) {
        _signInManager = signInManager;
        _userRepository = userRepository;
    }

The problem is when I try to Mock UserRepository in the following method:

    [Test, Description("Should login when provided with right credentials")]
    public void Login() {
        var user = new Employee {Name = "user"};
        var signInManger = A.Fake<SignInManager<User>>();
        var userRepository = A.Fake<UserRepository>();

        _authService = new AuthService(signInManger, userRepository);

        A.CallTo(() => userRepository.FindUserByUsername("user"))
            .Returns(user);

        _authService.Login("user", "password");
    }

I throws me the error:

FakeItEasy.Core.FakeCreationException :
Failed to create fake of type DAL.Repositories.UserRepository:

The constructors with the following signatures were not tried:
(*DAL.PostgresDbContext)

Types marked with * could not be resolved. Please provide a Dummy Factory to enable these constructors.

Any idea?


问:
Recieving Another js value from html attribute getting error
Here is my code,

```<code><section class="page-section portfolio" id="portfolio">
<div class="container">
    <center>
        <h4 id="randomText"></h4>
        <input type="text" class="form-control mb-2" placeholder="Enter Text "
 id="enter_text"
               required autofocus>
        <button id='verify_id' class="btn btn-primary btn-lg">Verify</button>
        <br><br>
        <p id="text_showing"></p>

    </center>
</div>

</section>
<script>
const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

function generateString() {
var length = 8;
let result = ' ';
const charactersLength = characters.length;
for ( let i = 0; i < length; i++ ) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
}

return result;
</code>```

}

```<code>function show_text(){
     document.getElementById('randomText').innerHTML=generateString();
}
show_text()
 </script>
 <script defer>
 $(document).ready(function(){
   $("#verify_id").click(function(){
   var text=$('#enter_text').val();
   var text1=$('#randomText').text();
     if (text == text1){
     $('#text_showing').text("You have successfully verified the text").css({
      'color': 'green', 'font-size': '150%' });
     }
     else{
            $('#text_showing').text("Given text and Input text not matching ").css({
    'color': 'red', 'font-size': '150%' });

    }
    });

   });

   </script>
</code>```

Now the problem after entering right text in input field I am getting the error msg "Given text and Input text not matching",I am unable to figure out the problem,can anyone please help me to sort out the problem?

答:
The problem is the space in let result = ' ';. Remove the space ' ' and it works.

Demo

const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

function generateString() {
  var length = 8;
  let result = '';
  const charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  return result;
}

function show_text() {
  document.getElementById('randomText').innerHTML = generateString();
}
show_text()

$(document).ready(function() {
  $("#verify_id").click(function() {
    var text = $('#enter_text').val();
    var text1 = $('#randomText').text();
    if (text == text1) {
      $('#text_showing').text("You have successfully verified the text").css({
        'color': 'green',
        'font-size': '150%'
      });
    } else {
      $('#text_showing').text("Given text and Input text not matching ").css({
        'color': 'red',
        'font-size': '150%'
      });

    }
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="page-section portfolio" id="portfolio">
  <div class="container">
    <center>
      <h4 id="randomText"></h4>
      <input type="text" class="form-control mb-2" placeholder="Enter Text " id="enter_text" required autofocus>
      <button id='verify_id' class="btn btn-primary btn-lg">Verify</button>
      <br><br>
      <p id="text_showing"></p>

    </center>
  </div>

</section></code>```

Body:
Here is my code,

        <input type="text" class="form-control mb-2" placeholder="Enter Text "
 id="enter_text"
               required autofocus>
        <button id='verify_id' class="btn btn-primary btn-lg">Verify</button>

Now the problem after entering right text in input field I am getting the error msg "Given text and Input text not matching",I am unable to figure out the problem,can anyone please help me to sort out the problem?

Body:
The problem is the space in let result = ' ';. Remove the space ' ' and it works.

Demo

const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';

function generateString() {
  var length = 8;
  let result = '';
  const charactersLength = characters.length;
  for (let i = 0; i < length; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  return result;
}

function show_text() {
  document.getElementById('randomText').innerHTML = generateString();
}
show_text()

$(document).ready(function() {
  $("#verify_id").click(function() {
    var text = $('#enter_text').val();
    var text1 = $('#randomText').text();
    if (text == text1) {
      $('#text_showing').text("You have successfully verified the text").css({
        'color': 'green',
        'font-size': '150%'
      });
    } else {
      $('#text_showing').text("Given text and Input text not matching ").css({
        'color': 'red',
        'font-size': '150%'
      });

    }
  });

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="page-section portfolio" id="portfolio">
  <div class="container">
    <center>
      <h4 id="randomText"></h4>
      <input type="text" class="form-control mb-2" placeholder="Enter Text " id="enter_text" required autofocus>
      <button id='verify_id' class="btn btn-primary btn-lg">Verify</button>
      <br><br>
      <p id="text_showing"></p>

    </center>
  </div>

</section>


问:
Java Regex not matching?
I have this code, but it does not seem to be working.

```<code>Pattern pattern=Pattern.compile("IMGURSESSION=([0-9a-zA-Z]*);");
Matcher matcher=pattern.matcher("IMGURSESSION=blahblah; path=/; domain=.imgur.com");
System.out.println(matcher.matches());
</code>```

Would anyone know why?

答:
Matcher#matches() method attempts to match the entire input sequence against the pattern.

```<code>Pattern.compile("IMGURSESSION=([0-9a-zA-Z]*);.*$"); //true
Pattern.compile("IMGURSESSION=([0-9a-zA-Z]*);"); //false
</code>```

Title: Java Regex not matching?

Body:
I have this code, but it does not seem to be working.

Pattern pattern=Pattern.compile("IMGURSESSION=([0-9a-zA-Z]*);");
Matcher matcher=pattern.matcher("IMGURSESSION=blahblah; path=/; domain=.imgur.com");
System.out.println(matcher.matches());

Would anyone know why?

Body:
Matcher#matches() method attempts to match the entire input sequence against the pattern.

Pattern.compile("IMGURSESSION=([0-9a-zA-Z]*);.*$"); //true
Pattern.compile("IMGURSESSION=([0-9a-zA-Z]*);"); //false


问:
How to enumerate nested data/keys with FirebaseLib?
Any ideas, why this code does not work? There are multiple nodes inside "names"</p>
```<code>$online_users = json_decode($firebase->get(PATH . '/' . $users . '/names/') );
     echo "$online_users";
     if ($online_users != null) {
         foreach ($online_users as $key => $value) {
             if ($value) {
                 echo "$key $value<br>";
             }
         }
     }
</code>```

答:
json_decode will return null if it's not a json data, or an object (array if you add the option). Use json_last_error (https://www.php.net/manual/fr/function.json-last-error.php) if you have null to know what is the error.

You can't use echo "$online_users"; because echo need a string. But you may have an object. Choose print_r() or var_dump()

Body:
Any ideas, why this code does not work? There are multiple nodes inside "names"

$online_users = json_decode($firebase->get(PATH . '/' . $users . '/names/') );
     echo "$online_users";
     if ($online_users != null) {
         foreach ($online_users as $key => $value) {
             if ($value) {
                 echo "$key $value
";
             }
         }
     }


问:
Integrating azure data factory and airflow
My end goal is to run Azure data factory (ADF) pipelines using Airflow. My current setup is a docker file which has python packages required for this like azure data providers and a helm chart from apache airflow. I have a custom values.yaml with celery executor which I am upgrading every time to run airflow locally.

So far this part is success.

The python packages give an azure data factory option just like how I wanted but I am unable to validate these. I tested the same credentials (resource group, client id, client secret, tenant id, subscription id) using a python code and it is valid.

This doesn't work on Airflow and I see this error

```<code>*** Trying to get logs (last 100 lines) from worker pod azuredatafactoryrunpipeline.3f394072d09e4c6e8d59566776f18b78 ***
</code>```
```<code>*** Unable to fetch logs from worker pod azuredatafactoryrunpipeline.3f394072d09e4c6e8d59566776f18b78 ***
(404)
Reason: Not Found
</code>```
```<code>HTTP response headers: HTTPHeaderDict({'Audit-Id': '4a506d8b-9bac-44d8-8a7c-ee01810e478f', 'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'Date': 'Mon, 07 Feb 2022 22:05:52 GMT', 'Content-Length': '288'})
</code>```
```<code>HTTP response body: b'{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"pods \\"azuredatafactoryrunpipeline.3f394072d09e4c6e8d59566776f18b78\\" not found","reason":"NotFound","details":{"name":"azuredatafactoryrunpipeline.3f394072d09e4c6e8d59566776f18b78","kind":"pods"},"code":404}\n'
</code>```

How do I debug this?

Is there a way to test ADF connection from Airflow ?

答:
Airflow has AzureDataFactoryRunPipelineOperator which used to execute a pipeline within a data factory (see docs)

You can also add sensor to wait till the pipeline is finished before continuing execution of your Airflow workflow.

Usage example:

```<code>from airflow.providers.microsoft.azure.operators.data_factory import AzureDataFactoryRunPipelineOperator
from airflow.providers.microsoft.azure.sensors.data_factory import AzureDataFactoryPipelineRunStatusSensor

run_pipeline1 = AzureDataFactoryRunPipelineOperator(
    task_id="run_pipeline",
    pipeline_name="pipeline",
    parameters={"myParam": "value"},
)

pipeline_run_sensor = AzureDataFactoryPipelineRunStatusSensor(
    task_id="pipeline_run_sensor",
    run_id=run_pipeline.output["run_id"],
)
run_pipeline2 >> pipeline_run_sensor
</code>```

To define ADF connection in Airflow check this doc.

Body:
My end goal is to run Azure data factory (ADF) pipelines using Airflow. My current setup is a docker file which has python packages required for this like azure data providers and a helm chart from apache airflow. I have a custom values.yaml with celery executor which I am upgrading every time to run airflow locally.

So far this part is success.

The python packages give an azure data factory option just like how I wanted but I am unable to validate these. I tested the same credentials (resource group, client id, client secret, tenant id, subscription id) using a python code and it is valid.

This doesn't work on Airflow and I see this error

*** Trying to get logs (last 100 lines) from worker pod azuredatafactoryrunpipeline.3f394072d09e4c6e8d59566776f18b78 ***

*** Unable to fetch logs from worker pod azuredatafactoryrunpipeline.3f394072d09e4c6e8d59566776f18b78 ***
(404)
Reason: Not Found

HTTP response headers: HTTPHeaderDict({'Audit-Id': '4a506d8b-9bac-44d8-8a7c-ee01810e478f', 'Cache-Control': 'no-cache, private', 'Content-Type': 'application/json', 'Date': 'Mon, 07 Feb 2022 22:05:52 GMT', 'Content-Length': '288'})

HTTP response body: b'{"kind":"Status","apiVersion":"v1","metadata":{},"status":"Failure","message":"pods \\"azuredatafactoryrunpipeline.3f394072d09e4c6e8d59566776f18b78\\" not found","reason":"NotFound","details":{"name":"azuredatafactoryrunpipeline.3f394072d09e4c6e8d59566776f18b78","kind":"pods"},"code":404}\n'

How do I debug this?

Is there a way to test ADF connection from Airflow ?

Body:
Airflow has AzureDataFactoryRunPipelineOperator which used to execute a pipeline within a data factory (see docs)

You can also add sensor to wait till the pipeline is finished before continuing execution of your Airflow workflow.

Usage example:

from airflow.providers.microsoft.azure.operators.data_factory import AzureDataFactoryRunPipelineOperator
from airflow.providers.microsoft.azure.sensors.data_factory import AzureDataFactoryPipelineRunStatusSensor

run_pipeline1 = AzureDataFactoryRunPipelineOperator(
    task_id="run_pipeline",
    pipeline_name="pipeline",
    parameters={"myParam": "value"},
)

pipeline_run_sensor = AzureDataFactoryPipelineRunStatusSensor(
    task_id="pipeline_run_sensor",
    run_id=run_pipeline.output["run_id"],
)
run_pipeline2 >> pipeline_run_sensor

To define ADF connection in Airflow check this doc.


问:
Create a spinner wheel in react native
Hello i am trying to make a spinner wheel in react native using Animatable. Following the example here (https://code.tutsplus.com/tutorials/practical-animations-in-react-native--cms-27567) I was able to rotate a rectangle box. Here is the code!

```<code>  <Animatable.View
                        ref={animation[0]}
                        style={[styles.box, { backgroundColor: animation[1] }]}
                        animation={animation[0]}
                        iterationCount={"infinite"}>
                        <Text style={styles.box_text}>{animation[0]}</Text>
 </Animatable.View>

const styles = StyleSheet.create({
        container: {
            flex: 1,
            flexDirection: 'column',
            padding: 20
        },
        row: {
            flex: 1,
            flexDirection: 'row',
            justifyContent: 'space-between'
        },
        box: {
            alignItems: 'center',
            justifyContent: 'center',
            height: 100,
            width: 100,
            backgroundColor: '#ccc'
        },
        box_text: {
            color: '#FFF'
        }
    });
</code>```

But the prob is here we are rotating a box creating using css, Is there a way where i can make my own spinner using html and css and rotate it and stop it according to the business rules?

Need some directions and suggestions thank you!

答: You can use https://www.npmjs.com/package/react-native-wheel-of-fortune npm package for your purpose.</p>

Title: Create a spinner wheel in react native

Body:
Hello i am trying to make a spinner wheel in react native using Animatable. Following the example here (https://code.tutsplus.com/tutorials/practical-animations-in-react-native--cms-27567) I was able to rotate a rectangle box. Here is the code!

  <Animatable.View
                        ref={animation[0]}
                        style={[styles.box, { backgroundColor: animation[1] }]}
                        animation={animation[0]}
                        iterationCount={"infinite"}>
                        <Text style={styles.box_text}>{animation[0]}</Text>
 </Animatable.View>

const styles = StyleSheet.create({
        container: {
            flex: 1,
            flexDirection: 'column',
            padding: 20
        },
        row: {
            flex: 1,
            flexDirection: 'row',
            justifyContent: 'space-between'
        },
        box: {
            alignItems: 'center',
            justifyContent: 'center',
            height: 100,
            width: 100,
            backgroundColor: '#ccc'
        },
        box_text: {
            color: '#FFF'
        }
    });

But the prob is here we are rotating a box creating using css, Is there a way where i can make my own spinner using html and css and rotate it and stop it according to the business rules?

Need some directions and suggestions thank you!