问:
Merge Overlapping Time Intervals based on Hierarchy in SQL
I am trying to solve a problem where i want to merge overlapping intervals for a given column id, but i also want to merge them based on hierarchy/priority. I have start_time and stop_time for each interval and each interval has a hierarchy/priority associated with it.

These are the following columns in the table:

```<code>id, start_time, stop_time, priority
</code>```

I was able to solve the problem where i do not have take into account the priority, but i am struggling with this one.

```<code>Red colour: p1 (priority 1)
Blue Colour: p2 (priority 2)
Green colour: p3 (priority 3)
</code>```

Note that in the example input below we will have 9 rows having same id, and the output will have 6 rows. Please note that for some id's might have only some of the priority values or just one, the solution should take care of that.

expected input and output:

答:
This is a "combining" islands problem. One solution is to find where the islands begin and do a cumulative sum of the beginnings.  You can determine the beginning by seeing where there are no overlaps:</p>

```<code>select id, priority, min(start_time), max(stop_time)
from (select t.*,
             countif(coalesce(prev_stop_time, stop_time) < stop_time) over (partition by id, priority order by start_time) as grp
      from (select t.*,
                   max(stop_time) over (partition by id, priority order by start_time rows between unbounded preceding and 1 preceding) as prev_stop_time
            from t
           ) t
      ) t
group by id, priority, grp;
</code>```

Body:
I am trying to solve a problem where i want to merge overlapping intervals for a given column id, but i also want to merge them based on hierarchy/priority. I have start_time and stop_time for each interval and each interval has a hierarchy/priority associated with it.

These are the following columns in the table:

id, start_time, stop_time, priority

I was able to solve the problem where i do not have take into account the priority, but i am struggling with this one.

Red colour: p1 (priority 1)
Blue Colour: p2 (priority 2)
Green colour: p3 (priority 3)

Note that in the example input below we will have 9 rows having same id, and the output will have 6 rows. Please note that for some id's might have only some of the priority values or just one, the solution should take care of that.

expected input and output:

Body:
This is a "combining" islands problem. One solution is to find where the islands begin and do a cumulative sum of the beginnings.  You can determine the beginning by seeing where there are no overlaps:

select id, priority, min(start_time), max(stop_time)
from (select t.*,
             countif(coalesce(prev_stop_time, stop_time) < stop_time) over (partition by id, priority order by start_time) as grp
      from (select t.*,
                   max(stop_time) over (partition by id, priority order by start_time rows between unbounded preceding and 1 preceding) as prev_stop_time
            from t
           ) t
      ) t
group by id, priority, grp;


来源: stackexchange

问:
Delphi - Enumerate the Disk(s) and other Drives on Windows PC

Possible Duplicate:

  Get drive information (free space, etc.) for drives on Windows and populate a memo box

I am quite new to programing (especially Delphi), and have been unable to find any examples as to how to enumerate all the drives on a PC.

I really care about Hard Disks and CD-Rom drives but I have been unable to find anything useable.

Can anyone point me in the direction of a good working sample?

答: See GLibWMI Library; With It you can access information about system drives.  </p>

ContentLicense: CC BY-SA 3.0


问:
The table component does not render under IE11, given : "Error in render: "TypeError: Object doesn't support property or method 'entries'""
I'm new to the web app development, and work on a project using Vue cli, antd components, and it runs at IE11.

The IE11 seems not render the the  component, it comment out the table.

IE11 element

also give the error at console:

```<code>[Vue warn]: Error in render: "TypeError: Object doesn't support property
or method 'entries'"
</code>```

I do check tickets from ant-design-vue, it looks like no one have the same problem, so I assume it is polyfill or ES5 to ES6 setting problem.

below is my html for the page

```<code>    <template>
      <div id="detailDash">
        <h1>{{id}}</h1>
        <a-table
          :columns="columns"
          :dataSource="data"
          style="padding: 50px;"
          :bordered="true">
        </a-table>
      </div>
    </template>
</code>```

vuejs code

```<code>    <script lang="ts">
    import { Component, Prop, Vue } from 'vue-property-decorator';
    const columns = [...];
    const innerColumns = [...];
    export default  {
      data(){
        return {
          id: '',
          status:'',
          data:[....],
          columns,
          innerColumns,
        }
      },
      created() {
          this.id = this.$route.params.envID;
      },
      methods:{
        checkStatus(){
          this.state = 'success'
          return status;
        }
      }
    }
    </script>
</code>```

babel.config.js

```<code>// babel.config.js
    module.exports = {
      presets: [
        ['@vue/app',
        {
          polyfills: [
            'es6.promise',
            'es6.symbol'
          ]
        }
      ]
      ]
    }
</code>```

I have been google all day about this typeError, but not one was giving a clean solution, I really need some help for this!!

答:
You need to add polyfills to older browsers in order to have them execute code which is intended for modern browsers. Object.entries is an example of a function which does not exist on IE.

As explained in my answer to this question you can polyfill statically (in your case by editing babel.config.js), or dynamically (by using a service like polyfill.io). The advantage to using a dynamic polyfill is that the API only ships what the browser actually needs, which reduces your bundle size.

Because you are using Vue CLI, you'll need to add a script tag to your public/index.html like this:

```<code><script crossorigin="anonymous" src="https://polyfill.io/v3/polyfill.min.js?features=Object.entries%2CSymbol.iterator"></script>
</code>```

I've included Object.entries and Symbol.iterator based on your comments above. You will likely need more. Use the builder to add additional features.

Finally, you'll need to continually test your app to see which features are needed for successful execution in a given browser. You may need to repeat this process several times until all of the errors go away. Make sure to test on multiple pages, as not all of your page bundles will have the same requirements.

ContentLicense: CC BY-SA 4.0

Body:
I'm new to the web app development, and work on a project using Vue cli, antd components, and it runs at IE11.

The IE11 seems not render the the  component, it comment out the table.

IE11 element

also give the error at console:

[Vue warn]: Error in render: "TypeError: Object doesn't support property
or method 'entries'"

I do check tickets from ant-design-vue, it looks like no one have the same problem, so I assume it is polyfill or ES5 to ES6 setting problem.

below is my html for the page

    <template>

{{id}}

    </template>

vuejs code

babel.config.js

// babel.config.js
    module.exports = {
      presets: [
        ['@vue/app',
        {
          polyfills: [
            'es6.promise',
            'es6.symbol'
          ]
        }
      ]
      ]
    }

I have been google all day about this typeError, but not one was giving a clean solution, I really need some help for this!!

Body:
You need to add polyfills to older browsers in order to have them execute code which is intended for modern browsers. Object.entries is an example of a function which does not exist on IE.

As explained in my answer to this question you can polyfill statically (in your case by editing babel.config.js), or dynamically (by using a service like polyfill.io). The advantage to using a dynamic polyfill is that the API only ships what the browser actually needs, which reduces your bundle size.

Because you are using Vue CLI, you'll need to add a script tag to your public/index.html like this:

<script crossorigin="anonymous" src="https://polyfill.io/v3/polyfill.min.js?features=Object.entries%2CSymbol.iterator"></script>

I've included Object.entries and Symbol.iterator based on your comments above. You will likely need more. Use the builder to add additional features.

Finally, you'll need to continually test your app to see which features are needed for successful execution in a given browser. You may need to repeat this process several times until all of the errors go away. Make sure to test on multiple pages, as not all of your page bundles will have the same requirements.


问:
Getting errors not quite sure why this is my first cobol program
Im slowly learning COBOL and am doing some challenges to get better but i am having a weird problem that i cant seem to trace and i wanted to see if anyone else can help

I double and triple checked that what was supposed to be in area A and B where in their proper col numbers

```<code>IDENTIFICATION DIVISION.
    PROGRAM-ID. CIRCLES.

    ENVIRONMENT DIVISION.
    CONFIGURATION SECTION.
    SOURCE-COMPUTER.
    OBJECT-COMPUTER.

    INPUT-OUTPUT SECTION.
    FILE-CONTROL.

    DATA DIVISION.
    FILE SECTION.

    WORKING-STORAGE SECTION.
    01  WS-CONSTANTS.
        05  WS-PI              PIC 9V99999 VALUE 3.14159.
    01   WS-CIRCLE.
        05 WS-AREA              PIC 999V99 VALUE ZEROES.
        05 WS-RADIUS            PIC 9999V99 VALUE ZEROES.
        05 WS-CIRCUMFERENCE     PIC 99999V99 VALUE ZEROES.
    01   WS-DISPLAY-VALUES.
        05 WS-DISPLAY-AREA                     PIC ZZ99.99.
        05 WS-DISPLAY-CIRCUMFERENCE  PIC ZZ99.99.

    PROCEDURE DIVISION.

    0100-PROCESS-RECORDS.

        DISPLAY "Please enter radius of circle: ".
        ACCEPT WS-RADIUS.
        COMPUTE WS-CIRCUMFRENCE = 2 * WS-PI * WS-RADIUS.
        MOVE WS-CIRCUMFRENCE TO WS-DISPLAY-CIRCUMFRENCE.
        DISPLAY "Circle Circumfrence is: ", WS-DISPLAY-CIRCUMFRENCE.
        COMPUTE WS-RADIUS = WS-PI * WS-RADIUS * WS-RADIUS.
        MOVE WS-AREA TO WS-DISPLAY-AREA.
        DISPLAY "Circle area is:  ", WS-DISPLAY-AREA

        STOP RUN

</code>```

compiler messages:

```<code>Circles.cbl:28: error: PROCEDURE DIVISION header missing
Circles.cbl:28: error: syntax error, unexpected level-number
Circles.cbl:29: error: unknown statement '05'
Circles.cbl:30: error: unknown statement '05'
Circles.cbl:34: error: syntax error, unexpected PROCEDURE
Circles.cbl: in paragraph '0100-PROCESS-RECORDS':
Circles.cbl:40: error: 'WS-RADIUS' is not defined
Circles.cbl:41: error: 'WS-CIRCUMFRENCE' is not defined
Circles.cbl:41: error: 'WS-PI' is not defined
Circles.cbl:41: error: 'WS-RADIUS' is not defined
Circles.cbl:42: error: 'WS-CIRCUMFRENCE' is not defined
Circles.cbl:42: error: 'WS-DISPLAY-CIRCUMFRENCE' is not defined
Circles.cbl:43: error: 'WS-DISPLAY-CIRCUM' is not defined
Circles.cbl:44: error: 'WS-RADIUS' is not defined
Circles.cbl:44: error: 'WS-PI' is not defined
Circles.cbl:44: error: 'WS-RADIUS' is not defined
Circles.cbl:44: error: 'WS-RADIUS' is not defined
Circles.cbl:45: error: 'WS-AREA' is not defined
Circles.cbl:45: error: 'WS-DISPLAY-AREA' is not defined
Circles.cbl:46: error: 'WS-DISPLAY-AREA' is not defined
</code>```

答:
After putting your program into an online compiler (code+results here) two issues were seen:

typo: WS-CIRCUMFRENCE -> WS-CIRCUMFENCE

missing separator period at the end

As you seem to not use free format but the column based one I've removed that option (-free from this project, fixed the issues specified above and added the minimal indentation, result: works like a charm.

I thought about possible issues but the only one I could think of was an additional specification of DECIMAL-POINT IS COMMA - but that raises error: invalid level number '14159', or bad indentation (this would likely be seen); you may want to recheck that you don't do the indentation by TABs (their actual size may differ between what you editor shows and what the compiler uses [most compilers use a size of 8 spaces by default).

Body:
Im slowly learning COBOL and am doing some challenges to get better but i am having a weird problem that i cant seem to trace and i wanted to see if anyone else can help

I double and triple checked that what was supposed to be in area A and B where in their proper col numbers

IDENTIFICATION DIVISION.
    PROGRAM-ID. CIRCLES.

    ENVIRONMENT DIVISION.
    CONFIGURATION SECTION.
    SOURCE-COMPUTER.
    OBJECT-COMPUTER.

    INPUT-OUTPUT SECTION.
    FILE-CONTROL.

    DATA DIVISION.
    FILE SECTION.

    WORKING-STORAGE SECTION.
    01  WS-CONSTANTS.
        05  WS-PI              PIC 9V99999 VALUE 3.14159.
    01   WS-CIRCLE.
        05 WS-AREA              PIC 999V99 VALUE ZEROES.
        05 WS-RADIUS            PIC 9999V99 VALUE ZEROES.
        05 WS-CIRCUMFERENCE     PIC 99999V99 VALUE ZEROES.
    01   WS-DISPLAY-VALUES.
        05 WS-DISPLAY-AREA                     PIC ZZ99.99.
        05 WS-DISPLAY-CIRCUMFERENCE  PIC ZZ99.99.

    PROCEDURE DIVISION.

    0100-PROCESS-RECORDS.

        DISPLAY "Please enter radius of circle: ".
        ACCEPT WS-RADIUS.
        COMPUTE WS-CIRCUMFRENCE = 2 * WS-PI * WS-RADIUS.
        MOVE WS-CIRCUMFRENCE TO WS-DISPLAY-CIRCUMFRENCE.
        DISPLAY "Circle Circumfrence is: ", WS-DISPLAY-CIRCUMFRENCE.
        COMPUTE WS-RADIUS = WS-PI * WS-RADIUS * WS-RADIUS.
        MOVE WS-AREA TO WS-DISPLAY-AREA.
        DISPLAY "Circle area is:  ", WS-DISPLAY-AREA

        STOP RUN

compiler messages:

Circles.cbl:28: error: PROCEDURE DIVISION header missing
Circles.cbl:28: error: syntax error, unexpected level-number
Circles.cbl:29: error: unknown statement '05'
Circles.cbl:30: error: unknown statement '05'
Circles.cbl:34: error: syntax error, unexpected PROCEDURE
Circles.cbl: in paragraph '0100-PROCESS-RECORDS':
Circles.cbl:40: error: 'WS-RADIUS' is not defined
Circles.cbl:41: error: 'WS-CIRCUMFRENCE' is not defined
Circles.cbl:41: error: 'WS-PI' is not defined
Circles.cbl:41: error: 'WS-RADIUS' is not defined
Circles.cbl:42: error: 'WS-CIRCUMFRENCE' is not defined
Circles.cbl:42: error: 'WS-DISPLAY-CIRCUMFRENCE' is not defined
Circles.cbl:43: error: 'WS-DISPLAY-CIRCUM' is not defined
Circles.cbl:44: error: 'WS-RADIUS' is not defined
Circles.cbl:44: error: 'WS-PI' is not defined
Circles.cbl:44: error: 'WS-RADIUS' is not defined
Circles.cbl:44: error: 'WS-RADIUS' is not defined
Circles.cbl:45: error: 'WS-AREA' is not defined
Circles.cbl:45: error: 'WS-DISPLAY-AREA' is not defined
Circles.cbl:46: error: 'WS-DISPLAY-AREA' is not defined


问:
Tensorflow Dataset API : Cache
I am trying to use tf.Dataset.cache but it seems to have no affect.

I have 3 questions please:

At what point would you want to cache your dataset ? I assume it will be before any mapping action that has random behavior. Is it recommended to cache the dataset after inital parsing from a TFRecord file before any other mapping ?

How can I measure the speed-optimization affect of caching ?

I would assume I will always want to cache my images to the memory. At least some portion of it and have the pipeline feed the network faster. When will I want to cache to a file ?

Thanks!

答:
The intention of .cache function is to speed up your data pipeline by cache your samples into memory/disk space. Therefore, for all epochs after initial epoch, your pipeline will no longer need to read/parse/process. So with that being said, it is usually the best to put it at the end of your data pipeline.

You can time your first epoch and your second epoch, and see if there's speed increase.

When your images are too big to fit into memory. But disk I/O takes time too. You'll need to make sure your pipeline processing is taking way longer than that for it to be beneficial.

Title: Tensorflow Dataset API : Cache


问:
Changing font color to an article with CSS?
how can I change the font color in one article, with css. I have 3 articles, like these:  I want to change the font color to the second article, in the css file, and I don't know how...

```<code><article class="news">
           <h2>Technologiczna osobliwość</h2>
            <p>
                Technologiczna osobliwość (lub po prostu osobliwość, z ang. singularity) – hipotetyczny punkt w przyszłym rozwoju cywilizacji, w którym postęp techniczny stanie się tak szybki, że wszelkie ludzkie
            </p>
            <blockquote>Wikipedia</blockquote>
        </article>

        <article class="news active-news">
                <h2>Superinteligencja</h2>
                <p>
                    Superinteligencja lub nadludzka inteligencja – osoba przewyższająca intelektualnie każdego istniejącego człowieka, praktycznie we wszystkich aspektach, w tym również kreatywnością,
                </p>
</code>```

I tried this:

```<code>news active-news  {
    color: #1db954;
}

this:

.news active-news  {
    color: #1db954;
}

and this:

#news active-news  {
    color: #1db954;
}
</code>```

答:
You need to directly concatenate the class-names of the styles with dots if they are for the same element.

.news.active-news  {
    color: #1db954;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><article class="news">
  <h2>Technologiczna osobliwość</h2>
  <p>
  Technologiczna osobliwość (lub po prostu osobliwość, z ang. singularity) – hipotetyczny punkt w przyszłym rozwoju cywilizacji, w którym postęp techniczny stanie się tak szybki, że wszelkie ludzkie
  </p>
  <blockquote>Wikipedia</blockquote>
</article>

<article class="news active-news">
  <h2>Superinteligencja</h2>
  <p>
  Superinteligencja lub nadludzka inteligencja – osoba przewyższająca intelektualnie każdego istniejącego człowieka, praktycznie we wszystkich aspektach, w tym również kreatywnością,
  </p>
</article></code>```

Another option would be to target a second element of a kind with this (no matter if it has the active-news style):

```<code>.news:nth-child(2) {
  color: #1db954;
}
</code>```

Body:
how can I change the font color in one article, with css. I have 3 articles, like these:  I want to change the font color to the second article, in the css file, and I don't know how...

Technologiczna osobliwość

                Technologiczna osobliwość (lub po prostu osobliwość, z ang. singularity) – hipotetyczny punkt w przyszłym rozwoju cywilizacji, w którym postęp techniczny stanie się tak szybki, że wszelkie ludzkie

Wikipedia

Superinteligencja

                    Superinteligencja lub nadludzka inteligencja – osoba przewyższająca intelektualnie każdego istniejącego człowieka, praktycznie we wszystkich aspektach, w tym również kreatywnością,

I tried this:

news active-news  {
    color: #1db954;
}

this:

.news active-news  {
    color: #1db954;
}

and this:

#news active-news  {
    color: #1db954;
}

Body:
You need to directly concatenate the class-names of the styles with dots if they are for the same element.

.news.active-news  {
    color: #1db954;
}

<article class="news">
  <h2>Technologiczna osobliwość</h2>
  <p>
  Technologiczna osobliwość (lub po prostu osobliwość, z ang. singularity) – hipotetyczny punkt w przyszłym rozwoju cywilizacji, w którym postęp techniczny stanie się tak szybki, że wszelkie ludzkie
  </p>
  <blockquote>Wikipedia</blockquote>
</article>

<article class="news active-news">
  <h2>Superinteligencja</h2>
  <p>
  Superinteligencja lub nadludzka inteligencja – osoba przewyższająca intelektualnie każdego istniejącego człowieka, praktycznie we wszystkich aspektach, w tym również kreatywnością,
  </p>
</article>

Another option would be to target a second element of a kind with this (no matter if it has the active-news style):

.news:nth-child(2) {
  color: #1db954;
}


问:
Not able to reset input field in laravel
I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.

```<code> <input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>
</code>```

JS for reset button:

```<code>document.getElementById("appForm").onreset = function() {
   document.getElementById("app_number").value = "";
  };
</code>```

Reset Button:

```<code><button class="btn btn-primary" id="reset-button" type="reset">Reset</button>
</code>```

答:
Use type="reset" for your button:

```<code><button type="reset">Cancel</button>
</code>```

Body:
I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.

 <input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>

JS for reset button:

document.getElementById("appForm").onreset = function() {
   document.getElementById("app_number").value = "";
  };

Reset Button:

<button class="btn btn-primary" id="reset-button" type="reset">Reset</button>

Body:
Use type="reset" for your button:

<button type="reset">Cancel</button>


问:
How can I elegantly implement multiple string replacements in the same file?
Currently I have some code to replace strings in a file that looks like this:

```<code>File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "( " + column.Key + " )",
    " " + column.Value + " "
));
File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]"
));
</code>```

However, each replacement opens and closes the file, and it seems that occasionally they run "too fast" and one replacement will not work because the file did not close yet in a previous string replacement. Is there any code I can reuse that solves this issue, perhaps using the FileStream class (so I can open and close once)? Or suggestions on a better way to do this? Just wondering if there is something simpler I can do than having to create byte arrays of the strings I want to replace and writing code to read, write, and seek through bytes manually. Thanks.

答:
Well, I'd use:

```<code> string text = File.ReadAllText(filePath);

 text = Regex.Replace(...);
 text = Regex.Replace(...);
 ...
 File.WriteAllText(filePath, text);
</code>```

I'm still surprised to hear that the original code didn't work though. It wasn't pleasant in terms of multiple writes and reads, but I'd have expected it to work.

Body:
Currently I have some code to replace strings in a file that looks like this:

File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "( " + column.Key + " )",
    " " + column.Value + " "
));
File.WriteAllText(filePath, Regex.Replace(File.ReadAllText(filePath),
    "(\\[\"" + column.Key + "\"\\])",
    "[\"" + column.Value + "\"]"
));

However, each replacement opens and closes the file, and it seems that occasionally they run "too fast" and one replacement will not work because the file did not close yet in a previous string replacement. Is there any code I can reuse that solves this issue, perhaps using the FileStream class (so I can open and close once)? Or suggestions on a better way to do this? Just wondering if there is something simpler I can do than having to create byte arrays of the strings I want to replace and writing code to read, write, and seek through bytes manually. Thanks.

Body:
Well, I'd use:

 string text = File.ReadAllText(filePath);

 text = Regex.Replace(...);
 text = Regex.Replace(...);
 ...
 File.WriteAllText(filePath, text);

I'm still surprised to hear that the original code didn't work though. It wasn't pleasant in terms of multiple writes and reads, but I'd have expected it to work.


问:
How to copy an array of floats from c# to a C dll
I'm trying to copy an array of floats from my C# application to an array in a C-coded DLL.

Im used to programming in C#, not so much with C. However I have no problem doing the reverse procedure ie. reading an array of floats from a C coded DLL into my C# application.  I've read several threads on this site but cant work out where Im going wrong.

C# CODE

```<code>[DllImport(@"MyDll")]
static extern int CopyArray(double[] MyArray);

double[] myValues = new double[100]
int a = 0;
while(a < 100)
{
    myValues[a] = a;
    a++;
}

CopyArray(myValues);
</code>```

C++ DLL

This is the function header;

```<code>__declspec(dllexport) int CopyArray(float* Wavelengths);
</code>```

This is the function code;

```<code>float theValues[100];
int CopyArray(float* theArray)
{
    status = 0;
    int count = 0;
    while (count < 100)
    {
        theValues[count] = theArray[count];
        ++count;
    }
    return(status);
}
</code>```

I'm expecting my C# array to end up in the C array "theValues" but that's not happening. There is nothing getting into "theValues" array.

答:
A couple of things.

You are mixing data types and they are different lengths (float is 32bit and double is 64bit). Both types exist in both languages, but your caller and callee need to agree on the data type. Here is a list of data types and their managed/unmanaged equivalents.

The parameter you are sending is not a pointer. It might be translated to that automatically by the compiler, but there are several options. It is entirely possible that the compiler will pick one you don't want (more info here). The one you are probably looking for is [In]. If you want to get data back from C to C#, you will also want [Out]:

```<code>[DllImport(@"MyDll")]
static extern int CopyArray([In, Out]double[] MyArray);
</code>```

Body:
I'm trying to copy an array of floats from my C# application to an array in a C-coded DLL.

Im used to programming in C#, not so much with C. However I have no problem doing the reverse procedure ie. reading an array of floats from a C coded DLL into my C# application.  I've read several threads on this site but cant work out where Im going wrong.

C# CODE

[DllImport(@"MyDll")]
static extern int CopyArray(double[] MyArray);

double[] myValues = new double[100]
int a = 0;
while(a < 100)
{
    myValues[a] = a;
    a++;
}

CopyArray(myValues);

C++ DLL

This is the function header;

__declspec(dllexport) int CopyArray(float* Wavelengths);

This is the function code;

float theValues[100];
int CopyArray(float* theArray)
{
    status = 0;
    int count = 0;
    while (count < 100)
    {
        theValues[count] = theArray[count];
        ++count;
    }
    return(status);
}

I'm expecting my C# array to end up in the C array "theValues" but that's not happening. There is nothing getting into "theValues" array.

Body:
A couple of things.

You are mixing data types and they are different lengths (float is 32bit and double is 64bit). Both types exist in both languages, but your caller and callee need to agree on the data type. Here is a list of data types and their managed/unmanaged equivalents.

The parameter you are sending is not a pointer. It might be translated to that automatically by the compiler, but there are several options. It is entirely possible that the compiler will pick one you don't want (more info here). The one you are probably looking for is [In]. If you want to get data back from C to C#, you will also want [Out]:

[DllImport(@"MyDll")]
static extern int CopyArray([In, Out]double[] MyArray);


问:
invalid relational operator error in case statement
i am gettng invalid relational operator in the query

```<code>AND CASE WHEN UPPER(TRIM(XXCORP_OM_DEALER_FEE_DIS_LIN.FEE_TYPE))='DEALER
DIRECT' THEN NULL ELSE XXCORP_OM_DEALER_FEE_DIS_LIN.FEE_TYPE END
AND CASE WHEN UPPER(TRIM(XXCORP_OM_DEALER_FEE_DIS_LIN_FEE_TYPE))='DEALER
DIRECT' THEN NULL ELSE XXCORP_OM_DEALER_FEE_DIS_LIN_FEE_TYPE END
</code>```

error message:ORA-00920: invalid relational operator
00920. 00000 -  "invalid relational operator"

答:
The operator AND operates on Boolean expressions (returning TRUE or FALSE).

You apply AND to this expression:

```<code>CASE
  WHEN UPPER(TRIM(XXCORP_OM_DEALER_FEE_DIS_LIN.FEE_TYPE))='DEALER DIRECT' THEN NULL
  ELSE XXCORP_OM_DEALER_FEE_DIS_LIN.FEE_TYPE
END
</code>```

which obviously does not return a Boolean value.

Maybe you miss something like:

```<code>AND CASE...END = somethingelse AND ...
</code>```

Body:
i am gettng invalid relational operator in the query

AND CASE WHEN UPPER(TRIM(XXCORP_OM_DEALER_FEE_DIS_LIN.FEE_TYPE))='DEALER
DIRECT' THEN NULL ELSE XXCORP_OM_DEALER_FEE_DIS_LIN.FEE_TYPE END
AND CASE WHEN UPPER(TRIM(XXCORP_OM_DEALER_FEE_DIS_LIN_FEE_TYPE))='DEALER
DIRECT' THEN NULL ELSE XXCORP_OM_DEALER_FEE_DIS_LIN_FEE_TYPE END

error message:ORA-00920: invalid relational operator
00920. 00000 -  "invalid relational operator"

Body:
The operator AND operates on Boolean expressions (returning TRUE or FALSE).

You apply AND to this expression:

CASE
  WHEN UPPER(TRIM(XXCORP_OM_DEALER_FEE_DIS_LIN.FEE_TYPE))='DEALER DIRECT' THEN NULL
  ELSE XXCORP_OM_DEALER_FEE_DIS_LIN.FEE_TYPE
END

which obviously does not return a Boolean value.

Maybe you miss something like:

AND CASE...END = somethingelse AND ...


问:
Is it possible to declare a string / int as numer?
I want to parse JSON in Java, but my JSON lookslike this:

```<code>...
{
    "total_count": 16,
    "entries": [
        {
            "2": "1788",
            "3": "Yes",
            "id": "2009131"
         },
         {
            "2": "956",
            "3": "No",
            "id": "1381"
         }
...
</code>```

I already figured out to "extract" the entries by:

```<code>if(jsonTree.isJsonObject()){
            System.out.println("True");
            JsonObject jsonObject = jsonTree.getAsJsonObject();

            JsonElement f2 = jsonObject.get("entries");
</code>```

Now I've a JSON array. For parsing with gson, I would need a class with variables like this (at least I think so):

```<code>int 2;
String 3;
</code>```

which isn't declarable as far as I know.

Is there a way (prefix, syntax?) to implement anyways? Or another way to extract and assign the values with the right id?

答:
You can use SerializedName annotation which allow to define field name different than property name in Java file. Below you can see example how to deserialise your JSON payload to Java model:

```<code>import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

import java.io.File;
import java.io.FileReader;
import java.util.List;

public class GsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Root root = gson.fromJson(new FileReader(jsonFile), Root.class);
        System.out.println(root);
    }
}

class Root {

    @SerializedName("total_count")
    private int totalCount;
    private List<Entry> entries;

    // getters, setters, toString
}

class Entry {
    private String id;

    @SerializedName("2")
    private String two;

    @SerializedName("3")
    private String three;

    // getters, setters, toString
}
</code>```

Above code prints:

```<code>Root{totalCount=16, entries=[Entry{id='2009131', two='1788', three='Yes'}, Entry{id='1381', two='956', three='No'}]}
</code>```

If your JSON is dynamic and can have more/less keys you can deserialise it to Map<String, String>:

```<code>import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

import java.io.File;
import java.io.FileReader;
import java.util.List;
import java.util.Map;

public class GsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Root root = gson.fromJson(new FileReader(jsonFile), Root.class);
        System.out.println(root);
    }
}

class Root {

    @SerializedName("total_count")
    private int totalCount;
    private List<Map<String, String>> entries;

    // getters, setters, toString
}
</code>```

Above code prints:

```<code>Root{totalCount=16, entries=[{2=1788, 3=Yes, id=2009131}, {2=956, 3=No, id=1381}]}
</code>```

Body:
I want to parse JSON in Java, but my JSON lookslike this:

...
{
    "total_count": 16,
    "entries": [
        {
            "2": "1788",
            "3": "Yes",
            "id": "2009131"
         },
         {
            "2": "956",
            "3": "No",
            "id": "1381"
         }
...

I already figured out to "extract" the entries by:

if(jsonTree.isJsonObject()){
            System.out.println("True");
            JsonObject jsonObject = jsonTree.getAsJsonObject();

            JsonElement f2 = jsonObject.get("entries");

Now I've a JSON array. For parsing with gson, I would need a class with variables like this (at least I think so):

int 2;
String 3;

which isn't declarable as far as I know.

Is there a way (prefix, syntax?) to implement anyways? Or another way to extract and assign the values with the right id?

Body:
You can use SerializedName annotation which allow to define field name different than property name in Java file. Below you can see example how to deserialise your JSON payload to Java model:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

import java.io.File;
import java.io.FileReader;
import java.util.List;

public class GsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Root root = gson.fromJson(new FileReader(jsonFile), Root.class);
        System.out.println(root);
    }
}

class Root {

    @SerializedName("total_count")
    private int totalCount;
    private List<Entry> entries;

    // getters, setters, toString
}

class Entry {
    private String id;

    @SerializedName("2")
    private String two;

    @SerializedName("3")
    private String three;

    // getters, setters, toString
}

Above code prints:

Root{totalCount=16, entries=[Entry{id='2009131', two='1788', three='Yes'}, Entry{id='1381', two='956', three='No'}]}

If your JSON is dynamic and can have more/less keys you can deserialise it to Map<String, String>:

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

import java.io.File;
import java.io.FileReader;
import java.util.List;
import java.util.Map;

public class GsonApp {

    public static void main(String[] args) throws Exception {
        File jsonFile = new File("./resource/test.json").getAbsoluteFile();

        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        Root root = gson.fromJson(new FileReader(jsonFile), Root.class);
        System.out.println(root);
    }
}

class Root {

    @SerializedName("total_count")
    private int totalCount;
    private List<Map<String, String>> entries;

    // getters, setters, toString
}

Above code prints:

Root{totalCount=16, entries=[{2=1788, 3=Yes, id=2009131}, {2=956, 3=No, id=1381}]}


问:
Singleton time triggered Azure Function across multiple regions
I have a time triggered Azure Function deployed in multiple regions and I want to have singleton behavior across them. For example, if the regions are west US and central Europe, I want only one of them to run each time. Can this be achieved?

As the documentation says, TimeTrigger uses the Singleton attribute implicitly to ensure only one instance of a function is run per host, so that aspect is covered.

In order to have the same behavior in all regions, I tried using Singleton with the following parameters:

```<code>[Singleton(Account = "myAccount", Mode = SingletonMode.Listener)]
</code>```

I tested it locally by copying my C# solution and running both projects. The following error was shown:

```<code>The listener for function 'MyFunction' was unable to start.
Microsoft.Azure.WebJobs.Host.Storage: Must replace singleton lease manager to
support multiple accounts.
</code>```

I did not find information about the Account property more than from the metadata of the Singleton class, that says Gets the name of the Azure Storage account that the blob lease should be created in. I don't know how the function knows how to connect to the Storage and where to configure the connection.

答:
I believe the Account property of the [Singleton] attribute refers to the name of an app setting, not actually the name of your storage account. If not specified, it assumes the storage account specified by the AzureWebJobsStorage app setting. The app setting that you reference here will need to contain the full storage connection string.

Note that if you want cross-region singleton behavior, all copies of your app will need to use the same storage account (which obviously could live in some other region). I expect there will be some egress charges related to this, but hopefully not enough to have much impact. Something to be aware of, though.

UPDATE:

Regarding the error message you encountered, it turns out there's actually an issue with this feature in Functions 2.0. A new GitHub issue was recently opened which tracks the problem: https://github.com/Azure/azure-webjobs-sdk/issues/2214. It also points to a temporary workaround, which is that you can register your own IDistributedLockManagerimplementation, as shown in the test code.

Body:
I have a time triggered Azure Function deployed in multiple regions and I want to have singleton behavior across them. For example, if the regions are west US and central Europe, I want only one of them to run each time. Can this be achieved?

As the documentation says, TimeTrigger uses the Singleton attribute implicitly to ensure only one instance of a function is run per host, so that aspect is covered.

In order to have the same behavior in all regions, I tried using Singleton with the following parameters:

[Singleton(Account = "myAccount", Mode = SingletonMode.Listener)]

I tested it locally by copying my C# solution and running both projects. The following error was shown:

The listener for function 'MyFunction' was unable to start.
Microsoft.Azure.WebJobs.Host.Storage: Must replace singleton lease manager to
support multiple accounts.

I did not find information about the Account property more than from the metadata of the Singleton class, that says Gets the name of the Azure Storage account that the blob lease should be created in. I don't know how the function knows how to connect to the Storage and where to configure the connection.


问:
Multiple where clauses, reading only one
I have to retrieve information with multiple where clauses. I can do this only using nested query. I'm supposed to be able to pull out information of 2 shiftName queries on one command.
Find the first and last name of a staff whose shifts are Classy Evening and Morning Shine.

So far whatever little luck I've found is with this code, but the problem here is it is returning results of 'Morning Shine' but not of 'Classy Evening'.
It's like the nested query is not even being processed. Can someone please help. I'm new to SQL so I apologise if my question is not clear enough.

```<code>SELECT stfName, stlNname
FROM STAFF, STAFF_SHIFT_CENTER
WHERE STAFF.staffID=STAFF_SHIFT_CENTER.staffID
AND STAFF_SHIFT_CENTER.shiftName='Morning Shine'
AND (SELECT staffID FROM STAFF_SHIFT_CENTER
WHERE shiftName='Classy Evening');
</code>```

答:
You can use aggregation for this.

```<code>SELECT s.stfName, s.stlNname
FROM STAFF s JOIN
     STAFF_SHIFT_CENTER ssc
     ON s.staffID = ssc.staffID
WHERE ssc.shiftName IN ('Morning Shine', 'Classy Evening')
GROUP BY s.stfName, s.stlNname
HAVING COUNT(DISTINCT ssc.shfitName) = 2;  -- each group has both shifts
</code>```

Notes:

Never use commas in the FROM clause.

Always use proper, explicit, standard JOIN syntax.

Table aliases make the query easier to write and to read.

Qualify all column names, so you know what table they are coming from.

Body:
I have to retrieve information with multiple where clauses. I can do this only using nested query. I'm supposed to be able to pull out information of 2 shiftName queries on one command.
Find the first and last name of a staff whose shifts are Classy Evening and Morning Shine.

So far whatever little luck I've found is with this code, but the problem here is it is returning results of 'Morning Shine' but not of 'Classy Evening'.
It's like the nested query is not even being processed. Can someone please help. I'm new to SQL so I apologise if my question is not clear enough.

SELECT stfName, stlNname
FROM STAFF, STAFF_SHIFT_CENTER
WHERE STAFF.staffID=STAFF_SHIFT_CENTER.staffID
AND STAFF_SHIFT_CENTER.shiftName='Morning Shine'
AND (SELECT staffID FROM STAFF_SHIFT_CENTER
WHERE shiftName='Classy Evening');

Body:
You can use aggregation for this.

SELECT s.stfName, s.stlNname
FROM STAFF s JOIN
     STAFF_SHIFT_CENTER ssc
     ON s.staffID = ssc.staffID
WHERE ssc.shiftName IN ('Morning Shine', 'Classy Evening')
GROUP BY s.stfName, s.stlNname
HAVING COUNT(DISTINCT ssc.shfitName) = 2;  -- each group has both shifts

Notes:

Never use commas in the FROM clause.

Always use proper, explicit, standard JOIN syntax.

Table aliases make the query easier to write and to read.

Qualify all column names, so you know what table they are coming from.


问:
How to find the most common n elements in groups of arrays
I have a db with ~30K properties.  Each property has anywhere from 1 to 200 tenants (about 100K tenants).  I am looking to find the most common grouping of n tenants (where n is generally 3, 4 or 5).

Say n = 3.

```<code>Property 1 -<br>
 Tenants - A, B, C, D, E<br>
Property 2 - <br>
 Tenants - A, D, E, F, G<br>
Property 3 - <br>
 Tenants - A, B, G, H, I<br>
Property 4 - <br>
 Tenants - A, J, K, L, M<br>
</code>```

In this case, even though A has 4 occurrences, the most frequent count of 3 common elements is 2 instances of A, D, E in properties 1 and 2.

I don't know where to start to set this up as a re-usable algorithm.  Can someone, much smarter than I, please point me in the right direction?  Many thanks.

答:
Assuming your database defines a many-to-many relationship between properties and tenants, you can self-join the relation table to get that result. Here's an example with n=3.

SELECT p1.tenant, p2.tenant, p3.tenant, COUNT(p1.property) occurrences
FROM property_tenants p1
JOIN property_tenants p2 ON p1.property = p2.property AND p1.tenant < p2.tenant
JOIN property_tenants p3 ON p1.property = p3.property AND p2.tenant < p3.tenant
GROUP BY p1.tenant, p2.tenant, p3.tenant
ORDER BY occurrences DESC
```

I don't really know how well this will perform with a large set of data, to be honest. I can just see that it works logically.

Body:
I have a db with ~30K properties.  Each property has anywhere from 1 to 200 tenants (about 100K tenants).  I am looking to find the most common grouping of n tenants (where n is generally 3, 4 or 5).

Say n = 3.

Property 1 -

 Tenants - A, B, C, D, E

Property 2 -

 Tenants - A, D, E, F, G

Property 3 -

 Tenants - A, B, G, H, I

Property 4 -

 Tenants - A, J, K, L, M

In this case, even though A has 4 occurrences, the most frequent count of 3 common elements is 2 instances of A, D, E in properties 1 and 2.

I don't know where to start to set this up as a re-usable algorithm.  Can someone, much smarter than I, please point me in the right direction?  Many thanks.

Body:
Assuming your database defines a many-to-many relationship between properties and tenants, you can self-join the relation table to get that result. Here's an example with n=3.

SELECT p1.tenant, p2.tenant, p3.tenant, COUNT(p1.property) occurrences
FROM property_tenants p1
JOIN property_tenants p2 ON p1.property = p2.property AND p1.tenant < p2.tenant
JOIN property_tenants p3 ON p1.property = p3.property AND p2.tenant < p3.tenant
GROUP BY p1.tenant, p2.tenant, p3.tenant
ORDER BY occurrences DESC

I don't really know how well this will perform with a large set of data, to be honest. I can just see that it works logically.


问:
Get commit hash for a commit in a branch
In a git branch I store the latest commit hash SHA using

latest_sha=$(git log --pretty=oneline | head -1 | cut -d ' ' -f 1)

After a bunch of commits in this branch, how do I get the next commit SHA after the latest_sha.

Say if there are 5 commits made to this branch after the $latest_sha.

I want to always get the SHA of the first commit after the latest_sha.

```<code>b8eead8ba4ff375911af6
c2452680eb7731e4d36ca
da2e113ca4768f5f34730
95b98d42a6e567ed56fc2
716c4f84a855f48bee55c
6a7223a74269f925cfd9e---I need this one
e945bcfabf3fbafc85084---latest_sha
159df375376ded565bec0
d725350982626f46a8b80
56a4b6ca91d93acc8d751
de584608616b1ed99a554
3cfc15339a98bb286d5baa
6ae834bf36c90fbd81854
fa9bdebd0f814f04ee05ba
cc44c4d9ff14314c1255da
5a6145586a8fdcaa2da659
bfea8cfe121d24a0ff1525

</code>```

Thanks!

答:
A Git branch name, in a sense, is the latest hash ID.  That is, if git log branchX shows you commit b8eead8ba4ff375911af6 first, then branchX is a name representing b8eead8ba4ff375911af6, and:

```<code>git show branchX
</code>```

will show the same commit as:

```<code>git show b8eead8ba4ff375911af6
</code>```

If you need the hash ID for some reason—e.g., because you're going to change the hash ID to which the branch name points, by adding new commits—the simplest command to get it is git rev-parse:

```<code>hash=$(git rev-parse refs/heads/$branch)
</code>```

For the rest, see alfunx's answer.  Note that if the commits form a diamond-shaped graph, e.g.:

```<code>          I--J
         /    \
...--G--H      M--N   <-- branchX
         \    /
          K--L
</code>```

then there are two commits that immediately follow H, but either I nor K are ancestors of each other, they're only related by both being descendants of H and ancestors (grandparents, in this case) of merge commit M.  Using git rev-list --ancestry-path ^<anything-identifying-H> <anything-identifying-branchX> will list commits I, J, K, L, M, and N. The listing will start at N and move back to M as its second entry, but at this point, Git now has a choice of whether to list J or L.  This is where the sorting options you choose go into effect.  The default sort is chronological by committer date-and-time stamp.

Having listed either J or L, Git can now list the parent of whichever commit it listed, or the remaining commit on the other fork of history.  Git will list one of them.  If it chose to list J first, then I, it must now list L and then K in that order; if it chose to list L first, then K, it must now show I and then J in that order.  But it might also list them in the order J, L, K, I, for instance; or J, L, I, K.  Adding --topo-order constrains git rev-list to avoid interleaving commits from the two legs.

The linearization order in complex graphs is generally problematic: there's no single solution that handles all cases.  That's why git rev-list offers multiple sorting options.

Body:
In a git branch I store the latest commit hash SHA using

latest_sha=$(git log --pretty=oneline | head -1 | cut -d ' ' -f 1)

After a bunch of commits in this branch, how do I get the next commit SHA after the latest_sha.

Say if there are 5 commits made to this branch after the $latest_sha.

I want to always get the SHA of the first commit after the latest_sha.

b8eead8ba4ff375911af6
c2452680eb7731e4d36ca
da2e113ca4768f5f34730
95b98d42a6e567ed56fc2
716c4f84a855f48bee55c
6a7223a74269f925cfd9e---I need this one
e945bcfabf3fbafc85084---latest_sha
159df375376ded565bec0
d725350982626f46a8b80
56a4b6ca91d93acc8d751
de584608616b1ed99a554
3cfc15339a98bb286d5baa
6ae834bf36c90fbd81854
fa9bdebd0f814f04ee05ba
cc44c4d9ff14314c1255da
5a6145586a8fdcaa2da659
bfea8cfe121d24a0ff1525

Thanks!

Body:
A Git branch name, in a sense, is the latest hash ID.  That is, if git log branchX shows you commit b8eead8ba4ff375911af6 first, then branchX is a name representing b8eead8ba4ff375911af6, and:

git show branchX

will show the same commit as:

git show b8eead8ba4ff375911af6

If you need the hash ID for some reason—e.g., because you're going to change the hash ID to which the branch name points, by adding new commits—the simplest command to get it is git rev-parse:

hash=$(git rev-parse refs/heads/$branch)

For the rest, see alfunx's answer.  Note that if the commits form a diamond-shaped graph, e.g.:

          I--J
         /    \
...--G--H      M--N   <-- branchX
         \    /
          K--L

then there are two commits that immediately follow H, but either I nor K are ancestors of each other, they're only related by both being descendants of H and ancestors (grandparents, in this case) of merge commit M.  Using git rev-list --ancestry-path ^<anything-identifying-H> <anything-identifying-branchX> will list commits I, J, K, L, M, and N. The listing will start at N and move back to M as its second entry, but at this point, Git now has a choice of whether to list J or L.  This is where the sorting options you choose go into effect.  The default sort is chronological by committer date-and-time stamp.

Having listed either J or L, Git can now list the parent of whichever commit it listed, or the remaining commit on the other fork of history.  Git will list one of them.  If it chose to list J first, then I, it must now list L and then K in that order; if it chose to list L first, then K, it must now show I and then J in that order.  But it might also list them in the order J, L, K, I, for instance; or J, L, I, K.  Adding --topo-order constrains git rev-list to avoid interleaving commits from the two legs.

The linearization order in complex graphs is generally problematic: there's no single solution that handles all cases.  That's why git rev-list offers multiple sorting options.


问:
Running GridSearch over voting classifier
Trying to run gridsearch over a voting ensemble combining a few classifiers. I keep encountering the same error when running my code

```<code>ValueError: Invalid parameter n_estimator for estimator GradientBoostingClassifier(criterion='friedman_mse', init=None,
              learning_rate=0.1, loss='deviance', max_depth=3,
              max_features=None, max_leaf_nodes=None,
              min_impurity_decrease=0.0, min_impurity_split=None,
              min_samples_leaf=1, min_samples_split=2,
              min_weight_fraction_leaf=0.0, n_estimators=100,
              n_iter_no_change=None, presort='auto', random_state=1,
              subsample=1.0, tol=0.0001, validation_fraction=0.1,
              verbose=0, warm_start=False). Check the list of available parameters with `estimator.get_params().keys()`.
</code>```

Here is the code I have:

```<code>dtc = DecisionTreeClassifier(random_state=1)
rfc = RandomForestClassifier(random_state=1)
ada = AdaBoostClassifier(random_state=1)
gdb = GradientBoostingClassifier(random_state=1)
eclf = VotingClassifier(estimators=[('dtc',dtc),('rfc',rfc),
                                          ('ada',ada),('gdb',gdb)],voting='hard')
#tuning parameters with gridsearch
params = [{'gdb__n_estimator':[10,20]}]
grid_search = GridSearchCV(eclf,params,cv=5,scoring='accuracy')
grid_search.fit(X_train,y_train)
</code>```

答:
Looking more closely, you'll see that the actual name of the parameter is n_estimators (plural); so, your params should be:

```<code>params = [{'gdb__n_estimators':[10,20]}]
</code>```

i.e. it is just a typo.

Body:
Trying to run gridsearch over a voting ensemble combining a few classifiers. I keep encountering the same error when running my code

ValueError: Invalid parameter n_estimator for estimator GradientBoostingClassifier(criterion='friedman_mse', init=None,
              learning_rate=0.1, loss='deviance', max_depth=3,
              max_features=None, max_leaf_nodes=None,
              min_impurity_decrease=0.0, min_impurity_split=None,
              min_samples_leaf=1, min_samples_split=2,
              min_weight_fraction_leaf=0.0, n_estimators=100,
              n_iter_no_change=None, presort='auto', random_state=1,
              subsample=1.0, tol=0.0001, validation_fraction=0.1,
              verbose=0, warm_start=False). Check the list of available parameters with `estimator.get_params().keys()`.

Here is the code I have:

dtc = DecisionTreeClassifier(random_state=1)
rfc = RandomForestClassifier(random_state=1)
ada = AdaBoostClassifier(random_state=1)
gdb = GradientBoostingClassifier(random_state=1)
eclf = VotingClassifier(estimators=[('dtc',dtc),('rfc',rfc),
                                          ('ada',ada),('gdb',gdb)],voting='hard')
#tuning parameters with gridsearch
params = [{'gdb__n_estimator':[10,20]}]
grid_search = GridSearchCV(eclf,params,cv=5,scoring='accuracy')
grid_search.fit(X_train,y_train)

Body:
Looking more closely, you'll see that the actual name of the parameter is n_estimators (plural); so, your params should be:

params = [{'gdb__n_estimators':[10,20]}]

i.e. it is just a typo.


答:
In this case you must use JQuery Lib. Basic you need to set ID for this element. And in jquery you listen click on this Element.</p>

```<code>$('#app_number').on('change', function () {
   // enter code here
});
</code>```

Title: Not able to reset input field in laravel

Body:
I need to reset the input field when user clicks on the rest button, I have other content on the page which is getting cleared except input field, I'm not sure if this is happening because I'm using old values after post request.

 <input type="text" name="app_number" class="form-control" onreset="this.value=''" value="{!! Request::input('app_number') !!}" id="app_number" placeholder="Application Number" required>

JS for reset button:

document.getElementById("appForm").onreset = function() {
   document.getElementById("app_number").value = "";
  };

Reset Button:

<button class="btn btn-primary" id="reset-button" type="reset">Reset</button>

Body:
In this case you must use JQuery Lib. Basic you need to set ID for this element. And in jquery you listen click on this Element.

$('#app_number').on('change', function () {
   // enter code here
});


问:
What steps should I take to determine the value category of an expression?
I'm rather confused about determiming the value category of an expression. Could you please provide the basic steps that should be taken (what should be analysed) to determing the value category of an expression?</p>

答:
If you just want a quick and usually correct answer, consider these rules of thumb:

If it's a function or an already existing object, then it's a glvalue.

Most glvalues are lvalues.

xvalues are the things that can specifically be moved from: casts to an rvalue reference type, or a function call where the function return type is an rvalue reference type (especially std::move and sometimes std::forward).

If it's just a value or a way of creating a new object, then it's a prvalue.

But there are some cases where the category could still be unclear.  And the above involves some simplifications (in particular, the rules for A.B and A ? B : C are more complicated).

The only really reliable way is to look for your answer in the Standard.

Determine what sort of expression you have in terms of the grammar. A literal? An operator expression? A lambda? Etc.

If the expression is an operator expression, figure out if overload resolution will select some overloaded operator function or a built-in candidate operator, as described in [over.match.oper], [over.oper], and [over.built].

If the expression is actually a call to an overloaded operator function, the value category is determined from the return type of the operator function selected by overload resolution, as described in [expr.call].  In this case, ignore the description of built-in operator behavior for this purpose.

Otherwise, find the section of [expr.prim] or [expr.compound] (see the table of contents) for the grammatical form of the expression.  That section will state how the value category of the expression is determined.  It will often be necessary to know the types and value categories of any subexpressions, so you may need to follow these rules recursively.


问:
Passing props to URL
I am using deckofcardsapi.com and I cannot pass my deck_id in props to fetch url.

Props are passing ok because when I use them in line 40 they display as normal string. And when I paste this string to variable deckId in line 23 it is giving me list of cards.

But when instead of copying string to deckId i use props.deckId there is error "TypeError: cards.cards is undefined"

On the other hand props.quantity works well.

Here is my code

```<code>import React, { useState, useEffect } from 'react';

function NewDeck(props) {
  const [deck, setDeck] = useState({ deck_id: [] });

  async function draw() {
    const result = await fetch(`https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1`);
    const json = await result.json();
    setDeck(json);
  };

    useEffect(() => {
    draw();
  }, []);

  return(
    <Draw deckId={deck.deck_id} quantity={props.quantity} />
  );
}

function Draw(props) {
  const [cards, setCards] = useState({ cards: [] });
  var deckId = props.deckId;  //when i put here for egzample "l31hmefvilqe" it is working

  async function draw() {
    const result = await fetch(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=${props.quantity}`);
    const json = await result.json();
    setCards(json);
  };

    useEffect(() => {
    draw();
  }, []);

  return(
    <ul>
      {cards.cards.map(item => (
        <li>{item.code}</li>
      ))}
      <li>deckId: {props.deckId}</li>
      <li>quantity: {props.quantity}</li>
    </ul>
  );
}

export default NewDeck;
</code>```

How to pass props.deckId to my fetch's url

I was searching for answer but with no result. This is probably my stupid mistake but i can't find it.

Thank you in adwance

答:
The problem is that at the first render of NewDeck the value of deck_id isn't set and it pass an empty array. You can fix it rendering the Draw component conditionally to the deck_id having a value . https://codesandbox.io/s/brave-margulis-olgxt In my example i set the deck_id to null and render draw only when deck_id exists.

PD: props.quantity is undefined and maybe you meant deck.remaining? Also check the draw() dependency for useEffect in the component, maybe you need to useCallback() (I0m not so sure of this because I'm still learning hooks)

Title: Passing props to URL

Body:
I am using deckofcardsapi.com and I cannot pass my deck_id in props to fetch url.

Props are passing ok because when I use them in line 40 they display as normal string. And when I paste this string to variable deckId in line 23 it is giving me list of cards.

But when instead of copying string to deckId i use props.deckId there is error "TypeError: cards.cards is undefined"

On the other hand props.quantity works well.

Here is my code

import React, { useState, useEffect } from 'react';

function NewDeck(props) {
  const [deck, setDeck] = useState({ deck_id: [] });

  async function draw() {
    const result = await fetch(`https://deckofcardsapi.com/api/deck/new/shuffle/?deck_count=1`);
    const json = await result.json();
    setDeck(json);
  };

    useEffect(() => {
    draw();
  }, []);

  return(
    <Draw deckId={deck.deck_id} quantity={props.quantity} />
  );
}

function Draw(props) {
  const [cards, setCards] = useState({ cards: [] });
  var deckId = props.deckId;  //when i put here for egzample "l31hmefvilqe" it is working

  async function draw() {
    const result = await fetch(`https://deckofcardsapi.com/api/deck/${deckId}/draw/?count=${props.quantity}`);
    const json = await result.json();
    setCards(json);
  };

    useEffect(() => {
    draw();
  }, []);

  return(

      {cards.cards.map(item => (

{item.code}

      ))}

deckId: {props.deckId}

quantity: {props.quantity}

  );
}

export default NewDeck;

How to pass props.deckId to my fetch's url

I was searching for answer but with no result. This is probably my stupid mistake but i can't find it.

Thank you in adwance


问:
Exporting Data from Postgres with Copy command in SpringBoot
I'm trying to do an export of a PostgreSQL table from Spring-boot application. I've a logic to select all the records and map it to a CSV. The application presently retrieves all the data and uses CSV libraries to format/export it. There is also direct command from PostgreSQL to export the data (COPY command), without using any APIs. Is it a way to have this done from application.

Added Queries from Spring-boot and tried executing the copy operation, where the spring is not allowing the command execution.

CopyManager from Postgres is recommended with Spring-boot?

Is there a way i can get the data directly from DB without the data getting retrieved by the application?

答:
COPY will create a file on the database server, so unless that's really what you want, don't use COPY.

If you want the data in a file on the application machine, use a SELECT statement, and format the output as CSV in the Java code, preferably using a CSV library.


问:
Mailchimp Restful API 3.0 in Node.js always Resource not Found
I'm trying to hit one of the mailchimp's api, but for somehow I always get

```<code>   {
  "type": "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
  "title": "Resource Not Found",
  "status": 404,
  "detail": "The requested resource could not be found.",
  "instance": ""
}
</code>```

I'm using request library to make the request and see the code below

```<code>var uniqueListId = "XXXX";
var apiKey = "XXX";

  .post(function(req, res) {
      var email = req.body.email;
      var status = "subscribed";

      request({
        url: 'https://usX.api.mailchimp.com/3.0/lists/' + uniqueListId + '/members',
        headers: {
          'Authorization': 'randomUser ' + apiKey,
          'Content-Type': 'application/json',
        },
        method: 'POST',
        json: {
          email_address: email,
          status: status
        }
      }, function(err, response, body) {
        if (err) {
          res.json(err);
        } else {
          res.json(response.statusCode, body);
        }
      });
    });
</code>```

For the sake of clarity, this is the documentation that I'm referring to http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/

Is it because of my req.body data?

答:
You're almost certainly confusing mailchimp's web_id with list_id. The list_id is the one you need for the API, the web_id is the one you see in the url when you open your list.
I have absolutely no idea why mailchimp uses 2 different ids, nor why they don't seem to put it forward in any of their developer documentation.

Below is an article which explains how to find it - basically you go to your list -> settings tab -> list name and defaults.

https://3by400.com/get-support/3by400-knowledgebase?view=kb&kbartid=6

Body:
I'm trying to hit one of the mailchimp's api, but for somehow I always get

   {
  "type": "http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
  "title": "Resource Not Found",
  "status": 404,
  "detail": "The requested resource could not be found.",
  "instance": ""
}

I'm using request library to make the request and see the code below

var uniqueListId = "XXXX";
var apiKey = "XXX";

  .post(function(req, res) {
      var email = req.body.email;
      var status = "subscribed";

      request({
        url: 'https://usX.api.mailchimp.com/3.0/lists/' + uniqueListId + '/members',
        headers: {
          'Authorization': 'randomUser ' + apiKey,
          'Content-Type': 'application/json',
        },
        method: 'POST',
        json: {
          email_address: email,
          status: status
        }
      }, function(err, response, body) {
        if (err) {
          res.json(err);
        } else {
          res.json(response.statusCode, body);
        }
      });
    });

For the sake of clarity, this is the documentation that I'm referring to http://developer.mailchimp.com/documentation/mailchimp/reference/lists/members/

Is it because of my req.body data?


问:
How to read tensorflow dataset caches without building the dataset again
I have created a dataset (tf.data.Dataset) with fairly complicated transformations and I have cached it to a file. My question is how can I read the content of that dataset again without reconstructing the dataset object again. For example:

```<code>import tensorflow as tf
tf.enable_eager_execution()
db = tf.data.Dataset.range(10)
db = db.cache('/tmp/range')
for v in db:
    print(v)
# /tmp/range.data-00000-of-00001  /tmp/range.index files are created

# later, you could restore the dataset from a method like this:
new_db = tf.data.Dataset.from_cache('/tmp/range')
</code>```

The idea is to build the dataset in another context and use it without building the complicated input pipeline that I had before.

答: I am pretty sure if you complete one epoch of reading the dataset, the next time you start a new training, it will still read from this cache file even if you make changes to your pipeline.</p>

Body:
I have created a dataset (tf.data.Dataset) with fairly complicated transformations and I have cached it to a file. My question is how can I read the content of that dataset again without reconstructing the dataset object again. For example:

import tensorflow as tf
tf.enable_eager_execution()
db = tf.data.Dataset.range(10)
db = db.cache('/tmp/range')
for v in db:
    print(v)
# /tmp/range.data-00000-of-00001  /tmp/range.index files are created

# later, you could restore the dataset from a method like this:
new_db = tf.data.Dataset.from_cache('/tmp/range')

The idea is to build the dataset in another context and use it without building the complicated input pipeline that I had before.


问:
How to change a dropdown to a text box for barcode scanning into a field
I have an Appmaker form to create a record that includes a many to one relation to another table. By default, the form creates a dropdown to select the related record from a list. This works fine, but I need to barcode scan (or type) the item name rather than select it.

When I change the dropdown to a text box and bind it to the related table, it greys out and becomes unusable when I preview it. (I get a circle with a line through it when hovering over.)

When I keep both the dropdown and the textbox on the same form, I can select a record from the dropdown and it populates the textbox. After that, the textbox becomes editable and works as desired.

How can I remove the dropdown and make the text box editable?

答:
The problem is that when you bind the textbox to a relational field it is looking for a record not just a value.
My thought is you are going to want to create a text box where you enter/scan in the value and leave it unbound. then in probably the onValueChange event write a script to query the item in the related table that you are trying to relate and set that equal to the field you are trying to edit.I don't know that this code will work haven't tested it but should get you going in the right direction:</p>

```<code>  var ds = app.datasources.Parts;
  ds.query.filters.Part._equals = newValue;
  ds.load(function() {
    if (ds.item === null) {
      alert("Part not found!");
      widget.root.descendants.FieldPart.value = null;
    }
    else {
      widget.root.descendants.FieldPart.value = ds.item;
    }
  });
</code>```

Body:
The problem is that when you bind the textbox to a relational field it is looking for a record not just a value.
My thought is you are going to want to create a text box where you enter/scan in the value and leave it unbound. then in probably the onValueChange event write a script to query the item in the related table that you are trying to relate and set that equal to the field you are trying to edit.I don't know that this code will work haven't tested it but should get you going in the right direction:

  var ds = app.datasources.Parts;
  ds.query.filters.Part._equals = newValue;
  ds.load(function() {
    if (ds.item === null) {
      alert("Part not found!");
      widget.root.descendants.FieldPart.value = null;
    }
    else {
      widget.root.descendants.FieldPart.value = ds.item;
    }
  });


问:
How to simulate a mouse click with touch data?
I'm working on a Qt5 application to attempt to make use of raw input data from a touchscreen because touch is not fully supported by my Linux kernel (2.6.32). I wrote a parser for the raw data coming from /dev/input/eventX because even though X doesn't support touch, the events are still there.

I'm able to read the events just fine, and wrote a wrapper called "TouchPoint" which contains the ID and (x,y) coordinates of each touch point, as well as a boolean indicating whether or not the touch point is currently "active" (ie: the user currently has that finger on the screen). It's worth noting that I also output the number of points of touch currently on the screen, and the value is accurate.

My issue is that I can't seem to figure out how to accurately simulate a mouse click with it. With multi-touch events in Linux, each touch point is assigned a "tracking ID" when the user presses a finger to the screen, and when that point is lifted, an event setting that slot's tracking ID to -1 is generated. I use this change of ID from some value to -1 to indicate that a touch point is "down" or not:

void TouchPoint::setID(int nid) {
    if((id == -1) && (nid >= 0)) down = true;
    else if(nid == -1) down = false;
    id = nid;
}
```

<p>So to try and simulate a mouse click, I do this when a tracking ID event is read:</p>

<pre class="lang-cpp prettyprint-override"><code>else if(event.code == ABS_MT_TRACKING_ID) {
    bool before = touchPoints[cSlot].isDown(); // where cSlot is the current slot the events are referring to
    touchPoints[cSlot].setID(event.value);
    bool after = touchPoints[cSlot].isDown();

    if(!before && after) touch(touchPoints[cSlot]);
}
</code>```

And then the touch method does this:

void MainWindow::touch(TouchPoint tp) {
    if(ui->touchMe->rect().contains(QPoint(tp.getX(), tp.getY()))) {
        on_touchMe_clicked();
    }
}
```

The button does not respond to me directly touching it, but sometimes if I wildly flail my fingers around the screen, the message box that should show when it's pressed will show, but when it does, my fingers are always somewhere on another area of the screen.

Can anyone think of something I might be doing wrong here? Is my method of checking to see if the touch point is within the button's bounds wrong? Or is my logic for keeping track of the "down" status of the touch points wrong? Or something else entirely?

UPDATE: I just noticed two things by outputting the screen coordinates of both the touch location and the button location.

The digitizer resolution is larger than the screen resolution, so I needed to scale the X and Y coordinates coming from the raw events.

My coordinates are offset because they are screen coordinates.

UPDATE 2: I've now dealt with the two issues mentioned in my last update, but I'm still not able to figure out how to accurately simulate a touch/mouse event to be able to interact with the interface. I also modified my TouchPoint class to have a boolean flag indicating whether or not the touch point was just updated, which is set to true when the tracking ID is updated and reset when an EV_SYN event is raised. This is so I can get the X and Y position events before creating the event for the application. I tried the following:

Using the QApplication class to post a mouse event to the QApplication::desktop()->screen() widget that has the position of the touch point.

Using the QTest class to raise a touchEvent to the QApplication::desktop()->screen() widget using the press and release methods for the given slot and position of the touch point and then using the bool event(QEvent*) method to try to catch the event. I also enabled the WA_AcceptTouchEvents attribute on the main window.

Neither of these works, as for some reason, when I have the "bool event(QEvent*)" method in place, the signal emitted from the thread reading /dev/input/eventX doesn't trigger the slot in the main window class. and I can't seem to find any other method to accomplish simulating the events. Anyone have any ideas?

答:
You wrote that you sometimes get your message box "clicked" when your fingers are in a "wrong position" so it sounds like you a mixing global screen coordinates and widget local coordinates. It seems, in your MainWindow::touch you try to check if a point in global screen coordinates, e.g. (530, 815) is inside a widget's geometry (in its local coordinates). QWidget::rect() returns internal geometry of the button (widget), i.e. a rectangle of widget's width and height, e.g. (0, 0, 60, 100).

You have to move the rect to a right position in global screen coordinates. QWidget::pos() returns widget local position to its parent. You can use QWidget::mapToGlobal to translate widget coordinate position to global screen coordinates. Then your rect is something like (500, 850, 60, 100) and you should get a hit and get your slot called.

However, better approach is to use QApplication::widgetAt to get the widget in a specific screen position and generate a mouse click for it.

You can generate a mouse click for a widget by posting a mouse press and release to it, something like below:

QPoint screenPos = QPoint(tp.getX(), tp.getY());
QWidget *targetWidget = QApplication::widgetAt(screenPos);

QPoint localPos = targetWidget->mapFromGlobal(screenPos);
QMouseEvent *eventPress = new QMouseEvent(QEvent::MouseButtonPress, localPos, screenPos, Qt::LeftButton, Qt::LeftButton,  Qt::NoModifier);
QApplication::postEvent(targetWidget, eventPress);
QMouseEvent *eventRelease = new QMouseEvent(QEvent::MouseButtonRelease, localPos, screenPos, Qt::LeftButton, Qt::LeftButton,  Qt::NoModifier);
QApplication::postEvent(targetWidget, eventRelease);
```

Body:
I'm working on a Qt5 application to attempt to make use of raw input data from a touchscreen because touch is not fully supported by my Linux kernel (2.6.32). I wrote a parser for the raw data coming from /dev/input/eventX because even though X doesn't support touch, the events are still there.

I'm able to read the events just fine, and wrote a wrapper called "TouchPoint" which contains the ID and (x,y) coordinates of each touch point, as well as a boolean indicating whether or not the touch point is currently "active" (ie: the user currently has that finger on the screen). It's worth noting that I also output the number of points of touch currently on the screen, and the value is accurate.

My issue is that I can't seem to figure out how to accurately simulate a mouse click with it. With multi-touch events in Linux, each touch point is assigned a "tracking ID" when the user presses a finger to the screen, and when that point is lifted, an event setting that slot's tracking ID to -1 is generated. I use this change of ID from some value to -1 to indicate that a touch point is "down" or not:

void TouchPoint::setID(int nid) {
    if((id == -1) && (nid >= 0)) down = true;
    else if(nid == -1) down = false;
    id = nid;
}

So to try and simulate a mouse click, I do this when a tracking ID event is read:

else if(event.code == ABS_MT_TRACKING_ID) {
    bool before = touchPoints[cSlot].isDown(); // where cSlot is the current slot the events are referring to
    touchPoints[cSlot].setID(event.value);
    bool after = touchPoints[cSlot].isDown();

    if(!before && after) touch(touchPoints[cSlot]);
}

And then the touch method does this:

void MainWindow::touch(TouchPoint tp) {
    if(ui->touchMe->rect().contains(QPoint(tp.getX(), tp.getY()))) {
        on_touchMe_clicked();
    }
}

The button does not respond to me directly touching it, but sometimes if I wildly flail my fingers around the screen, the message box that should show when it's pressed will show, but when it does, my fingers are always somewhere on another area of the screen.

Can anyone think of something I might be doing wrong here? Is my method of checking to see if the touch point is within the button's bounds wrong? Or is my logic for keeping track of the "down" status of the touch points wrong? Or something else entirely?

UPDATE: I just noticed two things by outputting the screen coordinates of both the touch location and the button location.

The digitizer resolution is larger than the screen resolution, so I needed to scale the X and Y coordinates coming from the raw events.

My coordinates are offset because they are screen coordinates.

UPDATE 2: I've now dealt with the two issues mentioned in my last update, but I'm still not able to figure out how to accurately simulate a touch/mouse event to be able to interact with the interface. I also modified my TouchPoint class to have a boolean flag indicating whether or not the touch point was just updated, which is set to true when the tracking ID is updated and reset when an EV_SYN event is raised. This is so I can get the X and Y position events before creating the event for the application. I tried the following:

Using the QApplication class to post a mouse event to the QApplication::desktop()->screen() widget that has the position of the touch point.

Using the QTest class to raise a touchEvent to the QApplication::desktop()->screen() widget using the press and release methods for the given slot and position of the touch point and then using the bool event(QEvent*) method to try to catch the event. I also enabled the WA_AcceptTouchEvents attribute on the main window.

Neither of these works, as for some reason, when I have the "bool event(QEvent*)" method in place, the signal emitted from the thread reading /dev/input/eventX doesn't trigger the slot in the main window class. and I can't seem to find any other method to accomplish simulating the events. Anyone have any ideas?


问:
Why SVG shadow is cut on the bottom side
I've made a little SVG icon that requires a shadow on the bottom. The thing that I couldn't understand is why its shadow is cut?

Thanks in advance!

<svg xmlns="http://www.w3.org/2000/svg" class="default___3oPC0 barMiddleSVG___3x9T-" filter="" fill="url('#star_container_gradient_one')" stroke="transparent" stroke-width="0" width="43" height="36" viewBox="0 -1 43 38"><linearGradient id="star_container_gradient_one" gradientTransform="rotate(90)">
<stop offset="0" stop-color="#c2c2b3"></stop>
<stop offset="1" stop-color="#dedece"></stop>
</linearGradient>
<defs>

<filter id="romb_container_shadow_bottom">
<feDropShadow dx="0" dy="2" stdDeviation=".5" flood-color="#4a444494"></feDropShadow>
</filter>
</defs>
<path filter="none" d="
            M 1 11
            L 21.4 1
            L 42.8 11
            L 42.8 26
            L 21.4 36
            L 1 26
            L 1 11
            Z
          "></path><path class="romb_top_border" filter="none" d="
            M 1 11
            L 21.4 1
            L 42.8 11
          "></path><path class="romb_bottom_border" filter="url(#romb_container_shadow_bottom)" d="
            M 42.8 26
            L 21.4 36
            L 1 26
"></path></svg>```

答:
Couple things. Adjust your size of the svg to accommodate the size needed for the result of the filter on the svg element and it's viewbox, and increase the height of the filter to accommodate the boundary of the svg. Example below, hope it helps, cheers.

Oh, and PS, I assume the 8 digit hex color Mr. Longson pointed out is a remnant habit from say XAML Path habits wherein you can specify the alpha channel by appending a value to the first octet. AKA <alpha opacity>RGB?

svg { border: rgba(255,0,0,.2) 3px solid}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><svg xmlns="http://www.w3.org/2000/svg" class="default___3oPC0 barMiddleSVG___3x9T-" filter="" fill="url('#star_container_gradient_one')" stroke="transparent" stroke-width="0" width="43" height="40" viewBox="0 0 43 38"><linearGradient id="star_container_gradient_one" gradientTransform="rotate(90)">
<stop offset="0" stop-color="#c2c2b3"></stop>
<stop offset="1" stop-color="#dedece"></stop>
</linearGradient>
<defs>
<style>.romb_top_border, .romb_bottom_border { fill: transparent; stroke: #e9ebd8; stroke-width: 1.5px; color }</style>
<filter id="romb_container_shadow_bottom" height="150%">
<feDropShadow dx="0" dy="2" stdDeviation=".5" flood-color="#4a444494"></feDropShadow>
</filter>
</defs>
<path filter="none" d="
            M 1 11
            L 21.4 1
            L 42.8 11
            L 42.8 26
            L 21.4 36
            L 1 26
            L 1 11
            Z
          "></path><path class="romb_top_border" filter="none" d="
            M 1 11
            L 21.4 1
            L 42.8 11
          "></path><path class="romb_bottom_border" filter="url(#romb_container_shadow_bottom)" d="
            M 42.8 26
            L 21.4 36
            L 1 26
"></path></svg></code>```

Body:
Couple things. Adjust your size of the svg to accommodate the size needed for the result of the filter on the svg element and it's viewbox, and increase the height of the filter to accommodate the boundary of the svg. Example below, hope it helps, cheers.

Oh, and PS, I assume the 8 digit hex color Mr. Longson pointed out is a remnant habit from say XAML Path habits wherein you can specify the alpha channel by appending a value to the first octet. AKA <alpha opacity>RGB?

svg { border: rgba(255,0,0,.2) 3px solid}

<svg xmlns="http://www.w3.org/2000/svg" class="default___3oPC0 barMiddleSVG___3x9T-" filter="" fill="url('#star_container_gradient_one')" stroke="transparent" stroke-width="0" width="43" height="40" viewBox="0 0 43 38"><linearGradient id="star_container_gradient_one" gradientTransform="rotate(90)">
<stop offset="0" stop-color="#c2c2b3"></stop>
<stop offset="1" stop-color="#dedece"></stop>
</linearGradient>
<defs>
<style>.romb_top_border, .romb_bottom_border { fill: transparent; stroke: #e9ebd8; stroke-width: 1.5px; color }</style>
<filter id="romb_container_shadow_bottom" height="150%">
<feDropShadow dx="0" dy="2" stdDeviation=".5" flood-color="#4a444494"></feDropShadow>
</filter>
</defs>
<path filter="none" d="
            M 1 11
            L 21.4 1
            L 42.8 11
            L 42.8 26
            L 21.4 36
            L 1 26
            L 1 11
            Z
          "></path><path class="romb_top_border" filter="none" d="
            M 1 11
            L 21.4 1
            L 42.8 11
          "></path><path class="romb_bottom_border" filter="url(#romb_container_shadow_bottom)" d="
            M 42.8 26
            L 21.4 36
            L 1 26
"></path></svg>


问:
Creating an MSI or Script to deploy an EXE through AD
First:
I know there are other questions that ask similar/the same thing, I have looked at them tried all of them but no solution has helped.

The problem:
We use Epson Iprojection (downloaded from here: https://www.epson.co.nz/products/projectors/software/) However I can not find a way to get an MSI out of it (I am starting to think there is no MSI bundled in the .exe), and I can not seem to install it through CMD on computer start using AD. Any help will be greatly appreciated.

答:
Buried within the single-exe download is iProjection_inst.exe, some sort of wrapper that prompts for language selection, and doesn't seem to have a standard "non-interactive" mode.

Inside this is instData\Setup.exe, a vintage "full screen" InstallShield installer with external ini / cab files.

Running this with Setup.exe /? doesn't give any command line arguments, as it would for a modern InstallShield setup.exe.

Although it supports recording an answer file via Setup.exe /r, when I try to replay the answer file with Setup.exe /s it seems to still prompt for EULA, and then fails to install.

So this is really a design flaw in the innermost installer to do with the dialog sequence.

Assuming Epson won't fix it and repackaging is too hard, a hacky alternative is to use Powershell to automate the UI of instData\Setup.exe once the "Welcome" screen is showing, but I don't think this will work running as an AD script.

```<code>$wshell = New-Object -ComObject wscript.shell
$aName = "Epson iProjection Setup"
function Next() {
  if ($wshell.AppActivate($aName)) {
    $wshell.SendKeys(' ');
    start-sleep 1;
  }
}
function AcceptEula() {
  if ($wshell.AppActivate($aName)) {
   $wshell.SendKeys("{TAB}");
   $wshell.SendKeys("{TAB}");
   $wshell.SendKeys(' ');
   start-sleep 1;
  }
}
Next; AcceptEula; AcceptEula; start-sleep 20; Next;
</code>```

Body:
Buried within the single-exe download is iProjection_inst.exe, some sort of wrapper that prompts for language selection, and doesn't seem to have a standard "non-interactive" mode.

Inside this is instData\Setup.exe, a vintage "full screen" InstallShield installer with external ini / cab files.

Running this with Setup.exe /? doesn't give any command line arguments, as it would for a modern InstallShield setup.exe.

Although it supports recording an answer file via Setup.exe /r, when I try to replay the answer file with Setup.exe /s it seems to still prompt for EULA, and then fails to install.

So this is really a design flaw in the innermost installer to do with the dialog sequence.

Assuming Epson won't fix it and repackaging is too hard, a hacky alternative is to use Powershell to automate the UI of instData\Setup.exe once the "Welcome" screen is showing, but I don't think this will work running as an AD script.

$wshell = New-Object -ComObject wscript.shell
$aName = "Epson iProjection Setup"
function Next() {
  if ($wshell.AppActivate($aName)) {
    $wshell.SendKeys(' ');
    start-sleep 1;
  }
}
function AcceptEula() {
  if ($wshell.AppActivate($aName)) {
   $wshell.SendKeys("{TAB}");
   $wshell.SendKeys("{TAB}");
   $wshell.SendKeys(' ');
   start-sleep 1;
  }
}
Next; AcceptEula; AcceptEula; start-sleep 20; Next;


问:
open multiple inset panel does not work in matplotlib
I want to open multiple inset axis in a figure.
However I get the following warning message and only the last inset panel is plotted.

```<code>/usr/lib/python2.7/dist-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
  warnings.warn(message, mplDeprecation, stacklevel=1)
</code>```

Here is the code:

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition

fig, ax= plt.subplots()

iax = plt.axes([0, 0, 1, 2])
ip = InsetPosition(ax, [0.4, 0.5, 0.2, 0.2]) #posx, posy, width, height
iax.set_axes_locator(ip)
iax.plot([1,2,4])

iax1 = plt.axes([0, 0, 1, 2])
ip = InsetPosition(ax, [0.7, 0.2, 0.2, 0.2]) #posx, posy, width, height
iax1.set_axes_locator(ip)
iax1.plot([1,2,4])
</code>```

Do you have any idea?

答:
Just take the warning seriously and do as it suggests in

Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.

namely, use a unique label for each axes:

```<code>import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition

fig, ax= plt.subplots()

iax = fig.add_axes([0, 0, 1, 2], label="iax")
ip = InsetPosition(ax, [0.4, 0.5, 0.2, 0.2]) #posx, posy, width, height
iax.set_axes_locator(ip)
iax.plot([1,2,4])

iax1 = fig.add_axes([0, 0, 1, 2], label="iax1")
ip = InsetPosition(ax, [0.7, 0.2, 0.2, 0.2]) #posx, posy, width, height
iax1.set_axes_locator(ip)
iax1.plot([1,2,4])

plt.show()
</code>```

Body:
I want to open multiple inset axis in a figure.
However I get the following warning message and only the last inset panel is plotted.

/usr/lib/python2.7/dist-packages/matplotlib/cbook/deprecation.py:106: MatplotlibDeprecationWarning: Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
  warnings.warn(message, mplDeprecation, stacklevel=1)

Here is the code:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition

fig, ax= plt.subplots()

iax = plt.axes([0, 0, 1, 2])
ip = InsetPosition(ax, [0.4, 0.5, 0.2, 0.2]) #posx, posy, width, height
iax.set_axes_locator(ip)
iax.plot([1,2,4])

iax1 = plt.axes([0, 0, 1, 2])
ip = InsetPosition(ax, [0.7, 0.2, 0.2, 0.2]) #posx, posy, width, height
iax1.set_axes_locator(ip)
iax1.plot([1,2,4])

Do you have any idea?

Body:
Just take the warning seriously and do as it suggests in

Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.

namely, use a unique label for each axes:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import InsetPosition

fig, ax= plt.subplots()

iax = fig.add_axes([0, 0, 1, 2], label="iax")
ip = InsetPosition(ax, [0.4, 0.5, 0.2, 0.2]) #posx, posy, width, height
iax.set_axes_locator(ip)
iax.plot([1,2,4])

iax1 = fig.add_axes([0, 0, 1, 2], label="iax1")
ip = InsetPosition(ax, [0.7, 0.2, 0.2, 0.2]) #posx, posy, width, height
iax1.set_axes_locator(ip)
iax1.plot([1,2,4])

plt.show()


问:
Changing Bullet Styles with Word 2007 Automation in C#
I am trying to change the style of my bullets in a word document (Word 2007)....  I currently place a bullet and it comes out as a circle.  I want it to be a square...  here's my code for applying bullets...

```<code>    public void ToggleBullets(bool bulletsOn)
{
    Microsoft.Office.Interop.Word.Application wd;
    Object _oMissing = Type.Missing;
    Object _numberType = WdNumberType.wdNumberListNum;
    if (bulletsOn)
    {
        wd.Selection.Range.ListFormat.ApplyBulletDefault(ref _oMissing);
    }
    else
    {
        wd.Selection.Range.ListFormat.RemoveNumbers(ref _numberType);
    }
}
</code>```

any ideas?  Let me know if you need more details

答:
I use the Open XML SDK 2.0 Productivity Tool for Microsoft Office:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c6e744e5-36e9-45f5-8d8c-331df206e0d0&displaylang=en

When I want to to do these kinds of things.  Just launch the Productivity tool, load up the .docx that has what you want and then let the tool generate the code for you.

I just whipped up an example and this was the code it generated:

```<code>using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
....
    public Paragraph GenerateParagraph()
    {
        Paragraph paragraph1 = new Paragraph(){ RsidParagraphAddition = "00EA7FFB", RsidParagraphProperties = "00EA7FFB", RsidRunAdditionDefault = "00EA7FFB" };

        ParagraphProperties paragraphProperties1 = new ParagraphProperties();
        ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId(){ Val = "ListParagraph" };

        NumberingProperties numberingProperties1 = new NumberingProperties();
        NumberingLevelReference numberingLevelReference1 = new NumberingLevelReference(){ Val = 0 };
        NumberingId numberingId1 = new NumberingId(){ Val = 2 };

        numberingProperties1.Append(numberingLevelReference1);
        numberingProperties1.Append(numberingId1);

        paragraphProperties1.Append(paragraphStyleId1);
        paragraphProperties1.Append(numberingProperties1);

        Run run1 = new Run();
        Text text1 = new Text(){ Space = SpaceProcessingModeValues.Preserve };
        text1.Text = "Item ";

        run1.Append(text1);

        paragraph1.Append(paragraphProperties1);
        paragraph1.Append(run1);
        return paragraph1;
    }
</code>```

This is using the OpenXml headers, and not Word specifically

Body:
I am trying to change the style of my bullets in a word document (Word 2007)....  I currently place a bullet and it comes out as a circle.  I want it to be a square...  here's my code for applying bullets...

    public void ToggleBullets(bool bulletsOn)
{
    Microsoft.Office.Interop.Word.Application wd;
    Object _oMissing = Type.Missing;
    Object _numberType = WdNumberType.wdNumberListNum;
    if (bulletsOn)
    {
        wd.Selection.Range.ListFormat.ApplyBulletDefault(ref _oMissing);
    }
    else
    {
        wd.Selection.Range.ListFormat.RemoveNumbers(ref _numberType);
    }
}

any ideas?  Let me know if you need more details

Body:
I use the Open XML SDK 2.0 Productivity Tool for Microsoft Office:
http://www.microsoft.com/downloads/en/details.aspx?FamilyID=c6e744e5-36e9-45f5-8d8c-331df206e0d0&displaylang=en

When I want to to do these kinds of things.  Just launch the Productivity tool, load up the .docx that has what you want and then let the tool generate the code for you.

I just whipped up an example and this was the code it generated:

using DocumentFormat.OpenXml.Wordprocessing;
using DocumentFormat.OpenXml;
....
    public Paragraph GenerateParagraph()
    {
        Paragraph paragraph1 = new Paragraph(){ RsidParagraphAddition = "00EA7FFB", RsidParagraphProperties = "00EA7FFB", RsidRunAdditionDefault = "00EA7FFB" };

        ParagraphProperties paragraphProperties1 = new ParagraphProperties();
        ParagraphStyleId paragraphStyleId1 = new ParagraphStyleId(){ Val = "ListParagraph" };

        NumberingProperties numberingProperties1 = new NumberingProperties();
        NumberingLevelReference numberingLevelReference1 = new NumberingLevelReference(){ Val = 0 };
        NumberingId numberingId1 = new NumberingId(){ Val = 2 };

        numberingProperties1.Append(numberingLevelReference1);
        numberingProperties1.Append(numberingId1);

        paragraphProperties1.Append(paragraphStyleId1);
        paragraphProperties1.Append(numberingProperties1);

        Run run1 = new Run();
        Text text1 = new Text(){ Space = SpaceProcessingModeValues.Preserve };
        text1.Text = "Item ";

        run1.Append(text1);

        paragraph1.Append(paragraphProperties1);
        paragraph1.Append(run1);
        return paragraph1;
    }

This is using the OpenXml headers, and not Word specifically