问:
Horizontally align text from two different divs
I have the following structure of html code :

```<code><link rel="stylesheet" href="test.css" />

<div class="row">
  <div class="container">
    <p class="content">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.
    </p>
    <p class="align">Should be aligned</p>
  </div>

  <div class="container">
    <p class="content">Very short text</p>

    <p class="align">Should be aligned</p>
    <p>Some more text here</p>
  </div>
</div>
</code>```

Here is my css :

```<code>.container {
  display: flex;
  flex-direction: column;
  width: 40%;
  margin-right: 20px;
}

.row {
  display: flex;
  flex-direction: row;
}
</code>```

I am trying to find a way to horizontally align the two element with the align class but I can not figure it out. I have to precise that the content of the element with "content" class could be anything so I need a solution that works in every case.

(If you have a solution using some Js code it is ok)

Here is a Jsfiddle demo.

Actual result is this :

And this is what I want to achieve :

The text should go where the arrow point to be aligned with the left text, and the "Some more text" should be after the aligned text I hope it's clear now

Thank you very much for your time !

答:
You can't do that with that HTML structure. You need to wrap the two
 in a
.

Then use a display:grid; and grid-template-row:2fr 1fr; in .container to define that the first divs consume about x2 the space from the second divs and get aligned properly.

.row {
  display: flex;
  flex-direction: row;
}

.container {
  display: grid;
  grid-template-rows: 2fr 1fr;
  width: 40%;
  margin-right: 20px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="row">
  <div class="container">
    <p class="content">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
    <p class="align">Should be aligned</p>
  </div>

  <div class="container">
    <p class="content">Very short text</p>
    <div>
      <p class="align">Should be aligned</p>
      <p>Some more text here</p>
    </div>
  </div>
</div></code>```

Body:
I have the following structure of html code :

<link rel="stylesheet" href="test.css" />

      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod
      tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
      veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
      commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
      velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
      cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
      est laborum.

Should be aligned

Very short text

Should be aligned

Some more text here

Here is my css :

.container {
  display: flex;
  flex-direction: column;
  width: 40%;
  margin-right: 20px;
}

.row {
  display: flex;
  flex-direction: row;
}

I am trying to find a way to horizontally align the two element with the align class but I can not figure it out. I have to precise that the content of the element with "content" class could be anything so I need a solution that works in every case.

(If you have a solution using some Js code it is ok)

Here is a Jsfiddle demo.

Actual result is this :

And this is what I want to achieve :

The text should go where the arrow point to be aligned with the left text, and the "Some more text" should be after the aligned text I hope it's clear now

Thank you very much for your time !

Body:
You can't do that with that HTML structure. You need to wrap the two <p> in a <div>.

Then use a display:grid; and grid-template-row:2fr 1fr; in .container to define that the first divs consume about x2 the space from the second divs and get aligned properly.

.row {
  display: flex;
  flex-direction: row;
}

.container {
  display: grid;
  grid-template-rows: 2fr 1fr;
  width: 40%;
  margin-right: 20px;
}

<div class="row">
  <div class="container">
    <p class="content">
      Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
      in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </p>
    <p class="align">Should be aligned</p>
  </div>

  <div class="container">
    <p class="content">Very short text</p>
    <div>
      <p class="align">Should be aligned</p>
      <p>Some more text here</p>
    </div>
  </div>
</div>


来源: stackexchange

问:
IEnumerable<T> as return type
Is there a problem with using IEnumerable<T> as a return type?
FxCop complains about returning List<T> (it advises returning Collection<T> instead).

Well, I've always been guided by a rule "accept the least you can, but return the maximum."

From this point of view, returning IEnumerable<T> is a bad thing, but what should I do when I want to use "lazy retrieval"? Also, the yield keyword is such a goodie.

答:
IEnumerable is cool because you can use the yield iterator that gives to the consumer just the data they need but there is a cost hidden in the construct.

Let me explain it with an example. Let's say I am consuming this method:

IEnumerable GetFilesFromFolder(string path)

So, what do I get? To get all the files of my folder I have to iterate the enumeration, and that's fine, after all that's how enumerations work, but what if, for any reason, I have to enumerate it twice?

The second time should I expect a refreshed result or the result is idempotent?  I do not know. I have to check the docs of the library / method.

The call to the GetEnumerator method of the enumeration done by the consumer, could, in fact, execute an I/O operation behind the scene, or an http call, or it could simply iterate an inner array, I can not know it for sure. I have to check the docs in the hope that this behavior is documented.

Does this detail matters? I think it does. At least from a performance perspective.

Even if the cost of iterations is slow and CPU bounded, this is not zero, and it could go even worse in the scenario of chains of enumerations, that often turn debugging sessions a nightmare.

I prefer to not give the consumer of my library doubts so whenever I know my API returns few elements I always use arrays as return type, and only when the data to return is huge I use IEnumerable or IAsyncEnumerable.

Anyway, if you want to return enumerations please document your API to tell consumers if the result is a snapshot or not.

OwnerDisplayName: Valve

ContentLicense: CC BY-SA 3.0

Title: IEnumerable<T> as return type

ContentLicense: CC BY-SA 4.0


问:
In Android Studio Giving Warning of Mapping New ns to old ns
When I trying to run the app or Rebuid it, Gives following errors.

(I m trying run or Rebuild old project in new Android Studio and SDK)

Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http:/ /schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http:/ /schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http:/ /schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http:/ /schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http:/ /schemas.android.com/sdk/android/repo/sys-img2/01

My Build Gradle is Like following;

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 30
    buildToolsVersion '30.0.2'
    defaultConfig {
        applicationId "com.etas.etas"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    //noinspection GradleDependency
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation files('libs/jtds-1.2.7.jar')
    implementation files('libs/ksoap.jar')
    implementation 'com.android.support:appcompat-v7:30.2'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.android.support:design:30.2'
    implementation 'com.google.firebase:firebase-appindexing:20.0.0'
    implementation 'com.android.support:support-v4:30.2'
}
</code>```

`

答:
Try upgrading your Gradle plugin to the latest one.

Go to path/to/your/flutter_app/android/build.gradle and inside the
dependencies block in buildscript you have to update your old
build Gradle to the latest one.

Also update Gradle distributionUrl in path/to/your/flutter_app/android/gradle/wrapper/gradle-wrapper.properties file to the same version you updated to

Clean your flutter project using flutter clean

Run your project again

Body:
When I trying to run the app or Rebuid it, Gives following errors.

(I m trying run or Rebuild old project in new Android Studio and SDK)

Warning: Mapping new ns http://schemas.android.com/repository/android/common/02 to old ns http:/ /schemas.android.com/repository/android/common/01
Warning: Mapping new ns http://schemas.android.com/repository/android/generic/02 to old ns http:/ /schemas.android.com/repository/android/generic/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/addon2/02 to old ns http:/ /schemas.android.com/sdk/android/repo/addon2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/repository2/02 to old ns http:/ /schemas.android.com/sdk/android/repo/repository2/01
Warning: Mapping new ns http://schemas.android.com/sdk/android/repo/sys-img2/02 to old ns http:/ /schemas.android.com/sdk/android/repo/sys-img2/01

My Build Gradle is Like following;

apply plugin: 'com.android.application'

android {
    compileSdkVersion 30
    buildToolsVersion '30.0.2'
    defaultConfig {
        applicationId "com.etas.etas"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    //noinspection GradleDependency
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation files('libs/jtds-1.2.7.jar')
    implementation files('libs/ksoap.jar')
    implementation 'com.android.support:appcompat-v7:30.2'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.android.support:design:30.2'
    implementation 'com.google.firebase:firebase-appindexing:20.0.0'
    implementation 'com.android.support:support-v4:30.2'
}

`


问:
Android Recyclerview with editable elements not updating correctly with new element
So, I have a Recyclerview, where every element contains an Icon, a textview and a textedit.

The adapter looks like this:

```<code>class ZutatenSmallListAdaptermitEingabe internal constructor(
    context: Context, parent: NewRezeptActivity
) : RecyclerView.Adapter<ZutatenSmallListAdaptermitEingabe.ZutatenViewHolder>() {

    private val inflater: LayoutInflater = LayoutInflater.from(context)
    private var zutaten = emptyList<ZutatenData>()
    private var mengenedits = emptyList<RefZutatRezept>()
    private val context = context
    private val parent = parent

    inner class ZutatenViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val zutatenItemView: TextView = itemView.findViewById(R.id.textSmallZutat)
        val zutatenPicView: ImageView = itemView.findViewById(R.id.image_SmallZutat)
        var zutatenMengenedit : EditText = itemView.findViewById(R.id.textedit_menge)

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ZutatenViewHolder {
        var itemView :View = inflater.inflate(R.layout.recyclerview_item_small_mitmengeeingabe, parent, false)
        return ZutatenViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: ZutatenViewHolder, position: Int) {
        val current = zutaten[position]
        val curpos = position
        holder.zutatenItemView.text = current.zutname
        holder.zutatenPicView.setImageDrawable(ContextCompat.getDrawable(context, current.bild))
        holder.zutatenItemView.setOnClickListener {
                parent.removeZutat(zutaten[position])
        }
        var richtigmengenedit =  mengenedits.firstOrNull() {it.zutatid == current.zutatid}
        if( richtigmengenedit != null) {
            holder.zutatenMengenedit.setText(richtigmengenedit.menge)
        }
        holder.zutatenMengenedit.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int){
                mengenedits[curpos].menge =  holder.zutatenMengenedit.text.toString()

            }
            override fun afterTextChanged(s: Editable?) {}

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
    })
    }

    internal fun setZutaten(zutats: List<ZutatenData>) {
        this.zutaten = zutats
        var neueListe = emptyList<RefZutatRezept>()
        for(zut in zutaten){
            var element = mengenedits.firstOrNull(){it.zutatid == zut.zutatid}
            if( element!= null){
                neueListe += element
            }else{
                neueListe += RefZutatRezept( zut.zutatid, 0, "")
            }
        }
        mengenedits = neueListe
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int = zutaten.size
}
</code>```

I have a list "zutaten" where I store the elements I want to display and I have another List "mengenedits", where I store the text the user writes into the textedit.

I also have two functions where I can add and remove elements from the list. Then the new List ist set with setZutatem.

When I add or remove an element I still want to show the right text in the textedit.
But the problem is when the List "zutaten" updates, the list of "mengedits" changes correctly, but in the onBindViewHolder function it somehow gets messed up. The text of the secon element shows in the textedit of the first.

答:
So I am not shure what the porblem was, but I fixed it:

I am only adding and removing certain items, so instead of replacing the whole list, I just removed or added the specific item and instead of calling a notifyDataSetChanged(), I just called notifyItemInserted and notifyItemRemoved

So the functions for removing an adding looked like this:

```<code>    fun addZutat(zutat: ZutatenData){
        zutaten.add(zutat)
        mengenedits.add( RefZutatRezept( zutat.zutatid, 0, ""))
        notifyItemInserted(zutaten.size -1)
    }

    fun removeZutat(zutat: ZutatenData){
        val pos = zutaten.indexOf(zutat)
        zutaten.removeAt(pos)
        mengenedits.removeAt(pos)
        notifyItemRemoved(pos)
    }
</code>```

Note: I also change the lists to MutableLists, because I wanted to call removeAt()

Body:
So, I have a Recyclerview, where every element contains an Icon, a textview and a textedit.

The adapter looks like this:

class ZutatenSmallListAdaptermitEingabe internal constructor(
    context: Context, parent: NewRezeptActivity
) : RecyclerView.Adapter<ZutatenSmallListAdaptermitEingabe.ZutatenViewHolder>() {

    private val inflater: LayoutInflater = LayoutInflater.from(context)
    private var zutaten = emptyList<ZutatenData>()
    private var mengenedits = emptyList<RefZutatRezept>()
    private val context = context
    private val parent = parent

    inner class ZutatenViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val zutatenItemView: TextView = itemView.findViewById(R.id.textSmallZutat)
        val zutatenPicView: ImageView = itemView.findViewById(R.id.image_SmallZutat)
        var zutatenMengenedit : EditText = itemView.findViewById(R.id.textedit_menge)

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ZutatenViewHolder {
        var itemView :View = inflater.inflate(R.layout.recyclerview_item_small_mitmengeeingabe, parent, false)
        return ZutatenViewHolder(itemView)
    }

    override fun onBindViewHolder(holder: ZutatenViewHolder, position: Int) {
        val current = zutaten[position]
        val curpos = position
        holder.zutatenItemView.text = current.zutname
        holder.zutatenPicView.setImageDrawable(ContextCompat.getDrawable(context, current.bild))
        holder.zutatenItemView.setOnClickListener {
                parent.removeZutat(zutaten[position])
        }
        var richtigmengenedit =  mengenedits.firstOrNull() {it.zutatid == current.zutatid}
        if( richtigmengenedit != null) {
            holder.zutatenMengenedit.setText(richtigmengenedit.menge)
        }
        holder.zutatenMengenedit.addTextChangedListener(object : TextWatcher {
            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int){
                mengenedits[curpos].menge =  holder.zutatenMengenedit.text.toString()

            }
            override fun afterTextChanged(s: Editable?) {}

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
    })
    }

    internal fun setZutaten(zutats: List<ZutatenData>) {
        this.zutaten = zutats
        var neueListe = emptyList<RefZutatRezept>()
        for(zut in zutaten){
            var element = mengenedits.firstOrNull(){it.zutatid == zut.zutatid}
            if( element!= null){
                neueListe += element
            }else{
                neueListe += RefZutatRezept( zut.zutatid, 0, "")
            }
        }
        mengenedits = neueListe
        notifyDataSetChanged()
    }

    override fun getItemCount(): Int = zutaten.size
}

I have a list "zutaten" where I store the elements I want to display and I have another List "mengenedits", where I store the text the user writes into the textedit.

I also have two functions where I can add and remove elements from the list. Then the new List ist set with setZutatem.

When I add or remove an element I still want to show the right text in the textedit.
But the problem is when the List "zutaten" updates, the list of "mengedits" changes correctly, but in the onBindViewHolder function it somehow gets messed up. The text of the secon element shows in the textedit of the first.

Body:
So I am not shure what the porblem was, but I fixed it:

I am only adding and removing certain items, so instead of replacing the whole list, I just removed or added the specific item and instead of calling a notifyDataSetChanged(), I just called notifyItemInserted and notifyItemRemoved

So the functions for removing an adding looked like this:

    fun addZutat(zutat: ZutatenData){
        zutaten.add(zutat)
        mengenedits.add( RefZutatRezept( zutat.zutatid, 0, ""))
        notifyItemInserted(zutaten.size -1)
    }

    fun removeZutat(zutat: ZutatenData){
        val pos = zutaten.indexOf(zutat)
        zutaten.removeAt(pos)
        mengenedits.removeAt(pos)
        notifyItemRemoved(pos)
    }

Note: I also change the lists to MutableLists, because I wanted to call removeAt()


问:
Can you configure Git such that it is no longer necessary to use --force to add ignored files?
My home directory is a git repo that I use to manage my dotfiles. Because it is also my home directory, it also contains a whole bunch of things I don't want git to even care about under normal circumstances which is why I added * to my gitignore.

Now I need to use --force whenever I want to add a new config file etc. to my tree.

Is there a way to configure git to not care about the addition of ignored files and let me add them without --force? I use a git UI where I can't modify the add command used to stage a new file.

答:
Putting * into .gitignore is very restrictive.

You should consider making some of your folders accessible or trackable to git; for example:

```<code># Ignore all files by default
/*

# Make git see the .gitignore

!.gitignore

# Make git see txt files in the root folder

!*.txt

# Allow git to see a whole folder structure recursively

!folder1

# Explicitly hide a folder

folder2
</code>```

Body:
Putting * into .gitignore is very restrictive.

You should consider making some of your folders accessible or trackable to git; for example:

# Ignore all files by default
/*

# Make git see the .gitignore

!.gitignore

# Make git see txt files in the root folder

!*.txt

# Allow git to see a whole folder structure recursively

!folder1

# Explicitly hide a folder

folder2


问:
html/css/js - marquee, scroll one element then pause, then scroll again
I am trying to create an overlay page for my twitch channel. I play Rocket League and the tracker network site provides overlays that show your rank.

Basically what I have put together is a marquee with a bunch of iframes to grab the rank overlays and scroll them. It works pretty well so far.

What I'd like to do is have it pause on load, scroll slowly to the next one, then pause again, and repeat at the end. I'm having a bit of trouble with finding the right combination of words to search in Google about this, most queries I get answers relating to scroll-stop with javascript.

Here's the current code:

```<code><html>
<head>
    <style>
        iframe {
            border: 0px;
            margin: 0px;
        }
    </style>
</head>
<body>
<marquee>
    <iframe src="https://tracker.gg/overlays/overlay/347710c7-d003-47ec-8c56-29269060692c"></iframe>
    <iframe src="https://tracker.gg/overlays/overlay/687c5759-99f1-4f40-95c3-377cfb1751be"></iframe>
    <iframe src="https://tracker.gg/overlays/overlay/b8efb59c-02ae-4edf-9c9d-50a6d1643064"></iframe>
    <iframe src="https://tracker.gg/overlays/overlay/80fc2dab-f197-452e-827d-36aafdeca87d"></iframe>
    <iframe src="https://tracker.gg/overlays/overlay/76576b68-97aa-42a5-a5e4-45574ab0d3e9"></iframe>
    <iframe src="https://tracker.gg/overlays/overlay/fe174a33-4b60-4bcd-aed6-3188dbf1d432"></iframe>
    <iframe src="https://tracker.gg/overlays/overlay/7c1a3a59-7540-4c15-a5b4-24d19dbd5880"></iframe>
    <iframe src="https://tracker.gg/overlays/overlay/ebc95461-8851-4576-a8bf-0f8aec7c9d46"></iframe>
</marquee>
</body>
</html>
</code>```

Any tips would be appreciated! Also looking into making it pure css/html without iframes and marquee in the future.

答:
Got this working how I wanted :)
Used pure CSS animations. Had to do some math to figure out how long the total animation would be, then figure out the percentages of the keyframes.
Thanks to @The_Paradox for pointing me to some JavaScript methods that put me in a rabbit-hole to find the CSS animation things!
(I am still using iframes, but tbf it's not a bad way to go for this type of thing...)</p>
```<code><html>
<head>
    <style>
        @keyframes mq1 {
            0%  { transform:translateX(100%);   }
            1%  { transform:translateX(0);      }
            9%  { transform:translateX(0);      }
            10%  { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq2 {
            0%  { transform:translateX(100%);   }
            10% { transform:translateX(100%);   }
            11% { transform:translateX(0);      }
            19% { transform:translateX(0);      }
            20% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }

        }

        @keyframes mq3 {
            0%  { transform:translateX(100%);   }
            20% { transform:translateX(100%);   }
            21% { transform:translateX(0);      }
            29% { transform:translateX(0);      }
            30% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq4 {
            0%  { transform:translateX(100%);   }
            30% { transform:translateX(100%);   }
            31% { transform:translateX(0);      }
            39% { transform:translateX(0);      }
            40% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq5 {
            0%  { transform:translateX(100%);   }
            40% { transform:translateX(100%);   }
            41% { transform:translateX(0);      }
            49% { transform:translateX(0);      }
            50% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq6 {
            0%  { transform:translateX(100%);   }
            50% { transform:translateX(100%);   }
            51% { transform:translateX(0);      }
            59% { transform:translateX(0);      }
            60% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq7 {
            0%  { transform:translateX(100%);   }
            60% { transform:translateX(100%);   }
            61% { transform:translateX(0);      }
            69% { transform:translateX(0);      }
            70% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq8 {
            0%  { transform:translateX(100%);   }
            70% { transform:translateX(100%);   }
            71% { transform:translateX(0);      }
            79% { transform:translateX(0);      }
            80% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq9 {
            0%  { transform:translateX(100%);   }
            80% { transform:translateX(100%);   }
            81% { transform:translateX(0);      }
            89% { transform:translateX(0);      }
            90% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq10 {
            0%  { transform:translateX(100%);   }
            90% { transform:translateX(100%);   }
            91% { transform:translateX(0);      }
            99% { transform:translateX(0);      }
            100%    { transform:translateX(-100%);  }
        }
        .marquee {
            width: 300px;
            height: 150px;
            margin: 10px auto;
            overflow: hidden;
            position: relative;
            white-space: nowrap;
            vertical-align: text-top;
            border: 0px;
        }

        .marquee iframe {
            position: absolute;
            width: 100%;
            height: 100%;
            margin: 0;
            text-align: center;
            transform:translateX(100%);
        }

        iframe.marquee:nth-child(1) {
            animation: mq1 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(2) {
            animation: mq2 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(3) {
            animation: mq3 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(4) {
            animation: mq4 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(5) {
            animation: mq5 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(6) {
            animation: mq6 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(7) {
            animation: mq7 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(8) {
            animation: mq8 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(9) {
            animation: mq9 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(10) {
            animation: mq10 80s ease 5s infinite;
        }

/*
        .marquee.iframe:nth-child(1) {
            animation: left-one 20s ease infinite;
        }
        .marquee.iframe:nth-child(2) {
            animation: left-two 20s ease infinite;
        }
*/
    </style>
</head>
<body>
<div class="marquee">
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/347710c7-d003-47ec-8c56-29269060692c"></iframe>
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/687c5759-99f1-4f40-95c3-377cfb1751be"></iframe>
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/b8efb59c-02ae-4edf-9c9d-50a6d1643064"></iframe>
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/80fc2dab-f197-452e-827d-36aafdeca87d"></iframe>
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/76576b68-97aa-42a5-a5e4-45574ab0d3e9"></iframe>
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/fe174a33-4b60-4bcd-aed6-3188dbf1d432"></iframe>
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/7c1a3a59-7540-4c15-a5b4-24d19dbd5880"></iframe>
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/ebc95461-8851-4576-a8bf-0f8aec7c9d46"></iframe>
        <iframe class="marquee" src=""></iframe>
        <iframe class="marquee" src=""></iframe>
</div>
</body>
</html>
</code>```

Body:
I am trying to create an overlay page for my twitch channel. I play Rocket League and the tracker network site provides overlays that show your rank.

Basically what I have put together is a marquee with a bunch of iframes to grab the rank overlays and scroll them. It works pretty well so far.

What I'd like to do is have it pause on load, scroll slowly to the next one, then pause again, and repeat at the end. I'm having a bit of trouble with finding the right combination of words to search in Google about this, most queries I get answers relating to scroll-stop with javascript.

Here's the current code:

<marquee>

</marquee>

Any tips would be appreciated! Also looking into making it pure css/html without iframes and marquee in the future.

Body:
Got this working how I wanted :)
Used pure CSS animations. Had to do some math to figure out how long the total animation would be, then figure out the percentages of the keyframes.
Thanks to @The_Paradox for pointing me to some JavaScript methods that put me in a rabbit-hole to find the CSS animation things!
(I am still using iframes, but tbf it's not a bad way to go for this type of thing...)

<html>
<head>
    <style>
        @keyframes mq1 {
            0%  { transform:translateX(100%);   }
            1%  { transform:translateX(0);      }
            9%  { transform:translateX(0);      }
            10%  { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq2 {
            0%  { transform:translateX(100%);   }
            10% { transform:translateX(100%);   }
            11% { transform:translateX(0);      }
            19% { transform:translateX(0);      }
            20% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }

        }

        @keyframes mq3 {
            0%  { transform:translateX(100%);   }
            20% { transform:translateX(100%);   }
            21% { transform:translateX(0);      }
            29% { transform:translateX(0);      }
            30% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq4 {
            0%  { transform:translateX(100%);   }
            30% { transform:translateX(100%);   }
            31% { transform:translateX(0);      }
            39% { transform:translateX(0);      }
            40% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq5 {
            0%  { transform:translateX(100%);   }
            40% { transform:translateX(100%);   }
            41% { transform:translateX(0);      }
            49% { transform:translateX(0);      }
            50% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq6 {
            0%  { transform:translateX(100%);   }
            50% { transform:translateX(100%);   }
            51% { transform:translateX(0);      }
            59% { transform:translateX(0);      }
            60% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq7 {
            0%  { transform:translateX(100%);   }
            60% { transform:translateX(100%);   }
            61% { transform:translateX(0);      }
            69% { transform:translateX(0);      }
            70% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq8 {
            0%  { transform:translateX(100%);   }
            70% { transform:translateX(100%);   }
            71% { transform:translateX(0);      }
            79% { transform:translateX(0);      }
            80% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq9 {
            0%  { transform:translateX(100%);   }
            80% { transform:translateX(100%);   }
            81% { transform:translateX(0);      }
            89% { transform:translateX(0);      }
            90% { transform:translateX(-100%);  }
            100%    { transform:translateX(-100%);  }
        }

        @keyframes mq10 {
            0%  { transform:translateX(100%);   }
            90% { transform:translateX(100%);   }
            91% { transform:translateX(0);      }
            99% { transform:translateX(0);      }
            100%    { transform:translateX(-100%);  }
        }
        .marquee {
            width: 300px;
            height: 150px;
            margin: 10px auto;
            overflow: hidden;
            position: relative;
            white-space: nowrap;
            vertical-align: text-top;
            border: 0px;
        }

        .marquee iframe {
            position: absolute;
            width: 100%;
            height: 100%;
            margin: 0;
            text-align: center;
            transform:translateX(100%);
        }

        iframe.marquee:nth-child(1) {
            animation: mq1 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(2) {
            animation: mq2 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(3) {
            animation: mq3 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(4) {
            animation: mq4 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(5) {
            animation: mq5 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(6) {
            animation: mq6 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(7) {
            animation: mq7 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(8) {
            animation: mq8 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(9) {
            animation: mq9 80s ease 5s infinite;
        }
        iframe.marquee:nth-child(10) {
            animation: mq10 80s ease 5s infinite;
        }

/*
        .marquee.iframe:nth-child(1) {
            animation: left-one 20s ease infinite;
        }
        .marquee.iframe:nth-child(2) {
            animation: left-two 20s ease infinite;
        }
*/
    </style>
</head>
<body>
<div class="marquee">
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/347710c7-d003-47ec-8c56-29269060692c"></iframe>
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/687c5759-99f1-4f40-95c3-377cfb1751be"></iframe>
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/b8efb59c-02ae-4edf-9c9d-50a6d1643064"></iframe>
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/80fc2dab-f197-452e-827d-36aafdeca87d"></iframe>
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/76576b68-97aa-42a5-a5e4-45574ab0d3e9"></iframe>
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/fe174a33-4b60-4bcd-aed6-3188dbf1d432"></iframe>
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/7c1a3a59-7540-4c15-a5b4-24d19dbd5880"></iframe>
        <iframe class="marquee" src="https://tracker.gg/overlays/overlay/ebc95461-8851-4576-a8bf-0f8aec7c9d46"></iframe>
        <iframe class="marquee" src=""></iframe>
        <iframe class="marquee" src=""></iframe>
</div>
</body>
</html>


问:
Expected ',' or '...' before numeric const
I am new in C programming and trying to figure out some problems encountered.
When I wrote </p>

```<code>#define N 5

void Sort(int *const array,  int N);
</code>```

<p>the compiler gave me the message "Expected ',' or '...' before numeric const". After searching on the internet and found out that the problem may be casued by the #define being debugged as numeric values. I did get through the compiler by not using the #define for the constant N. However, I wondered how should I modified the above two lines so that I won't get that error message?  </p>

答:
You #define a macro that is expanded by the preprocessor before the compiler sees the code.  So, the compiler gets:

```<code>void Sort(int *const array, int 5);
</code>```

This is not valid C syntax.

Body:
I am new in C programming and trying to figure out some problems encountered.
When I wrote

#define N 5

void Sort(int *const array,  int N);

the compiler gave me the message "Expected ',' or '...' before numeric const". After searching on the internet and found out that the problem may be casued by the #define being debugged as numeric values. I did get through the compiler by not using the #define for the constant N. However, I wondered how should I modified the above two lines so that I won't get that error message?

Body:
You #define a macro that is expanded by the preprocessor before the compiler sees the code.  So, the compiler gets:

void Sort(int *const array, int 5);

This is not valid C syntax.


问:
How to edit the image so Tesseract OCR recognizes it? (Python)
Here is the image I am trying tesseract to detect:

So far, I have tried greyscaling, inverting, blurring, thresholding and still no recognition.

Is there something I'm missing that prevents it from recognizing or is there something (or any resources) that might help me detect it?

Since uploading the question I have tried separating the digits and feeding Tesseract, but still wont detect anything.

答:
For the specific image you have posted, Tesseract is able to recognize the digits.

Add a "white list" applies only digits: "_char_whitelist=1234567890"

Add --psm 6 argument - assume a single uniform block of text.

Tesseract manages to identify the text without cleaning:

```<code>import cv2
import pytesseract

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"  # For Windows OS

# Read input image
img = cv2.imread("num30.jpg")

# Apply OCR
data = pytesseract.image_to_string(img, config="-c tessedit"
                                               "_char_whitelist=1234567890"
                                               " --psm 6"
                                               " ")

print(data)
</code>```

Output:

30

Example for cleaning up the input image:

Assumptions:

The dark pixels next to the image borders are not part of the text.

Small clusters applies noise.

The cleaning process may apply two stages:

Iterating the most top row, bottom row, left column and right column.

Apply cv2.floodFill (fill with white) when a pixel is dark.

Find small clusters using cv2.connectedComponentsWithStats, and fill the small clusters with white color.

Code sample:

```<code>import cv2
import pytesseract

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"  # For Windows OS

img = cv2.imread("num30.jpg")  # Read input image

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # Convert to grayscale.

for x in range(gray.shape[1]):
    # Fill dark top pixels:
    if gray[0, x] < 200:
        cv2.floodFill(gray, None, seedPoint=(x, 0), newVal=255, loDiff=3, upDiff=3)  # Fill the background with white color

    # Fill dark bottom pixels:
    if gray[-1, x] < 200:
        cv2.floodFill(gray, None, seedPoint=(x, gray.shape[0]-1), newVal=255, loDiff=3, upDiff=3)  # Fill the background with white color

for y in range(gray.shape[0]):
    # Fill dark left side pixels:
    if gray[y, 0] < 200:
        cv2.floodFill(gray, None, seedPoint=(0, y), newVal=255, loDiff=3, upDiff=3)  # Fill the background with white color

    # Fill dark right side pixels:
    if gray[y, -1] < 200:
        cv2.floodFill(gray, None, seedPoint=(gray.shape[1]-1, y), newVal=255, loDiff=3, upDiff=3)  # Fill the background with white color

cv2.imshow('gray after floodFill', gray)  # Show image for testing

# Convert to binary and invert polarity
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# Find connected components (clusters)
nlabel, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh, connectivity=8)

# Remove small clusters: With both width<=10 and height<=10 (clean small size noise).
for i in range(nlabel):
    if (stats[i, cv2.CC_STAT_WIDTH] <= 10) and (stats[i, cv2.CC_STAT_HEIGHT] <= 10):
        thresh[labels == i] = 0

cv2.imshow('thresh', thresh)  # Show image for testing

# Put 255 where thresh is zero.s
gray[thresh == 0] = 255

cv2.imshow('gray', gray)

# Apply OCR
data = pytesseract.image_to_string(img, config="-c tessedit"
                                               "_char_whitelist=1234567890"
                                               " --psm 6"
                                               " ")

print(data)

cv2.waitKey()
cv2.destroyAllWindows()
</code>```

Output image:

Body:
For the specific image you have posted, Tesseract is able to recognize the digits.

Add a "white list" applies only digits: "_char_whitelist=1234567890"

Add --psm 6 argument - assume a single uniform block of text.

Tesseract manages to identify the text without cleaning:

import cv2
import pytesseract

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"  # For Windows OS

# Read input image
img = cv2.imread("num30.jpg")

# Apply OCR
data = pytesseract.image_to_string(img, config="-c tessedit"
                                               "_char_whitelist=1234567890"
                                               " --psm 6"
                                               " ")

print(data)

Output:

30

Example for cleaning up the input image:

Assumptions:

The dark pixels next to the image borders are not part of the text.

Small clusters applies noise.

The cleaning process may apply two stages:

Iterating the most top row, bottom row, left column and right column.

Apply cv2.floodFill (fill with white) when a pixel is dark.

Find small clusters using cv2.connectedComponentsWithStats, and fill the small clusters with white color.

Code sample:

import cv2
import pytesseract

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"  # For Windows OS

img = cv2.imread("num30.jpg")  # Read input image

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # Convert to grayscale.

for x in range(gray.shape[1]):
    # Fill dark top pixels:
    if gray[0, x] < 200:
        cv2.floodFill(gray, None, seedPoint=(x, 0), newVal=255, loDiff=3, upDiff=3)  # Fill the background with white color

    # Fill dark bottom pixels:
    if gray[-1, x] < 200:
        cv2.floodFill(gray, None, seedPoint=(x, gray.shape[0]-1), newVal=255, loDiff=3, upDiff=3)  # Fill the background with white color

for y in range(gray.shape[0]):
    # Fill dark left side pixels:
    if gray[y, 0] < 200:
        cv2.floodFill(gray, None, seedPoint=(0, y), newVal=255, loDiff=3, upDiff=3)  # Fill the background with white color

    # Fill dark right side pixels:
    if gray[y, -1] < 200:
        cv2.floodFill(gray, None, seedPoint=(gray.shape[1]-1, y), newVal=255, loDiff=3, upDiff=3)  # Fill the background with white color

cv2.imshow('gray after floodFill', gray)  # Show image for testing

# Convert to binary and invert polarity
ret, thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# Find connected components (clusters)
nlabel, labels, stats, centroids = cv2.connectedComponentsWithStats(thresh, connectivity=8)

# Remove small clusters: With both width<=10 and height<=10 (clean small size noise).
for i in range(nlabel):
    if (stats[i, cv2.CC_STAT_WIDTH] <= 10) and (stats[i, cv2.CC_STAT_HEIGHT] <= 10):
        thresh[labels == i] = 0

cv2.imshow('thresh', thresh)  # Show image for testing

# Put 255 where thresh is zero.s
gray[thresh == 0] = 255

cv2.imshow('gray', gray)

# Apply OCR
data = pytesseract.image_to_string(img, config="-c tessedit"
                                               "_char_whitelist=1234567890"
                                               " --psm 6"
                                               " ")

print(data)

cv2.waitKey()
cv2.destroyAllWindows()

Output image:


问:
How are two different appservices identified
How are two appservices in the same appservice plan uniquely identified though I understand they have different urls but it is explained that at the backend this urls are converted into IP addresses however the appservices have the same Outbound IP addresses</p>

答: URLs are not converted into IP addresses on the backend side, domain names like myapp.azurewebsites.net are resolved to IP addresses by DNS servers - and afterwards the client sends an HTTP request to the derived IP address which belongs to a server on Azure side. Indeed this means that the Azure backend wouldn't be able to assign a request to the right app service so there is another property necessary for this matching - which is the HTTP Host header. This header is used by an internal load balancer (called a "front end" on Azure side) which distributes the request to the worker(s) your application is running on.</p>


问:
Return a value of first & last row matching criterion in Google Sheets
I have 2 columns of numbers, the idea is to find the first & last value in column L that respects a criterion and return the value from the same row in column K.
As the criterion is "higher than 99% of the max value in column L", I tried the MINIFS formula, but I cannot use this as a criterion.

I guess the solution will include the MATCH, INDEX formula but I cannot find the right combination

In this specific example,  we want to return the value of the first column that has in column L a number higher than 0,99*max(L3:L62)(=3.0879...) so it should return 19
This will be verified for a couple rows until the value goes below the 99% again. This last row is 58.

Link to sheet :
https://docs.google.com/spreadsheets/d/1MUkYDPoR1NxB8qWcYr_2Fp91FgUbnUOpfGd7EUuWCOg/edit?usp=sharing

答:
Try

```<code>=query({K3:L62};"select Col1 where Col2 > "&substitute(to_text(0,99*MAX(L3:L62));",";".")&" limit 1";0)
</code>```

query as app script needs US notation in values (dot instead of comma)

to get the last row

```<code>=query({K3:L62};"select Col1 where Col2 > "&SUBSTITUTE(to_text(0,99*MAX(L3:L62));",";".")&" order by Col1 desc limit 1";0)
</code>```

Body:
Try

=query({K3:L62};"select Col1 where Col2 > "&substitute(to_text(0,99*MAX(L3:L62));",";".")&" limit 1";0)

query as app script needs US notation in values (dot instead of comma)

to get the last row

=query({K3:L62};"select Col1 where Col2 > "&SUBSTITUTE(to_text(0,99*MAX(L3:L62));",";".")&" order by Col1 desc limit 1";0)


问:
Uninitialized Constant Error when catching Exception
I need to post articles to Wordpress via XMLRPC and catch any exceptions:

```<code>connection = XMLRPC::Client.new('mysite.com', '/xmlrpc.php', 80)
  connection.call(
  'metaWeblog.newPost',
  1,
  'user',
  'password',
  post,
  true
)
</code>```

There is en error:

```<code>C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/baseparser.rb:441:in `rescue in pull': #<NoMethodError: undefined method `[]' for nil:NilClass> (REXML::ParseException)
C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/baseparser.rb:341:in `pull'
C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/streamparser.rb:16:in `parse'
C:/Ruby192/lib/ruby/1.9.1/rexml/document.rb:204:in `parse_stream'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/parser.rb:717:in `parse'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/parser.rb:460:in `parseMethodResponse'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/client.rb:421:in `call2'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/client.rb:410:in `call'
</code>```

I successfully caught the exception with:

```<code>connection = XMLRPC::Client.new('mysite.com', '/xmlrpc.php', 80)
begin
  connection.call(
    'metaWeblog.newPost',
    1,
    'user',
    'password',
    post,
    true
  )
rescue REXML::ParseException
  puts "Skipping error"
end
</code>```

Post is OK, article is in Wordpress.

Next I needed to catch an exception about site availability (when site is not accessible)
I tried to catch the exception with:

```<code>connection = XMLRPC::Client.new('notaccessibleSite.com', '/xmlrpc.php', 80)
begin
  connection.call(
    'metaWeblog.newPost',
    1,
    'user',
    'password',
    post,
    true
  )
rescue REXML::ParseException
  puts "Skipping error"
rescue
  puts "Others errors"
end
</code>```

But this does not work:

```<code>myscript.rb:47:in `rescue in makeRpc': uninitialized constant Object::REXML (NameError)
from myscript.rb:38:in `makeRpc'
from myscript.rb:62:in `block in postContent'
from myscript.rb:58:in `each'
from myscript.rb:58:in `postContent'
from myscript.rb:71:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `<main>'
</code>```

Any suggestions?

答: You must require 'rexml/rexml' before.

Body:
I need to post articles to Wordpress via XMLRPC and catch any exceptions:

connection = XMLRPC::Client.new('mysite.com', '/xmlrpc.php', 80)
  connection.call(
  'metaWeblog.newPost',
  1,
  'user',
  'password',
  post,
  true
)

There is en error:

C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/baseparser.rb:441:in `rescue in pull': #<NoMethodError: undefined method `[]' for nil:NilClass> (REXML::ParseException)
C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/baseparser.rb:341:in `pull'
C:/Ruby192/lib/ruby/1.9.1/rexml/parsers/streamparser.rb:16:in `parse'
C:/Ruby192/lib/ruby/1.9.1/rexml/document.rb:204:in `parse_stream'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/parser.rb:717:in `parse'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/parser.rb:460:in `parseMethodResponse'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/client.rb:421:in `call2'
C:/Ruby192/lib/ruby/1.9.1/xmlrpc/client.rb:410:in `call'

I successfully caught the exception with:

connection = XMLRPC::Client.new('mysite.com', '/xmlrpc.php', 80)
begin
  connection.call(
    'metaWeblog.newPost',
    1,
    'user',
    'password',
    post,
    true
  )
rescue REXML::ParseException
  puts "Skipping error"
end

Post is OK, article is in Wordpress.

Next I needed to catch an exception about site availability (when site is not accessible)
I tried to catch the exception with:

connection = XMLRPC::Client.new('notaccessibleSite.com', '/xmlrpc.php', 80)
begin
  connection.call(
    'metaWeblog.newPost',
    1,
    'user',
    'password',
    post,
    true
  )
rescue REXML::ParseException
  puts "Skipping error"
rescue
  puts "Others errors"
end

But this does not work:

myscript.rb:47:in `rescue in makeRpc': uninitialized constant Object::REXML (NameError)
from myscript.rb:38:in `makeRpc'
from myscript.rb:62:in `block in postContent'
from myscript.rb:58:in `each'
from myscript.rb:58:in `postContent'
from myscript.rb:71:in `<top (required)>'
from -e:1:in `load'
from -e:1:in `'

Any suggestions?

Body: You must require 'rexml/rexml' before.


问:
React delete active class after second click
I'm new in React. I needed active class that can be active only on one element at time and it's work, but if I click one of the element, active class is constantly active on one of them. I need to switch class to inactive, if i click element already active or even better, after click an active element or outside of the elements.

MenuDish.js

```<code>const MenuDish = props =>{

  const clickHandler = (keyID) => {
    props.onChange(keyID);
  }
    return (
        <Card className={"menu-dish no-paddings " + (props.disabled === props.id ? "active-card" : "inactive-card")} >
            <Button className={"dish-img-button shadow-none border-none " } onClick={(e) => clickHandler(props.id, e)}>
              <Image fluid src={props.dishImage} className={"dish-image-width " + (props.disabled === props.id ? "active-card-image" :  "inactive-card-image") }>
              </Image>
              <div className={"image-blur "+ (props.disabled === props.id ? "active-card-blur" : "inactive-card-blur")}></div>
            </Button>
        </Card>
    )

}
</code>```

MenuDishes.js

```<code>const MenuDishes = (props) =>{
    const [active, setActive] = useState();

    function activeButton(value){
        setActive(value)
    }

   return (
        props.dishes.map((item) =>(
            <MenuDish dish={item.dish_name} price={item.dish_cost} dishImage={item.dish_img_link} key={item.id} ingredients={item.dish_ingredient_list} description={item.dish_description} category={item.dish_category} isVege={""+ item.dish_is_vege} spiciness={item.dish_spiciness} onChange={activeButton} disabled={active} id={item.id}/>
        ))
    );
</code>```

答:
Create a state in parent component to maintain the active id.

Based on that state change the active class

Parent

```<code>const [selectedId, setSelectedId] = useState(null);

const onChange = (id) => {
  setSelectedId(id === selectedId ? null : id); //To close the Menu if its already opened
};

<MenuDish onChange={onChange} selectedId={selectedId} />;
</code>```

MenuDish

```<code>const MenuDish = (props) =>{

  const clickHandler = (keyID) => {
    props.onChange(keyID);
  }
    return (
        <Card className={"menu-dish no-paddings " + (props.selectedId === props.id ? "active-card" : "inactive-card")} >
            <Button className={"dish-img-button shadow-none border-none " } onClick={(e) => clickHandler(props.id, e)}>
              <Image fluid src={props.dishImage} className={"dish-image-width " + (props.selectedId === props.id ? "active-card-image" :  "inactive-card-image") }>
              </Image>
              <div className={"image-blur "+ (props.selectedId === props.id ? "active-card-blur" : "inactive-card-blur")}></div>
            </Button>
        </Card>
    )

}
</code>```

...

```<code>props.selectedId === props.id ? "active-class"
</code>```

Body:
I'm new in React. I needed active class that can be active only on one element at time and it's work, but if I click one of the element, active class is constantly active on one of them. I need to switch class to inactive, if i click element already active or even better, after click an active element or outside of the elements.

MenuDish.js

const MenuDish = props =>{

  const clickHandler = (keyID) => {
    props.onChange(keyID);
  }
    return (
        <Card className={"menu-dish no-paddings " + (props.disabled === props.id ? "active-card" : "inactive-card")} >
            <Button className={"dish-img-button shadow-none border-none " } onClick={(e) => clickHandler(props.id, e)}>
              <Image fluid src={props.dishImage} className={"dish-image-width " + (props.disabled === props.id ? "active-card-image" :  "inactive-card-image") }>
              </Image>

            </Button>
        </Card>
    )

}

MenuDishes.js

const MenuDishes = (props) =>{
    const [active, setActive] = useState();

    function activeButton(value){
        setActive(value)
    }

   return (
        props.dishes.map((item) =>(
            <MenuDish dish={item.dish_name} price={item.dish_cost} dishImage={item.dish_img_link} key={item.id} ingredients={item.dish_ingredient_list} description={item.dish_description} category={item.dish_category} isVege={""+ item.dish_is_vege} spiciness={item.dish_spiciness} onChange={activeButton} disabled={active} id={item.id}/>
        ))
    );

Body:
Create a state in parent component to maintain the active id.

Based on that state change the active class

Parent

const [selectedId, setSelectedId] = useState(null);

const onChange = (id) => {
  setSelectedId(id === selectedId ? null : id); //To close the Menu if its already opened
};

<MenuDish onChange={onChange} selectedId={selectedId} />;

MenuDish

const MenuDish = (props) =>{

  const clickHandler = (keyID) => {
    props.onChange(keyID);
  }
    return (
        <Card className={"menu-dish no-paddings " + (props.selectedId === props.id ? "active-card" : "inactive-card")} >
            <Button className={"dish-img-button shadow-none border-none " } onClick={(e) => clickHandler(props.id, e)}>
              <Image fluid src={props.dishImage} className={"dish-image-width " + (props.selectedId === props.id ? "active-card-image" :  "inactive-card-image") }>
              </Image>
              <div className={"image-blur "+ (props.selectedId === props.id ? "active-card-blur" : "inactive-card-blur")}></div>
            </Button>
        </Card>
    )

}

...

props.selectedId === props.id ? "active-class"


问:
BigQuery: [CTE Table name] missing dataset while no default dataset is set in the request
My original table has:
(1) acceptance_rate - string, percentage
(2) host_is_superhost - boolean

I wanted to convert (1) acceptance_rate to integer without the %, so I created a CTE as follow:

```<code>WITH acceptance_rate_cte AS
(SELECT
    CAST(REPLACE(acceptance_rate,'%',"") AS int) AS new_acceptance_rate,
    host_is_superhost AS new_superhost
FROM table1
WHERE acceptance_rate NOT IN ("N/A","0%")
ORDER BY new_acceptance_rate DESC)

SELECT new_acceptance_rate, new_superhost
FROM acceptance_rate_cte;
</code>```

New CTE table looks like:

new_acceptance_rate | new_superhost

100 | true

90 | true

95 | false
...

NEXT, I wanted to create a table to group all the new_acceptance_rate into buckets of 20 and then count how many true or false are within those buckets. So I did this:

```<code>SELECT CASE WHEN new_acceptance_rate >0 AND  new_acceptance_rate <= 20 then '1-20'
     WHEN new_acceptance_rate >20 AND new_acceptance_rate <=40 then '21-40'
     WHEN new_acceptance_rate >40 AND new_acceptance_rate<=60 THEN '41-60'
     WHEN new_acceptance_rate >60 AND new_acceptance_rate <=80 THEN '61-80'
     ELSE 'Above 80'
     END acceptance_range,
     new_superhost,
     count(*) as superhost_count
FROM acceptance_rate_cte
</code>```

My expectation for the result is to look like this:

acceptance_range | new_superhost | superhost_count

1-20 | true | 15

1-20 | false | 25

...

But instead i received an error msg as follow:

Error running query Table name "acceptance_rate_cte" missing dataset
while no default dataset is set in the request.

答:
I ran your query above with some sample data it seems to be mostly correct.

```<code>with acceptance_rate_cte AS
(   SELECT
    CAST(REPLACE(acceptance_rate,'%',"") AS int) AS new_acceptance_rate,
    host_is_superhost AS new_superhost
    FROM table1
    WHERE acceptance_rate NOT IN ("N/A","0%")
    ORDER BY new_acceptance_rate DESC
)
SELECT CASE WHEN new_acceptance_rate >0 AND  new_acceptance_rate <= 20 then '1-20'
     WHEN new_acceptance_rate >20 AND new_acceptance_rate <=40 then '21-40'
     WHEN new_acceptance_rate >40 AND new_acceptance_rate<=60 THEN '41-60'
     WHEN new_acceptance_rate >60 AND new_acceptance_rate <=80 THEN '61-80'
     ELSE 'Above 80'
     END acceptance_range,
     new_superhost,
     count(*) as superhost_count
FROM acceptance_rate_cte
GROUP BY acceptance_range, new_superhost;
</code>```

I did have to add a group by in order for it to execute properly.  Based on your error though my guess is you have not run both the CTE and query together in the same session.  When you execute run both at the same time.

Body:
My original table has:
(1) acceptance_rate - string, percentage
(2) host_is_superhost - boolean

I wanted to convert (1) acceptance_rate to integer without the %, so I created a CTE as follow:

WITH acceptance_rate_cte AS
(SELECT
    CAST(REPLACE(acceptance_rate,'%',"") AS int) AS new_acceptance_rate,
    host_is_superhost AS new_superhost
FROM table1
WHERE acceptance_rate NOT IN ("N/A","0%")
ORDER BY new_acceptance_rate DESC)

SELECT new_acceptance_rate, new_superhost
FROM acceptance_rate_cte;

New CTE table looks like:

new_acceptance_rate | new_superhost

100 | true

90 | true

95 | false
...

NEXT, I wanted to create a table to group all the new_acceptance_rate into buckets of 20 and then count how many true or false are within those buckets. So I did this:

SELECT CASE WHEN new_acceptance_rate >0 AND  new_acceptance_rate <= 20 then '1-20'
     WHEN new_acceptance_rate >20 AND new_acceptance_rate <=40 then '21-40'
     WHEN new_acceptance_rate >40 AND new_acceptance_rate<=60 THEN '41-60'
     WHEN new_acceptance_rate >60 AND new_acceptance_rate <=80 THEN '61-80'
     ELSE 'Above 80'
     END acceptance_range,
     new_superhost,
     count(*) as superhost_count
FROM acceptance_rate_cte

My expectation for the result is to look like this:

acceptance_range | new_superhost | superhost_count

1-20 | true | 15

1-20 | false | 25

...

But instead i received an error msg as follow:

Error running query Table name "acceptance_rate_cte" missing dataset
while no default dataset is set in the request.

Body:
I ran your query above with some sample data it seems to be mostly correct.

with acceptance_rate_cte AS
(   SELECT
    CAST(REPLACE(acceptance_rate,'%',"") AS int) AS new_acceptance_rate,
    host_is_superhost AS new_superhost
    FROM table1
    WHERE acceptance_rate NOT IN ("N/A","0%")
    ORDER BY new_acceptance_rate DESC
)
SELECT CASE WHEN new_acceptance_rate >0 AND  new_acceptance_rate <= 20 then '1-20'
     WHEN new_acceptance_rate >20 AND new_acceptance_rate <=40 then '21-40'
     WHEN new_acceptance_rate >40 AND new_acceptance_rate<=60 THEN '41-60'
     WHEN new_acceptance_rate >60 AND new_acceptance_rate <=80 THEN '61-80'
     ELSE 'Above 80'
     END acceptance_range,
     new_superhost,
     count(*) as superhost_count
FROM acceptance_rate_cte
GROUP BY acceptance_range, new_superhost;

I did have to add a group by in order for it to execute properly.  Based on your error though my guess is you have not run both the CTE and query together in the same session.  When you execute run both at the same time.


问:
How to download blobs from azure storage via node js to local storage?
I have followed official documentation for downloading blobs, but it downloads blob with metadata and properties. What I need to do is download blob file as it is from azure storage to local file system with node js. Please note that my blob storage is private.

Below is the code I have as of now

```<code>    const { BlobServiceClient } = require('@azure/storage-blob');
    const { v1: uuidv1} = require('uuid');
    async function main() {
        console.log('Azure Blob storage v12 - JavaScript quickstart sample');
        // Quick start code goes here
        const AZURE_STORAGE_CONNECTION_STRING = process.env.AZURE_STORAGE_CONNECTION_STRING;
        const containerName = process.env.CONTAINER_NAME;

        // Create the BlobServiceClient object which will be used to create a container client
        const blobServiceClient = BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);
        // Get a reference to a container
        const containerClient = blobServiceClient.getContainerClient(containerName);
        const blockBlobClient = containerClient.getBlockBlobClient(process.env.BLOB_NAME);
        const downloadBlockBlobResponse = await blockBlobClient.download(0);
        console.log('\nDownloaded blob content...');
        console.log('\t', await streamToString(downloadBlockBlobResponse.readableStreamBody));
    }
    async function streamToString(readableStream) {
        return new Promise((resolve, reject) => {
        const chunks = [];
        readableStream.on("data", (data) => {
        chunks.push(data.toString());
        });
        readableStream.on("end", () => {
        resolve(chunks.join(""));
        });
        readableStream.on("error", reject);
        });
   }
    main().then(() => console.log('Done')).catch((ex) => console.log(ex.message))
</code>```

答:
To save the blob content to your local file system, you can simply use downloadToFile method.

Essentially change the following line of code:

```<code>const downloadBlockBlobResponse = await blockBlobClient.download(0);
</code>```

to

```<code>const downloadBlockBlobResponse = await blockBlobClient.downloadToFile('local-file-path');
</code>```

You would also not need streamToString method so you can safely delete that.

Body:
I have followed official documentation for downloading blobs, but it downloads blob with metadata and properties. What I need to do is download blob file as it is from azure storage to local file system with node js. Please note that my blob storage is private.

Below is the code I have as of now

    const { BlobServiceClient } = require('@azure/storage-blob');
    const { v1: uuidv1} = require('uuid');
    async function main() {
        console.log('Azure Blob storage v12 - JavaScript quickstart sample');
        // Quick start code goes here
        const AZURE_STORAGE_CONNECTION_STRING = process.env.AZURE_STORAGE_CONNECTION_STRING;
        const containerName = process.env.CONTAINER_NAME;

        // Create the BlobServiceClient object which will be used to create a container client
        const blobServiceClient = BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);
        // Get a reference to a container
        const containerClient = blobServiceClient.getContainerClient(containerName);
        const blockBlobClient = containerClient.getBlockBlobClient(process.env.BLOB_NAME);
        const downloadBlockBlobResponse = await blockBlobClient.download(0);
        console.log('\nDownloaded blob content...');
        console.log('\t', await streamToString(downloadBlockBlobResponse.readableStreamBody));
    }
    async function streamToString(readableStream) {
        return new Promise((resolve, reject) => {
        const chunks = [];
        readableStream.on("data", (data) => {
        chunks.push(data.toString());
        });
        readableStream.on("end", () => {
        resolve(chunks.join(""));
        });
        readableStream.on("error", reject);
        });
   }
    main().then(() => console.log('Done')).catch((ex) => console.log(ex.message))

Body:
To save the blob content to your local file system, you can simply use downloadToFile method.

Essentially change the following line of code:

const downloadBlockBlobResponse = await blockBlobClient.download(0);

to

const downloadBlockBlobResponse = await blockBlobClient.downloadToFile('local-file-path');

You would also not need streamToString method so you can safely delete that.


问:
How to add and remove classes to the active slide child 'div' on react slick carousel
If you are on the active slide i want to add a className content_animation to the className="content_text".

And if the slide changes whether you click/swipe the arrows or dots, the active slide will always do the same which is to add a className content_animation to the className="content_text".

Im tyring to achieve it using beforeChange and/or afterChange.

Here is the react slick docs

Below is my code and also here is the complete sandbox code https://codesandbox.io/.

import React, { Component } from "react";
import Slider from "react-slick";

export default class SlideChangeHooks extends Component {
  render() {
    const settings = {
      dots: true,
      infinite: true,
      speed: 1000,
      slidesToShow: 1,
      slidesToScroll: 1,
      beforeChange: (oldIndex, newIndex) => {
        setTimeout(() => {
          const sample = document.querySelector(".content_text");
          sample.classList.remove("content_animation");
          console.log("beforeChange", oldIndex, newIndex);
        });
      },
      afterChange: (index) => {
        setTimeout(() => {
          const sample = document.querySelector(".content_text");
          sample.classList.add("content_animation");
          console.log("afterChange", index);
        });
      }
    };
    return (

        <Slider {...settings}>

1

Lorem Ipsum

2

Lorem Ipsum 2

3

Lorem Ipsum 3

        </Slider>

    );
  }
}```

答:
I got it check my updated code on sandbox link here hopefully work on all browsers.

So for now i just removed the beforeChange and afterChange. By default the opacity of the text is 0 and then I update the opacity effects of the text from CSS targeting the slick-active or slick-current classes.

Still open for any workaround or possible solutions.


问:
NSDateFormatter not working
Ok I feel kind of dumb asking this, but any idea why this is not working:

```<code> {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"mmmm dd, yyyy"];

        NSDate *myDateFromString = [formatter dateFromString:creditDate.text];
         NSLog(@"%@", myDateFromString);
        [self.credit setCertificationDate: myDateFromString];
    }
</code>```

It returns null

答:
Format and string don't match because "m" is minute and "M" is month. So "August 18 2012" can't be interpreted, take "MMMM dd yyyy" instead You can check formats at unicode.org

I always set a locale explicitly:

```<code>  NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
  [dateFormatter setLocale:usLocale];
  [usLocale release];
</code>```

As long as you don't parse month names, it doesn't matter if your real locale is en_US if supplying an explicit format string.

Some more hints:

Use a hard coded strings for testing to rule out that the supplied date is wrong.

Try easier formatter strings like without time or month as number to isolate the erroneous part.

If it is still not working,you can use NSDateFormatter's getObjectValue:forString:range:error: to get more detailed information about the error.

Title: NSDateFormatter not working

Body:
Ok I feel kind of dumb asking this, but any idea why this is not working:

 {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"mmmm dd, yyyy"];

        NSDate *myDateFromString = [formatter dateFromString:creditDate.text];
         NSLog(@"%@", myDateFromString);
        [self.credit setCertificationDate: myDateFromString];
    }

It returns null

Body:
Format and string don't match because "m" is minute and "M" is month. So "August 18 2012" can't be interpreted, take "MMMM dd yyyy" instead You can check formats at unicode.org

I always set a locale explicitly:

  NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
  [dateFormatter setLocale:usLocale];
  [usLocale release];

As long as you don't parse month names, it doesn't matter if your real locale is en_US if supplying an explicit format string.

Some more hints:

Use a hard coded strings for testing to rule out that the supplied date is wrong.

Try easier formatter strings like without time or month as number to isolate the erroneous part.

If it is still not working,you can use NSDateFormatter's getObjectValue:forString:range:error: to get more detailed information about the error.


问:
SwiftUI, Core Data, ScrollViewReader - [error] precondition failure: invalid graph update (access from multiple threads?)
I'm trying to make a list of Core Data items in SwiftUI where adding new item will also trigger scroll to last item.

Here is a code I have. It's based on sample Core Data app in Xcode. One Entity: Item with one attribute: timestamp.

```<code>import SwiftUI
import CoreData

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
        animation: .default)
    private var items: FetchedResults<Item>

    var body: some View {
        NavigationView {
            ScrollViewReader { proxy in
                ScrollView {
                    ForEach(items, id: \.self) { item in
                        Text("Some item")
                            .padding()
                            .id(item.objectID)
                    }
                    .onDelete(perform: deleteItems)
                }
                .onChange(of: items.count) { _ in
//                  DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        withAnimation {
                            proxy.scrollTo(items.last?.objectID)
                        }
//                  }
                }
                .toolbar {
                    ToolbarItem {
                        Button(action: addItem) {
                            Label("Add Item", systemImage: "plus")
                        }
                    }
                }
            }
            Text("Select an item")
        }
    }

    private func addItem() {
        withAnimation {
            let newItem = Item(context: viewContext)
            newItem.timestamp = Date()

            do {
                try viewContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }

    private func deleteItems(offsets: IndexSet) {
        withAnimation {
            offsets.map { items[$0] }.forEach(viewContext.delete)

            do {
                try viewContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}
</code>```

It works, but I'm getting errors like this in Xcode:

2022-02-06 16:28:47.280984+0700 scroll[901:2894134] [error]
precondition failure: invalid graph update (access from multiple
threads?)

How to fix this? My guess is that it's something to do with concurrency. When new item is created it gets new id. Number of item changes. Core Data saves data. UI scrolls with animation. But maybe when scroll is triggered, swift is still not sure which item is last on the list?

So, things I've tried:

If you uncomment

```<code>DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
</code>```

And closing bracket as well - I am not getting an error when I'm adding one item at a time. But if I tap + few times, I'm getting errors again.

Another surprising thing is that if I change ScrollView to List, I am not getting errors at all. Even without DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {

答:
I think using Combine Framework with debounce(for:scheduler:options:) Operator should solve your problem.

I had the same problem with my code and following solution works great.

```<code>import SwiftUI
import Combine

struct ChatView: View {
@StateObject var messagesManager: MessagesManager
@State private var cancellables: Set<AnyCancellable> = []

var body: some View {
    VStack {
        VStack {
            TitleRow()

            ScrollViewReader { proxy in
                ScrollView {
                VStack {
                    ForEach(messagesManager.messages) { message in
                        MessageBubble(message: message)
                    }
                }
                .padding(.top, 10)
                .background(.white)
                .cornerRadius(30, corners: [.topLeft, .topRight]) // Custom cornerRadius modifier added in Extensions file
                .onChange(of: messagesManager.lastMessageId) { id in
                    // When the lastMessageId changes, scroll to the bottom of the conversation
                    messagesManager.$lastMessageId.debounce(for: .seconds(0.2), scheduler: RunLoop.main)
                        .sink { _ in
                            withAnimation {
                                proxy.scrollTo(id, anchor: .bottom)
                            }
                        }.store(in: &cancellables)

                    }
                }
            }
        }

        .background(Color("blue-curious"))

        MessageField()
            .environmentObject(messagesManager)
    }.onTapGesture {
        dissmissKeybord()
    }
}

func dissmissKeybord() {
    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}
</code>```

}

Body:
I'm trying to make a list of Core Data items in SwiftUI where adding new item will also trigger scroll to last item.

Here is a code I have. It's based on sample Core Data app in Xcode. One Entity: Item with one attribute: timestamp.

import SwiftUI
import CoreData

struct ContentView: View {
    @Environment(\.managedObjectContext) private var viewContext

    @FetchRequest(
        sortDescriptors: [NSSortDescriptor(keyPath: \Item.timestamp, ascending: true)],
        animation: .default)
    private var items: FetchedResults<Item>

    var body: some View {
        NavigationView {
            ScrollViewReader { proxy in
                ScrollView {
                    ForEach(items, id: \.self) { item in
                        Text("Some item")
                            .padding()
                            .id(item.objectID)
                    }
                    .onDelete(perform: deleteItems)
                }
                .onChange(of: items.count) { _ in
//                  DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
                        withAnimation {
                            proxy.scrollTo(items.last?.objectID)
                        }
//                  }
                }
                .toolbar {
                    ToolbarItem {
                        Button(action: addItem) {
                            Label("Add Item", systemImage: "plus")
                        }
                    }
                }
            }
            Text("Select an item")
        }
    }

    private func addItem() {
        withAnimation {
            let newItem = Item(context: viewContext)
            newItem.timestamp = Date()

            do {
                try viewContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }

    private func deleteItems(offsets: IndexSet) {
        withAnimation {
            offsets.map { items[$0] }.forEach(viewContext.delete)

            do {
                try viewContext.save()
            } catch {
                // Replace this implementation with code to handle the error appropriately.
                // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                let nsError = error as NSError
                fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
    }
}

It works, but I'm getting errors like this in Xcode:

2022-02-06 16:28:47.280984+0700 scroll[901:2894134] [error]
precondition failure: invalid graph update (access from multiple
threads?)

How to fix this? My guess is that it's something to do with concurrency. When new item is created it gets new id. Number of item changes. Core Data saves data. UI scrolls with animation. But maybe when scroll is triggered, swift is still not sure which item is last on the list?

So, things I've tried:

If you uncomment

DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {

And closing bracket as well - I am not getting an error when I'm adding one item at a time. But if I tap + few times, I'm getting errors again.

Another surprising thing is that if I change ScrollView to List, I am not getting errors at all. Even without DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {

Body:
I think using Combine Framework with debounce(for:scheduler:options:) Operator should solve your problem.

I had the same problem with my code and following solution works great.

import SwiftUI
import Combine

struct ChatView: View {
@StateObject var messagesManager: MessagesManager
@State private var cancellables: Set<AnyCancellable> = []

var body: some View {
    VStack {
        VStack {
            TitleRow()

            ScrollViewReader { proxy in
                ScrollView {
                VStack {
                    ForEach(messagesManager.messages) { message in
                        MessageBubble(message: message)
                    }
                }
                .padding(.top, 10)
                .background(.white)
                .cornerRadius(30, corners: [.topLeft, .topRight]) // Custom cornerRadius modifier added in Extensions file
                .onChange(of: messagesManager.lastMessageId) { id in
                    // When the lastMessageId changes, scroll to the bottom of the conversation
                    messagesManager.$lastMessageId.debounce(for: .seconds(0.2), scheduler: RunLoop.main)
                        .sink { _ in
                            withAnimation {
                                proxy.scrollTo(id, anchor: .bottom)
                            }
                        }.store(in: &cancellables)

                    }
                }
            }
        }

        .background(Color("blue-curious"))

        MessageField()
            .environmentObject(messagesManager)
    }.onTapGesture {
        dissmissKeybord()
    }
}

func dissmissKeybord() {
    UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
}

}


问:
Find any (arbitrary) path between a pair of source-destination
We are trying to write PGQL query on PG View(version 21.4) to find any (arbitrary) path between a pair of source-destination.

We had being using the following link as our PGQL guideline. https://pgql-lang.org/spec/1.4/#any-path

Query: SELECT s.ID as s_id, d.ID AS d_id FROM MATCH ANY (s) -[e]->+ (d) on my_graph

Error: java.lang.UnsupportedOperationException: Only zero (0) or more path quantifier is supported

What would had cause the error since it was working on PGS.
Any solution or workaround would be appreciated.

答:
In version 21.4, only * is supported on PG Views. From 22.1, other quantifiers are also supported.

Significant New Features in Oracle Graph Server and Client 22.1 https://docs.oracle.com/en/database/oracle/property-graph/22.1/spgdg/changes-in-this-release.html

Added PGQL support for more quantifiers when executing PGQL queries against property graph views.

Supported Quantifiers in PGQL SELECT Queries https://docs.oracle.com/en/database/oracle/property-graph/22.1/spgdg/pgql-features-supported-property-graph-views.html

```<code>Syntax  Description
------  -----------
*       zero or more
+       one or more
?       zero or one
{n}     exactly n
{n,}    n or more
{n,m}   between n and m (inclusive)
{,m}    between zero and m (inclusive)
</code>```

Body:
In version 21.4, only * is supported on PG Views. From 22.1, other quantifiers are also supported.

Significant New Features in Oracle Graph Server and Client 22.1 https://docs.oracle.com/en/database/oracle/property-graph/22.1/spgdg/changes-in-this-release.html

Added PGQL support for more quantifiers when executing PGQL queries against property graph views.

Supported Quantifiers in PGQL SELECT Queries https://docs.oracle.com/en/database/oracle/property-graph/22.1/spgdg/pgql-features-supported-property-graph-views.html

Syntax  Description
------  -----------
*       zero or more
+       one or more
?       zero or one
{n}     exactly n
{n,}    n or more
{n,m}   between n and m (inclusive)
{,m}    between zero and m (inclusive)


问:
How can I run private instances of my Discord Bot for each server?
A bot I'm working on offers a premium subscription and as one of the perks, I'd like to offer users a chance to change stuff like the avatar, username, status, etc. for the bot in their server, similar to how Mee6 does it. What would be the simplest way to go about this?
I'm thinking Docker and Containers would work out well, but I feel as if there's an easier way to go about this.</p>

答:
Yes, you can, but user need to provide their bot's token, you don't need to use docker container, you only need to create multiple Client

// Client one
const client1 = new Discord.Client({...});
// Client two
const client2 = new Discord.Client({...});

// login to client
client1.login("client 1 token")
client2.login("client 2 token")
```

If you want to manage more client, you can create a collection then put all client into it.

Body:
Yes, you can, but user need to provide their bot's token, you don't need to use docker container, you only need to create multiple Client

// Client one
const client1 = new Discord.Client({...});
// Client two
const client2 = new Discord.Client({...});

// login to client
client1.login("client 1 token")
client2.login("client 2 token")

If you want to manage more client, you can create a collection then put all client into it.


问:
How to put a black border around certain dots on a ggplot geom_point plot
I am trying to make a geom plot using ggplot for some pathways of interest. I would like to put a black border around certain dots that are significant. -log10 > 1.2, so they are easier to identify. Is there anyway to do this in the package so I do not have to do in an illustrator package after I have produced the image? Thank you kindly for advice.

Image of current dot image:

Image of raw data:

```<code>cols <- c("blue",
          "white",
          "red")

li <- c(-2, 2)

D1 <- ggplot(Practice, aes(Practice$case, Practice$pathway,
      colour = Enrichment_score, size = Practice$ln)) +
  geom_point(alpha = 0.8) +
  scale_colour_gradientn(colours = cols) +
  theme(legend.position="bottom") +
  scale_size(breaks = c(0, 1.2, 1.4), range =  c(0.06,12)) +
  guides(size=guide_legend(title = "-log10(q value)"),
         scale_colour_gradient()) +
  labs(colour = "Enrichment Score") +
  theme_bw()

D1 + ggtitle("") +
  xlab("") + ylab("") +
  scale_x_discrete(limits=c("Responder vs Non-responder",
                            "Non-responder vs Control",
                            "Responder vs Control",
                            "Case vs Control"))
</code>```

答:
Since I do not have your original data, and you don't have an example graph, I'll use diamonds to see if this is want you want.

To "circle" the data point that you want to highlight, we can use an extra geom_point, and use some subset of data in it.

In your case, the subset can be like geom_point(data = subset(Practice, -log10(Enrichment_score) > 1.2), col = "black", stroke = 3, shape = 21).

```<code>library(tidyveres)

cols <- c("blue", "white", "red")
ggplot(diamonds, aes(cut, clarity,
                    colour = price, size = depth)) +
  geom_point(alpha = 0.8) +
  scale_colour_gradientn(colours = cols) +
  theme(legend.position="bottom") +
  scale_size(breaks = c(0, 1.2, 1.4), range =  c(0.06,12)) +
  guides(size=guide_legend(title = "-log10(q value)"),
         scale_colour_gradient()) +
  labs(colour = "Enrichment Score") +
  theme_bw() +
  geom_point(data = subset(diamonds, depth > 70), col = "black", stroke = 3, shape = 21)
</code>```

Also, you don't need to use the dollar sign $ to specify column names in ggplot.

Body:
I am trying to make a geom plot using ggplot for some pathways of interest. I would like to put a black border around certain dots that are significant. -log10 > 1.2, so they are easier to identify. Is there anyway to do this in the package so I do not have to do in an illustrator package after I have produced the image? Thank you kindly for advice.

Image of current dot image:

Image of raw data:

cols <- c("blue",
          "white",
          "red")

li <- c(-2, 2)

D1 <- ggplot(Practice, aes(Practice$case, Practice$pathway,
      colour = Enrichment_score, size = Practice$ln)) +
  geom_point(alpha = 0.8) +
  scale_colour_gradientn(colours = cols) +
  theme(legend.position="bottom") +
  scale_size(breaks = c(0, 1.2, 1.4), range =  c(0.06,12)) +
  guides(size=guide_legend(title = "-log10(q value)"),
         scale_colour_gradient()) +
  labs(colour = "Enrichment Score") +
  theme_bw()

D1 + ggtitle("") +
  xlab("") + ylab("") +
  scale_x_discrete(limits=c("Responder vs Non-responder",
                            "Non-responder vs Control",
                            "Responder vs Control",
                            "Case vs Control"))

Body:
Since I do not have your original data, and you don't have an example graph, I'll use diamonds to see if this is want you want.

To "circle" the data point that you want to highlight, we can use an extra geom_point, and use some subset of data in it.

In your case, the subset can be like geom_point(data = subset(Practice, -log10(Enrichment_score) > 1.2), col = "black", stroke = 3, shape = 21).

library(tidyveres)

cols <- c("blue", "white", "red")
ggplot(diamonds, aes(cut, clarity,
                    colour = price, size = depth)) +
  geom_point(alpha = 0.8) +
  scale_colour_gradientn(colours = cols) +
  theme(legend.position="bottom") +
  scale_size(breaks = c(0, 1.2, 1.4), range =  c(0.06,12)) +
  guides(size=guide_legend(title = "-log10(q value)"),
         scale_colour_gradient()) +
  labs(colour = "Enrichment Score") +
  theme_bw() +
  geom_point(data = subset(diamonds, depth > 70), col = "black", stroke = 3, shape = 21)

Also, you don't need to use the dollar sign $ to specify column names in ggplot.


问:
What is the difference between AWS::Serverless::Api and AWS::Serverless::HttpApi?
What is the difference between AWS::Serverless::Api and AWS::Serverless::HttpApi?

From what I can understand AWS::Serverless::HttpApi seems to configure the HTTP API which can also be configured with AWS::ApiGatewayV2::Api, is this correct?

What does AWS::Serverless::Api configure, is it the old RestAPI which you also can configure through AWS::ApiGateway::RestApi?

答:
Yes, AWS::Serverless::Api configures REST API. AWS::Serverless::Api is a higher level resource then AWS::ApiGateway::RestApi.

For example with just single AWS::Serverless::Api you can define your paths (/test) and their methods (GET). The same using AWS::ApiGateway::RestApi is not possible. You have to separately construct AWS::ApiGateway::Resource and AWS::ApiGateway::Method.


问:
How to get the class names in a tensorflow dataset?
I am trying to understand how to work with tensorflow datasets, tfds.

The dataset is a directory of this kind

```<code>-dataset
  -train
    -class_name1
      -files...
    -class_name2
      -files...
   -val
    -class_name1
      -files...
    -class_name2
      -files...
  -test
    -class_name1
      -files...
    -class_name2
      -files...
</code>```

Here is some code:

```<code>import tensorflow_datasets as tfds
builder = tfds.ImageFolder('/content/dataset')
train_ds, val_ds, test_ds = builder.as_dataset(split=['train', 'val', 'test'], shuffle_files=True, as_supervised=True)
</code>```
```<code>print(builder.info)
</code>```
```<code>Output:
tfds.core.DatasetInfo(
    name='image_folder',
    version=1.0.0,
    description='Generic image classification dataset.',
    homepage='https://www.tensorflow.org/datasets/catalog/image_folder',
    features=FeaturesDict({
        'image': Image(shape=(None, None, 3), dtype=tf.uint8),
        'image/filename': Text(shape=(), dtype=tf.string),
        'label': ClassLabel(shape=(), dtype=tf.int64, num_classes=243),
    }),
    total_num_examples=73090,
    splits={
        'test': 5849,
        'train': 58469,
        'val': 8772,
    },
    supervised_keys=('image', 'label'),
    citation="""""",
    redistribution_info=,
)
</code>```

When i am plotting, doing classification reports, confusion matrix etc
i want to be able to use the class_names not the integer labels.

Is there some easy command that give me access to the class_names?
(There are 243 classes, not 2)

答:
You have access to train_ds, val_ds, test_ds, and they have class_names, which you could access using the label as an index, as mentioned by fpierrem

Here's am example of a plot:

```<code>import matplotlib.pyplot as plt

plt.figure(figsize=(10, 10))
for images, labels in train_ds.take(1):
    for i in range(9):
        ax = plt.subplot(3, 3, i + 1)
        plt.imshow(images[i].numpy().astype("uint8"))
        plt.title(train_ds.class_names[labels[i]])
        plt.axis("off")

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

see. https://www.tensorflow.org/tutorials/keras/classification#import_the_fashion_mnist_dataset
and
https://www.tensorflow.org/tutorials/load_data/images#visualize_the_data

Body:
I am trying to understand how to work with tensorflow datasets, tfds.

The dataset is a directory of this kind

-dataset
  -train
    -class_name1
      -files...
    -class_name2
      -files...
   -val
    -class_name1
      -files...
    -class_name2
      -files...
  -test
    -class_name1
      -files...
    -class_name2
      -files...

Here is some code:

import tensorflow_datasets as tfds
builder = tfds.ImageFolder('/content/dataset')
train_ds, val_ds, test_ds = builder.as_dataset(split=['train', 'val', 'test'], shuffle_files=True, as_supervised=True)

print(builder.info)

Output:
tfds.core.DatasetInfo(
    name='image_folder',
    version=1.0.0,
    description='Generic image classification dataset.',
    homepage='https://www.tensorflow.org/datasets/catalog/image_folder',
    features=FeaturesDict({
        'image': Image(shape=(None, None, 3), dtype=tf.uint8),
        'image/filename': Text(shape=(), dtype=tf.string),
        'label': ClassLabel(shape=(), dtype=tf.int64, num_classes=243),
    }),
    total_num_examples=73090,
    splits={
        'test': 5849,
        'train': 58469,
        'val': 8772,
    },
    supervised_keys=('image', 'label'),
    citation="""""",
    redistribution_info=,
)

When i am plotting, doing classification reports, confusion matrix etc
i want to be able to use the class_names not the integer labels.

Is there some easy command that give me access to the class_names?
(There are 243 classes, not 2)

Body:
You have access to train_ds, val_ds, test_ds, and they have class_names, which you could access using the label as an index, as mentioned by fpierrem

Here's am example of a plot:

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 10))
for images, labels in train_ds.take(1):
    for i in range(9):
        ax = plt.subplot(3, 3, i + 1)
        plt.imshow(images[i].numpy().astype("uint8"))
        plt.title(train_ds.class_names[labels[i]])
        plt.axis("off")

plt.show()

see. https://www.tensorflow.org/tutorials/keras/classification#import_the_fashion_mnist_dataset
and
https://www.tensorflow.org/tutorials/load_data/images#visualize_the_data