问:
Android - Dynamically Add Views into View
I have a layout for a view -

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_header"
        style="@style/Home.ListHeader" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_none"
        android:visibility="gone"
        style="@style/TextBlock"
        android:paddingLeft="6px" />

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_list" />

</LinearLayout>
</code>```

What I want to do, is in my main activity with a layout like this

```<code><LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:id="@+id/item_wrapper">
</LinearLayout>
</code>```

I want to loop through my data model and inject multiple views consisting of the first layout into the main layout.  I know I can do this by building the controls completely within the code, but I was wondering if there was a way to dynamically build the views so that I can continue using a layout instead of putting everything in code.

答:
See the LayoutInflater class.

```<code>LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup parent = (ViewGroup)findViewById(R.id.where_you_want_to_insert);
inflater.inflate(R.layout.the_child_view, parent);
</code>```

Body:
I have a layout for a view -

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_header"
        style="@style/Home.ListHeader" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_none"
        android:visibility="gone"
        style="@style/TextBlock"
        android:paddingLeft="6px" />

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/items_list" />

</LinearLayout>

What I want to do, is in my main activity with a layout like this

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="0px"
    android:id="@+id/item_wrapper">
</LinearLayout>

I want to loop through my data model and inject multiple views consisting of the first layout into the main layout.  I know I can do this by building the controls completely within the code, but I was wondering if there was a way to dynamically build the views so that I can continue using a layout instead of putting everything in code.

Body:
See the LayoutInflater class.

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup parent = (ViewGroup)findViewById(R.id.where_you_want_to_insert);
inflater.inflate(R.layout.the_child_view, parent);


来源: stackexchange

问:
Can I use mongock with Spring Data Repositories?
I tried to inject with @Autowired annotation a repository into changelog
and it doesn't get injected.

Config uses spring application context

```<code>@Bean
public SpringBootMongock mongock(ApplicationContext springContext, MongoClient mongoClient) {
  return new SpringBootMongockBuilder(mongoClient, "yourDbName", "com.package.to.be.scanned.for.changesets")
      .setApplicationContext(springContext)
      .setLockQuickConfig()
      .build();
}
</code>```

And the changelog

```<code>@ChangeLog(order = "001")
public class MyMigration {

    @Autowired
    private MyRepository repo;

    @ChangeSet(order = "001", id = "someChangeId", author = "testAuthor")
    public void importantWorkToDo(DB db){
       repo.findAll() // here null pointer
    }
}
</code>```

答:
we have recently released the version 4.0.7.alpha, which among other things allows you to use Spring repositories(and any other custom bean you wish) in your changeSets with no problem. You can insert, update, delete and read. It will be safely covered by the lock.

The only restriction is that it needs to be an interface, which should be the common case for Spring repositories.

Please take a look to this example

ContentLicense: CC BY-SA 4.0

Body:
I tried to inject with @Autowired annotation a repository into changelog
and it doesn't get injected.

Config uses spring application context

@Bean
public SpringBootMongock mongock(ApplicationContext springContext, MongoClient mongoClient) {
  return new SpringBootMongockBuilder(mongoClient, "yourDbName", "com.package.to.be.scanned.for.changesets")
      .setApplicationContext(springContext)
      .setLockQuickConfig()
      .build();
}

And the changelog

@ChangeLog(order = "001")
public class MyMigration {

    @Autowired
    private MyRepository repo;

    @ChangeSet(order = "001", id = "someChangeId", author = "testAuthor")
    public void importantWorkToDo(DB db){
       repo.findAll() // here null pointer
    }
}


问:
Parallelize the function in Python
I have a below function that Im trying to parallelize using multiprocessing but I couldn't get it working successful.  </p>

```<code>for d in result_list:
    v=d['content'][0]['template']['module']
    if isinstance(v, list):
        for i, v2 in enumerate(v):
            df_module,  = normalizeJSON(d,i,v2['id'])
            dim_content_module=dim_content_module.append(df_module, ignore_index=True,sort=False)

    else:
        print('module is not a list')

</code>```

答:
Is the result list or dictionary?

Use map or imap or async function of both function will be more simple.

```<code>from multiprocessing import Pool

args = [r for r in result]
with Pool() as pool:
    results = pool.map(worker, args)

def worker(d):
    v = d['header'][0]['id']['value']
    if isinstance(v, list):
        for i, v2 in enumerate(v):
            df = function1(d, i, v2['id'])
    return df
</code>```

Title: Parallelize the function in Python

Body:
I have a below function that Im trying to parallelize using multiprocessing but I couldn't get it working successful.

for d in result_list:
    v=d['content'][0]['template']['module']
    if isinstance(v, list):
        for i, v2 in enumerate(v):
            df_module,  = normalizeJSON(d,i,v2['id'])
            dim_content_module=dim_content_module.append(df_module, ignore_index=True,sort=False)

    else:
        print('module is not a list')

Body:
Is the result list or dictionary?

Use map or imap or async function of both function will be more simple.

from multiprocessing import Pool

args = [r for r in result]
with Pool() as pool:
    results = pool.map(worker, args)

def worker(d):
    v = d['header'][0]['id']['value']
    if isinstance(v, list):
        for i, v2 in enumerate(v):
            df = function1(d, i, v2['id'])
    return df


问:
Access office 365 group using ews api
I am trying to access office 365 groups using ews java api using impersonation. I am getting error:

```<code> The SMTP address has no mailbox associated with it.
</code>```

Code:

```<code>ExchangeCredentials credentials = new WebCredentials("admin@xxxx.onmicrosoft.com", "passwordxxx");
service.setCredentials(credentials);
service.setImpersonatedUserId(
            new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "group-smtp@xxx.onmicrosoft.com"));
FolderView folderView = new FolderView(50);
FindFoldersResults findFolderResults = service.findFolders(WellKnownFolderName.MsgFolderRoot, folderView);
</code>```

The aim is to get channel messages of the team associated with this group. According to this: link

The channel messages are stored in group's mailbox's Conversation History/Team Chat folder

答: If you want to access the messages in a Teams channel. You could use List Channel messages graph API</p>

Title: Access office 365 group using ews api

Body:
I am trying to access office 365 groups using ews java api using impersonation. I am getting error:

 The SMTP address has no mailbox associated with it.

Code:

ExchangeCredentials credentials = new WebCredentials("admin@xxxx.onmicrosoft.com", "passwordxxx");
service.setCredentials(credentials);
service.setImpersonatedUserId(
            new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "group-smtp@xxx.onmicrosoft.com"));
FolderView folderView = new FolderView(50);
FindFoldersResults findFolderResults = service.findFolders(WellKnownFolderName.MsgFolderRoot, folderView);

The aim is to get channel messages of the team associated with this group. According to this: link

The channel messages are stored in group's mailbox's Conversation History/Team Chat folder


问:
Django DRF signal, post_save is not firing
I am having a issue about creating a token. I setup DRF's TokenAuthentication but when I sign up a user signal is not firing.

in settings.py

```<code>INSTALLED_APPS = [
    ..
    'rest_framework',
    'rest_framework.authtoken',
    ..
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ]
}
</code>```

inside account app, this signals.py

```<code>from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token

@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    print("fired")
    if created:
        Token.objects.create(user=instance)
</code>```

I can save the new user but for new user can't create a token. print("firing") not running as well. What am I missing here?

答:
I solved the problem by registering signals.py inside the apps.py

```<code>from django.apps import AppConfig

class AccountConfig(AppConfig):
    name = 'account'

    def ready(self):
        import account.signals
</code>```

And also must to add account app and also signals into installed apps like below.

```<code>INSTALLED_APPS = [
   ...
    'account.apps.AccountConfig', # here
    'rest_framework',
    'rest_framework.authtoken',
   ...
]
</code>```

then I can finally got my token.

Body:
I am having a issue about creating a token. I setup DRF's TokenAuthentication but when I sign up a user signal is not firing.

in settings.py

INSTALLED_APPS = [
    ..
    'rest_framework',
    'rest_framework.authtoken',
    ..
]

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',
    ]
}

inside account app, this signals.py

from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token

@receiver(post_save, sender=User)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    print("fired")
    if created:
        Token.objects.create(user=instance)

I can save the new user but for new user can't create a token. print("firing") not running as well. What am I missing here?

Body:
I solved the problem by registering signals.py inside the apps.py

from django.apps import AppConfig

class AccountConfig(AppConfig):
    name = 'account'

    def ready(self):
        import account.signals

And also must to add account app and also signals into installed apps like below.

INSTALLED_APPS = [
   ...
    'account.apps.AccountConfig', # here
    'rest_framework',
    'rest_framework.authtoken',
   ...
]

then I can finally got my token.


问:
How many bits is a WORD and is that constant over different architectures?
Is a machine WORD always the same or does it depend on the machine architecture?
And is the meaning of the word WORD context sensitive or generally applicable?

答:
WORD is a Windows specific 16-bit integer type, and is hardware independent.

If you mean a machine word, then there's no need to shout.

OwnerDisplayName: mixedpickles

ContentLicense: CC BY-SA 3.0

OwnerDisplayName: Pete Kirkham

ContentLicense: CC BY-SA 2.5


问:
Deadlock detection with JVMTI
I wonder whether it is possible to detect deadlocks dynamically in Java by using the JVMTI. There are two events indicating actions on monitors using the synchronized statement:

Monitor Contended Enter

Sent when a thread is attempting to enter a Java programming language monitor already acquired by another thread.

Monitor Contended Entered

Sent when a thread enters a Java programming language monitor after waiting for it to be released by another thread.

This means, with JVMTI I can only see those monitors which are already locked. I wanted to reconstruct a wait-for graph, but without events indicating me, that a lock was acquired which is not held by any thread. This is impossible.

Are there alternatives? The SIGQUIT command on Unix allows a thread dump which displays the deadlocks, it seems like this is not possible within JVMTI.

答:
You should be able to get this information via JMX.

Try

```<code>ManagementFactory.getThreadMXBean().findMonitorDeadlockedThreads();
</code>```

Title: Deadlock detection with JVMTI

Body:
You should be able to get this information via JMX.

Try

ManagementFactory.getThreadMXBean().findMonitorDeadlockedThreads();


问:
How can i create a Bootstrap like 12 column ( only grid ) grid system using new CSS GRID Layout
How can I create a bootstrap-like 12 column grid using the new CSS GRID technology? Can anybody please show me a demo how to do it? I am really getting confused with this new technology. I want to make a simple 12 column grid-like bootstrap using CSS grid. What my approach should be for this?</p>

答:
Adding some makeup to the @G-Cyrillus answer, the accepted answer.

If you would like your columns to be full width at a certain screen sizes for better user experience, then add this at the bottom of the CSS file:

```<code>/* Full Width below 768 pixels */
@media only screen and (max-width: 768px) {
  .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12{
     grid-column: auto/span 12;
  }
}
</code>```

So Your full code should look like this:

.grid {
  margin: 1em;
  border: solid lightgray;
  background: lightgray;
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  grid-gap: 2px;
  counter-reset: div;
}

.grid div {
  border: solid;
  text-align: center;
}

.grid div:before {
  counter-increment: div;
  content: 'N°' counter(div);
}

.grid div[class]:after {
  display: block;
  text-align: center;
  background: lightblue;
  content: "Class applied : "attr(class);
  color: crimson;
}

/* spanning cols, complete values missing */

.col-2 {
  grid-column: auto/span 2;
}

.col-3 {
  grid-column: auto/span 3;
}

.col-6 {
  grid-column: auto/span 6;
}

.col-8 {
  grid-column: auto/span 8;
}

/* spanning rows , complete values missing*/

.row-2 {
  grid-row: auto/span 2;
}

/* Full Width below 768 pixels */
@media only screen and (max-width: 768px) {
  .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12{
     grid-column: auto/span 12;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="grid">
  <div class="col-3"></div>
  <div class="col-3"></div>
  <div class="col-3"></div>
  <div class="col-3"></div>
  <div class="col-6"></div>
  <div class="col-6"></div>
  <div class="col-2 row-2"></div>
  <div class="col-8"></div>
  <div class="col-2 row-2"></div>
  <div class="col-3"></div>
  <div class="col-2"></div>
  <div class="col-3"></div>
</div></code>```

Body:
Adding some makeup to the @G-Cyrillus answer, the accepted answer.

If you would like your columns to be full width at a certain screen sizes for better user experience, then add this at the bottom of the CSS file:

/* Full Width below 768 pixels */
@media only screen and (max-width: 768px) {
  .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12{
     grid-column: auto/span 12;
  }
}

So Your full code should look like this:

.grid {
  margin: 1em;
  border: solid lightgray;
  background: lightgray;
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  grid-gap: 2px;
  counter-reset: div;
}

.grid div {
  border: solid;
  text-align: center;
}

.grid div:before {
  counter-increment: div;
  content: 'N°' counter(div);
}

.grid div[class]:after {
  display: block;
  text-align: center;
  background: lightblue;
  content: "Class applied : "attr(class);
  color: crimson;
}

/* spanning cols, complete values missing */

.col-2 {
  grid-column: auto/span 2;
}

.col-3 {
  grid-column: auto/span 3;
}

.col-6 {
  grid-column: auto/span 6;
}

.col-8 {
  grid-column: auto/span 8;
}

/* spanning rows , complete values missing*/

.row-2 {
  grid-row: auto/span 2;
}

/* Full Width below 768 pixels */
@media only screen and (max-width: 768px) {
  .col-1, .col-2, .col-3, .col-4, .col-5, .col-6, .col-7, .col-8, .col-9, .col-10, .col-11, .col-12{
     grid-column: auto/span 12;
  }
}

<div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="grid">
  <div class="col-3"></div>
  <div class="col-3"></div>
  <div class="col-3"></div>
  <div class="col-3"></div>
  <div class="col-6"></div>
  <div class="col-6"></div>
  <div class="col-2 row-2"></div>
  <div class="col-8"></div>
  <div class="col-2 row-2"></div>
  <div class="col-3"></div>
  <div class="col-2"></div>
  <div class="col-3"></div>
</div>


问:
How to detect what page I came from Javascript
Is there any way to detect from what page you came from with Java Script?

I orriginally have added a parameter in the link

```<code>mywebsite.com/thispage.jsp?lastpage=lastPageName
</code>```

But I think this is not a good way to detect it.

I want to use it to create an "404: Page not found" site with a 'go Back!' Button, so I can just link from every page and go back to this exact page.

If you know a better Idea to create this Button, you are welcome to comment it.

**Answer:**
For some reason a java method that run `history.back()` did not work for me.

Go Back
```

This direct javascript usage did work for me

**EDIT:**
I ran my file in the internal browser from Eclipse, what didn't work. The moment I started testing on Chrome or a `Chromium based browser` it worked.

答:
There's a back method on the window.history object you can use to do that.

https://developer.mozilla.org/en-US/docs/Web/API/History/back

Body:
Is there any way to detect from what page you came from with Java Script?

I orriginally have added a parameter in the link

mywebsite.com/thispage.jsp?lastpage=lastPageName

But I think this is not a good way to detect it.

I want to use it to create an "404: Page not found" site with a 'go Back!' Button, so I can just link from every page and go back to this exact page.

If you know a better Idea to create this Button, you are welcome to comment it.

**Answer:**
For some reason a java method that run `history.back()` did not work for me.

Go Back

This direct javascript usage did work for me

**EDIT:**
I ran my file in the internal browser from Eclipse, what didn't work. The moment I started testing on Chrome or a `Chromium based browser` it worked.


问:
Kotlin - custom dialog in Android
I want to create a custom dialog in Kotlin. I looked through questions on this theme on Stack Overflow, but I could not find any useful information. How can I do it?

答:
Works fine. You can also customize it the way you want.

Main class:

```<code>class CustomAlertDialogOneButton( activity: Activity?,
private val alertOneButtonClickListener: OnAlertOneButtonClickListener):Dialog(activity!!) {

private var title = ""
private var text = ""
private var dialogId = -1
private var buttonName = ""

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.custom_alert_one_button_dialog)
    setCancelable(false)
    this.window?.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
    viewsClickListenerInit()
}

override fun onStart() {
    initDialog()
    super.onStart()
}

private fun fillFields(title: String, text: String?, dialogId: Int, buttonName: String) {
    clearDialog()
    this.title = title
    this.text = text ?: ""
    this.dialogId = dialogId
    this.buttonName = buttonName
}

private fun clearDialog() {
    title = ""
    text = ""
}

private fun initDialog() {
    if (title.isNotBlank()) {
        tvAlertTitle.text = title
    }

    if (text.isNotBlank()) {
        tvAlertText.text = text
    }

    tvAlertButtonOk.text = buttonName
}

fun show(title: String, text: String?, dialogId: Int = -1, buttonName: String = ResourcesRepository.resources.getString(R.string.ok)) {
    fillFields(title, text, dialogId, buttonName)
    super.show()
}

private fun viewsClickListenerInit() {
    tvAlertButtonOk.setOnClickListener {
        alertOneButtonClickListener.okClickListener(dialogId)
        dismiss()
    }
}}
</code>```

XML for it: name it likes - custom_alert_one_button_dialog.xml

```<code><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="280dp"
android:layout_height="145dp"
android:background="@color/colorWhite"
android:orientation="vertical">

<androidx.constraintlayout.widget.Guideline
    android:id="@+id/center_vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.5" />

<TextView
    android:id="@+id/tvAlertTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingStart="24dp"
    android:paddingTop="22dp"
    android:textAlignment="center"
    android:textColor="@color/colorDarkGrey"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/tvAlertText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingStart="24dp"
    android:paddingTop="13dp"
    android:paddingEnd="24dp"
    android:paddingBottom="10dp"
    android:textColor="@color/colorGrey"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/tvAlertTitle" />

<TextView
    android:id="@+id/tvAlertButtonOk"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingStart="10dp"
    android:paddingTop="10dp"
    android:paddingEnd="34dp"
    android:paddingBottom="18dp"
    android:text="@string/ok"
    android:textColor="@color/colorDarkGrey"
    android:textSize="14sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent" />
</code>```

Interface for button click listener:

```<code>interface OnAlertOneButtonClickListener {

fun okClickListener(dialogId: Int = -1)}
</code>```

Implementation:

```<code>class SomeActivity : AppCompatActivity(), OnAlertOneButtonClickListener {
****
 private var customDialogOneButton by lazy {
    CustomAlertDialogOneButton(this, this)
 }
****
customDialogOneButton.show(
                title = "some title",
                text = "some text",
                dialogId = some int constant,
                buttonName = "some button name"
            )
****
override fun okClickListener(dialogId: Int) {
    when (dialogId) {
        some int constant -> {
            // call method
        }

    }
}
</code>```

Title: Kotlin - custom dialog in Android

Body:
Works fine. You can also customize it the way you want.

Main class:

class CustomAlertDialogOneButton( activity: Activity?,
private val alertOneButtonClickListener: OnAlertOneButtonClickListener):Dialog(activity!!) {

private var title = ""
private var text = ""
private var dialogId = -1
private var buttonName = ""

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.custom_alert_one_button_dialog)
    setCancelable(false)
    this.window?.setBackgroundDrawable(ColorDrawable(android.graphics.Color.TRANSPARENT))
    viewsClickListenerInit()
}

override fun onStart() {
    initDialog()
    super.onStart()
}

private fun fillFields(title: String, text: String?, dialogId: Int, buttonName: String) {
    clearDialog()
    this.title = title
    this.text = text ?: ""
    this.dialogId = dialogId
    this.buttonName = buttonName
}

private fun clearDialog() {
    title = ""
    text = ""
}

private fun initDialog() {
    if (title.isNotBlank()) {
        tvAlertTitle.text = title
    }

    if (text.isNotBlank()) {
        tvAlertText.text = text
    }

    tvAlertButtonOk.text = buttonName
}

fun show(title: String, text: String?, dialogId: Int = -1, buttonName: String = ResourcesRepository.resources.getString(R.string.ok)) {
    fillFields(title, text, dialogId, buttonName)
    super.show()
}

private fun viewsClickListenerInit() {
    tvAlertButtonOk.setOnClickListener {
        alertOneButtonClickListener.okClickListener(dialogId)
        dismiss()
    }
}}

XML for it: name it likes - custom_alert_one_button_dialog.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="280dp"
android:layout_height="145dp"
android:background="@color/colorWhite"
android:orientation="vertical">

<androidx.constraintlayout.widget.Guideline
    android:id="@+id/center_vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.5" />

<TextView
    android:id="@+id/tvAlertTitle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingStart="24dp"
    android:paddingTop="22dp"
    android:textAlignment="center"
    android:textColor="@color/colorDarkGrey"
    android:textSize="20sp"
    android:textStyle="bold"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/tvAlertText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingStart="24dp"
    android:paddingTop="13dp"
    android:paddingEnd="24dp"
    android:paddingBottom="10dp"
    android:textColor="@color/colorGrey"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/tvAlertTitle" />

<TextView
    android:id="@+id/tvAlertButtonOk"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:paddingStart="10dp"
    android:paddingTop="10dp"
    android:paddingEnd="34dp"
    android:paddingBottom="18dp"
    android:text="@string/ok"
    android:textColor="@color/colorDarkGrey"
    android:textSize="14sp"
    android:textStyle="bold"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent" />

Interface for button click listener:

interface OnAlertOneButtonClickListener {

fun okClickListener(dialogId: Int = -1)}

Implementation:

class SomeActivity : AppCompatActivity(), OnAlertOneButtonClickListener {
****
 private var customDialogOneButton by lazy {
    CustomAlertDialogOneButton(this, this)
 }
****
customDialogOneButton.show(
                title = "some title",
                text = "some text",
                dialogId = some int constant,
                buttonName = "some button name"
            )
****
override fun okClickListener(dialogId: Int) {
    when (dialogId) {
        some int constant -> {
            // call method
        }

    }
}


问:
How to get the data-column-index in DataTables?
I already tried, data('columnIndex') but it gives me undefine.

I need to get the value of data-column-index for my custom reOrder function.

```<code>$('#columnAge').data('column-index') // undefined
$('#columnAge').data('columnIndex') // get the value of data-index instead
</code>```

Thanks

答:
Try next code:

```<code>$(#columnAge).attr("data-column-index")
</code>```

I hope that work. It worked fine for my case.

Body:
I already tried, data('columnIndex') but it gives me undefine.

I need to get the value of data-column-index for my custom reOrder function.

$('#columnAge').data('column-index') // undefined
$('#columnAge').data('columnIndex') // get the value of data-index instead

Thanks

Body:
Try next code:

$(#columnAge).attr("data-column-index")

I hope that work. It worked fine for my case.


问:
Perl : How to match a parenthesis inside a regexp?
I'm trying to extract some fields from a fixed format data, which looks like this:

```<code>G1 = DFF(G2)
</code>```

Say $_ has the above line, and I want to get G1 and G2 after matching it with a suitable reg exp. I'm using this :

```<code>if (/(w+)\s*=\s*DFF\((w+)\)/)
{
    print "$1, $2";
}
</code>```

But this isn't printing what I want (prints nothing, which means my pattern is wrong). Can anyone show me what I'm doing wrong (pls be patient, this is my first perl program !!)

答:
```<code>if (/(\w+)\s*=\s*DFF\((\w+)\)/)
</code>```

It's not the parens that are incorrect, it's the word match \w that needs an escape.

Body:
I'm trying to extract some fields from a fixed format data, which looks like this:

G1 = DFF(G2)

Say $_ has the above line, and I want to get G1 and G2 after matching it with a suitable reg exp. I'm using this :

if (/(w+)\s*=\s*DFF\((w+)\)/)
{
    print "$1, $2";
}

But this isn't printing what I want (prints nothing, which means my pattern is wrong). Can anyone show me what I'm doing wrong (pls be patient, this is my first perl program !!)

Body:
if (/(\w+)\s*=\s*DFF\((\w+)\)/)

It's not the parens that are incorrect, it's the word match \w that needs an escape.


问:
How to scrape data from flexbox element/container with Python and Beautiful Soup
I am trying to scrape data from a utility website using python, beautiful soup and selenium. The data that I am trying to scrape is stuff like: time, cause, status, etc. When I run a typical page request, parse the page, and parse the data that I am looking for (data in id="OutageListTable"), and print it, the divs and strings are nowhere to be found. When I inspect the page element, the data is there, but it is in a flex container.

This is the code that I am using:

```<code>from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import urllib3
from selenium import webdriver

my_url = 'https://www.pse.com/outage/outage-map'

browser = webdriver.Firefox()
browser.get(my_url)

html = browser.page_source
page_soup = soup(html, features='lxml')

outage_list = page_soup.find(id='OutageListTable')
print(outage_list)

browser.quit()
</code>```

How do you retrieve information that is in a flex/flexbox container? I am not finding any resources online to help me figure it out.

答:
The data is loaded dynamically via Javascript. You can use requests module to obtain the data.

For example:

```<code>import json
import requests

url = 'https://www.pse.com/api/sitecore/OutageMap/AnonymoussMapListView'

data = requests.get(url).json()

# uncomment this to print all data:
#print(json.dumps(data, indent=4))

for d in data['PseMap']:
    print('{} - {}'.format(d['DataProvider']['PointOfInterest']['Title'], d['DataProvider']['PointOfInterest']['MapType']))
    for info in d['DataProvider']['Attributes']:
        print(info['Name'], info['Value'])
    print('-' * 80)
</code>```

Prints:

```<code>Bellingham - Outage
Start time 06/02 06:09 PM
Est. restoration time 06/03 06:30 AM
Customers impacted 1
Cause Trees/Vegetation
Status Crew assigned
Last updated 06/02 11:50 PM
--------------------------------------------------------------------------------
Deming - Outage
Start time 06/02 07:10 PM
Est. restoration time 06/03 03:30 AM
Customers impacted 568
Cause Accident
Status Repair crew onsite
Last updated 06/02 11:50 PM
--------------------------------------------------------------------------------
Everest - Outage
Start time 06/02 10:42 AM
Customers impacted 4
Cause Scheduled Outage
Status Repair crew onsite
Last updated 06/02 10:50 AM
--------------------------------------------------------------------------------
Kenmore - Outage
Start time 06/02 09:59 PM
Est. restoration time 05/29 01:00 AM
Customers impacted 2
Cause Scheduled Outage
Status Repair crew onsite
Last updated 06/02 10:05 PM
--------------------------------------------------------------------------------
Kent - Outage
Start time 06/02 06:43 PM
Est. restoration time To Be Determined
Customers impacted 26
Cause Car/Equip Accident
Status Waiting for repairs
Last updated 06/02 10:15 PM
--------------------------------------------------------------------------------
Kent - Outage
Start time 06/02 10:09 PM
Est. restoration time To Be Determined
Customers impacted 13
Cause Under Investigation
Status Repair crew onsite
Last updated 06/02 10:15 PM
--------------------------------------------------------------------------------
Northwest Bellevue - Outage
Start time 06/02 11:28 PM
Est. restoration time To Be Determined
Customers impacted 14
Cause Under Investigation
Status Repair crew onsite
Last updated 06/02 11:30 PM
--------------------------------------------------------------------------------
Pacific - Outage
Start time 06/02 06:19 PM
Est. restoration time 06/03 02:30 AM
Customers impacted 3
Cause Accident
Status Crew assigned
Last updated 06/02 11:00 PM
--------------------------------------------------------------------------------
Woodinville - Outage
Start time 06/02 08:29 PM
Est. restoration time 06/03 03:30 AM
Customers impacted 2
Cause Under Investigation
Status Crew assigned
Last updated 06/03 12:15 AM
--------------------------------------------------------------------------------
</code>```

Body:
I am trying to scrape data from a utility website using python, beautiful soup and selenium. The data that I am trying to scrape is stuff like: time, cause, status, etc. When I run a typical page request, parse the page, and parse the data that I am looking for (data in id="OutageListTable"), and print it, the divs and strings are nowhere to be found. When I inspect the page element, the data is there, but it is in a flex container.

This is the code that I am using:

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import urllib3
from selenium import webdriver

my_url = 'https://www.pse.com/outage/outage-map'

browser = webdriver.Firefox()
browser.get(my_url)

html = browser.page_source
page_soup = soup(html, features='lxml')

outage_list = page_soup.find(id='OutageListTable')
print(outage_list)

browser.quit()

How do you retrieve information that is in a flex/flexbox container? I am not finding any resources online to help me figure it out.

Body:
The data is loaded dynamically via Javascript. You can use requests module to obtain the data.

For example:

import json
import requests

url = 'https://www.pse.com/api/sitecore/OutageMap/AnonymoussMapListView'

data = requests.get(url).json()

# uncomment this to print all data:
#print(json.dumps(data, indent=4))

for d in data['PseMap']:
    print('{} - {}'.format(d['DataProvider']['PointOfInterest']['Title'], d['DataProvider']['PointOfInterest']['MapType']))
    for info in d['DataProvider']['Attributes']:
        print(info['Name'], info['Value'])
    print('-' * 80)

Prints:

Bellingham - Outage
Start time 06/02 06:09 PM
Est. restoration time 06/03 06:30 AM
Customers impacted 1
Cause Trees/Vegetation
Status Crew assigned
Last updated 06/02 11:50 PM
--------------------------------------------------------------------------------
Deming - Outage
Start time 06/02 07:10 PM
Est. restoration time 06/03 03:30 AM
Customers impacted 568
Cause Accident
Status Repair crew onsite
Last updated 06/02 11:50 PM
--------------------------------------------------------------------------------
Everest - Outage
Start time 06/02 10:42 AM
Customers impacted 4
Cause Scheduled Outage
Status Repair crew onsite
Last updated 06/02 10:50 AM
--------------------------------------------------------------------------------
Kenmore - Outage
Start time 06/02 09:59 PM
Est. restoration time 05/29 01:00 AM
Customers impacted 2
Cause Scheduled Outage
Status Repair crew onsite
Last updated 06/02 10:05 PM
--------------------------------------------------------------------------------
Kent - Outage
Start time 06/02 06:43 PM
Est. restoration time To Be Determined
Customers impacted 26
Cause Car/Equip Accident
Status Waiting for repairs
Last updated 06/02 10:15 PM
--------------------------------------------------------------------------------
Kent - Outage
Start time 06/02 10:09 PM
Est. restoration time To Be Determined
Customers impacted 13
Cause Under Investigation
Status Repair crew onsite
Last updated 06/02 10:15 PM
--------------------------------------------------------------------------------
Northwest Bellevue - Outage
Start time 06/02 11:28 PM
Est. restoration time To Be Determined
Customers impacted 14
Cause Under Investigation
Status Repair crew onsite
Last updated 06/02 11:30 PM
--------------------------------------------------------------------------------
Pacific - Outage
Start time 06/02 06:19 PM
Est. restoration time 06/03 02:30 AM
Customers impacted 3
Cause Accident
Status Crew assigned
Last updated 06/02 11:00 PM
--------------------------------------------------------------------------------
Woodinville - Outage
Start time 06/02 08:29 PM
Est. restoration time 06/03 03:30 AM
Customers impacted 2
Cause Under Investigation
Status Crew assigned
Last updated 06/03 12:15 AM
--------------------------------------------------------------------------------


问:
Sum and Count by month, shown with last day of that month
I have a transaction table like this:

```<code> Trandate    channelID   branch    amount
---------   ---------   ------    ------
01/05/2019     1          2        2000
11/05/2019     1          2        2200
09/03/2020     1          2        5600
15/03/2020     1          2        600
12/10/2019     2         10        12000
12/10/2019     2         10        12000
15/11/2019     4          7        4400
15/02/2020     4          2        2500
</code>```

I need to sum amount and count transactions by year and month. I tried this:

```<code>select DISTINCT
   DATEPART(YEAR,a.TranDate) as [YearT],
   DATEPART(MONTH,a.TranDate) as [monthT],
   count(*) as [countoftran],
   sum(a.Amount) as [amount],
   a.Name as [branch],
   a.ChannelName as [channelID]
from transactions as a
where a.TranDate>'20181231'
group by a.Name, a.ChannelName, DATEPART(YEAR,a.TranDate), DATEPART(MONTH,a.TranDate)
order by a.Name, YearT, MonthT
</code>```

It works like charm. However, I will use this data on PowerBI thus I cannot show these results in a "line graphic" due to the year and month info being in separate columns.

I tried changing format on SQL to 'YYYYMM' alas powerBI doesn't recognise this column as date.

So, in the end, I need a result table looks like this:

```<code> YearT      channelID   branch    Tamount   TranT
---------   ---------   ------    -------   -----
31/05/2019     1          2        4400      2
30/03/2020     1          2        7800      2
31/10/2019     2         10        24000     2
30/11/2019     4          7        4400      1
29/02/2020     4          2        2500      1
</code>```

I have tried several little changes with no result.

Help is much appreciated.

答:
You may try with the following statement:

```<code>SELECT
   EOMONTH(DATEFROMPARTS(YEAR(Trandate), MONTH(Trandate), 1)) AS YearT,
   branch, channelID,
   SUM(amount) AS TAmount,
   COUNT(*) AS TranT
FROM (VALUES
   ('20190501', 1,  2, 2000),
   ('20190511', 1,  2, 2200),
   ('20200309', 1,  2, 5600),
   ('20200315', 1,  2, 600),
   ('20191012', 2, 10, 12000),
   ('20191012', 2, 10, 12000),
   ('20191115', 4,  7, 4400),
   ('20200215', 4,  2, 2500)
) v (Trandate, channelID, branch, amount)
GROUP BY DATEFROMPARTS(YEAR(Trandate), MONTH(Trandate), 1), branch, channelID
ORDER BY DATEFROMPARTS(YEAR(Trandate), MONTH(Trandate), 1)
</code>```

Result:

```<code>YearT       branch  channelID   TAmount TranT
2019-05-31  2       1           4200    2
2019-10-31  10      2           24000   2
2019-11-30  7       4           4400    1
2020-02-29  2       4           2500    1
2020-03-31  2       1           6200    2
</code>```

Body:
I have a transaction table like this:

 Trandate    channelID   branch    amount
---------   ---------   ------    ------
01/05/2019     1          2        2000
11/05/2019     1          2        2200
09/03/2020     1          2        5600
15/03/2020     1          2        600
12/10/2019     2         10        12000
12/10/2019     2         10        12000
15/11/2019     4          7        4400
15/02/2020     4          2        2500

I need to sum amount and count transactions by year and month. I tried this:

select DISTINCT
   DATEPART(YEAR,a.TranDate) as [YearT],
   DATEPART(MONTH,a.TranDate) as [monthT],
   count(*) as [countoftran],
   sum(a.Amount) as [amount],
   a.Name as [branch],
   a.ChannelName as [channelID]
from transactions as a
where a.TranDate>'20181231'
group by a.Name, a.ChannelName, DATEPART(YEAR,a.TranDate), DATEPART(MONTH,a.TranDate)
order by a.Name, YearT, MonthT

It works like charm. However, I will use this data on PowerBI thus I cannot show these results in a "line graphic" due to the year and month info being in separate columns.

I tried changing format on SQL to 'YYYYMM' alas powerBI doesn't recognise this column as date.

So, in the end, I need a result table looks like this:

 YearT      channelID   branch    Tamount   TranT
---------   ---------   ------    -------   -----
31/05/2019     1          2        4400      2
30/03/2020     1          2        7800      2
31/10/2019     2         10        24000     2
30/11/2019     4          7        4400      1
29/02/2020     4          2        2500      1

I have tried several little changes with no result.

Help is much appreciated.

Body:
You may try with the following statement:

SELECT
   EOMONTH(DATEFROMPARTS(YEAR(Trandate), MONTH(Trandate), 1)) AS YearT,
   branch, channelID,
   SUM(amount) AS TAmount,
   COUNT(*) AS TranT
FROM (VALUES
   ('20190501', 1,  2, 2000),
   ('20190511', 1,  2, 2200),
   ('20200309', 1,  2, 5600),
   ('20200315', 1,  2, 600),
   ('20191012', 2, 10, 12000),
   ('20191012', 2, 10, 12000),
   ('20191115', 4,  7, 4400),
   ('20200215', 4,  2, 2500)
) v (Trandate, channelID, branch, amount)
GROUP BY DATEFROMPARTS(YEAR(Trandate), MONTH(Trandate), 1), branch, channelID
ORDER BY DATEFROMPARTS(YEAR(Trandate), MONTH(Trandate), 1)

Result:

YearT       branch  channelID   TAmount TranT
2019-05-31  2       1           4200    2
2019-10-31  10      2           24000   2
2019-11-30  7       4           4400    1
2020-02-29  2       4           2500    1
2020-03-31  2       1           6200    2


问:
Azure Storage - Is it possible to create two or more static website containers in one storage account?
I'm wondering if is supported or possible to manage several static file web servers in the same storage account.

Looking around in the options for Static Website in an Azure Storage account, it only has a toogle an only one primary endpoint and an associated container to serve the static website (named $web).

Is there a way to setup the account to provide two Static Website containers?

答: As of now, it can only support one static website for one storage account. There is also an issue about that.</p>


问:
how can i get the value of an azure cli list command into a variable?
When i run the following command in azure, I want to place the value of the "name" in a variable like $ipconfigname. The output lists out many other values but I only need this one value "name" in the variable, how can i accomplish this?

az network nic ip-config list -g rg01 --nic-name vmnic01

答:
Well, when you use the list command, it means the output must be a list no matter how many members it has. So as you want, the variable $ipconfigname actually is a list of the config name. You can use the Azure CLI command to set the variable like below only with the name list:

```<code>$ipconfigNames = az network nic ip-config list -g rg01 --nic-name vmnic01 --query "[].name" -o tsv
</code>```

Body:
Well, when you use the list command, it means the output must be a list no matter how many members it has. So as you want, the variable $ipconfigname actually is a list of the config name. You can use the Azure CLI command to set the variable like below only with the name list:

$ipconfigNames = az network nic ip-config list -g rg01 --nic-name vmnic01 --query "[].name" -o tsv


问:
in istio, how a virtualservice defined in a namespace can use a gateway defined in another namespace
If a virtualservice A is defined in namespace A using networking.istio.io, how can it use a gateway B defined in another namespace, namespace B?

Thanks

答:
If it´s not in the same namespace as virtual service, you have to specify that in virtual service

Check the spec.gateways section

```<code>apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: bookinfo-Mongo
  namespace: bookinfo-namespace
spec:
  gateways:
  - some-config-namespace/my-gateway # can omit the namespace if gateway is in same
                                       namespace as virtual service.
</code>```

```<code>apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: my-gateway
  namespace: some-config-namespace
</code>```

There is related  istio documentation about that.

Body:
If it´s not in the same namespace as virtual service, you have to specify that in virtual service

Check the spec.gateways section

apiVersion: networking.istio.io/v1alpha3
kind: VirtualService
metadata:
  name: bookinfo-Mongo
  namespace: bookinfo-namespace
spec:
  gateways:
  - some-config-namespace/my-gateway # can omit the namespace if gateway is in same
                                       namespace as virtual service.

apiVersion: networking.istio.io/v1alpha3
kind: Gateway
metadata:
  name: my-gateway
  namespace: some-config-namespace

There is related  istio documentation about that.


问:
Total Collections, rejecting collections of types that do not include all possibilities
Let's say we have the following types:

sealed trait T
case object Goat extends T
case object Monk extends T
case object Tiger extends T
```

<p>Now, how do you construct a collection of <code>T</code> such that <em>at least one</em> of each sub-<code>T</code> appears in the collection, this constraint being enforced at compile time? A collection where, contrary to this:</p>

```val s:Seq[T] = Seq(Goat)
```

<p>which compiles, this:</p>

```val ts:TotalSeq[T] = TotalSeq(Goat, Goat, Tiger)
```

does not. I've used Scala above, but I would be happy to see solutions in other languages as well.

(Forgive me if my words are a bit off; I have a cold and am amusing myself today with puzzles.)

答:
If I'm interpreting this correctly...

```<code>{-# LANGUAGE GADTs #-}
{-# LANGUAGE EmptyDataDecls #-}

data Goat
data Monk
data Tiger

data T a where
    TGoat  :: T Goat
    TMonk  :: T Monk
    TTiger :: T Tiger

data TSeq a where
    TNil :: TSeq ((), (), ())
    TG   :: T Goat -> TSeq ((), m, t) -> TSeq (Goat, m, t)
    TM   :: T Monk -> TSeq (g, (), t) -> TSeq (g, Monk, t)
    TT   :: T Tiger -> TSeq (g, m, ()) -> TSeq (g, m, Tiger)
    TCG  :: T Goat -> TSeq (Goat, m, t) -> TSeq (Goat, m, t)
    TCM  :: T Monk -> TSeq (g, Monk, t) -> TSeq (g, Monk, t)
    TCT  :: T Tiger -> TSeq (g, m, Tiger) -> TSeq (g, m, Tiger)
</code>```

Be aware that no attempt has been made to make this usable. It's incredibly clumsy.

Now, given these values:

```<code>x = TCG TGoat (TG TGoat (TT TTiger (TM TMonk TNil)))

y = TG TGoat TNil
</code>```

And this function:

```<code>f :: TSeq (Goat, Monk, Tiger) -> a
f _ = undefined
</code>```

...then only f x will type check, not f y.

N.B. Removing items from the sequence is left as an exercise for the reader.

EDIT: Upon further consideration I've decided the above is not at all terrible enough. Behold:

Some mysteriously familiar boilerplate:

```<code>data Yes = Yes
data No = No

class TypeEq' () x y b => TypeEq x y b | x y -> b
instance TypeEq' () x y b => TypeEq x y b

class TypeEq' q x y b | q x y -> b
class TypeEq'' q x y b | q x y -> b

instance TypeCast b Yes => TypeEq' () x x b
instance TypeEq'' q x y b => TypeEq' q x y b
instance TypeEq'' () x y No

class TypeCast   a b   | a -> b, b->a   where typeCast   :: a -> b
class TypeCast'  t a b | t a -> b, t b -> a where typeCast'  :: t->a->b
class TypeCast'' t a b | t a -> b, t b -> a where typeCast'' :: t->a->b
instance TypeCast'  () a b => TypeCast a b where typeCast x = typeCast' () x
instance TypeCast'' t a b => TypeCast' t a b where typeCast' = typeCast''
instance TypeCast'' () a a where typeCast'' _ x  = x
</code>```

A bit of general hackery:

```<code>infixr 1 :*:
data NIL
data h :*: t = h :*: t

class TIns x ys r | x ys -> r
instance TIns x NIL (x :*: NIL)
instance ( TypeEq x h b
         , TIns' b x h t r
         ) => TIns x (h :*: t) r

class TIns' b x h t r | b x h t -> r
instance TIns' Yes x h t (h :*: r)
instance (TIns x t r) => TIns' No x h t (h :*: r)

class TElem x ys r | x ys -> r
instance TElem x NIL No
instance (TypeEq x h b, TElem' b x h t r) => TElem x (h :*: t) r

class TElem' b x h t r | b x h t -> r
instance TElem' Yes x h t Yes
instance (TElem x t r) => TElem' No x h t r
</code>```

Aaaaaaaand the payoff:

```<code>data TSeq2 a b where
    TNil2  :: TSeq2 NIL NIL
    TCons2 :: (TIns x ys r) => T x -> TSeq2 xs ys -> TSeq2 (x :*: xs) r

class (TElem x ys Yes) => Has ys x
instance (TElem x ys Yes) => Has ys x

class HasAll ys xs
instance HasAll ys NIL
instance (ys `Has` h, ys `HasAll` t) => HasAll ys (h :*: t)

x2 = TCons2 TGoat (TCons2 TGoat (TCons2 TTiger (TCons2 TMonk TNil2)))

y2 = TCons2 TGoat TNil2

f2 :: (s `HasAll` (Goat :*: Tiger :*: Monk :*: NIL)) => TSeq2 q s -> a
f2 _ = undefined
</code>```

As with the above, f2 x2 typechecks, while f2 y2 fails.

This is still messy and rather painful to use, but far more generic!

And just to prove that the result can still be treated as an ordinary data type in other circumstances, here's an instance of Show:

```<code>instance Show (T a) where
    show TGoat = "TGoat"
    show TMonk = "TMonk"
    show TTiger = "TTiger"

instance Show (TSeq2 a b) where
    show TNil2 = "[]"
    show (TCons2 x xs) = concat [show x, ":", show xs]
</code>```

So now we can do things like show only sequences that contain all three kinds of item:

```<code>showTotal :: (s `HasAll` (Goat :*: Tiger :*: Monk :*: NIL)) => TSeq2 q s -> String
showTotal = show
</code>```

Body:
Let's say we have the following types:

sealed trait T
case object Goat extends T
case object Monk extends T
case object Tiger extends T

Now, how do you construct a collection of T such that at least one of each sub-T appears in the collection, this constraint being enforced at compile time? A collection where, contrary to this:

val s:Seq[T] = Seq(Goat)

which compiles, this:

val ts:TotalSeq[T] = TotalSeq(Goat, Goat, Tiger)

does not. I've used Scala above, but I would be happy to see solutions in other languages as well.

(Forgive me if my words are a bit off; I have a cold and am amusing myself today with puzzles.)

Body:
If I'm interpreting this correctly...

{-# LANGUAGE GADTs #-}
{-# LANGUAGE EmptyDataDecls #-}

data Goat
data Monk
data Tiger

data T a where
    TGoat  :: T Goat
    TMonk  :: T Monk
    TTiger :: T Tiger

data TSeq a where
    TNil :: TSeq ((), (), ())
    TG   :: T Goat -> TSeq ((), m, t) -> TSeq (Goat, m, t)
    TM   :: T Monk -> TSeq (g, (), t) -> TSeq (g, Monk, t)
    TT   :: T Tiger -> TSeq (g, m, ()) -> TSeq (g, m, Tiger)
    TCG  :: T Goat -> TSeq (Goat, m, t) -> TSeq (Goat, m, t)
    TCM  :: T Monk -> TSeq (g, Monk, t) -> TSeq (g, Monk, t)
    TCT  :: T Tiger -> TSeq (g, m, Tiger) -> TSeq (g, m, Tiger)

Be aware that no attempt has been made to make this usable. It's incredibly clumsy.

Now, given these values:

x = TCG TGoat (TG TGoat (TT TTiger (TM TMonk TNil)))

y = TG TGoat TNil

And this function:

f :: TSeq (Goat, Monk, Tiger) -> a
f _ = undefined

...then only f x will type check, not f y.

N.B. Removing items from the sequence is left as an exercise for the reader.

EDIT: Upon further consideration I've decided the above is not at all terrible enough. Behold:

Some mysteriously familiar boilerplate:

data Yes = Yes
data No = No

class TypeEq' () x y b => TypeEq x y b | x y -> b
instance TypeEq' () x y b => TypeEq x y b

class TypeEq' q x y b | q x y -> b
class TypeEq'' q x y b | q x y -> b

instance TypeCast b Yes => TypeEq' () x x b
instance TypeEq'' q x y b => TypeEq' q x y b
instance TypeEq'' () x y No

class TypeCast   a b   | a -> b, b->a   where typeCast   :: a -> b
class TypeCast'  t a b | t a -> b, t b -> a where typeCast'  :: t->a->b
class TypeCast'' t a b | t a -> b, t b -> a where typeCast'' :: t->a->b
instance TypeCast'  () a b => TypeCast a b where typeCast x = typeCast' () x
instance TypeCast'' t a b => TypeCast' t a b where typeCast' = typeCast''
instance TypeCast'' () a a where typeCast'' _ x  = x

A bit of general hackery:

infixr 1 :*:
data NIL
data h :*: t = h :*: t

class TIns x ys r | x ys -> r
instance TIns x NIL (x :*: NIL)
instance ( TypeEq x h b
         , TIns' b x h t r
         ) => TIns x (h :*: t) r

class TIns' b x h t r | b x h t -> r
instance TIns' Yes x h t (h :*: r)
instance (TIns x t r) => TIns' No x h t (h :*: r)

class TElem x ys r | x ys -> r
instance TElem x NIL No
instance (TypeEq x h b, TElem' b x h t r) => TElem x (h :*: t) r

class TElem' b x h t r | b x h t -> r
instance TElem' Yes x h t Yes
instance (TElem x t r) => TElem' No x h t r

Aaaaaaaand the payoff:

data TSeq2 a b where
    TNil2  :: TSeq2 NIL NIL
    TCons2 :: (TIns x ys r) => T x -> TSeq2 xs ys -> TSeq2 (x :*: xs) r

class (TElem x ys Yes) => Has ys x
instance (TElem x ys Yes) => Has ys x

class HasAll ys xs
instance HasAll ys NIL
instance (ys `Has` h, ys `HasAll` t) => HasAll ys (h :*: t)

x2 = TCons2 TGoat (TCons2 TGoat (TCons2 TTiger (TCons2 TMonk TNil2)))

y2 = TCons2 TGoat TNil2

f2 :: (s `HasAll` (Goat :*: Tiger :*: Monk :*: NIL)) => TSeq2 q s -> a
f2 _ = undefined

As with the above, f2 x2 typechecks, while f2 y2 fails.

This is still messy and rather painful to use, but far more generic!

And just to prove that the result can still be treated as an ordinary data type in other circumstances, here's an instance of Show:

instance Show (T a) where
    show TGoat = "TGoat"
    show TMonk = "TMonk"
    show TTiger = "TTiger"

instance Show (TSeq2 a b) where
    show TNil2 = "[]"
    show (TCons2 x xs) = concat [show x, ":", show xs]

So now we can do things like show only sequences that contain all three kinds of item:

showTotal :: (s `HasAll` (Goat :*: Tiger :*: Monk :*: NIL)) => TSeq2 q s -> String
showTotal = show


问:
Uploading File to SharePoint from AWS Lambda Function
I have a lambda function (currently Node.js, but could be turned into .NET Core) that runs on a schedule. I would like to, as part of its work, to upload a file to a SharePoint Online document library. What would be the best way to do this, especially considering authentication?</p>

答:
I would use the Microsoft Graph APIs to upload files into Document Libraries of SharePoint Online

Microsoft Graph: Uploading Files to SharePoint


问:
Need help setting my default API Route on SwashBuckle (AzureFunctions)
So TL;DR I've been learning how to incorporate shwashbuckle into Azure Functions and It's been working pretty well so far, but I can't change my default route prefix.

I was able to change a number of other properties like title, servers, etc, but I really need the default api to come out as just /path instead of /api/path, if that makes sense.

I'll post my code below and hopefully some of you guys will be able to help me.

Function:

```<code>namespace SwashBuckleExample.Functions.Functions
{
    public class GetClubByClubNameHttp
    {
        private ISwashBuckleExampleProcess _process;
        private ILogger<GetClubByClubNameHttp> _logger;

        public GetClubByClubNameHttp(ISwashBuckleExampleProcess process, ILogger<GetClubByClubNameHttp> logger)
        {
            _process = process;
            _logger = logger;
        }

        /// <summary>
        /// Function that runs GetClubByNameProcess
        /// </summary>
        /// <param name="req">HttpRequest</param>
        /// <returns>SwashBuckleExampleSuccessResponse Item</returns>
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(SwashBuckleExampleSuccessResponse))]
        [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(SwashBuckleExampleBaseResponse))]
        [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(SwashBuckleExampleBaseResponse))]
        [FunctionName("GetClubByClubNameHttp")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            [RequestBodyType(typeof(SwashBuckleExampleClubNameRequest), "Contains Club Name used for searching purposes")]HttpRequest req)
        {
            _logger.LogInformation("C# HTTP trigger function UpdateClientHttp");

            //Read Query parameters

            //Read RequestBody
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            //Decouple Requests

            SwashBuckleExampleClubNameRequest request = JsonConvert.DeserializeObject<SwashBuckleExampleClubNameRequest>(requestBody);

            //Make all pipeline Request
            var responseObject = _process.GetClubByNameProcess(request);
            return !responseObject.HasErrors ? (ObjectResult)new OkObjectResult(responseObject) : (ObjectResult)new BadRequestObjectResult(responseObject);
        }
    }
}
</code>```

SwashBuckleStartup:

```<code>using System.Reflection;
using AzureFunctions.Extensions.Swashbuckle;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.DependencyInjection;
using SwashBuckleExample.Functions;
using SwashBuckleExample.Functions.SwaggerFunctions.SwaggerDocumentFilter;

[assembly: WebJobsStartup(typeof(SwashBuckleStartup))]
namespace SwashBuckleExample.Functions
{
    internal class SwashBuckleStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            //Register the extension
            builder.AddSwashBuckle(Assembly.GetExecutingAssembly(), c =>
            {
                c.ConfigureSwaggerGen = (d => d.DocumentFilter<SwashBuckleExampleDocumentFilter>());
            });
        }
    }
}
</code>```

DocumentFilter:

```<code>namespace SwashBuckleExample.Functions.SwaggerFunctions.SwaggerDocumentFilter
{
    public class SwashBuckleExampleDocumentFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            swaggerDoc.Info.Title = "SwashBuckleExample";
            swaggerDoc.Info.Version = "v1";
            swaggerDoc.Servers = new List<OpenApiServer>() { new OpenApiServer() { Url = "LinkToServer" } };
        }
    }
}
</code>```

Thank you for your help.

ps:

I need to remove this parameter that always shows up and I don't know why. Is there any way to do so?
Parameters

答:
1. How to change Azure function default route prefix.

If we want to change Azure function default route prefix, we can implement it by setting routePrefix specified in the host.json. For more details, please refer to here and here.

For example

Add the following settings in your host.json file.

```<code>{
  "version": "2.0",
  "extensions": {

    "http": {
      "routePrefix" : ""
    }
  },
  ....
}
</code>```

2. Why does your swagger file have query parameter code?

The reason for this situation is that you set the Azure function HTTP trigger auth level as Function or Admin with code HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]. After doing that, we need to provide the function key or host key to be included in a query string variable named code when we call the function. Its URL should be likehttps://<APP_NAME>.azurewebsites.net/api/<FUNCTION_NAME>?code=<API_KEY>. For more details, please refer to the document

For example

My code

```<code>[ProducesResponseType(typeof(TestModel[]), (int)HttpStatusCode.OK)]
        [FunctionName("TestGets")]
        public async Task<IActionResult> Gets([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "test")]
            HttpRequest request)
        {
            return new OkObjectResult(new[] { new TestModel(), new TestModel() });
        }

        [ProducesResponseType(typeof(TestModel), (int)HttpStatusCode.Created)]
        [FunctionName("TestAdd")]
        public Task<IActionResult> Add([HttpTrigger(AuthorizationLevel.Function, "post", Route = "test")]
            TestModel testModel)
        {
            return Task.FromResult<IActionResult>(new CreatedResult("", testModel));
        }
</code>```

So if you want to remove the parameter, please update code as [HttpTrigger(AuthorizationLevel.Anonymous,...)

For example
My code

```<code>ProducesResponseType(typeof(TestModel), (int)HttpStatusCode.Created)]
        [FunctionName("TestAdd")]
        public Task<IActionResult> Add([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "test")]
            TestModel testModel)
        {
            return Task.FromResult<IActionResult>(new CreatedResult("", testModel));
        }
</code>```

Body:
So TL;DR I've been learning how to incorporate shwashbuckle into Azure Functions and It's been working pretty well so far, but I can't change my default route prefix.

I was able to change a number of other properties like title, servers, etc, but I really need the default api to come out as just /path instead of /api/path, if that makes sense.

I'll post my code below and hopefully some of you guys will be able to help me.

Function:

namespace SwashBuckleExample.Functions.Functions
{
    public class GetClubByClubNameHttp
    {
        private ISwashBuckleExampleProcess _process;
        private ILogger<GetClubByClubNameHttp> _logger;

        public GetClubByClubNameHttp(ISwashBuckleExampleProcess process, ILogger<GetClubByClubNameHttp> logger)
        {
            _process = process;
            _logger = logger;
        }

        ///
        /// Function that runs GetClubByNameProcess
        ///
        /// <param name="req">HttpRequest</param>
        /// <returns>SwashBuckleExampleSuccessResponse Item</returns>
        [ProducesResponseType((int)HttpStatusCode.OK, Type = typeof(SwashBuckleExampleSuccessResponse))]
        [ProducesResponseType((int)HttpStatusCode.InternalServerError, Type = typeof(SwashBuckleExampleBaseResponse))]
        [ProducesResponseType((int)HttpStatusCode.BadRequest, Type = typeof(SwashBuckleExampleBaseResponse))]
        [FunctionName("GetClubByClubNameHttp")]
        public async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]
            [RequestBodyType(typeof(SwashBuckleExampleClubNameRequest), "Contains Club Name used for searching purposes")]HttpRequest req)
        {
            _logger.LogInformation("C# HTTP trigger function UpdateClientHttp");

            //Read Query parameters

            //Read RequestBody
            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();

            //Decouple Requests

            SwashBuckleExampleClubNameRequest request = JsonConvert.DeserializeObject<SwashBuckleExampleClubNameRequest>(requestBody);

            //Make all pipeline Request
            var responseObject = _process.GetClubByNameProcess(request);
            return !responseObject.HasErrors ? (ObjectResult)new OkObjectResult(responseObject) : (ObjectResult)new BadRequestObjectResult(responseObject);
        }
    }
}

SwashBuckleStartup:

using System.Reflection;
using AzureFunctions.Extensions.Swashbuckle;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Hosting;
using Microsoft.Extensions.DependencyInjection;
using SwashBuckleExample.Functions;
using SwashBuckleExample.Functions.SwaggerFunctions.SwaggerDocumentFilter;

[assembly: WebJobsStartup(typeof(SwashBuckleStartup))]
namespace SwashBuckleExample.Functions
{
    internal class SwashBuckleStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
            //Register the extension
            builder.AddSwashBuckle(Assembly.GetExecutingAssembly(), c =>
            {
                c.ConfigureSwaggerGen = (d => d.DocumentFilter<SwashBuckleExampleDocumentFilter>());
            });
        }
    }
}

DocumentFilter:

namespace SwashBuckleExample.Functions.SwaggerFunctions.SwaggerDocumentFilter
{
    public class SwashBuckleExampleDocumentFilter : IDocumentFilter
    {
        public void Apply(OpenApiDocument swaggerDoc, DocumentFilterContext context)
        {
            swaggerDoc.Info.Title = "SwashBuckleExample";
            swaggerDoc.Info.Version = "v1";
            swaggerDoc.Servers = new List<OpenApiServer>() { new OpenApiServer() { Url = "LinkToServer" } };
        }
    }
}

Thank you for your help.

ps:

I need to remove this parameter that always shows up and I don't know why. Is there any way to do so?
Parameters

Body:
1. How to change Azure function default route prefix.

If we want to change Azure function default route prefix, we can implement it by setting routePrefix specified in the host.json. For more details, please refer to here and here.

For example

Add the following settings in your host.json file.

{
  "version": "2.0",
  "extensions": {

    "http": {
      "routePrefix" : ""
    }
  },
  ....
}

2. Why does your swagger file have query parameter code?

The reason for this situation is that you set the Azure function HTTP trigger auth level as Function or Admin with code HttpTrigger(AuthorizationLevel.Function, "post", Route = null)]. After doing that, we need to provide the function key or host key to be included in a query string variable named code when we call the function. Its URL should be likehttps://<APP_NAME>.azurewebsites.net/api/<FUNCTION_NAME>?code=<API_KEY>. For more details, please refer to the document

For example

My code

[ProducesResponseType(typeof(TestModel[]), (int)HttpStatusCode.OK)]
        [FunctionName("TestGets")]
        public async Task<IActionResult> Gets([HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "test")]
            HttpRequest request)
        {
            return new OkObjectResult(new[] { new TestModel(), new TestModel() });
        }

        [ProducesResponseType(typeof(TestModel), (int)HttpStatusCode.Created)]
        [FunctionName("TestAdd")]
        public Task<IActionResult> Add([HttpTrigger(AuthorizationLevel.Function, "post", Route = "test")]
            TestModel testModel)
        {
            return Task.FromResult<IActionResult>(new CreatedResult("", testModel));
        }

So if you want to remove the parameter, please update code as [HttpTrigger(AuthorizationLevel.Anonymous,...)

For example
My code

ProducesResponseType(typeof(TestModel), (int)HttpStatusCode.Created)]
        [FunctionName("TestAdd")]
        public Task<IActionResult> Add([HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "test")]
            TestModel testModel)
        {
            return Task.FromResult<IActionResult>(new CreatedResult("", testModel));
        }


问:
Docker for Magento 2 Development
Original Post:

Install Magento 2! Before copying and pasting the command shown below into the Docker terminal
Erreur : SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known
url : https://www.magemodule.com/all-things-magento/magento-2-tutorials/docker-magento-2-development/#install-docker

Additional notes from the comment:

After this command : php bin/magento setup:install \ --admin-firstname=John \ --admin-lastname=Doe \ --admin-email=johndoe@example.com \ --admin-user=admin \ --admin-password='SomePassword123' \ --base-url=local.domain.com \ --base-url-secure=local.domain.com \ --backend-frontname=admin \ --db-host=mysql \ --db-name=magento \ --db-user=root \ --db-password=root \ --use-rewrites=1 \ --language=en_US \ --currency=USD \ --timezone=America/New_York \ --use-secure-admin=1 \ --admin-use-security-key=1 \ --session-save=files \ --use-sample-data

答:
1-you must have a php version 7 imperatively
2-php bin/magento sampledata:deploy (recommended)
3 -Finally, Let’s Install Magento 2! (Install Magento 2! Before copying and pasting the command shown below into the Docker terminal ) (step 4)
you have to do this step (step 4 ) after :
docker exec -it web bash and cd /app

worked --> OK

Title: Docker for Magento 2 Development


问:
MVVM ViewModel default constructor
I have been getting up to speed with the MVVM pattern in Silverlight and was wondering how to implement binding from the View to the ViewModel when the ViewModel constructor has a parameter if an interface type.

If I bind the viewmodel to the view in XAML then you can not use a parameterised constructor. Given that I was creating a default constructor passing an instance to the parameterised constructor but this breaks the abstraction.

View

```<code><navigation:Page x:Class="QSmart.DataViewer.Report.RecentFailures.Report"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           mc:Ignorable="d"
           xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           xmlns:local="clr-namespace:QSmart.DataViewer.Report.RecentFailures"
           d:DesignWidth="640" d:DesignHeight="480"
           Title="Report Page" xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation">
    <UserControl.Resources>
        <local:ReportViewModel x:Key="ViewModel"/>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" DataContext="{StaticResource ViewModel}" >
        <telerik:RadGridView Name="RadGridView1" ItemsSource="{Binding Path=Faults,Mode=OneWay}" AutoGenerateColumns="True" />
    </Grid>
</navigation:Page>
</code>```

View Model

```<code>Public Sub New(ByVal serviceDataAgent As IRecentFailuresReportServiceAgent)
    If Not IsInDesignMode Then
        If serviceDataAgent IsNot Nothing Then
            ServiceAgent = serviceDataAgent
        End If
        Messenger.Default.Register(Of RecentFailuresMessage)(Me, Sub(m) ChangeReportSettings(m))
        LoadData()
    End If
End Sub
</code>```

What is the method to get around this? Is it recommended to use the code behind of the view to pass into the parameterised constructor and then bind to the viewmodel?

答: You can use an IoC container to create your objects, including view and view model. When doing this, the container will try to satisfy all needed components by your view model, if possible.</p>

Title: MVVM ViewModel default constructor

Body:
I have been getting up to speed with the MVVM pattern in Silverlight and was wondering how to implement binding from the View to the ViewModel when the ViewModel constructor has a parameter if an interface type.

If I bind the viewmodel to the view in XAML then you can not use a parameterised constructor. Given that I was creating a default constructor passing an instance to the parameterised constructor but this breaks the abstraction.

View

<navigation:Page x:Class="QSmart.DataViewer.Report.RecentFailures.Report"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
           xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
           xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
           mc:Ignorable="d"
           xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           xmlns:local="clr-namespace:QSmart.DataViewer.Report.RecentFailures"
           d:DesignWidth="640" d:DesignHeight="480"
           Title="Report Page" xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation">
    <UserControl.Resources>
        <local:ReportViewModel x:Key="ViewModel"/>
    </UserControl.Resources>
    <Grid x:Name="LayoutRoot" DataContext="{StaticResource ViewModel}" >
        <telerik:RadGridView Name="RadGridView1" ItemsSource="{Binding Path=Faults,Mode=OneWay}" AutoGenerateColumns="True" />
    </Grid>
</navigation:Page>

View Model

Public Sub New(ByVal serviceDataAgent As IRecentFailuresReportServiceAgent)
    If Not IsInDesignMode Then
        If serviceDataAgent IsNot Nothing Then
            ServiceAgent = serviceDataAgent
        End If
        Messenger.Default.Register(Of RecentFailuresMessage)(Me, Sub(m) ChangeReportSettings(m))
        LoadData()
    End If
End Sub

What is the method to get around this? Is it recommended to use the code behind of the view to pass into the parameterised constructor and then bind to the viewmodel?


问:
how can i return value from this function?
https://coinpaprika.github.io/coinpaprika-api-swift-client/index.html</p>

```<code>func gettingFunction(name: String){
    Coinpaprika.API.coins().perform { (response) in
      switch response {
      case .success(let coins):

                return coins[0].id // i want return this value

        case .failure(let error):
        print(error)
        // Failure reason as error
      }

    }

}
</code>```

答:
It is an async call so you can use completion to do this. And you can pass Result type in completion with values

func gettingFunction(name: String, _ completion: @escaping (Result<Int, Error>) -> Void {
    Coinpaprika.API.coins().perform { response in
        switch response {
        case .success(let coins):

            completion(.success(coins[0].id))

        case .failure(let error):
            print(error)
            completion(.failure(error))
      }

    }
}
```

<hr>

<p>Usage</p>

<pre class="lang-swift prettyprint-override"><code>gettingFunction(name: "asd") { result in
    switch result {
    case .success(let id):
        print("ID is:", id)
    case .failure(let error):
        print("Error is:", error)
    }
}
</code>```

If you want to use the value in another function. You should call this function in .success case because we have the ID value in this case.

gettingFunction(name: "asd") { result in
    switch result {
    case .success(let id):
        print("ID is:", id)
        anotherFunction(id: id)

    case .failure(let error):
        print("Error is:", error)
    }
}
```

Body:
https://coinpaprika.github.io/coinpaprika-api-swift-client/index.html

func gettingFunction(name: String){
    Coinpaprika.API.coins().perform { (response) in
      switch response {
      case .success(let coins):

                return coins[0].id // i want return this value

        case .failure(let error):
        print(error)
        // Failure reason as error
      }

    }

}

Body:
It is an async call so you can use completion to do this. And you can pass Result type in completion with values

func gettingFunction(name: String, _ completion: @escaping (Result<Int, Error>) -> Void {
    Coinpaprika.API.coins().perform { response in
        switch response {
        case .success(let coins):

            completion(.success(coins[0].id))

        case .failure(let error):
            print(error)
            completion(.failure(error))
      }

    }
}

Usage

gettingFunction(name: "asd") { result in
    switch result {
    case .success(let id):
        print("ID is:", id)
    case .failure(let error):
        print("Error is:", error)
    }
}

If you want to use the value in another function. You should call this function in .success case because we have the ID value in this case.

gettingFunction(name: "asd") { result in
    switch result {
    case .success(let id):
        print("ID is:", id)
        anotherFunction(id: id)

    case .failure(let error):
        print("Error is:", error)
    }
}


问:
Make multiple API calls and return combined response in minimum time
I have 10 health check URLs which are simply get service
I am hitting them in a loop like below

```<code>for(int i=0;i<10;i++){
  Response response = given().when().relaxedHttpsValidation().get(url[i]);
   list.add(response);
  }
   return list;
</code>```

Now the problem is it hits API in series and waiting for a response for all, I just want to hit all API in parallel but combine the result, I tried using threads but unable to get an idea on how to combine the response in case of multi-threading

答:
If I am reading your question right I believe you want to make parallel calls and combine the results, and in that case I would suggest you to make use of TestNG. I had a similar requirement in the past and this link helped me out

Here's a sample code

```<code>public class Parallel {

    @DataProvider(parallel = true)
    public Object[] getURL() {
        return new Object[] { "https://reqres.in/api/users/1", "https://reqres.in/api/users/2",
                "https://reqres.in/api/users/3", "https://reqres.in/api/users/4", "https://reqres.in/api/users/5",
                "https://reqres.in/api/users/6" };
    }

    ArrayList<String> original = new ArrayList<String>();

    @Test(dataProvider = "getURL")
    public void stack(String url) {

        Response response = given().when().get(url);

        JsonPath js = response.jsonPath();

        String email = js.getString("data.email");

        original.add(js.getString("data.email"));
    }

    @AfterTest
    public void simple() {
        System.out.println("List : " + original);
    }

}
</code>```

Just remove (parallel = true) to see how it works sequentially. I have extracted the email field from the response using JSONPath and added to the list

Don't forget to update the POM

Body:
I have 10 health check URLs which are simply get service
I am hitting them in a loop like below

for(int i=0;i<10;i++){
  Response response = given().when().relaxedHttpsValidation().get(url[i]);
   list.add(response);
  }
   return list;

Now the problem is it hits API in series and waiting for a response for all, I just want to hit all API in parallel but combine the result, I tried using threads but unable to get an idea on how to combine the response in case of multi-threading

Body:
If I am reading your question right I believe you want to make parallel calls and combine the results, and in that case I would suggest you to make use of TestNG. I had a similar requirement in the past and this link helped me out

Here's a sample code

public class Parallel {

    @DataProvider(parallel = true)
    public Object[] getURL() {
        return new Object[] { "https://reqres.in/api/users/1", "https://reqres.in/api/users/2",
                "https://reqres.in/api/users/3", "https://reqres.in/api/users/4", "https://reqres.in/api/users/5",
                "https://reqres.in/api/users/6" };
    }

    ArrayList<String> original = new ArrayList<String>();

    @Test(dataProvider = "getURL")
    public void stack(String url) {

        Response response = given().when().get(url);

        JsonPath js = response.jsonPath();

        String email = js.getString("data.email");

        original.add(js.getString("data.email"));
    }

    @AfterTest
    public void simple() {
        System.out.println("List : " + original);
    }

}

Just remove (parallel = true) to see how it works sequentially. I have extracted the email field from the response using JSONPath and added to the list

Don't forget to update the POM


问:
Extracting a Part of URL string in jmeter JSON response
I have the following JSON response to my request in JMeter:

```<code>{
"response":
 {"info":
{"success":"1",
"ticket":"http://43.252.88.109:4006/BracketICT/?t=aZCcbzidJJKfFgrkk1RYPH0zHTl+MtTuoGeiUw0hEw48nLZUoPrfntO29VV2daEiR3cPbu25/Xf2a3Q1UMZs1tG2BeMKvA0tCrq9+e3dTrWZ0Z1yTrWlkWEbAwmvRwAfMdoX+vDfKd30hW9CBVpyUsA==&uniqueID=dGdck61pZFhGwMJr0cAHzNruDU6ItF1s&dev=1696661"}}}
</code>```

I want to break my url into 3 parts extract and themin 3 different regex variables:
The value folllowing http://43.252.88.109:4006/BracketICT/?
 i.e.

```<code>t=aZCcbzidJJKfFgrkk1RYPH0zHTl+MtTuoGeiUw0hEw48nLZUoPrfntO29VV2daEiR3cPbu25/Xf2a3Q1UMZs1tG2BeMKvA0tCrq9+e3dTrWZ0Z1yTrWlkWEbAwmvRwAfMdoX+vDfKd30hW9CBVpyUsA==
</code>```

then the value following uniqueID i.e

```<code>=dGdck61pZFhGwMJr0cAHzNruDU6ItF1s
</code>```

and the value in dev

How this can be done using Regular expression extractor?

答:
You can use regular expression in 3 separate extractors:

```<code>t=([^&]+)
uniqueID=([^&]+)
dev=([^"]+)
</code>```

If you want also the = sign to be included move it inside brackets

You are searching for all characters different than & (or "), which marks the end of the string

Body:
I have the following JSON response to my request in JMeter:

{
"response":
 {"info":
{"success":"1",
"ticket":"http://43.252.88.109:4006/BracketICT/?t=aZCcbzidJJKfFgrkk1RYPH0zHTl+MtTuoGeiUw0hEw48nLZUoPrfntO29VV2daEiR3cPbu25/Xf2a3Q1UMZs1tG2BeMKvA0tCrq9+e3dTrWZ0Z1yTrWlkWEbAwmvRwAfMdoX+vDfKd30hW9CBVpyUsA==&uniqueID=dGdck61pZFhGwMJr0cAHzNruDU6ItF1s&dev=1696661"}}}

I want to break my url into 3 parts extract and themin 3 different regex variables:
The value folllowing http://43.252.88.109:4006/BracketICT/?
 i.e.

t=aZCcbzidJJKfFgrkk1RYPH0zHTl+MtTuoGeiUw0hEw48nLZUoPrfntO29VV2daEiR3cPbu25/Xf2a3Q1UMZs1tG2BeMKvA0tCrq9+e3dTrWZ0Z1yTrWlkWEbAwmvRwAfMdoX+vDfKd30hW9CBVpyUsA==

then the value following uniqueID i.e

=dGdck61pZFhGwMJr0cAHzNruDU6ItF1s

and the value in dev

How this can be done using Regular expression extractor?

Body:
You can use regular expression in 3 separate extractors:

t=([^&]+)
uniqueID=([^&]+)
dev=([^"]+)

If you want also the = sign to be included move it inside brackets

You are searching for all characters different than & (or "), which marks the end of the string


问:
Regex for special char
Can anyone help to get a regex build for below input string,I need to extract the the data which is marked ☒.
Eg:-

Input text:-

```<code>☐I am good
☐This is sky
☒Nice to meet you
☐hello world
</code>```

Output :-
    Nice to meet you

答:
Just use

```<code>^☒.+
</code>```

See a demo on regex101.com.

If you happen to have it in one line, you may use

```<code>☒[^☐\n]+
</code>```

See another demo on regex101.com.

Title: Regex for special char

Body:
Can anyone help to get a regex build for below input string,I need to extract the the data which is marked ☒.
Eg:-

Input text:-

☐I am good
☐This is sky
☒Nice to meet you
☐hello world

Output :-
    Nice to meet you

Body:
Just use

^☒.+

See a demo on regex101.com.

If you happen to have it in one line, you may use

☒[^☐\n]+

See another demo on regex101.com.


问:
Lights in A-Frame have striped artifacts depending on distance from them
I am using the latest A-Frame 1.0.4 and I have tried both with spot light (in the picture attached) and with direct light.

The shadowBias is set to -0.0001, changing it affects the artifact only slightly.

If I set the shadowMapHeight and shadowMapWidth to 1024 the artifact shrinks back a bit from the source of light. To have it completely disappear I have to put 4096, which is a bit too much, performance-wise. I can't have all lights with a 4k shadow map.

A similar effect has increasing the shadowCamera far, from 500 to 5000 for example. but this introduces wrong shadows, distant from the objects (even if I tweak the shadowBias).

Am I doing something wrong? Why the lights with default settings have these problems? Does it perhaps depend on the models ?

Any clue would be appreciated

答:
I was able to find the culprit! My models are double sided, and this resulted into the front face casting shadow on the back face together with the back face casting shadow on the front face, hence the striped glitch.

After having a look at three.js - material and confirming with material.side that it was actually double sided, I used material.shadowSide = THREE.BackSide to force the backside to cast shadow onto the frontside, regardless of the model/material double side property.
This solved the glitch!

Of course be mindful that if a model has wrong normals i.e. don't facing towards the outside / inverted , that face will have the glitch again.


问:
How to run Kafka-Connect in Minikube?
To run cp S3-connect to consume kafka topic in my local mac, I did something like below

```<code>    1. Installed Confluent Kafka connector and ran the kafka connect-standalone.sh
ML-C02Z605SLVDQ:kafka_2.12-2.5.0 e192270$ confluent-hub install confluentinc/kafka-connect-s3:latest --component-dir /usr/local/share/java --worker-configs config/connect-distributed.properties

ML-C02Z605SLVDQ:kafka_2.12-2.5.0 e192270$ cd kafka_2.12-2.5.0

ML-C02Z605SLVDQ:kafka_2.12-2.5.0 e192270$ bin/connect-standalone.sh config/connect-standalone.properties s3-sink.properties. // s3-sink.properties connector.class=io.confluent.connect.s3.S3SinkConnector
</code>```

Now, to run Kafka S3 connect in minikube I have installed Kafka-connect(kafka-connect-s3) in minikube using cp-helm-charts with help this tutorial Using a connector with Helm-installed Kafka/Confluent.

How to copy kafka config and script files inside kafka-connect pod ?

Should I need to login kafka-connect pod to run
connect-standalone.sh command?

答:
You can also take a look at https://strimzi.io/.
The project is aimed at making the installation and management of a Kafka and Kafka Connect cluster on Kubernetes very easy.</p>

Title: How to run Kafka-Connect in Minikube?

Body:
To run cp S3-connect to consume kafka topic in my local mac, I did something like below

    1. Installed Confluent Kafka connector and ran the kafka connect-standalone.sh
ML-C02Z605SLVDQ:kafka_2.12-2.5.0 e192270$ confluent-hub install confluentinc/kafka-connect-s3:latest --component-dir /usr/local/share/java --worker-configs config/connect-distributed.properties

ML-C02Z605SLVDQ:kafka_2.12-2.5.0 e192270$ cd kafka_2.12-2.5.0

ML-C02Z605SLVDQ:kafka_2.12-2.5.0 e192270$ bin/connect-standalone.sh config/connect-standalone.properties s3-sink.properties. // s3-sink.properties connector.class=io.confluent.connect.s3.S3SinkConnector

Now, to run Kafka S3 connect in minikube I have installed Kafka-connect(kafka-connect-s3) in minikube using cp-helm-charts with help this tutorial Using a connector with Helm-installed Kafka/Confluent.

How to copy kafka config and script files inside kafka-connect pod ?

Should I need to login kafka-connect pod to run
connect-standalone.sh command?


问:
How to update a MVC Form before Submit
So i have 2 Viewbags, they each have a list of values from a database table, the first Viewbag have all possible values of a database column, while the other have only the values corresponding to the selected  value in the first Viewbag.
I have the logic for the search.
but i need to have the form update after selecting one value, since they both need to be in the same form, it is not searching for the second value.

OBS:i am only using the controllers, and cshtml views, not razor pages.

答:
Here is a simple demo how to create cascading selectlist in asp.net core mvc:

Model:

```<code>public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class SubCategory
{
    public int Id { get; set; }
    public int CategoryId { get; set; }
    public string SubCategoryName { get; set; }
}
</code>```

View(Index.cshtml):

```<code><div>
    <div style="float:left;width:40%">
        <form id="form">
            <div class="form-group row">
                <label>Category Name</label>
                <div class="col-12">
                    <select id="CategoryId" class="custom-select mr-sm-2"
                            asp-items="@(new SelectList( @ViewBag.Category,"Id","Name"))">
                        <option value="">Please Select</option>
                    </select>
                </div>
            </div>
            <div class="form-group row">
                <label>SubCategory Name</label>
                <div class="col-12">
                    <select id="SubCategoryId" class="custom-select mr-sm-2"
                            asp-items="@(new SelectList(string.Empty,"Id","SubCategoryName"))">
                        <option value="">Please Select</option>
                    </select>
                </div>
            </div>
            <div>
                <input type="button" value="Search" />
            </div>
        </form>

    </div>
</div>

@section Scripts
{
    <script>
    $(function () {
        $('#CategoryId').change(function () {
            var data = $("#CategoryId").val();
            $.ajax({
                url: '/Home/GetSubCategory?CategoryId=' + data,
                type: 'Get',
                success: function (data) {
                    var items = "";
                    $.each(data, function (i, item) {
                        items += "<option value='" + item.value + "'>" + item.text + "</option>";
                    });
                    $('#SubCategoryId').html(items);
                }
            })
        });
    })
    </script>
}
</code>```

Controller:

```<code>public class HomeController : Controller
{
    private readonly MvcProj3Context _context;
    public HomeController(MvcProj3Context context)
    {
        _context = context;
    }
    public IActionResult Index()
    {
        ViewBag.Category = _context.Category.ToList();
        return View();
    }
    public JsonResult GetSubCategory(int CategoryId)
    {
        ViewBag.SubCategory = (from m in _context.SubCategory
                               where m.CategoryId == CategoryId
                               select m).ToList();
        return Json(new SelectList(ViewBag.SubCategory, "Id", "SubCategoryName"));
   }
}
</code>```

Result:

Title: How to update a MVC Form before Submit

Body:
Here is a simple demo how to create cascading selectlist in asp.net core mvc:

Model:

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class SubCategory
{
    public int Id { get; set; }
    public int CategoryId { get; set; }
    public string SubCategoryName { get; set; }
}

View(Index.cshtml):

<div>
    <div style="float:left;width:40%">
        <form id="form">
            <div class="form-group row">
                <label>Category Name</label>
                <div class="col-12">
                    <select id="CategoryId" class="custom-select mr-sm-2"
                            asp-items="@(new SelectList( @ViewBag.Category,"Id","Name"))">
                        <option value="">Please Select</option>
                    </select>
                </div>
            </div>
            <div class="form-group row">
                <label>SubCategory Name</label>
                <div class="col-12">
                    <select id="SubCategoryId" class="custom-select mr-sm-2"
                            asp-items="@(new SelectList(string.Empty,"Id","SubCategoryName"))">
                        <option value="">Please Select</option>
                    </select>
                </div>
            </div>
            <div>
                <input type="button" value="Search" />
            </div>
        </form>

    </div>
</div>

@section Scripts
{
    <script>
    $(function () {
        $('#CategoryId').change(function () {
            var data = $("#CategoryId").val();
            $.ajax({
                url: '/Home/GetSubCategory?CategoryId=' + data,
                type: 'Get',
                success: function (data) {
                    var items = "";
                    $.each(data, function (i, item) {
                        items += "<option value='" + item.value + "'>" + item.text + "</option>";
                    });
                    $('#SubCategoryId').html(items);
                }
            })
        });
    })
    </script>
}

Controller:

public class HomeController : Controller
{
    private readonly MvcProj3Context _context;
    public HomeController(MvcProj3Context context)
    {
        _context = context;
    }
    public IActionResult Index()
    {
        ViewBag.Category = _context.Category.ToList();
        return View();
    }
    public JsonResult GetSubCategory(int CategoryId)
    {
        ViewBag.SubCategory = (from m in _context.SubCategory
                               where m.CategoryId == CategoryId
                               select m).ToList();
        return Json(new SelectList(ViewBag.SubCategory, "Id", "SubCategoryName"));
   }
}

Result:


问:
Why does Xtext no longer generates Xtend classes?
I am refactoring an Xtext project developed on an older version and notice that, by default, the Xtext framework now generates Java classes in place of what used to be Xtend classes.

Is the Xtext project moving towards Java recently? Is this to harness Java's updates? What does it mean for Xtend within Xtext?

I am curious because my project uses a lot of extension methods and string templates, so I need to know if I should update my code at some point.

答:
https://blogs.itemis.com/en/xtext-2.20-release

To be more specific, we still think that Xtend is the most powerful language supporting template expressions. The most common use case for this are code generators. Besides that, writing unit tests with Xtend feels much cleaner than with Java.
  However, we decided to encourage to use Xtend only for these areas, and not as the primary general-purpose language. And we start doing this with the “New Project” wizard. The configuration that this wizard creates for a new Xtext project, will now use Java as the language for generated skeleton classes, so that newly-created projects (and especially new users) are using Java by default.

The Xtext project started to discourage the usage of Xtend where the latter’s language features do not have a significant benefit over Java. And internally, the project started to refactor the codebase to follow this recommendation.


问:
Python, how to calculate the difference between lists
I have list

a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]

and need to calculate the difference between two neighbor points in this list.

For example, (B-A), (C-B), (D-C) and get this output:

output = [(20, -2), (43, 7), (-70, 0)

Are there any fast ways how to do it?

答:
```<code>from operator import sub
a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]
for i in range(len(a)-1):
    print(tuple(map(sub, a[i+1][1:],a[i][1:])))
</code>```

Try this. Also show us what you have tried.

Body:
from operator import sub
a = [('A', 10, 7), ('B', 30, 5), ('C', 73, 12), ('D', 3, 12)]
for i in range(len(a)-1):
    print(tuple(map(sub, a[i+1][1:],a[i][1:])))

Try this. Also show us what you have tried.


问:
Azure Storage - Is it possible to create two or more static website containers in one storage account?
I'm wondering if is supported or possible to manage several static file web servers in the same storage account.

Looking around in the options for Static Website in an Azure Storage account, it only has a toogle an only one primary endpoint and an associated container to serve the static website (named $web).

Is there a way to setup the account to provide two Static Website containers?

答:
If you are asking about Static Web sites (Preview service) , the answer is NO

However if you are looking for static sites with Blob storage, Yes you can do it, You can deploy static SPAs in subfolders and have multiple at the same time on different subfolders.


问:
UDF calling external C++ code inside SQL Server
Suposse I have an UDF in SQL Server 2008:

```<code>Create function dbo.ReadXml (@xmlMatrix xml) returns table
as
return
( select
   --SOME C++ CODE
)
go
</code>```

Is it possible to add a c++ code or call a c++ function inside the UDF?

答:
Onyl if this C++ function was compiled and installed as an extended stored procedure.

But extended stored procedures are deprecated and will be removed soon.

So your only reliable option is to write a CLR function. It can be a C# CLR function that calls an external C++ dll, or it might be a managed C++ CLR function that would contain your code directly.

Body:
Suposse I have an UDF in SQL Server 2008:

Create function dbo.ReadXml (@xmlMatrix xml) returns table
as
return
( select
   --SOME C++ CODE
)
go

Is it possible to add a c++ code or call a c++ function inside the UDF?