问:
How to Enable Or Disable One td value angularjs based On Radio Button Click?
Here In a table, multiple records are there, I want to enable or disable particular table data based on the radio button click. For Ex: If I click Yes then that row table data Should Enable. Rest All Should In Disable Form.(AngularJS)

Anyone Could you please help me on this.

```<code><table style="background: ghostwhite;" class="table table-striped table-hover">

      <thead>
        <tr>
          <th scope="col">#</th>
          <th scope="col">Product Name</th>
          <th scope="col">Variant Name</th>
          <th scope="col">Purchase Price</th>
          <th scope="col">Selling Price</th>

          <th scope="col">Offer ?</th>
          <th scope="col">Offer Details</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-show="AllItemDetails.length == 0"><td colspan="5" style="text-align:center;color: red;font-weight: bold;">No Details Found ..</td></tr>
            <tr dir-paginate="item in AllItemDetails|itemsPerPage:itemsPerPage |filter:search" total-items="total_count" current-page="pageno">
                <td>{{itemsPerPage * (pageno-1)+$index+1}}</td>
                <td>{{item.productName}}</td>
                <td>{{item.variantName}}</td>
                <td>{{item.purchasePrice}}</td>
                <td>
                    <div class="col-md-6">
                        <input type="text" ng-model="item.sellingPrice" class="form-control" placeholder="Enter Selling Price" only-digits required/>
                    </div>
                </td>

                <td>
                    <div class="col-md-6">
                            <label>
                                <input type="radio" name="isOffer{{itemsPerPage * (pageno-1)+$index+1}}" value="YES" ng-model="isOffer" ng-value="'YES'" ng-checked="(isOffer === 'YES')" ng-click="showDetails(itemsPerPage * (pageno-1)+$index+1)">YES
                            </label>
                            <label>
                                <input type="radio" name="isOffer{{itemsPerPage * (pageno-1)+$index+1}}" value="NO" ng-model="isOffer" ng-value="'NO'" ng-checked="(isOffer === 'NO')" ng-click="hideDetails(itemsPerPage * (pageno-1)+$index+1)">NO
                            </label>
                    </div>
                </td>

                <td>
                    <div id="offer{{itemsPerPage * (pageno-1)+$index+1}}">
                            <input ng-disabled="{{isOffer === 'NO'}}" type="text" placeholder="Offer Name"/>
                            <input ng-disabled="{{isOffer === 'NO'}}" type="text" placeholder="%"/>
                    </div>
                </td>

            </tr>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td>
                    <input style="float: right;" type="button" class="btn btn-primary" value="Update Price" ng-click="updateSellingPrice(AllItemDetails)" ng-disabled="pricemanagement.$invalid"/>
                </td>
            </tr>
     </tbody>

    </table>
</code>```

答:
The issue here is with what you are passing to your ng-disabled directive. ng-disabled takes an expression and evaluates it within the present scope. So it is not required to interpolate ({{...}}) the expression.

You can fix your issue by removing the interpolation ({{...}}) when passing the expression to the ng-disabled directive

```<code><div id="offer{{itemsPerPage * (pageno-1)+$index+1}}">
    <input ng-disabled="isOffer === 'NO'" type="text" placeholder="Offer Name"/>
    <input ng-disabled="isOffer === 'NO'" type="text" placeholder="%"/>
</div>
</code>```

Here is the documentation for reference: https://docs.angularjs.org/api/ng/directive/ngDisabled

Body:
Here In a table, multiple records are there, I want to enable or disable particular table data based on the radio button click. For Ex: If I click Yes then that row table data Should Enable. Rest All Should In Disable Form.(AngularJS)

Anyone Could you please help me on this.

          #
          Product Name
          Variant Name
          Purchase Price
          Selling Price

          Offer ?
          Offer Details

No Details Found ..

                {{itemsPerPage * (pageno-1)+$index+1}}
                {{item.productName}}
                {{item.variantName}}
                {{item.purchasePrice}}

                        <input type="text" ng-model="item.sellingPrice" class="form-control" placeholder="Enter Selling Price" only-digits required/>

                                <input type="radio" name="isOffer{{itemsPerPage * (pageno-1)+$index+1}}" value="YES" ng-model="isOffer" ng-value="'YES'" ng-checked="(isOffer === 'YES')" ng-click="showDetails(itemsPerPage * (pageno-1)+$index+1)">YES

                                <input type="radio" name="isOffer{{itemsPerPage * (pageno-1)+$index+1}}" value="NO" ng-model="isOffer" ng-value="'NO'" ng-checked="(isOffer === 'NO')" ng-click="hideDetails(itemsPerPage * (pageno-1)+$index+1)">NO

                            <input ng-disabled="{{isOffer === 'NO'}}" type="text" placeholder="Offer Name"/>
                            <input ng-disabled="{{isOffer === 'NO'}}" type="text" placeholder="%"/>

                    <input style="float: right;" type="button" class="btn btn-primary" value="Update Price" ng-click="updateSellingPrice(AllItemDetails)" ng-disabled="pricemanagement.$invalid"/>

Body:
The issue here is with what you are passing to your ng-disabled directive. ng-disabled takes an expression and evaluates it within the present scope. So it is not required to interpolate ({{...}}) the expression.

You can fix your issue by removing the interpolation ({{...}}) when passing the expression to the ng-disabled directive

<div id="offer{{itemsPerPage * (pageno-1)+$index+1}}">
    <input ng-disabled="isOffer === 'NO'" type="text" placeholder="Offer Name"/>
    <input ng-disabled="isOffer === 'NO'" type="text" placeholder="%"/>
</div>

Here is the documentation for reference: https://docs.angularjs.org/api/ng/directive/ngDisabled


来源: stackexchange

问:
java.lang.ClassCastException: cannot assign instance of scala.collection.immutable.List$SerializationProxy

I processing the csv file from Spring Batch java application to spark cleaning.

cleaned files writing to parquet in cluster.

getting Serialization exception.

Caused by: java.lang.ClassCastException: cannot assign instance of scala.collection.immutable.List$SerializationProxy to field org.apache.spark.rdd.RDD.org$apache$spark$rdd$RDD$$dependencies_ of type scala.collection.Seq in instance of org.apache.spark.rdd.MapPartitionsRDD
          at java.io.ObjectStreamClass$FieldReflector.setObjFieldValues(ObjectStreamClass.java:2287)

答:
I have the same error message when running this code:

```<code>import org.apache.spark.ml.feature.{CountVectorizer, CountVectorizerModel}
import org.apache.spark.ml.clustering.LDA
import org.apache.spark.sql.functions.udf
import scala.collection.mutable.WrappedArray

val txt = Array("A B B C", "A B D D", "A C D")
val txtDf     = spark.sparkContext.parallelize(txt).toDF("txt")
val txtDfSplit = txtDf.withColumn("txt", split(col("txt"), " "))

// val txtDfSplit = df.withColumn("txt", split(col("txt"), " "))

// create sparse vector with the number
// of occurrences of each word using CountVectorizer
val cvModel = new CountVectorizer().setInputCol("txt").setOutputCol("features").setVocabSize(4).setMinDF(2).fit(txtDfSplit)

val txtDfTrain = cvModel.transform(txtDfSplit)
txtDfTrain.show(false)
</code>```

Produces this error:

org.apache.spark.SparkException: Job aborted due to stage failure:
  Task 9 in stage 1.0 failed 4 times, most recent failure: Lost task 9.3
  in stage 1.0 (TID 25, somehostname.domain, executor 1):
  java.lang.ClassCastException: cannot assign instance of
  scala.collection.immutable.List$SerializationProxy to field
  org.apache.spark.rdd.RDD.org$apache$spark$rdd$RDD$$dependencies_ of
  type scala.collection.Seq in instance of
  org.apache.spark.rdd.MapPartitionsRDD

I have been looking through various pages describing this error and it seems to be some kind of version conflict. The code works in IntelliJ (stand alone). I get the error when the app is submitted to Spark.

ContentLicense: CC BY-SA 4.0

Body:
I have the same error message when running this code:

import org.apache.spark.ml.feature.{CountVectorizer, CountVectorizerModel}
import org.apache.spark.ml.clustering.LDA
import org.apache.spark.sql.functions.udf
import scala.collection.mutable.WrappedArray

val txt = Array("A B B C", "A B D D", "A C D")
val txtDf     = spark.sparkContext.parallelize(txt).toDF("txt")
val txtDfSplit = txtDf.withColumn("txt", split(col("txt"), " "))

// val txtDfSplit = df.withColumn("txt", split(col("txt"), " "))

// create sparse vector with the number
// of occurrences of each word using CountVectorizer
val cvModel = new CountVectorizer().setInputCol("txt").setOutputCol("features").setVocabSize(4).setMinDF(2).fit(txtDfSplit)

val txtDfTrain = cvModel.transform(txtDfSplit)
txtDfTrain.show(false)

Produces this error:

org.apache.spark.SparkException: Job aborted due to stage failure:
  Task 9 in stage 1.0 failed 4 times, most recent failure: Lost task 9.3
  in stage 1.0 (TID 25, somehostname.domain, executor 1):
  java.lang.ClassCastException: cannot assign instance of
  scala.collection.immutable.List$SerializationProxy to field
  org.apache.spark.rdd.RDD.org$apache$spark$rdd$RDD$$dependencies_ of
  type scala.collection.Seq in instance of
  org.apache.spark.rdd.MapPartitionsRDD

I have been looking through various pages describing this error and it seems to be some kind of version conflict. The code works in IntelliJ (stand alone). I get the error when the app is submitted to Spark.


问:
Using pointer to a struct to create linked list and Memory allocation in C
I have a concept question I suppose.  When I need to create a linked list, but I am just given a pointer to a struct (and the struct contains some data type and pointer "next").  How would I ensure that I am creating the other links and not just the root node?  I am not using malloc or else this would be more apparent answer. This list is acting as malloc itself.

Thanks in advance!

To Clarify:

There will be single dimension array which will act as a block of memory of fixed sized.  The linked list will then "allocate" by removing a node and putting it into the array or "free" data by removing it from array to add back to list.

example

(struct defined by some data type and pointer)
struct is called node

```<code>node array[10];  //this acts as memory
node* linked_list;  //this gives or removes data to memory (array)
</code>```

答:
This is similar to how we did things in my Data Structures class using FORTRAN 77 (back in the mid-Cretaceous); we allocated a fixed-size array and used it as our memory pool.

Basically, you have to maintain a "free" list; these are the nodes that are available for use.  When you first start up, you initialize each element in your array to explicitly point to the next element:

```<code>struct node {T data; struct node *next; } pool[N]; // for some type T
...
for (i = 0; i < N-1; i++)
  pool[i].next = &pool[i+1];
pool[i].next = NULL;
</code>```

Your free list initially points to the first element in the pool:

```<code>struct node *free = &pool[0];
</code>```

When you allocate a node, you retrieve the element that free points to, update free to point to the next available element in the list (if one exists), then initialize the element as necessary:

```<code>if (free) // is there a free node available
{
  struct node *newNode = free;
  free = free->next;
  newNode->data = ...;
  newNode->next = NULL;
  ...
}
</code>```

When you're done with a node, you add it back to the head of the free list:

```<code>node->next = free;
free = node;
</code>```

Naturally, real code would be better organized than this, but this should be enough to give you an idea of what to do.

ContentLicense: CC BY-SA 3.0

Body:
I have a concept question I suppose.  When I need to create a linked list, but I am just given a pointer to a struct (and the struct contains some data type and pointer "next").  How would I ensure that I am creating the other links and not just the root node?  I am not using malloc or else this would be more apparent answer. This list is acting as malloc itself.

Thanks in advance!

To Clarify:

There will be single dimension array which will act as a block of memory of fixed sized.  The linked list will then "allocate" by removing a node and putting it into the array or "free" data by removing it from array to add back to list.

example

(struct defined by some data type and pointer)
struct is called node

node array[10];  //this acts as memory
node* linked_list;  //this gives or removes data to memory (array)

Body:
This is similar to how we did things in my Data Structures class using FORTRAN 77 (back in the mid-Cretaceous); we allocated a fixed-size array and used it as our memory pool.

Basically, you have to maintain a "free" list; these are the nodes that are available for use.  When you first start up, you initialize each element in your array to explicitly point to the next element:

struct node {T data; struct node *next; } pool[N]; // for some type T
...
for (i = 0; i < N-1; i++)
  pool[i].next = &pool[i+1];
pool[i].next = NULL;

Your free list initially points to the first element in the pool:

struct node *free = &pool[0];

When you allocate a node, you retrieve the element that free points to, update free to point to the next available element in the list (if one exists), then initialize the element as necessary:

if (free) // is there a free node available
{
  struct node *newNode = free;
  free = free->next;
  newNode->data = ...;
  newNode->next = NULL;
  ...
}

When you're done with a node, you add it back to the head of the free list:

node->next = free;
free = node;

Naturally, real code would be better organized than this, but this should be enough to give you an idea of what to do.


问:
I am seeing a "GET /emp HTTP/1.1" 404 2159 on my terminal when I try to connect to the django server ...I am receiving a 404 page not found
I feel like my server can't render my views well because of some url configuration issues.It always render the message Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/emp

Here is my project structure

```<code>|--hrdjango
 |--employee
   |--migrations folder
   |--admin.py
   |--urls.py
    ...
   |views.py

|--hrdjango
  ...
 |--settings.py
 |--urls.py
</code>```

views.py

```<code>from django.shortcuts import render, redirect
from .forms import EmployeeForm
from .models import Employee
# Create your views here.
def emp(request):
    if request.method == "POST":
        form = EmployeeForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                return redirect('/show')
            except:
                pass
    else:
        form = EmployeeForm()
    return render(request,'index.html',{'form':form})
def show(request):
    employees = Employee.objects.all()
    return render(request,"show.html",{'employees':employees})
def edit(request, id):
    employee = Employee.objects.get(id=id)
    return render(request,'edit.html', {'employee':employee})
def update(request, id):
    employee = Employee.objects.get(id=id)
    form = EmployeeForm(request.POST, instance = employee)
    if form.is_valid():
        form.save()
        return redirect("/show")
    return render(request, 'edit.html', {'employee': employee})
def destroy(request, id):
    employee = Employee.objects.get(id=id)
    employee.delete()
    return redirect("/show")

</code>```

employee/urls.py

```<code>
from .import views
from django.contrib import admin
from django.urls import path, include
app_name = 'employee'
urlpatterns = [
    path('', views.emp, name='emp'),
    path('show',views.show, name='show'),
    path('edit/<int:id>', views.edit, name='edit'),
    path('update/<int:id>', views.update, name='update'),
    path('delete/<int:id>', views.destroy, name='destroy'),
    ]
</code>```

hrdjango/urls

```<code>
from django.contrib import admin
from django.urls import include, path
from employee import views

urlpatterns = [
path('admin/', admin.site.urls),
path('employee/', include('employee.urls')),
path('', views.emp),
]
</code>```

I was expecting to see the views rendering according to my urls config, but it seems like it can't render my views because it is not seeing it.

答:
If you want to access emp(request) view.

hrdjango/urls

```<code>from django.contrib import admin
from django.urls import include, path
from employee import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('employee/', include('employee.urls')),
    # path('', views.emp), - remove this line
]
</code>```

Then,,, You can make GET request for example, like this.

Below URI will invoke emp(request) method

http://127.0.0.1/employee/

Also, in your ModelForm Meta class, you should specify Employee class and not Employee class instance.

forms.py

```<code>from django import forms
from .models import Employee
class EmployeeForm(forms.ModelForm):

    class Meta:
        model = Employee
        fields = '__all__'
</code>```

I hope, it helps you.

Body:
I feel like my server can't render my views well because of some url configuration issues.It always render the message Page not found (404)
Request Method: GET
Request URL:    http://127.0.0.1:8000/emp

Here is my project structure

|--hrdjango
 |--employee
   |--migrations folder
   |--admin.py
   |--urls.py
    ...
   |views.py

|--hrdjango
  ...
 |--settings.py
 |--urls.py

views.py

from django.shortcuts import render, redirect
from .forms import EmployeeForm
from .models import Employee
# Create your views here.
def emp(request):
    if request.method == "POST":
        form = EmployeeForm(request.POST)
        if form.is_valid():
            try:
                form.save()
                return redirect('/show')
            except:
                pass
    else:
        form = EmployeeForm()
    return render(request,'index.html',{'form':form})
def show(request):
    employees = Employee.objects.all()
    return render(request,"show.html",{'employees':employees})
def edit(request, id):
    employee = Employee.objects.get(id=id)
    return render(request,'edit.html', {'employee':employee})
def update(request, id):
    employee = Employee.objects.get(id=id)
    form = EmployeeForm(request.POST, instance = employee)
    if form.is_valid():
        form.save()
        return redirect("/show")
    return render(request, 'edit.html', {'employee': employee})
def destroy(request, id):
    employee = Employee.objects.get(id=id)
    employee.delete()
    return redirect("/show")

employee/urls.py

from .import views
from django.contrib import admin
from django.urls import path, include
app_name = 'employee'
urlpatterns = [
    path('', views.emp, name='emp'),
    path('show',views.show, name='show'),
    path('edit/<int:id>', views.edit, name='edit'),
    path('update/<int:id>', views.update, name='update'),
    path('delete/<int:id>', views.destroy, name='destroy'),
    ]

hrdjango/urls

from django.contrib import admin
from django.urls import include, path
from employee import views

urlpatterns = [
path('admin/', admin.site.urls),
path('employee/', include('employee.urls')),
path('', views.emp),
]

I was expecting to see the views rendering according to my urls config, but it seems like it can't render my views because it is not seeing it.

Body:
If you want to access emp(request) view.

hrdjango/urls

from django.contrib import admin
from django.urls import include, path
from employee import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('employee/', include('employee.urls')),
    # path('', views.emp), - remove this line
]

Then,,, You can make GET request for example, like this.

Below URI will invoke emp(request) method

http://127.0.0.1/employee/

Also, in your ModelForm Meta class, you should specify Employee class and not Employee class instance.

forms.py

from django import forms
from .models import Employee
class EmployeeForm(forms.ModelForm):

    class Meta:
        model = Employee
        fields = '__all__'

I hope, it helps you.


问:
React Material UI Checkbox: How to check/uncheck other boxes in group by checking a different box?
I have 3 checkboxes set up, (Not Started, In Progress, Completed), that I would like allow only one to be checked at a certain time.

So if Not Started is automatically checked to begin with, how would I cause it uncheck 'Not Started' if I check 'Completed'?

Heres my code for now:

In App.js:

```<code>  const newGame = {
     id: uuid.v4(),
     title: title,
     hours: hours,
     notStarted: true,
     inProgress: false,
     completed: false,

  }

  notStarted = (id) => {
    this.setState({games: this.state.games.map(game => {
      if(game.id === id){

        game.notStarted = !game.notStarted
        game.inProgress = false;
        game.completed = false;
      }
    return game;
  })})
};

  markCompleted = (id) => {
this.setState({games: this.state.games.map(game => {
  if(game.id === id){

    game.completed = !game.completed
    game.notStarted = false;
    game.inProgress = false;
  }
  return game;
})})
};
</code>```

And in the render() method:

```<code><Backlog games={this.state.games}
        markCompleted={this.markCompleted}
        inProgress={this.inProgress}
        notStarted={this.notStarted}
/>
</code>```

And this is the checkboxes in Game.js

```<code><FormControlLabel
      control={
         <Checkbox
              color="primary"
              onChange={this.props.notStarted.bind(this, id)}
          />
      }
      label="Not Started"
/>
<FormControlLabel
      control={
         <Checkbox
              color="primary"
              onChange={this.props.markCompleted.bind(this, id)}
          />
      }
      label="Completed"
/>
</code>```

As of now, I can successfully change the state of the props, but I'm unsure how to make the box check/uncheck according to the state?

答: Simply use the radio button instead of checkbox. This is the default radio behavior.</p>

Body:
I have 3 checkboxes set up, (Not Started, In Progress, Completed), that I would like allow only one to be checked at a certain time.

So if Not Started is automatically checked to begin with, how would I cause it uncheck 'Not Started' if I check 'Completed'?

Heres my code for now:

In App.js:

  const newGame = {
     id: uuid.v4(),
     title: title,
     hours: hours,
     notStarted: true,
     inProgress: false,
     completed: false,

  }

  notStarted = (id) => {
    this.setState({games: this.state.games.map(game => {
      if(game.id === id){

        game.notStarted = !game.notStarted
        game.inProgress = false;
        game.completed = false;
      }
    return game;
  })})
};

  markCompleted = (id) => {
this.setState({games: this.state.games.map(game => {
  if(game.id === id){

    game.completed = !game.completed
    game.notStarted = false;
    game.inProgress = false;
  }
  return game;
})})
};

And in the render() method:

<Backlog games={this.state.games}
        markCompleted={this.markCompleted}
        inProgress={this.inProgress}
        notStarted={this.notStarted}
/>

And this is the checkboxes in Game.js

<FormControlLabel
      control={
         <Checkbox
              color="primary"
              onChange={this.props.notStarted.bind(this, id)}
          />
      }
      label="Not Started"
/>
<FormControlLabel
      control={
         <Checkbox
              color="primary"
              onChange={this.props.markCompleted.bind(this, id)}
          />
      }
      label="Completed"
/>

As of now, I can successfully change the state of the props, but I'm unsure how to make the box check/uncheck according to the state?


问:
org.gradle.execution.MultipleBuildFailures when using @Query Room Persistence Library
Getting Build error when using @Query in Dao class (room persistence library)

I am using both java and kotlin in my project so there may be problem of dependencies, I tried different implementation and kapt but no luck.

My dependencies (see at last for room persistence library)

```<code>dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
//noinspection GradleCompatible
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'com.google.android.material:material:1.1.0-alpha05'
implementation "org.jetbrains.anko:anko:$anko_version"
implementation "org.jetbrains.anko:anko-commons:$anko_version"
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.google.dagger:dagger:2.19'
implementation 'androidx.appcompat:appcompat:1.1.0-alpha03'
implementation 'com.google.firebase:firebase-database:16.1.0'
annotationProcessor 'com.google.dagger:dagger-compiler:2.19'
kapt 'com.google.dagger:dagger-android-processor:2.19'
kapt 'com.google.dagger:dagger-compiler:2.19'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'

implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'

implementation 'com.google.code.findbugs:jsr305:3.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
//BUTTER KNIFE
implementation 'com.jakewharton:butterknife:10.1.0'
kapt 'com.jakewharton:butterknife-compiler:10.1.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
//crashlytics
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.9'
// Update your firebase-core version, if it's lower than v11.4.2
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.crashlytics.sdk.android:crashlytics-ndk:2.0.5'

//firebase messaging
implementation 'com.google.firebase:firebase-messaging:17.5.0'
//sms retrival
implementation 'com.google.android.gms:play-services-base:16.1.0'
implementation 'com.google.android.gms:play-services-identity:16.0.0'
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.android.gms:play-services-auth-api-phone:16.0.0'
implementation project(':library')

//for intro
implementation 'com.github.AppIntro:AppIntro:5.1.0'
//picaso
implementation 'com.squareup.picasso:picasso:2.71828'
//room
def room_version = "1.1.1"

implementation "android.arch.persistence.room:runtime:$room_version"
kapt "android.arch.persistence.room:compiler:$room_version"
</code>```

My Entity Class

```<code>    @Entity(tableName = "product")
    public class Product
    {
        @PrimaryKey
        @ColumnInfo(name = "id")
        public Integer id;
        @ColumnInfo(name = "category")
        public String category;
        @ColumnInfo(name = "name")
        public String name;
        @ColumnInfo(name = "price")
        public Double price;
        @ColumnInfo(name = "desc")
        public String desc;
        @ColumnInfo(name = "img_url")
        public String img_url;

        public Product(Integer id, String category, String name, Double price, String desc, String img_url) {
            this.id = id;
            this.category = category;
            this.name = name;
            this.price = price;
            this.desc = desc;
            this.img_url = img_url;
        }
    }
</code>```

My Dao Class which is building good when not using @Query,
but when @Query is in used, building error causes.

```<code>    @Dao
    public interface CartDao
    {
        @Query("SELECT * FROM product")
        ArrayList<Product> getAllProduct();

        @Delete
        void delete(Product cart);
    }
</code>```

Build Error

org.gradle.execution.MultipleBuildFailures: Build completed with 1 failures..
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  at         java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  at java.lang.Thread.run(Thread.java:745)
          Caused by: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:kaptPureshDebugKotlin'...6 more
          Caused by: org.gradle.api.GradleException: Compilation error. See log for more details
      at         org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:14)
      at         org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.run(GradleKotlinCompilerWork.kt:135)
      at         org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:152)
      at         org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:147)
      at         org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runJvmCompilerAsync(GradleKotlinCompilerRunner.kt:87)
      at         org.jetbrains.kotlin.gradle.internal.KaptWithKotlincTask.compile(KaptWithKotlincTask.kt:72)..34 more

答:
I also had this same error run clean build, invalidate caches or try run with </p>

```<code>gradlew assembleDebug
</code>```

<p>This will show you where is the problem in you app. </p>

Body:
Getting Build error when using @Query in Dao class (room persistence library)

I am using both java and kotlin in my project so there may be problem of dependencies, I tried different implementation and kapt but no luck.

My dependencies (see at last for room persistence library)

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
//noinspection GradleCompatible
implementation 'com.squareup.okhttp3:logging-interceptor:3.11.0'
implementation 'com.google.android.material:material:1.1.0-alpha05'
implementation "org.jetbrains.anko:anko:$anko_version"
implementation "org.jetbrains.anko:anko-commons:$anko_version"
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.google.dagger:dagger:2.19'
implementation 'androidx.appcompat:appcompat:1.1.0-alpha03'
implementation 'com.google.firebase:firebase-database:16.1.0'
annotationProcessor 'com.google.dagger:dagger-compiler:2.19'
kapt 'com.google.dagger:dagger-android-processor:2.19'
kapt 'com.google.dagger:dagger-compiler:2.19'
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.4.0'

implementation 'io.reactivex.rxjava2:rxandroid:2.1.0'

implementation 'com.google.code.findbugs:jsr305:3.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
//BUTTER KNIFE
implementation 'com.jakewharton:butterknife:10.1.0'
kapt 'com.jakewharton:butterknife-compiler:10.1.0'
implementation 'androidx.recyclerview:recyclerview:1.0.0'
//crashlytics
implementation 'com.crashlytics.sdk.android:crashlytics:2.9.9'
// Update your firebase-core version, if it's lower than v11.4.2
implementation 'com.google.firebase:firebase-core:16.0.8'
implementation 'com.crashlytics.sdk.android:crashlytics-ndk:2.0.5'

//firebase messaging
implementation 'com.google.firebase:firebase-messaging:17.5.0'
//sms retrival
implementation 'com.google.android.gms:play-services-base:16.1.0'
implementation 'com.google.android.gms:play-services-identity:16.0.0'
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.android.gms:play-services-auth-api-phone:16.0.0'
implementation project(':library')

//for intro
implementation 'com.github.AppIntro:AppIntro:5.1.0'
//picaso
implementation 'com.squareup.picasso:picasso:2.71828'
//room
def room_version = "1.1.1"

implementation "android.arch.persistence.room:runtime:$room_version"
kapt "android.arch.persistence.room:compiler:$room_version"

My Entity Class

    @Entity(tableName = "product")
    public class Product
    {
        @PrimaryKey
        @ColumnInfo(name = "id")
        public Integer id;
        @ColumnInfo(name = "category")
        public String category;
        @ColumnInfo(name = "name")
        public String name;
        @ColumnInfo(name = "price")
        public Double price;
        @ColumnInfo(name = "desc")
        public String desc;
        @ColumnInfo(name = "img_url")
        public String img_url;

        public Product(Integer id, String category, String name, Double price, String desc, String img_url) {
            this.id = id;
            this.category = category;
            this.name = name;
            this.price = price;
            this.desc = desc;
            this.img_url = img_url;
        }
    }

My Dao Class which is building good when not using @Query,
but when @Query is in used, building error causes.

    @Dao
    public interface CartDao
    {
        @Query("SELECT * FROM product")
        ArrayList<Product> getAllProduct();

        @Delete
        void delete(Product cart);
    }

Build Error

org.gradle.execution.MultipleBuildFailures: Build completed with 1 failures..
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  at         java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  at java.lang.Thread.run(Thread.java:745)
          Caused by: org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:kaptPureshDebugKotlin'...6 more
          Caused by: org.gradle.api.GradleException: Compilation error. See log for more details
      at         org.jetbrains.kotlin.gradle.tasks.TasksUtilsKt.throwGradleExceptionIfError(tasksUtils.kt:14)
      at         org.jetbrains.kotlin.compilerRunner.GradleKotlinCompilerWork.run(GradleKotlinCompilerWork.kt:135)
      at         org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:152)
      at         org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runCompilerAsync(GradleKotlinCompilerRunner.kt:147)
      at         org.jetbrains.kotlin.compilerRunner.GradleCompilerRunner.runJvmCompilerAsync(GradleKotlinCompilerRunner.kt:87)
      at         org.jetbrains.kotlin.gradle.internal.KaptWithKotlincTask.compile(KaptWithKotlincTask.kt:72)..34 more

Body:
I also had this same error run clean build, invalidate caches or try run with

gradlew assembleDebug

This will show you where is the problem in you app.


问:
How can I specify type constraint to have same arguments in two predicates?
I want to create generic event handler function for some custom made events.

Events looks like Event<T extends Function> and have addListener and removeListener method. And then used like this: type MyEvent = Event<(a1: string, a2: number) => void>.

My goal is create a function that takes two arguments: such event and predicate with same arguments with event handler. For example for one argument:

```<code>export function myFunction<A1>(
    event: Event<(a1: A1) => void>,
    predicate: (a1: A1) => boolean): Promise<void> {

}
</code>```

How can I make this function more generic, to be able to handle more than one argument?

答:
You can use tuples in rest parameters to do this:</p>

```<code>export function myFunction<A extends any[]>(
    event: Event<(...a: A) => void>, // A will be a tuple of parameter types inferred from here
    predicate: (...a: A) => boolean): Promise<void>{
    return Promise.resolve();
}

declare let e: Event<(v: string, n: number) => void>;

myFunction(e, (v, n) => v.length > 0 && n > 0); // v, n typed correctly
myFunction(e, (v) => v.length > 0); // fewer args allowed as usually in TS
myFunction(e, (v, n, z) => v.length > 0); // error here
</code>```

Body:
I want to create generic event handler function for some custom made events.

Events looks like Event<T extends Function> and have addListener and removeListener method. And then used like this: type MyEvent = Event<(a1: string, a2: number) => void>.

My goal is create a function that takes two arguments: such event and predicate with same arguments with event handler. For example for one argument:

export function myFunction<A1>(
    event: Event<(a1: A1) => void>,
    predicate: (a1: A1) => boolean): Promise<void> {

}

How can I make this function more generic, to be able to handle more than one argument?

Body:
You can use tuples in rest parameters to do this:

export function myFunction<A extends any[]>(
    event: Event<(...a: A) => void>, // A will be a tuple of parameter types inferred from here
    predicate: (...a: A) => boolean): Promise<void>{
    return Promise.resolve();
}

declare let e: Event<(v: string, n: number) => void>;

myFunction(e, (v, n) => v.length > 0 && n > 0); // v, n typed correctly
myFunction(e, (v) => v.length > 0); // fewer args allowed as usually in TS
myFunction(e, (v, n, z) => v.length > 0); // error here


问:
How to convert HTML into formatted Text so that the layout such as spacing, table borders, element positioning remains intact?
How to convert HTML into formatted Text, so that the layout such as spacing, table borders, element positioning remains intact? Is there any tool for the same?

Tried a few options already as follows but output formatting is not as desired:

TxtControl conversion

PythonCom conversion

Issue: Converting HTML table with spacing between cells resulting in cell content getting moved to next line hence disturbing the formatting.
Expected output is: Table row cell content shall be in the same line and border shall be intact in the text file.

Also, PDF/RTF to TEXT conversion will also work just formatting should be intact.

Attaching screenshots for more clarity on the requirement.
INPUT HTML SCREENSHOT

OUTPUT TEXT SCREENSHOT

Alternatively, is there any way to read HTML character by character and write into text file so that the layout does not change in text output.

答:
Does this work?

You can convert HTML into BBCode and you have a RTF editor.

http://www.ecardmax.com/hoteditor/

Just make sure to check the HTML Checkbox so that you can insert HTML into that. So when you paste your text, you choose the HTML part, you should try both.

Here are the results of the post from yours in BBCode

Note that that is my edited version:

```<code>How to [B]convert[/B] HTML into formatted Text, so that the layout such as spacing, table borders, element positioning remains intact? Is there any tool for the same?
Tried a few options already as follows but output formatting is not as desired:
[LIST=1]
[*]TxtControl conversion
[*]PythonCom conversion[/LIST]
[B]Issue:[/B] Converting HTML table with spacing between cells resulting in cell content getting moved to next line hence disturbing the formatting.Expected output is : Table row cell content shall be in same line and border shall be intact in text file.
Also, PDF/RTF to TEXT conversion will also work just formatting should be intact.
</code>```

It could be that you manually need to remove something from it, as example I had to remove the text called "Thanks for your edit!" that appears when you edit something and it's still in pending.

This is useful if you want to convert old posts you can't access anymore on XenForo.

You then could put it into a text replacer, where it could replace [B] into **

Body:
Does this work?

You can convert HTML into BBCode and you have a RTF editor.

http://www.ecardmax.com/hoteditor/

Just make sure to check the HTML Checkbox so that you can insert HTML into that. So when you paste your text, you choose the HTML part, you should try both.

Here are the results of the post from yours in BBCode

Note that that is my edited version:

How to [B]convert[/B] HTML into formatted Text, so that the layout such as spacing, table borders, element positioning remains intact? Is there any tool for the same?
Tried a few options already as follows but output formatting is not as desired:
[LIST=1]
[*]TxtControl conversion
[*]PythonCom conversion[/LIST]
[B]Issue:[/B] Converting HTML table with spacing between cells resulting in cell content getting moved to next line hence disturbing the formatting.Expected output is : Table row cell content shall be in same line and border shall be intact in text file.
Also, PDF/RTF to TEXT conversion will also work just formatting should be intact.

It could be that you manually need to remove something from it, as example I had to remove the text called "Thanks for your edit!" that appears when you edit something and it's still in pending.

This is useful if you want to convert old posts you can't access anymore on XenForo.

You then could put it into a text replacer, where it could replace [B] into **


问:
ExtJS with a .NET backend
What's my best option (using the latest in the .NET framework) for creating a webapp with with a complete ExtJS frontend (all server interaction happens through AJAX with XML or JSON)? Are there any problems with using WCF? The following (fake, but funny) O'Reilly book cover seems to imply so.

http://www.oreillymaker.com/link/14746/extjswcf/

答: have you seen http://www.coolite.com/?</p>

OwnerDisplayName: Abdullah Jibaly

ContentLicense: CC BY-SA 2.5

Title: ExtJS with a .NET backend

Body: have you seen http://www.coolite.com/?

OwnerDisplayName: Causas


问:
Does not exist in current context error, but it should - ASP.NET c#
Here is the code:

```<code>for (int i = 0; i < Model.Count; i++)
{
    Writer.WriteBeginTag("li");
    if (i % 2 == 1)
    {
            string myVar  = "even ";
    }
    if ((i+1) % 3 == 0)
    {
        myVar += "third";
    }
    Writer.WriteAttribute("class", ""); // I want to use myVar here
    Writer.Write(HtmlTextWriter.TagRightChar);
    Writer.WriteEndTag("li");
}
</code>```

I'm not all that familiar with .NET or C#. I get an error The name "myVar" does not exist in the current context on the second myVar. If I comment this line out, I then have a message The variable "myVar" is assigned but its value is never used. on the first myVar. I don't really understand how or why this would be out of context/scope.

Any ideas?

答:
myVar only exists inside your if.

You need to move the declaration to the body of the loop.

Body:
Here is the code:

for (int i = 0; i < Model.Count; i++)
{
    Writer.WriteBeginTag("li");
    if (i % 2 == 1)
    {
            string myVar  = "even ";
    }
    if ((i+1) % 3 == 0)
    {
        myVar += "third";
    }
    Writer.WriteAttribute("class", ""); // I want to use myVar here
    Writer.Write(HtmlTextWriter.TagRightChar);
    Writer.WriteEndTag("li");
}

I'm not all that familiar with .NET or C#. I get an error The name "myVar" does not exist in the current context on the second myVar. If I comment this line out, I then have a message The variable "myVar" is assigned but its value is never used. on the first myVar. I don't really understand how or why this would be out of context/scope.

Any ideas?


问:
Is there a way to read many files and save the values of the array or list in c#?
I try to read the data of all files through a loop, but there is a problem with starting the program ?

Meteorological reference

```<code>        string filePath = @"C:\Meteo\*.dat";

        List<string> lines =  File.ReadAllLines(filePath).ToList();

        foreach (string line in lines)
        {
            MessageBox.Show(line);
        }
</code>```

The output is:

```<code>************** Exception Text **************
System.ArgumentException: Illegal characters in path.
   at System.Security.Permissions.FileIOPermission.EmulateFileIOPermissionChecks(String fullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
   at System.IO.StreamReader..ctor(String path, Encoding encoding)
   at System.IO.File.InternalReadAllLines(String path, Encoding encoding)
   at System.IO.File.ReadAllLines(String path)
   at WindowsFormsApp1.frm_main.frm_main_Load(Object sender, EventArgs e) in C:\Users\admin\Desktop\WindowsFormsApp1\WindowsFormsApp1\WindowsFormsApp1\frm_main.cs:line 103
   at System.Windows.Forms.Form.OnLoad(EventArgs e)
   at System.Windows.Forms.Form.OnCreateControl()
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl()
   at System.Windows.Forms.Control.WmShowWindow(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   at System.Windows.Forms.Form.WmShowWindow(Message& m)
   at System.Windows.Forms.Form.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
</code>```

The files look like this:.dat file

答:
You should enumerate files:

```<code>var files = Directory.EnumerateFiles(@"C:\Meteo", "*.dat");
</code>```

Then you can use SelectMany if you want to glue the files' lines together:

```<code>// all lines of all *.dat files in the single list
List<string> lines = Directory
  .EnumerateFiles(@"C:\Meteo", "*.dat")
  .SelectMany(file => File.ReadLines(file))
  .ToList();
</code>```

Or you can process each file in a loop:

```<code>foreach (string file in Directory.EnumerateFiles(@"C:\Meteo", "*.dat")) {
  //TODO: process the file here
}
</code>```

Edit: Let's process each file in a loop (see comments below)

```<code>// for each file
foreach (string file in Directory.EnumerateFiles(@"C:\Meteo", "*.dat")) {
  // read each line
  foreach (string line in File.ReadLines(file)) {
    // and show file name and line in a message box
    MessageBox.Show(line, file);
  }
}
</code>```

Body:
I try to read the data of all files through a loop, but there is a problem with starting the program ?

Meteorological reference

        string filePath = @"C:\Meteo\*.dat";

        List<string> lines =  File.ReadAllLines(filePath).ToList();

        foreach (string line in lines)
        {
            MessageBox.Show(line);
        }

The output is:

************** Exception Text **************
System.ArgumentException: Illegal characters in path.
   at System.Security.Permissions.FileIOPermission.EmulateFileIOPermissionChecks(String fullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
   at System.IO.StreamReader..ctor(String path, Encoding encoding)
   at System.IO.File.InternalReadAllLines(String path, Encoding encoding)
   at System.IO.File.ReadAllLines(String path)
   at WindowsFormsApp1.frm_main.frm_main_Load(Object sender, EventArgs e) in C:\Users\admin\Desktop\WindowsFormsApp1\WindowsFormsApp1\WindowsFormsApp1\frm_main.cs:line 103
   at System.Windows.Forms.Form.OnLoad(EventArgs e)
   at System.Windows.Forms.Form.OnCreateControl()
   at System.Windows.Forms.Control.CreateControl(Boolean fIgnoreVisible)
   at System.Windows.Forms.Control.CreateControl()
   at System.Windows.Forms.Control.WmShowWindow(Message& m)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.ScrollableControl.WndProc(Message& m)
   at System.Windows.Forms.Form.WmShowWindow(Message& m)
   at System.Windows.Forms.Form.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

The files look like this:.dat file

Body:
You should enumerate files:

var files = Directory.EnumerateFiles(@"C:\Meteo", "*.dat");

Then you can use SelectMany if you want to glue the files' lines together:

// all lines of all *.dat files in the single list
List<string> lines = Directory
  .EnumerateFiles(@"C:\Meteo", "*.dat")
  .SelectMany(file => File.ReadLines(file))
  .ToList();

Or you can process each file in a loop:

foreach (string file in Directory.EnumerateFiles(@"C:\Meteo", "*.dat")) {
  //TODO: process the file here
}

Edit: Let's process each file in a loop (see comments below)

// for each file
foreach (string file in Directory.EnumerateFiles(@"C:\Meteo", "*.dat")) {
  // read each line
  foreach (string line in File.ReadLines(file)) {
    // and show file name and line in a message box
    MessageBox.Show(line, file);
  }
}


问:
How to lock the result of the output cell, once it meets a criteria, from subsequent value change in the input cell in Google Sheets?
I'm looking to solve this situation:

Depending on the value —variable in time— in B1 (input cell), print a specific "status" in the output cell (D1).

With 3 possible status:

1st: "VALID"

2nd: "PENDING"

3rd: "APPROVED"

with the 3 main properties:

A1 = value fixed (doesn't change in time)

B1 = value changing in time

C1 = string "APPROVED" (to be inputted manually)

D1 = output cell

Following this formula:

```<code>=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")
</code>```

What I'm trying to do is:

As soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status), have the D1 cell status "PENDING" locked to "PENDING".
I.e. not reverting to "VALID" if/when B1<=A1 changes back to B1>A1.

Additionally, only unlocking the "PENDING" status to the "APPROVED" status if the condition for the Status "APPROVED" (len(C1)-manually inputting the string "APPROVED" into C1) is met subsequently.

Here a simple example of expected result:

At T1 (say, May 27 2019, 12:15pm):

B1>A1 -> Status= VALID

A1 = 1.2 (in A1, fixed number)

B1 = 1.5 (in B1, number variable in time)

C1 = (empty cell)

D1 = VALID

At T2 (say, May 27 2019, 1:15pm):

B1<=A1 -> Status= PENDING

A1 = 1.2 (say May 27 2019, 12:15pm)

B1 = 1.2 (or 1.1) (in B1, number variable in time)

C1 =  (empty cell)

D1 = PENDING

At T3 (say, May 27 2019, 2:15pm):

B1>A1 -> Status= PENDING (no revert back to VALID despite B1 reverting to B1>A1)

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 (in B1, number variable in time)

C1 = (empty cell)

D1 = PENDING

At T4 (say, May 27 2019, 3:15pm):

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 or 1.1 (in B1, number variable in time)

D1 = APPROVED (because of manual input of any character into C1)

C1 = (any lenght of character into C1)

(User manually input any character/string into C1 -> Status= APPROVED (because of len(C1), the PENDING Status gets unlocked to APPROVED status)

At T3 is the issue I'm currently facing.

With this formula:

```<code>=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")
</code>```

The "PENDING" status (gained from T2) reverts back to "VALID"

How can one lock the "PENDING" status as soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status)?

Then unlock the "PENDING" status when the "APPROVED" string is manually typed into D1?

New question:
Can we color and bold code the status as well?

For example:

Cells A22 to A25 in the sheet below.

Sheet here:

https://docs.google.com/spreadsheets/d/1UjjMnLmNbEDUfXjeCIOgBZwYqTeXdm_t_4N45OL0k6I/edit#gid=0

Thanks a lot for your help!

答:
Finally got it sorted!

It was a matter of order of precedence of operations similar to the IFS function mode of operations:

1st operation statement:

The 1st If statement regarding the "APPROVED" status as 1st instruction to the machine.

2nd operation statement:

(To which the machine continues computing If 1st is FALSE)

Proceed to the "PENDING" status IF statement (regular) as 2nd operation instruction to the machine.

3rd operation instruction:

(To which the machine continues computing If 1st is (still) FALSE and the 2nd statement is (still) TRUE)

Proceed to locking the ""PENDING" status in cell D1, if Cell D1 contains the string "PENDING" (inherited from 2nd operation statement found as TRUE before) (statusCell = "PENDING" —> D1 = "PENDING")

4th operation statement:

(To which the machine continues computing If neither 1st, 2nd/3rd operations statements are TRUE)

Proceed to the "VALID" status IF statement as 4th/3rd operation instruction to the machine.

Machine reasoning mode:

The machine must thus proceed to perform its operations in a backward fashion comparing to usual human thinking: 1st APPROVED, then PENDING, Then Lock PENDING, and finally VALID.

Edit (Jun 9th 2019):

I corrected some minor errors in the script:

[LOCKVALUECOLORBOLDWORDS for LOCKVALUE&COLOR&BOLDWORDS, (statusCell == "PENDING") for (statusCell = "PENDING"), and the comment [1.] if the value of approveCell is not-blank..., for [1.] if the value of approveCell is blank...)].
(I must have forgotten somehow to save it before posting it).

Now it's working as expected.

Here the Sheet:

How to lock the result of the output cell, once it meets a criteria, from subsequent value change in the input cell in Google Sheets?

But for some reason, the function needs to execute twice after each edit to print the new status.

Video demo here:

https://youtu.be/DEI7RGRotcs

I'll see why it is so and look for how to figure out how to make it print after single execution.

New Script so far:

https://pastebin.com/gxK0bvcu

```<code>/**
* Locks the Status of a cell according to criteria and Colors and bolds the specific words of status
*
* @param arg3:  Colors "VALID" Status to orange, "PENDING" Status to green, and "APPROVED" to purple
*
* @customfunction
*/

function LOCKVALUECOLORBOLDWORDS(arg3) {

      var app = SpreadsheetApp;
      var activeSheet = app.getActiveSpreadsheet().getActiveSheet();

      //(read left to right) get the value from range A1:A1, from active sheet, and assign it the variable "fixedvalueCell"
      var fixedvalueCell = activeSheet.getRange(1, 1).getValue();

      //(read left to right) get the value from range B1:B1, from active sheet, and assign it the variable "changingvalueCell"
      var changingvalueCell = activeSheet.getRange(1, 2).getValue();

      //(read left to right) get the value from range C1:C1, from active sheet, and assign it the variable "approveCell"
      var approveCell = activeSheet.getRange(1, 3).getValue();

      //(read left to right) get the value from range D1:D1, from active sheet, and assign it the variable "statusCell"
      var statusCell = activeSheet.getRange(1, 4).getValue();

      //[1.] if the value of approveCell is not-blank, then set/print "APPROVED" into D1, and color it to purple, and bold it.
      if
        (approveCell !== "") {
        activeSheet.getRange(1, 4).setValue("APPROVED").setFontColor("#7F00FF").setFontWeight("bold");
      }

      //[2.] if the value of changingvalueCell is smaller or equal to the value of fixedvalueCell, then set/print "PENDING" into D1, and color it to green, and bold it.
        else if
        (changingvalueCell <= fixedvalueCell) {
        activeSheet.getRange(1, 4).setValue("PENDING").setFontColor("#7FFF00").setFontWeight("bold");
      }

      //[3.] if the value of statusCell is "PENDING", then set/print "PENDING" into D1, and color it to green, and bold it.
        else if
        (statusCell == "PENDING") {
        activeSheet.getRange(1, 4).setValue("PENDING").setFontColor("#7FFF00").setFontWeight("bold");
      }

      //[4.] if all [1.] and [2.] and [3.] IF statements are FALSE (for everything else), then set/print "VALID" into D1, and color it to orange, and bold it.
        else {
        activeSheet.getRange(1, 4).setValue("VALID").setFontColor("#FF6600").setFontWeight("bold");
      }

      var result = arg3;

      return result;

    }

</code>```

Body:
I'm looking to solve this situation:

Depending on the value —variable in time— in B1 (input cell), print a specific "status" in the output cell (D1).

With 3 possible status:

1st: "VALID"

2nd: "PENDING"

3rd: "APPROVED"

with the 3 main properties:

A1 = value fixed (doesn't change in time)

B1 = value changing in time

C1 = string "APPROVED" (to be inputted manually)

D1 = output cell

Following this formula:

=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")

What I'm trying to do is:

As soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status), have the D1 cell status "PENDING" locked to "PENDING".
I.e. not reverting to "VALID" if/when B1<=A1 changes back to B1>A1.

Additionally, only unlocking the "PENDING" status to the "APPROVED" status if the condition for the Status "APPROVED" (len(C1)-manually inputting the string "APPROVED" into C1) is met subsequently.

Here a simple example of expected result:

At T1 (say, May 27 2019, 12:15pm):

B1>A1 -> Status= VALID

A1 = 1.2 (in A1, fixed number)

B1 = 1.5 (in B1, number variable in time)

C1 = (empty cell)

D1 = VALID

At T2 (say, May 27 2019, 1:15pm):

B1<=A1 -> Status= PENDING

A1 = 1.2 (say May 27 2019, 12:15pm)

B1 = 1.2 (or 1.1) (in B1, number variable in time)

C1 =  (empty cell)

D1 = PENDING

At T3 (say, May 27 2019, 2:15pm):

B1>A1 -> Status= PENDING (no revert back to VALID despite B1 reverting to B1>A1)

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 (in B1, number variable in time)

C1 = (empty cell)

D1 = PENDING

At T4 (say, May 27 2019, 3:15pm):

A1 = 1.2 (in A1, fixed number)

B1 = 1.4 or 1.1 (in B1, number variable in time)

D1 = APPROVED (because of manual input of any character into C1)

C1 = (any lenght of character into C1)

(User manually input any character/string into C1 -> Status= APPROVED (because of len(C1), the PENDING Status gets unlocked to APPROVED status)

At T3 is the issue I'm currently facing.

With this formula:

=IFS(len(C1),"APPROVED",B1>A1,"VALID",B1<=A1,"PENDING",TRUE,"ERROR")

The "PENDING" status (gained from T2) reverts back to "VALID"

How can one lock the "PENDING" status as soon as B1>A1 ("VALID" status) changes to B1<=A1 ("PENDING" status)?

Then unlock the "PENDING" status when the "APPROVED" string is manually typed into D1?

New question:
Can we color and bold code the status as well?

For example:

Cells A22 to A25 in the sheet below.

Sheet here:

https://docs.google.com/spreadsheets/d/1UjjMnLmNbEDUfXjeCIOgBZwYqTeXdm_t_4N45OL0k6I/edit#gid=0

Thanks a lot for your help!

Body:
Finally got it sorted!

It was a matter of order of precedence of operations similar to the IFS function mode of operations:

1st operation statement:

The 1st If statement regarding the "APPROVED" status as 1st instruction to the machine.

2nd operation statement:

(To which the machine continues computing If 1st is FALSE)

Proceed to the "PENDING" status IF statement (regular) as 2nd operation instruction to the machine.

3rd operation instruction:

(To which the machine continues computing If 1st is (still) FALSE and the 2nd statement is (still) TRUE)

Proceed to locking the ""PENDING" status in cell D1, if Cell D1 contains the string "PENDING" (inherited from 2nd operation statement found as TRUE before) (statusCell = "PENDING" —> D1 = "PENDING")

4th operation statement:

(To which the machine continues computing If neither 1st, 2nd/3rd operations statements are TRUE)

Proceed to the "VALID" status IF statement as 4th/3rd operation instruction to the machine.

Machine reasoning mode:

The machine must thus proceed to perform its operations in a backward fashion comparing to usual human thinking: 1st APPROVED, then PENDING, Then Lock PENDING, and finally VALID.

Edit (Jun 9th 2019):

I corrected some minor errors in the script:

[LOCKVALUECOLORBOLDWORDS for LOCKVALUE&COLOR&BOLDWORDS, (statusCell == "PENDING") for (statusCell = "PENDING"), and the comment [1.] if the value of approveCell is not-blank..., for [1.] if the value of approveCell is blank...)].
(I must have forgotten somehow to save it before posting it).

Now it's working as expected.

Here the Sheet:

How to lock the result of the output cell, once it meets a criteria, from subsequent value change in the input cell in Google Sheets?

But for some reason, the function needs to execute twice after each edit to print the new status.

Video demo here:

https://youtu.be/DEI7RGRotcs

I'll see why it is so and look for how to figure out how to make it print after single execution.

New Script so far:

https://pastebin.com/gxK0bvcu

/**
* Locks the Status of a cell according to criteria and Colors and bolds the specific words of status
*
* @param arg3:  Colors "VALID" Status to orange, "PENDING" Status to green, and "APPROVED" to purple
*
* @customfunction
*/

function LOCKVALUECOLORBOLDWORDS(arg3) {

      var app = SpreadsheetApp;
      var activeSheet = app.getActiveSpreadsheet().getActiveSheet();

      //(read left to right) get the value from range A1:A1, from active sheet, and assign it the variable "fixedvalueCell"
      var fixedvalueCell = activeSheet.getRange(1, 1).getValue();

      //(read left to right) get the value from range B1:B1, from active sheet, and assign it the variable "changingvalueCell"
      var changingvalueCell = activeSheet.getRange(1, 2).getValue();

      //(read left to right) get the value from range C1:C1, from active sheet, and assign it the variable "approveCell"
      var approveCell = activeSheet.getRange(1, 3).getValue();

      //(read left to right) get the value from range D1:D1, from active sheet, and assign it the variable "statusCell"
      var statusCell = activeSheet.getRange(1, 4).getValue();

      //[1.] if the value of approveCell is not-blank, then set/print "APPROVED" into D1, and color it to purple, and bold it.
      if
        (approveCell !== "") {
        activeSheet.getRange(1, 4).setValue("APPROVED").setFontColor("#7F00FF").setFontWeight("bold");
      }

      //[2.] if the value of changingvalueCell is smaller or equal to the value of fixedvalueCell, then set/print "PENDING" into D1, and color it to green, and bold it.
        else if
        (changingvalueCell <= fixedvalueCell) {
        activeSheet.getRange(1, 4).setValue("PENDING").setFontColor("#7FFF00").setFontWeight("bold");
      }

      //[3.] if the value of statusCell is "PENDING", then set/print "PENDING" into D1, and color it to green, and bold it.
        else if
        (statusCell == "PENDING") {
        activeSheet.getRange(1, 4).setValue("PENDING").setFontColor("#7FFF00").setFontWeight("bold");
      }

      //[4.] if all [1.] and [2.] and [3.] IF statements are FALSE (for everything else), then set/print "VALID" into D1, and color it to orange, and bold it.
        else {
        activeSheet.getRange(1, 4).setValue("VALID").setFontColor("#FF6600").setFontWeight("bold");
      }

      var result = arg3;

      return result;

    }


问:
Foreground does not apply for labels
I have some labels like this:

```<code> <Label x:Name="ledCalculate" Width="Auto" Content="Calculate" Height="25" FontFamily="Cambria" FontSize="18.667" VerticalContentAlignment="Bottom" Padding="10,0,0,0"  BorderThickness="0,0,0,1" Style="{StaticResource RightPanelLabels}" Grid.Row="11"/>
</code>```

I defined a style for it:

```<code> <Style TargetType="Label" x:Key="RightPanelLabels" BasedOn="{StaticResource
    {x:Type Label } }">

        <Setter Property="Foreground" Value="#FFEABEBE"></Setter>
        <Setter Property="BorderBrush" Value="#FF818080"></Setter>
        <Setter Property="BorderThickness" Value="0,0,0,1"></Setter>
    </Style>
</code>```

Border thickness setter in style applies for control and it has upper precedence in style, and visual studio ignores its values in local, but  foreground setter in style does not applies, when i set it locally it applies,

Why border thickness in style have upper precedence but foreground in local have upper precedence????????

I know there is a default template for labels like bellow that have a trigger for IsEnabled , that template is something like this:

```<code><ControlTemplate TargetType="{x:Type Label}">
    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">
        <ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
        </Trigger>
    </ControlTemplate.Triggers>
 </ControlTemplate>
</code>```

Can anyone help me?
Sorry for my English.

答:
All the local styles take precedence over defined styles, so inline styles will always override other styles defined in resources.
When I run the code I found that Style's BorderThickness also get overridden by the local inline style value for BorderThickness as well.

I too would love to hear if there's a workaround for this.
I found this article as well, hope it helps Same problem with a style trigger though

EDIT:

Upon trying it few different ways I found using this method we can override the label's inline Foreground style, but I don't know whether it's the healthiest way

```<code><Style TargetType="{x:Type Label}">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBlock Text="{Binding}"
                           Foreground="Red" />
                    </DataTemplate>
                </Setter.Value>
            </Setter>
  </Style>

 <Label FontSize="50" Foreground="Black"> I am Black inline, Red on Style </Label>
</code>```

This is me just editing the ContentTemplate of the Label .
Basically, this possible for Label because Label derives from ContentControl whereas TextBlock lives in the System.Windows.Controls namespace, it is not a control. It derives directly from FrameworkElement.
TextBlock are used in many other controls to show texts, including in Label.

Refer this article to know more about this

Title: Foreground does not apply for labels

Body:
I have some labels like this:

I defined a style for it:

Border thickness setter in style applies for control and it has upper precedence in style, and visual studio ignores its values in local, but  foreground setter in style does not applies, when i set it locally it applies,

Why border thickness in style have upper precedence but foreground in local have upper precedence????????

I know there is a default template for labels like bellow that have a trigger for IsEnabled , that template is something like this:

<ControlTemplate TargetType="{x:Type Label}">
    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="True">
        <ContentPresenter ContentTemplate="{TemplateBinding ContentTemplate}" Content="{TemplateBinding Content}" ContentStringFormat="{TemplateBinding ContentStringFormat}" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    </Border>
    <ControlTemplate.Triggers>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
        </Trigger>
    </ControlTemplate.Triggers>
 </ControlTemplate>

Can anyone help me?
Sorry for my English.

Body:
All the local styles take precedence over defined styles, so inline styles will always override other styles defined in resources.
When I run the code I found that Style's BorderThickness also get overridden by the local inline style value for BorderThickness as well.

I too would love to hear if there's a workaround for this.
I found this article as well, hope it helps Same problem with a style trigger though

EDIT:

Upon trying it few different ways I found using this method we can override the label's inline Foreground style, but I don't know whether it's the healthiest way

<Style TargetType="{x:Type Label}">
            <Setter Property="ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBlock Text="{Binding}"
                           Foreground="Red" />
                    </DataTemplate>
                </Setter.Value>
            </Setter>
  </Style>

 <Label FontSize="50" Foreground="Black"> I am Black inline, Red on Style </Label>

This is me just editing the ContentTemplate of the Label .
Basically, this possible for Label because Label derives from ContentControl whereas TextBlock lives in the System.Windows.Controls namespace, it is not a control. It derives directly from FrameworkElement.
TextBlock are used in many other controls to show texts, including in Label.

Refer this article to know more about this


问:
Strange difference between Integer variable and Array variable
```<code>a = 1
def bla x
 x = x + 1
end

bla a # =>2 when I use bla to add 1, it return 2

a # => 1 but it get back to the original value

a = [1]
</code>```

but Array

```<code>def bla x
 x << 1
end

bla a # => [1,1]

a # =>[1,1] stay in the new value
</code>```

Could Anybody tell me why it is?

答: '<<' operator always append value to existing variable(by reference) but others does not.</p>

Body:
a = 1
def bla x
 x = x + 1
end

bla a # =>2 when I use bla to add 1, it return 2

a # => 1 but it get back to the original value

a = [1]

but Array

def bla x
 x << 1
end

bla a # => [1,1]

a # =>[1,1] stay in the new value

Could Anybody tell me why it is?


问:
Actix-Web reports "App data is not configured" when processing a file upload
I'm using the Actix framework to create a simple server and I've implemented a file upload using a simple HTML frontend.

```<code>use actix_web::web::Data;
use actix_web::{middleware, web, App, HttpResponse, HttpServer};
use std::cell::Cell;

// file upload functions, the same as you can find it under the
// actix web documentation:
// https://github.com/actix/examples/blob/master/multipart/src/main.rs :
mod upload;

fn index() -> HttpResponse {
    let html = r#"<html>
            <head><title>Upload Test</title></head>
            <body>
                <form target="/" method="post" enctype="multipart/form-data">
                    <input type="file" name="file"/>
                    <input type="submit" value="Submit"></button>
                </form>
            </body>
        </html>"#;

    HttpResponse::Ok().body(html)
}

#[derive(Clone)]
pub struct AppState {
    counter: Cell<usize>,
}

impl AppState {
    fn new() -> Result<Self, Error> {
        // some stuff
        Ok(AppState {
            counter: Cell::new(0usize),
        })
    }
}
fn main() {

    let app_state = AppState::new().unwrap();

    println!("Started http server: http://127.0.0.1:8000");

    HttpServer::new(move || {
        App::new()
            .wrap(middleware::Logger::default())
            .service(
                web::resource("/")
                    .route(web::get().to(index))
                    .route(web::post().to_async(upload::upload)),
            )
            .data(app_state.clone())
    })
    .bind("127.0.0.1:8000")
    .unwrap()
    .run()
    .unwrap();
}
</code>```

Running the server works fine, but when I submit the file upload, it says:

App data is not configured, to configure use App::data()

I don't know what to do.

答:
I asked people in the rust-jp community to tell you the correct answer.

Use Arc outer HttpServer.

```<code>/*
~~~Cargo.toml
[package]
name = "actix-data-example"
version = "0.1.0"
authors = ["ncaq <ncaq@ncaq.net>"]
edition = "2018"

[dependencies]
actix-web = "1.0.0-rc"
env_logger = "0.6.0"
~~~
 */

use actix_web::*;
use std::sync::*;

fn main() -> std::io::Result<()> {
    std::env::set_var("RUST_LOG", "actix_web=trace");
    env_logger::init();

    let data = Arc::new(Mutex::new(ActixData::default()));
    HttpServer::new(move || {
        App::new()
            .wrap(middleware::Logger::default())
            .data(data.clone())
            .service(web::resource("/index/").route(web::get().to(index)))
            .service(web::resource("/create/").route(web::get().to(create)))
    })
    .bind("0.0.0.0:3000")?
    .run()
}

fn index(actix_data: web::Data<Arc<Mutex<ActixData>>>) -> HttpResponse {
    println!("actix_data: {:?}", actix_data);
    HttpResponse::Ok().body(format!("{:?}", actix_data))
}

fn create(actix_data: web::Data<Arc<Mutex<ActixData>>>) -> HttpResponse {
    println!("actix_data: {:?}", actix_data);
    actix_data.lock().unwrap().counter += 1;
    HttpResponse::Ok().body(format!("{:?}", actix_data))
}

/// actix-webが保持する状態
#[derive(Debug, Default)]
struct ActixData {
    counter: usize,
}
</code>```

This post report to upstream.
Official document data cause App data is not configured, to configure use App::data() · Issue #874 · actix/actix-web

Body:
I'm using the Actix framework to create a simple server and I've implemented a file upload using a simple HTML frontend.

use actix_web::web::Data;
use actix_web::{middleware, web, App, HttpResponse, HttpServer};
use std::cell::Cell;

// file upload functions, the same as you can find it under the
// actix web documentation:
// https://github.com/actix/examples/blob/master/multipart/src/main.rs :
mod upload;

fn index() -> HttpResponse {
    let html = r#"
            <title>Upload Test</title>

                <form target="/" method="post" enctype="multipart/form-data">
                    <input type="file" name="file"/>
                    <input type="submit" value="Submit"></button>
                </form>

        "#;

    HttpResponse::Ok().body(html)
}

#[derive(Clone)]
pub struct AppState {
    counter: Cell<usize>,
}

impl AppState {
    fn new() -> Result<Self, Error> {
        // some stuff
        Ok(AppState {
            counter: Cell::new(0usize),
        })
    }
}
fn main() {

    let app_state = AppState::new().unwrap();

    println!("Started http server: http://127.0.0.1:8000");

    HttpServer::new(move || {
        App::new()
            .wrap(middleware::Logger::default())
            .service(
                web::resource("/")
                    .route(web::get().to(index))
                    .route(web::post().to_async(upload::upload)),
            )
            .data(app_state.clone())
    })
    .bind("127.0.0.1:8000")
    .unwrap()
    .run()
    .unwrap();
}

Running the server works fine, but when I submit the file upload, it says:

App data is not configured, to configure use App::data()

I don't know what to do.

Body:
I asked people in the rust-jp community to tell you the correct answer.

Use Arc outer HttpServer.

/*
~~~Cargo.toml
[package]
name = "actix-data-example"
version = "0.1.0"
authors = ["ncaq <ncaq@ncaq.net>"]
edition = "2018"

[dependencies]
actix-web = "1.0.0-rc"
env_logger = "0.6.0"
~~~
 */

use actix_web::*;
use std::sync::*;

fn main() -> std::io::Result<()> {
    std::env::set_var("RUST_LOG", "actix_web=trace");
    env_logger::init();

    let data = Arc::new(Mutex::new(ActixData::default()));
    HttpServer::new(move || {
        App::new()
            .wrap(middleware::Logger::default())
            .data(data.clone())
            .service(web::resource("/index/").route(web::get().to(index)))
            .service(web::resource("/create/").route(web::get().to(create)))
    })
    .bind("0.0.0.0:3000")?
    .run()
}

fn index(actix_data: web::Data<Arc<Mutex<ActixData>>>) -> HttpResponse {
    println!("actix_data: {:?}", actix_data);
    HttpResponse::Ok().body(format!("{:?}", actix_data))
}

fn create(actix_data: web::Data<Arc<Mutex<ActixData>>>) -> HttpResponse {
    println!("actix_data: {:?}", actix_data);
    actix_data.lock().unwrap().counter += 1;
    HttpResponse::Ok().body(format!("{:?}", actix_data))
}

/// actix-webが保持する状態
#[derive(Debug, Default)]
struct ActixData {
    counter: usize,
}

This post report to upstream.
Official document data cause App data is not configured, to configure use App::data() · Issue #874 · actix/actix-web


问:
Unresolved external symbol bcrypt_gensalt
I have one problem with library <bcrypt.h>. Compiler say error with function bcrypt_gensalt.

```<code>#include <iostream>
#include <bcrypt.h>

using namespace std;

int main() {

    const char* passwd = "Secret_Password";

    char results[BCRYPT_HASHSIZE];

    bcrypt_gensalt(10, results);

    system("pause");
    return 0;
}
</code>```

Error from compiler:

```<code>unresolved external symbol bcrypt_gensalt referenced in function main
</code>```

答:
You need to reference Bcrypt.lib.

See here: http://msdn.microsoft.com/en-us/library/ba1z7822.aspx.

Body:
I have one problem with library <bcrypt.h>. Compiler say error with function bcrypt_gensalt.

#include <iostream>
#include <bcrypt.h>

using namespace std;

int main() {

    const char* passwd = "Secret_Password";

    char results[BCRYPT_HASHSIZE];

    bcrypt_gensalt(10, results);

    system("pause");
    return 0;
}

Error from compiler:

unresolved external symbol bcrypt_gensalt referenced in function main


问:
Query-string encoding of a JavaScript object
Is there a fast and simple way to encode a JavaScript object into a string that I can pass via a GET request?

No jQuery, no other frameworks—just plain JavaScript :)

答:
```<code>const serialize = obj => Object.keys(obj).reduce((a, b) =>
    a.push(encodeURIComponent(b) + "=" + encodeURIComponent(obj[b])) && a,
    []).join("&");
</code>```

Call:

```<code>console.log(serialize({a:1,b:2}));
// output: 'a=1&b=2
</code>```

'

Body:
const serialize = obj => Object.keys(obj).reduce((a, b) =>
    a.push(encodeURIComponent(b) + "=" + encodeURIComponent(obj[b])) && a,
    []).join("&");

Call:

console.log(serialize({a:1,b:2}));
// output: 'a=1&b=2

'


问:
problem facing with android application on two different android platform O.S. device
I have build one android application in androids version(2.2) and i have specified minimum sdk version in android manifest file as 3 i.e (version-1.5) .so i have to make sure that this application should run successfully on api leval of device having from 3 i.e Version(1.5) to 8 Version(2.2but since contact content provider for android Api platform "leval(4)" and "leval(8)" are different,and in my application i am using contact content provider,i am facing exceptions as "illegal argument","null pointer","uncought exception" at runtime.

On the other side if i build the application with version(1.6),It not gives runtime exception but when i tried to get contact details from device e.g(phone number,email),it gives null value as "null pointer" exception.

do you have any proper solution for this.please replay..

答: The attribute android:minSdk does not guarantee that your application will run on these devices (see here).</p>


问:
Jenkins Git integration - How to disable SSL certificate validation
I am getting the below error while creating a job from Jenkins. How do I disable certificate validation in Jenkins?

From Git Bash I can use git config --global http.sslVerify false command to disable it, but not sure how to use it from Jenkins.

Error:

```<code>Failed to connect to repository : Command "C:\Program Files (x86)\Git\cmd\git.exe ls-remote -h url ofmy repository.git HEAD" returned status code 128:
stdout:
stderr: fatal: unable to access 'url of my git/': SSL certificate problem: self signed certificate in certificate chain
</code>```

答:
Login or switch to  jenkins user; for switching run this command on terminal:

```<code>su - jenkins
</code>```

And then run

```<code>git config --global http.sslVerify false
</code>```

Body:
I am getting the below error while creating a job from Jenkins. How do I disable certificate validation in Jenkins?

From Git Bash I can use git config --global http.sslVerify false command to disable it, but not sure how to use it from Jenkins.

Error:

Failed to connect to repository : Command "C:\Program Files (x86)\Git\cmd\git.exe ls-remote -h url ofmy repository.git HEAD" returned status code 128:
stdout:
stderr: fatal: unable to access 'url of my git/': SSL certificate problem: self signed certificate in certificate chain

Body:
Login or switch to  jenkins user; for switching run this command on terminal:

su - jenkins

And then run

git config --global http.sslVerify false


问:
How to use setTimeout in a Vue.js method?
How can I use the setTimeout() function in a Vue.js method?

I have already tried something like this, but it doesn't work:

```<code>fetchHole: function () {
    //get data
},

addHole: function () {
    //my query add new
    setTimeout(function () { this.fetchHole() }, 1000)
},
</code>```

I get this error message: Uncaught TypeError: this.fetchHole is not a function

答:
You can try :

addHole:function(){
  let vm = this
  setTimeout(function(){vm.fetchHole()}, 1000)
}```

Body:
How can I use the setTimeout() function in a Vue.js method?

I have already tried something like this, but it doesn't work:

fetchHole: function () {
    //get data
},

addHole: function () {
    //my query add new
    setTimeout(function () { this.fetchHole() }, 1000)
},

I get this error message: Uncaught TypeError: this.fetchHole is not a function


问:
Updating database with real-time windowed aggregations
I have a streaming pipeline that consumes a streaming source (Kafka) and will write to a CloudSQL database. The goal is to keep the CloudSQL database updated in real-time with a Key/Value sum aggregation of records received in the past hour.

eg. In the last hour 3 records with KV <001,3>,<001,4>,<001,2> were recieved, database should have a record 001, 9. Records older than an hour aren't included.

My current solution a SlidingWindow into a GroupByKey after the KafkaIO.read:

```<code>                    .apply(Window.into(SlidingWindows
                                .of(Duration.standardSeconds(3600))
                                  .every(Duration.standardSeconds(20)))
                    ).apply(GroupByKey.create())
</code>```

Followed by a ParDo that sums each key, and then update the SQL database.

The result is that every 20 seconds my CloudSQL db is updated with the aggregation of each key of the last hour, which meets the functional requirements. The issue is the amount of upserts to CloudSQL this causes: most of the KV outputs are identical to the previous window, so each window every 20s triggers an hours worth of transactions (~500k).

It would make sense to trigger each KV output only when a record with that key is consumed, or avoid outputting the KV's which have not changed since the previous window. Or, some sort of filter before the CloudSQL insert that takes in everything and that only outputs changed KV's. Is this possible or is there another solution?

答:
One possible method to explore would be to make use of the State API downstream of your sliding window aggregation.

However elements flowing into the this are unordered, so you can not just store the element and compare it with the incoming value.

You will need to add each element in the DoFn to a BagState (as a Timestamped Value).

Set a Timer and then during the the OnTimer() function read all the elements in the bagstate sort them and output the values you need. You will also need to store the max(timestamp) value in a ValueState object so that you can use it the next time the OnTimer is called.

The size of the window you use for the State API DoFn will be arbitrary, the larger it is the less unneeded upserts. On the downside the larger the window the more keys you will keep around in the ValueState which may no longer be needed. Avoid using the Global Window as this will require you to build in a GC function as the window will never expire and your key space will grow forever.

Body:
I have a streaming pipeline that consumes a streaming source (Kafka) and will write to a CloudSQL database. The goal is to keep the CloudSQL database updated in real-time with a Key/Value sum aggregation of records received in the past hour.

eg. In the last hour 3 records with KV <001,3>,<001,4>,<001,2> were recieved, database should have a record 001, 9. Records older than an hour aren't included.

My current solution a SlidingWindow into a GroupByKey after the KafkaIO.read:

                    .apply(Window.into(SlidingWindows
                                .of(Duration.standardSeconds(3600))
                                  .every(Duration.standardSeconds(20)))
                    ).apply(GroupByKey.create())

Followed by a ParDo that sums each key, and then update the SQL database.

The result is that every 20 seconds my CloudSQL db is updated with the aggregation of each key of the last hour, which meets the functional requirements. The issue is the amount of upserts to CloudSQL this causes: most of the KV outputs are identical to the previous window, so each window every 20s triggers an hours worth of transactions (~500k).

It would make sense to trigger each KV output only when a record with that key is consumed, or avoid outputting the KV's which have not changed since the previous window. Or, some sort of filter before the CloudSQL insert that takes in everything and that only outputs changed KV's. Is this possible or is there another solution?


问:
Issue sending Http POST request to Nodejs Server
I am having an issue sending over an array of information from my client.js to the node server using an http POST request. After a couple of days I think I have narrowed it down.

My current set up is the following:

Server

After X amount of time, the server will start to ask clients to send their collected data.

The server sends out only one request at a time, waiting to receive that clients info before sending a request to the next client

Client

The client receives the request from the server

Http stuff to send POST request is set up

Array data is converted to json

1000ms is waited before sending the http post request

Server

Post request is received & that data is added to a local array

My server.js

```<code>var http    = require('http')
  , connect = require('connect')
  , io      = require('socket.io')
  , fs      = require('fs')
  , uuid    = require('node-uuid')
  , _       = require('lodash');

// omitted event handers & pubnub setup

var app = connect().use(connect.static(__dirname)).use(connect.directory(__dirname));
var server = http.createServer(app);
server.listen(8888);
io = io.listen(server);

// Following handles sending request to clients

function phaseTwo() {
  var count = 0;
  setTimeout(function() {

    pubnub.publish({
      channel: 'channel' + viewers[count],
      message: { message: 'measurements',
                 uuid:    'Server',
                 receiver: viewers[count] }
    });

    // set up server to listen for http POST
    app.use(function(req, res) {

     if (req.method == 'POST') {
       count++;
       req.on('data', function(chunk) {

         // add that array into one main array
         latencyData.push.apply(latencyData, chunk);

         dataCollected++;
       });

       pubnub.publish({
         channel: 'channel' + viewers[count],
         message: { message: 'measurements',
                    uuid:    'Server',
                    receiver: viewers[count] }
       });
     }
    }); // end app.use
  }, msDuration);
}
</code>```

client

```<code>  if (message.message == 'measurements') {
    console.log('   Received measurements event');

    var http = new XMLHttpRequest();
    var url = 'http://localhost:8888/';
    http.open('POST', url, true);

    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // http.setRequestHeader("Content-length", latency.length);
    // http.setRequestHeader("Connection", "close");

    var myJsonString = JSON.stringify(latency);

    setTimeout( function() {
      http.send(myJsonString);
    }, 1000);

  }
</code>```

The problem is that without that 1000ms delay on the client side, the server does not receive all the client's data. Even worse, when trying to scale up a few hundred clients, no more http posts are sent to the server after 240 clients have sent their info (there is enough ram for them)

With no delay on the client making the POST request, the server should be waiting for the current client to send over their information over before continuing. The other issue is that even with under the 240 clients, say testing 200 clients, even with no delay only about 10% of their data is received (this stuff is written to a text file at the end)

Im very new to using http post/get stuff so I think that is the issue.
Is there anything immediately wrong from anyone experiences with http or nodejs stuff?

edit: I found one mistake. Back on the server side, on the post request whatever data is gotten from the server is added right away to the local array on the server without first making sure it's an array. Im not completely sure if this would break things enough to be the source of my problem

答:
Make proper route in server to handle incoming requests make your app aware of such routes.

You can console.log(req) to check it in server side how you are getting the request with all the data.

Body:
I am having an issue sending over an array of information from my client.js to the node server using an http POST request. After a couple of days I think I have narrowed it down.

My current set up is the following:

Server

After X amount of time, the server will start to ask clients to send their collected data.

The server sends out only one request at a time, waiting to receive that clients info before sending a request to the next client

Client

The client receives the request from the server

Http stuff to send POST request is set up

Array data is converted to json

1000ms is waited before sending the http post request

Server

Post request is received & that data is added to a local array

My server.js

var http    = require('http')
  , connect = require('connect')
  , io      = require('socket.io')
  , fs      = require('fs')
  , uuid    = require('node-uuid')
  , _       = require('lodash');

// omitted event handers & pubnub setup

var app = connect().use(connect.static(__dirname)).use(connect.directory(__dirname));
var server = http.createServer(app);
server.listen(8888);
io = io.listen(server);

// Following handles sending request to clients

function phaseTwo() {
  var count = 0;
  setTimeout(function() {

    pubnub.publish({
      channel: 'channel' + viewers[count],
      message: { message: 'measurements',
                 uuid:    'Server',
                 receiver: viewers[count] }
    });

    // set up server to listen for http POST
    app.use(function(req, res) {

     if (req.method == 'POST') {
       count++;
       req.on('data', function(chunk) {

         // add that array into one main array
         latencyData.push.apply(latencyData, chunk);

         dataCollected++;
       });

       pubnub.publish({
         channel: 'channel' + viewers[count],
         message: { message: 'measurements',
                    uuid:    'Server',
                    receiver: viewers[count] }
       });
     }
    }); // end app.use
  }, msDuration);
}

client

  if (message.message == 'measurements') {
    console.log('   Received measurements event');

    var http = new XMLHttpRequest();
    var url = 'http://localhost:8888/';
    http.open('POST', url, true);

    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    // http.setRequestHeader("Content-length", latency.length);
    // http.setRequestHeader("Connection", "close");

    var myJsonString = JSON.stringify(latency);

    setTimeout( function() {
      http.send(myJsonString);
    }, 1000);

  }

The problem is that without that 1000ms delay on the client side, the server does not receive all the client's data. Even worse, when trying to scale up a few hundred clients, no more http posts are sent to the server after 240 clients have sent their info (there is enough ram for them)

With no delay on the client making the POST request, the server should be waiting for the current client to send over their information over before continuing. The other issue is that even with under the 240 clients, say testing 200 clients, even with no delay only about 10% of their data is received (this stuff is written to a text file at the end)

Im very new to using http post/get stuff so I think that is the issue.
Is there anything immediately wrong from anyone experiences with http or nodejs stuff?

edit: I found one mistake. Back on the server side, on the post request whatever data is gotten from the server is added right away to the local array on the server without first making sure it's an array. Im not completely sure if this would break things enough to be the source of my problem