问:
IntelliJ: Error:java: error: release version 5 not supported
I'm using IntelliJ IDEA Ultimate 2019.3.1. Whenever I try to start any simple Java Maven project (may it be even a simple Hello World) I get the following error:

```<code>Error:java: error: release version 5 not supported
</code>```

Running java --version by terminal I get the following output:

```<code>openjdk 11.0.5 2019-10-15
OpenJDK Runtime Environment (build 11.0.5+10-post-Ubuntu-0ubuntu1.1)
OpenJDK 64-Bit Server VM (build 11.0.5+10-post-Ubuntu-0ubuntu1.1, mixed mode, sharing)
</code>```

Running javac --version by terminal I get the following output:

```<code>javac 11.0.5
</code>```

Going to the Settings of the Java Compiler ( as suggested here ) I see this:

I tried editing the "Target bytecode version" to 1.8 but I get the following errors:

```<code>Error:(1, 26) java: package javafx.application does not exist
Error:(2, 20) java: package javafx.stage does not exist
Error:(4, 27) java: cannot find symbol
  symbol: class Application
Error:(12, 23) java: cannot find symbol
  symbol:   class Stage
  location: class Main
Error:(7, 9) java: cannot find symbol
  symbol:   method launch(java.lang.String[])
  location: class Main
Error:(11, 5) java: method does not override or implement a method from a supertype
</code>```

Changing it to version 1.11 I get this error instead:

```<code>Error:java: Source option 5 is no longer supported. Use 6 or later.
</code>```

What do you think is the problem? How may I solve it?

答:
File->Settings

From left side ->"Build, Execution, Deployment" ->"java compiler"

choose the project that you work on and choose the java version you need

Body:
I'm using IntelliJ IDEA Ultimate 2019.3.1. Whenever I try to start any simple Java Maven project (may it be even a simple Hello World) I get the following error:

Error:java: error: release version 5 not supported

Running java --version by terminal I get the following output:

openjdk 11.0.5 2019-10-15
OpenJDK Runtime Environment (build 11.0.5+10-post-Ubuntu-0ubuntu1.1)
OpenJDK 64-Bit Server VM (build 11.0.5+10-post-Ubuntu-0ubuntu1.1, mixed mode, sharing)

Running javac --version by terminal I get the following output:

javac 11.0.5

Going to the Settings of the Java Compiler ( as suggested here ) I see this:

I tried editing the "Target bytecode version" to 1.8 but I get the following errors:

Error:(1, 26) java: package javafx.application does not exist
Error:(2, 20) java: package javafx.stage does not exist
Error:(4, 27) java: cannot find symbol
  symbol: class Application
Error:(12, 23) java: cannot find symbol
  symbol:   class Stage
  location: class Main
Error:(7, 9) java: cannot find symbol
  symbol:   method launch(java.lang.String[])
  location: class Main
Error:(11, 5) java: method does not override or implement a method from a supertype

Changing it to version 1.11 I get this error instead:

Error:java: Source option 5 is no longer supported. Use 6 or later.

What do you think is the problem? How may I solve it?


来源: stackexchange

问:
Install IBM Qiskit for quantum computer simulation
I am having trouble uploading qiskit to my Ananconda3 environment.  I follow these steps without any problem. In Anaconda3 shell

conda create -n ENV_NAME python=3

conda activate ENV_NAME

pip install qiskit

pip install qiskit[visualization]

When I check the modules with conda list, qiskit is not to be found. Other modules such as numpy, matplotlib, etc. are present.

Any suggestions?  On my previous Windows based PC, I was able to download everything without any  problems.

答: Did you try  pip list since you installed with pip

ContentLicense: CC BY-SA 4.0


问:
Dynamically determine the correct type of data with a type hint
Is it possible to interpret data differently based on a 'type-field'?

I am loading data (all from the same file). I know the type of the data, and what the type definitions look like. With the current union approach, it'd always show all fields, but I'd like to be able to automatically be able to determine which type applies. I could cast the type during runtime, but that's not ideal.

Not sure if I am pushing TS a bit too much here, and if it instead should live in the actual loading/parsing logic?

Current approach

enum MyTypes {
  TypeA = "A",
  TypeB = "B",
}
```
<pre class="lang-js prettyprint-override"><code>type IData = {
  type: MyTypes;
  data: IDataAllTypes <---- force the type to be `IDataTypeA` if the type field is `TypeA`
}
</code>```

type IDataAllTypes = IDataTypeA | IDataTypeB

type IDataTypeA = {
  id: string
  age: number
  foo: string[]
}

type IDataTypeB = {
  id: string
  name: string
  bar: string[]
}
```

答:
You can do it like this</p>
```<code>enum MyTypes {
  TypeA = "A",
  TypeB = "B",
}

type IDataTypeA = {
  id: string
  age: number
  foo: string[]
}

type IDataTypeB = {
  id: string
  name: string
  bar: string[]
}

IDataA {
  type: MyTypes.TypeA,
  data: IDataTypeA,
}

IDataB {
  type: MyTypes.TypeB,
  data: IDataTypeB,
}

IDataAllTypes = IDataA | IDataB;
</code>```

Body:
Is it possible to interpret data differently based on a 'type-field'?

I am loading data (all from the same file). I know the type of the data, and what the type definitions look like. With the current union approach, it'd always show all fields, but I'd like to be able to automatically be able to determine which type applies. I could cast the type during runtime, but that's not ideal.

Not sure if I am pushing TS a bit too much here, and if it instead should live in the actual loading/parsing logic?

Current approach

enum MyTypes {
  TypeA = "A",
  TypeB = "B",
}

type IData = {
  type: MyTypes;
  data: IDataAllTypes <---- force the type to be `IDataTypeA` if the type field is `TypeA`
}

type IDataAllTypes = IDataTypeA | IDataTypeB

type IDataTypeA = {
  id: string
  age: number
  foo: string[]
}

type IDataTypeB = {
  id: string
  name: string
  bar: string[]
}

Body:
You can do it like this

enum MyTypes {
  TypeA = "A",
  TypeB = "B",
}

type IDataTypeA = {
  id: string
  age: number
  foo: string[]
}

type IDataTypeB = {
  id: string
  name: string
  bar: string[]
}

IDataA {
  type: MyTypes.TypeA,
  data: IDataTypeA,
}

IDataB {
  type: MyTypes.TypeB,
  data: IDataTypeB,
}

IDataAllTypes = IDataA | IDataB;


问:
How to get OTP from SMS - autofill
I want to catch or read OTP of SMS messages automatically. I did some tests like this code :

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Demo Auto OTP'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _textController = TextEditingController();
  String _error;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Multi-Factor-Authentication"),
        ),
        body: Form(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: _textController,
                autofillHints: [ AutofillHints.oneTimeCode ],
                keyboardType: TextInputType.visiblePassword,
                maxLength: 6,
                maxLengthEnforced: true,
                style: TextStyle(fontSize: 32),
              ),

              RaisedButton(
                child: Text("Verify"),
                onPressed: () => Navigator.of(context).pop(_textController.value.text),
              ),
            ],
          ),
        )
    );
  }
}
</code>```

And this is the test SMS message : 12345 is your code to log in.

Flutter documentation for oneTimeCode:
https://api.flutter.dev/flutter/services/AutofillHints/oneTimeCode-constant.html

Flutter Autofill : https://github.com/flutter/flutter/blob/7891006299/packages/flutter/lib/src/services/autofill.dart#L362

IOS : https://developer.apple.com/documentation/uikit/uitextcontenttype

Android :
https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_SMS_OTP

答:
@Kamrul Hasan Jony described very well. But one thing that should be keep in mind who is implementing this.
Before assigning the OTP to controller you should check app_Signature or another validation so that OTP takes from specific msg only. eg.

```<code>setState(() {
  _commingSms = commingSms;
  String aStr = _commingSms.replaceAll(new RegExp(r'[^0-9]'),'');
  String otp = aStr.substring(0,4);
  if(_commingSms.contains(AppConstants.appSignature)){
    textEditingController.text = otp;
    //_presenter.validateOtp(widget.apiToken, widget.phone, textEditingController.text, context);
  }
});
</code>```

Moreover for iOS AltSmsAutofill().listenForSms returns iOS version(alt_sms_autofill: ^1.0.0). So you will get rid of everything if you use some kind of validation before assigning otp to the controller.

Title: How to get OTP from SMS - autofill

Body:
I want to catch or read OTP of SMS messages automatically. I did some tests like this code :

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Demo Auto OTP'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _textController = TextEditingController();
  String _error;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Multi-Factor-Authentication"),
        ),
        body: Form(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: _textController,
                autofillHints: [ AutofillHints.oneTimeCode ],
                keyboardType: TextInputType.visiblePassword,
                maxLength: 6,
                maxLengthEnforced: true,
                style: TextStyle(fontSize: 32),
              ),

              RaisedButton(
                child: Text("Verify"),
                onPressed: () => Navigator.of(context).pop(_textController.value.text),
              ),
            ],
          ),
        )
    );
  }
}

And this is the test SMS message : 12345 is your code to log in.

Flutter documentation for oneTimeCode:
https://api.flutter.dev/flutter/services/AutofillHints/oneTimeCode-constant.html

Flutter Autofill : https://github.com/flutter/flutter/blob/7891006299/packages/flutter/lib/src/services/autofill.dart#L362

IOS : https://developer.apple.com/documentation/uikit/uitextcontenttype

Android :
https://developer.android.com/reference/androidx/autofill/HintConstants#AUTOFILL_HINT_SMS_OTP

Body:
@Kamrul Hasan Jony described very well. But one thing that should be keep in mind who is implementing this.
Before assigning the OTP to controller you should check app_Signature or another validation so that OTP takes from specific msg only. eg.

setState(() {
  _commingSms = commingSms;
  String aStr = _commingSms.replaceAll(new RegExp(r'[^0-9]'),'');
  String otp = aStr.substring(0,4);
  if(_commingSms.contains(AppConstants.appSignature)){
    textEditingController.text = otp;
    //_presenter.validateOtp(widget.apiToken, widget.phone, textEditingController.text, context);
  }
});

Moreover for iOS AltSmsAutofill().listenForSms returns iOS version(alt_sms_autofill: ^1.0.0). So you will get rid of everything if you use some kind of validation before assigning otp to the controller.


问:
What's the difference between capitalized and lowercase versions of Keras.losses and Keras.metrics?
While I was constructing a simple Sequential ANN and selecting parameters for the model.compile method, I observed that Keras.metrics and Keras.losses contain capitalized as well as lowercase versions, for example tf.keras.metrics.SparseCategoricalAccuracy versus tf.keras.metrics.sparse_categorical_accuracy. I was wondering what the difference is between those versions and which one is more suitable to be used in model.compile ?

答:
tf.keras.metrics.SparseCategoricalAccuracy is a Class so you get an object and you can pass it over to model.compile. Since it is an object it can have state between the calls.

However tf.keras.metrics.sparse_categorical_accuracy is a function and it is stateless. Both perform the same operation but their usage is different.


问:
Does This Hierarchy work with ListView? Getting NoReverseMatch Error
I'm running into an issue debugging the following error:

Reverse for 'tasks' with arguments '('',)' not found. 1 pattern(s) tried: ['customer/(?P[-a-zA-Z0-9_]+)/tasks/$']

However, I'm pretty certain that my url parameters are correct and without typos. The url and page worked fine with a function based view, the problem started when I changed to a ListView.

Template:

```<code><a href="{% url 'customerportal:tasks' object.slug %}" class="nav-link">
</code>```

I also tried:

```<code><a href="{% url 'customerportal:tasks' slug=object.slug %}" class="nav-link">
<a href="{% url 'customerportal:tasks' slug=object.slug|slugify %}" class="nav-link">
</code>```

DetailView - passing slug param to url

```<code>class ProjectDetailView(DetailView):
model = Project
template_name = 'customerportal/customer_portal.html'

def get(self, request, *args, **kwargs):
    self.object = self.get_object()
    if not self.object.access_verification(request.user):
        raise PermissionDenied()
    context = self.get_context_data(object=self.object)
    return self.render_to_response(context)
</code>```

My ListView (errors):

```<code>class TaskListView(ListView):
    model = Task
    template_name = 'customerportal/tasks.html'

    def get_queryset(self):
        self.project = get_object_or_404(Project, slug=self.kwargs['customer_portal'])
        return Task.objects.filter(project=self.project.id)
</code>```

URLs:

```<code>path('<slug:slug>/', ProjectDetailView.as_view(), name='customer_portal'),
path('<slug:customer_portal>/tasks/', TaskListView.as_view(), name='tasks'),
</code>```

I've confirmed that I'm passing the right slug by printing it. The slug parameter is from a parent directory as seen in the urls.py above. I'm guessing ListView doesn't work this way? If not is there a way I could maintain this structure, or do I have to switch back to a function based view in order to get this to work?

Thanks.

答:
there is 2 things to sort out:

your error message says that there is a path that looks similar to this:

```<code>path('customer/<slug:customer_portal>/tasks/', TaskListView.as_view(), name='tasks'),
</code>```

but your paths do not match that pattern of the error message - maybe you edited the paths after the error appeared.

the error type "... arguments '('',)' ..." always means that the parameter in your {% url ... %} statement is empty. In your case that would mean object.slug is empty
Please check what you handover to the template as object.slug

Body:
I'm running into an issue debugging the following error:

Reverse for 'tasks' with arguments '('',)' not found. 1 pattern(s) tried: ['customer/(?P[-a-zA-Z0-9_]+)/tasks/$']

However, I'm pretty certain that my url parameters are correct and without typos. The url and page worked fine with a function based view, the problem started when I changed to a ListView.

Template:

I also tried:

DetailView - passing slug param to url

class ProjectDetailView(DetailView):
model = Project
template_name = 'customerportal/customer_portal.html'

def get(self, request, *args, **kwargs):
    self.object = self.get_object()
    if not self.object.access_verification(request.user):
        raise PermissionDenied()
    context = self.get_context_data(object=self.object)
    return self.render_to_response(context)

My ListView (errors):

class TaskListView(ListView):
    model = Task
    template_name = 'customerportal/tasks.html'

    def get_queryset(self):
        self.project = get_object_or_404(Project, slug=self.kwargs['customer_portal'])
        return Task.objects.filter(project=self.project.id)

URLs:

path('<slug:slug>/', ProjectDetailView.as_view(), name='customer_portal'),
path('<slug:customer_portal>/tasks/', TaskListView.as_view(), name='tasks'),

I've confirmed that I'm passing the right slug by printing it. The slug parameter is from a parent directory as seen in the urls.py above. I'm guessing ListView doesn't work this way? If not is there a way I could maintain this structure, or do I have to switch back to a function based view in order to get this to work?

Thanks.

Body:
there is 2 things to sort out:

your error message says that there is a path that looks similar to this:

path('customer/<slug:customer_portal>/tasks/', TaskListView.as_view(), name='tasks'),

but your paths do not match that pattern of the error message - maybe you edited the paths after the error appeared.

the error type "... arguments '('',)' ..." always means that the parameter in your {% url ... %} statement is empty. In your case that would mean object.slug is empty
Please check what you handover to the template as object.slug


答:
This is called a discriminated union. It's a union type where all members have a common field that can be used to enforce the rest of the type.

You can declare IData like this:

```<code>type IDataA = {
    type: MyTypes.TypeA,
    data: IDataTypeA
}

type IDataB = {
    type: MyTypes.TypeB,
    data: IDataTypeB
}
type IData = IDataA | IDataB
</code>```

Now this works like you expect:

```<code>const testA: IData = { type: MyTypes.TypeA, data: { id: 'qwe', age: 123, foo: ['a'] }}
const testB: IData = { type: MyTypes.TypeB, data: { id: 'qwe', name: 'asd', bar: ['b'] }}

// Type error. Can't pair type A with values from type B
const testFail: IData = { type: MyTypes.TypeA, data: { id: 'qwe', name: 'asd', bar: ['b'] }}
</code>```

Playground

Title: Dynamically determine the correct type of data with a type hint

Body:
This is called a discriminated union. It's a union type where all members have a common field that can be used to enforce the rest of the type.

You can declare IData like this:

type IDataA = {
    type: MyTypes.TypeA,
    data: IDataTypeA
}

type IDataB = {
    type: MyTypes.TypeB,
    data: IDataTypeB
}
type IData = IDataA | IDataB

Now this works like you expect:

const testA: IData = { type: MyTypes.TypeA, data: { id: 'qwe', age: 123, foo: ['a'] }}
const testB: IData = { type: MyTypes.TypeB, data: { id: 'qwe', name: 'asd', bar: ['b'] }}

// Type error. Can't pair type A with values from type B
const testFail: IData = { type: MyTypes.TypeA, data: { id: 'qwe', name: 'asd', bar: ['b'] }}

<a href="https://www.typescriptlang.org/play?target=1&ssl=34&ssc=93&pln=30&pc=1#code/KYOwrgtgBAsgngFTgB2AZygbwFBSk1AQSgF4oAiQ8gGl3xWACFSLGbsBfbbAFwagCSAEQCGPEQWDEyOPAEsAJgC4oaHgCc5IAOZ0R24CvAQARsHV0AZgHtrKtZp0BtALqdufVINHjJzGXSK9hpaunggIhCGqiE6dCYi6sGO2q7uvPzCYiLSWHR4ntHwkmgAdJKEtHh4CtkqWb4MhOmF3tn+edVQhSrFDGV+VdW14vU+EgyM7q0NIiyzxAA+beJT3ADG1iBq3eg8hGPZLJjdDL2I-eVN1FAjIionQVAA5ACOAO7Azzf60QCMACYAMw3Gx2KBOZ4iZ4uKAcLibbY8XZqRiHcTHU6oc4lK6oRg3O4PKBPN6fb5QCJRFRQtAKCkJJIQ54mGFwrjYAD0nPoXnM6ms6lKUAAwiIQM9kcgRHJ1FjgFBiO85DwABZQABuIgANmB0FBLALoK0poidjw9gAxGXa9FzGTynGXCqEupYEnKF4fL43KnRWn0m6MlSQ1mw+FAA" rel="nofollow noreferrer">Playground


问:
Can Nant be used to deploy to different servers?
Can Nant be used to deploy an application to a different set of servers based on some type of property/parameter?

What I need NANT to do:
An environment is made up of 1 or more servers.
We have multiple environments (dev, qa, prod).
The package contains multiple web-site projects.

When NANT is asked to build for DEV, it needs to build the projects and setup the web.config up correctly to work in the DEV environment (connection strings, etc). In addition each web-site project needs to be deployed to the correct server for that environment.

In addition, can NANT be used to build all my projects once and then deploy it multiple times (deploy to Dev, QA, Prod environments?) (ie, the build and deploy are done at different times and once a build has been created, the deploy could be run on that build package multiple times)

答:
Look at my answer here for Configuration Management: Should I have multiple build.xml files for one project (dev,staging,production)

Basically you need environment configs for DEV, QA, PREPROD, PROD etc, specify the environment you want to deploy during deploy ( say from command line through -D:environment=DEV ) which will use the appropriate config and deploy.

Build once, deploy everywhere is the general approach you should follow. Build and deploy should be separate targets. Use a CI tool if needed ( like Jenkins, TeamCity) to build the application. Expose the build application ( zip, tar, war etc) as Artifacts. In the deploy target, download the necessary artifact and do the deploy.

ContentLicense: CC BY-SA 3.0


问:
Place value notation in quantum computing?
How do quantum computers store numbers in place value systems? Do they use the binary system, like traditional computation does?</p>

答: It can do more than binary number in classic computer. 2 qubits can have 4 values. For classic, 2 bits, can store 2 values only</p>


问:
pop method LinkedList Class
I have implemented the LinkedList class: I need to implement the pop() which takes no parameter. The method removes and returns the item at the end of the linked list. If the list is empty it returns None and does nothing.

```<code>class LinkedList:
        def __init__(self):
            self.head = None
            self.count = 0

        def is_empty(self):
            return self.count == 0

        def size(self):
            return self.count

        def add(self, item):
            new_node = Node(item)
            new_node.set_next(self.head)
            self.head = new_node
            self.count += 1

        def search(self, item):
            current = self.head
            while current != None:
                if current.get_data() == item:
                    return True
                else:
                    current = current.get_next()
            return False

        def remove(self, item):
            found = False
            current = self.head
            previous = None
            while current != None and not found:
                if current.get_data() == item:
                    found = True
                else:
                    previous = current
                    current = current.get_next()
            if found:
                if previous == None:
                    self.head = current.get_next()
                else:
                    previous.set_next(current.get_next())
                self.count -= 1
            else:
                raise ValueError("remove(" + str(item) + "). " + str(item) + " is not in list")

        def clear(self):
            self.head = None
            self.count = 0

        def __str__(self):
            temp = self.head
            if(temp != None):
                output ="Head"
                while (temp != None):
                    output = output+" --> "+str(temp.data)
                    temp = temp.next
                return output
            else:
                return "Head --> None"

        def append(self, item):
            new_node = Node(item)

            if self.head is None:
                self.head = new_node
                return
            last = self.head
            while(last.next):
                last = last.next

            last.next = new_node

        def pop(self):   #Problem here
            if self.head is None:
                return None
            else:
                popnode = self.head
                self.head = self.head.next
                popnode.next = None
                return popnode.data
</code>```

Test:

```<code>a_list = LinkedList()
a_list.add(1)
a_list.add(2)
a_list.add(3)
print(a_list)
print("Removed item:",a_list.pop())
print("Removed item:",a_list.pop())
print(a_list)
</code>```

Expected Output:

```<code>Head --> 3 --> 2 --> 1
Removed item: 1
Removed item: 2
Head --> 3
</code>```

Recd Output:

```<code>Head --> 3 --> 2 --> 1
Removed item: 3
Removed item: 2
Head --> 1
</code>```

Test:

```<code>a_list = LinkedList()
a_list.append(1)
a_list.append(2)
a_list.append(3)
print(a_list)
print("Removed item:",a_list.pop())
print("Removed item:",a_list.pop())
print(a_list)
</code>```

Expected output:

```<code>Head --> 1 --> 2 --> 3
Removed item: 3
Removed item: 2
Head --> 1
</code>```

Recd output:

```<code>Head --> 1 --> 2 --> 3
Removed item: 1
Removed item: 2
Head --> 3
</code>```

答:
Just track popnode.next when become None and at the same time store previous item, when popnode.next become None, Just put next of prev None, and return data of popnode.next:

def pop(self):  # Problem here
    if self.head is None:
        return None
    elif self.head.next == None:
        d = self.head.data
        self.head = None
        return d
    else:
        popnode = self.head
        prev = popnode
        while popnode.next:
            prev = popnode
            popnode = popnode.next
        prev.next = None
        return popnode.data

```
<p>The output of:</p>
<pre class="lang-python prettyprint-override"><code>a_list = LinkedList()
a_list.add(1)
a_list.add(2)
a_list.add(3)
print(a_list)
print("Removed item:", a_list.pop())
print("Removed item:", a_list.pop())
print("Removed item:", a_list.pop())
print(a_list)
</code>```

Will be:

Head --> 3--> 2--> 1
Removed item: 1
Removed item: 2
Removed item: 3
Head  None
```

Title: pop method LinkedList Class

Body:
I have implemented the LinkedList class: I need to implement the pop() which takes no parameter. The method removes and returns the item at the end of the linked list. If the list is empty it returns None and does nothing.

class LinkedList:
        def __init__(self):
            self.head = None
            self.count = 0

        def is_empty(self):
            return self.count == 0

        def size(self):
            return self.count

        def add(self, item):
            new_node = Node(item)
            new_node.set_next(self.head)
            self.head = new_node
            self.count += 1

        def search(self, item):
            current = self.head
            while current != None:
                if current.get_data() == item:
                    return True
                else:
                    current = current.get_next()
            return False

        def remove(self, item):
            found = False
            current = self.head
            previous = None
            while current != None and not found:
                if current.get_data() == item:
                    found = True
                else:
                    previous = current
                    current = current.get_next()
            if found:
                if previous == None:
                    self.head = current.get_next()
                else:
                    previous.set_next(current.get_next())
                self.count -= 1
            else:
                raise ValueError("remove(" + str(item) + "). " + str(item) + " is not in list")

        def clear(self):
            self.head = None
            self.count = 0

        def __str__(self):
            temp = self.head
            if(temp != None):
                output ="Head"
                while (temp != None):
                    output = output+" --> "+str(temp.data)
                    temp = temp.next
                return output
            else:
                return "Head --> None"

        def append(self, item):
            new_node = Node(item)

            if self.head is None:
                self.head = new_node
                return
            last = self.head
            while(last.next):
                last = last.next

            last.next = new_node

        def pop(self):   #Problem here
            if self.head is None:
                return None
            else:
                popnode = self.head
                self.head = self.head.next
                popnode.next = None
                return popnode.data

Test:

a_list = LinkedList()
a_list.add(1)
a_list.add(2)
a_list.add(3)
print(a_list)
print("Removed item:",a_list.pop())
print("Removed item:",a_list.pop())
print(a_list)

Expected Output:

Head --> 3 --> 2 --> 1
Removed item: 1
Removed item: 2
Head --> 3

Recd Output:

Head --> 3 --> 2 --> 1
Removed item: 3
Removed item: 2
Head --> 1

Test:

a_list = LinkedList()
a_list.append(1)
a_list.append(2)
a_list.append(3)
print(a_list)
print("Removed item:",a_list.pop())
print("Removed item:",a_list.pop())
print(a_list)

Expected output:

Head --> 1 --> 2 --> 3
Removed item: 3
Removed item: 2
Head --> 1

Recd output:

Head --> 1 --> 2 --> 3
Removed item: 1
Removed item: 2
Head --> 3

Body:
Just track popnode.next when become None and at the same time store previous item, when popnode.next become None, Just put next of prev None, and return data of popnode.next:

def pop(self):  # Problem here
    if self.head is None:
        return None
    elif self.head.next == None:
        d = self.head.data
        self.head = None
        return d
    else:
        popnode = self.head
        prev = popnode
        while popnode.next:
            prev = popnode
            popnode = popnode.next
        prev.next = None
        return popnode.data

The output of:

a_list = LinkedList()
a_list.add(1)
a_list.add(2)
a_list.add(3)
print(a_list)
print("Removed item:", a_list.pop())
print("Removed item:", a_list.pop())
print("Removed item:", a_list.pop())
print(a_list)

Will be:

Head --> 3--> 2--> 1
Removed item: 1
Removed item: 2
Removed item: 3
Head  None


问:
java codility Frog-River-One
I have been trying to solve a Java exercise on a Codility web page.

Below is the link to the mentioned exercise and my solution.

https://codility.com/demo/results/demoH5GMV3-PV8

Can anyone tell what can I correct in my code in order to improve the score?

Just in case here is the task description:

A small frog wants to get to the other side of a river. The frog is currently located at position 0, and wants to get to position X. Leaves fall from a tree onto the surface of the river.

You are given a non-empty zero-indexed array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in minutes.

The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X.

For example, you are given integer X = 5 and array A such that:

```<code>  A[0] = 1
  A[1] = 3
  A[2] = 1
  A[3] = 4
  A[4] = 2
  A[5] = 3
  A[6] = 5
  A[7] = 4
</code>```

In minute 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river.

Write a function:

```<code>class Solution { public int solution(int X, int[] A); }
</code>```

that, given a non-empty zero-indexed array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river.

If the frog is never able to jump to the other side of the river, the function should return −1.

For example, given X = 5 and array A such that:

```<code>  A[0] = 1
  A[1] = 3
  A[2] = 1
  A[3] = 4
  A[4] = 2
  A[5] = 3
  A[6] = 5
  A[7] = 4
</code>```

the function should return 6, as explained above. Assume that:

```<code>N and X are integers within the range [1..100,000];
each element of array A is an integer within the range [1..X].
</code>```

Complexity:

```<code>expected worst-case time complexity is O(N);
expected worst-case space complexity is O(X), beyond input storage (not counting the storage required for input arguments).
</code>```

Elements of input arrays can be modified.

And here is my solution:

```<code>import java.util.ArrayList;
import java.util.List;

class Solution {

    public int solution(int X, int[] A) {
        int list[] = A;
        int sum = 0;
        int searchedValue = X;

        List<Integer> arrayList = new ArrayList<Integer>();

        for (int iii = 0; iii < list.length; iii++) {

            if (list[iii] <= searchedValue && !arrayList.contains(list[iii])) {
                sum += list[iii];
                arrayList.add(list[iii]);
            }
            if (list[iii] == searchedValue) {
                if (sum == searchedValue * (searchedValue + 1) / 2) {
                    return iii;
                }
            }
        }
        return -1;
    }
}
</code>```

答:
in C#</p>
```<code>public static int solution(int X, int[] A)
{
    HashSet<int> hash = new HashSet<int>();

    for (int i = 0; i < A.Length; i++)
    {
        if (A[i] <= X)
        {
            hash.Add(A[i]);

            if (hash.Count == X)
                return i;
        }
    }
    return -1;
}
</code>```

Title: java codility Frog-River-One

Body:
I have been trying to solve a Java exercise on a Codility web page.

Below is the link to the mentioned exercise and my solution.

https://codility.com/demo/results/demoH5GMV3-PV8

Can anyone tell what can I correct in my code in order to improve the score?

Just in case here is the task description:

A small frog wants to get to the other side of a river. The frog is currently located at position 0, and wants to get to position X. Leaves fall from a tree onto the surface of the river.

You are given a non-empty zero-indexed array A consisting of N integers representing the falling leaves. A[K] represents the position where one leaf falls at time K, measured in minutes.

The goal is to find the earliest time when the frog can jump to the other side of the river. The frog can cross only when leaves appear at every position across the river from 1 to X.

For example, you are given integer X = 5 and array A such that:

  A[0] = 1
  A[1] = 3
  A[2] = 1
  A[3] = 4
  A[4] = 2
  A[5] = 3
  A[6] = 5
  A[7] = 4

In minute 6, a leaf falls into position 5. This is the earliest time when leaves appear in every position across the river.

Write a function:

class Solution { public int solution(int X, int[] A); }

that, given a non-empty zero-indexed array A consisting of N integers and integer X, returns the earliest time when the frog can jump to the other side of the river.

If the frog is never able to jump to the other side of the river, the function should return −1.

For example, given X = 5 and array A such that:

  A[0] = 1
  A[1] = 3
  A[2] = 1
  A[3] = 4
  A[4] = 2
  A[5] = 3
  A[6] = 5
  A[7] = 4

the function should return 6, as explained above. Assume that:

N and X are integers within the range [1..100,000];
each element of array A is an integer within the range [1..X].

Complexity:

expected worst-case time complexity is O(N);
expected worst-case space complexity is O(X), beyond input storage (not counting the storage required for input arguments).

Elements of input arrays can be modified.

And here is my solution:

import java.util.ArrayList;
import java.util.List;

class Solution {

    public int solution(int X, int[] A) {
        int list[] = A;
        int sum = 0;
        int searchedValue = X;

        List<Integer> arrayList = new ArrayList<Integer>();

        for (int iii = 0; iii < list.length; iii++) {

            if (list[iii] <= searchedValue && !arrayList.contains(list[iii])) {
                sum += list[iii];
                arrayList.add(list[iii]);
            }
            if (list[iii] == searchedValue) {
                if (sum == searchedValue * (searchedValue + 1) / 2) {
                    return iii;
                }
            }
        }
        return -1;
    }
}

Body:
in C#

public static int solution(int X, int[] A)
{
    HashSet<int> hash = new HashSet<int>();

    for (int i = 0; i < A.Length; i++)
    {
        if (A[i] <= X)
        {
            hash.Add(A[i]);

            if (hash.Count == X)
                return i;
        }
    }
    return -1;
}


问:
json data formatting using pandas
Here, having the input data in this format (json) :

```<code>[
    {
        "timestamp": "2019-05-25T00:00:00",
        "name": "sample_name",
        "keys": ["Field 1", "Field 2", "Field 3", "Field 4", "Field 5", "Field 6"],
        "values": ["value1", "value2", "value3", "value4", "value5", "value6"],
        "is_accepted": false,
    },
    {
        "timestamp": "2018-05-26T00:00:00",
        "name": "sample_name",
        "keys": ["Field 1", "Field 2", "Field 3", "Field 4", "Field 5", "Field 6"],
        "values": ["value11", "value21", "value31", "value41", "value51", "value61"],
        "is_accepted": false,
    }
]
</code>```

and I need to reformat it as per the following

```<code>{
    "info": {
        "timeColumn": "date",
        "name": "sample_name",
        "segments": ["Field 1", "Field 2", "Field 3", "Field 4", "Field 5", "Field 6"]
    },
    "data": [
        {
            "Field 1": "value1",
            "Field 2": "value2",
            "Field 3": "value3",
            "Field 4": "value4",
            "Field 5": "value5",
            "Field 6": "value6",
            "date": "2019-05-25T00:00:00",
            "is_accepted": false
        },
        {
            "Field 1": "value11",
            "Field 2": "value21",
            "Field 3": "value31",
            "Field 4": "value41",
            "Field 5": "value51",
            "Field 6": "value61",
            "date": "2018-05-26T00:00:00",
            "is_accepted": false
        }
    ]
}
</code>```

Need to combine the values into the data field from the input json data. Since I'm a newbie in coding, is there any effective approach that can be adopted here using pandas

答:
You can simply use Python here to reformat your json file, like this:

# Define a helper function
def reformat(input_item):
    output_item = {
        key: value for key, value in zip(input_item["keys"], input_item["values"])
    }
    output_item["date"] = input_item["timestamp"]
    output_item["is_accepted"] = input_item["is_accepted"]
    return output_item

# Build a new dictionary
import json

with open("data.json", "r") as f:
    data = json.load(f)

new_data = {
    "info": {
        "timeColumn": "date",
        "name": "sample_name",
        "segments": ["Field 1", "Field 2", "Field 3", "Field 4", "Field 5", "Field 6"],
    },
    "data": [reformat(input_item) for input_item in data],
}

# Save to a new json file
with open("new_data.json", "w", encoding="utf-8") as f:
    json.dump(new_data, f, ensure_ascii=False, indent=4)
```
<p>In <code>new_data.json</code>, you find the expected result:</p>
<pre class="lang-json prettyprint-override"><code>{
    "info": {
        "timeColumn": "date",
        "name": "sample_name",
        "segments": [
            "Field 1",
            "Field 2",
            "Field 3",
            "Field 4",
            "Field 5",
            "Field 6"
        ]
    },
    "data": [
        {
            "Field 1": "value1",
            "Field 2": "value2",
            "Field 3": "value3",
            "Field 4": "value4",
            "Field 5": "value5",
            "Field 6": "value6",
            "date": "2019-05-25T00:00:00",
            "is_accepted": "false"
        },
        {
            "Field 1": "value11",
            "Field 2": "value21",
            "Field 3": "value31",
            "Field 4": "value41",
            "Field 5": "value51",
            "Field 6": "value61",
            "date": "2018-05-26T00:00:00",
            "is_accepted": "false"
        }
    ]
}
</code>```

Title: json data formatting using pandas

Body:
Here, having the input data in this format (json) :

[
    {
        "timestamp": "2019-05-25T00:00:00",
        "name": "sample_name",
        "keys": ["Field 1", "Field 2", "Field 3", "Field 4", "Field 5", "Field 6"],
        "values": ["value1", "value2", "value3", "value4", "value5", "value6"],
        "is_accepted": false,
    },
    {
        "timestamp": "2018-05-26T00:00:00",
        "name": "sample_name",
        "keys": ["Field 1", "Field 2", "Field 3", "Field 4", "Field 5", "Field 6"],
        "values": ["value11", "value21", "value31", "value41", "value51", "value61"],
        "is_accepted": false,
    }
]

and I need to reformat it as per the following

{
    "info": {
        "timeColumn": "date",
        "name": "sample_name",
        "segments": ["Field 1", "Field 2", "Field 3", "Field 4", "Field 5", "Field 6"]
    },
    "data": [
        {
            "Field 1": "value1",
            "Field 2": "value2",
            "Field 3": "value3",
            "Field 4": "value4",
            "Field 5": "value5",
            "Field 6": "value6",
            "date": "2019-05-25T00:00:00",
            "is_accepted": false
        },
        {
            "Field 1": "value11",
            "Field 2": "value21",
            "Field 3": "value31",
            "Field 4": "value41",
            "Field 5": "value51",
            "Field 6": "value61",
            "date": "2018-05-26T00:00:00",
            "is_accepted": false
        }
    ]
}

Need to combine the values into the data field from the input json data. Since I'm a newbie in coding, is there any effective approach that can be adopted here using pandas

Body:
You can simply use Python here to reformat your json file, like this:

# Define a helper function
def reformat(input_item):
    output_item = {
        key: value for key, value in zip(input_item["keys"], input_item["values"])
    }
    output_item["date"] = input_item["timestamp"]
    output_item["is_accepted"] = input_item["is_accepted"]
    return output_item

# Build a new dictionary
import json

with open("data.json", "r") as f:
    data = json.load(f)

new_data = {
    "info": {
        "timeColumn": "date",
        "name": "sample_name",
        "segments": ["Field 1", "Field 2", "Field 3", "Field 4", "Field 5", "Field 6"],
    },
    "data": [reformat(input_item) for input_item in data],
}

# Save to a new json file
with open("new_data.json", "w", encoding="utf-8") as f:
    json.dump(new_data, f, ensure_ascii=False, indent=4)

In new_data.json, you find the expected result:

{
    "info": {
        "timeColumn": "date",
        "name": "sample_name",
        "segments": [
            "Field 1",
            "Field 2",
            "Field 3",
            "Field 4",
            "Field 5",
            "Field 6"
        ]
    },
    "data": [
        {
            "Field 1": "value1",
            "Field 2": "value2",
            "Field 3": "value3",
            "Field 4": "value4",
            "Field 5": "value5",
            "Field 6": "value6",
            "date": "2019-05-25T00:00:00",
            "is_accepted": "false"
        },
        {
            "Field 1": "value11",
            "Field 2": "value21",
            "Field 3": "value31",
            "Field 4": "value41",
            "Field 5": "value51",
            "Field 6": "value61",
            "date": "2018-05-26T00:00:00",
            "is_accepted": "false"
        }
    ]
}


问:
(Python)Unable to import excel file using colab
i have tried to import an excel csv file from my local disk but failed

```<code>import pandas as pd
df=pd.read_csv(r'C:/Users/Username/Desktop/da/SeoulBikeData.csv',encoding="gbk")
print("df")
</code>```

error:

```<code>FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/Username/Desktop/da/SeoulBikeData.csv'
</code>```

答: You cannot import local directory excel files directly in Google collab. You have to upload the excel file in the Collab directory and then you can import it.</p>

Body:
i have tried to import an excel csv file from my local disk but failed

import pandas as pd
df=pd.read_csv(r'C:/Users/Username/Desktop/da/SeoulBikeData.csv',encoding="gbk")
print("df")

error:

FileNotFoundError: [Errno 2] No such file or directory: 'C:/Users/Username/Desktop/da/SeoulBikeData.csv'


问:
Swipe features in android studio
If I swipe left to right or right to left, then I swipe up or down without releasing finger  swiping up or down occurred on Scroll Gesture. But I don't want to occur this. I want if am swiping horizontally only horizontal swiping should work not vertical without release finger. I don't know how doing that in android studio, If anyone can help, please help me, thanks in advance.

I have already tried, but can't solve the above problem.

override fun onScroll(event: MotionEvent?, event1: MotionEvent?, distanceX: Float, distanceY: Float): Boolean {

```<code>    val sWidth = Resources.getSystem().displayMetrics.widthPixels
    val sHeight = Resources.getSystem().displayMetrics.heightPixels

    val border = 100 * Resources.getSystem().displayMetrics.density.toInt()
    if(event!!.x < border || event.y < border || event.x > sWidth - border || event.y > sHeight - border)
        return false

    if(abs(distanceX) < abs(distanceY)){
        if(event.x < sWidth/2){
            //brightness
            // left side up and down
        }
        else{
            //volume
            // right side up and down

    }if (distanceY > distanceX){

       If (distance Y > 0){
            // left to right swipe
      }else{
        // right to left swipe
        }
   }

    return true
}
</code>```

When I swipe up and down. Left or Right swipe also occur.

答:
Check my answer for a question related to a RecyclerView in a ViewPager. This problem might be similar to yours.

Link to the answer

The answer gives priority to the view which you want to scroll and nothing else!

Title: Swipe features in android studio

Body:
If I swipe left to right or right to left, then I swipe up or down without releasing finger  swiping up or down occurred on Scroll Gesture. But I don't want to occur this. I want if am swiping horizontally only horizontal swiping should work not vertical without release finger. I don't know how doing that in android studio, If anyone can help, please help me, thanks in advance.

I have already tried, but can't solve the above problem.

override fun onScroll(event: MotionEvent?, event1: MotionEvent?, distanceX: Float, distanceY: Float): Boolean {

    val sWidth = Resources.getSystem().displayMetrics.widthPixels
    val sHeight = Resources.getSystem().displayMetrics.heightPixels

    val border = 100 * Resources.getSystem().displayMetrics.density.toInt()
    if(event!!.x < border || event.y < border || event.x > sWidth - border || event.y > sHeight - border)
        return false

    if(abs(distanceX) < abs(distanceY)){
        if(event.x < sWidth/2){
            //brightness
            // left side up and down
        }
        else{
            //volume
            // right side up and down

    }if (distanceY > distanceX){

       If (distance Y > 0){
            // left to right swipe
      }else{
        // right to left swipe
        }
   }

    return true
}

When I swipe up and down. Left or Right swipe also occur.


问:
Recursion forEach does not update my values? using Javascript
I need to update my values with recursion but my loop no work?
First check code:

```<code>  const minusItem = (items) => {
    console.log("items", items);
    if (items.length > 0) {
      items.forEach((orgUnit) => {
        orgUnit.dashCheck = true;
        orgUnit.allChildItemChecked = false;
        if (orgUnit.parentNode.unitId) {
          minusItem(orgUnit.parentNode); //recursion
        }
      });
    }
  };
</code>```

items is array but worst of all sometimes an object is sent but there is an if that says

items.length > 0

here I filter only strings that have length> 0

array is like

```<code>[
 {
 unitId: 1 ,
 title: "Test 1 " ,
 dashCheck: false,
 allChildItemChecked: false
 parentNode: {
    unitId: 2 ,
    title: "Test 2" ,
    dashCheck: false,
    allChildItemChecked: false,
    parentNode: {
       unitId: 3 ,
       title: "Test 3" ,
       dashCheck: false,
       allChildItemChecked: false,
        }
      }
   }
]
</code>```

of these parentNode can have 100....

I need to loop thought each and set

```<code>    orgUnit.dashCheck = true;
    orgUnit.allChildItemChecked = false;
</code>```

答:
Lodash cloneDeepWith if you don't mind

const data = [{unitId: 1 ,title:"Test 1 ",dashCheck: false,allChildItemChecked:false,parentNode:{unitId:2,title:"Test 2" ,dashCheck:false,allChildItemChecked:false,parentNode:{unitId:3 ,title:"Test 3",dashCheck:false,allChildItemChecked:false}}}];

const result = _.cloneDeepWith(data, (val, key) => {
    if (key === 'dashCheck') return true;
    if (key === 'allChildItemChecked') return false;
});

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

```

Body:
I need to update my values with recursion but my loop no work?
First check code:

  const minusItem = (items) => {
    console.log("items", items);
    if (items.length > 0) {
      items.forEach((orgUnit) => {
        orgUnit.dashCheck = true;
        orgUnit.allChildItemChecked = false;
        if (orgUnit.parentNode.unitId) {
          minusItem(orgUnit.parentNode); //recursion
        }
      });
    }
  };

items is array but worst of all sometimes an object is sent but there is an if that says

items.length > 0

here I filter only strings that have length> 0

array is like

[
 {
 unitId: 1 ,
 title: "Test 1 " ,
 dashCheck: false,
 allChildItemChecked: false
 parentNode: {
    unitId: 2 ,
    title: "Test 2" ,
    dashCheck: false,
    allChildItemChecked: false,
    parentNode: {
       unitId: 3 ,
       title: "Test 3" ,
       dashCheck: false,
       allChildItemChecked: false,
        }
      }
   }
]

of these parentNode can have 100....

I need to loop thought each and set

    orgUnit.dashCheck = true;
    orgUnit.allChildItemChecked = false;

Body:
Lodash cloneDeepWith if you don't mind

const data = [{unitId: 1 ,title:"Test 1 ",dashCheck: false,allChildItemChecked:false,parentNode:{unitId:2,title:"Test 2" ,dashCheck:false,allChildItemChecked:false,parentNode:{unitId:3 ,title:"Test 3",dashCheck:false,allChildItemChecked:false}}}];

const result = _.cloneDeepWith(data, (val, key) => {
    if (key === 'dashCheck') return true;
    if (key === 'allChildItemChecked') return false;
});

console.log(result);

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

<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>


问:
How to remove accents and all chars <> a..z in sql-server?
I need to do the following modifications to a varchar(20) field:

substitute accents with normal letters (like è to e)

after (1) remove all the chars not in a..z

for example

```<code>'aèàç=.32s df'
</code>```

must become

```<code>'aeacsdf'
</code>```

are there special stored functions to achieve this easily?

UPDATE: please provide a T-SQL not CLR solution. This is the workaround I temporarly did because it temporarly suits my needs, anyway using a more elegant approach would be better.

```<code>CREATE FUNCTION sf_RemoveExtraChars (@NAME nvarchar(50))
RETURNS nvarchar(50)
AS
BEGIN
  declare @TempString nvarchar(100)
  set @TempString = @NAME
  set @TempString = LOWER(@TempString)
  set @TempString =  replace(@TempString,' ', '')
  set @TempString =  replace(@TempString,'à', 'a')
  set @TempString =  replace(@TempString,'è', 'e')
  set @TempString =  replace(@TempString,'é', 'e')
  set @TempString =  replace(@TempString,'ì', 'i')
  set @TempString =  replace(@TempString,'ò', 'o')
  set @TempString =  replace(@TempString,'ù', 'u')
  set @TempString =  replace(@TempString,'ç', 'c')
  set @TempString =  replace(@TempString,'''', '')
  set @TempString =  replace(@TempString,'`', '')
  set @TempString =  replace(@TempString,'-', '')
  return @TempString
END
GO
</code>```

答:
Simplified with:</p>
```<code>CREATE OR ALTER FUNCTION F_CLEAN_ACCENT_STRING(@NAME NVARCHAR(128))
RETURNS NVARCHAR(128)
AS
BEGIN
   DECLARE @OUT NVARCHAR(128) = '', @I TINYINT = 1, @C CHAR(1);
   WHILE @I <= LEN(@NAME)
   BEGIN
      IF @C NOT LIKE '[A-Z0-9_]' COLLATE French_CI_AI
         SET @OUT = @OUT + '_';
      ELSE
         SET @OUT = @OUT + CHAR(ASCII(SUBSTRING(@NAME, @I, 1) COLLATE SQL_Latin1_General_CP1253_CI_AI));
      SET @I += 1;
   END;
   RETURN @OUT;
END;
GO

SELECT dbo.F_CLEAN_ACCENT_STRING('Électricîté de Fränce') AS UNACCENT;

UNACCENT
----------------------
Electricite de France
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I need to do the following modifications to a varchar(20) field:

substitute accents with normal letters (like è to e)

after (1) remove all the chars not in a..z

for example

'aèàç=.32s df'

must become

'aeacsdf'

are there special stored functions to achieve this easily?

UPDATE: please provide a T-SQL not CLR solution. This is the workaround I temporarly did because it temporarly suits my needs, anyway using a more elegant approach would be better.

CREATE FUNCTION sf_RemoveExtraChars (@NAME nvarchar(50))
RETURNS nvarchar(50)
AS
BEGIN
  declare @TempString nvarchar(100)
  set @TempString = @NAME
  set @TempString = LOWER(@TempString)
  set @TempString =  replace(@TempString,' ', '')
  set @TempString =  replace(@TempString,'à', 'a')
  set @TempString =  replace(@TempString,'è', 'e')
  set @TempString =  replace(@TempString,'é', 'e')
  set @TempString =  replace(@TempString,'ì', 'i')
  set @TempString =  replace(@TempString,'ò', 'o')
  set @TempString =  replace(@TempString,'ù', 'u')
  set @TempString =  replace(@TempString,'ç', 'c')
  set @TempString =  replace(@TempString,'''', '')
  set @TempString =  replace(@TempString,'`', '')
  set @TempString =  replace(@TempString,'-', '')
  return @TempString
END
GO

Body:
Simplified with:

CREATE OR ALTER FUNCTION F_CLEAN_ACCENT_STRING(@NAME NVARCHAR(128))
RETURNS NVARCHAR(128)
AS
BEGIN
   DECLARE @OUT NVARCHAR(128) = '', @I TINYINT = 1, @C CHAR(1);
   WHILE @I <= LEN(@NAME)
   BEGIN
      IF @C NOT LIKE '[A-Z0-9_]' COLLATE French_CI_AI
         SET @OUT = @OUT + '_';
      ELSE
         SET @OUT = @OUT + CHAR(ASCII(SUBSTRING(@NAME, @I, 1) COLLATE SQL_Latin1_General_CP1253_CI_AI));
      SET @I += 1;
   END;
   RETURN @OUT;
END;
GO

SELECT dbo.F_CLEAN_ACCENT_STRING('Électricîté de Fränce') AS UNACCENT;

UNACCENT
----------------------
Electricite de France


问:
Window based averages based on ranges within another table
I have a table that has positions like so:

```<code>create or replace table data (
  pos int not null,
  val float not null,
  constraint data_pk primary key (pos)
);
</code>```

And, a ranges type table like so:

```<code>create or replace table ranges (
  label varchar(32) not null,
  left int not null,
  right int not null,
  constraint ranges_pk primary key (label)
);
</code>```

with ranges like

```<code>        ('alpha', 11, 13),
        ('bravo', 11, 14),
        ('charlie', 11, 15),
        ('echo', 12, 18),
        ('delta', 12, 19),
        ('foxtrot', 13, 20)
</code>```

for each label, I need to lookup every possible 3 subrange within the "data" table, take these 3 subrange averages, and then average them...

I couldn't think of a good way to describe what I'm after, so I thought I'd show what I'd expect for 'charlie':

The results for charlie in the select should be:

```<code>    ('charlie', 40.111), -- avg(avg(data[pos=11], data[pos=12], data[pos=13]), avg(data[pos=12], data[pos=13], data[pos=14]), avg(data[pos=13], data[pos=14], data[pos=15]))
                         -- -> avg(avg(31, 37, 41), avg(37, 41, 43), avg(41, 43, 47))
                         -- -> avg(36.333, 40.333, 43.667) -> 40.111
</code>```

(for data like)

```<code>insert into data (pos, val) values
    (1, 2), (2, 3), (3, 5), (4, 7), (5, 11), (6, 13), (7, 17), (8, 19),
    (9, 23), (10, 29), (11, 31), (12, 37), (13, 41), (14, 43), (15, 47), (16, 53),
    (17, 59), (18, 61), (19, 67), (20, 71), (21, 73), (22, 79), (23, 83), (24, 89),
    (25, 97), (26, 101), (27, 103), (28, 107), (29, 109), (30, 113), (31, 127), (32, 131),
    (33, 137), (34, 139), (35, 149), (36, 151), (37, 157), (38, 163), (39, 167), (40, 173),
    (41, 179), (42, 181), (43, 191), (44, 193), (45, 197), (46, 199), (47, 211), (48, 223),
    (49, 227), (50, 229), (51, 233), (52, 239), (53, 241), (54, 251);
</code>```

Is there a way to do this within Snowflake SQL? Or must I resort to python to do this? If it helps I made a gist with more data..

Thanks!

Body:
I have a table that has positions like so:

create or replace table data (
  pos int not null,
  val float not null,
  constraint data_pk primary key (pos)
);

And, a ranges type table like so:

create or replace table ranges (
  label varchar(32) not null,
  left int not null,
  right int not null,
  constraint ranges_pk primary key (label)
);

with ranges like

        ('alpha', 11, 13),
        ('bravo', 11, 14),
        ('charlie', 11, 15),
        ('echo', 12, 18),
        ('delta', 12, 19),
        ('foxtrot', 13, 20)

for each label, I need to lookup every possible 3 subrange within the "data" table, take these 3 subrange averages, and then average them...

I couldn't think of a good way to describe what I'm after, so I thought I'd show what I'd expect for 'charlie':

The results for charlie in the select should be:

    ('charlie', 40.111), -- avg(avg(data[pos=11], data[pos=12], data[pos=13]), avg(data[pos=12], data[pos=13], data[pos=14]), avg(data[pos=13], data[pos=14], data[pos=15]))
                         -- -> avg(avg(31, 37, 41), avg(37, 41, 43), avg(41, 43, 47))
                         -- -> avg(36.333, 40.333, 43.667) -> 40.111

(for data like)

insert into data (pos, val) values
    (1, 2), (2, 3), (3, 5), (4, 7), (5, 11), (6, 13), (7, 17), (8, 19),
    (9, 23), (10, 29), (11, 31), (12, 37), (13, 41), (14, 43), (15, 47), (16, 53),
    (17, 59), (18, 61), (19, 67), (20, 71), (21, 73), (22, 79), (23, 83), (24, 89),
    (25, 97), (26, 101), (27, 103), (28, 107), (29, 109), (30, 113), (31, 127), (32, 131),
    (33, 137), (34, 139), (35, 149), (36, 151), (37, 157), (38, 163), (39, 167), (40, 173),
    (41, 179), (42, 181), (43, 191), (44, 193), (45, 197), (46, 199), (47, 211), (48, 223),
    (49, 227), (50, 229), (51, 233), (52, 239), (53, 241), (54, 251);

Is there a way to do this within Snowflake SQL? Or must I resort to python to do this? If it helps I made a gist with more data..

Thanks!

Body:
Here is a step by step answer:

WITH data(pos, val) AS (
    SELECT * FROM VALUES
      (1, 2), (2, 3), (3, 5), (4, 7), (5, 11), (6, 13), (7, 17), (8, 19),
      (9, 23), (10, 29), (11, 31), (12, 37), (13, 41), (14, 43), (15, 47), (16, 53),
      (17, 59), (18, 61), (19, 67), (20, 71), (21, 73), (22, 79), (23, 83), (24, 89),
      (25, 97), (26, 101), (27, 103), (28, 107), (29, 109), (30, 113), (31, 127), (32, 131),
      (33, 137), (34, 139), (35, 149), (36, 151), (37, 157), (38, 163), (39, 167), (40, 173),
      (41, 179), (42, 181), (43, 191), (44, 193), (45, 197), (46, 199), (47, 211), (48, 223),
      (49, 227), (50, 229), (51, 233), (52, 239), (53, 241), (54, 251)
), codes(name,s_val, e_val) AS (
     SELECT * FROM VALUES
        ('alpha', 11, 13),
        ('bravo', 11, 14),
        ('charlie', 11, 15),
        ('echo', 12, 18),
        ('delta', 12, 19),
        ('foxtrot', 13, 20)
), ranges as (
    SELECT row_number() over (order by null)-1 as seq
    FROM table(generator(rowcount => 200))
), boost_codes AS (
    select c.name
      ,c.s_val + r.seq + 0 as b1
      ,c.s_val + r.seq + 2 as b3
    from codes as c
    join ranges as r
      ON r.seq <= (e_val - s_val - 2)
), almost_there AS (
    select
       bc.name
       ,avg(d.val) as partial
    from boost_codes as bc
    join data as d ON d.pos between bc.b1 and bc.b3
    GROUP BY 1, bc.b1
)
SELECT name
    ,round(avg(partial),3) as output
FROM almost_there
GROUP BY 1
ORDER BY 1;

which gives:

NAME
OUTPUT

alpha
36.333

bravo
38.333

charlie
40.111

delta
50.778

echo
48.467

foxtrot
55.111


问:
W3.CSS and Javascript navigation bar Issue
I built a simple website for my business in w3.css from w3schools.com; https://www.housewashingdelmarva.com/

However, when the website is reduced to mobile phone size and the navigation goes to the 3 stacked bars, I can't get it to click and lower the menu. I believe it's a javascript issue. But I am mostly a front-end CSS and HTML designer. Not sure what I have mistakenly done wrong as I have built two other similar sites that work fine mobile-wise and can't see the difference in the code.

If any javascript coders or w3.css designers notice my mistake, I would appreciate your help.

Thx!

答:
You forgot to add 'demo' id in myFunction during onClick event on Hamburger icon. Click here to see the image where the problem is highlighted.</p>
```<code><div class="w3-bar w3-theme-d3 w3-round-xxlarge">
    <a class="w3-bar-item w3-button w3-hover-cyan" href="https://www.housewashingdelmarva.com/">Home</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Services">Services</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Testimonials">Testimonials</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Gallery">Gallery</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Area-Partners">Our Area Partners</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#FAQ">FAQ</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Service-Area">Service Area</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#About-Us">About Us</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Contact-Us">Contact Us</a>
    <a href="javascript:void(0)" class="w3-bar-item w3-button w3-right w3-hide-large w3-hover-cyan w3-hide-medium" onclick="myFunction('demo')">☰</a>
</div>
</code>```

Body:
You forgot to add 'demo' id in myFunction during onClick event on Hamburger icon. Click here to see the image where the problem is highlighted.

<div class="w3-bar w3-theme-d3 w3-round-xxlarge">
    <a class="w3-bar-item w3-button w3-hover-cyan" href="https://www.housewashingdelmarva.com/">Home</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Services">Services</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Testimonials">Testimonials</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Gallery">Gallery</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Area-Partners">Our Area Partners</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#FAQ">FAQ</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Service-Area">Service Area</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#About-Us">About Us</a>
    <a class="w3-bar-item w3-button w3-hover-cyan w3-hide-small" href="#Contact-Us">Contact Us</a>
    <a href="javascript:void(0)" class="w3-bar-item w3-button w3-right w3-hide-large w3-hover-cyan w3-hide-medium" onclick="myFunction('demo')">☰</a>
</div>


问:
Strapi V4 Next js [slug].js is not working getStaticPaths() getStaticProps()
I develop with Strapi V4 and Next

migrating V3 to V4

[slug].js this file was happened error

I don't know the reasons

enter image description here

enter image description here

答:
maybe try adding the .attributes on line 62 and .data on line 78, check what you get from the fetch call</p>
```<code>62 - evt.attributes.slug

78 - events.data[0]
</code>```

Body:
maybe try adding the .attributes on line 62 and .data on line 78, check what you get from the fetch call

62 - evt.attributes.slug

78 - events.data[0]


问:
The point within the range of rectangle
In easy English can someone please explain to me this line of code.</p>
```<code>public bool IsAt(Point2D pt)
    {
        return (pt.X > Width && pt.X < Width + X && pt.Y > Height && pt.Y < Height + Y);
    }
</code>```

答:
I'd expect the next logic:

```<code>pt.X > X && pt.X < X + Width && pt.Y > Y && pt.Y < Y + Height
</code>```

assuming X,Y is bottom left corner (when OY is up).

In your code variable naming is too strange.

Title: The point within the range of rectangle

Body:
In easy English can someone please explain to me this line of code.

public bool IsAt(Point2D pt)
    {
        return (pt.X > Width && pt.X < Width + X && pt.Y > Height && pt.Y < Height + Y);
    }

Body:
I'd expect the next logic:

pt.X > X && pt.X < X + Width && pt.Y > Y && pt.Y < Y + Height

assuming X,Y is bottom left corner (when OY is up).

In your code variable naming is too strange.


问:
accessing host machine from a pod running on a kind cluster
I'm running a kind cluster and from one of the pods I need to access the host machine.  I know in minikube you can access it using 10.0.0.2 is there some way I can access it, the same way I could use host.docker.internal on Docker Desktop?

答:
Docker uses default subdomain 172.17.0.0/16, and assign the pods IP address 172.17.X.X

Host server can be access using ip address 172.17.0.1


问:
Using CD74HC4067 16-Channel Analog Multiplexer Demultiplexer is not working as expected
I am working on a project that needs multiple digital signals and I am considering the CD74HC4067 (on a break-board) to work as a multiplexer. More specifically i am trying to build a keypad with multiple ttp123 break-boards. Each ttp123 signal is connected to one of the 0-15 pins of the CD74HC4067. The S0-S3 pins are connected to digital Pins 7-4 on a pro mini. Signal is on A0 and EN is on A1. A1 and EN have a 4K7 resistor to ground. I power the setup with a separate 5v and the arduino is connected on a pc usb port.

I expect when a ttp123 is pressed to trigger a HIGH and this event to be passed to SIG pin.
Here is my code:

```<code>//Using CD74HC4067 16-Channel Analog Multiplexer
//Mux control pins

int s0 = 6;
int s1 = 7;
int s2 = 8;
int s3 = 9;

//Mux in "SIG" pin
int SIG_pin = A0;
int EN_pin  = A1;

void setup(){
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);
  pinMode(EN_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
  digitalWrite(EN_pin, LOW);

  Serial.begin(9600);
  Serial.println("keypad interfacing_CD74HC4067 starting...");
}

void loop(){
  String a;
  //digitalWrite(EN_pin, HIGH);
  Serial.println(" press any key to continue ...");
  //digitalWrite(EN_pin, LOW);
  while (!Serial.available());
  while(Serial.available()) {

  //Loop through and read all 16 values
  for(int i = 0; i < 16; i ++){
    //Serial.print("Value at channel ");
    //Serial.print(i);
    //Serial.print("is : ");
    //Serial.println(readMux(i));

      float volts = readMux(i);

      Serial.print("Value at channel ");
      Serial.print(i);
      Serial.print(" is : ");
      Serial.print(volts);
      Serial.println();

    //delay(1000);
  }
  a= Serial.readString();// read the incoming data as string
}
}
float readMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[16][4]={
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
    {0,1,0,1}, //channel 10
    {1,1,0,1}, //channel 11
    {0,0,1,1}, //channel 12
    {1,0,1,1}, //channel 13
    {0,1,1,1}, //channel 14
    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig

  for(int j = 0; j < 4; j ++){
    digitalWrite(controlPin[j], muxChannel[channel][j]);
  }
  //read the value at the SIG pin
  int val = analogRead(SIG_pin);

  //return the value
  float voltage = (val * 5) / 1024.0;
  return voltage;
}
</code>```

Just for simplicity, I have connected only one ttp123 on the system, ttp123 signal to channel12 on 74HC4067. With ttp123 touched, I would expect to get a high on SIG when I write
{0,0,1,1}, to S0-S3. All other channels should be LOW. However here is what I get:

On my first run after boot:

```<code> press any key to continue ...
Value at channel 0 is : 2.53
Value at channel 1 is : 2.58
Value at channel 2 is : 2.53
Value at channel 3 is : 2.60
Value at channel 4 is : 2.51
Value at channel 5 is : 2.55
Value at channel 6 is : 2.50
Value at channel 7 is : 2.52
Value at channel 8 is : 2.42
Value at channel 9 is : 2.47
Value at channel 10 is : 2.43
Value at channel 11 is : 2.50
Value at channel 12 is : 2.40
Value at channel 13 is : 2.43
Value at channel 14 is : 2.38
Value at channel 15 is : 2.44
</code>```

and then all channels seem to lower...

```<code> press any key to continue ...
Value at channel 0 is : 1.70
Value at channel 1 is : 1.76
Value at channel 2 is : 1.71
Value at channel 3 is : 1.78
Value at channel 4 is : 1.70
Value at channel 5 is : 1.76
Value at channel 6 is : 1.72
Value at channel 7 is : 1.77
Value at channel 8 is : 1.67
Value at channel 9 is : 1.72
Value at channel 10 is : 1.69
Value at channel 11 is : 1.76
Value at channel 12 is : 1.69
Value at channel 13 is : 1.73
Value at channel 14 is : 1.67
Value at channel 15 is : 1.74
</code>```

and I get no HIGH on channel 12 as I should.

Is there a need for a pullup or pulldown resistors in this setup? Should I connect a resistor to each S0-S3 with ground? Why is this not working?

答:
Since there was an elementary failure in the code as well I would like to post the solution in here:

I had failed to initialize the A0 pin as input:

pinMode(SIG_pin, INPUT);

Here is the working set of code:

```<code>// interfacing mux with tp223

//Mux control pins

const int s0 = 6;
const int s1 = 7;
const int s2 = 8;
const int s3 = 9;

//Mux in "SIG" pin
int SIG_pin = A0;
int EN_pin  = 10;

void setup(){
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);
  pinMode(SIG_pin, INPUT);
  pinMode(EN_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
  digitalWrite(EN_pin, LOW);

  Serial.begin(115200);
  Serial.println("keypad interfacing_CD74HC4067 starting...");
}

void loop(){

  //Loop through and read all 16 values
  for(int i = 0; i < 16; i ++){
      int val = readMux(i);

      if (val > 0) {
        Serial.print(i);
        Serial.print(" pressed ");
        Serial.print(val);
        Serial.println();
      }
  }

}
float readMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[16][4]={
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
    {0,1,0,1}, //channel 10
    {1,1,0,1}, //channel 11
    {0,0,1,1}, //channel 12
    {1,0,1,1}, //channel 13
    {0,1,1,1}, //channel 14
    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int j = 0; j < 4; j ++){
    digitalWrite(controlPin[j], muxChannel[channel][j]);
  }
  //read the value at the SIG pin
  int val = digitalRead(SIG_pin);
  //return the value
  return val;
}
</code>```

I would like to mention that there was a cabling issue as well. I pulled down the signal pin with a 10k resistor.

Body:
I am working on a project that needs multiple digital signals and I am considering the CD74HC4067 (on a break-board) to work as a multiplexer. More specifically i am trying to build a keypad with multiple ttp123 break-boards. Each ttp123 signal is connected to one of the 0-15 pins of the CD74HC4067. The S0-S3 pins are connected to digital Pins 7-4 on a pro mini. Signal is on A0 and EN is on A1. A1 and EN have a 4K7 resistor to ground. I power the setup with a separate 5v and the arduino is connected on a pc usb port.

I expect when a ttp123 is pressed to trigger a HIGH and this event to be passed to SIG pin.
Here is my code:

//Using CD74HC4067 16-Channel Analog Multiplexer
//Mux control pins

int s0 = 6;
int s1 = 7;
int s2 = 8;
int s3 = 9;

//Mux in "SIG" pin
int SIG_pin = A0;
int EN_pin  = A1;

void setup(){
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);
  pinMode(EN_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
  digitalWrite(EN_pin, LOW);

  Serial.begin(9600);
  Serial.println("keypad interfacing_CD74HC4067 starting...");
}

void loop(){
  String a;
  //digitalWrite(EN_pin, HIGH);
  Serial.println(" press any key to continue ...");
  //digitalWrite(EN_pin, LOW);
  while (!Serial.available());
  while(Serial.available()) {

  //Loop through and read all 16 values
  for(int i = 0; i < 16; i ++){
    //Serial.print("Value at channel ");
    //Serial.print(i);
    //Serial.print("is : ");
    //Serial.println(readMux(i));

      float volts = readMux(i);

      Serial.print("Value at channel ");
      Serial.print(i);
      Serial.print(" is : ");
      Serial.print(volts);
      Serial.println();

    //delay(1000);
  }
  a= Serial.readString();// read the incoming data as string
}
}
float readMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[16][4]={
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
    {0,1,0,1}, //channel 10
    {1,1,0,1}, //channel 11
    {0,0,1,1}, //channel 12
    {1,0,1,1}, //channel 13
    {0,1,1,1}, //channel 14
    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig

  for(int j = 0; j < 4; j ++){
    digitalWrite(controlPin[j], muxChannel[channel][j]);
  }
  //read the value at the SIG pin
  int val = analogRead(SIG_pin);

  //return the value
  float voltage = (val * 5) / 1024.0;
  return voltage;
}

Just for simplicity, I have connected only one ttp123 on the system, ttp123 signal to channel12 on 74HC4067. With ttp123 touched, I would expect to get a high on SIG when I write
{0,0,1,1}, to S0-S3. All other channels should be LOW. However here is what I get:

On my first run after boot:

 press any key to continue ...
Value at channel 0 is : 2.53
Value at channel 1 is : 2.58
Value at channel 2 is : 2.53
Value at channel 3 is : 2.60
Value at channel 4 is : 2.51
Value at channel 5 is : 2.55
Value at channel 6 is : 2.50
Value at channel 7 is : 2.52
Value at channel 8 is : 2.42
Value at channel 9 is : 2.47
Value at channel 10 is : 2.43
Value at channel 11 is : 2.50
Value at channel 12 is : 2.40
Value at channel 13 is : 2.43
Value at channel 14 is : 2.38
Value at channel 15 is : 2.44

and then all channels seem to lower...

 press any key to continue ...
Value at channel 0 is : 1.70
Value at channel 1 is : 1.76
Value at channel 2 is : 1.71
Value at channel 3 is : 1.78
Value at channel 4 is : 1.70
Value at channel 5 is : 1.76
Value at channel 6 is : 1.72
Value at channel 7 is : 1.77
Value at channel 8 is : 1.67
Value at channel 9 is : 1.72
Value at channel 10 is : 1.69
Value at channel 11 is : 1.76
Value at channel 12 is : 1.69
Value at channel 13 is : 1.73
Value at channel 14 is : 1.67
Value at channel 15 is : 1.74

and I get no HIGH on channel 12 as I should.

Is there a need for a pullup or pulldown resistors in this setup? Should I connect a resistor to each S0-S3 with ground? Why is this not working?

Body:
Since there was an elementary failure in the code as well I would like to post the solution in here:

I had failed to initialize the A0 pin as input:

pinMode(SIG_pin, INPUT);

Here is the working set of code:

// interfacing mux with tp223

//Mux control pins

const int s0 = 6;
const int s1 = 7;
const int s2 = 8;
const int s3 = 9;

//Mux in "SIG" pin
int SIG_pin = A0;
int EN_pin  = 10;

void setup(){
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);
  pinMode(SIG_pin, INPUT);
  pinMode(EN_pin, OUTPUT);

  digitalWrite(s0, LOW);
  digitalWrite(s1, LOW);
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
  digitalWrite(EN_pin, LOW);

  Serial.begin(115200);
  Serial.println("keypad interfacing_CD74HC4067 starting...");
}

void loop(){

  //Loop through and read all 16 values
  for(int i = 0; i < 16; i ++){
      int val = readMux(i);

      if (val > 0) {
        Serial.print(i);
        Serial.print(" pressed ");
        Serial.print(val);
        Serial.println();
      }
  }

}
float readMux(int channel){
  int controlPin[] = {s0, s1, s2, s3};

  int muxChannel[16][4]={
    {0,0,0,0}, //channel 0
    {1,0,0,0}, //channel 1
    {0,1,0,0}, //channel 2
    {1,1,0,0}, //channel 3
    {0,0,1,0}, //channel 4
    {1,0,1,0}, //channel 5
    {0,1,1,0}, //channel 6
    {1,1,1,0}, //channel 7
    {0,0,0,1}, //channel 8
    {1,0,0,1}, //channel 9
    {0,1,0,1}, //channel 10
    {1,1,0,1}, //channel 11
    {0,0,1,1}, //channel 12
    {1,0,1,1}, //channel 13
    {0,1,1,1}, //channel 14
    {1,1,1,1}  //channel 15
  };

  //loop through the 4 sig
  for(int j = 0; j < 4; j ++){
    digitalWrite(controlPin[j], muxChannel[channel][j]);
  }
  //read the value at the SIG pin
  int val = digitalRead(SIG_pin);
  //return the value
  return val;
}

I would like to mention that there was a cabling issue as well. I pulled down the signal pin with a 10k resistor.


问:
BASHRC PS1 show datetime but plus 3 hours
Every of us set own convenience working with Linux shell, for example I use
/root/.bashrc

```<code>PS1='[\h:\w] \D{%F %T}\n\$ '
</code>```

to show servername + current server datetime + newline for command - so it looks like

```<code>[servername217:~] 2022-02-06 00:55:02
#
</code>```

But I met a stumbling block with syntax trying to set not server time, but my home, for example plus 3 hours. It's easy to make with regular BASH

```<code>date -d '+ 3 hour' '+%F %T'
</code>```

but when I try to use, for example,

```<code>PS1='[\h:\w] [date -d '+ 3 hour' '+%F %T']\n\$ '
</code>```

I always get an error. It seems PS1 understands only

```<code>\D{%F %T}
</code>```

but how to add 3 hours to %T under this format ? Or there is an another way ?

答:
It's a bit too heavyweight to use the external date command. If you have Bash 4.3+ you can use the builtin printf %(fmt)T:

$ cat ps1
NOW_PLUS_3_HOURS=''

function _prompt_command()
{
    local secs

    printf -v secs '%(%s)T'
    (( secs += 3 * 3600 ))
    printf -v NOW_PLUS_3_HOURS '%(%F %T)T' $secs
}

PROMPT_COMMAND=_prompt_command
PS1='[$NOW_PLUS_3_HOURS] $ '
$ date +'%F %T'
2022-02-06 16:37:02
$ source ./ps1
[2022-02-06 19:37:06] $
[2022-02-06 19:37:11] $
```

And by using the PROMPT_COMMAND you can do a lot more interesting things.

Body:
Every of us set own convenience working with Linux shell, for example I use
/root/.bashrc

PS1='[\h:\w] \D{%F %T}\n\$ '

to show servername + current server datetime + newline for command - so it looks like

[servername217:~] 2022-02-06 00:55:02
#

But I met a stumbling block with syntax trying to set not server time, but my home, for example plus 3 hours. It's easy to make with regular BASH

date -d '+ 3 hour' '+%F %T'

but when I try to use, for example,

PS1='[\h:\w] [date -d '+ 3 hour' '+%F %T']\n\$ '

I always get an error. It seems PS1 understands only

\D{%F %T}

but how to add 3 hours to %T under this format ? Or there is an another way ?

Body:
It's a bit too heavyweight to use the external date command. If you have Bash 4.3+ you can use the builtin printf %(fmt)T:

$ cat ps1
NOW_PLUS_3_HOURS=''

function _prompt_command()
{
    local secs

    printf -v secs '%(%s)T'
    (( secs += 3 * 3600 ))
    printf -v NOW_PLUS_3_HOURS '%(%F %T)T' $secs
}

PROMPT_COMMAND=_prompt_command
PS1='[$NOW_PLUS_3_HOURS] $ '
$ date +'%F %T'
2022-02-06 16:37:02
$ source ./ps1
[2022-02-06 19:37:06] $
[2022-02-06 19:37:11] $

And by using the PROMPT_COMMAND you can do a lot more interesting things.


问:
Removing logging with ProGuard doesn't remove the strings being logged

Possible Duplicate:

  Removing unused strings during ProGuard optimisation

I have an Android application with dozens of logging statements. I'd prefer they wouldn't appear in the release version, so I used Proguard with something like this in the proguard.cfg file:

```<code>-assumenosideeffects class android.util.Log {
    public static *** d(...);
}
</code>```

But the problem is that there are a lot of Log.d("something is " + something), and although the Log.d() statement is being removed from the bytecode, the strings are still there.

So, following this answer, I created a simple wrapper class, something along the lines of:

```<code>public class MyLogger {
    public static void d(Object... msgs) {
        StringBuilder log = new StringBuilder();
        for(Object msg : msgs) {
            log.append(msg.toString());
        }
        Log.d(TAG, log.toString());
    }
}
</code>```

Then I edited my proguard.cfg:

```<code>-assumenosideeffects class my.package.MyLogger {
    public static *** d(...);
}
</code>```

But the strings are still found in the generated bytecode!

Other than this, I am using the standard proguard.cfg provided by the Android SDK. Am I doing something wrong?

Edit: after examining the generated bytecode, I saw that the strings were there, but they were not being appended one to another, as I thought. They were being stored in an array. Why? To pass them as variable parameters to my method. It looks like ProGuard doesn't like that, so I modified my logger class like this:

```<code>public static void d(Object a) {
    log(a);
}

public static void d(Object a, Object b) {
    log(a, b);
}

(... I had to put like seven d() methods ...)

private static void log(Object... msgs) {
    (same as before)
}
</code>```

It's ugly, but now the strings are nowhere in the bytecode.

Is this some kind of bug/limitation of ProGuard? Or is it just me not understanding how it works?

答:
Your solution with different methods for different numbers of arguments is probably the most convenient one. A single method with a variable number of arguments would be nicer, but the current version of ProGuard is not smart enough to remove all the unused code.

The java compiler compiles a variable number of arguments as a single array argument. On the invocation side, this means creating an array of the right size, filling out the elements, and passing it to the method. ProGuard sees that the array is being created and then being used to store elements in it. It doesn't realize (yet) that it then isn't used for actual useful operations, with the method invocation being gone. As a result, the array creation and initialization are preserved.

It's a good practice to check the processed code if you're expecting some particular optimization.

Body:
Possible Duplicate:

  Removing unused strings during ProGuard optimisation

I have an Android application with dozens of logging statements. I'd prefer they wouldn't appear in the release version, so I used Proguard with something like this in the proguard.cfg file:

-assumenosideeffects class android.util.Log {
    public static *** d(...);
}

But the problem is that there are a lot of Log.d("something is " + something), and although the Log.d() statement is being removed from the bytecode, the strings are still there.

So, following this answer, I created a simple wrapper class, something along the lines of:

public class MyLogger {
    public static void d(Object... msgs) {
        StringBuilder log = new StringBuilder();
        for(Object msg : msgs) {
            log.append(msg.toString());
        }
        Log.d(TAG, log.toString());
    }
}

Then I edited my proguard.cfg:

-assumenosideeffects class my.package.MyLogger {
    public static *** d(...);
}

But the strings are still found in the generated bytecode!

Other than this, I am using the standard proguard.cfg provided by the Android SDK. Am I doing something wrong?

Edit: after examining the generated bytecode, I saw that the strings were there, but they were not being appended one to another, as I thought. They were being stored in an array. Why? To pass them as variable parameters to my method. It looks like ProGuard doesn't like that, so I modified my logger class like this:

public static void d(Object a) {
    log(a);
}

public static void d(Object a, Object b) {
    log(a, b);
}

(... I had to put like seven d() methods ...)

private static void log(Object... msgs) {
    (same as before)
}

It's ugly, but now the strings are nowhere in the bytecode.

Is this some kind of bug/limitation of ProGuard? Or is it just me not understanding how it works?


问:
How Can I Tell If Microsoft Defender Has Scanned A Blob (a blob with no virus)
I'm looking into using Microsoft Defender for Cloud to use with Blob Storage.

Ideally I'd like to:

Upload to Storage

Have Defender for cloud scan for viruses

If there's an issue, remove it

If there's NOT an issue, process it further.

Step 3 is easy. Workflow automation and can easily trigger such events.

The bit I can't work out is: what if the scan goes through fine?

I've looked in Logic Apps and can't find a 'successfully scanned' trigger.

When will the scan occur? As soon as uploaded, or just on a schedule?

Is there anything I can go on (metadata?) to know a blob has been scanned and is good to go?

答:
Microsoft Defender for Storage does not currently scan uploaded files. You can read more about this here. This being the case you cannot accomplish what you are are trying to do with the current offering.
You have a couple of options:

Wait for the release of the malware scanning feature (this is in the works)

Use something like this


问:
Micro frontend react application - State Management using Redux - Data sharing

React (Typescript & Redux & Webpack)

I'm developing a micro front-end application using react (typescript & redux & webpack)

But I'm seeing blockers in sharing the data between container app & child apps,

Above the planned structure, there roles based authorization

Teacher
(Access to Teacher - Student Management App &  Student - Academic Assessment && Teacher Registration App

Parents
 (Acccess to Parent Registration App && Student - Academic - Assessment

Student
 (Student Registration App && Student-Academic Assessment App)

Now, I'm seeing a blocker in sharing the redux-store data across child applications, i.e. when users log in from the login app, how to share the logged user information to child apps so that role-based access is implemented effectively, data is also to be shared.
 Store should not be shared across apps.

答:
Honestly, you are making things more complicated for yourself that it needs to be. To make some of that data available to each other, you will end up with multiple copies of the same data in different stores that has to be kept in sync.

Just share that store instead of coming up with a complicated scheme of making some application state available to some others and not others.

If you suddenly start accessing another sub-app's data, chances are you actually need that access. And then you will have to enable data sharing there again - which you could have from the beginning.

Another solution for this would be to add some code rules. A "human" solution, not a "technical" if you want to phrase it like that:

one central store

an app can only dispatch actions from it's own app

one app's reducers can listen for actions from other apps (this is how app A could lead to a state change in app B if you need it)

you only use selectors, no inline-written selectors

keep all selectors in a central (but scoped) location for all apps to access, but add a linter rule to "forbid" import of certain scoped selectors to other apps. You can easily disable those rules for certain combinations to allow read-only cross-app access.