问:
black hat python chapter 7, I'm getting the error "github3.exceptions.NotFoundError:404"; can anyone see the problem here?
I've been following a book called Black Hat Python 2nd edition and, when it comes to the task in chapter 7, I'm getting errors like the titular "github3.exceptions.NotFoundError:404" i have no idea on how to fix it and looking at other questions has, unfortunately, not helped me. I'm going to put here the program in its entirety and all of the errors that i get when i run it. I hope that some of you can help me.

full program:

```<code>import base64
import github3
import importlib
import json
import sys
import random
import threading
import time
from datetime import datetime

def connect_to_github():
    with open("mytoken.txt") as f:
        token = f.read()
    user = 'Anderaxarex'
    sess = github3.login(token=token)
    return sess.repository(user, 'bhptrojan')

def get_content(dirname, module_name, repo):
    return repo.file_contents(f'{dirname}/{module_name}').content

class Trojan:
    def __init__(self, id):
        self.id = id
        self.config_file = f'{id}.json'
        self.repo = connect_to_github()
        self.data_path = f'data/{id}'

    def get_config(self):
        config_file = get_content('config', self.config_file, self.repo)
        config = json.loads(base64.b64decode(config_file))

        for task in config:
            if task['module'] not in sys.modules:
                exec("import %s" % task['module'])
        return config

    def store_result(self, data):
        message = datetime.now().isoformat()
        remotepath = f'data/{self.id}/{message}.data'
        bindata = bytes('%r' % data, 'utf-8')
        self.repo.create_file(remotepath, message, base64.b64decode(bindata))

    def module_runner(self, module):
        result = sys.modules[module].run()
        self.store_result(result)

    def run(self):
        while True:
            config = self.get_config()
            for task in config:
                thread = threading.Thread(
                    target=self.module_runner,
                    args=(task['module'],)
                )
                thread.start()
                time.sleep(random.randint(1, 10))

            time.sleep(random.randint(3*60, 3*60*60))

class GitImporter:
    def __init__(self):
        self.current_module_code=""
        self.repo = connect_to_github()

    def find_module(self, name, path=None):
        print("[||] Retrieving %s" % name)
        self.repo = connect_to_github()
        new_library = get_content('modules', f'{name}.py', self.repo)
        if new_library is not None:
            self.current_module_code = base64.b64decode(new_library)
            return self

    def load_modules(self, name):
        spec = importlib.util.spec_from_loader(name, loader=None, origin=self.repo.git_url)
        new_module = importlib.util.module_from_spec(spec)
        exec(self.current_module_code, new_module.__dict__)
        sys.modules[spec.name] = new_module
        return new_module

if __name__ == '__main__':
    sys.meta_path.append(GitImporter())
    trojan = Trojan(f'{random.randint(1000, 10000)}')
    trojan.run()
</code>```

error messages:

```<code>Traceback (most recent call last):
  File "tro.py", line 83, in <module>
    trojan.run()
  File "tro.py", line 49, in run
    config = self.get_config()
  File "tro.py", line 29, in get_config
    config_file = get_content('config', self.config_file, self.repo)
  File "tro.py", line 19, in get_content
    return repo.file_contents(f'{dirname}/{module_name}').content
  File "C:\Users\ascar\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\github3\repos\repo.py", line 1676, in file_contents
    json = self._json(self._get(url, params={"ref": ref}), 200)
  File "C:\Users\ascar\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\github3\models.py", line 153, in _json
    raise exceptions.error_for(response)
github3.exceptions.NotFoundError: 404 Not Found
</code>```

答: I don't know the book specifically, but have browsed through chapter 7 from the 1st edition. If I am correct then Anderaxarex is your username. In that case, you will need to create the repository bhptrojan on your github account.

Body:
I've been following a book called Black Hat Python 2nd edition and, when it comes to the task in chapter 7, I'm getting errors like the titular "github3.exceptions.NotFoundError:404" i have no idea on how to fix it and looking at other questions has, unfortunately, not helped me. I'm going to put here the program in its entirety and all of the errors that i get when i run it. I hope that some of you can help me.

full program:

import base64
import github3
import importlib
import json
import sys
import random
import threading
import time
from datetime import datetime

def connect_to_github():
    with open("mytoken.txt") as f:
        token = f.read()
    user = 'Anderaxarex'
    sess = github3.login(token=token)
    return sess.repository(user, 'bhptrojan')

def get_content(dirname, module_name, repo):
    return repo.file_contents(f'{dirname}/{module_name}').content

class Trojan:
    def __init__(self, id):
        self.id = id
        self.config_file = f'{id}.json'
        self.repo = connect_to_github()
        self.data_path = f'data/{id}'

    def get_config(self):
        config_file = get_content('config', self.config_file, self.repo)
        config = json.loads(base64.b64decode(config_file))

        for task in config:
            if task['module'] not in sys.modules:
                exec("import %s" % task['module'])
        return config

    def store_result(self, data):
        message = datetime.now().isoformat()
        remotepath = f'data/{self.id}/{message}.data'
        bindata = bytes('%r' % data, 'utf-8')
        self.repo.create_file(remotepath, message, base64.b64decode(bindata))

    def module_runner(self, module):
        result = sys.modules[module].run()
        self.store_result(result)

    def run(self):
        while True:
            config = self.get_config()
            for task in config:
                thread = threading.Thread(
                    target=self.module_runner,
                    args=(task['module'],)
                )
                thread.start()
                time.sleep(random.randint(1, 10))

            time.sleep(random.randint(3*60, 3*60*60))

class GitImporter:
    def __init__(self):
        self.current_module_code=""
        self.repo = connect_to_github()

    def find_module(self, name, path=None):
        print("[||] Retrieving %s" % name)
        self.repo = connect_to_github()
        new_library = get_content('modules', f'{name}.py', self.repo)
        if new_library is not None:
            self.current_module_code = base64.b64decode(new_library)
            return self

    def load_modules(self, name):
        spec = importlib.util.spec_from_loader(name, loader=None, origin=self.repo.git_url)
        new_module = importlib.util.module_from_spec(spec)
        exec(self.current_module_code, new_module.__dict__)
        sys.modules[spec.name] = new_module
        return new_module

if __name__ == '__main__':
    sys.meta_path.append(GitImporter())
    trojan = Trojan(f'{random.randint(1000, 10000)}')
    trojan.run()

error messages:

Traceback (most recent call last):
  File "tro.py", line 83, in <module>
    trojan.run()
  File "tro.py", line 49, in run
    config = self.get_config()
  File "tro.py", line 29, in get_config
    config_file = get_content('config', self.config_file, self.repo)
  File "tro.py", line 19, in get_content
    return repo.file_contents(f'{dirname}/{module_name}').content
  File "C:\Users\ascar\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\github3\repos\repo.py", line 1676, in file_contents
    json = self._json(self._get(url, params={"ref": ref}), 200)
  File "C:\Users\ascar\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\github3\models.py", line 153, in _json
    raise exceptions.error_for(response)
github3.exceptions.NotFoundError: 404 Not Found


来源: stackexchange

问:
How do I use Excel's "=SUMPRODUCT(--ISNUMBER(SEARCH..." function to exclude 'complicated compounded' results?
I am trying to validate a list of product descriptions to highlight any instances where the colour of the product has been used in its description.

I have a list of colours...

```<code>Example:
Blue
Red
Green
Yellow
Purple
etc.
</code>```

I am using the following formula to detect if one of these colours has been used:

=IF(SUMPRODUCT(--ISNUMBER(SEARCH(Table1[Colors],A1)))>0,"Cannot include a colour","")

Where Table1[Colours] contains my list of colour text strings and A1 contains my first product description.

(Dave Bruns @ ExcelJet has a great read for anyone wanting to use SUMPRODUCT/ISNUMBER/SEARCH combinations.)

If a product description contains a colour specified in my Table1[Colours] list the formula produces "Cannot include a colour" to remind the user this is not allowed.

Example:
"Garmin Forerunner 10 Running Sportswatch Green"

The first issue i am faced with is that my current formula procs when the product description contains a compound word containing a colour...

Example:
"Blackberry Z10 Smartphone"

This inaccurately invalidates the description because the string "Black" in this text is not being used to describe the colour of the product.

As the title suggests, my main issue lies with outsmarting 'complicated compound' words...

... my Table1[Colours] list does not simply contain the basic Primary, Secondary and Tertiary colours, but also more exotic ones like Coral, Fuchsia and Tan.

This causes complication when the product description contains a word like "Stand".

Why is this a problem you may be thinking? Stand contains one of my exotic colours 'Tan'

S-Tan-d

Unfortunately this also causes my formula to proc. (Annoying right?)

The solution I am looking for is an addition to my existing formula =IF(SUMPRODUCT(--ISNUMBER(SEARCH(Table1[Colors],A1)))>0,"Cannot include a colour","") which accounts for the possible occurrence of a 'complicated compound' be this by a counter list of acceptable words (e.g. Table2[Exceptions] or by wild carding the search to match the exact colour with no Prefix or Suffix (this option would have to allow for the possibility of a dual colour separated by a / e.g. "Black/Red", so wild carding with certain punctuation exceptions?)

...Its all just a bit horrible and inconvenient.

Any advice is appreciated.

Thanks, Mr. J

ContentLicense: CC BY-SA 3.0

Body:
I am trying to validate a list of product descriptions to highlight any instances where the colour of the product has been used in its description.

I have a list of colours...

Example:
Blue
Red
Green
Yellow
Purple
etc.

I am using the following formula to detect if one of these colours has been used:

=IF(SUMPRODUCT(--ISNUMBER(SEARCH(Table1[Colors],A1)))>0,"Cannot include a colour","")

Where Table1[Colours] contains my list of colour text strings and A1 contains my first product description.

(Dave Bruns @ ExcelJet has a great read for anyone wanting to use SUMPRODUCT/ISNUMBER/SEARCH combinations.)

If a product description contains a colour specified in my Table1[Colours] list the formula produces "Cannot include a colour" to remind the user this is not allowed.

Example:
"Garmin Forerunner 10 Running Sportswatch Green"

The first issue i am faced with is that my current formula procs when the product description contains a compound word containing a colour...

Example:
"Blackberry Z10 Smartphone"

This inaccurately invalidates the description because the string "Black" in this text is not being used to describe the colour of the product.

As the title suggests, my main issue lies with outsmarting 'complicated compound' words...

... my Table1[Colours] list does not simply contain the basic Primary, Secondary and Tertiary colours, but also more exotic ones like Coral, Fuchsia and Tan.

This causes complication when the product description contains a word like "Stand".

Why is this a problem you may be thinking? Stand contains one of my exotic colours 'Tan'

S-Tan-d

Unfortunately this also causes my formula to proc. (Annoying right?)

The solution I am looking for is an addition to my existing formula =IF(SUMPRODUCT(--ISNUMBER(SEARCH(Table1[Colors],A1)))>0,"Cannot include a colour","") which accounts for the possible occurrence of a 'complicated compound' be this by a counter list of acceptable words (e.g. Table2[Exceptions] or by wild carding the search to match the exact colour with no Prefix or Suffix (this option would have to allow for the possibility of a dual colour separated by a / e.g. "Black/Red", so wild carding with certain punctuation exceptions?)

...Its all just a bit horrible and inconvenient.

Any advice is appreciated.

Thanks, Mr. J

Body:
=SUMPRODUCT(  ($G$2:$G$159 >= $E$164) *  ($G$2:$G$159 <= $F$164 ) * (EXACT($E165,$F$2:$F$159)))

Better use "EXACT" instead of is number

ContentLicense: CC BY-SA 4.0


问:
convert length to point in svg (polygon) dynamically
I am doing a small assignment to find out the type of the triangle whether is equilateral, isosceles, or scalene based on the values a,b,c.

my problem is that I couldn't manage to convert the a,b,c values in order to draw the shape by using SVG (polygon) since it takes points and I have only values

function triangle(a, b, c) {
  if (a === b && a === c && b === c) return "equilateral";
  if (a === b && a === c) return "isosceles";
  else {
    return "scalene";
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <div>
        <svg className="traingle" height="400" width="400">
          <polygon points={`200 ${b}, 200 ${a}, 0 ${c}`} />
        </svg>
      </div></code>```

答:
Here is a working snippet with calculateTriangle. Please note that the side length numbers should be valid

const calculateTriangle = (a, b, c) => {
  const ax = 0;
  const ay = 0;
  const bx = ax + c;
  const by = ay;
  const cosAlpha = (a * a - b * b - c * c) / (b * c * 2);
  const alpha = Math.acos(cosAlpha);
  const cx = ax - b * cosAlpha;
  const cy = ay + b * Math.sin(alpha);
  return {ax, ay, bx, by, cx, cy};
};

const onDraw = () => {
    const a = d3.select('#side-a').node().value;
    const b = d3.select('#side-b').node().value;
    const c = d3.select('#side-c').node().value;
  const {ax, ay, bx, by, cx, cy} = calculateTriangle(parseInt(a), parseInt(b), parseInt(c));
  d3.select('polygon').attr('points', `${ax},${ay} ${bx},${by} ${cx},${cy}`)
  console.log('T: ', t);
}

d3.select('button').on('click', onDraw);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#wrapper {
  display: flex;
  flex-direction: row;
}

#container {
  font-family: Ubuntu;
  font-size: 16px;
  display: flex:
  flex-direction: column;
}

#container > div {
  display: flex;
  flex-direction: row;
  margin: 10px 0 0 20px;
}

#container > div > span {
  width: 10px;
}

#container > div > input {
  margin-left: 20px;
  width: 50px;
}

#container button {
  margin-left: 30px;
  width: 60px;
}

svg {
  border: 1px solid grey;
  margin: 10px 0 0 20px;
}</code>```

      A: <input type="number" id="side-a" value="50"/>

      B: <input type="number" id="side-b" value="40"/>

      C: <input type="number" id="side-c" value="30"/>

      <button>DRAW</button>

  <svg width="110" height="110">
    <polygon transform="translate(10,10)" />
  </svg>

```

Body:
I am doing a small assignment to find out the type of the triangle whether is equilateral, isosceles, or scalene based on the values a,b,c.

my problem is that I couldn't manage to convert the a,b,c values in order to draw the shape by using SVG (polygon) since it takes points and I have only values

function triangle(a, b, c) {
  if (a === b && a === c && b === c) return "equilateral";
  if (a === b && a === c) return "isosceles";
  else {
    return "scalene";
  }
}

        <svg className="traingle" height="400" width="400">
          <polygon points={`200 ${b}, 200 ${a}, 0 ${c}`} />
        </svg>

Body:
Here is a working snippet with calculateTriangle. Please note that the side length numbers should be valid

const calculateTriangle = (a, b, c) => {
  const ax = 0;
  const ay = 0;
  const bx = ax + c;
  const by = ay;
  const cosAlpha = (a * a - b * b - c * c) / (b * c * 2);
  const alpha = Math.acos(cosAlpha);
  const cx = ax - b * cosAlpha;
  const cy = ay + b * Math.sin(alpha);
  return {ax, ay, bx, by, cx, cy};
};

const onDraw = () => {
    const a = d3.select('#side-a').node().value;
    const b = d3.select('#side-b').node().value;
    const c = d3.select('#side-c').node().value;
  const {ax, ay, bx, by, cx, cy} = calculateTriangle(parseInt(a), parseInt(b), parseInt(c));
  d3.select('polygon').attr('points', `${ax},${ay} ${bx},${by} ${cx},${cy}`)
  console.log('T: ', t);
}

d3.select('button').on('click', onDraw);

#wrapper {
  display: flex;
  flex-direction: row;
}

#container {
  font-family: Ubuntu;
  font-size: 16px;
  display: flex:
  flex-direction: column;
}

#container > div {
  display: flex;
  flex-direction: row;
  margin: 10px 0 0 20px;
}

#container > div > span {
  width: 10px;
}

#container > div > input {
  margin-left: 20px;
  width: 50px;
}

#container button {
  margin-left: 30px;
  width: 60px;
}

svg {
  border: 1px solid grey;
  margin: 10px 0 0 20px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<div id='wrapper'>
  <div id='container'>
    <div>
      <span>A: </span><input type="number" id="side-a" value="50"/>
    </div>
    <div>
      <span>B: </span><input type="number" id="side-b" value="40"/>
    </div>
    <div>
      <span>C: </span><input type="number" id="side-c" value="30"/>
    </div>
    <div>
      <button>DRAW</button>
    </div>
  </div>
  <svg width="110" height="110">
    <polygon transform="translate(10,10)" />
  </svg>
</div>


问:
Flink - KafkaSink not writing data to kafka topic
I'm trying to read JSON events from Kafka, aggregate it on a eventId and its category and write them to a different kafka topic through flink. The program is able to read messages from kafka, but KafkaSink is not writing the data back to the other kafka topic. I'm not sure on the mistake I'm doing. Can someone please check and let me know, where I'm wrong. Here is the code I'm using.

```<code>KafkaSource<EventMessage> source = KafkaSource.<EventMessage>builder()
        .setBootstrapServers(LOCAL_KAFKA_BROKER)
        .setTopics(INPUT_KAFKA_TOPIC)
        .setGroupId(LOCAL_GROUP)
        .setStartingOffsets(OffsetsInitializer.earliest())
        .setValueOnlyDeserializer(new InputDeserializationSchema())
        .build();

WindowAssigner<Object, TimeWindow> windowAssigner = TumblingEventTimeWindows.of(WINDOW_SIZE);

DataStream<EventMessage> eventStream = env.fromSource(source, WatermarkStrategy.noWatermarks(), "Event Source");

DataStream<EventSummary> events =
eventStream
        .keyBy(eventMessage -> eventMessage.getCategory() + eventMessage.getEventId())
        .window(windowAssigner)
        .aggregate(new EventAggregator())
        .name("EventAggregator test >> ");

KafkaSink<EventSummary> sink = KafkaSink.<EventSummary>builder()
        .setBootstrapServers(LOCAL_KAFKA_BROKER)
        .setRecordSerializer(KafkaRecordSerializationSchema.builder()
                .setTopic(OUTPUT_KAFKA_TOPIC)
                .setValueSerializationSchema(new OutputSummarySerializationSchema())
                .build())
        .setDeliverGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
        .build();

events.sinkTo(sink);
</code>```

These are the POJO's I've created for input message and output.

```<code># EventMessage POJO
public class EventMessage implements Serializable {
    private Long timestamp;
    private int eventValue;
    private String eventId;
    private String category;

    public EventMessage() { }

    public EventMessage(Long timestamp, int eventValue, String eventId, String category) {
        this.timestamp = timestamp;
        this.eventValue = eventValue;
        this.eventId = eventId;
        this.category = category;
    }
    .....
}

# EventSummary POJO
public class EventSummary {

    public EventMessage eventMessage;
    public int sum;
    public int count;

    public EventSummary() { }
    ....
}
</code>```

These are the deserialization and serialization schemas I'm using.

```<code>public class InputDeserializationSchema implements DeserializationSchema<EventMessage> {

    static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public EventMessage deserialize(byte[] bytes) throws IOException {

        return objectMapper.readValue(bytes, EventMessage.class);
    }

    @Override
    public boolean isEndOfStream(EventMessage inputMessage) {
        return false;
    }

    @Override
    public TypeInformation<EventMessage> getProducedType() {
        return TypeInformation.of(EventMessage.class);
    }
}

public class OutputSummarySerializationSchema implements SerializationSchema<EventSummary> {

    static ObjectMapper objectMapper = new ObjectMapper();

    Logger logger = LoggerFactory.getLogger(OutputSummarySerializationSchema.class);

    @Override
    public byte[] serialize(EventSummary eventSummary) {
        if (objectMapper == null) {
            objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
            objectMapper = new ObjectMapper();
        }
        try {
            String json = objectMapper.writeValueAsString(eventSummary);
            return json.getBytes();
        } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
            logger.error("Failed to parse JSON", e);
        }
        return new byte[0];
    }
}
</code>```

I'm using this aggregator for aggregating the JSON messages.

```<code>public class EventAggregator implements AggregateFunction<EventMessage, EventSummary, EventSummary> {

    private static final Logger log = LoggerFactory.getLogger(EventAggregator.class);
    @Override
    public EventSummary createAccumulator() {
        return new EventSummary();
    }

    @Override
    public EventSummary add(EventMessage eventMessage, EventSummary eventSummary) {
        eventSummary.eventMessage = eventMessage;
        eventSummary.count += 1;
        eventSummary.sum += eventMessage.getEventValue();

        return eventSummary;
    }

    @Override
    public EventSummary getResult(EventSummary eventSummary) {
        return eventSummary;
    }

    @Override
    public EventSummary merge(EventSummary summary1, EventSummary summary2) {
        return new EventSummary(null,
                summary1.sum + summary2.sum,
                summary1.count + summary2.count);
    }
}
</code>```

Can someone help me on this?

Thanks in advance.

答:
In order for event time windowing to work, you must specify a proper WatermarkStrategy. Otherwise, the windows will never close, and no results will be produced.

The role that watermarks play is to mark a place in a stream, and indicate that the stream is, at that point, complete through some specific timestamp. Until receiving this indicator of stream completeness, windows continue to wait for more events to be assigned to them.

To simply the debugging the watermarks, you might switch to a PrintSink until you get the watermarking working properly. Or to simplify debugging the KafkaSink, you could switch to using processing time windows until the sink is working.

Body:
I'm trying to read JSON events from Kafka, aggregate it on a eventId and its category and write them to a different kafka topic through flink. The program is able to read messages from kafka, but KafkaSink is not writing the data back to the other kafka topic. I'm not sure on the mistake I'm doing. Can someone please check and let me know, where I'm wrong. Here is the code I'm using.

KafkaSource<EventMessage> source = KafkaSource.<EventMessage>builder()
        .setBootstrapServers(LOCAL_KAFKA_BROKER)
        .setTopics(INPUT_KAFKA_TOPIC)
        .setGroupId(LOCAL_GROUP)
        .setStartingOffsets(OffsetsInitializer.earliest())
        .setValueOnlyDeserializer(new InputDeserializationSchema())
        .build();

WindowAssigner<Object, TimeWindow> windowAssigner = TumblingEventTimeWindows.of(WINDOW_SIZE);

DataStream<EventMessage> eventStream = env.fromSource(source, WatermarkStrategy.noWatermarks(), "Event Source");

DataStream<EventSummary> events =
eventStream
        .keyBy(eventMessage -> eventMessage.getCategory() + eventMessage.getEventId())
        .window(windowAssigner)
        .aggregate(new EventAggregator())
        .name("EventAggregator test >> ");

KafkaSink<EventSummary> sink = KafkaSink.<EventSummary>builder()
        .setBootstrapServers(LOCAL_KAFKA_BROKER)
        .setRecordSerializer(KafkaRecordSerializationSchema.builder()
                .setTopic(OUTPUT_KAFKA_TOPIC)
                .setValueSerializationSchema(new OutputSummarySerializationSchema())
                .build())
        .setDeliverGuarantee(DeliveryGuarantee.AT_LEAST_ONCE)
        .build();

events.sinkTo(sink);

These are the POJO's I've created for input message and output.

# EventMessage POJO
public class EventMessage implements Serializable {
    private Long timestamp;
    private int eventValue;
    private String eventId;
    private String category;

    public EventMessage() { }

    public EventMessage(Long timestamp, int eventValue, String eventId, String category) {
        this.timestamp = timestamp;
        this.eventValue = eventValue;
        this.eventId = eventId;
        this.category = category;
    }
    .....
}

# EventSummary POJO
public class EventSummary {

    public EventMessage eventMessage;
    public int sum;
    public int count;

    public EventSummary() { }
    ....
}

These are the deserialization and serialization schemas I'm using.

public class InputDeserializationSchema implements DeserializationSchema<EventMessage> {

    static ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public EventMessage deserialize(byte[] bytes) throws IOException {

        return objectMapper.readValue(bytes, EventMessage.class);
    }

    @Override
    public boolean isEndOfStream(EventMessage inputMessage) {
        return false;
    }

    @Override
    public TypeInformation<EventMessage> getProducedType() {
        return TypeInformation.of(EventMessage.class);
    }
}

public class OutputSummarySerializationSchema implements SerializationSchema<EventSummary> {

    static ObjectMapper objectMapper = new ObjectMapper();

    Logger logger = LoggerFactory.getLogger(OutputSummarySerializationSchema.class);

    @Override
    public byte[] serialize(EventSummary eventSummary) {
        if (objectMapper == null) {
            objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
            objectMapper = new ObjectMapper();
        }
        try {
            String json = objectMapper.writeValueAsString(eventSummary);
            return json.getBytes();
        } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
            logger.error("Failed to parse JSON", e);
        }
        return new byte[0];
    }
}

I'm using this aggregator for aggregating the JSON messages.

public class EventAggregator implements AggregateFunction<EventMessage, EventSummary, EventSummary> {

    private static final Logger log = LoggerFactory.getLogger(EventAggregator.class);
    @Override
    public EventSummary createAccumulator() {
        return new EventSummary();
    }

    @Override
    public EventSummary add(EventMessage eventMessage, EventSummary eventSummary) {
        eventSummary.eventMessage = eventMessage;
        eventSummary.count += 1;
        eventSummary.sum += eventMessage.getEventValue();

        return eventSummary;
    }

    @Override
    public EventSummary getResult(EventSummary eventSummary) {
        return eventSummary;
    }

    @Override
    public EventSummary merge(EventSummary summary1, EventSummary summary2) {
        return new EventSummary(null,
                summary1.sum + summary2.sum,
                summary1.count + summary2.count);
    }
}

Can someone help me on this?

Thanks in advance.


问:
Linq Except not giving desired results in C#, datatable
I have two DataTables. I applied the Except operator as follows,
and got either unfiltered or undesired results.

```<code>resultDataTable = dtA.AsEnumerable().Except(dtB.AsEnumerable()).CopyToDataTable();
</code>```

Could anyone please kindly explain to me why Except(dtB.AsEnumerable()) is not the way to put it?

Note:
Both DataTables are plain simple with just one column.

dtA contains a dozen rows of strings.

dtB contains thousands of rows of strings.

I also tried the same syntax with another use case the set operator, Intersect. This does not work either.

resultDataTable2 =dtA.AsEnumerable().Intersect(dtB.AsEnumerable()).CopyToDataTable();

答:
Could anyone please kindly explain to me why Except(dtB.AsEnumerable()) is not the way to put it?

When you do a.Except(b) the contents of b are loaded into a hash set. A hash set is a device that doesn't accept duplicates, so it returns false when you try to add something that is already there inside it.

After b is loaded into the hash set, then a is looped over, also being added to the hash set. Anything that adds successfully (set.Add returns true because it is not already there) is returned. Anything that is already there (set.Add returns false because it was added by being in b, or appearing earlier in a) is not returned. You should note that this process also dedupes a, so 1,1,2,3 except 2,3 would return just a single 1. You've achieved "every unique thing in a that isn't in b" - but do check whether you wanted a to be deduped too

A hash set is a wonderful thing, that enables super fast lookups. To do this it relies on two methods that every object has: GetHashcode and Equals. GetHashcode converts an object into a probably-unique number. Equals makes absolutely sure an object A equals B. Hash set tracks all the hashcodes and objects it's seen before, so when you add something it first gets the hashcode of what youre trying to add.. If it never saw that hashcode before it adds the item. If you try add anything that has the same hashcode as something it saw already, it uses Equals to check whether or not it's the same as what it saw it already (sometimes hashcodes are the same for different data) and adds the item if Equals declares it to be different. This whole operation is very fast, much faster than searching object by object through all the objects it saw before.

By default any class in C# gets its implementation of GetHashcode and Equals from object. Object's versions of these methods essentially return the memory address for GetHashcode, and compare the memory addresses for Equals

This works fine for stuff that really is at the same memory address:

```<code>var p = new Person(){Name="John"};
var q = p;                         //same mem address as p
</code>```

But it doesn't work for objects that have the same data but live at different memory addresses:

```<code>var p = new Person(){Name="John"};
var q = new Person(){Name="John"}; //not same mem address as p
</code>```

If you define two people as being equal if they have the same name, and you want C# to consider them equal in the same way, you have to instruct C# to compare the names, not the memory addresses.

A DataRow is like Person above: just because it has the same data as another DataRow, doesn't mean it's the same row in C#'s opinion. Further, because a single DataRow cannot belong to two datatables, it's certain that the "John" in row 1 of dtA, is a different object to the "John" in row 1 of dtB..

By defaul Equals returns false for these two data rows, so Except will never consider them equal and remove dtA's John because of the presence of John in dtB..

..unless you provide an alternative comparison strategy that overrides C#s default opinion of equality. That might look like:

provide a comparer, like Kalpesh's answer, typos on the class name aside),

override Equals/GetHashcode for the datarows so they work off column data, not memory addresses,

or use some other thing that does already have Equals and GetHashcode that work off data rather than memory addresses

As these are just datatables of a single column full of strings they're notionally not much more than an array of string. If we make them into an array of strings, when we do a.Except(b) we will be comparing strings. By default C#s opinion of whether one string equals another is based on the data content of the string rather than the memory address it lives at1, so you can either use string arrays/lists to start with or convert your dtA/B to a string array:

```<code>var arrA = dtA.Rows.Cast<DataRow>().Select(r => r[0] as string).ToArray();
var arrB = dtB.Rows.Cast<DataRow>().Select(r => r[0] as string).ToArray();
var result = arra.Except(arrB);
</code>```

Techncially we don't even need to call ToArray()..

If you really need the result to be a datatable, make one and add all the strings to it:

```<code>var resultDt = new DataTable();
resultDt.Columns.Add("x");
foreach(var s in result)
  resultDt.Rows.Add(s);
</code>```

1: we'll ignore interning for now

Body:
I have two DataTables. I applied the Except operator as follows,
and got either unfiltered or undesired results.

resultDataTable = dtA.AsEnumerable().Except(dtB.AsEnumerable()).CopyToDataTable();

Could anyone please kindly explain to me why Except(dtB.AsEnumerable()) is not the way to put it?

Note:
Both DataTables are plain simple with just one column.

dtA contains a dozen rows of strings.

dtB contains thousands of rows of strings.

I also tried the same syntax with another use case the set operator, Intersect. This does not work either.

resultDataTable2 =dtA.AsEnumerable().Intersect(dtB.AsEnumerable()).CopyToDataTable();

Body:
Could anyone please kindly explain to me why Except(dtB.AsEnumerable()) is not the way to put it?

When you do a.Except(b) the contents of b are loaded into a hash set. A hash set is a device that doesn't accept duplicates, so it returns false when you try to add something that is already there inside it.

After b is loaded into the hash set, then a is looped over, also being added to the hash set. Anything that adds successfully (set.Add returns true because it is not already there) is returned. Anything that is already there (set.Add returns false because it was added by being in b, or appearing earlier in a) is not returned. You should note that this process also dedupes a, so 1,1,2,3 except 2,3 would return just a single 1. You've achieved "every unique thing in a that isn't in b" - but do check whether you wanted a to be deduped too

A hash set is a wonderful thing, that enables super fast lookups. To do this it relies on two methods that every object has: GetHashcode and Equals. GetHashcode converts an object into a probably-unique number. Equals makes absolutely sure an object A equals B. Hash set tracks all the hashcodes and objects it's seen before, so when you add something it first gets the hashcode of what youre trying to add.. If it never saw that hashcode before it adds the item. If you try add anything that has the same hashcode as something it saw already, it uses Equals to check whether or not it's the same as what it saw it already (sometimes hashcodes are the same for different data) and adds the item if Equals declares it to be different. This whole operation is very fast, much faster than searching object by object through all the objects it saw before.

By default any class in C# gets its implementation of GetHashcode and Equals from object. Object's versions of these methods essentially return the memory address for GetHashcode, and compare the memory addresses for Equals

This works fine for stuff that really is at the same memory address:

var p = new Person(){Name="John"};
var q = p;                         //same mem address as p

But it doesn't work for objects that have the same data but live at different memory addresses:

var p = new Person(){Name="John"};
var q = new Person(){Name="John"}; //not same mem address as p

If you define two people as being equal if they have the same name, and you want C# to consider them equal in the same way, you have to instruct C# to compare the names, not the memory addresses.

A DataRow is like Person above: just because it has the same data as another DataRow, doesn't mean it's the same row in C#'s opinion. Further, because a single DataRow cannot belong to two datatables, it's certain that the "John" in row 1 of dtA, is a different object to the "John" in row 1 of dtB..

By defaul Equals returns false for these two data rows, so Except will never consider them equal and remove dtA's John because of the presence of John in dtB..

..unless you provide an alternative comparison strategy that overrides C#s default opinion of equality. That might look like:

provide a comparer, like Kalpesh's answer, typos on the class name aside),

override Equals/GetHashcode for the datarows so they work off column data, not memory addresses,

or use some other thing that does already have Equals and GetHashcode that work off data rather than memory addresses

As these are just datatables of a single column full of strings they're notionally not much more than an array of string. If we make them into an array of strings, when we do a.Except(b) we will be comparing strings. By default C#s opinion of whether one string equals another is based on the data content of the string rather than the memory address it lives at1, so you can either use string arrays/lists to start with or convert your dtA/B to a string array:

var arrA = dtA.Rows.Cast<DataRow>().Select(r => r[0] as string).ToArray();
var arrB = dtB.Rows.Cast<DataRow>().Select(r => r[0] as string).ToArray();
var result = arra.Except(arrB);

Techncially we don't even need to call ToArray()..

If you really need the result to be a datatable, make one and add all the strings to it:

var resultDt = new DataTable();
resultDt.Columns.Add("x");
foreach(var s in result)
  resultDt.Rows.Add(s);

1: we'll ignore interning for now


问:
Print one element of a Set in Swift
I have a set like this:

```<code>var someItems: Set = [7,3,8]
</code>```

And I want to print out only the  the number 7 of the set above.

How can I do this?

答:
You can use this extension to refer to the set member by index, so someItems[0] for example.</p>
```<code>extension Set {

var length: Int {
    return count
}

subscript (i: Int) -> Set {
    return self[i ..< i + 1]
}

func substring(fromIndex: Int) -> Set {
    return self[Swift.min(fromIndex, length) ..< length]
}

func substring(toIndex: Int) -> Set {
    return self[0 ..< Swift.max(0, toIndex)]
}

subscript (r: Range<Int>) -> Set {
    let range = Range(uncheckedBounds: (lower: Swift.max(0, Swift.min(length, r.lowerBound)),
                                        upper: Swift.min(length, Swift.max(0, r.upperBound))))
    let start = index(startIndex, offsetBy: range.lowerBound)
    let end = index(start, offsetBy: range.upperBound - range.lowerBound)
    return Set(self[start ..< end])
}
}
</code>```

Title: Print one element of a Set in Swift

Body:
I have a set like this:

var someItems: Set = [7,3,8]

And I want to print out only the  the number 7 of the set above.

How can I do this?

Body:
You can use this extension to refer to the set member by index, so someItems[0] for example.

extension Set {

var length: Int {
    return count
}

subscript (i: Int) -> Set {
    return self[i ..< i + 1]
}

func substring(fromIndex: Int) -> Set {
    return self[Swift.min(fromIndex, length) ..< length]
}

func substring(toIndex: Int) -> Set {
    return self[0 ..< Swift.max(0, toIndex)]
}

subscript (r: Range<Int>) -> Set {
    let range = Range(uncheckedBounds: (lower: Swift.max(0, Swift.min(length, r.lowerBound)),
                                        upper: Swift.min(length, Swift.max(0, r.upperBound))))
    let start = index(startIndex, offsetBy: range.lowerBound)
    let end = index(start, offsetBy: range.upperBound - range.lowerBound)
    return Set(self[start ..< end])
}
}


问:
Problem with custom vertical UISlider
I'm trying to implement vertical slider with no thumb, that reacts to touches on it's track. I have subclassed UISlider and everything goes fine in horizontal slider, but when I'm transforming slider to vertical there is wierd stuff with coordinates going on. May be there is other way to implement this? Please, give me right direction, thanks!

I'm using this code for slider now:

```<code>@implementation MMTouchSlider

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self];

    self.value = self.minimumValue + (self.maximumValue - self.minimumValue) * (touchLocation.x / self.frame.size.width);

    [super touchesBegan:touches withEvent:event];
}

- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value {

    CGRect thumbRect = [super thumbRectForBounds:bounds trackRect:rect value:value];
    return thumbRect;
}

@end
</code>```

答:
It's easy to make a vertical slider - just use 270 degree rotation!</p>

```<code>UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(100, 100, 200, 10)];
float angleInDegrees = 270;
float angleInRadians = angleInDegrees * (M_PI/180);
slider.transform = CGAffineTransformMakeRotation(angleInRadians);
[self.view addSubView:slider];
</code>```

Title: Problem with custom vertical UISlider

Body:
I'm trying to implement vertical slider with no thumb, that reacts to touches on it's track. I have subclassed UISlider and everything goes fine in horizontal slider, but when I'm transforming slider to vertical there is wierd stuff with coordinates going on. May be there is other way to implement this? Please, give me right direction, thanks!

I'm using this code for slider now:

@implementation MMTouchSlider

-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

    UITouch *touch = [[event allTouches] anyObject];
    CGPoint touchLocation = [touch locationInView:self];

    self.value = self.minimumValue + (self.maximumValue - self.minimumValue) * (touchLocation.x / self.frame.size.width);

    [super touchesBegan:touches withEvent:event];
}

- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value {

    CGRect thumbRect = [super thumbRectForBounds:bounds trackRect:rect value:value];
    return thumbRect;
}

@end

Body:
It's easy to make a vertical slider - just use 270 degree rotation!

UISlider *slider = [[UISlider alloc] initWithFrame:CGRectMake(100, 100, 200, 10)];
float angleInDegrees = 270;
float angleInRadians = angleInDegrees * (M_PI/180);
slider.transform = CGAffineTransformMakeRotation(angleInRadians);
[self.view addSubView:slider];


问:
AzureStorage Blob Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature
I'm trying to upload a image in Windows Azure Blob and I'm geting the following error which I can't handle.

Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

The error occurs when I try to create a container.

container.CreateIfNotExists()
```
<p>Here is my code</p>
<pre class="lang-cs prettyprint-override"><code>try
{
    Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve a reference to a container.
    CloudBlobContainer container = blobClient.GetContainerReference("samples");

    // Create the container if it doesn't already exist.
    // here is the error
    if (container.CreateIfNotExists())
    {
        container.SetPermissions(
            new BlobContainerPermissions
            {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });
    }

    CloudBlockBlob blockBlob = container.GetBlockBlobReference("Image1");
    using (var fileStream = System.IO.File.OpenRead(@"Path"))
    {
        blockBlob.UploadFromStream(fileStream);
    }
}
catch (StorageException ex1)
{
    throw ex1;
}
</code>```

I have tried a lot of options in my code but still getting the error.

答:
To form your auth header for blob storage, you need to use sdk or refer to this document, and the error is usually cause by the SAS token validation error.

I will suggest you to print your SAS token or catch the header to analyze if you miss anything. And I share my example(upload) for SAS token and auth header generation(shell script) for your reference. You can check this link if you want more details.

```<code>generatesig() {
#######
# From: https://learn.microsoft.com/en-us/rest/api/storageservices/create-account-sas?redirectedfrom=MSDN
#
# StringToSign = signedPermissions + "\n" +
#                signedStart + "\n" +
#                signedExpiry + "\n" +
#                canonicalizedResource + "\n" +
#                signedIdentifier + "\n" +
#                signedIP + "\n" +
#                signedProtocol + "\n" +
#                signedVersion + "\n" +
#                signedResource + "\n"
#                signedSnapshotTime + "\n" +
#                rscc + "\n" +
#                rscd + "\n" +
#                rsce + "\n" +
#                rscl + "\n" +
#                rsct
    local ST=$(TZ=GMT date -u +"%Y-%m-%dT%H:%M:%SZ")
    local SE=$(TZ=GMT date -u +"%Y-%m-%dT%H:%M:%SZ" -d "next day")
    local canonicalizedResource="/blob/${AZURE_STORAGE_ACCOUNT}/${AZURE_CONTAINER_NAME}/${FILE_NAME}"
    # StringToSign="${AZURE_STORAGE_ACCOUNT}\nr\nb\no\n${ST}\n${SE}\n\nhttps\n2020-08-04"
    # decoded_hex_key="$(echo -n $AZURE_ACCESS_KEY | base64 -d -w0 | xxd -p -c256)"
    # sig=$(printf  "$StringToSign" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$decoded_hex_key" -binary | base64 -w0)

local StringToSign="r\n${ST}\n${SE}\n${canonicalizedResource}\n\n\nhttps\n2020-08-04\nb\n\n\n\n\n\n"
echo ${StringToSign}
local decoded_hex_key="$(echo -n $AZURE_ACCESS_KEY | base64 -d -w0 | xxd -p -c256)"
local sig=$(printf  "$StringToSign" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$decoded_hex_key" -binary | base64 -w0)

}

local request_date=$(TZ=GMT date "+%a, %d %h %Y %H:%M:%S %Z")
local storage_service_version="2020-10-02"

# HTTP Request headers
local x_ms_date_h="x-ms-date:$request_date"
local x_ms_version_h="x-ms-version:$storage_service_version"
local signature=$(generatesig)
local authorization_header="Authorization: SharedKey $AZURE_STORAGE_ACCOUNT:$signature"

curl -X ${HTTP_METHOD} \
        -o /dev/null -w '%{http_code}' \
        -H "$x_ms_date_h" \
        -H "$x_ms_version_h" \
        -H "$authorization_header" \
        -H "Content-Length: 0" \
        ${REQUEST_URL}
</code>```

Body:
I'm trying to upload a image in Windows Azure Blob and I'm geting the following error which I can't handle.

Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.

The error occurs when I try to create a container.

container.CreateIfNotExists()

Here is my code

try
{
    Microsoft.WindowsAzure.Storage.CloudStorageAccount storageAccount = Microsoft.WindowsAzure.Storage.CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"]);
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

    // Retrieve a reference to a container.
    CloudBlobContainer container = blobClient.GetContainerReference("samples");

    // Create the container if it doesn't already exist.
    // here is the error
    if (container.CreateIfNotExists())
    {
        container.SetPermissions(
            new BlobContainerPermissions
            {
                PublicAccess = BlobContainerPublicAccessType.Blob
            });
    }

    CloudBlockBlob blockBlob = container.GetBlockBlobReference("Image1");
    using (var fileStream = System.IO.File.OpenRead(@"Path"))
    {
        blockBlob.UploadFromStream(fileStream);
    }
}
catch (StorageException ex1)
{
    throw ex1;
}

I have tried a lot of options in my code but still getting the error.

Body:
To form your auth header for blob storage, you need to use sdk or refer to this document, and the error is usually cause by the SAS token validation error.

I will suggest you to print your SAS token or catch the header to analyze if you miss anything. And I share my example(upload) for SAS token and auth header generation(shell script) for your reference. You can check this link if you want more details.

generatesig() {
#######
# From: https://learn.microsoft.com/en-us/rest/api/storageservices/create-account-sas?redirectedfrom=MSDN
#
# StringToSign = signedPermissions + "\n" +
#                signedStart + "\n" +
#                signedExpiry + "\n" +
#                canonicalizedResource + "\n" +
#                signedIdentifier + "\n" +
#                signedIP + "\n" +
#                signedProtocol + "\n" +
#                signedVersion + "\n" +
#                signedResource + "\n"
#                signedSnapshotTime + "\n" +
#                rscc + "\n" +
#                rscd + "\n" +
#                rsce + "\n" +
#                rscl + "\n" +
#                rsct
    local ST=$(TZ=GMT date -u +"%Y-%m-%dT%H:%M:%SZ")
    local SE=$(TZ=GMT date -u +"%Y-%m-%dT%H:%M:%SZ" -d "next day")
    local canonicalizedResource="/blob/${AZURE_STORAGE_ACCOUNT}/${AZURE_CONTAINER_NAME}/${FILE_NAME}"
    # StringToSign="${AZURE_STORAGE_ACCOUNT}\nr\nb\no\n${ST}\n${SE}\n\nhttps\n2020-08-04"
    # decoded_hex_key="$(echo -n $AZURE_ACCESS_KEY | base64 -d -w0 | xxd -p -c256)"
    # sig=$(printf  "$StringToSign" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$decoded_hex_key" -binary | base64 -w0)

local StringToSign="r\n${ST}\n${SE}\n${canonicalizedResource}\n\n\nhttps\n2020-08-04\nb\n\n\n\n\n\n"
echo ${StringToSign}
local decoded_hex_key="$(echo -n $AZURE_ACCESS_KEY | base64 -d -w0 | xxd -p -c256)"
local sig=$(printf  "$StringToSign" | openssl dgst -sha256 -mac HMAC -macopt "hexkey:$decoded_hex_key" -binary | base64 -w0)

}

local request_date=$(TZ=GMT date "+%a, %d %h %Y %H:%M:%S %Z")
local storage_service_version="2020-10-02"

# HTTP Request headers
local x_ms_date_h="x-ms-date:$request_date"
local x_ms_version_h="x-ms-version:$storage_service_version"
local signature=$(generatesig)
local authorization_header="Authorization: SharedKey $AZURE_STORAGE_ACCOUNT:$signature"

curl -X ${HTTP_METHOD} \
        -o /dev/null -w '%{http_code}' \
        -H "$x_ms_date_h" \
        -H "$x_ms_version_h" \
        -H "$authorization_header" \
        -H "Content-Length: 0" \
        ${REQUEST_URL}


问:
Changing state (visibility) of nested td
I would like to change the visibility of the td with class="tempCLS". The structure is shown in the image below with html code.

In the css file I have tried doing .tempCls {visibility : hidden; }

I have also tried doing: .tbl > thead > tr > .tempCls {... }

Thanks for any help

答:
You need to know the difference between display:none and visibility:hidden

visibility:hidden hides the element, but it still takes up space in the layout. e.g. `

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
.tmpCls{
    visibility:hidden;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>
<body>

<h2>HTML Table</h2>

<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td class="tmpCls">Maria Anders</td>
    <td class="tmpCls">Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td class="tmpCls">Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td class="tmpCls">Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>

</body>
</html></code>```

`

display:none removes the element completely from the document. It does not take up any space but the code exist in source code and can be shown any time by removing the property.

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
.tmpCls{
    display:none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
</head>
<body>

<h2>HTML Table</h2>

<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td class="tmpCls">Maria Anders</td>
    <td class="tmpCls">Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td class="tmpCls">Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td class="tmpCls">Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>

</body>
</html></code>```

As for your concern about  being nested element, it does not matter or should not effect the css of element via class. Unless you have styled the element somewhere else. The hierarchy of importance of style is as follows

external css(external file with .css extension) => internal css(css style in

Body:
You need to know the difference between display:none and visibility:hidden

visibility:hidden hides the element, but it still takes up space in the layout. e.g. `

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
.tmpCls{
    visibility:hidden;
}

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<h2>HTML Table</h2>

<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td class="tmpCls">Maria Anders</td>
    <td class="tmpCls">Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td class="tmpCls">Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td class="tmpCls">Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>

</body>
</html>

`

display:none removes the element completely from the document. It does not take up any space but the code exist in source code and can be shown any time by removing the property.

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
.tmpCls{
    display:none;
}

<!DOCTYPE html>
<html>
<head>
</head>
<body>

<h2>HTML Table</h2>

<table>
  <tr>
    <th>Company</th>
    <th>Contact</th>
    <th>Country</th>
  </tr>
  <tr>
    <td>Alfreds Futterkiste</td>
    <td class="tmpCls">Maria Anders</td>
    <td class="tmpCls">Germany</td>
  </tr>
  <tr>
    <td>Centro comercial Moctezuma</td>
    <td class="tmpCls">Francisco Chang</td>
    <td>Mexico</td>
  </tr>
  <tr>
    <td class="tmpCls">Ernst Handel</td>
    <td>Roland Mendel</td>
    <td>Austria</td>
  </tr>
  <tr>
    <td>Island Trading</td>
    <td>Helen Bennett</td>
    <td>UK</td>
  </tr>
  <tr>
    <td>Laughing Bacchus Winecellars</td>
    <td>Yoshi Tannamuri</td>
    <td>Canada</td>
  </tr>
  <tr>
    <td>Magazzini Alimentari Riuniti</td>
    <td>Giovanni Rovelli</td>
    <td>Italy</td>
  </tr>
</table>

</body>
</html>

As for your concern about <td> being nested element, it does not matter or should not effect the css of element via class. Unless you have styled the element somewhere else. The hierarchy of importance of style is as follows

external css(external file with .css extension) => internal css(css style in <style> inside the same file) => inline css(css in style attribute within html tag) => !important


问:
How do I replace a string in Powershell with a Multi-Line String?
I am trying to create a report in a rich text format in powershell. I have a space for a list of templates, denoted by the text %TEMPLATES%, which I am trying to replace with a list of items in a directory. However, whilst I can add newlines to the list of items to separate them (and this prints OK in the console window) when I replace them in the rtf document the newlines are not present and the items are all joined with no spacing. I can't figure out why this -replace wouldn't work. See the example code below:

```<code>$statusRecordTemplate = 'StatusRecord.rtf'

$templates = (Get-ChildItem $templatesPath) | Join-String -Separator "`r`n"

$content = Get-Content $statusRecordTemplate -Raw

$content = $content -replace '%TEMPLATES%' , $templates

Set-Content  -Path 'C:\temp\testout.rtf' -Value $content
</code>```

答:
Newlines in RTF are not significant. You have to use the paragraph tag (\par) instead.

```<code>$templates = (Get-ChildItem $templatesPath) | Join-String -Separator '\par '
</code>```

Make sure to include a space after the tag, as in my sample. This is necessary when a tag is followed by literal text.

Additionally you have to escape control characters in the literal text and properly encode any non-ASCII characters. See this Q&A for further information.

Body:
I am trying to create a report in a rich text format in powershell. I have a space for a list of templates, denoted by the text %TEMPLATES%, which I am trying to replace with a list of items in a directory. However, whilst I can add newlines to the list of items to separate them (and this prints OK in the console window) when I replace them in the rtf document the newlines are not present and the items are all joined with no spacing. I can't figure out why this -replace wouldn't work. See the example code below:

$statusRecordTemplate = 'StatusRecord.rtf'

$templates = (Get-ChildItem $templatesPath) | Join-String -Separator "`r`n"

$content = Get-Content $statusRecordTemplate -Raw

$content = $content -replace '%TEMPLATES%' , $templates

Set-Content  -Path 'C:\temp\testout.rtf' -Value $content

Body:
Newlines in RTF are not significant. You have to use the paragraph tag (\par) instead.

$templates = (Get-ChildItem $templatesPath) | Join-String -Separator '\par '

Make sure to include a space after the tag, as in my sample. This is necessary when a tag is followed by literal text.

Additionally you have to escape control characters in the literal text and properly encode any non-ASCII characters. See this Q&A for further information.


问:
getting binary format for displaying image in datagridview
i am currently facing some problem retrieving image for display on a datagridview control.
The Image data type in the database  is blob.
 I am using mysql as a database for retrieving the image . may i ask if it is possible to just retrieve a image data of this format and display in the gridview? or do i need to store the image in a image folder for retrieval?

I am using winforms application

答: Storing it in the local folder shall help you if you wish to reload it again later provided the DB isnt modified. Other wise i dont see any benefits here. Some times DB access is faster.</p>


问:
Represent Pandas DataFrame Date Column in milliseconds
NewB here.

I am reading a .csv file that contains Date,Open,High,Low,Close .... etc from Yahoo Finance, into a DataFrame.

Am trying to plot this data into a chart using HighCharts.  My initial reading and some samples about HighCharts seem to explain that to plot a StockChart, it needs date values in MilliSeconds.  And it definitely does make sense as HighChart is designed for such.

Now in my .csv i have the Date as 'YYYY-MM-DD' format, i am trying to convert this into milliseconds.

a simple code

```<code>from datetime import datetime
dt=datetime.strptime('2022-01-22','%Y-%m-%d')
print(dt)
millisec = dt*1000
print(millisec)
</code>```
```<code>[OutPut]
2022-01-22 00:00:00
1642798800000.0
</code>```

now if I try this with Pandas am not abt to figure out how to ....  I read the documentation but not sure my situation is address in there.

https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html

https://pandas.pydata.org/docs/reference/api/pandas.Timestamp.html

This is how my code looks like and the following Error:

```<code>import pandas as pd
# reading csv file into dataframe
df = pd.read_csv('stock.csv')
# checking column data types
print(df.dtypes)
# creating new column to store TimeStamp  This is where i get the error
df['TimeStamped'] = pd.Timestamp(df['Date'],unit='ms')
</code>```
```<code>[OutPut]
Date    object
Open    float64
High    float64
Low     float64
Close   float64

TypeError: Cannot convert input [0    2019-12-31
</code>```

Assuming that the Date column is Object, I did a conversion

df[Date] = pd.to_datetime(df[Date],yearfirst=True,format='%Y-%m-%d')

Its still the same error.

Appreciate any help to Convert Date to milliseconds.

Thank You,

答:
Thank You @MrFuppes

```<code>import pandas as pd
import numpy as np

# reading csv file into dataframe
df = pd.read_csv('stock.csv')

# replacing [Date] Column
df['Date'] = pd.to_datetime(df['Date']).astype(np.int64)/1e6
</code>```

astype()

a bit more clarification for those who do not know ....
Python astype() method enables us to set or convert the data type of an existing data column in a dataset or a data frame. By this, we can change or transform the type of the data values or single or multiple columns to altogether another form using astype() function

and finally 1e6, i had no idea about this till i looked for it

1e6

Python takes the number to the left of the e and multiplies it by 10 raised to the power of the number after the e . So 1e6 is equivalent to 1×10⁶.

Once again thank you to @MrFuppes.

Body:
NewB here.

I am reading a .csv file that contains Date,Open,High,Low,Close .... etc from Yahoo Finance, into a DataFrame.

Am trying to plot this data into a chart using HighCharts.  My initial reading and some samples about HighCharts seem to explain that to plot a StockChart, it needs date values in MilliSeconds.  And it definitely does make sense as HighChart is designed for such.

Now in my .csv i have the Date as 'YYYY-MM-DD' format, i am trying to convert this into milliseconds.

a simple code

from datetime import datetime
dt=datetime.strptime('2022-01-22','%Y-%m-%d')
print(dt)
millisec = dt*1000
print(millisec)

[OutPut]
2022-01-22 00:00:00
1642798800000.0

now if I try this with Pandas am not abt to figure out how to ....  I read the documentation but not sure my situation is address in there.

https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html

https://pandas.pydata.org/docs/reference/api/pandas.Timestamp.html

This is how my code looks like and the following Error:

import pandas as pd
# reading csv file into dataframe
df = pd.read_csv('stock.csv')
# checking column data types
print(df.dtypes)
# creating new column to store TimeStamp  This is where i get the error
df['TimeStamped'] = pd.Timestamp(df['Date'],unit='ms')

[OutPut]
Date    object
Open    float64
High    float64
Low     float64
Close   float64

TypeError: Cannot convert input [0    2019-12-31

Assuming that the Date column is Object, I did a conversion

df[Date] = pd.to_datetime(df[Date],yearfirst=True,format='%Y-%m-%d')

Its still the same error.

Appreciate any help to Convert Date to milliseconds.

Thank You,

Body:
Thank You @MrFuppes

import pandas as pd
import numpy as np

# reading csv file into dataframe
df = pd.read_csv('stock.csv')

# replacing [Date] Column
df['Date'] = pd.to_datetime(df['Date']).astype(np.int64)/1e6

astype()

a bit more clarification for those who do not know ....
Python astype() method enables us to set or convert the data type of an existing data column in a dataset or a data frame. By this, we can change or transform the type of the data values or single or multiple columns to altogether another form using astype() function

and finally 1e6, i had no idea about this till i looked for it

1e6

Python takes the number to the left of the e and multiplies it by 10 raised to the power of the number after the e . So 1e6 is equivalent to 1×10⁶.

Once again thank you to @MrFuppes.


问:
Deciding function
I am a beginner in sql.

I need confirmation on whether i am choosing the right function.

I am writing a query where i want to list the purchaser id's of the purchasers that have the most number of ticket purchases.
Would this be done through COUNT(*) and MAX ?

答:
Yes, you would do this by GROUP BY the purchaser's id and then ORDER BY the COUNT(*) of the rows in DESCending order and then, from Oracle 12c, can use FETCH FIRST ROW WITH TIES to get those with the greatest number of purchases.

You do not need to use MAX (although I'm sure there are variants of the query where you could use it).

Since this appears to be a homework question, I'll leave creating the entire query to you.

Title: Deciding function


问:
Import multiple Spreadsheets into 1 Sheet using AppScript
I have a script that imports data from different google sheets into one sheet, it works perfectly except the fact that every time when I'm running the script the imported data starts further down in the sheet. What do I need to change in the script that every time i start the script it will push the data starting the first row of the sheet?</p>
```<code>function getData() {
  get_IDs=["1pkcy4jx14odSN-Ir2Nqai89_0dJc7RiLapWxRWIURj4","1J8_cZsjEa9c8vktPBvqGvcdwUBAVkWT3NSdTnXp6tMk"];

  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var copySheet =ss.getSheetByName("Sheet3");
  copySheet.getRange('A1:Z').clear();

  for(z=0;z<get_IDs.length;z++)
  {

  var ss1=SpreadsheetApp.openById(get_IDs[z]);
  var sheets =ss1.getSheetByName("Export Department");
  var sheetsRange = sheets.getDataRange();
  var sheetsValues = sheetsRange.getValues();

  for(var y = 1;y<sheetsValues.length;y++)
  {
    copySheet.appendRow(sheetsValues[y]);
  }

  }

}```
</code>```

答:
Use setValues() instead of appendRow() and increment a counter by the number of rows on each import:

```<code>function getData() {
  get_IDs = ["1pkcy4jx14odSN-Ir2Nqai89_0dJc7RiLapWxRWIURj4", "1J8_cZsjEa9c8vktPBvqGvcdwUBAVkWT3NSdTnXp6tMk"]

  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var copySheet = ss.getSheetByName("Sheet3")
  copySheet.getRange('A1:Z').clear()

  let pasteRow = 1

  for (z = 0; z < get_IDs.length; z++) {
    var ss1 = SpreadsheetApp.openById(get_IDs[z])
    var sheets = ss1.getSheetByName("Export Department")
    var sheetsRange = sheets.getDataRange()
    var sheetsValues = sheetsRange.getValues()

    sheetsValues.splice(0, 1)

    copySheet.getRange(pasteRow, 1, sheetsValues.length, sheetsValues[0].length).setValues(sheetsValues)
    pasteRow += sheetsValues.length
  }

}
</code>```

Body:
I have a script that imports data from different google sheets into one sheet, it works perfectly except the fact that every time when I'm running the script the imported data starts further down in the sheet. What do I need to change in the script that every time i start the script it will push the data starting the first row of the sheet?

function getData() {
  get_IDs=["1pkcy4jx14odSN-Ir2Nqai89_0dJc7RiLapWxRWIURj4","1J8_cZsjEa9c8vktPBvqGvcdwUBAVkWT3NSdTnXp6tMk"];

  var ss=SpreadsheetApp.getActiveSpreadsheet();
  var copySheet =ss.getSheetByName("Sheet3");
  copySheet.getRange('A1:Z').clear();

  for(z=0;z<get_IDs.length;z++)
  {

  var ss1=SpreadsheetApp.openById(get_IDs[z]);
  var sheets =ss1.getSheetByName("Export Department");
  var sheetsRange = sheets.getDataRange();
  var sheetsValues = sheetsRange.getValues();

  for(var y = 1;y<sheetsValues.length;y++)
  {
    copySheet.appendRow(sheetsValues[y]);
  }

  }

}```

Body:
Use setValues() instead of appendRow() and increment a counter by the number of rows on each import:

function getData() {
  get_IDs = ["1pkcy4jx14odSN-Ir2Nqai89_0dJc7RiLapWxRWIURj4", "1J8_cZsjEa9c8vktPBvqGvcdwUBAVkWT3NSdTnXp6tMk"]

  var ss = SpreadsheetApp.getActiveSpreadsheet()
  var copySheet = ss.getSheetByName("Sheet3")
  copySheet.getRange('A1:Z').clear()

  let pasteRow = 1

  for (z = 0; z < get_IDs.length; z++) {
    var ss1 = SpreadsheetApp.openById(get_IDs[z])
    var sheets = ss1.getSheetByName("Export Department")
    var sheetsRange = sheets.getDataRange()
    var sheetsValues = sheetsRange.getValues()

    sheetsValues.splice(0, 1)

    copySheet.getRange(pasteRow, 1, sheetsValues.length, sheetsValues[0].length).setValues(sheetsValues)
    pasteRow += sheetsValues.length
  }

}


问:
As seen in the image, create two responsive DIVs with space between them

I'm working on a codewell challenge and I'm stuck on this portion. I can't make an even space between them, and the images are overlapping.

.website {
  display: flex;
  justify-content: space-between;
}

.arrow {
  display: inline-block;
  width: 1rem;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="website">
  <div class="spense">
    <img id="spense" src="./Assets/Spense.png" alt="spense">
    <h3>Spense.com<img class="arrow" src="./Assets/noun-arrow-2841221-svg.png" alt="arrow-icon"></h3>
    Rethinking the way writers get paid, an open resource platform <br> design to help writers focus more on writing, and less on <br> when and how they'll get paid, Projects in collaboration with <br> Codewell.cc
  </div>
  <div class="yelp">
    <img id="yelp" src="./Assets/YelpCamp.png" alt="YelpCamp">
    <h3>YelpCamp.com<img class="arrow" src="./Assets/noun-arrow-2841221-svg.png" alt="arrow-icon"></h3>
    Allowing backpack travelers to perfectly plan their trip <br> through an open-source platform similar to TripAdvisor. With <br>over 1m MAU, YelpCamp has been the crowd's favorite in <br>2021.
  </div>
</div></code>```

答:
you can use ,
justify content to space-evenly instead! and that should work</p>

Body:
I'm working on a codewell challenge and I'm stuck on this portion. I can't make an even space between them, and the images are overlapping.

.website {
  display: flex;
  justify-content: space-between;
}

.arrow {
  display: inline-block;
  width: 1rem;
}

Spense.com

    Rethinking the way writers get paid, an open resource platform
 design to help writers focus more on writing, and less on
 when and how they'll get paid, Projects in collaboration with
 Codewell.cc

YelpCamp.com

    Allowing backpack travelers to perfectly plan their trip
 through an open-source platform similar to TripAdvisor. With
over 1m MAU, YelpCamp has been the crowd's favorite in
2021.


问:
How to get arg values from a subfunction's decorator?
```<code>def decorator(*args, **kwargs):
    def inner(f):
        print(kwargs['here'])
        return f
    return inner

class Test:
    def test(self, a, b):
        @decorator(here='access/change this value')
        def add(a, b):
            print(a + b)
        add(a, b)
        return

if __name__ == '__main__':
    t = Test()
    t.test(1, 2)
</code>```

How to use "t" to extract or change the value "access/change this value" from a decorator's args on a subfunction. getattribute can only help get function(self) not subfunction, am I right?

For example, I would like to get the value "access/change this value" without running function test.  Or change arg here = [original str] + "a new str"

答:
As the decorator is applied to a function defined inside the Test.test method (hence a new one is created each time the function runs), we can't target the add function, but we can mess with the decorator reference.

from unittest import mock as mocking

if __name__ == '__main__':
    t = Test()
    with mocking.patch("__main__.decorator") as decorator_mock:
        # create another version of the decorator, the one we want
        def my_other_dorator(*args, **kwargs):
            def inner(f):
                print(f"HELLO {args=!r} {kwargs=!r}")
                return f
            return inner
        # and make that it is this one that gets called when `@decorator(...)` is executed
        decorator_mock.side_effect = my_other_dorator
        # now that all is in place, let it run !
        t.test(1, 2)
```
```HELLO args=() kwargs={'here': 'access/change this value'}
3
```

What happened is that we replaced the decorator definition by another, so that we can do whatever we want.

The sublibrary mock comes from the standard library unittest because mocks are very useful for testing, but as monkey patching is part of the Python philosophy, I don't see a problem with using it. But it may lead to very surprising behaviors, so I would not suggest it as a best practice though.

Body:
def decorator(*args, **kwargs):
    def inner(f):
        print(kwargs['here'])
        return f
    return inner

class Test:
    def test(self, a, b):
        @decorator(here='access/change this value')
        def add(a, b):
            print(a + b)
        add(a, b)
        return

if __name__ == '__main__':
    t = Test()
    t.test(1, 2)

How to use "t" to extract or change the value "access/change this value" from a decorator's args on a subfunction. getattribute can only help get function(self) not subfunction, am I right?

For example, I would like to get the value "access/change this value" without running function test.  Or change arg here = [original str] + "a new str"

Body:
As the decorator is applied to a function defined inside the Test.test method (hence a new one is created each time the function runs), we can't target the add function, but we can mess with the decorator reference.

from unittest import mock as mocking

if __name__ == '__main__':
    t = Test()
    with mocking.patch("__main__.decorator") as decorator_mock:
        # create another version of the decorator, the one we want
        def my_other_dorator(*args, **kwargs):
            def inner(f):
                print(f"HELLO {args=!r} {kwargs=!r}")
                return f
            return inner
        # and make that it is this one that gets called when `@decorator(...)` is executed
        decorator_mock.side_effect = my_other_dorator
        # now that all is in place, let it run !
        t.test(1, 2)

HELLO args=() kwargs={'here': 'access/change this value'}
3

What happened is that we replaced the decorator definition by another, so that we can do whatever we want.

The sublibrary mock comes from the standard library unittest because mocks are very useful for testing, but as monkey patching is part of the Python philosophy, I don't see a problem with using it. But it may lead to very surprising behaviors, so I would not suggest it as a best practice though.


问:
Is it programatically illegal to make a seperate Main Activity in Android Studio?
My contacts list in Android Studio has a "Remove Contacts" tab that works as a Main Activity, having a Main_Remove_Contact class and a Remove_Contact class.

I would like to know if it's wrong to make a class that would be a Main Class in another project, but not on this one; can the app withstand a Main Activity and a "Main Activity"-like class. I'm saying this because of this error:

```<code>2022-02-09 08:36:32.966 6840-6840/com.example.wolfixfinal E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.wolfixfinal, PID: 6840
    java.lang.SecurityException: Permission Denial: writing com.android.providers.contacts.ContactsProvider2 uri content://com.android.contacts/data from pid=6840, uid=10160 requires android.permission.WRITE_CONTACTS, or grantUriPermission()
        at android.os.Parcel.createExceptionOrNull(Parcel.java:2373)
        at android.os.Parcel.createException(Parcel.java:2357)
        at android.os.Parcel.readException(Parcel.java:2340)
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:190)
        at android.database.DatabaseUtils.readExceptionWithOperationApplicationExceptionFromParcel(DatabaseUtils.java:165)
        at android.content.ContentProviderProxy.applyBatch(ContentProviderNative.java:599)
        at android.content.ContentProviderClient.applyBatch(ContentProviderClient.java:576)
        at android.content.ContentProviderClient.applyBatch(ContentProviderClient.java:564)
        at android.content.ContentResolver.applyBatch(ContentResolver.java:2196)
        at com.example.wolfixfinal.Main_Remove_Contact.onOptionsItemSelected(Main_Remove_Contact.java:55)
        at android.app.Activity.onMenuItemSelected(Activity.java:4269)
        at androidx.fragment.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:352)
        at androidx.appcompat.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:264)
        at androidx.appcompat.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)
        at androidx.appcompat.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:66)
        at androidx.appcompat.widget.Toolbar$1.onMenuItemClick(Toolbar.java:221)
        at androidx.appcompat.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:781)
        at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:834)
        at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
        at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:985)
        at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:975)
        at androidx.appcompat.widget.ActionMenuView.invokeItem(ActionMenuView.java:625)
        at androidx.appcompat.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:151)
        at android.view.View.performClick(View.java:7448)
        at android.view.View.performClickInternal(View.java:7425)
        at android.view.View.access$3600(View.java:810)
        at android.view.View$PerformClick.run(View.java:28305)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
</code>```

One of the lines says

at com.example.wolfixfinal.Main_Remove_Contact.onOptionsItemSelected(Main_Remove_Contact.java:55)

The code of the method where the line is is the following:

```<code>@Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
            case R.id.menu_refresh:
                showContacts();
                break;
            case R.id.menu_check:
                for(int i = 0; i < listView.getAdapter().getCount(); i++){
                    listView.setItemChecked(i,true);
                }
                break;
            case R.id.menu_delete:
                ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data._ID + "=?", new String[]{String.valueOf(item)}).build());
                try {
                    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                } catch (OperationApplicationException e) {
                    e.printStackTrace();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
        }
        return true;
    }
</code>```

.applyBatch (in the try catch segment) is where the error is at. Does it have to do with the aforementioned Main Activity problem, or is it something else (it could be an outdated resource).

TL;DR:

Question in the title

Is applyBatch outdated?

If not, how does it work in the method inserted above?

If more code is needed in the Main_Remove_Class activity, I'll edit the question. It does get some attributes from Remove_Class but I don't know if they're needed.

I think this question could also help with some specific IntelliJ Idea key-words, so I'll add that as a tag too. I might make a specific question about .applyBatch too if necessary.

Thanks in advance!

Edit: I already have the permission that asks the app if it can read contacts (android.permission.WRITE_CONTACTS).

答:
Those activities are all fine.

You need to ask the user to grant the android.permission.WRITE_CONTACTS runtime permission for writing contacts:

This is the error:

```<code>java.lang.SecurityException: Permission Denial: writing com.android.providers.contacts.ContactsProvider2 uri content://com.android.contacts/data from pid=6840, uid=10160 requires android.permission.WRITE_CONTACTS, or grantUriPermission()
</code>```

Dangerous permissions like WRITE_CONTACTS require you to ask the user for a permission at runtime. This means, just declaring the permission in the android manifest file is not enough.

Check out the guide on Request app permissions.

Body:
My contacts list in Android Studio has a "Remove Contacts" tab that works as a Main Activity, having a Main_Remove_Contact class and a Remove_Contact class.

I would like to know if it's wrong to make a class that would be a Main Class in another project, but not on this one; can the app withstand a Main Activity and a "Main Activity"-like class. I'm saying this because of this error:

2022-02-09 08:36:32.966 6840-6840/com.example.wolfixfinal E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.wolfixfinal, PID: 6840
    java.lang.SecurityException: Permission Denial: writing com.android.providers.contacts.ContactsProvider2 uri content://com.android.contacts/data from pid=6840, uid=10160 requires android.permission.WRITE_CONTACTS, or grantUriPermission()
        at android.os.Parcel.createExceptionOrNull(Parcel.java:2373)
        at android.os.Parcel.createException(Parcel.java:2357)
        at android.os.Parcel.readException(Parcel.java:2340)
        at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:190)
        at android.database.DatabaseUtils.readExceptionWithOperationApplicationExceptionFromParcel(DatabaseUtils.java:165)
        at android.content.ContentProviderProxy.applyBatch(ContentProviderNative.java:599)
        at android.content.ContentProviderClient.applyBatch(ContentProviderClient.java:576)
        at android.content.ContentProviderClient.applyBatch(ContentProviderClient.java:564)
        at android.content.ContentResolver.applyBatch(ContentResolver.java:2196)
        at com.example.wolfixfinal.Main_Remove_Contact.onOptionsItemSelected(Main_Remove_Contact.java:55)
        at android.app.Activity.onMenuItemSelected(Activity.java:4269)
        at androidx.fragment.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:352)
        at androidx.appcompat.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:264)
        at androidx.appcompat.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:109)
        at androidx.appcompat.app.ToolbarActionBar$2.onMenuItemClick(ToolbarActionBar.java:66)
        at androidx.appcompat.widget.Toolbar$1.onMenuItemClick(Toolbar.java:221)
        at androidx.appcompat.widget.ActionMenuView$MenuBuilderCallback.onMenuItemSelected(ActionMenuView.java:781)
        at androidx.appcompat.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:834)
        at androidx.appcompat.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:158)
        at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:985)
        at androidx.appcompat.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:975)
        at androidx.appcompat.widget.ActionMenuView.invokeItem(ActionMenuView.java:625)
        at androidx.appcompat.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:151)
        at android.view.View.performClick(View.java:7448)
        at android.view.View.performClickInternal(View.java:7425)
        at android.view.View.access$3600(View.java:810)
        at android.view.View$PerformClick.run(View.java:28305)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

One of the lines says

at com.example.wolfixfinal.Main_Remove_Contact.onOptionsItemSelected(Main_Remove_Contact.java:55)

The code of the method where the line is is the following:

@Override
    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
            case R.id.menu_refresh:
                showContacts();
                break;
            case R.id.menu_check:
                for(int i = 0; i < listView.getAdapter().getCount(); i++){
                    listView.setItemChecked(i,true);
                }
                break;
            case R.id.menu_delete:
                ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

                ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data._ID + "=?", new String[]{String.valueOf(item)}).build());
                try {
                    getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
                } catch (OperationApplicationException e) {
                    e.printStackTrace();
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                break;
        }
        return true;
    }

.applyBatch (in the try catch segment) is where the error is at. Does it have to do with the aforementioned Main Activity problem, or is it something else (it could be an outdated resource).

TL;DR:

Question in the title

Is applyBatch outdated?

If not, how does it work in the method inserted above?

If more code is needed in the Main_Remove_Class activity, I'll edit the question. It does get some attributes from Remove_Class but I don't know if they're needed.

I think this question could also help with some specific IntelliJ Idea key-words, so I'll add that as a tag too. I might make a specific question about .applyBatch too if necessary.

Thanks in advance!

Edit: I already have the permission that asks the app if it can read contacts (android.permission.WRITE_CONTACTS).

Body:
Those activities are all fine.

You need to ask the user to grant the android.permission.WRITE_CONTACTS runtime permission for writing contacts:

This is the error:

java.lang.SecurityException: Permission Denial: writing com.android.providers.contacts.ContactsProvider2 uri content://com.android.contacts/data from pid=6840, uid=10160 requires android.permission.WRITE_CONTACTS, or grantUriPermission()

Dangerous permissions like WRITE_CONTACTS require you to ask the user for a permission at runtime. This means, just declaring the permission in the android manifest file is not enough.

Check out the guide on Request app permissions.


问:
Unable to pair device for debugging over Wi-Fi, Android Studio (Bumblebee)
I want to debug my Flutter app via wireless debugging on Android Studio Bumblebee. When I go to the "Pair devices over WiFi" section. It shows me this -

My platform tools are up to date (32.0.0). And yet it's showing this.

I'm more confused to why it's not working because, it did work a few hours earlier, but does not anymore. Any help is appreciated.

EDIT : It started working again. I don't know how, I have not changed a thing, yet it is.

答:
Just update your Bumblebee on the last patch https://developer.android.com/studio?utm_source=android-studio

It helped me with the same issue


问:
Restricting Android Broadcast Receiver from specific app
I have 2 applications.

If I use service, I can set permission so only app1 can send intent to app2:

Define permission in app2 (protection level: signature), and
use that permission in app1.

Service in app2 is protected by that permission.

In this way, only app1 can send an intent to a service on app2,
and no other app (unless my signature is leaked) can send intent to
service on app2.

Can I do the same with Broadcast Receiver?

app1: sendBroadcast(intent, permission)

app2: define permission, use that permission.

To my understanding for using sendBroadcast(intent, permission), the
application doesn't need to "use" the permission. Meaning ANY application
can send intent to app2. Those permission parameters only checked against
app2, to avoid other applications  to receive this intent.
(If I remove app2, and install fake app2 with the same permission string
 defined, fake app2 can get intent from app1, which is unexpected)

BTW, If application define the permission and use it itself, the
 protectionLevel(signature) seems to have no meaning. Is this true?

Now, I can set additional permission:

app1: Define permission, use that permission.

app2: Receiver restricted only for that permission.

Again, if one removes app1, installs fake app1 with the very same
permission, then fake app1 can send fake intent to app2.
What can I do to prevent app2 from receiving fake intent?

Thanks

答:
Here is my code:

Sender App

MainActivity.java

```<code>package com.karthik.apptx;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.Process;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void OnClickButton(View view) {
        Intent intent = new Intent();
        intent.setAction("com.karthik.apprx");
        intent.putExtra("PACKAGE_NAME", this.getPackageName());
        intent.putExtra("PID", Process.myPid());
        intent.putExtra("DATA", "Hello Karthik");
        intent.setComponent(new ComponentName("com.karthik.apprx", "com.karthik.apprx.AppRxReceiver"));
        sendBroadcast(intent);
    }
}
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.karthik.apptx">

    <uses-permission android:name="com.karthik.PERMISSION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppTx">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

Receiver App (Written in Kotlin)

MyBroadcastReceiver.kt

```<code>package com.karthik.apprx

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.Toast

class AppRxReceiver : BroadcastReceiver() {

    override fun onReceive(ctx: Context?, intent: Intent?) {
        Log.d("AppRxReceiver", intent.toString())
        Log.d("AppRxReceiver", intent?.getStringExtra("PACKAGE_NAME").toString())
        Log.d("AppRxReceiver", "" + intent?.getIntExtra("PID", 0))
        Log.d("AppRxReceiver", intent?.getStringExtra("DATA").toString())
        Toast.makeText(ctx, "Received Data", Toast.LENGTH_SHORT).show()
    }
}
</code>```

AndroidManifest.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.karthik.apprx">

    <permission
        android:name="com.karthik.PERMISSION"
        android:protectionLevel="signature"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppRx">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.AppRx.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver
            android:name=".AppRxReceiver"
            android:enabled="true"
            android:exported="true"
            android:permission="com.karthik.PERMISSION">
            <intent-filter>
                <action android:name="com.karthik.apptx" />
            </intent-filter>
        </receiver>
    </application>

</manifest>
</code>```

PS: For my convenience, I have chosen to write Sender-App in Java and Receiver-App in Kotlin.

Body:
Here is my code:

Sender App

MainActivity.java

package com.karthik.apptx;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.Process;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void OnClickButton(View view) {
        Intent intent = new Intent();
        intent.setAction("com.karthik.apprx");
        intent.putExtra("PACKAGE_NAME", this.getPackageName());
        intent.putExtra("PID", Process.myPid());
        intent.putExtra("DATA", "Hello Karthik");
        intent.setComponent(new ComponentName("com.karthik.apprx", "com.karthik.apprx.AppRxReceiver"));
        sendBroadcast(intent);
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.karthik.apptx">

    <uses-permission android:name="com.karthik.PERMISSION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppTx">
        <activity
            android:name=".MainActivity"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Receiver App (Written in Kotlin)

MyBroadcastReceiver.kt

package com.karthik.apprx

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.Toast

class AppRxReceiver : BroadcastReceiver() {

    override fun onReceive(ctx: Context?, intent: Intent?) {
        Log.d("AppRxReceiver", intent.toString())
        Log.d("AppRxReceiver", intent?.getStringExtra("PACKAGE_NAME").toString())
        Log.d("AppRxReceiver", "" + intent?.getIntExtra("PID", 0))
        Log.d("AppRxReceiver", intent?.getStringExtra("DATA").toString())
        Toast.makeText(ctx, "Received Data", Toast.LENGTH_SHORT).show()
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.karthik.apprx">

    <permission
        android:name="com.karthik.PERMISSION"
        android:protectionLevel="signature"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.AppRx">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:label="@string/app_name"
            android:theme="@style/Theme.AppRx.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver
            android:name=".AppRxReceiver"
            android:enabled="true"
            android:exported="true"
            android:permission="com.karthik.PERMISSION">
            <intent-filter>
                <action android:name="com.karthik.apptx" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

PS: For my convenience, I have chosen to write Sender-App in Java and Receiver-App in Kotlin.