问:
Restrict Azure App Service to a whitelist of IPs without returning 403
I have an Azure App Service where the customer is using an Akamai WAF in front of it to connect to it. Now I have the requirement that the App Service should not be reachable other then through that WAF. I got a list of IPs I have entered in the App Service Networking in the Access Restrictions list (App Service -> Networking -> Access restrictions).

This works pretty well in principle, but if I now try to access the service directly (so by using appname.azurewebsites.net), not through the WAF, it will return a 403 error response. But the requirement is that the service should not answer, at all.

Is there a way to achieve that in Azure? What would be the best way to do this?

答:
There is a way to achieve this behaviour right now in an app service:
What you need to do is use an app service plan on the Isolation tier, create a v-net and add a network security group to it where you can restrict inbound ips.

This is pretty expensive, but currently the only way.

What I ended up with is to use a VM with a v-net, as this is much cheaper. An App service on the isolation tier unfortunatly would have destroyed the budget.


来源: stackexchange

问:
Identity-layout-renderer is not rendering anything for .NET Core console Application
I have a .NET Core Console application.

like this:

```<code>  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netcoreapp2.1;netcoreapp3.1</TargetFrameworks>
  </PropertyGroup>
</code>```

I'm running on Windows 10 with VS 2019.

I cannot get the below layout renderer to log anything.

https://github.com/NLog/NLog/wiki/Identity-layout-renderer

```<code>${identity:authType=Boolean:separator=String:name=Boolean
          :isAuthenticated=Boolean}
</code>```

My nlog.config

<?xml version="1.0" encoding="utf-8" ?>

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogFile="MyApp.NLog.INTERNAL.log"
      internalLogLevel="Info" >

  <targets>

    <target xsi:type="File" name="target1" fileName="MyApp.NLog.${shortdate}.log"
            layout="${date}|${level:uppercase=true}|${logger}|***|${identity:authType=true:separator=/:name=true:isAuthenticated=true}|****|${message} ${exception:format=toString,Data}|${all-event-properties}" />

  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="target1" />
  </rules>
</nlog>
```

<p>example log:  :(</p>

```2020/02/19 12:03:40.617|INFO|MyCompany.MyObject|***||****|HeyYouThere |
```

<p>Nothing between ***||**** :(</p>

<p>and nlog internal log output (MyApp.NLog.INTERNAL.log) (no errors)</p>

```2020-02-19 12:03:38.3612 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.Extensions.Logging.dll
2020-02-19 12:03:38.3734 Info Loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.Extensions.Logging.dll
2020-02-19 12:03:38.3847 Info NLog.Extensions.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 1.6.1.1203. Product version: 1.6.1.
2020-02-19 12:03:38.3847 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.Extensions.Logging.dll succeeded!
2020-02-19 12:03:38.3847 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.WindowsIdentity.dll
2020-02-19 12:03:38.3847 Info Loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.WindowsIdentity.dll
2020-02-19 12:03:38.3938 Info NLog.WindowsIdentity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.6.8.10751. Product version: 4.6.8.
2020-02-19 12:03:38.3938 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.WindowsIdentity.dll succeeded!
2020-02-19 12:03:38.3938 Info Message Template Auto Format enabled
2020-02-19 12:03:38.4652 Info Adding target FileTarget(Name=target1)
2020-02-19 12:03:38.5111 Info Found 39 configuration items
2020-02-19 12:03:38.5614 Info Configuration file change detected! Reloading in 1000ms...
2020-02-19 12:03:38.5614 Info Configuration file change detected! Reloading in 1000ms...
2020-02-19 12:03:39.5688 Info Reloading configuration...
2020-02-19 12:03:39.5688 Info Configuring from an XML element in c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\nlog.config...
2020-02-19 12:03:39.5688 Info Message Template Auto Format enabled
2020-02-19 12:03:39.5688 Info Adding target FileTarget(Name=target1)
2020-02-19 12:03:39.5688 Info Closing old configuration.
2020-02-19 12:03:39.5987 Info Found 39 configuration items
```

<p>Nuget packages</p>

```  <ItemGroup>
    <PackageReference Include="NLog" Version="4.6.8" />
    <PackageReference Include="NLog.Extensions.Logging" Version="1.6.1" />
    <PackageReference Include="NLog.WindowsIdentity" Version="4.6.8" />
  </ItemGroup>
```

<p>As far as I can see, it looks like I have the nuget package</p>

```.nuget\packages\nlog\4.6.8\lib\netstandard2.0\NLog.dll
namespace NLog.LayoutRenderers
{
    [LayoutRenderer("identity")]
    public class IdentityLayoutRenderer : LayoutRenderer
```

答:
From the link (thanks @granadaCoder)

NET Core has different default. The default principal policy in .NET Core is no principal.

If you would like to keep .NET Framework behavior, call AppDomain.CurrentDomain.SetPrincipalPolicy(PrincipalPolicy.UnauthenticatedPrincipal) in the Main method of your app.

ContentLicense: CC BY-SA 4.0

Body:
I have a .NET Core Console application.

like this:

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFrameworks>netcoreapp2.1;netcoreapp3.1</TargetFrameworks>
  </PropertyGroup>

I'm running on Windows 10 with VS 2019.

I cannot get the below layout renderer to log anything.

https://github.com/NLog/NLog/wiki/Identity-layout-renderer

${identity:authType=Boolean:separator=String:name=Boolean
          :isAuthenticated=Boolean}

My nlog.config

<?xml version="1.0" encoding="utf-8" ?>

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      internalLogFile="MyApp.NLog.INTERNAL.log"
      internalLogLevel="Info" >

  <targets>

    <target xsi:type="File" name="target1" fileName="MyApp.NLog.${shortdate}.log"
            layout="${date}|${level:uppercase=true}|${logger}|***|${identity:authType=true:separator=/:name=true:isAuthenticated=true}|****|${message} ${exception:format=toString,Data}|${all-event-properties}" />

  </targets>

  <rules>
    <logger name="*" minlevel="Trace" writeTo="target1" />
  </rules>
</nlog>

example log:  :(

2020/02/19 12:03:40.617|INFO|MyCompany.MyObject|***||****|HeyYouThere |

Nothing between ***||**** :(

and nlog internal log output (MyApp.NLog.INTERNAL.log) (no errors)

2020-02-19 12:03:38.3612 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.Extensions.Logging.dll
2020-02-19 12:03:38.3734 Info Loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.Extensions.Logging.dll
2020-02-19 12:03:38.3847 Info NLog.Extensions.Logging, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 1.6.1.1203. Product version: 1.6.1.
2020-02-19 12:03:38.3847 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.Extensions.Logging.dll succeeded!
2020-02-19 12:03:38.3847 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.WindowsIdentity.dll
2020-02-19 12:03:38.3847 Info Loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.WindowsIdentity.dll
2020-02-19 12:03:38.3938 Info NLog.WindowsIdentity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c. File version: 4.6.8.10751. Product version: 4.6.8.
2020-02-19 12:03:38.3938 Info Auto loading assembly file: c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\NLog.WindowsIdentity.dll succeeded!
2020-02-19 12:03:38.3938 Info Message Template Auto Format enabled
2020-02-19 12:03:38.4652 Info Adding target FileTarget(Name=target1)
2020-02-19 12:03:38.5111 Info Found 39 configuration items
2020-02-19 12:03:38.5614 Info Configuration file change detected! Reloading in 1000ms...
2020-02-19 12:03:38.5614 Info Configuration file change detected! Reloading in 1000ms...
2020-02-19 12:03:39.5688 Info Reloading configuration...
2020-02-19 12:03:39.5688 Info Configuring from an XML element in c:\myfolder1\myfolder2\bin\Debug\netcoreapp3.1\nlog.config...
2020-02-19 12:03:39.5688 Info Message Template Auto Format enabled
2020-02-19 12:03:39.5688 Info Adding target FileTarget(Name=target1)
2020-02-19 12:03:39.5688 Info Closing old configuration.
2020-02-19 12:03:39.5987 Info Found 39 configuration items

Nuget packages

  <ItemGroup>
    <PackageReference Include="NLog" Version="4.6.8" />
    <PackageReference Include="NLog.Extensions.Logging" Version="1.6.1" />
    <PackageReference Include="NLog.WindowsIdentity" Version="4.6.8" />
  </ItemGroup>

As far as I can see, it looks like I have the nuget package

.nuget\packages\nlog\4.6.8\lib\netstandard2.0\NLog.dll
namespace NLog.LayoutRenderers
{
    [LayoutRenderer("identity")]
    public class IdentityLayoutRenderer : LayoutRenderer


问:
NotImplementedError: Non-relative patterns are unsupported from attempted looping over all .html files in a directory
I am trying to loop over all html files in a directory but am getting this error:

```<code>NotImplementedError: Non-relative patterns are unsupported
</code>```

The code I am using is:

```<code>from bs4 import BeautifulSoup
import argparse
from pathlib import Path

parser = argparse.ArgumentParser(description = ("Script to scrape data from antismash html output"))

parser.add_argument("-p", "--path", help = "give path/to/directory containing antismash outputs", required = True)

args = parser.parse_args()

for file in Path(args.path).glob("/*.html"):
    def scraper(filename):
        soup = BeautifulSoup(open(filename), 'html.parser')
        soup.findAll('a') > os.path.basename(filename).txt
</code>```

I have previously used the same method and not gotten an error so I am not sure what is going on.

答:
You don't need to use / inside the glob call when working with PathLib. The correct code would be:

```<code>for file in Path(args.path).glob("*.html"):
    def scraper(filename):
        soup = BeautifulSoup(open(filename), 'html.parser')
        soup.findAll('a') > os.path.basename(filename).txt
</code>```

Body:
I am trying to loop over all html files in a directory but am getting this error:

NotImplementedError: Non-relative patterns are unsupported

The code I am using is:

from bs4 import BeautifulSoup
import argparse
from pathlib import Path

parser = argparse.ArgumentParser(description = ("Script to scrape data from antismash html output"))

parser.add_argument("-p", "--path", help = "give path/to/directory containing antismash outputs", required = True)

args = parser.parse_args()

for file in Path(args.path).glob("/*.html"):
    def scraper(filename):
        soup = BeautifulSoup(open(filename), 'html.parser')
        soup.findAll('a') > os.path.basename(filename).txt

I have previously used the same method and not gotten an error so I am not sure what is going on.

Body:
You don't need to use / inside the glob call when working with PathLib. The correct code would be:

for file in Path(args.path).glob("*.html"):
    def scraper(filename):
        soup = BeautifulSoup(open(filename), 'html.parser')
        soup.findAll('a') > os.path.basename(filename).txt


问:
Spring boot @Caching With Multiple Keys
```<code>public class Student {
    public int studentName;
    public String Addr1;
    public String Addr2;
    public String Addr2;
    //getter setter
}

I have one repository class which contains following methods
class StudentRepoImpl{
   @Cacheable(value = "Students")
   public List<Students> findAllStudents() {
     //fetching all cust and putting in the Students cache
   }

   @Cacheable(value = "Students")
   public List<Students> findStudentsBystudentNameAndAddresses() {
     //fetching all cust data by **Name/Address1/Address2/Address3** basis of field available studentName/Address1/Address2/Address3 and putting in Student table
   }

}
</code>```

Current Output :

Fetch All data from DB and adding in Students cache in findAllStudents() method

But while searching for data based on some criteria (Name/Address1/Address2/Address3) using findStudentsBystudentNameAndAddresses() method it is fetching data from DB instead of cache.

Note: Not added Key while caching because there are 4 fields in search criteria (Name/Address1/Address2/Address3) and these are conditional fields means some time only Address1 will be in search criteria or sometime Address1+Address2 or sometimes all Address1+Address2+Address3 fields and I want to fetch exact match on the basis of Name and available Addresses.

答:
Try to add configuration like this

```<code>@Configuration
public class CachingConfig {
    @Bean(name = "springCM")
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("Students");
    }
}
</code>```

Hope useful

Title: Spring boot @Caching With Multiple Keys

Body:
public class Student {
    public int studentName;
    public String Addr1;
    public String Addr2;
    public String Addr2;
    //getter setter
}

I have one repository class which contains following methods
class StudentRepoImpl{
   @Cacheable(value = "Students")
   public List<Students> findAllStudents() {
     //fetching all cust and putting in the Students cache
   }

   @Cacheable(value = "Students")
   public List<Students> findStudentsBystudentNameAndAddresses() {
     //fetching all cust data by **Name/Address1/Address2/Address3** basis of field available studentName/Address1/Address2/Address3 and putting in Student table
   }

}

Current Output :

Fetch All data from DB and adding in Students cache in findAllStudents() method

But while searching for data based on some criteria (Name/Address1/Address2/Address3) using findStudentsBystudentNameAndAddresses() method it is fetching data from DB instead of cache.

Note: Not added Key while caching because there are 4 fields in search criteria (Name/Address1/Address2/Address3) and these are conditional fields means some time only Address1 will be in search criteria or sometime Address1+Address2 or sometimes all Address1+Address2+Address3 fields and I want to fetch exact match on the basis of Name and available Addresses.

Body:
Try to add configuration like this

@Configuration
public class CachingConfig {
    @Bean(name = "springCM")
    public CacheManager cacheManager() {
        return new ConcurrentMapCacheManager("Students");
    }
}

Hope useful


问:
How can I get JQuery to replace the non URL parts of the string when fetching the background images url
I have this code which extracts the element for the background image, however it pulls in the " url' " parts of the code too. I just need the actual image address

I have tried to use the replace function but it doesn't do anything to the string when i check the output.

```<code>var jsonData =
{ "image": jQuery('#block-content').css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1'),
var script = document.createElement('script');
script.type = 'application/ld+json';
script.text = JSON.stringify(jsonData);
jQuery("head").append(script);
</code>```

The image inside the element is //imageaddress.jpg so it's extracting it as

```<code>https://example.com/recipes/url(https://example.com/sites/image.jpg?itok=jfzYQHZx)
</code>```

How can i fix this so that it just gives me

```<code>https://example.com/sites/image.jpg?itok=jfzYQHZx
</code>```

答:
Note that some URLs are not always in the quotes:

```<code>url(https://example.com/sites/image.jpg?itok=jfzYQHZx)
</code>```

Then add ['"]? => ? Detects zero or 1 char

var str  = "url('https://example.com/sites/image.jpg?itok=jfzYQHZx')"; // example string
var str2 = "url(https://example.com/sites/image.jpg?itok=jfzYQHZx)"; // without quotes
str  = str.replace(/^url\(["']?(.+?)["']?\)/,"$1"); // replace with first group (.+?)
str2 = str2.replace(/^url\(["']?(.+?)["']?\)/,"$1");
console.log(str);
console.log(str2);```
</div>
</div>
</p>

```var jsonData = { "image": jQuery('#block-content').css('background-image').replace(/^url\(["']?(.+?)["']?\)/,"$1"),}
```

Body:
I have this code which extracts the element for the background image, however it pulls in the " url' " parts of the code too. I just need the actual image address

I have tried to use the replace function but it doesn't do anything to the string when i check the output.

var jsonData =
{ "image": jQuery('#block-content').css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1'),
var script = document.createElement('script');
script.type = 'application/ld+json';
script.text = JSON.stringify(jsonData);
jQuery("head").append(script);

The image inside the element is //imageaddress.jpg so it's extracting it as

https://example.com/recipes/url(https://example.com/sites/image.jpg?itok=jfzYQHZx)

How can i fix this so that it just gives me

https://example.com/sites/image.jpg?itok=jfzYQHZx

Body:
Note that some URLs are not always in the quotes:

url(https://example.com/sites/image.jpg?itok=jfzYQHZx)

Then add ['"]? => ? Detects zero or 1 char

var str  = "url('https://example.com/sites/image.jpg?itok=jfzYQHZx')"; // example string
var str2 = "url(https://example.com/sites/image.jpg?itok=jfzYQHZx)"; // without quotes
str  = str.replace(/^url\(["']?(.+?)["']?\)/,"$1"); // replace with first group (.+?)
str2 = str2.replace(/^url\(["']?(.+?)["']?\)/,"$1");
console.log(str);
console.log(str2);

var jsonData = { "image": jQuery('#block-content').css('background-image').replace(/^url\(["']?(.+?)["']?\)/,"$1"),}


问:
Nuxt export 'default' (imported as 'mod') was not found
I am using Nuxt with Typescript. I create a following component:

```<code><template>
    <div class="field">
        <label class="label" v-if="typeof label !== 'undefined'">{{ label }}</label>
        <div class="control">
            <textarea
                v-if="inputType === 'textarea'"
                class="textarea"
                @input="$emit('input', $event.target.value)"
            ></textarea>
            <input
                v-if="inputType === 'input'"
                :type="type"
                class="input"
                @input="$emit('input', $event.target.value)"
            >
        </div>
    </div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator"

@Component({})
export default class AppInput extends Vue {
    @Prop({ type: String, required: false, default: "input" })
    inputType!: string

    @Prop({ type: String, required: false })
    label!: string

    @Prop({ type: String, required: false, default: "text" })
    type!: string
}
</script>

<style>
</style>
</code>```

And then in @/plugins/components.ts, I import the component as following:

```<code>import Vue from "vue"
import AppInput from "@/components/Forms/AppInput.vue"

Vue.component("AppInput", AppInput)
</code>```

When I compile the project with Nuxt, it throws me export 'default' (imported as 'mod') was not found error. Please help!

答:
You will need atleast an empty export default script in your vue files to not see this error. If you don't have any export default statement, it gives this error/warning.</p>

```<code>export default {

}
</code>```

Body:
I am using Nuxt with Typescript. I create a following component:

<template>

        {{ label }}

            <textarea
                v-if="inputType === 'textarea'"
                class="textarea"
                @input="$emit('input', $event.target.value)"
            ></textarea>
            <input
                v-if="inputType === 'input'"
                :type="type"
                class="input"
                @input="$emit('input', $event.target.value)"
            >

</template>

And then in @/plugins/components.ts, I import the component as following:

import Vue from "vue"
import AppInput from "@/components/Forms/AppInput.vue"

Vue.component("AppInput", AppInput)

When I compile the project with Nuxt, it throws me export 'default' (imported as 'mod') was not found error. Please help!

Body:
You will need atleast an empty export default script in your vue files to not see this error. If you don't have any export default statement, it gives this error/warning.

export default {

}


问:
How Do I ' #import "Firebase.h ' in Xcode?
I'm manually adding some Firebase SDK's in my iOS app and have been following Firebase's provided readme to the letter. As it directs, I've already dragged all the SDKs I need into my project but there's one step I'm not understanding. It reads:

8. Drag the Firebase.h header in this directory into your project. This will
   allow you to #import "Firebase.h" and start using any Firebase SDKs that you
   have.

I've added the Firebase.h header file into my project but I don't know how/where to add #import "Firebase.h". Since I haven't done that, building my app produces the error: No such module 'Firebase' when I try to import Firebase in my view controllers.

For reference, I had been using cocoapods for Firebase up until the recent iOS 13.3.1 update that broke my ability to test my app on my physical device, so I'm attempting to manually add the static Firebase SDK's in the hopes that I would then be able to continue debugging on my iPhone 6s. I'm 75% of the way through my app's development and have already fully integrated Firebase so this little switch-over from pods to static SDKs is definitely annoying, but it has to be done. I removed all the Firebase pods I was using in my Podfile and am just stuck at the step bolded above... hopefully it's a simple thing and then everything will work again as I already have it completely integrated throughout my app.

If you'd like a deeper background, here's a Stack Overflow question that describes the exact initial problem I was having with debugging on my physical device with the 13.3.1 iOS update.

And here's where I asked for alternative ways to incorporate Firebase that avoids pods (in case that fixes the issue). This is where I learned about Firebase's zip binary distribution. I downloaded the zip file with the Firebase SDKs, chose the ones I need, and have been following the readme to add them to my project.

答:
To add Firebase module support, you also need to do the subsequent instruction in the zip distribution README after dragging Firebase.h:</p>

```<code>9. If you're using Swift, or you want to use modules, drag module.modulemap into
   your project and update your User Header Search Paths to contain the
   directory that contains your module map.
</code>```

Body:
To add Firebase module support, you also need to do the subsequent instruction in the zip distribution README after dragging Firebase.h:

9. If you're using Swift, or you want to use modules, drag module.modulemap into
   your project and update your User Header Search Paths to contain the
   directory that contains your module map.


问:
How do I compute the non-client window size in WPF?
WPF has the SystemParameters class that exposes a great number of system metrics. On my computer I have noticed that a normal window has a title that is 30 pixels high and a border that is 8 pixels wide. This is on Windows 7 with the Aero theme enabled:

However, SystemParameters return the following values:

```<code>SystemParameters.BorderWidth = 5
SystemParameters.CaptionHeight = 21
</code>```

Here I have disabled the Aero theme:

Now, SystemParameters return the following values:

```<code>SystemParameters.BorderWidth = 1
SystemParameters.CaptionHeight = 18
</code>```

How do I compute the actual observed values by using SystemParameters?

答:
For a resizable window you need to use a different set of parameters to compute the size:

```<code>var titleHeight = SystemParameters.WindowCaptionHeight
  + SystemParameters.ResizeFrameHorizontalBorderHeight;
var verticalBorderWidth = SystemParameters.ResizeFrameVerticalBorderWidth;
</code>```

These sizes will change when you modify the theme.

ContentLicense: CC BY-SA 3.0

Body:
WPF has the SystemParameters class that exposes a great number of system metrics. On my computer I have noticed that a normal window has a title that is 30 pixels high and a border that is 8 pixels wide. This is on Windows 7 with the Aero theme enabled:

However, SystemParameters return the following values:

SystemParameters.BorderWidth = 5
SystemParameters.CaptionHeight = 21

Here I have disabled the Aero theme:

Now, SystemParameters return the following values:

SystemParameters.BorderWidth = 1
SystemParameters.CaptionHeight = 18

How do I compute the actual observed values by using SystemParameters?

Body:
For a resizable window you need to use a different set of parameters to compute the size:

var titleHeight = SystemParameters.WindowCaptionHeight
  + SystemParameters.ResizeFrameHorizontalBorderHeight;
var verticalBorderWidth = SystemParameters.ResizeFrameVerticalBorderWidth;

These sizes will change when you modify the theme.


问:
Summing up selected row duplicates
I have data that looks like this.

I wish to sum up the value column for rows that have the same name, time, and site. In this case, rows 3 and 4 would be summed, and rows 5 and 7 would be summed up.

I wish for the resulting data frame to look like this.

example data:

```<code>    name = c('a', 'a', 'b' , 'b', 'c', 'c', 'c', 'd')
    time = c(1,2,1,1,3,3,3,4)
    site = c('A', 'A', 'A', 'A','B', 'D','B', 'E')
    value = c(5,8,1,0,7,0,8,10)

mock = data.frame(name, time,site,value)
</code>```

答:
I really like the data.table way to do this :

```<code>library(data.table)
data[, .(value = sum(value)), by = list(name, time, site)]

   name time site value
1:    a    1    A     5
2:    a    2    A     8
3:    b    1    A     1
4:    c    3    B    15
5:    c    3    D     0
6:    d    4    E    10
</code>```

The nice thing with data.table is that the order of your rows in the first column isn't change while aggregate() change it.

Title: Summing up selected row duplicates

Body:
I have data that looks like this.

I wish to sum up the value column for rows that have the same name, time, and site. In this case, rows 3 and 4 would be summed, and rows 5 and 7 would be summed up.

I wish for the resulting data frame to look like this.

example data:

    name = c('a', 'a', 'b' , 'b', 'c', 'c', 'c', 'd')
    time = c(1,2,1,1,3,3,3,4)
    site = c('A', 'A', 'A', 'A','B', 'D','B', 'E')
    value = c(5,8,1,0,7,0,8,10)

mock = data.frame(name, time,site,value)

Body:
I really like the data.table way to do this :

library(data.table)
data[, .(value = sum(value)), by = list(name, time, site)]

   name time site value
1:    a    1    A     5
2:    a    2    A     8
3:    b    1    A     1
4:    c    3    B    15
5:    c    3    D     0
6:    d    4    E    10

The nice thing with data.table is that the order of your rows in the first column isn't change while aggregate() change it.


问:
Is it important to label all visible objects for object detection?
We have to make a custom dataset for object detection for CNN. So we're going to note objects for detection with bounding boxes. I referred to several guides for object detection labeling like PASCAL. However, we encountered an issue for labeling.

If we want to label people in dataset images, do we need to label all visible objects(=people) in a picture? If we skip some objects(=people) in a picture, does it effect on object detection? I added some examples for labeling. Image (1) is a case of labeling all visible people in an image. And in Image (2), we just labeled some people in entire image.

Is Image (2) influence bad effect on object detection? It it does, we're going to label all visible objects as possible in an image.

(Image 1) Labeling all visible objects in a picture

(Image 2) Labeling some visible objects in a picture

答:
Yes it is important, if you skip some persons the network will only partially learn how to detect and regress a person location. The network may be resilient to few labelling errors but not as many as in your second example image.

To train an accurate network you need to label every visible object instance and if you want your network to be resilient to object obfuscation you should label partially masked objects too.

You can easily verify this behaviour by training two networks: one with all labels and the other one with half of them.


问:
Use order output parameter and specify serialization key with marshmallow-sqlalchemy
I'm using marshmallow 3.4.0 and marshmallow-sqlalchemy 0.22.2

I have this SQLAlchemy model and Marshmallow schema

```<code>class Zone(Base):
    zone_id = Column(Integer, primary_key=True)
    name = Column(String(65))
    location_id = Column(Integer, ForeignKey('locations.location_id'))
    location = relationship("Location", lazy="joined")

class ZoneSchema(SQLAlchemySchema):
    class Meta:
        model = Zone
        fields = ("zone_id", "name", "location")
        ordered = True
        load_instance = True

    zone_id = auto_field(data_key="id")
    location = fields.Nested(LocationSchema)
</code>```

If I remove
zone_id = auto_field(data_key="id")
the fields are ordered as requested.

If I remove

```<code>fields = ("zone_id", "name", "location")
ordered = True
</code>```

The key is set to id as requested.

If I run the code above, I get this error

```<code>
  File "[...]/models_schema.py", line 30, in <module>
    class ZoneSchema(SQLAlchemySchema):
  File "/venvs/backend-api/lib/python3.8/site-packages/marshmallow/schema.py", line 107, in __new__
    cls_fields = _get_fields(attrs, base.FieldABC, pop=True, ordered=ordered)
  File "/venvs/backend-api/lib/python3.8/site-packages/marshmallow/schema.py", line 57, in _get_fields
    fields.sort(key=lambda pair: pair[1]._creation_index)
  File "/venvs/backend-api/lib/python3.8/site-packages/marshmallow/schema.py", line 57, in <lambda>
    fields.sort(key=lambda pair: pair[1]._creation_index)
AttributeError: 'SQLAlchemyAutoField' object has no attribute '_creation_index'
</code>```

Could someone explain to me how I can set access the zone_id field and add the "data_key" property ?

答:
As a last resort, I read the documentation and I managed to find an answer by myself.

```<code>class ZoneSchema(SQLAlchemySchema):
    class Meta:
        model = Zone
        fields = ("zone_id", "name", "location")
        ordered = True
        load_instance = True

    location = fields.Nested(LocationSchema)

    @pre_dump
    def set_data_key_for_zone_id(self, data, many, **kwargs):
        self.fields.get("zone_id").data_key = "id"
        return data
</code>```

As you can see, I kept the ordered = True part and use the pre-dump decorator to access the zone_id field and set the data_key attribute.

If there is a better way to do this, please let me/us know !

Body:
I'm using marshmallow 3.4.0 and marshmallow-sqlalchemy 0.22.2

I have this SQLAlchemy model and Marshmallow schema

class Zone(Base):
    zone_id = Column(Integer, primary_key=True)
    name = Column(String(65))
    location_id = Column(Integer, ForeignKey('locations.location_id'))
    location = relationship("Location", lazy="joined")

class ZoneSchema(SQLAlchemySchema):
    class Meta:
        model = Zone
        fields = ("zone_id", "name", "location")
        ordered = True
        load_instance = True

    zone_id = auto_field(data_key="id")
    location = fields.Nested(LocationSchema)

If I remove
zone_id = auto_field(data_key="id")
the fields are ordered as requested.

If I remove

fields = ("zone_id", "name", "location")
ordered = True

The key is set to id as requested.

If I run the code above, I get this error

  File "[...]/models_schema.py", line 30, in <module>
    class ZoneSchema(SQLAlchemySchema):
  File "/venvs/backend-api/lib/python3.8/site-packages/marshmallow/schema.py", line 107, in __new__
    cls_fields = _get_fields(attrs, base.FieldABC, pop=True, ordered=ordered)
  File "/venvs/backend-api/lib/python3.8/site-packages/marshmallow/schema.py", line 57, in _get_fields
    fields.sort(key=lambda pair: pair[1]._creation_index)
  File "/venvs/backend-api/lib/python3.8/site-packages/marshmallow/schema.py", line 57, in <lambda>
    fields.sort(key=lambda pair: pair[1]._creation_index)
AttributeError: 'SQLAlchemyAutoField' object has no attribute '_creation_index'

Could someone explain to me how I can set access the zone_id field and add the "data_key" property ?

Body:
As a last resort, I read the documentation and I managed to find an answer by myself.

class ZoneSchema(SQLAlchemySchema):
    class Meta:
        model = Zone
        fields = ("zone_id", "name", "location")
        ordered = True
        load_instance = True

    location = fields.Nested(LocationSchema)

    @pre_dump
    def set_data_key_for_zone_id(self, data, many, **kwargs):
        self.fields.get("zone_id").data_key = "id"
        return data

As you can see, I kept the ordered = True part and use the pre-dump decorator to access the zone_id field and set the data_key attribute.

If there is a better way to do this, please let me/us know !


问:
jQuery set dynamically created input fields based on difference between 2 fields
Is there a way I can set input values of each dynamically created input fields based on a difference between 2 dynamically created fields. Below is my code and what am trying to achieve.

HTML

```<code><table id="requested-wh-stock-table" class="table table-bordered table-hover dataTable" width="100%">
    <thead>
        <tr>
            <th>Luminaire</th>
            <th>Order Quantity</th>
            <th>Delivered Qty</th>
            <th>Back Order Qty</th>
        </tr>
    </thead>
    <tbody>
        @foreach ($salesorder as $request)
        <tr>
            <td><input type="text" class="form-control" name="luminaire" value="{{$request->luminaire}}" readonly></td>
            <td><input type="number" class="form-control" name="order_quantity" id="order_quantity"
                    value="{{$request->quantity}}" readonly /></td>
            <td><input type="number" class="form-control" name="delivered_quantity" id="delivered_quantity" value="" />
            </td>
            <td><input type="number" class="form-control" name="backorder_quantity" id="backorder_quantity" value=""
                    readonly /></td>
        </tr>
        @endforeach
    </tbody>
</table>
</code>```

jQuery

```<code>//Update Backorder qty based on Delivered Quantity amount
$(document).ready(function () {
    $("#delivered_quantity").change(function () {
        var backorder_quantity = $("#order_quantity").val() - $("#delivered_quantity").val();
        $("#backorder_quantity").val(backorder_quantity);
    });
});
</code>```

Currently, it only updates the first field, it does not update other fields, is there a way I can loop through all fields and update Backorder field as I change the Delivered Quantity field?

答:
You should not use id on elements which are not unique. Since the inputs will be rendered multiple times (in rows), then I suggest to not use the id attribute. So let's try to use the name attribute instead for finding the DOM.

On the change event listener of delivered_quantity input, get the other fields in the same row. To do that, from this object inside the event handler, do seek the closest tr and then find the particular field from it's child.

$(document).ready(function() {
    $("[name=delivered_quantity]").change(function() {
        var order_quantity = $(this).closest('tr').find("[name=order_quantity]").val()
        var delivered_quantity = $(this).closest('tr').find("[name=delivered_quantity]").val();
        var backorder_quantity = order_quantity - delivered_quantity

        $(this).closest('tr').find("[name=backorder_quantity]").val(backorder_quantity);
    });
});
```

Body:
Is there a way I can set input values of each dynamically created input fields based on a difference between 2 dynamically created fields. Below is my code and what am trying to achieve.

HTML

            Luminaire
            Order Quantity
            Delivered Qty
            Back Order Qty

        @foreach ($salesorder as $request)

            <input type="text" class="form-control" name="luminaire" value="{{$request->luminaire}}" readonly>
            <input type="number" class="form-control" name="order_quantity" id="order_quantity"
                    value="{{$request->quantity}}" readonly />
            <input type="number" class="form-control" name="delivered_quantity" id="delivered_quantity" value="" />

            <input type="number" class="form-control" name="backorder_quantity" id="backorder_quantity" value=""
                    readonly />

        @endforeach

jQuery

//Update Backorder qty based on Delivered Quantity amount
$(document).ready(function () {
    $("#delivered_quantity").change(function () {
        var backorder_quantity = $("#order_quantity").val() - $("#delivered_quantity").val();
        $("#backorder_quantity").val(backorder_quantity);
    });
});

Currently, it only updates the first field, it does not update other fields, is there a way I can loop through all fields and update Backorder field as I change the Delivered Quantity field?


问:
Cypress isn't retaining my authentication cookie when using visit() multiple times in one test
Part of my Cypress E2E tests are validating that certain URLs are fully restricted so users without the correct role cannot access them. To that end, I've written a scenario with multiple visit statements in it:

```<code>beforeEach(() => {
    cy.visit(Cypress.env(HOST_URL));

});

it('cannot scan without scan role', () => {
    cy.login(standard.userName, password);
    cy.get('#scanDirectoryLink_text')
        .should('not.exist');
    cy.visit(`${Cypress.env(HOST_URL)}/scanning`);
    cy.url()
        .should('not.include', 'scanning')
        .should('not.include', 'login');
});
</code>```

In this scenario, I both validate that the link to the page is not visible, and that directly navigating to the URL won't succeed. My problem is that when I use the second cy.visit() command, it bumps me back to the login page. So technically it doesn't reach the page, but the reason for this is not what I intended.

I don't want to preserve my cookies between tests, but I'm hoping to preserve them across multiple cy.visit() calls so that I don't loose my authentication. Or else is there a better way to programmatically move to a new URL within my site?

答:
Try add this in support/index.js</p>

```<code>Cypress.LocalStorage.clear = function (keys, ls, rs) {
  //keep localStorage
  return;
}
</code>```

Body:
Part of my Cypress E2E tests are validating that certain URLs are fully restricted so users without the correct role cannot access them. To that end, I've written a scenario with multiple visit statements in it:

beforeEach(() => {
    cy.visit(Cypress.env(HOST_URL));

});

it('cannot scan without scan role', () => {
    cy.login(standard.userName, password);
    cy.get('#scanDirectoryLink_text')
        .should('not.exist');
    cy.visit(`${Cypress.env(HOST_URL)}/scanning`);
    cy.url()
        .should('not.include', 'scanning')
        .should('not.include', 'login');
});

In this scenario, I both validate that the link to the page is not visible, and that directly navigating to the URL won't succeed. My problem is that when I use the second cy.visit() command, it bumps me back to the login page. So technically it doesn't reach the page, but the reason for this is not what I intended.

I don't want to preserve my cookies between tests, but I'm hoping to preserve them across multiple cy.visit() calls so that I don't loose my authentication. Or else is there a better way to programmatically move to a new URL within my site?

Body:
Try add this in support/index.js

Cypress.LocalStorage.clear = function (keys, ls, rs) {
  //keep localStorage
  return;
}


问:
Read posts from a Facebook fans page
One of my apps has a page on Facebook. This app is a Windows Phone app.

I don't know if I can do the following:

I want to read all posts from Facebook page and show it in a ListBox inside Windows Phone app.

Can I do that?

答:
You can use the Facebook SDK from WP7: http://facebooksdk.codeplex.com/wikipage?title=Code%20Examples

Here is an example of reading a post: http://facebooksdk.codeplex.com/wikipage?title=Code%20Examples

Title: Read posts from a Facebook fans page


问:
How to parallel process binary files in Ruby?
I'm trying to make a function that splits binary file into chunks and uploads

class ChunksClient < ApiStruct::Client
  # Takes the file, splits it into chunks and uploads each chunk into array of urls
  # in corresponding order
  def upload_chunks(big_file, array_of_urls)
    chunk_size = 5242880
    links.each do |link|
      chunk = object.read(chunk_size)
      upload_chunk(chunk, link)
    end
  end

  def upload_chunk(chunk, link)
    put(path: link, body: chunk, headers: { 'Content-type': 'application/octet-stream' })
  end
end
```

<p>However, doing it one chunk in a time is slow. So I tried to process them in parallel:</p>

<pre class="lang-rb prettyprint-override"><code>class ChunksClient < ApiStruct::Client
  # Takes the file, splits it into chunks and uploads each chunk into array of urls
  # in corresponding order
  def upload_chunks(big_file, array_of_urls)
    @chunk_size = 5242880
    @index = 0
    @object = object
    threads = []
    links.each do
      threads << Thread.new do
        chunk, index = take_chunk_with_index
        upload_chunk(chunk, links[index])
      end
    end
    threads.each(&:join)
  end

  private

  def upload_chunk(chunk, link)
    put(path: link, body: chunk, headers: { 'Content-type': 'application/octet-stream' })
  end

  def take_chunk_with_index
    index = @index
    chunk = @object.read(@chunk_size)
    @index += 1
    [chunk, index]
  end
end
</code>```

But it puts chunks into random links each time. I could just load the chunks into memory, but that way it would have trouble uploading big files (in gigabytes, for example)

Is there a correct way to process binary files with threads?

答:
You should synchronize your take_chunk_with_index method with Mutex like so;

@mutex = Mutex.new

def take_chunk_with_index
  @mutex.synchronize do
    index = @index
    chunk = @object.read(@chunk_size)
    @index += 1
    [chunk, index]
  end
end
```

Body:
I'm trying to make a function that splits binary file into chunks and uploads

class ChunksClient < ApiStruct::Client
  # Takes the file, splits it into chunks and uploads each chunk into array of urls
  # in corresponding order
  def upload_chunks(big_file, array_of_urls)
    chunk_size = 5242880
    links.each do |link|
      chunk = object.read(chunk_size)
      upload_chunk(chunk, link)
    end
  end

  def upload_chunk(chunk, link)
    put(path: link, body: chunk, headers: { 'Content-type': 'application/octet-stream' })
  end
end

However, doing it one chunk in a time is slow. So I tried to process them in parallel:

class ChunksClient < ApiStruct::Client
  # Takes the file, splits it into chunks and uploads each chunk into array of urls
  # in corresponding order
  def upload_chunks(big_file, array_of_urls)
    @chunk_size = 5242880
    @index = 0
    @object = object
    threads = []
    links.each do
      threads << Thread.new do
        chunk, index = take_chunk_with_index
        upload_chunk(chunk, links[index])
      end
    end
    threads.each(&:join)
  end

  private

  def upload_chunk(chunk, link)
    put(path: link, body: chunk, headers: { 'Content-type': 'application/octet-stream' })
  end

  def take_chunk_with_index
    index = @index
    chunk = @object.read(@chunk_size)
    @index += 1
    [chunk, index]
  end
end

But it puts chunks into random links each time. I could just load the chunks into memory, but that way it would have trouble uploading big files (in gigabytes, for example)

Is there a correct way to process binary files with threads?


问:
How do you save the Slack modal view ID for future updates?
I'm using Slack's modals + their new BlockKit interactive actions. I have a modal dialog with several section's that include select menu accessories. When one of those accessories changes (ex: user preference goes from Yes -> No), I want to update the modal's view to reflect the change in some contextual text.

The docs outline two ways to update a model. Because I'm not using the traditional modal inputs, I have to update the modal via the API and not via response_action. Proof: I don't even receive a view_submission payload at all... I receive a blockkit_action payload.

The docs conflict a bit. In the above link they say that to update a view you must pass in the returned ID of the view when it was opened:

Remember the view.id that was included in the success response when
  you used views.open earlier? We hope you kept it, because you can now
  use it to update that view.

But when you look at the docs for the views.open and views.update, it appears there is a second option: external_id. The views.update docs say this:

A unique identifier of the view set by the developer. Must be unique
  for all views on a team. Max length of 255 characters. Either view_id
  or external_id is required.

Initially I got everything working really nicely by choosing an external ID of myapp-mymodal-[userID]. But as soon as I tried opening the modal simultaneously on my Desktop + Mobile client, I started getting internal_error responses and have been unable to open the modal since!

So I started looking into saving the view ID, per the first quote. My problem is: that ID changes every time the modal opens. I don't understand how I am expected to possibly keep track of the 0-2 "active" view IDs that might be taking place across a user's Desktop + Mobile clients (or more than 2 if they have an iPad, a second laptop, etc).

I tried to look for some sort of unique client ID that I could either use to include in the external_id or in my view_id persistence logic, but given that Slack's API appears to be sesssion-less I couldn't find any such thing.

How do others solve this problem?

答:
Try using the private_metadata field in the View

I initially did the same thing you did, which worked, but I wanted to avoid that edge case if possible. What I figured out, is that I could pass the external_id that I created when opening the view into the view's metadata, and then retrieve it when I receive an interaction.

When I set the external_id I set it to the userID + the current time (so it's always unique, even if the user opens the modal from different devices)

```<code>externalID := UserID + time.Now().String()
</code>```

and pass that both as the external_id for the view, and as a string into the private_metadata.

```<code>PrivateMetadata string `json:"private_metadata"`
</code>```

When the user interacts with one of my blocks and Slack sends me the interactive message, I retrieve the metadata like this:

```<code>Request.Payload.View.PrivateMetadata
</code>```

I wrote my Slack app in Go, but I tried to make it clear for any language. Let me know if anything is unclear or needs expanding on - this is my first time giving back to the Stackoverflow community.

Body:
Try using the private_metadata field in the View

I initially did the same thing you did, which worked, but I wanted to avoid that edge case if possible. What I figured out, is that I could pass the external_id that I created when opening the view into the view's metadata, and then retrieve it when I receive an interaction.

When I set the external_id I set it to the userID + the current time (so it's always unique, even if the user opens the modal from different devices)

externalID := UserID + time.Now().String()

and pass that both as the external_id for the view, and as a string into the private_metadata.

PrivateMetadata string `json:"private_metadata"`

When the user interacts with one of my blocks and Slack sends me the interactive message, I retrieve the metadata like this:

Request.Payload.View.PrivateMetadata

I wrote my Slack app in Go, but I tried to make it clear for any language. Let me know if anything is unclear or needs expanding on - this is my first time giving back to the Stackoverflow community.


问:
Passing a double pointer in a function
I was creating a program with linked lists in C. I created a head variable in main function. Then I passed it by reference to a function insert_at_head(struct node **head).

I have another function for inserting at tail. In a base condition, if my list is empty, I want to call insert_at_head(struct node **head) again. But I am getting confused in passing the actual parameter. Should it be insert_at_head (&(*head)) or insert_at_head (head)?

Personally, I think both are same, because both of them are passing a double pointer. Which one should I use?

答:
Regarding the insert_at_head function, you have to remember that in C all arguments are passed by value. That means the value is copied into the argument variable. Inside the function, if you modify the argument variable (like assigning to it) then you only modify the copy, not the original.

If you want to modify the original value, then you have to emulate pass by reference, which can be done by using the address-of operator & to pass a pointer to the value. If you want to do this for a variable which is a pointer, then you get a pointer to a pointer.

Here's a simple example:

```<code>#include <stdio.h>

// Define two global variables
int a = 10;
int b = 20;

void change1(int *x)
{
    x = &b;  // Make x point to b
}

void change2(int **x)
{
    *x = &b;  // Make *x point to b
}

int main(void)
{
    // Define a pointer variable, and make it point to the global variable a
    int *pointer_to_a = &a;

    // Will print the value of a, i.e. 10
    printf("*pointer_to_a = %d\n", *pointer_to_a);

    // Try to change where pointer_to_a is pointing
    change1(pointer_to_a);

    // Here pointer_to_a is *still* pointing to a, it wasn't changed, will print the value 10
    printf("*pointer_to_a = %d\n", *pointer_to_a);

    // Do another attempt to change where pointer_to_a is pointing
    change2(&pointer_to_a);

    // Now pointer_to_a is no longer pointing to a, it points to b and 20 will be printed
    printf("*pointer_to_a = %d\n", *pointer_to_a);
}
</code>```

Getting back to the insert_at_head function (whose functionality we can only speculate about) I'm guessing it will add to the head of a linked list. It will do that by modifying where the head of the list is pointing.

As seen by the example above, unless we pass a pointer to the pointer, assignments to the head will be lost once the function ends. And this is solved by using pointer to a pointer, and passing the head pointer using the address-of operator & when calling the function.

Title: Passing a double pointer in a function

Body:
Regarding the insert_at_head function, you have to remember that in C all arguments are passed by value. That means the value is copied into the argument variable. Inside the function, if you modify the argument variable (like assigning to it) then you only modify the copy, not the original.

If you want to modify the original value, then you have to emulate pass by reference, which can be done by using the address-of operator & to pass a pointer to the value. If you want to do this for a variable which is a pointer, then you get a pointer to a pointer.

Here's a simple example:

#include <stdio.h>

// Define two global variables
int a = 10;
int b = 20;

void change1(int *x)
{
    x = &b;  // Make x point to b
}

void change2(int **x)
{
    *x = &b;  // Make *x point to b
}

int main(void)
{
    // Define a pointer variable, and make it point to the global variable a
    int *pointer_to_a = &a;

    // Will print the value of a, i.e. 10
    printf("*pointer_to_a = %d\n", *pointer_to_a);

    // Try to change where pointer_to_a is pointing
    change1(pointer_to_a);

    // Here pointer_to_a is *still* pointing to a, it wasn't changed, will print the value 10
    printf("*pointer_to_a = %d\n", *pointer_to_a);

    // Do another attempt to change where pointer_to_a is pointing
    change2(&pointer_to_a);

    // Now pointer_to_a is no longer pointing to a, it points to b and 20 will be printed
    printf("*pointer_to_a = %d\n", *pointer_to_a);
}

Getting back to the insert_at_head function (whose functionality we can only speculate about) I'm guessing it will add to the head of a linked list. It will do that by modifying where the head of the list is pointing.

As seen by the example above, unless we pass a pointer to the pointer, assignments to the head will be lost once the function ends. And this is solved by using pointer to a pointer, and passing the head pointer using the address-of operator & when calling the function.


问:
Mix and trim 2 files with Sox
I need a little bit help and hope to find that here.

I am using sox for tagging some music with voice tags on my server while user is uploading the file. This is my command which I was using. Everything is working fine.

```<code>sox -m {voice_tag_loop} {source_file} {output_file}
</code>```

Now I want to change something, but don't know how to do that and find no solution.
So the {voice_tag_loop} will be uploaded by user and can have all length e.g. 30 seconds, 20s, 17s or 1 Minute. Don't know that before.

The {source_file} is the music file and can have also different length e.g. 3:13 Min, 4:20Min

How can I mix the {voice_tag_loop} with the {source_file} that the {output_file} has the length of {source_file} but has the {voice_tag_loop} is mixed and looped/ repeated into also with as long the length of the {source_file}

I hope I could explain that, that you can understand that.

Best regards

答:
OK I have now the answer for all you wants to mix short audio with long audio and the short one should repeated as long the long audio is.

In my case a small description. The short file will be changed to 44.1kHz and will be looped every 30 seconds. Max 100 times but as long as the long file is. And finally both files will be mixed. This all is one procedure.

sox {short_file} -r 44.1k -p pad 0 30 repeat 100 trim 0 $(sox --i -d {long_file}) | sox - -m  {long_file} {output_file}

Regards

Title: Mix and trim 2 files with Sox

Body:
I need a little bit help and hope to find that here.

I am using sox for tagging some music with voice tags on my server while user is uploading the file. This is my command which I was using. Everything is working fine.

sox -m {voice_tag_loop} {source_file} {output_file}

Now I want to change something, but don't know how to do that and find no solution.
So the {voice_tag_loop} will be uploaded by user and can have all length e.g. 30 seconds, 20s, 17s or 1 Minute. Don't know that before.

The {source_file} is the music file and can have also different length e.g. 3:13 Min, 4:20Min

How can I mix the {voice_tag_loop} with the {source_file} that the {output_file} has the length of {source_file} but has the {voice_tag_loop} is mixed and looped/ repeated into also with as long the length of the {source_file}

I hope I could explain that, that you can understand that.

Best regards


问:
Enable quicks (double?) clicks on Ipad Safari
I'm building a HTML/JavaScript interface in which I would need some reactivity and so, the possibility for users to click really fast on the same button on the page.

I disabled the doubleclick/zoom on the iPad thanks to the <meta name="viewport" content="user-scalable=no" />, but then, if I double click or click too fast on the buttons, it does nothing.

I'm using jQuery and tried the dblclick event, didn't work.

答: You can try using the doubletap plugin which enable the use of "doubletap" events on iPhone and iPad devices.</p>


问:
Word Addin/OfficeJS - Detect if Cursor is on Chart Element
I want to be able to check if the document cursor is inside of a Chart element within the MS Word API. Right now I have an application that inserts text, but when I try to insert said text into the title of the Chart, it deletes the chart and replaces it with the Content Control I'm inserting.

Instead of deleting the chart, I want to check if the cursor is inside of the Chart via context. If I'm inside of the Chart in any way, be able to throw a warning message to the user and escape. Is there a way to do this?

答:
This should do it. Like @CindyMeister said you can check the ooxml and inspect it, range.getOoxml() will only return something if the cursor is on some xml object that's been inserted into the document.

example.ts

Word.run(async (context: RequestContext) => {
  const range: Range = context.document.getSelection();
  const ooxml: ClientResult<string> = range.getOoxml();
  context.load(range);
  await context.sync();

  const ooxmlVal = ooxml.value;
  if (ooxmlVal) {

    const lowered = ooxmlVal.toLowerCase();
    const isChart = lowered.includes("excel") && lowered.includes("chart");
    if (isChart) {
      console.log("CURSOR IS ON CHART");
    }
  }
});
```


问:
How do I append an HTTP header in this format in PHP (cURL)?
I am trying to make a GET request in PHP using cURL and here is what the documentation says about my header:

Append an HTTP header called zuluapi using the created signature.

zuluapi <publicKey>:<base 64 encoded signature>

I have the publicKey and signature, I just can't seem to figure out how to attach the header in the way they want. When I try to add the header, like below, I get bad header error.

```<code>$headers = [
    "zuluapi {$public}:{$signedMessage}"
];
</code>```

答:
The header structure is indeed invalid.

Look for the specification (rfc):
https://www.rfc-editor.org/rfc/rfc7230#section-3.2.3

No whitespace is allowed between the header field-name and colon.  In
the past, differences in the handling of such whitespace have led to
security vulnerabilities in request routing and response handling.

You are not allowed to use whitespace in the header name.

Since i am not familiar with the api you are trying to make requests to and did not provide any links to the docs i am going to give you some examples, pick the one that works for you.

```<code>// Posibility #1
$headers = [
    "zuluapi{$public}: {$signedMessage}"
];

// Posibility #2
$headers = [
    "zuluapi-{$public}: {$signedMessage}"
];
</code>```

Body:
I am trying to make a GET request in PHP using cURL and here is what the documentation says about my header:

Append an HTTP header called zuluapi using the created signature.

zuluapi <publicKey>:<base 64 encoded signature>

I have the publicKey and signature, I just can't seem to figure out how to attach the header in the way they want. When I try to add the header, like below, I get bad header error.

$headers = [
    "zuluapi {$public}:{$signedMessage}"
];

Body:
The header structure is indeed invalid.

Look for the specification (rfc):
https://www.rfc-editor.org/rfc/rfc7230#section-3.2.3

No whitespace is allowed between the header field-name and colon.  In
the past, differences in the handling of such whitespace have led to
security vulnerabilities in request routing and response handling.

You are not allowed to use whitespace in the header name.

Since i am not familiar with the api you are trying to make requests to and did not provide any links to the docs i am going to give you some examples, pick the one that works for you.

// Posibility #1
$headers = [
    "zuluapi{$public}: {$signedMessage}"
];

// Posibility #2
$headers = [
    "zuluapi-{$public}: {$signedMessage}"
];


问:
Can adding equals() and hashCode() method spoil something
Is it possible that adding equals() and hashCode() methods will break already existing code?

I have a class with 3 fields, getters and setters:

```<code>public class Person {
private final String name;
private final List<Friend> friends;
private final Integer age;
</code>```

to test this class I used: isEqualToComparingFieldByField() method to compare two Person objects instead of adding equals() and hashCode(). Other solution is to override equals() and hashCode() and use assertEquals() to compare these object but can I be totally sure that it won't break anything?

答:
Can I be totally sure that it won't break anything?

No. You're changing the meaning of equality from reference identity to a sort of value equality. You'll break anything relying on the current behaviour. For example, here's some valid code:

```<code>Person person1 = new Person("Foo", 100);
Person person2 = new Person("Foo", 100);
// This is fine. Two distinct Person objects will never be equal...
if (person1.equals(person2)) {
    launchNuclearMissiles();
}
</code>```

Your proposed change would break that.

Do you actually have code like that? It's hard to tell.

More likely, if you want to change hashCode to include hashes from the List<Friend>, you could very easily break code unless the type is actually immutable. For example:

```<code>Map<Person, String> map = new HashMap<>();
Person person = new Person("Foo", 100);
map.put(person, "Some value");

// If this changes the result of hashCode()...
person.addFriend(new Friend("Bar"));
// ... then you may not be able to find even the same object in the map.
System.out.println(map.get(person));
</code>```

Fundamentally, you need to be aware of what other code uses Person, so you know what it's relying on. If Person is immutable, that makes life much simpler because you don't need to worry about the second kind of problem. (Overriding equals() and hashCode() for mutable types is a fundamentally treacherous business.)

Body:
Is it possible that adding equals() and hashCode() methods will break already existing code?

I have a class with 3 fields, getters and setters:

public class Person {
private final String name;
private final List<Friend> friends;
private final Integer age;

to test this class I used: isEqualToComparingFieldByField() method to compare two Person objects instead of adding equals() and hashCode(). Other solution is to override equals() and hashCode() and use assertEquals() to compare these object but can I be totally sure that it won't break anything?

Body:
Can I be totally sure that it won't break anything?

No. You're changing the meaning of equality from reference identity to a sort of value equality. You'll break anything relying on the current behaviour. For example, here's some valid code:

Person person1 = new Person("Foo", 100);
Person person2 = new Person("Foo", 100);
// This is fine. Two distinct Person objects will never be equal...
if (person1.equals(person2)) {
    launchNuclearMissiles();
}

Your proposed change would break that.

Do you actually have code like that? It's hard to tell.

More likely, if you want to change hashCode to include hashes from the List<Friend>, you could very easily break code unless the type is actually immutable. For example:

Map<Person, String> map = new HashMap<>();
Person person = new Person("Foo", 100);
map.put(person, "Some value");

// If this changes the result of hashCode()...
person.addFriend(new Friend("Bar"));
// ... then you may not be able to find even the same object in the map.
System.out.println(map.get(person));

Fundamentally, you need to be aware of what other code uses Person, so you know what it's relying on. If Person is immutable, that makes life much simpler because you don't need to worry about the second kind of problem. (Overriding equals() and hashCode() for mutable types is a fundamentally treacherous business.)


问:
Keep a radio button checked after submit
I am trying to keep a radio button checked even after submission (in Angular).</p>

```<code><label class="container" *ngFor="let content of contents; let idx = index">
    <input type="radio"
       value={{content}}
       (change)="radioChangeHandler($event)"  name="radio">
       {{content}}
    <span class="checkmark"></span>
</label>
</code>```

答: When front-end sends data (object, array, etc) to the back-end, it receives response. This response may contain various types of information, including data showing what it is received by the back-end. Use the response for mapping (and keeping the stored data still visible on your form).</p>

Body:
I am trying to keep a radio button checked even after submission (in Angular).

    <input type="radio"
       value={{content}}
       (change)="radioChangeHandler($event)"  name="radio">
       {{content}}


问:
Trunk-based development release & hotfix questions
I'm having trouble to understand how to deal with the following scenario:

Feature A is committed to master as commit A.

We are ready for release v1.0.0 so we tag commit A as v1.0.0 and we create a release branch rel-1.0.x from it for QA.

Feature B is committed to master as commit B.

QA approves v1.0.0, we deploy and delete the rel-1.0.x branch.

We are ready for release v2.0.0 so we tag commit B as v2.0.0 and create a rel-2.0.x branch from it for QA.

A bug is found in production (v1.0.0) and must be fixed and deployed right away.

At this point I'm not sure how we should handle that. If the bug is in the trunk we could create a hotfix branch from the trunk, fix the bug and merge into the trunk. Then, create a rel-1.0.1 branch from v1.0.0, cherry-pick the fix from the trunk, tag it as v1.0.1 and deploy.

Now what I find odd is that the v1.0.1 commit is not as-is in master given it's been cherry-picked from master and tagged in the rel-1.0.1 branch. Furthermore, if the fix is also needed in rel-2.0.x then how should we handle this? Should we cherry-pick the bug-fix from the trunk again and tag it as a different version, such as v2.0.1?

Here's the kind of graph I'd be getting doing the above (note that v1.1 represents version 2.0 of the text above and that it's the Second feature A fix that occurred while preparing the v1.1 release.):

答:
Coming back to this question, it seems like my concerns were not founded and the versioning/tagging approach as well as the workflow described in the above question is acceptable and works just fine in practice.

One challenge I've faced though is when master incrementally diverges more and more from what's in production. This could happen for many reasons, such as having commits in master that were in theory ready to get released, but somehow didn't go in production. The way I've dealt with that problem is by continuously re-working the commit tree in production so that what diverges stays on top.


问:
How can I not show a css drop shadow on ie6?
I want to know if I can ignore my css drop shadow on ie6 without using conditional statements to filter the css.

here is my current css:

```<code>/* Drop shadow */
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000')";
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000');
box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);
-moz-box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);
-o-box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);
-webkit-box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);
</code>```

Maybe -ms-filter-ie6: none or something :P along those lines

答: IE6 only knows about filter, it won't recognise the -ms-filter style, so dropping filter would do the trick. The downside is that this would also kill it for IE7.

Body:
I want to know if I can ignore my css drop shadow on ie6 without using conditional statements to filter the css.

here is my current css:

/* Drop shadow */
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000')";
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=4, Direction=135, Color='#000000');
box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);
-moz-box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);
-o-box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);
-webkit-box-shadow: 0px 10px 15px rgba(0, 0, 0, 0.7);

Maybe -ms-filter-ie6: none or something :P along those lines


问:
How to create a 3 dimensional array and then pull info 1 dimension at a time?
I would like to take data sets from Sheet 1 and fill in table values in Sheet 2. I believe using a multidimensional array to be the optimum way of accomplishing this.

Sheet 1 is setup as such:
Column A = "Dates", Column C = "SNs", Column E = "M0s", and Column F = "HNs".

An operator enters in an M0 value, and if a ("E").Row has that value, I want that row's SN, HN, and Date to be entered into Sheet 2. Just because two rows have the same M0 doesn't mean they have the same SN, HN, or Date. I would like each row's values to be stored separately, hence a multidimensional array (3 dimensional in this case).

The code below is my successful attempt at storing all SNs in an single dimensional array (based on M0 entered) and then entering those values into Sheet 2.

```<code>        Sub FillSheet2()
        Dim varSNarray As Variant
        Dim M0cell As Range
        Dim SNcell As Long  'could be substituted with Variant or String

        ReDim varSNarray(0)
        For Each M0cell In ws.Range("E7:E200000").Cells
            If M0cell.Value <> vbNullString Then
                If M0cell.Value = varPrintM0 Then
                    SNcell = ws.Range("C" & M0cell.Row).Value
                    varSNarray(UBound(varSNarray)) = SNcell
                    ReDim Preserve varSNarray(UBound(varSNarray) + 1) As Variant

                End If
            End If
        Next M0cell

        ReDim Preserve varSNarray(UBound(varSNarray) - 1)

        Dim i As Long
        For i = LBound(varSNarray) To UBound(varSNarray)

            Dim ws2range As Range
            Dim ws2SNcellnum As Long

            If i > 149 Then
                Set ws2range = ws2.Range("AN6:AN55")
                    ws2SNcellnum = i - 144
                    ws2.Range("AN" & ws2SNcellnum).Value = varSNarray(i)

            ElseIf i > 99 Then
                Set ws2range = ws2.Range("AA6:AA55")
                    ws2SNcellnum = i - 94
                    ws2.Range("AA" & ws2SNcellnum).Value = varSNarray(i)

            ElseIf i > 49 Then
                Set ws2range = ws2.Range("N6:N55")
                    ws2SNcellnum = i - 44
                    ws2.Range("N" & ws2SNcellnum).Value = varSNarray(i)

            Else
                Set ws2range = ws2.Range("A6:A55")
                    ws2SNcellnum = i + 6
                    ws2.Range("A" & ws2SNcellnum).Value = varSNarray(i)
            End If

        Next i
 End Sub
</code>```

I would like to add HN and Date along with SN as this sub runs. I don't know how to augment the array to allow for HN and Date storage though. Below is how I imagine it would look like. However, I cannot successfully create my array. I'm fairly sure it has something to do with my variable setups.

```<code>            Dim varSNarray As Variant
            Dim M0cell As Range
            Dim SNcell As Long
            Dim HNcell As Long
            Dim Datecell As Long

            ReDim varSNarray(0, 0, 0)
            For Each M0cell In ws.Range("E7:E200000").Cells
                If M0cell.Value <> vbNullString Then
                    If M0cell.Value = varPrintM0 Then
                    SNcell = ws.Range("C" & M0cell.Row).Value
                        varSNarray(UBound(varSNarray), HNcell, Datecell) = SNcell
                        varSNarray(SNcell, UBound(varSNarray), Datecell) = HNcell 'Script out of range error
                        varSNarray(SNcell, HNcell, UBound(varSNarray)) = Datecell

                        ReDim Preserve varSNarray(UBound(varSNarray) + 1, UBound(varSNarray) + 1, UBound(varSNarray) + 1) As Variant

                    End If

                End If
            Next M0cell

            ReDim Preserve varSNarray(UBound(varSNarray) - 1)

            Dim i As Long
            For i = LBound(varSNarray) To UBound(varSNarray)

                Dim ws2range As Range
                Dim ws2SNcellnum As Long

                If i > 149 Then
                    Set ws2range = ws2.Range("AN6:AN55")
                        ws2SNcellnum = i - 144
                        ws2.Range("AN" & ws2SNcellnum).Value = varSNarray(i)
                        ws2.Range("AN" & ws2SNcellnum).Value = varSNarray(HNcell)
                        ws2.Range("AN" & ws2SNcellnum).Value = varSNarray(Datecell)
                 ''''
                 Removed this section has its the same as above
                 ''''
                    Set ws2range = ws2.Range("A6:A55")
                        ws2SNcellnum = i + 6
                        ws2.Range("A" & ws2SNcellnum).Value = varSNarray(i)
                        ws2.Range("A" & ws2SNcellnum).Value = varSNarray(HNcell)
                        ws2.Range("A" & ws2SNcellnum).Value = varSNarray(Datecell)

                End If

            Next i
</code>```

How do I store data into a 3 dimensional array and then successful pull 1 dimension from the array at a time?

答:
I don't think an array is necessary here, just write the records to Sheet 2 as they are found. For example

```<code>Option Explicit
Sub FillSheet2()

    Const COL_DATE = "A"
    Const COL_SN = "C"
    Const COL_M0 = "E"
    Const COL_HN = "F"
    Const START_ROW = 7

    ' target sheet
    Const TARGET_START_ROW = 5
    Const TARGET_START_COL = 1 'A
    Const COL_REPEAT = 13 ' N, AA, AN
    Const MAX_ROWS = 50

    Dim wb As Workbook, wsSource As Worksheet, wsTarget As Worksheet
    Set wb = ThisWorkbook
    Set wsSource = wb.Sheets("Sheet1")
    Set wsTarget = wb.Sheets("Sheet2")
    wsTarget.Cells.Clear

    Dim iRow As Integer, iLastRow As Integer, iCount As Integer
    Dim iTargetRow As Integer, iTargetCol As Integer, sM0 As String
    Dim varPrintM0 As String

    iTargetCol = TARGET_START_COL
    iTargetRow = TARGET_START_ROW

    varPrintM0 = "Test4"

    iCount = 0
    iLastRow = wsSource.Range(COL_M0 & Rows.Count).End(xlUp).Row

    ' ----------
    With wsSource
        For iRow = START_ROW To iLastRow
            sM0 = .Range(COL_M0 & iRow)
            If sM0 = varPrintM0 Then

                With wsTarget.Cells(iTargetRow, iTargetCol)
                  .Offset(0, 0) = wsSource.Range(COL_SN & iRow).Value
                  .Offset(0, 1) = wsSource.Range(COL_HN & iRow).Value
                  .Offset(0, 2) = wsSource.Range(COL_DATE & iRow).Value
                End With
                iTargetRow = iTargetRow + 1

                If iTargetRow >= MAX_ROWS + TARGET_START_ROW Then
                  iTargetCol = iTargetCol + COL_REPEAT
                  iTargetRow = TARGET_START_ROW
                End If
                iCount = iCount + 1
            End If
        Next
    End With
    MsgBox iCount & " rows copied", vbInformation, "Finished"
    ' --------

End Sub
</code>```

If you do want to use an array replace the code between the ------ lines above with this

```<code>    Dim ar(5, 50, 3) As Variant ' max of 5 blocks of 50 records
    Dim t As Integer, r As Long
    t = 1: r = 1

    ' fill array
    With wsSource
        For iRow = START_ROW To iLastRow
            sM0 = .Range(COL_M0 & iRow)
            If sM0 = varPrintM0 Then

                With wsTarget.Cells(iTargetRow, iTargetCol)
                    ar(t, r, 0) = sM0
                    ar(t, r, 1) = wsSource.Range(COL_SN & iRow).Value
                    ar(t, r, 2) = wsSource.Range(COL_HN & iRow).Value
                    ar(t, r, 3) = wsSource.Range(COL_DATE & iRow).Value
                End With

                r = r + 1
                If r > MAX_ROWS Then
                    r = 1
                    t = t + 1
                End If
                iCount = iCount + 1
            End If
        Next
    End With

    ' output array
    Dim iLastTable As Long, c As Long
    iLastTable = t
    For t = 1 To iLastTable
        For r = 1 To 50
            c = 1 + COL_REPEAT * (t - 1)
            With wsTarget.Cells(r + 4, c)
                .Offset(0, 0) = ar(t, r, 1)
                .Offset(0, 1) = ar(t, r, 2)
                .Offset(0, 2) = ar(t, r, 3)
            End With
        Next r
    Next t
    MsgBox iCount & " rows copied using Array", vbInformation, "Finished"
</code>```

Body:
I would like to take data sets from Sheet 1 and fill in table values in Sheet 2. I believe using a multidimensional array to be the optimum way of accomplishing this.

Sheet 1 is setup as such:
Column A = "Dates", Column C = "SNs", Column E = "M0s", and Column F = "HNs".

An operator enters in an M0 value, and if a ("E").Row has that value, I want that row's SN, HN, and Date to be entered into Sheet 2. Just because two rows have the same M0 doesn't mean they have the same SN, HN, or Date. I would like each row's values to be stored separately, hence a multidimensional array (3 dimensional in this case).

The code below is my successful attempt at storing all SNs in an single dimensional array (based on M0 entered) and then entering those values into Sheet 2.

        Sub FillSheet2()
        Dim varSNarray As Variant
        Dim M0cell As Range
        Dim SNcell As Long  'could be substituted with Variant or String

        ReDim varSNarray(0)
        For Each M0cell In ws.Range("E7:E200000").Cells
            If M0cell.Value <> vbNullString Then
                If M0cell.Value = varPrintM0 Then
                    SNcell = ws.Range("C" & M0cell.Row).Value
                    varSNarray(UBound(varSNarray)) = SNcell
                    ReDim Preserve varSNarray(UBound(varSNarray) + 1) As Variant

                End If
            End If
        Next M0cell

        ReDim Preserve varSNarray(UBound(varSNarray) - 1)

        Dim i As Long
        For i = LBound(varSNarray) To UBound(varSNarray)

            Dim ws2range As Range
            Dim ws2SNcellnum As Long

            If i > 149 Then
                Set ws2range = ws2.Range("AN6:AN55")
                    ws2SNcellnum = i - 144
                    ws2.Range("AN" & ws2SNcellnum).Value = varSNarray(i)

            ElseIf i > 99 Then
                Set ws2range = ws2.Range("AA6:AA55")
                    ws2SNcellnum = i - 94
                    ws2.Range("AA" & ws2SNcellnum).Value = varSNarray(i)

            ElseIf i > 49 Then
                Set ws2range = ws2.Range("N6:N55")
                    ws2SNcellnum = i - 44
                    ws2.Range("N" & ws2SNcellnum).Value = varSNarray(i)

            Else
                Set ws2range = ws2.Range("A6:A55")
                    ws2SNcellnum = i + 6
                    ws2.Range("A" & ws2SNcellnum).Value = varSNarray(i)
            End If

        Next i
 End Sub

I would like to add HN and Date along with SN as this sub runs. I don't know how to augment the array to allow for HN and Date storage though. Below is how I imagine it would look like. However, I cannot successfully create my array. I'm fairly sure it has something to do with my variable setups.

            Dim varSNarray As Variant
            Dim M0cell As Range
            Dim SNcell As Long
            Dim HNcell As Long
            Dim Datecell As Long

            ReDim varSNarray(0, 0, 0)
            For Each M0cell In ws.Range("E7:E200000").Cells
                If M0cell.Value <> vbNullString Then
                    If M0cell.Value = varPrintM0 Then
                    SNcell = ws.Range("C" & M0cell.Row).Value
                        varSNarray(UBound(varSNarray), HNcell, Datecell) = SNcell
                        varSNarray(SNcell, UBound(varSNarray), Datecell) = HNcell 'Script out of range error
                        varSNarray(SNcell, HNcell, UBound(varSNarray)) = Datecell

                        ReDim Preserve varSNarray(UBound(varSNarray) + 1, UBound(varSNarray) + 1, UBound(varSNarray) + 1) As Variant

                    End If

                End If
            Next M0cell

            ReDim Preserve varSNarray(UBound(varSNarray) - 1)

            Dim i As Long
            For i = LBound(varSNarray) To UBound(varSNarray)

                Dim ws2range As Range
                Dim ws2SNcellnum As Long

                If i > 149 Then
                    Set ws2range = ws2.Range("AN6:AN55")
                        ws2SNcellnum = i - 144
                        ws2.Range("AN" & ws2SNcellnum).Value = varSNarray(i)
                        ws2.Range("AN" & ws2SNcellnum).Value = varSNarray(HNcell)
                        ws2.Range("AN" & ws2SNcellnum).Value = varSNarray(Datecell)
                 ''''
                 Removed this section has its the same as above
                 ''''
                    Set ws2range = ws2.Range("A6:A55")
                        ws2SNcellnum = i + 6
                        ws2.Range("A" & ws2SNcellnum).Value = varSNarray(i)
                        ws2.Range("A" & ws2SNcellnum).Value = varSNarray(HNcell)
                        ws2.Range("A" & ws2SNcellnum).Value = varSNarray(Datecell)

                End If

            Next i

How do I store data into a 3 dimensional array and then successful pull 1 dimension from the array at a time?

Body:
I don't think an array is necessary here, just write the records to Sheet 2 as they are found. For example

Option Explicit
Sub FillSheet2()

    Const COL_DATE = "A"
    Const COL_SN = "C"
    Const COL_M0 = "E"
    Const COL_HN = "F"
    Const START_ROW = 7

    ' target sheet
    Const TARGET_START_ROW = 5
    Const TARGET_START_COL = 1 'A
    Const COL_REPEAT = 13 ' N, AA, AN
    Const MAX_ROWS = 50

    Dim wb As Workbook, wsSource As Worksheet, wsTarget As Worksheet
    Set wb = ThisWorkbook
    Set wsSource = wb.Sheets("Sheet1")
    Set wsTarget = wb.Sheets("Sheet2")
    wsTarget.Cells.Clear

    Dim iRow As Integer, iLastRow As Integer, iCount As Integer
    Dim iTargetRow As Integer, iTargetCol As Integer, sM0 As String
    Dim varPrintM0 As String

    iTargetCol = TARGET_START_COL
    iTargetRow = TARGET_START_ROW

    varPrintM0 = "Test4"

    iCount = 0
    iLastRow = wsSource.Range(COL_M0 & Rows.Count).End(xlUp).Row

    ' ----------
    With wsSource
        For iRow = START_ROW To iLastRow
            sM0 = .Range(COL_M0 & iRow)
            If sM0 = varPrintM0 Then

                With wsTarget.Cells(iTargetRow, iTargetCol)
                  .Offset(0, 0) = wsSource.Range(COL_SN & iRow).Value
                  .Offset(0, 1) = wsSource.Range(COL_HN & iRow).Value
                  .Offset(0, 2) = wsSource.Range(COL_DATE & iRow).Value
                End With
                iTargetRow = iTargetRow + 1

                If iTargetRow >= MAX_ROWS + TARGET_START_ROW Then
                  iTargetCol = iTargetCol + COL_REPEAT
                  iTargetRow = TARGET_START_ROW
                End If
                iCount = iCount + 1
            End If
        Next
    End With
    MsgBox iCount & " rows copied", vbInformation, "Finished"
    ' --------

End Sub

If you do want to use an array replace the code between the ------ lines above with this

    Dim ar(5, 50, 3) As Variant ' max of 5 blocks of 50 records
    Dim t As Integer, r As Long
    t = 1: r = 1

    ' fill array
    With wsSource
        For iRow = START_ROW To iLastRow
            sM0 = .Range(COL_M0 & iRow)
            If sM0 = varPrintM0 Then

                With wsTarget.Cells(iTargetRow, iTargetCol)
                    ar(t, r, 0) = sM0
                    ar(t, r, 1) = wsSource.Range(COL_SN & iRow).Value
                    ar(t, r, 2) = wsSource.Range(COL_HN & iRow).Value
                    ar(t, r, 3) = wsSource.Range(COL_DATE & iRow).Value
                End With

                r = r + 1
                If r > MAX_ROWS Then
                    r = 1
                    t = t + 1
                End If
                iCount = iCount + 1
            End If
        Next
    End With

    ' output array
    Dim iLastTable As Long, c As Long
    iLastTable = t
    For t = 1 To iLastTable
        For r = 1 To 50
            c = 1 + COL_REPEAT * (t - 1)
            With wsTarget.Cells(r + 4, c)
                .Offset(0, 0) = ar(t, r, 1)
                .Offset(0, 1) = ar(t, r, 2)
                .Offset(0, 2) = ar(t, r, 3)
            End With
        Next r
    Next t
    MsgBox iCount & " rows copied using Array", vbInformation, "Finished"


问:
SDL: No available video device - prepackaged apps on Devuan
I'm trying to compile an SDL2 "Hello here's a window" application but it's not working. This is the error I get:

```<code>Could not initialize SDL: No available video device
</code>```

Here's my code:

```<code>#include <stdio.h>
#include "SDL2/SDL.h"

int greatSuccess = 1;

int main(int argc, char* argv[]) {
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) == 0) {

    // this code path is not hit, omitted

  } else {
    printf("Could not initialize SDL: %s\n", SDL_GetError());
    greatSuccess = 0;
  }
  return !greatSuccess ;
}
</code>```

The error that causes this generalizes to pre-packaged applications; mgba-sdl, a frontend to mgba based on SDL2, produces the same error:

```<code>Could not initialize video: No available video device
</code>```

I say the same, because the No available video device is (presumably) produced by SDL_GetError() in both cases.

Enumerating video devices from inside the application results in:

```<code>0: dummy
</code>```

My platform is Devuan ASCII, which is based on Debian 9/Stretch.

Here's the output from ldd ./hellowindow:

```<code>    linux-vdso.so.1
    libSDL2-2.0.so.0 => /usr/local/lib/libSDL2-2.0.so.0
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0
    librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1
    libGL.so.1 => /usr/lib/x86_64-linux-gnu/libGL.so.1
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6
    /lib64/ld-linux-x86-64.so.2
    libexpat.so.1 => /lib/x86_64-linux-gnu/libexpat.so.1
    libxcb-dri3.so.0 => /usr/lib/x86_64-linux-gnu/libxcb-dri3.so.0
    libxcb-present.so.0 => /usr/lib/x86_64-linux-gnu/libxcb-present.so.0
    libxcb-sync.so.1 => /usr/lib/x86_64-linux-gnu/libxcb-sync.so.1
    libxshmfence.so.1 => /usr/lib/x86_64-linux-gnu/libxshmfence.so.1
    libglapi.so.0 => /usr/lib/x86_64-linux-gnu/libglapi.so.0
    libXext.so.6 => /usr/lib/x86_64-linux-gnu/libXext.so.6
    libXdamage.so.1 => /usr/lib/x86_64-linux-gnu/libXdamage.so.1
    libXfixes.so.3 => /usr/lib/x86_64-linux-gnu/libXfixes.so.3
    libX11-xcb.so.1 => /usr/lib/x86_64-linux-gnu/libX11-xcb.so.1
    libX11.so.6 => /usr/lib/x86_64-linux-gnu/libX11.so.6
    libxcb.so.1 => /usr/lib/x86_64-linux-gnu/libxcb.so.1
    libxcb-glx.so.0 => /usr/lib/x86_64-linux-gnu/libxcb-glx.so.0
    libxcb-dri2.so.0 => /usr/lib/x86_64-linux-gnu/libxcb-dri2.so.0
    libXxf86vm.so.1 => /usr/lib/x86_64-linux-gnu/libXxf86vm.so.1
    libdrm.so.2 => /usr/lib/x86_64-linux-gnu/libdrm.so.2
    libXau.so.6 => /usr/lib/x86_64-linux-gnu/libXau.so.6
    libXdmcp.so.6 => /usr/lib/x86_64-linux-gnu/libXdmcp.so.6
    libbsd.so.0 => /lib/x86_64-linux-gnu/libbsd.so.0
</code>```

glxgears does work. glxinfo produces:

```<code>OpenGL vendor string: Intel Open Source Technology Center
OpenGL renderer string: Mesa DRI Mobile Intel GM45 Express Chipset
OpenGL version string: 2.1 Mesa 13.0.6
OpenGL shading language version string: 1.20
OpenGL extensions:
OpenGL ES profile version string: OpenGL ES 2.0 Mesa 13.0.6
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 1.0.16
OpenGL ES profile extensions:
</code>```

Some things I've tried:

export DISPLAY=:0 (didn't work, and it already was set, to :0.0)

SDL_VIDEODRIVER=x11 (didn't work, and it fails before this starts to make sense, see the enumeration of video drivers)

compiling with sdl2-config --static-libs instead of --cflags --libs

Perhaps SDL2 does not support OpenGL 2.1? What's going on here?

This is all rather odd to me, like a video driver issue except I have drivers that work, confirmed by glxgears and glxinfo.

答:
keltar spotted the issue in one go: I had a second, locally built install of SDL2.

I fixed the issue by removing the following files and directory:

```<code>/usr/local/bin/sdl2-config
/usr/local/include/SDL2/
/usr/local/lib/libsdl*
</code>```

The copies in /usr/local where built without graphics support and took precedence over the package manager's version, which is why it didn't work.

Body:
I'm trying to compile an SDL2 "Hello here's a window" application but it's not working. This is the error I get:

Could not initialize SDL: No available video device

Here's my code:

#include <stdio.h>
#include "SDL2/SDL.h"

int greatSuccess = 1;

int main(int argc, char* argv[]) {
  if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) == 0) {

    // this code path is not hit, omitted

  } else {
    printf("Could not initialize SDL: %s\n", SDL_GetError());
    greatSuccess = 0;
  }
  return !greatSuccess ;
}

The error that causes this generalizes to pre-packaged applications; mgba-sdl, a frontend to mgba based on SDL2, produces the same error:

Could not initialize video: No available video device

I say the same, because the No available video device is (presumably) produced by SDL_GetError() in both cases.

Enumerating video devices from inside the application results in:

0: dummy

My platform is Devuan ASCII, which is based on Debian 9/Stretch.

Here's the output from ldd ./hellowindow:

    linux-vdso.so.1
    libSDL2-2.0.so.0 => /usr/local/lib/libSDL2-2.0.so.0
    libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6
    libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2
    libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0
    librt.so.1 => /lib/x86_64-linux-gnu/librt.so.1
    libGL.so.1 => /usr/lib/x86_64-linux-gnu/libGL.so.1
    libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6
    /lib64/ld-linux-x86-64.so.2
    libexpat.so.1 => /lib/x86_64-linux-gnu/libexpat.so.1
    libxcb-dri3.so.0 => /usr/lib/x86_64-linux-gnu/libxcb-dri3.so.0
    libxcb-present.so.0 => /usr/lib/x86_64-linux-gnu/libxcb-present.so.0
    libxcb-sync.so.1 => /usr/lib/x86_64-linux-gnu/libxcb-sync.so.1
    libxshmfence.so.1 => /usr/lib/x86_64-linux-gnu/libxshmfence.so.1
    libglapi.so.0 => /usr/lib/x86_64-linux-gnu/libglapi.so.0
    libXext.so.6 => /usr/lib/x86_64-linux-gnu/libXext.so.6
    libXdamage.so.1 => /usr/lib/x86_64-linux-gnu/libXdamage.so.1
    libXfixes.so.3 => /usr/lib/x86_64-linux-gnu/libXfixes.so.3
    libX11-xcb.so.1 => /usr/lib/x86_64-linux-gnu/libX11-xcb.so.1
    libX11.so.6 => /usr/lib/x86_64-linux-gnu/libX11.so.6
    libxcb.so.1 => /usr/lib/x86_64-linux-gnu/libxcb.so.1
    libxcb-glx.so.0 => /usr/lib/x86_64-linux-gnu/libxcb-glx.so.0
    libxcb-dri2.so.0 => /usr/lib/x86_64-linux-gnu/libxcb-dri2.so.0
    libXxf86vm.so.1 => /usr/lib/x86_64-linux-gnu/libXxf86vm.so.1
    libdrm.so.2 => /usr/lib/x86_64-linux-gnu/libdrm.so.2
    libXau.so.6 => /usr/lib/x86_64-linux-gnu/libXau.so.6
    libXdmcp.so.6 => /usr/lib/x86_64-linux-gnu/libXdmcp.so.6
    libbsd.so.0 => /lib/x86_64-linux-gnu/libbsd.so.0

glxgears does work. glxinfo produces:

OpenGL vendor string: Intel Open Source Technology Center
OpenGL renderer string: Mesa DRI Mobile Intel GM45 Express Chipset
OpenGL version string: 2.1 Mesa 13.0.6
OpenGL shading language version string: 1.20
OpenGL extensions:
OpenGL ES profile version string: OpenGL ES 2.0 Mesa 13.0.6
OpenGL ES profile shading language version string: OpenGL ES GLSL ES 1.0.16
OpenGL ES profile extensions:

Some things I've tried:

export DISPLAY=:0 (didn't work, and it already was set, to :0.0)

SDL_VIDEODRIVER=x11 (didn't work, and it fails before this starts to make sense, see the enumeration of video drivers)

compiling with sdl2-config --static-libs instead of --cflags --libs

Perhaps SDL2 does not support OpenGL 2.1? What's going on here?

This is all rather odd to me, like a video driver issue except I have drivers that work, confirmed by glxgears and glxinfo.

Body:
keltar spotted the issue in one go: I had a second, locally built install of SDL2.

I fixed the issue by removing the following files and directory:

/usr/local/bin/sdl2-config
/usr/local/include/SDL2/
/usr/local/lib/libsdl*

The copies in /usr/local where built without graphics support and took precedence over the package manager's version, which is why it didn't work.


问:
Venn Diagram in React JS
I am using d3.js to create venn diagram in react js. While trying to create I use venn module. So I used below code for starting purpose

```<code> var venn = require("venn");
 venn.create([1,2]);
 console.log(venn);
</code>```

While running the problem am getting following error

```<code>**Error: **define cannot be used indirect****

// Execute the module function
**modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));**
</code>```

could anyone suggest me to resolve this issue.

答:
This worked for me:</p>

```<code>
import React, {useEffect, useState} from "react";
import * as d3 from "d3";
import * as venn from "venn.js";
export const VennDiagram = (props) => {

  const [sets, setSets] = useState([
    { sets: ["I"], size: 1000, label: "IMPORTANT: Plan" },
    { sets: ["U"], size: 200, label: "URGENT: Delegate Next" },
    { sets: ["S"], size: 1000, label: "FIT: Make Time" },
    { sets: ["I", "U"], size: 300, label: "Delegate Now" },
    { sets: ["S", "U"], size: 300, label: "Do Next" },
    { sets: ["S", "I"], size: 300, label: "Schedule" },
    { sets: ["S", "I", "U"], size: 80, label: "Do Now" }
  ]);
  useEffect(() => {

    let chart = venn.VennDiagram();
    d3.select("#venn").datum(sets).call(chart);
  }, [sets]);

  return (
    <div id="venn" style={{ textAlign: "center" }}>
    </div>
  );
};
</code>```

Title: Venn Diagram in React JS

Body:
I am using d3.js to create venn diagram in react js. While trying to create I use venn module. So I used below code for starting purpose

 var venn = require("venn");
 venn.create([1,2]);
 console.log(venn);

While running the problem am getting following error

**Error: **define cannot be used indirect****

// Execute the module function
**modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));**

could anyone suggest me to resolve this issue.

Body:
This worked for me:

import React, {useEffect, useState} from "react";
import * as d3 from "d3";
import * as venn from "venn.js";
export const VennDiagram = (props) => {

  const [sets, setSets] = useState([
    { sets: ["I"], size: 1000, label: "IMPORTANT: Plan" },
    { sets: ["U"], size: 200, label: "URGENT: Delegate Next" },
    { sets: ["S"], size: 1000, label: "FIT: Make Time" },
    { sets: ["I", "U"], size: 300, label: "Delegate Now" },
    { sets: ["S", "U"], size: 300, label: "Do Next" },
    { sets: ["S", "I"], size: 300, label: "Schedule" },
    { sets: ["S", "I", "U"], size: 80, label: "Do Now" }
  ]);
  useEffect(() => {

    let chart = venn.VennDiagram();
    d3.select("#venn").datum(sets).call(chart);
  }, [sets]);

  return (
    <div id="venn" style={{ textAlign: "center" }}>
    </div>
  );
};


问:
emacs -nw issues with cscope and terminals
Few issues with emacs in term windows. Any help is appreciated.

a. I start emacs over ssh with emacs -nw with cscope enabled. After I search for a symbol or a definition, on the cscope buffer when i press 'enter', emacs says - Buffer is read-only. Whereas the same functionality on emacs with xwindows (gtk or anything else) takes me to the file and line on edit buffer. How can I have the same functionality with 'emacs -nw'.

b. Also the arrow mark on edit/source buffer when i do next reference for symbol from cscope buffer stays on the edit buffer. How can I make it go?

c. My keys are mapped to cscope functions just like in xcscope.el. All the control keys expect Ctrl-F3 and Ctrl-F4 work. How can I enable this too.

Thanks much,

答:
terminal send different key sequences than emacs may be expecting.  you need to provide translations for the terminal type in order to get emacs to work correctly.  for example, i have this config to setup the terminal i use (the weird char is a literal "escape" char, which you can type in using "C-q <esc>":

```<code>(let ((map (if (boundp 'input-decode-map)
               input-decode-map function-key-map)))
  (define-key map (kbd "RET") [return])

  (define-key map "[OA" (kbd "<C-up>"))
  (define-key map "[OB" (kbd "<C-down>"))
  (define-key map "[OC" (kbd "<C-right>"))
  (define-key map "[OD" (kbd "<C-left>"))

  (define-key map "[A" (kbd "<C-up>"))
  (define-key map "[B" (kbd "<C-down>"))
  (define-key map "[C" (kbd "<C-right>"))
  (define-key map "[D" (kbd "<C-left>"))

  (define-key map "OA" (kbd "<M-up>"))
  (define-key map "OB" (kbd "<M-down>"))
  (define-key map "OC" (kbd "<M-right>"))
  (define-key map "OD" (kbd "<M-left>"))

  (define-key map "[OA" (kbd "<M-C-up>"))
  (define-key map "[OB" (kbd "<M-C-down>"))
  (define-key map "[OC" (kbd "<M-C-right>"))
  (define-key map "[OD" (kbd "<M-C-left>"))

  (define-key map "[[17~" (kbd "<C-f6>"))
  (define-key map "[[18~" (kbd "<C-f7>"))
  (define-key map "[[19~" (kbd "<C-f8>"))
  (define-key map "[[20~" (kbd "<C-f9>"))
  (define-key map "[[21~" (kbd "<C-f10>"))
  (define-key map "[[23~" (kbd "<C-f11>"))
  (define-key map "[[24~" (kbd "<C-f12>"))

  (define-key map "\e[1~" [home])
  (define-key map "\e[4~" [end])
  (define-key map "\e\e[1~" [M-home])
  (define-key map "\e\e[4~" [M-end])
)
</code>```

in some terminals, you can get the key code by typing "C-v" and then the desired keys.  this should output the actual keycodes that the terminal sends for the keys you pressed after the "C-v".

Body:
terminal send different key sequences than emacs may be expecting.  you need to provide translations for the terminal type in order to get emacs to work correctly.  for example, i have this config to setup the terminal i use (the weird char is a literal "escape" char, which you can type in using "C-q <esc>":

(let ((map (if (boundp 'input-decode-map)
               input-decode-map function-key-map)))
  (define-key map (kbd "RET") [return])

  (define-key map "[OA" (kbd "<C-up>"))
  (define-key map "[OB" (kbd "<C-down>"))
  (define-key map "[OC" (kbd "<C-right>"))
  (define-key map "[OD" (kbd "<C-left>"))

  (define-key map "[A" (kbd "<C-up>"))
  (define-key map "[B" (kbd "<C-down>"))
  (define-key map "[C" (kbd "<C-right>"))
  (define-key map "[D" (kbd "<C-left>"))

  (define-key map "OA" (kbd "<M-up>"))
  (define-key map "OB" (kbd "<M-down>"))
  (define-key map "OC" (kbd "<M-right>"))
  (define-key map "OD" (kbd "<M-left>"))

  (define-key map "[OA" (kbd "<M-C-up>"))
  (define-key map "[OB" (kbd "<M-C-down>"))
  (define-key map "[OC" (kbd "<M-C-right>"))
  (define-key map "[OD" (kbd "<M-C-left>"))

  (define-key map "[[17~" (kbd "<C-f6>"))
  (define-key map "[[18~" (kbd "<C-f7>"))
  (define-key map "[[19~" (kbd "<C-f8>"))
  (define-key map "[[20~" (kbd "<C-f9>"))
  (define-key map "[[21~" (kbd "<C-f10>"))
  (define-key map "[[23~" (kbd "<C-f11>"))
  (define-key map "[[24~" (kbd "<C-f12>"))

  (define-key map "\e[1~" [home])
  (define-key map "\e[4~" [end])
  (define-key map "\e\e[1~" [M-home])
  (define-key map "\e\e[4~" [M-end])
)

in some terminals, you can get the key code by typing "C-v" and then the desired keys.  this should output the actual keycodes that the terminal sends for the keys you pressed after the "C-v".