问:
How can I use 2 values on Universal Tween Engine, libgdx java
I whant to I make 2 values work simultaneously
example:
 I whant X go from 0 to 100 and Y from 500 to -200
variable

with my code only works on X_start and X_end it go from (0, 1,2...100)
but the Y_start and Y_end don't work that way, it goes (500,500...500,-200) and what I need it to do is (500,499,498...-199,-200)

```<code>float X_start = 0;
float X_end = 100;
float Y_start = 500;
float Y_end = -200;

Tween.set(skeleton, SkeletonAcessor.P_Z).target(X_start,Y_start).start(tweenManager);
Tween.to(skeleton,SkeletonAcessor.P_Z, 5.0f).target(X_end,Y_end).setCallback(new TweenCallback(){

        @Override
        public void onEvent(int arg0, BaseTween<?> arg1) {

        }

    }).start(tweenManager);
tweenManager.update(Float.MIN_VALUE);
</code>```

my public class SkeletonAcessor implements TweenAccessor

```<code>public class SkeletonAcessor implements TweenAccessor<Skeleton> {
    // tween the position
    public static final int P_X = 1;
    public static final int P_Y = 2;

    // tween the scale
    public static final int P_Z = 3;
    public static final int P_TREME =4;

    @Override
    public int getValues(Skeleton target, int tweenType, float[] returnValues) {
        switch(tweenType){
            case P_X:
                returnValues[0] = target.getRootBone().getX();
               // returnValues[1] = target.getRootBone().getY();
                return 1;
            case P_Y:
                returnValues[0] = target.getRootBone().getY();
                return 1;
            case P_Z:
                returnValues[0] = target.getRootBone().getScaleX();
                returnValues[0] = target.getRootBone().getScaleY();
                returnValues[1] = target.getRootBone().getY();
               // System.out.println("get valor "+returnValues[0]+"\n");
                return 1;
            case P_TREME:
             returnValues[1] = target.getRootBone().getX();

            return 1;
            default:
                assert false;
                return -1;

        }
    }

    @Override
    public void setValues(Skeleton target, int tweenType, float[] newValues) {
        switch(tweenType){
            case P_X:
                target.getRootBone().setX(newValues[0]);
                // dá o efeito andar
                //target.getRootBone().setY(((float)(0.1*Math.cos(newValues[0]))*20) +400);
                break;

            case P_Y:
                target.getRootBone().setY(newValues[0]);
                break;
            case P_Z:

                target.getRootBone().setScaleX( newValues[0]/2);
                target.getRootBone().setScaleY( newValues[0]/2);
                target.getRootBone().setY(newValues[1]);

            //  System.out.println("newValues[1] "+newValues[1]+" \n");
                break;
            case P_TREME:
                int random = (int)(Math.random() * 20 + 1);
              //  System.out.println("rand "+random+" valor "+newValues[0]+"\n");
                target.getRootBone().setX(newValues[1]+random);

                break;
            default:
                assert false;
        }

    }
}
</code>```

答: on getValues just change return 1 to return 2 and it will work

Body:
I whant to I make 2 values work simultaneously
example:
 I whant X go from 0 to 100 and Y from 500 to -200
variable

with my code only works on X_start and X_end it go from (0, 1,2...100)
but the Y_start and Y_end don't work that way, it goes (500,500...500,-200) and what I need it to do is (500,499,498...-199,-200)

float X_start = 0;
float X_end = 100;
float Y_start = 500;
float Y_end = -200;

Tween.set(skeleton, SkeletonAcessor.P_Z).target(X_start,Y_start).start(tweenManager);
Tween.to(skeleton,SkeletonAcessor.P_Z, 5.0f).target(X_end,Y_end).setCallback(new TweenCallback(){

        @Override
        public void onEvent(int arg0, BaseTween<?> arg1) {

        }

    }).start(tweenManager);
tweenManager.update(Float.MIN_VALUE);

my public class SkeletonAcessor implements TweenAccessor

public class SkeletonAcessor implements TweenAccessor<Skeleton> {
    // tween the position
    public static final int P_X = 1;
    public static final int P_Y = 2;

    // tween the scale
    public static final int P_Z = 3;
    public static final int P_TREME =4;

    @Override
    public int getValues(Skeleton target, int tweenType, float[] returnValues) {
        switch(tweenType){
            case P_X:
                returnValues[0] = target.getRootBone().getX();
               // returnValues[1] = target.getRootBone().getY();
                return 1;
            case P_Y:
                returnValues[0] = target.getRootBone().getY();
                return 1;
            case P_Z:
                returnValues[0] = target.getRootBone().getScaleX();
                returnValues[0] = target.getRootBone().getScaleY();
                returnValues[1] = target.getRootBone().getY();
               // System.out.println("get valor "+returnValues[0]+"\n");
                return 1;
            case P_TREME:
             returnValues[1] = target.getRootBone().getX();

            return 1;
            default:
                assert false;
                return -1;

        }
    }

    @Override
    public void setValues(Skeleton target, int tweenType, float[] newValues) {
        switch(tweenType){
            case P_X:
                target.getRootBone().setX(newValues[0]);
                // dá o efeito andar
                //target.getRootBone().setY(((float)(0.1*Math.cos(newValues[0]))*20) +400);
                break;

            case P_Y:
                target.getRootBone().setY(newValues[0]);
                break;
            case P_Z:

                target.getRootBone().setScaleX( newValues[0]/2);
                target.getRootBone().setScaleY( newValues[0]/2);
                target.getRootBone().setY(newValues[1]);

            //  System.out.println("newValues[1] "+newValues[1]+" \n");
                break;
            case P_TREME:
                int random = (int)(Math.random() * 20 + 1);
              //  System.out.println("rand "+random+" valor "+newValues[0]+"\n");
                target.getRootBone().setX(newValues[1]+random);

                break;
            default:
                assert false;
        }

    }
}


来源: stackexchange

问:
how to connect a netlify function to my angular app
I'm unable to do a create request of form datas with a netlify function on my angular app

I'm trying to apply this tutorial https://www.netlify.com/blog/2018/07/09/building-serverless-crud-apps-with-netlify-functions--faunadb/ on my project with angular7 front.

my netlify function:

```<code>/* code from functions/todos-create.js */
import faunadb from 'faunadb' /* Import faunaDB sdk */

/* configure faunaDB Client with our secret */
const q = faunadb.query
const client = new faunadb.Client({
  secret: process.env.FAUNADB_SECRET
})

/* export our lambda function as named "handler" export */
exports.handler = (event, context, callback) => {
  /* parse the string body into a useable JS object */
  const data = JSON.parse(event.body)
  console.log("Function `todo-create` invoked", data)
  const todoItem = {
    data: data
  }
  /* construct the fauna query */
  return client.query(q.Create(q.Ref("classes/todos"), todoItem))
  .then((response) => {
    console.log("success", response)
    /* Success! return the response with statusCode 200 */
    return callback(null, {
      statusCode: 200,
      body: JSON.stringify(response)
    })
  }).catch((error) => {
    console.log("error", error)
    /* Error! return the error with statusCode 400 */
    return callback(null, {
      statusCode: 400,
      body: JSON.stringify(error)
    })
  })
}
</code>```

my service:

```<code>import { Injectable } from '@angular/core';
import { Mission } from 'src/app/shared/models';

@Injectable({
  providedIn: 'root'
})
export class MissionService {

  public mission = new Mission();
  myTodo = {
    title: 'My todo title',
    completed: false,
  };

  constructor() { }

  createTodo(data) {
    return fetch('/.netlify/functions/todos-create', {
      body: JSON.stringify(data),
      method: 'POST'
    }).then(response => {
      return response.json();
    });
  }
}
</code>```

as requested in tutorial I add this at the end of my package.json:

```<code>"proxy": {
    "/.netlify/functions": {
      "target": "http://localhost:4200",
      "pathRewrite": {
        "^/\\.netlify/functions": ""
      }
    }
  }
</code>```

but with "http://localhost:4200" adress for angular I supposed

I apply createTodo on click my form button but:

"ERROR Error: "Uncaught (in promise): SyntaxError: JSON.parse:
  unexpected character at line 1 column 1 of the JSON data" in firefox

AND

"Request from ::ffff:127.0.0.1: POST /todos-create  Response with
  status 500 in 12 ms.  Error during invocation:  TypeError: n is not a
  function" in console

solution is here: https://github.com/netlify/netlify-lambda/issues/64

答: You need to look at what is the event received by the netlify function. Looks like the body is not a JSON object as a string, as expected by JSON.parse. That would not be surprising given that a GET call does not have a body.</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm unable to do a create request of form datas with a netlify function on my angular app

I'm trying to apply this tutorial https://www.netlify.com/blog/2018/07/09/building-serverless-crud-apps-with-netlify-functions--faunadb/ on my project with angular7 front.

my netlify function:

/* code from functions/todos-create.js */
import faunadb from 'faunadb' /* Import faunaDB sdk */

/* configure faunaDB Client with our secret */
const q = faunadb.query
const client = new faunadb.Client({
  secret: process.env.FAUNADB_SECRET
})

/* export our lambda function as named "handler" export */
exports.handler = (event, context, callback) => {
  /* parse the string body into a useable JS object */
  const data = JSON.parse(event.body)
  console.log("Function `todo-create` invoked", data)
  const todoItem = {
    data: data
  }
  /* construct the fauna query */
  return client.query(q.Create(q.Ref("classes/todos"), todoItem))
  .then((response) => {
    console.log("success", response)
    /* Success! return the response with statusCode 200 */
    return callback(null, {
      statusCode: 200,
      body: JSON.stringify(response)
    })
  }).catch((error) => {
    console.log("error", error)
    /* Error! return the error with statusCode 400 */
    return callback(null, {
      statusCode: 400,
      body: JSON.stringify(error)
    })
  })
}

my service:

import { Injectable } from '@angular/core';
import { Mission } from 'src/app/shared/models';

@Injectable({
  providedIn: 'root'
})
export class MissionService {

  public mission = new Mission();
  myTodo = {
    title: 'My todo title',
    completed: false,
  };

  constructor() { }

  createTodo(data) {
    return fetch('/.netlify/functions/todos-create', {
      body: JSON.stringify(data),
      method: 'POST'
    }).then(response => {
      return response.json();
    });
  }
}

as requested in tutorial I add this at the end of my package.json:

"proxy": {
    "/.netlify/functions": {
      "target": "http://localhost:4200",
      "pathRewrite": {
        "^/\\.netlify/functions": ""
      }
    }
  }

but with "http://localhost:4200" adress for angular I supposed

I apply createTodo on click my form button but:

"ERROR Error: "Uncaught (in promise): SyntaxError: JSON.parse:
  unexpected character at line 1 column 1 of the JSON data" in firefox

AND

"Request from ::ffff:127.0.0.1: POST /todos-create  Response with
  status 500 in 12 ms.  Error during invocation:  TypeError: n is not a
  function" in console

solution is here: https://github.com/netlify/netlify-lambda/issues/64


问:
How can I refactor this if elif statements?
There is list of grades - [a,b,c,d,e,f]

```<code>grade = int(input())
if grade >= 90 and grade <= 100:
    print('a')
elif grade >=70 and grade <= 80:
    print('b')
elif grade >=60 and grade <= 70:
    print('c')
elif grade >= 50 and grade <= 60:
    print('d')
elif grade < 50:
    print('e')
</code>```

How can I rewrite this elegantly in 2-3 lines of code?

Like, there is dictionary with key grades 'a', 'b', 'c', 'd' and it prints depending on the grade?

答:
You could zip grades and thresholds:

```<code>grades = "edcba"
limits = [50, 60, 70, 80, 100]  # I think that 80-90 gap is not intentional
grade = int(input())
for limit, letter in zip(limits, grades):
    if grade <= limit:
        print(letter)
        break
else:
    print("Not found!")
</code>```

Body:
There is list of grades - [a,b,c,d,e,f]

grade = int(input())
if grade >= 90 and grade <= 100:
    print('a')
elif grade >=70 and grade <= 80:
    print('b')
elif grade >=60 and grade <= 70:
    print('c')
elif grade >= 50 and grade <= 60:
    print('d')
elif grade < 50:
    print('e')

How can I rewrite this elegantly in 2-3 lines of code?

Like, there is dictionary with key grades 'a', 'b', 'c', 'd' and it prints depending on the grade?

Body:
You could zip grades and thresholds:

grades = "edcba"
limits = [50, 60, 70, 80, 100]  # I think that 80-90 gap is not intentional
grade = int(input())
for limit, letter in zip(limits, grades):
    if grade <= limit:
        print(letter)
        break
else:
    print("Not found!")


答:
```<code>grades =  {'a': range(90,100), 'b': range(80,90),'c': range(70,80), 'd': range(60,70), 'e': range(50,60)}

grade = int(input())

for key,value in grades.items():
    if grade in value:
        print (key)
</code>```

or just use list comprehension:

```<code>grades =  {'a': range(90,100), 'b': range(80,90),'c': range(70,80), 'd':range(60,70), 'e': range(50,60)}

grade = int(input())

print ([key for key,value in grades.items() if grade in value][0])
</code>```

Title: How can I refactor this if elif statements?

Body:
grades =  {'a': range(90,100), 'b': range(80,90),'c': range(70,80), 'd': range(60,70), 'e': range(50,60)}

grade = int(input())

for key,value in grades.items():
    if grade in value:
        print (key)

or just use list comprehension:

grades =  {'a': range(90,100), 'b': range(80,90),'c': range(70,80), 'd':range(60,70), 'e': range(50,60)}

grade = int(input())

print ([key for key,value in grades.items() if grade in value][0])


问:
How to write security rules for firebase firestore when request data and in case where we have not used firebase authentication?
I have used Firebase Firestore for database storage. I had a scenario in which i need to manage users login and logout using phone number and OTP. and as Firebase authentication manages authentication using email id or if you want to use it with phone number every time you need to verify it using OTP which was not feasible for my application so, I created my own process of authentication in which I am using OTP authentication once and I store users data to the collection and then after when users login I directly check it from collection.

It is perfectly working now but as I am facing issues while changing security rules as I want to restrict user in reading database. But I don't know how to write it as I have found many solution till now but that all were having auth in request but as I am not using auth I may not have auth in request and could find it null.

```<code>service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write : if true;
    }
  }
}
</code>```

I have given read and write access to all the collection so, anyone having key can access db but I want to restrict it using security rules and I have kind of found a way of restricting user when creating or updating as I will be getting resource when requesting for set or update but in case of reading or getting data it might not have resources as i am not passing any data . So please help me if you know how can I write such rules. Thanks In Advance...

答:
To allow only users that are authentication with Firebase access to data, you rules would be:

```<code>allow read, write: if request.auth.uid != null;
</code>```

It isn't possible to do the same without Firebase Authentication, as the only way to pass data about the user into security rules is through Firebase Authentication.

If you have your own authentication mechanism, you can implement that as a custom provider within Firebase Authentication. In this approach you use server-side code to generate a Firebase token based on the information you have about the user, and the information from that token then becomes available in the security rules under auth.token.

Body:
I have used Firebase Firestore for database storage. I had a scenario in which i need to manage users login and logout using phone number and OTP. and as Firebase authentication manages authentication using email id or if you want to use it with phone number every time you need to verify it using OTP which was not feasible for my application so, I created my own process of authentication in which I am using OTP authentication once and I store users data to the collection and then after when users login I directly check it from collection.

It is perfectly working now but as I am facing issues while changing security rules as I want to restrict user in reading database. But I don't know how to write it as I have found many solution till now but that all were having auth in request but as I am not using auth I may not have auth in request and could find it null.

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write : if true;
    }
  }
}

I have given read and write access to all the collection so, anyone having key can access db but I want to restrict it using security rules and I have kind of found a way of restricting user when creating or updating as I will be getting resource when requesting for set or update but in case of reading or getting data it might not have resources as i am not passing any data . So please help me if you know how can I write such rules. Thanks In Advance...

Body:
To allow only users that are authentication with Firebase access to data, you rules would be:

allow read, write: if request.auth.uid != null;

It isn't possible to do the same without Firebase Authentication, as the only way to pass data about the user into security rules is through Firebase Authentication.

If you have your own authentication mechanism, you can implement that as a custom provider within Firebase Authentication. In this approach you use server-side code to generate a Firebase token based on the information you have about the user, and the information from that token then becomes available in the security rules under auth.token.


问:
Django specify decimal places for FloatRangeField
I have a model which has FloatRangeField

```<code>class Credit(models.Model):

    interest_range = FloatRangeField('Interest', null=True, blank=True)
</code>```

And I have a model form:

```<code>class CreditForm(forms.ModelForm):

    interest_range = InclusiveFloatRangeField()
</code>```

Now, I want to specify 2 fixed decimal places (Only in UI, database check is not important)

Seems models.FloatRangeField doesn't support decimal_places. And I cant't find any example in django documentation to specify decimal places for FloatRangeField with widgets.

django version: 2.2

答:
```<code>class LenderProfile(models.Model):
      interest_range = DecimalField('Interest',decimal_places=2, null=True, blank=True)
</code>```

there with DecimalField at the model can you select how many decimals fields you want with decimal_places

Body:
I have a model which has FloatRangeField

class Credit(models.Model):

    interest_range = FloatRangeField('Interest', null=True, blank=True)

And I have a model form:

class CreditForm(forms.ModelForm):

    interest_range = InclusiveFloatRangeField()

Now, I want to specify 2 fixed decimal places (Only in UI, database check is not important)

Seems models.FloatRangeField doesn't support decimal_places. And I cant't find any example in django documentation to specify decimal places for FloatRangeField with widgets.

django version: 2.2

Body:
class LenderProfile(models.Model):
      interest_range = DecimalField('Interest',decimal_places=2, null=True, blank=True)

there with DecimalField at the model can you select how many decimals fields you want with decimal_places


问:
check if value of one column lies between the range of another column(array) in a dataframe
I have a dataframe where I need to compare a few values and deduce a few things out of it.

For instance,

my DF

```<code>CITY DAY MONTH TAG RANGE     VALUE  RANK
A    1    01    A   [50, 90]   55     1
A    2    02    B   [30, 40]   34     3
A    1    03    A   [05, 10]   15    20
A    1    04    B   [50, 60]   11    10
A    1    05    B   [50, 60]   54    4
</code>```

I have to check , for every row if the value of "VALUE" lies between the "RANGE". Here, arr[0] is the lower limit and arr[1] is the upper limit.

I need to create a new DF such that,

NEW-DF

```<code>TAG  Positive  Negative
A     1          1
B     2          1
</code>```

If the "value" lies between the given range and the rank < 5 then I would add it to "positive"

If the value doesnt lie in the given range , then it is a negative

If the value lies in the given range, but the rank > 5, then I would count it as negative

"Positive" and "Negative" is nothing but the count of the values fulfilling either conditions.

Body:
I have a dataframe where I need to compare a few values and deduce a few things out of it.

For instance,

my DF

CITY DAY MONTH TAG RANGE     VALUE  RANK
A    1    01    A   [50, 90]   55     1
A    2    02    B   [30, 40]   34     3
A    1    03    A   [05, 10]   15    20
A    1    04    B   [50, 60]   11    10
A    1    05    B   [50, 60]   54    4

I have to check , for every row if the value of "VALUE" lies between the "RANGE". Here, arr[0] is the lower limit and arr[1] is the upper limit.

I need to create a new DF such that,

NEW-DF

TAG  Positive  Negative
A     1          1
B     2          1

If the "value" lies between the given range and the rank < 5 then I would add it to "positive"

If the value doesnt lie in the given range , then it is a negative

If the value lies in the given range, but the rank > 5, then I would count it as negative

"Positive" and "Negative" is nothing but the count of the values fulfilling either conditions.

Body:
You have to use a UDF first to process the range :

val df = Seq(("A","1","01","A","[50,90]","55","1")).toDF("city","day","month","tag","range","value","rank")

+----+---+-----+---+-------+-----+----+
|city|day|month|tag|  range|value|rank|
+----+---+-----+---+-------+-----+----+
|   A|  1|   01|  A|[50,90]|   55|   1|
+----+---+-----+---+-------+-----+----+

  def checkRange(range : String,rank : String, value : String) : String = {
    val rangeProcess = range.dropRight(1).drop(1).split(",")
    if (rank.toInt > 5){
      "negative"
    } else {
      if (value > rangeProcess(0) && value < rangeProcess(1)){
        "positive"
      } else {
        "negative"
      }
    }
  }

  val checkRangeUdf = udf(checkRange _)

df.withColumn("Result",checkRangeUdf(col("range"),col("rank"),col("value"))).show()

+----+---+-----+---+-------+-----+----+--------+
|city|day|month|tag|  range|value|rank|  Result|
+----+---+-----+---+-------+-----+----+--------+
|   A|  1|   01|  A|[50,90]|   55|   1|positive|
+----+---+-----+---+-------+-----+----+--------+

val result = df.withColumn("Result",checkRangeUdf(col("range"),col("rank"),col("value"))).groupBy("city","Result").count.show

+----+--------+-----+
|city|  Result|count|
+----+--------+-----+
|   A|positive|    1|
+----+--------+-----+


问:
Promise.all is finished before the promises that it's relying on
I have a list of API requests that only when all of them are finished I will return an answer. I used th Promise.all for that but it seems like the then of promise.all is being triggered before the promises he suppose to wait for.
I figured it happens because I have an get request inside of a post request. How can I make this work?

This a react-redux prject.

```<code>if (devices) {
    const APIArray = [];
    devices.forEach(device => {
        const data = {
            id: device.id,
        };
        dispatch({ type: EDIT_DEVICE, payload: data });
        APIArray.push(
            axios
                .post('/deploy/update', data)
                .then(res => {
                    ApiUtils.get(`/deploy/device?deviceId=${data.id}`).then(response => {
                        console.log('1');
                        dispatch({ type: EDIT_DEVICE_SUCCESS, payload: { device: response.data } });
                    });
                })
                .catch(error => {
                    dispatch({ type: EDIT_DEVICE_FAIL, payload: { device: data, error: error } });
                })
        );
    });

    return Promise.all(APIArray)
        .then(res => {
            console.log('2');
            dispatch({ type: UPDATE_DEVICES_SUCCESS, payload: res });
            return res;
        })
        .catch(err => {
            return err
        );
}

expected: console.log('1')
          console.log('1')
          console.log('2')
actual: console.log('2')
        console.log('1')
        console.log('1')
</code>```

答:
you should change </p>

```<code>.then(res => {
   ApiUtils.get(`/deploy/device?deviceId=${data.id}`).then(...);
})
</code>```

<p>by </p>

```<code>.then(res => {
   return ApiUtils.get(`/deploy/device?deviceId=${data.id}`).then(...);
 })

 // or without brackets

.then(res => ApiUtils.get(`/deploy/device?deviceId=${data.id}`).then(...))
</code>```

Body:
I have a list of API requests that only when all of them are finished I will return an answer. I used th Promise.all for that but it seems like the then of promise.all is being triggered before the promises he suppose to wait for.
I figured it happens because I have an get request inside of a post request. How can I make this work?

This a react-redux prject.

if (devices) {
    const APIArray = [];
    devices.forEach(device => {
        const data = {
            id: device.id,
        };
        dispatch({ type: EDIT_DEVICE, payload: data });
        APIArray.push(
            axios
                .post('/deploy/update', data)
                .then(res => {
                    ApiUtils.get(`/deploy/device?deviceId=${data.id}`).then(response => {
                        console.log('1');
                        dispatch({ type: EDIT_DEVICE_SUCCESS, payload: { device: response.data } });
                    });
                })
                .catch(error => {
                    dispatch({ type: EDIT_DEVICE_FAIL, payload: { device: data, error: error } });
                })
        );
    });

    return Promise.all(APIArray)
        .then(res => {
            console.log('2');
            dispatch({ type: UPDATE_DEVICES_SUCCESS, payload: res });
            return res;
        })
        .catch(err => {
            return err
        );
}

expected: console.log('1')
          console.log('1')
          console.log('2')
actual: console.log('2')
        console.log('1')
        console.log('1')

Body:
you should change

.then(res => {
   ApiUtils.get(`/deploy/device?deviceId=${data.id}`).then(...);
})

by

.then(res => {
   return ApiUtils.get(`/deploy/device?deviceId=${data.id}`).then(...);
 })

 // or without brackets

.then(res => ApiUtils.get(`/deploy/device?deviceId=${data.id}`).then(...))


问:
How to search columns in search input only from logged-in user data?
How will I get only the columns of the logged user on input search query? Means that I search only the data that he has stored

```<code>$restaurants = Restaurant::where('title', 'like', '%'.$query.'%')
</code>```

Restaurant have user_id column, in user model:

```<code>public function restaurants() {
    return $this->hasMany('App\Restaurant');
}
</code>```

in restaurant model:

```<code>public function user() {
    return $this->belongsTo('App\User');
}
</code>```

答:
You can try this.

```<code>$user = \Auth::user();
$restaurants = Restaurant::where('title', 'like', '%'.$query.'%')
                         ->where("user_id", $user->id)
                         ->get();
</code>```

If you would like to add it globaly scoped Restorent model you should use Global Scope.

With this solution, you just need to add a Global Scope with Restorent model and after that for each restorent related transaction user could fetch/update/delete their own entries only.

App/Scopes/UserScope.php

```<code><?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class UserScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('user_id', \Auth::user()->id);
    }
}
</code>```

Ueses: in your model Restaurant.php

```<code><?php

namespace App;

use App\Scopes\UserScope;
use Illuminate\Database\Eloquent\Model;

class Restaurant extends Model
{
    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new UserScope);
    }
}
</code>```

Body:
How will I get only the columns of the logged user on input search query? Means that I search only the data that he has stored

$restaurants = Restaurant::where('title', 'like', '%'.$query.'%')

Restaurant have user_id column, in user model:

public function restaurants() {
    return $this->hasMany('App\Restaurant');
}

in restaurant model:

public function user() {
    return $this->belongsTo('App\User');
}

Body:
You can try this.

$user = \Auth::user();
$restaurants = Restaurant::where('title', 'like', '%'.$query.'%')
                         ->where("user_id", $user->id)
                         ->get();

If you would like to add it globaly scoped Restorent model you should use Global Scope.

With this solution, you just need to add a Global Scope with Restorent model and after that for each restorent related transaction user could fetch/update/delete their own entries only.

App/Scopes/UserScope.php

<?php

namespace App\Scopes;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;

class UserScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $builder
     * @param  \Illuminate\Database\Eloquent\Model  $model
     * @return void
     */
    public function apply(Builder $builder, Model $model)
    {
        $builder->where('user_id', \Auth::user()->id);
    }
}

Ueses: in your model Restaurant.php

<?php

namespace App;

use App\Scopes\UserScope;
use Illuminate\Database\Eloquent\Model;

class Restaurant extends Model
{
    /**
     * The "booting" method of the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        static::addGlobalScope(new UserScope);
    }
}


问:
Is there a way to score a list that have its members in another list?
I have two lists. The phrase list contain both words and phrases while the check list contains only words. I want to confirm if any member of the check list is a part or in the phrase list. I will give each string in the phrase list a score depending on its membership in the check list.

In the example below, information retrieval yields 0.5 because only one word ("information") out of two is in the check list. On the other hand, wave transformation yields 1 because both "wave" and "transformation" appear in check.

I have looked for how to do it but none has worked

```<code>score = []
phrase = ['information retrieval', 'wave transformation', 'information', 'services', 'gold coast village']
check = ['information', 'wave', 'transformation', 'village', 'services']
</code>```

I expect the score list to contain the score for each member of the phrase list.

```<code>phrase = ['information retrieval', 'wave transformation', 'information', 'services', 'gold coast village']
score = [0.5, 1, 1, 1, 0.33]
</code>```

答:
Try this:

```<code>phrase = list(map(str.split, phrase))
score = [len(set(check).intersection(k))/len(k) for k in phrase]
</code>```

Output :

```<code>[0.5, 1.0, 1.0, 1.0, 0.3333333333333333]
</code>```

Body:
I have two lists. The phrase list contain both words and phrases while the check list contains only words. I want to confirm if any member of the check list is a part or in the phrase list. I will give each string in the phrase list a score depending on its membership in the check list.

In the example below, information retrieval yields 0.5 because only one word ("information") out of two is in the check list. On the other hand, wave transformation yields 1 because both "wave" and "transformation" appear in check.

I have looked for how to do it but none has worked

score = []
phrase = ['information retrieval', 'wave transformation', 'information', 'services', 'gold coast village']
check = ['information', 'wave', 'transformation', 'village', 'services']

I expect the score list to contain the score for each member of the phrase list.

phrase = ['information retrieval', 'wave transformation', 'information', 'services', 'gold coast village']
score = [0.5, 1, 1, 1, 0.33]

Body:
Try this:

phrase = list(map(str.split, phrase))
score = [len(set(check).intersection(k))/len(k) for k in phrase]

Output :

[0.5, 1.0, 1.0, 1.0, 0.3333333333333333]


问:
How to repeat sequence of days 1:7 based on continuous days to correspond with weeks
I want to add a column of days each week to my dataset which contains continuous days and continuous weeks already for a large dataset

I've tried to use the floor function and the rep function already

Edit I'm attempting to automate the final output mydata$day_of_week

```<code>time_in_hrs<-c(0,2,12,24,25,29,30,32,38,43,57,82,93,105,199,205,245,263)
mydata<-as.data.frame(time_in_hrs)
mydata$time_in_days<-floor(mydata$time_in_hrs/24)+1
mydata$time_in_weeks<-floor(mydata$time_in_days/8)+1
mydata$day_of_week<-c(1,1,1,2,2,2,2,2,2,2,3,4,4,5,2,2,4,4)
</code>```

答:
with the rep-command you can try the following:

```<code>mydata$days <- rep(c("Monday", "Tuesday", "Wednesday", Thursday",
"Friday", "Saturday", "Sunday"), times = 5)

mydata$days <- rep(1:7, times = 5)
</code>```

Hope this might help you.

Best, Veronika

Body:
I want to add a column of days each week to my dataset which contains continuous days and continuous weeks already for a large dataset

I've tried to use the floor function and the rep function already

Edit I'm attempting to automate the final output mydata$day_of_week

time_in_hrs<-c(0,2,12,24,25,29,30,32,38,43,57,82,93,105,199,205,245,263)
mydata<-as.data.frame(time_in_hrs)
mydata$time_in_days<-floor(mydata$time_in_hrs/24)+1
mydata$time_in_weeks<-floor(mydata$time_in_days/8)+1
mydata$day_of_week<-c(1,1,1,2,2,2,2,2,2,2,3,4,4,5,2,2,4,4)

Body:
with the rep-command you can try the following:

mydata$days <- rep(c("Monday", "Tuesday", "Wednesday", Thursday",
"Friday", "Saturday", "Sunday"), times = 5)

mydata$days <- rep(1:7, times = 5)

Hope this might help you.

Best, Veronika


问:
How to delete the first row
I have some trouble with Laravel SQL builder. I want to delete the first row. I am using the below code:

```<code>DB::table('ahah')->first()->delete().
</code>```

In the controller, I've already imported DB class using the statement use Illuminate\Support\Facades\DB. Can you tell me what's the problem and how to fix it?

答:
As others answered, your requirement should be fulfilled as you described in your question.

I'm just adding a cleaner technique to delete the FIRST row of the table. Create the model (made using Eloquent), then add a scope method which will return the first row of the table and then you just need to call delete() on the query builder.

```<code><?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class FooBarModel extends Model
{
    protected $table = 'foo_bar';

    /**
     * Scope a query to retrieve first row.
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeFirstRow($query)
    {
        return $query->orderBy('id')->first();  // Assuming id is the name of primary key column in the table
    }
}
</code>```

Then you may delete the first row as:

```<code>FooBarModel::firstRow()->delete();  // This will delete the very first available row every time it is called
</code>```

However, handling the exceptions is always a good practice. Here if no row exists in the table, then calling the above statement will raise an exception as the query builder object will return null. So better first check if the result is not null then only call delete() method.

```<code>$firstRow = FooBarModel::firstRow();
if (!is_null($firstRow)) {
    $firstRow->delete();
}
</code>```

Similarly, you can create other scopes as well to delete the last row, last to the last row, etc.

If you want to go for a more cleaner way than this then you can just write a method in the Model itself and write all code to delete there.

```<code>/**
 * @return bool
 */
public static function deleteFirstRow()
{
    $firstRow = self::firstRow();
    if (!is_null($firstRow)) {
        $firstRow->delete();
        return true;
    }
    return false;
}
</code>```

Then call deleteFirstRow() to delete first row.

```<code>FooBarModel::deleteFirstRow();
</code>```

Hope this helps.

Title: How to delete the first row

Body:
I have some trouble with Laravel SQL builder. I want to delete the first row. I am using the below code:

DB::table('ahah')->first()->delete().

In the controller, I've already imported DB class using the statement use Illuminate\Support\Facades\DB. Can you tell me what's the problem and how to fix it?

Body:
As others answered, your requirement should be fulfilled as you described in your question.

I'm just adding a cleaner technique to delete the FIRST row of the table. Create the model (made using Eloquent), then add a scope method which will return the first row of the table and then you just need to call delete() on the query builder.

<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class FooBarModel extends Model
{
    protected $table = 'foo_bar';

    /**
     * Scope a query to retrieve first row.
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeFirstRow($query)
    {
        return $query->orderBy('id')->first();  // Assuming id is the name of primary key column in the table
    }
}

Then you may delete the first row as:

FooBarModel::firstRow()->delete();  // This will delete the very first available row every time it is called

However, handling the exceptions is always a good practice. Here if no row exists in the table, then calling the above statement will raise an exception as the query builder object will return null. So better first check if the result is not null then only call delete() method.

$firstRow = FooBarModel::firstRow();
if (!is_null($firstRow)) {
    $firstRow->delete();
}

Similarly, you can create other scopes as well to delete the last row, last to the last row, etc.

If you want to go for a more cleaner way than this then you can just write a method in the Model itself and write all code to delete there.

/**
 * @return bool
 */
public static function deleteFirstRow()
{
    $firstRow = self::firstRow();
    if (!is_null($firstRow)) {
        $firstRow->delete();
        return true;
    }
    return false;
}

Then call deleteFirstRow() to delete first row.

FooBarModel::deleteFirstRow();

Hope this helps.


问:
How do I find Roman Numerals in a string and make it all upper case in C#?
I have a XML file with multiple roman numerals. I want to take the roman numerals and convert them to uppercase. I have found the numerals using Regex but I don't know how to replace each one with uppercase.

Input - For Roman Numerals

答:
You could use Regex.Replace for converting matches to UpperCase. For example,</p>

```<code>var result= Regex.Replace(text, pattern,c=>c.ToString().ToUpper());
</code>```

Body:
You could use Regex.Replace for converting matches to UpperCase. For example,

var result= Regex.Replace(text, pattern,c=>c.ToString().ToUpper());


问:
How to copy values from one df to the original df with a certain condition?
Currently I am working on clustering problem and I have a problem with copying the values from one dataframe to the original dataframe.

```<code>    CustomerID | Date |     Time| TotalSum | CohortMonth| CohortIndex
--------------------------------------------------------------------
0   |17850.0|2017-11-29||08:26:00|15.30|2017-11-01|1|
--------------------------------------------------------------------
1   |17850.0|2017-11-29||08:26:00|20.34|2017-11-01|1|
--------------------------------------------------------------------
2   |17850.0|2017-11-29||08:26:00|22.00|2017-11-01|1|
--------------------------------------------------------------------
3   |17850.0|2017-11-29||08:26:00|20.34|2017-11-01|1|
--------------------------------------------------------------------
</code>```

And the dataframe with values (clusters) to copy:

```<code>CustomerID|Cluster
------------------
12346.0   |     1
------------------
12346.0   |     1
------------------
12346.0   |     1
------------------
</code>```

Please help me with the problem: How to copy values from the second df based on Customer ID criteria to the first dataframe.

I tried the code like this:

```<code>df.merge(ic,left_on='CustomerID',right_on='Cluster',how='left').drop('CustomerID',1).fillna('')
</code>```

But it doesn't work and I get an error...

Besides it tried a version of such code as:

```<code>df, ic = [d.reset_index(drop=True) for d in (df, ic)]
ic.join(df[['CustomerID']])
</code>```

But it gets the same error or error like the 'Customer ID' not in df...
Sorry if it's not clear and bad formatted question...It is my first question on stackoverflow. Thank you all.

UPDATE

I have tried this

```<code>df1=df.merge(ic,left_on='CustomerID',right_on='Cluster',how='left')

 if ic['CustomerID'].values != df1['CustomerID_x'].values:
    df1.Cluster=ic.Cluster
 else:
    df1.Cluster='NaN'
</code>```

But I've got different cluster for the same customer.

    CustomerID_x| Date | Time | TotalSum | CohortMonth | CohortIndex | CustomerID_y | Cluster

0|17850.0|2017-11-29||08:26:00|15.30 | 2017-11-01 | 1 | NaN | 1.0

1|17850.0|2017-11-29||08:26:00|20.34 | 2017-11-01 | 1 | NaN | 0.0

2|17850.0|2017-11-29||08:26:00|22.00 | 2017-11-01 | 1 | NaN | 1.0

3|17850.0|2017-11-29||08:26:00|20.34 | 2017-11-01 | 1 | NaN | 2.0

4|17850.0|2017-11-29||08:26:00|20.34 | 2017-11-01 | 1 | NaN | 1.0

Body:
Currently I am working on clustering problem and I have a problem with copying the values from one dataframe to the original dataframe.

    CustomerID | Date |     Time| TotalSum | CohortMonth| CohortIndex
--------------------------------------------------------------------
0   |17850.0|2017-11-29||08:26:00|15.30|2017-11-01|1|
--------------------------------------------------------------------
1   |17850.0|2017-11-29||08:26:00|20.34|2017-11-01|1|
--------------------------------------------------------------------
2   |17850.0|2017-11-29||08:26:00|22.00|2017-11-01|1|
--------------------------------------------------------------------
3   |17850.0|2017-11-29||08:26:00|20.34|2017-11-01|1|
--------------------------------------------------------------------

And the dataframe with values (clusters) to copy:

CustomerID|Cluster
------------------
12346.0   |     1
------------------
12346.0   |     1
------------------
12346.0   |     1
------------------

Please help me with the problem: How to copy values from the second df based on Customer ID criteria to the first dataframe.

I tried the code like this:

df.merge(ic,left_on='CustomerID',right_on='Cluster',how='left').drop('CustomerID',1).fillna('')

But it doesn't work and I get an error...

Besides it tried a version of such code as:

df, ic = [d.reset_index(drop=True) for d in (df, ic)]
ic.join(df[['CustomerID']])

But it gets the same error or error like the 'Customer ID' not in df...
Sorry if it's not clear and bad formatted question...It is my first question on stackoverflow. Thank you all.

UPDATE

I have tried this

df1=df.merge(ic,left_on='CustomerID',right_on='Cluster',how='left')

 if ic['CustomerID'].values != df1['CustomerID_x'].values:
    df1.Cluster=ic.Cluster
 else:
    df1.Cluster='NaN'

But I've got different cluster for the same customer.

    CustomerID_x| Date | Time | TotalSum | CohortMonth | CohortIndex | CustomerID_y | Cluster

0|17850.0|2017-11-29||08:26:00|15.30 | 2017-11-01 | 1 | NaN | 1.0

1|17850.0|2017-11-29||08:26:00|20.34 | 2017-11-01 | 1 | NaN | 0.0

2|17850.0|2017-11-29||08:26:00|22.00 | 2017-11-01 | 1 | NaN | 1.0

3|17850.0|2017-11-29||08:26:00|20.34 | 2017-11-01 | 1 | NaN | 2.0

4|17850.0|2017-11-29||08:26:00|20.34 | 2017-11-01 | 1 | NaN | 1.0

Body:
Given what you've written, I think you want:

>>> df1 = pd.DataFrame({"CustomerID": [17850.0] * 4, "CohortIndex": [1,1,1,1] })
>>> df1
   CustomerID  CohortIndex
0     17850.0            1
1     17850.0            1
2     17850.0            1
3     17850.0            1

>>> df2
   CustomerID  Cluster
0     12346.0        1
1     17850.0        1
2     12345.0        1

>>> pd.merge(df1, df2, 'left', 'CustomerID')
   CustomerID  CohortIndex  Cluster
0     17850.0            1        1
1     17850.0            1        1
2     17850.0            1        1
3     17850.0            1        1


问:
Change Read Only Functionality with a button in Access
New to visual basic but I've been trying to learn it for Microsoft Access. In my database I have forms linked together for UI. The forms have an 'edit' button.

I want the form to not be editable until the 'edit' button is clicked. So I've made all attributes in the form to be read-only.

My button is not yet functional. I would like these 'read-only' attributes to be editable once the edit button is clicked.

I've tried this in the function for when the edit button is clicked:

```<code>Me.AllowEdits = True
TextFeild.Enabled = True
</code>```

But it doesn't do anything.

答: Are the fields locked? (i.e. TextField.Locked = true). I usually put a "Lock" toggle on my forms that alternates the "locked" property between true/false for all controls on the form.</p>

Body:
New to visual basic but I've been trying to learn it for Microsoft Access. In my database I have forms linked together for UI. The forms have an 'edit' button.

I want the form to not be editable until the 'edit' button is clicked. So I've made all attributes in the form to be read-only.

My button is not yet functional. I would like these 'read-only' attributes to be editable once the edit button is clicked.

I've tried this in the function for when the edit button is clicked:

Me.AllowEdits = True
TextFeild.Enabled = True

But it doesn't do anything.


问:
What is the difference between sqlite3 and sqlalchemy?
Beginner question- what is the difference between sqlite and sqlalchemy? </p>

答:
They're apples and oranges.

Sqlite is a database storage engine, which can be better compared with things such as MySQL, PostgreSQL, Oracle, MSSQL, etc. It is used to store and retrieve structured data from files.

SQLAlchemy is a Python library that provides an object relational mapper (ORM). It does what it suggests: it maps your databases (tables, etc.) to Python objects, so that you can more easily and natively interact with them. SQLAlchemy can be used with sqlite, MySQL, PostgreSQL, etc.

So, an ORM provides a set of tools that let you interact with your database models consistently across database engines.

ContentLicense: CC BY-SA 3.0


问:
How to write triggers to enforce business rules?
I want to create triggers for practicing PL/SQL and I sorta got stuck with these two ones, which I'm sure they're simple, but I can't get a hold of this code.

The first trigger forbids an employee to have a salary higher than the 80% of their boss (The code is incomplete because I don't know how to continue):

CREATE OR REPLACE TRIGGER MAX_SALARY
BEFORE INSERT ON EMP
FOR EACH ROW
P.BOSS EMP.JOB%TYPE := 'BOSS'
P.SALARY EMP.SAL%TYPE
BEGIN
SELECT SAL FROM EMP
WHERE
 JOB != P.BOSS
...
```

<p>And the second one, there must not be less than two employees per department</p>

<pre class="lang-sql prettyprint-override"><code>CREATE TRIGGER MIN_LIMIT
AFTER DELETE OR UPDATE EMPNO
EMPLOYEES NUMBER(2,0);
BEGIN
SELECT COUNT(EMPNO)INTO EMPLOYEES FROM EMP
WHERE DEPTNO = DEPT.DEPTNO;
IF EMPLOYEES < 2 THEN
DBMS_OUTPUT.PUT_LINE('There cannot be less than two employees per department');
END IF;
END;
</code>```

I really don't know If I'm actually getting closer or far from it altogether...

答:
which I'm sure they're simple

Actually these tasks are not simple for triggers. The business logic is simple, and the SQL to execute the business logic is simple, but implementing it in triggers is hard. To understand why you need to understand how triggers work.

Triggers fire as part of a transaction, which means they are are applied to the outcome of a SQL statement such as an insert or an update. There are two types of triggers, row level and statement level triggers.

Row-level triggers fire once for every row in the result set we can reference values in the current row, which is useful for evaluating row-level rules.. But we cannot execute DML against the owning table: Oracle hurls ORA-04088 mutating table exception, because such actions violate transactional integrity.

Statement level triggers fire exactly once per statement. Consequently they are useful for enforcing table-level rules but crucially they have no access to the result set, which means they don’t know which records have been affected by the DML.

Both your business rules are table level rules, as they require the evaluation of more than one EMP record. So, can we enforce them through triggers? Let’s start with the second rule:

there must not be less than two employees per department

We could implement this with an trigger AFTER statement trigger like this:

```<code>CREATE or replace TRIGGER MIN_LIMIT
AFTER DELETE OR UPDATE on EMP
declare
    EMPLOYEES pls_integer;
BEGIN

    for i in ( select * from dept) loop

        SELECT COUNT(EMPNO) INTO EMPLOYEES
        FROM EMP
        where i.DEPTNO = EMP.DEPTNO;
        IF EMPLOYEES < 2 THEN
            raise_application_error(-20042, 'problem with dept #' || i.DEPTNO || '. There cannot be less than two employees per department');
        END IF;
    end loop;
END;
/
</code>```

Note this trigger uses RAISE_APPLICATION_ERROR() instead of DBMS_OUTPUT.PUT_LINE(). Raising an actual exception is always the  best approach: messages can be ignored but exceptions must be handled.

The problem with this approach is that it will fail any update or delete of any employee, because the classic SCOTT.DEPT table has a record DEPTNO=40 which has no child records in EMP. So maybe we can be cool with departments which have zero employees but not with those which have just one?

```<code>CREATE or replace TRIGGER MIN_LIMIT
AFTER DELETE OR UPDATE on EMP
declare
    EMPLOYEES pls_integer;
BEGIN

    for i in ( select  deptno, count(*) as emp_cnt
                 from emp
                 group by deptno having count(*) < 2
               ) loop

             raise_application_error(-20042, 'problem with dept #' || i.DEPTNO || '. There cannot be less than two employees per department');
    end loop;
END;
/
</code>```

This will enforce the rule. Unless of course somebody tries to insert one employee into department 40:

```<code>insert into emp
values(  2323, 'APC', ‘DEVELOPER', 7839,  sysdate,   4200, null, 40  )
/
</code>```

We can commit this. It will succeed because our trigger doesn’t fire on insert. But some other user’s update will subsequently fail. Which is obviously bobbins. So we need to include INSERT in the trigger actions.

```<code>CREATE or replace TRIGGER MIN_LIMIT
AFTER INSERT or DELETE OR UPDATE on EMP
declare
    EMPLOYEES pls_integer;
BEGIN

    for i in ( select  deptno, count(*) as emp_cnt
                 from emp
                 group by deptno having count(*) < 2
               ) loop

             raise_application_error(-20042, 'problem with dept #' || i.DEPTNO || '. There cannot be less than two employees per department');
    end loop;
END;
/
</code>```

Unfortunately now we cannot insert one employee in department 40:

ORA-20042: problem with dept #40. There cannot be less than two employees per department

  ORA-06512: at "APC.MIN_LIMIT", line 10

  ORA-06512: at "SYS.DBMS_SQL", line 1721

We need to insert two employees in a single statement:

```<code>insert into emp
select 2323, 'APC', 'DEVELOPER', 7839, sysdate, 4200, null, 40 from dual union all
select 2324, 'ANGEL', 'DEVELOPER', 7839, sysdate, 4200, null, 40 from dual
/
</code>```

Note that switching existing employees to a new department has the same limitation: we have to update at least two employees in the same statement.

The other problem is that the trigger may perform badly, because we have to query the whole table after every statement. Perhaps we can do better? Yes. A compound trigger (Oracle 11g and later) allows us to track the affected records for use in a statement level AFTER trigger. Let’s see how we can use one to implement the first rule

No employee can have a salary higher than the 80% of their boss

Compound triggers are highly neat. They allow us to share program constructs across all the events of the trigger. This means we can store the values from row-level events in a collection, which we can use to drive some SQL in an statement level AFTER code..

So this trigger fires on three events. Before a SQL statement is processed we initialise a collection which uses the projection of the EMP table. The code before row stashes the pertinent values from the current row, if the employee has a manager. (Obviously the rule cannot apply to President King who has no boss). The after code loops through the stashed values, looks up the salary of the pertinent manager and evaluates the employee's new salary against their boss's salary.

```<code>CREATE  OR REPLACE TRIGGER MAX_SALARY
FOR INSERT OR UPDATE ON EMP
COMPOUND TRIGGER
  type emp_array is table of emp%rowtype index by simple_integer;
  emps_nt emp_array ;
  v_idx simple_integer := 0;

BEFORE STATEMENT IS
BEGIN
    emps_nt := new emp_array();
END BEFORE STATEMENT;

BEFORE EACH ROW IS
BEGIN
    v_idx := v_idx + 1;
    if :new.mgr is not null then
        emps_nt(v_idx).empno := :new.empno;
        emps_nt(v_idx).mgr := :new.mgr;
        emps_nt(v_idx).sal := :new.sal;
    end if;
END BEFORE EACH ROW;

AFTER EACH ROW IS
BEGIN
    null;
END AFTER EACH ROW;

AFTER STATEMENT IS
    mgr_sal emp.sal%type;
BEGIN
    for i in emps_nt.first() .. emps_nt.last() loop

         select sal into mgr_sal
         from emp
          where emp.empno = emps_nt(i).mgr;

         if emps_nt(i).sal > (mgr_sal * 0.8) then
              raise_application_error(-20024, 'salary of empno ' || emps_nt(i).empno || ' is too high!');

        end if;

    end loop;

END AFTER STATEMENT;
END;
/
</code>```

This code will check every employee if the update is universal, for instance when everybody gets a 20% pay rise...

```<code>update emp
set sal = sal * 1.2
/
</code>```

But if we only update a subset of the EMP table it only checks the boss records it needs to:

```<code>update emp set sal = sal * 1.2
where deptno = 20
/
</code>```

This makes it more efficient than the previous trigger. We could re-write trigger MIN_LIMIT as a compound trigger; that is left as an exercise for the reader :)

Likewise, each trigger fails as soon as a single violating row is found:

ORA-20024: salary of empno 7902 is too high!

  ORA-06512: at "APC.MAX_SALARY", line 36

It would be possible to evaluate all affected rows, stash the violating row(s) in another collection then display all the rows in the collection. Another exercise for the reader.

Finally, note that having two triggers fire on the same event on the same table is not good practice. It's generally better (more efficient, easier to debug) to have one trigger which does everything.

An after thought. What happens to Rule #1 if one session increases the salary of an employee whilst simultaneously another session decreases the salary of the boss? The trigger will pass both updates but we can end up with a violation of the rule. This is an inevitable consequence of the way triggers work with Oracle's read-commit transaction consistency. There is no way to avoid it except by employing a pessimistic locking strategy and pre-emptively locking all the rows which might be affected by a change. That may not scale and is definitely hard to implement using pure SQL: it needs stored procedures. This is another reason why triggers are not good for enforcing business rules.

I'm using Oracle10g

That is unfortunate. Oracle 10g has been obsolete for almost a decade now. Even 11g is deprecated. However, if you really have no option but to stick with 10g you have a couple of options.

The first is to grind through the whole table, doing the lookups of each boss for every employee. This is just about bearable for a toy table such as EMP but likely to be a performance disaster in real life.

The better option is to fake compound triggers using the same workaround we all used to apply: write a package. We rely on global variables - collections - to maintain state across calls to packaged procedures, and have different triggers to make those calls. Basically you need one procedure call for each trigger and one trigger for each step in the compound trigger. @JustinCave posted an example of how to do this on another question; it should be simple to translate my code above to his template.

Body:
I want to create triggers for practicing PL/SQL and I sorta got stuck with these two ones, which I'm sure they're simple, but I can't get a hold of this code.

The first trigger forbids an employee to have a salary higher than the 80% of their boss (The code is incomplete because I don't know how to continue):

CREATE OR REPLACE TRIGGER MAX_SALARY
BEFORE INSERT ON EMP
FOR EACH ROW
P.BOSS EMP.JOB%TYPE := 'BOSS'
P.SALARY EMP.SAL%TYPE
BEGIN
SELECT SAL FROM EMP
WHERE
 JOB != P.BOSS
...

And the second one, there must not be less than two employees per department

CREATE TRIGGER MIN_LIMIT
AFTER DELETE OR UPDATE EMPNO
EMPLOYEES NUMBER(2,0);
BEGIN
SELECT COUNT(EMPNO)INTO EMPLOYEES FROM EMP
WHERE DEPTNO = DEPT.DEPTNO;
IF EMPLOYEES < 2 THEN
DBMS_OUTPUT.PUT_LINE('There cannot be less than two employees per department');
END IF;
END;

I really don't know If I'm actually getting closer or far from it altogether...

Body:
which I'm sure they're simple

Actually these tasks are not simple for triggers. The business logic is simple, and the SQL to execute the business logic is simple, but implementing it in triggers is hard. To understand why you need to understand how triggers work.

Triggers fire as part of a transaction, which means they are are applied to the outcome of a SQL statement such as an insert or an update. There are two types of triggers, row level and statement level triggers.

Row-level triggers fire once for every row in the result set we can reference values in the current row, which is useful for evaluating row-level rules.. But we cannot execute DML against the owning table: Oracle hurls ORA-04088 mutating table exception, because such actions violate transactional integrity.

Statement level triggers fire exactly once per statement. Consequently they are useful for enforcing table-level rules but crucially they have no access to the result set, which means they don’t know which records have been affected by the DML.

Both your business rules are table level rules, as they require the evaluation of more than one EMP record. So, can we enforce them through triggers? Let’s start with the second rule:

there must not be less than two employees per department

We could implement this with an trigger AFTER statement trigger like this:

CREATE or replace TRIGGER MIN_LIMIT
AFTER DELETE OR UPDATE on EMP
declare
    EMPLOYEES pls_integer;
BEGIN

    for i in ( select * from dept) loop

        SELECT COUNT(EMPNO) INTO EMPLOYEES
        FROM EMP
        where i.DEPTNO = EMP.DEPTNO;
        IF EMPLOYEES < 2 THEN
            raise_application_error(-20042, 'problem with dept #' || i.DEPTNO || '. There cannot be less than two employees per department');
        END IF;
    end loop;
END;
/

Note this trigger uses RAISE_APPLICATION_ERROR() instead of DBMS_OUTPUT.PUT_LINE(). Raising an actual exception is always the  best approach: messages can be ignored but exceptions must be handled.

The problem with this approach is that it will fail any update or delete of any employee, because the classic SCOTT.DEPT table has a record DEPTNO=40 which has no child records in EMP. So maybe we can be cool with departments which have zero employees but not with those which have just one?

CREATE or replace TRIGGER MIN_LIMIT
AFTER DELETE OR UPDATE on EMP
declare
    EMPLOYEES pls_integer;
BEGIN

    for i in ( select  deptno, count(*) as emp_cnt
                 from emp
                 group by deptno having count(*) < 2
               ) loop

             raise_application_error(-20042, 'problem with dept #' || i.DEPTNO || '. There cannot be less than two employees per department');
    end loop;
END;
/

This will enforce the rule. Unless of course somebody tries to insert one employee into department 40:

insert into emp
values(  2323, 'APC', ‘DEVELOPER', 7839,  sysdate,   4200, null, 40  )
/

We can commit this. It will succeed because our trigger doesn’t fire on insert. But some other user’s update will subsequently fail. Which is obviously bobbins. So we need to include INSERT in the trigger actions.

CREATE or replace TRIGGER MIN_LIMIT
AFTER INSERT or DELETE OR UPDATE on EMP
declare
    EMPLOYEES pls_integer;
BEGIN

    for i in ( select  deptno, count(*) as emp_cnt
                 from emp
                 group by deptno having count(*) < 2
               ) loop

             raise_application_error(-20042, 'problem with dept #' || i.DEPTNO || '. There cannot be less than two employees per department');
    end loop;
END;
/

Unfortunately now we cannot insert one employee in department 40:

ORA-20042: problem with dept #40. There cannot be less than two employees per department

  ORA-06512: at "APC.MIN_LIMIT", line 10

  ORA-06512: at "SYS.DBMS_SQL", line 1721

We need to insert two employees in a single statement:

insert into emp
select 2323, 'APC', 'DEVELOPER', 7839, sysdate, 4200, null, 40 from dual union all
select 2324, 'ANGEL', 'DEVELOPER', 7839, sysdate, 4200, null, 40 from dual
/

Note that switching existing employees to a new department has the same limitation: we have to update at least two employees in the same statement.

The other problem is that the trigger may perform badly, because we have to query the whole table after every statement. Perhaps we can do better? Yes. A compound trigger (Oracle 11g and later) allows us to track the affected records for use in a statement level AFTER trigger. Let’s see how we can use one to implement the first rule

No employee can have a salary higher than the 80% of their boss

Compound triggers are highly neat. They allow us to share program constructs across all the events of the trigger. This means we can store the values from row-level events in a collection, which we can use to drive some SQL in an statement level AFTER code..

So this trigger fires on three events. Before a SQL statement is processed we initialise a collection which uses the projection of the EMP table. The code before row stashes the pertinent values from the current row, if the employee has a manager. (Obviously the rule cannot apply to President King who has no boss). The after code loops through the stashed values, looks up the salary of the pertinent manager and evaluates the employee's new salary against their boss's salary.

CREATE  OR REPLACE TRIGGER MAX_SALARY
FOR INSERT OR UPDATE ON EMP
COMPOUND TRIGGER
  type emp_array is table of emp%rowtype index by simple_integer;
  emps_nt emp_array ;
  v_idx simple_integer := 0;

BEFORE STATEMENT IS
BEGIN
    emps_nt := new emp_array();
END BEFORE STATEMENT;

BEFORE EACH ROW IS
BEGIN
    v_idx := v_idx + 1;
    if :new.mgr is not null then
        emps_nt(v_idx).empno := :new.empno;
        emps_nt(v_idx).mgr := :new.mgr;
        emps_nt(v_idx).sal := :new.sal;
    end if;
END BEFORE EACH ROW;

AFTER EACH ROW IS
BEGIN
    null;
END AFTER EACH ROW;

AFTER STATEMENT IS
    mgr_sal emp.sal%type;
BEGIN
    for i in emps_nt.first() .. emps_nt.last() loop

         select sal into mgr_sal
         from emp
          where emp.empno = emps_nt(i).mgr;

         if emps_nt(i).sal > (mgr_sal * 0.8) then
              raise_application_error(-20024, 'salary of empno ' || emps_nt(i).empno || ' is too high!');

        end if;

    end loop;

END AFTER STATEMENT;
END;
/

This code will check every employee if the update is universal, for instance when everybody gets a 20% pay rise...

update emp
set sal = sal * 1.2
/

But if we only update a subset of the EMP table it only checks the boss records it needs to:

update emp set sal = sal * 1.2
where deptno = 20
/

This makes it more efficient than the previous trigger. We could re-write trigger MIN_LIMIT as a compound trigger; that is left as an exercise for the reader :)

Likewise, each trigger fails as soon as a single violating row is found:

ORA-20024: salary of empno 7902 is too high!

  ORA-06512: at "APC.MAX_SALARY", line 36

It would be possible to evaluate all affected rows, stash the violating row(s) in another collection then display all the rows in the collection. Another exercise for the reader.

Finally, note that having two triggers fire on the same event on the same table is not good practice. It's generally better (more efficient, easier to debug) to have one trigger which does everything.

An after thought. What happens to Rule #1 if one session increases the salary of an employee whilst simultaneously another session decreases the salary of the boss? The trigger will pass both updates but we can end up with a violation of the rule. This is an inevitable consequence of the way triggers work with Oracle's read-commit transaction consistency. There is no way to avoid it except by employing a pessimistic locking strategy and pre-emptively locking all the rows which might be affected by a change. That may not scale and is definitely hard to implement using pure SQL: it needs stored procedures. This is another reason why triggers are not good for enforcing business rules.

I'm using Oracle10g

That is unfortunate. Oracle 10g has been obsolete for almost a decade now. Even 11g is deprecated. However, if you really have no option but to stick with 10g you have a couple of options.

The first is to grind through the whole table, doing the lookups of each boss for every employee. This is just about bearable for a toy table such as EMP but likely to be a performance disaster in real life.

The better option is to fake compound triggers using the same workaround we all used to apply: write a package. We rely on global variables - collections - to maintain state across calls to packaged procedures, and have different triggers to make those calls. Basically you need one procedure call for each trigger and one trigger for each step in the compound trigger. @JustinCave posted an example of how to do this on another question; it should be simple to translate my code above to his template.


问:
Splitting date and time then transfer them to their new respective columns
I have a website which have a date and time combined in the start of meeting and end of meeting.

Meeting_start
2019-04-26 11:39:15

I already created new columns for date and time. How can I split the existing date and time then transfer them to their new respective columns?

Ps. I'm looking for SQL codes.

Body:
You can simply use the date and time functions available in mySQL

set @d='2019-04-26 11:39:15';
select date(@d),time(@d);

Will output

+------------+----------+
| date(@d)   | time(@d) |
+------------+----------+
| 2019-04-26 | 11:39:15 |
+------------+----------+

Assuming that the existing column is called meeting_start and a table called TABLE you could then do

update `TABLE` set `date_col`=date( `meeting_start` ), `time_col`=time( `meeting_start` );

A simple table schema to illustrate how to update the new fields

mysql> describe `so_datetime_fudge`;
+--------------------+------------------+------+-----+---------+----------------+
| Field              | Type             | Null | Key | Default | Extra          |
+--------------------+------------------+------+-----+---------+----------------+
| id                 | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| name               | varchar(50)      | YES  |     | NULL    |                |
| meeting_start      | datetime         | YES  |     | NULL    |                |
| meeting_start_date | date             | YES  |     | NULL    |                |
| meeting_start_time | time             | YES  |     | NULL    |                |
+--------------------+------------------+------+-----+---------+----------------+

A snapshot of the table with 3 rows of dummy data

mysql> select * from so_datetime_fudge;
+----+-----------------------+---------------------+--------------------+--------------------+
| id | name                  | meeting_start       | meeting_start_date | meeting_start_time |
+----+-----------------------+---------------------+--------------------+--------------------+
|  1 | The First of Too Many | 2019-05-27 16:48:30 | NULL               | NULL               |
|  2 | Holy Cow Batman       | 2019-05-27 16:54:56 | NULL               | NULL               |
|  3 | The End is Nigh       | 2019-05-27 16:55:22 | NULL               | NULL               |
+----+-----------------------+---------------------+--------------------+--------------------+

Then running this query:

update `so_datetime_fudge` set `meeting_start_date`=date( `meeting_start` ), `meeting_start_time`=time( `meeting_start` );

Running the same SELECT query after the update

mysql> select * from so_datetime_fudge;
+----+-----------------------+---------------------+--------------------+--------------------+
| id | name                  | meeting_start       | meeting_start_date | meeting_start_time |
+----+-----------------------+---------------------+--------------------+--------------------+
|  1 | The First of Too Many | 2019-05-27 16:48:30 | 2019-05-27         | 16:48:30           |
|  2 | Holy Cow Batman       | 2019-05-27 16:54:56 | 2019-05-27         | 16:54:56           |
|  3 | The End is Nigh       | 2019-05-27 16:55:22 | 2019-05-27         | 16:55:22           |
+----+-----------------------+---------------------+--------------------+--------------------+

But, if you create a VIEW of the table you can structure this how you like and the underlying data remains unchanged

CREATE VIEW `vw_datetime_fudge` AS select
    `id`,
    `name`,
    date( `meeting_start` ) as `meeting_start_date`,
    time( `meeting_start` ) as `meeting_start_time`
from `so_datetime_fudge`;

mysql> select * from `vw_datetime_fudge`;
+----+-----------------------+--------------------+--------------------+
| id | name                  | meeting_start_date | meeting_start_time |
+----+-----------------------+--------------------+--------------------+
|  1 | The First of Too Many | 2019-05-27         | 16:48:30           |
|  2 | Holy Cow Batman       | 2019-05-27         | 16:54:56           |
|  3 | The End is Nigh       | 2019-05-27         | 16:55:22           |
+----+-----------------------+--------------------+--------------------+


问:
How to update subtype attribute values in oracle database?
How to update column value of a subtype?

Code like this can't access the grade attribute of student:

```<code>update persons set grade = 'graduated';
</code>```

CREATE OR REPLACE TYPE person (
    name varchar2(20),
    age number,
    address varchar2(20)
) NOT FINAL;

CREATE OR REPLACE TYPE student UNDER person (
    grade varchar2(20)
) NOT FINAL;

CREATE TABLE persons OF person;

INSERT INTO persons VALUES (student('Jon', 'undergraduate'));
```

How I change student grade to 'graduated'?

答:
I found a answer to my problem.

This is the code to update subtype attributes:

```<code>DECLARE
    s student;

BEGIN
    select treat(value(p) as student) into s from persons p where name = 'Jon';
    s.grade = 'graduated';
    update persons p set value(p) = s where name = 'Jon';
END;
</code>```

Body:
How to update column value of a subtype?

Code like this can't access the grade attribute of student:

update persons set grade = 'graduated';

CREATE OR REPLACE TYPE person (
    name varchar2(20),
    age number,
    address varchar2(20)
) NOT FINAL;

CREATE OR REPLACE TYPE student UNDER person (
    grade varchar2(20)
) NOT FINAL;

CREATE TABLE persons OF person;

INSERT INTO persons VALUES (student('Jon', 'undergraduate'));

How I change student grade to 'graduated'?

Body:
I found a answer to my problem.

This is the code to update subtype attributes:

DECLARE
    s student;

BEGIN
    select treat(value(p) as student) into s from persons p where name = 'Jon';
    s.grade = 'graduated';
    update persons p set value(p) = s where name = 'Jon';
END;


问:
Service not found: even though it exists in the app's container
What do I have:

services.yaml:

```<code>app.foo.bar:
    class: App\Foo\Bar
    arguments: #[ ... ]
</code>```

Controller:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class MyController extends Controller
{
    public function baz(Request $request)
    {
        $this->get('some_bundle.some_service');
    }
}
```

And it works.

But as Symfony\Bundle\FrameworkBundle\Controller\Controller is deprecated, I've tried to extend Symfony\Bundle\FrameworkBundle\Controller\AbstractController and I got

Service "some_bundle.some_service" not found: even
  though it exists in the app's container, the container inside
  "App\Controller\MyController" is a smaller service locator
  that only knows about the "doctrine", "http_kernel", "parameter_bag",
  "request_stack", "router", "serializer" and "session" services. Try
  using dependency injection instead.

Can I use get() somehow with AbstractController? AbstractController uses ControllerTrait, I wonder why the error takes place.

答:
A lot of things changed in symfony4 vs previous versions. You are using everything as if in a previous version. The quick solution is not the "preferred" way, but to start can change the public key from the default false to true in your services.yaml file.

A better way is to leave it private and use dependency injection instead. The naming of the service has changed as well (now just the path of the service). See the docs here. For your code, try these:

```<code>// services.yaml

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false

    App\Foo\Bar:
        tags: { ** }
</code>```

And the controller with dependence injection:

```<code>use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class MyController extends AbstractController
{
    public function baz(Request $request, Bar $bar)
    {
        $bar->doSomething();
    }
}
</code>```

There's a nice tutorial about these things (and more) here.

Body:
What do I have:

services.yaml:

app.foo.bar:
    class: App\Foo\Bar
    arguments: #[ ... ]

Controller:

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class MyController extends Controller
{
    public function baz(Request $request)
    {
        $this->get('some_bundle.some_service');
    }
}

And it works.

But as Symfony\Bundle\FrameworkBundle\Controller\Controller is deprecated, I've tried to extend Symfony\Bundle\FrameworkBundle\Controller\AbstractController and I got

Service "some_bundle.some_service" not found: even
  though it exists in the app's container, the container inside
  "App\Controller\MyController" is a smaller service locator
  that only knows about the "doctrine", "http_kernel", "parameter_bag",
  "request_stack", "router", "serializer" and "session" services. Try
  using dependency injection instead.

Can I use get() somehow with AbstractController? AbstractController uses ControllerTrait, I wonder why the error takes place.

Body:
A lot of things changed in symfony4 vs previous versions. You are using everything as if in a previous version. The quick solution is not the "preferred" way, but to start can change the public key from the default false to true in your services.yaml file.

A better way is to leave it private and use dependency injection instead. The naming of the service has changed as well (now just the path of the service). See the docs here. For your code, try these:

// services.yaml

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false

    App\Foo\Bar:
        tags: { ** }

And the controller with dependence injection:

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class MyController extends AbstractController
{
    public function baz(Request $request, Bar $bar)
    {
        $bar->doSomething();
    }
}

There's a nice tutorial about these things (and more) here.


问:
Can .NET provided APIs get obfuscated too?
I am considering using obfuscation for my .NET application. My question is that any of these obfuscators also obfuscates any .NET APIs that my code calls. So for example if my class calls any .NET file stream functions or socket related APIs, will they also get obfuscated?</p>

答:
Yes, it is possible to obfuscate the calls to .Net APIs, Crypto Obfuscator does exactly this - it replaces method calls made to .Net APIs with proxy methods.

Before:

Application.EnableVisualStyles();

After:

A.A();

DISCLAIMER: I work at LogicNP Software, the developer of Crypto Obfuscator.


问:
Is there a weighted.median() function?
I'm looking for something similar in form to weighted.mean(). I've found some solutions via search that write out the entire function but would appreciate something a bit more user friendly.

答:
A way in base to get a weighted median will be to order by the values and build the cumsum of the weights and get the value(s) at sum * 0.5 of the weights.

```<code>medianWeighted <- function(x, w, q=.5) {
  n <- length(x)
  i <- order(x)
  w <- cumsum(w[i])
  p <- w[n] * q
  j <- findInterval(p, w)
  Vectorize(function(p,j) if(w[n] <= 0) NA else
    if(j < 1) x[i[1]] else
      if(j == n) x[i[n]] else
        if(w[j] == p) (x[i[j]] + x[i[j+1]]) / 2 else
          x[i[j+1]])(p,j)
}
</code>```

What will have the following results with simple input data.

```<code>medianWeighted(c(10, 40), c(1, 2))
#[1] 40
median(rep(c(10, 40), c(1, 2)))
#[1] 40

medianWeighted(c(10, 40), c(2, 1))
#[1] 10
median(rep(c(10, 40), c(2, 1)))
#[1] 10

medianWeighted(c(10, 40), c(1.5, 2))
#[1] 40
medianWeighted(c(10, 40), c(3, 4))
#[1] 40
median(rep(c(10, 40), c(3, 4)))
#[1] 40

medianWeighted(c(10, 40), c(1.5, 1.5))
#[1] 25
medianWeighted(c(10, 40), c(3, 3))
#[1] 25
median(rep(c(10, 40), c(3, 3)))
#[1] 25

medianWeighted(c(10, 40), c(0, 1))
#[1] 40
medianWeighted(c(10, 40), c(1, 0))
#[1] 10
medianWeighted(c(10, 40), c(0, 0))
#[1] NA
</code>```

It can also be used for other qantiles

```<code>medianWeighted(1:10, 10:1, seq(0, 1, 0.25))
[1]  1  2  4  6 10
</code>```

Compare with other methods.

```<code>#Functions from other Answers
weighted.median <- function(x, w) {
  w <- w[order(x)]
  x <- x[order(x)]

  prob <- cumsum(w)/sum(w)
  ps <- which(abs(prob - .5) == min(abs(prob - .5)))
  return(x[ps])
}

my_wtd_q = function(x, w, prob, n = 4096)
  with(density(x, weights = w/sum(w), n = n),
       x[which.max(cumsum(y*(x[2L] - x[1L])) >= prob)])

weighted.quantile <- function(x, w, probs = seq(0, 1, 0.25),
                              na.rm = FALSE, names = TRUE) {

  if (any(probs > 1) | any(probs < 0)) stop("'probs' outside [0,1]")

  if (length(w) == 1) w <- rep(w, length(x))
  if (length(w) != length(x)) stop("w must have length 1 or be as long as x")

  if (isTRUE(na.rm)) {
    w <- x[!is.na(x)]
    x <- x[!is.na(x)]
  }

  w <- w[order(x)] / sum(w)
  x <- x[order(x)]

  cum_w <- cumsum(w) - w * (1 - (seq_along(w) - 1) / (length(w) - 1))
  res <- approx(x = cum_w, y = x, xout = probs)$y

  if (isTRUE(names)) {
    res <- setNames(res, paste0(format(100 * probs, digits = 7), "%"))
  }
  res
}
</code>```

Methods

```<code>M <- alist(
  medRep = median(rep(DF$x, DF$w)),
 isotone = isotone::weighted.median(DF$x, DF$w),
 laeken = laeken::weightedMedian(DF$x, DF$w),
 spatstat1 = spatstat.geom::weighted.median(DF$x, DF$w, type=1),
 spatstat2 = spatstat.geom::weighted.median(DF$x, DF$w, type=2),
 spatstat4 = spatstat.geom::weighted.median(DF$x, DF$w, type=4),
 survey = survey::svyquantile(~x, survey::svydesign(id=~1, weights=~w, data=DF), 0.5)$x[1],
 RAndres = weighted.median(DF$x, DF$w),
 matrixStats = matrixStats::weightedMedian(DF$x, DF$w),
 MichaelChirico = my_wtd_q(DF$x, DF$w, .5),
 Leonardo = weighted.quantile(DF$x, DF$w, .5),
 GKi = medianWeighted(DF$x, DF$w)
)
</code>```

Results

```<code>DF <- data.frame(x=c(10, 40), w=c(1, 2))
sapply(M, eval)
#        medRep        isotone         laeken      spatstat1      spatstat2
#      40.00000       40.00000       40.00000       40.00000       25.00000
#     spatstat4         survey        RAndres    matrixStats MichaelChirico
#      17.50000       40.00000       10.00000       30.00000       34.15005
#  Leonardo.50%            GKi
#      25.00000       40.00000

DF <- data.frame(x=c(10, 40), w=c(1, 1))
sapply(M, eval)
#        medRep        isotone         laeken      spatstat1      spatstat2
#      25.00000       25.00000       40.00000       10.00000       10.00000
#     spatstat4         survey        RAndres    matrixStats MichaelChirico
#      10.00000       10.00000       10.00000       25.00000       25.05044
#  Leonardo.50%            GKi
#      25.00000       25.00000
</code>```

In those two cases only isotone and GKi give identical results compared to what median(rep(x, w)) returns.

Title: Is there a weighted.median() function?

Body:
A way in base to get a weighted median will be to order by the values and build the cumsum of the weights and get the value(s) at sum * 0.5 of the weights.

medianWeighted <- function(x, w, q=.5) {
  n <- length(x)
  i <- order(x)
  w <- cumsum(w[i])
  p <- w[n] * q
  j <- findInterval(p, w)
  Vectorize(function(p,j) if(w[n] <= 0) NA else
    if(j < 1) x[i[1]] else
      if(j == n) x[i[n]] else
        if(w[j] == p) (x[i[j]] + x[i[j+1]]) / 2 else
          x[i[j+1]])(p,j)
}

What will have the following results with simple input data.

medianWeighted(c(10, 40), c(1, 2))
#[1] 40
median(rep(c(10, 40), c(1, 2)))
#[1] 40

medianWeighted(c(10, 40), c(2, 1))
#[1] 10
median(rep(c(10, 40), c(2, 1)))
#[1] 10

medianWeighted(c(10, 40), c(1.5, 2))
#[1] 40
medianWeighted(c(10, 40), c(3, 4))
#[1] 40
median(rep(c(10, 40), c(3, 4)))
#[1] 40

medianWeighted(c(10, 40), c(1.5, 1.5))
#[1] 25
medianWeighted(c(10, 40), c(3, 3))
#[1] 25
median(rep(c(10, 40), c(3, 3)))
#[1] 25

medianWeighted(c(10, 40), c(0, 1))
#[1] 40
medianWeighted(c(10, 40), c(1, 0))
#[1] 10
medianWeighted(c(10, 40), c(0, 0))
#[1] NA

It can also be used for other qantiles

medianWeighted(1:10, 10:1, seq(0, 1, 0.25))
[1]  1  2  4  6 10

Compare with other methods.

#Functions from other Answers
weighted.median <- function(x, w) {
  w <- w[order(x)]
  x <- x[order(x)]

  prob <- cumsum(w)/sum(w)
  ps <- which(abs(prob - .5) == min(abs(prob - .5)))
  return(x[ps])
}

my_wtd_q = function(x, w, prob, n = 4096)
  with(density(x, weights = w/sum(w), n = n),
       x[which.max(cumsum(y*(x[2L] - x[1L])) >= prob)])

weighted.quantile <- function(x, w, probs = seq(0, 1, 0.25),
                              na.rm = FALSE, names = TRUE) {

  if (any(probs > 1) | any(probs < 0)) stop("'probs' outside [0,1]")

  if (length(w) == 1) w <- rep(w, length(x))
  if (length(w) != length(x)) stop("w must have length 1 or be as long as x")

  if (isTRUE(na.rm)) {
    w <- x[!is.na(x)]
    x <- x[!is.na(x)]
  }

  w <- w[order(x)] / sum(w)
  x <- x[order(x)]

  cum_w <- cumsum(w) - w * (1 - (seq_along(w) - 1) / (length(w) - 1))
  res <- approx(x = cum_w, y = x, xout = probs)$y

  if (isTRUE(names)) {
    res <- setNames(res, paste0(format(100 * probs, digits = 7), "%"))
  }
  res
}

Methods

M <- alist(
  medRep = median(rep(DF$x, DF$w)),
 isotone = isotone::weighted.median(DF$x, DF$w),
 laeken = laeken::weightedMedian(DF$x, DF$w),
 spatstat1 = spatstat.geom::weighted.median(DF$x, DF$w, type=1),
 spatstat2 = spatstat.geom::weighted.median(DF$x, DF$w, type=2),
 spatstat4 = spatstat.geom::weighted.median(DF$x, DF$w, type=4),
 survey = survey::svyquantile(~x, survey::svydesign(id=~1, weights=~w, data=DF), 0.5)$x[1],
 RAndres = weighted.median(DF$x, DF$w),
 matrixStats = matrixStats::weightedMedian(DF$x, DF$w),
 MichaelChirico = my_wtd_q(DF$x, DF$w, .5),
 Leonardo = weighted.quantile(DF$x, DF$w, .5),
 GKi = medianWeighted(DF$x, DF$w)
)

Results

DF <- data.frame(x=c(10, 40), w=c(1, 2))
sapply(M, eval)
#        medRep        isotone         laeken      spatstat1      spatstat2
#      40.00000       40.00000       40.00000       40.00000       25.00000
#     spatstat4         survey        RAndres    matrixStats MichaelChirico
#      17.50000       40.00000       10.00000       30.00000       34.15005
#  Leonardo.50%            GKi
#      25.00000       40.00000

DF <- data.frame(x=c(10, 40), w=c(1, 1))
sapply(M, eval)
#        medRep        isotone         laeken      spatstat1      spatstat2
#      25.00000       25.00000       40.00000       10.00000       10.00000
#     spatstat4         survey        RAndres    matrixStats MichaelChirico
#      10.00000       10.00000       10.00000       25.00000       25.05044
#  Leonardo.50%            GKi
#      25.00000       25.00000

In those two cases only isotone and GKi give identical results compared to what median(rep(x, w)) returns.


问:
Upload an .ipa to apple store using macintouch
i have build a mobile application, i tested on iphone using developer certificate
it works fine on that device

I want to upload to app store  but i discovered that my windows can not do that

i found a server online: macintouch that can help me with that

Pls can anyone help to acheive this OR

use the server please tell me is the server good

macintouch: is the server good to use for upload to appstore

答:
I don't know about macintouch server but you need either Xcode or Application Loader to upload ipa to AppStore. May be you can try installing one on them into your server.
 See this for instruction for uploading from xcode.

There is also some software (available for windows) which will help you to upload ipa to AppStore. But I haven't used, so am not sure, you get succeed or not but you can try. Example app


问:
exclude index.html from service worker cache in create-react-app
I have a reactJs app using create-react-app. The app uses service-worker and other PWA features but somehow I am seeing that despite updating the website or deploying a new build, chrome always picks index.html from service worker and does not make a network call at all.

I think caching the index.html using the service worker is the issue but have not been able to exclude it from getting cached, I did check a few questions on SO and issues on github but could not get a fix for this.

I am using the default service-worker registration

registerServiceWorker.js

```<code>// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.

// This link also includes instructions on opting out of this behavior.

const isLocalhost = Boolean(
    window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
        /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export default function register() {

    if (/*process.env.NODE_ENV === 'production' &&*/ 'serviceWorker' in navigator) {
       // alert('found' + process.env.NODE_ENV);
        // The URL constructor is available in all browsers that support SW.
        const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
        if (publicUrl.origin !== window.location.origin) {
            // Our service worker won't work if PUBLIC_URL is on a different origin
            // from what our page is served on. This might happen if a CDN is used to
            // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
            return;
        }

        window.addEventListener('load', () => {
            const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

            if (isLocalhost) {
                // This is running on localhost. Lets check if a service worker still exists or not.
                checkValidServiceWorker(swUrl);
            } else {
                // Is not local host. Just register service worker
                registerValidSW(swUrl);
            }
        });

    } else {
        //alert('not found' + process.env.NODE_ENV);
    }
}

function registerValidSW(swUrl) {
    navigator.serviceWorker
        .register(swUrl)
        .then(registration => {

            registration.onupdatefound = () => {
                const installingWorker = registration.installing;

                installingWorker.onstatechange = () => {
                    if (installingWorker.state === 'installed') {
                        if (navigator.serviceWorker.controller) {
                            // At this point, the old content will have been purged and
                            // the fresh content will have been added to the cache.
                            // It's the perfect time to display a "New content is
                            // available; please refresh." message in your web app.
                            console.log('New content is available; please refresh.');
                        } else {
                            // At this point, everything has been precached.
                            // It's the perfect time to display a
                            // "Content is cached for offline use." message.
                            console.log('Content is cached for offline use.');
                        }
                    }
                };
            };
        })
        .catch(error => {
            console.error('Error during service worker registration:', error);
        });
}

function checkValidServiceWorker(swUrl) {
    // Check if the service worker can be found. If it can't reload the page.
    fetch(swUrl)
        .then(response => {
            // Ensure service worker exists, and that we really are getting a JS file.
            if (
                response.status === 404 ||
                response.headers.get('Content-Type').indexOf('javascript') === -1
            ) {
                // No service worker found. Probably a different app. Reload the page.
                navigator.serviceWorker.ready.then(registration => {
                    registration.unregister().then(() => {
                        window.location.reload();
                    });
                });
            } else {
                // Service worker found. Proceed as normal.
                registerValidSW(swUrl);
            }
        })
        .catch(() => {
            console.log(
                'No internet connection found. App is running in offline mode.'
            );
        });
}

export function unregister() {
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.ready.then(registration => {
            registration.unregister();
        });
    }
}
</code>```

Please help.

答:
After trying multiple options, the one that worked best was not I was really willing to implement but could not find anything better.

From the service-worker.js file remove below lines

```<code>workbox.routing.registerNavigationRoute("/index.html", {

  blacklist: [/^\/_/,/\/[^\/]+\.[^\/]+$/],
});
</code>```

This will not cache index.html and try to pull it every time from the server, though this does not sound best but does the trick.

Body:
I have a reactJs app using create-react-app. The app uses service-worker and other PWA features but somehow I am seeing that despite updating the website or deploying a new build, chrome always picks index.html from service worker and does not make a network call at all.

I think caching the index.html using the service worker is the issue but have not been able to exclude it from getting cached, I did check a few questions on SO and issues on github but could not get a fix for this.

I am using the default service-worker registration

registerServiceWorker.js

// In production, we register a service worker to serve assets from local cache.

// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.

// This link also includes instructions on opting out of this behavior.

const isLocalhost = Boolean(
    window.location.hostname === 'localhost' ||
    // [::1] is the IPv6 localhost address.
    window.location.hostname === '[::1]' ||
    // 127.0.0.1/8 is considered localhost for IPv4.
    window.location.hostname.match(
        /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
    )
);

export default function register() {

    if (/*process.env.NODE_ENV === 'production' &&*/ 'serviceWorker' in navigator) {
       // alert('found' + process.env.NODE_ENV);
        // The URL constructor is available in all browsers that support SW.
        const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
        if (publicUrl.origin !== window.location.origin) {
            // Our service worker won't work if PUBLIC_URL is on a different origin
            // from what our page is served on. This might happen if a CDN is used to
            // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
            return;
        }

        window.addEventListener('load', () => {
            const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;

            if (isLocalhost) {
                // This is running on localhost. Lets check if a service worker still exists or not.
                checkValidServiceWorker(swUrl);
            } else {
                // Is not local host. Just register service worker
                registerValidSW(swUrl);
            }
        });

    } else {
        //alert('not found' + process.env.NODE_ENV);
    }
}

function registerValidSW(swUrl) {
    navigator.serviceWorker
        .register(swUrl)
        .then(registration => {

            registration.onupdatefound = () => {
                const installingWorker = registration.installing;

                installingWorker.onstatechange = () => {
                    if (installingWorker.state === 'installed') {
                        if (navigator.serviceWorker.controller) {
                            // At this point, the old content will have been purged and
                            // the fresh content will have been added to the cache.
                            // It's the perfect time to display a "New content is
                            // available; please refresh." message in your web app.
                            console.log('New content is available; please refresh.');
                        } else {
                            // At this point, everything has been precached.
                            // It's the perfect time to display a
                            // "Content is cached for offline use." message.
                            console.log('Content is cached for offline use.');
                        }
                    }
                };
            };
        })
        .catch(error => {
            console.error('Error during service worker registration:', error);
        });
}

function checkValidServiceWorker(swUrl) {
    // Check if the service worker can be found. If it can't reload the page.
    fetch(swUrl)
        .then(response => {
            // Ensure service worker exists, and that we really are getting a JS file.
            if (
                response.status === 404 ||
                response.headers.get('Content-Type').indexOf('javascript') === -1
            ) {
                // No service worker found. Probably a different app. Reload the page.
                navigator.serviceWorker.ready.then(registration => {
                    registration.unregister().then(() => {
                        window.location.reload();
                    });
                });
            } else {
                // Service worker found. Proceed as normal.
                registerValidSW(swUrl);
            }
        })
        .catch(() => {
            console.log(
                'No internet connection found. App is running in offline mode.'
            );
        });
}

export function unregister() {
    if ('serviceWorker' in navigator) {
        navigator.serviceWorker.ready.then(registration => {
            registration.unregister();
        });
    }
}

Please help.

Body:
After trying multiple options, the one that worked best was not I was really willing to implement but could not find anything better.

From the service-worker.js file remove below lines

workbox.routing.registerNavigationRoute("/index.html", {

  blacklist: [/^\/_/,/\/[^\/]+\.[^\/]+$/],
});

This will not cache index.html and try to pull it every time from the server, though this does not sound best but does the trick.