问:
Regular expression in distinct texts
I have two patterns to use a regular expression. In the first one, I have this pattern and I can catch the word.

With this regex:

```<code>referente[,;]*\s\S\s(.+)\.\sOnde
</code>```

O COORDENADOR-GERAL DE GESTÃO DE PESSOAS DO MINISTÉRIO DOS TRANSPORTES, PORTOS E AVIAÇÃO CIVIL, no uso das atribuições que lhe foram subdelegadas pela Portaria/SAAD nº. 202, art. 1°, inciso VII, de 08 de outubro de 2010, publicada no Diário Oficial da União, de 11 de outubro de 2010, resolve:
  Retificar a Portaria COGEP-MT nº 3394, de 30 de novembro de 2016, publicada no Diário Oficial da União, Seção 2, página 55, de 13 de dezembro de 2016, referente à MARIA ALIXANDRINA COSTA REIS. Onde se lê "MARIA AUXILIADORA COSTA REIS"; Leia-se "MARIA ALIXANDRINA COSTA REIS.(Processo SEI: 50000.124582/2016-62) BA.

I need to take the name in another pattern.

O COORDENADOR-GERAL DE GESTÃO DE PESSOAS DO MINISTÉRIO DOS
  TRANSPORTES, PORTOS E AVIAÇÃO CIVIL, no uso das atribuições que lhe
  foram subdelegadas pela Portaria/SAAD nº. 202, art.1º, inciso VII, de
  08 de outubro de 2010, publicada no Diário Oficial da União, de 11 de
  outubro de 2010, resolve: Conceder Pensão Temporária, nos termos do
  artigo 215 e 217, inciso II, alínea "a" da Lei nº 8.112/1990, à
  ELIANE RIBEIRO MENESES, filha inválida do ex-servidor ASTOLFO
  MENEZES, matrícula SIAPE nº. 0783182, do Quadro Permanente deste
  Ministério, falecido na inatividade em 05 de agosto de 1997, cuja cota
  parte equivale a 100% (cem por cento) do valor correspondente à
  remuneração decorrente do cargo de Artífice de Mecânica (NI), Classe
  "A", Padrão "III", com vigência partir do momento da Publicação da
  Portaria de Concessão e efeitos financeiros a partir de 30 de maio de
  2015, data do falecimento da viúva. (Processo SEI nº
  50000.019342/2016-47) - MG.

I need to take the bold word too, in the same regex. How can I modify this regex?

Title: Regular expression in distinct texts

Body:
I have two patterns to use a regular expression. In the first one, I have this pattern and I can catch the word.

With this regex:

referente[,;]*\s\S\s(.+)\.\sOnde

O COORDENADOR-GERAL DE GESTÃO DE PESSOAS DO MINISTÉRIO DOS TRANSPORTES, PORTOS E AVIAÇÃO CIVIL, no uso das atribuições que lhe foram subdelegadas pela Portaria/SAAD nº. 202, art. 1°, inciso VII, de 08 de outubro de 2010, publicada no Diário Oficial da União, de 11 de outubro de 2010, resolve:
  Retificar a Portaria COGEP-MT nº 3394, de 30 de novembro de 2016, publicada no Diário Oficial da União, Seção 2, página 55, de 13 de dezembro de 2016, referente à MARIA ALIXANDRINA COSTA REIS. Onde se lê "MARIA AUXILIADORA COSTA REIS"; Leia-se "MARIA ALIXANDRINA COSTA REIS.(Processo SEI: 50000.124582/2016-62) BA.

I need to take the name in another pattern.

O COORDENADOR-GERAL DE GESTÃO DE PESSOAS DO MINISTÉRIO DOS
  TRANSPORTES, PORTOS E AVIAÇÃO CIVIL, no uso das atribuições que lhe
  foram subdelegadas pela Portaria/SAAD nº. 202, art.1º, inciso VII, de
  08 de outubro de 2010, publicada no Diário Oficial da União, de 11 de
  outubro de 2010, resolve: Conceder Pensão Temporária, nos termos do
  artigo 215 e 217, inciso II, alínea "a" da Lei nº 8.112/1990, à
  ELIANE RIBEIRO MENESES, filha inválida do ex-servidor ASTOLFO
  MENEZES, matrícula SIAPE nº. 0783182, do Quadro Permanente deste
  Ministério, falecido na inatividade em 05 de agosto de 1997, cuja cota
  parte equivale a 100% (cem por cento) do valor correspondente à
  remuneração decorrente do cargo de Artífice de Mecânica (NI), Classe
  "A", Padrão "III", com vigência partir do momento da Publicação da
  Portaria de Concessão e efeitos financeiros a partir de 30 de maio de
  2015, data do falecimento da viúva. (Processo SEI nº
  50000.019342/2016-47) - MG.

I need to take the bold word too, in the same regex. How can I modify this regex?

Body: My solution is ([,;]*)*\sà\s((\w+\s)+\w+)[\.,]


来源: stackexchange

问:
What's the best symmetrical .net encryption provider for size?
I have a scenario where I need to serialize a struct to a byte array or string, encrypt it and then store it in a SQL table.

The issue is that it's possible that this table will run into millions of rows and so size is all important.

I've been using the BinaryFormatter to serialize to a byte[], converting it to Ascii and then compressing it with the RijndaelManaged provider.

Prior to encryption, the string is about 230 bytes. Post encryption, it is over 600 bytes.

Does anyone know if any of the other cryptographic providers would do a better job of this? Or, if indeed there's a better way that I should be going about this?

Thanks very much in advance,

Z

答:
In general, encryption algorithms only add a fixed overhead (for IV and, in the case of asymmetric encryption algorithms, the encrypted symmetric key). If you're seeing a 2x increase in size, that indicates that you are doing something before or after encrypting that increases the size of the data.

I would remove the ascii conversion - encryption algorithms work just fine on raw binary data - and make sure you are storing into the database as a raw binary blob, rather than base64-ing or similar. If you still have trouble, please post the code you're using.

ContentLicense: CC BY-SA 2.5


问:
Why is += (addition assignment, plus equal) so slow in node?
In certain versions of node, a += b is significantly slower than a = a + b, but similar in the browser and later versions. What causes them to run so differently?

node v6.10.0 (V8 5.1.281.93), 75% slower, or reverse is 4x faster

node v8.0.0  (V8 5.8.283.41), 86% slower, or reverse is 7x faster

node v8.2.1  (V8 5.8.283.41), 86% slower, or reverse is 7x faster

node v8.3.0  (V8 6.0.286.52), similar

node v8.7.0  (v8 6.1.534.42), similar

node v8.9.2  (V8 6.1.534.48), similar

chrome 62.0.3202.94 (V8 6.1.534.42), similar

safari 11.0.1, similar

Edit: found that it's related to node's v8 engine update from 5 to 6.

Snippet:

```<code>const iter = 10 * 1000 * 1000

function one() {
  let i = 0
  let sum = 0
  while (i < iter) {
    sum += i
    i++
  }
}

function two() {
  let i = 0
  let sum = 0
  while (i < iter) {
    sum = sum + i
    i++
  }
}

let time
const tries = 10

time = Date.now()
for (let i = 0; i < tries; i++) {
  one()
}
console.log('one: ' + String(Date.now() - time))

time = Date.now()
for (let i = 0; i < tries; i++) {
  two()
}
console.log('two: ' + String(Date.now() - time))
</code>```

答: This is not an issue in Node, but with the V8 engine (which Node happens to use). There's a list of "bailout reasons" on the github page (github.com/vhf/v8-bailout-reasons), which are language constructs that kill optimization. "Unsupported let compound assignment", that is, compound assignment with let-bound variables, is one of them. If you profile the code in Chromium's dev tools, you should be able to see "Not optimized: Unsupported let compound assignment": https://i.imgur.com/OWDMqQU.png</p>

ContentLicense: CC BY-SA 3.0

Body:
In certain versions of node, a += b is significantly slower than a = a + b, but similar in the browser and later versions. What causes them to run so differently?

node v6.10.0 (V8 5.1.281.93), 75% slower, or reverse is 4x faster

node v8.0.0  (V8 5.8.283.41), 86% slower, or reverse is 7x faster

node v8.2.1  (V8 5.8.283.41), 86% slower, or reverse is 7x faster

node v8.3.0  (V8 6.0.286.52), similar

node v8.7.0  (v8 6.1.534.42), similar

node v8.9.2  (V8 6.1.534.48), similar

chrome 62.0.3202.94 (V8 6.1.534.42), similar

safari 11.0.1, similar

Edit: found that it's related to node's v8 engine update from 5 to 6.

Snippet:

const iter = 10 * 1000 * 1000

function one() {
  let i = 0
  let sum = 0
  while (i < iter) {
    sum += i
    i++
  }
}

function two() {
  let i = 0
  let sum = 0
  while (i < iter) {
    sum = sum + i
    i++
  }
}

let time
const tries = 10

time = Date.now()
for (let i = 0; i < tries; i++) {
  one()
}
console.log('one: ' + String(Date.now() - time))

time = Date.now()
for (let i = 0; i < tries; i++) {
  two()
}
console.log('two: ' + String(Date.now() - time))


问:
guidelines for importing modules in python
I know that there have been a number of questions concerning importing modules in python, but my question seems to be somewhat different.

I'm trying to understand when you have to import a whole module as opposed to when you have to import a specific entry in the module. It seems that only one of the two ways work.

For example if I want to use basename, importing os.path doesn't do the trick.

```<code>>>> import os.path
>>> basename('scripts/cy.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'basename' is not defined
</code>```

Instead I need to import basename from os.path as in

```<code>>>> from os.path import basename
>>> basename('scripts/cy.py')
'cy.py'
</code>```

Going the other way, if I want to use shutil.copyfile, importing copyfile from shutil doesn't work

```<code>>>>
>>> from shutil import copyfile
>>>
>>> shutil.copyfile('emma','newemma')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'shutil' is not defined
</code>```

Instead I must import shutil as in

```<code>>>>
>>> import shutil
>>>
>>> shutil.copyfile('emma','newemma')
'newemma'
>>>
</code>```

The only way I have been able to get this right is through experimentation.
Are there some guidelines to avoid experimentation?

答:
you could use form module import *

```<code>from time import *
sleep(2)
</code>```

which allow you to call its submodules, instead of:

```<code>from time import sleep
sleep(2)
</code>```

or:

```<code>import time
time.sleep(2)
</code>```

this imports every sub-module of the package
https://docs.python.org/2/tutorial/modules.html#importing-from-a-package

Body:
I know that there have been a number of questions concerning importing modules in python, but my question seems to be somewhat different.

I'm trying to understand when you have to import a whole module as opposed to when you have to import a specific entry in the module. It seems that only one of the two ways work.

For example if I want to use basename, importing os.path doesn't do the trick.

>>> import os.path
>>> basename('scripts/cy.py')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'basename' is not defined

Instead I need to import basename from os.path as in

>>> from os.path import basename
>>> basename('scripts/cy.py')
'cy.py'

Going the other way, if I want to use shutil.copyfile, importing copyfile from shutil doesn't work

>>>
>>> from shutil import copyfile
>>>
>>> shutil.copyfile('emma','newemma')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'shutil' is not defined

Instead I must import shutil as in

>>>
>>> import shutil
>>>
>>> shutil.copyfile('emma','newemma')
'newemma'
>>>

The only way I have been able to get this right is through experimentation.
Are there some guidelines to avoid experimentation?

Body:
you could use form module import *

from time import *
sleep(2)

which allow you to call its submodules, instead of:

from time import sleep
sleep(2)

or:

import time
time.sleep(2)

this imports every sub-module of the package
https://docs.python.org/2/tutorial/modules.html#importing-from-a-package


问:
Using Airflow macro outside of operators
Is there any way to use Airflow macro outside of any operators?

For example, in the DAG I have an action:

```<code>datestamp = '{{ ds }}'

print(datestamp) # prints string not the date when I run it for any date

scanner = S3KeySensor(
        task_id='scanner',
        poke_interval=60,
        timeout=24 * 60 * 60,
        soft_fail=False,
        wildcard_match=True,
        bucket_key=getPath() + datestamp, #datestamp correctly replaced with execution date
        bucket_name=bucketName,
        dag=dag)
</code>```

So when calling scanner, "ds" value gets replaced with execution date which is expected, but I want to use "ds" value in some other places. But in that case, it doesn't replace value, instead it gets entire string as "{{ ds }}". In the above example. print statement prints "{{ ds }}" not the execution date.

答:
Lucky for you bucket_key is templated, just put the jinja template inside.

```<code>…
bucket_key=getPath() + '{{ ds }}',
…
</code>```

Completely outside an operator you cannot use these macros. Because the file is interpreted regularly by the scheduler, and not just during a dag run. So what would the value of ds be when the dag isn't running?

However since you're unlikely to want to do anything with it outside the tasks, you could put it into a templated field. You can also extend another field to be templated.

```<code>class MySensor(S3KeySensor):
    template_fields = ('bucket_key', 'bucket_name', 'my_thing')

    def __init__(self, my_thing=None, *args, **kwargs):
        super(MySensor, self).__init__(*args, **kwargs)
        self.my_thing = my_thing

    def post_execute(self, context):
        logging.info(
           "I probably wanted to over-ride poke to use {}".format(self.my_thing)

scanner = MySensor(
    my_thing='{{ ds }}',
    task_id='scanner',
    poke_interval=60,
    timeout=24 * 60 * 60,
    soft_fail=False,
    wildcard_match=True,
    bucket_key=getPath() + '{{ ds }}',
    bucket_name=bucketName,
    dag=dag)
</code>```

Edit: IIRC self.my_thing doesn't change after the init, rather, the context.my_thing will get templated just before (?pre_execute and) execute is called.

ContentLicense: CC BY-SA 4.0

Body:
Is there any way to use Airflow macro outside of any operators?

For example, in the DAG I have an action:

datestamp = '{{ ds }}'

print(datestamp) # prints string not the date when I run it for any date

scanner = S3KeySensor(
        task_id='scanner',
        poke_interval=60,
        timeout=24 * 60 * 60,
        soft_fail=False,
        wildcard_match=True,
        bucket_key=getPath() + datestamp, #datestamp correctly replaced with execution date
        bucket_name=bucketName,
        dag=dag)

So when calling scanner, "ds" value gets replaced with execution date which is expected, but I want to use "ds" value in some other places. But in that case, it doesn't replace value, instead it gets entire string as "{{ ds }}". In the above example. print statement prints "{{ ds }}" not the execution date.

Body:
Lucky for you bucket_key is templated, just put the jinja template inside.

…
bucket_key=getPath() + '{{ ds }}',
…

Completely outside an operator you cannot use these macros. Because the file is interpreted regularly by the scheduler, and not just during a dag run. So what would the value of ds be when the dag isn't running?

However since you're unlikely to want to do anything with it outside the tasks, you could put it into a templated field. You can also extend another field to be templated.

class MySensor(S3KeySensor):
    template_fields = ('bucket_key', 'bucket_name', 'my_thing')

    def __init__(self, my_thing=None, *args, **kwargs):
        super(MySensor, self).__init__(*args, **kwargs)
        self.my_thing = my_thing

    def post_execute(self, context):
        logging.info(
           "I probably wanted to over-ride poke to use {}".format(self.my_thing)

scanner = MySensor(
    my_thing='{{ ds }}',
    task_id='scanner',
    poke_interval=60,
    timeout=24 * 60 * 60,
    soft_fail=False,
    wildcard_match=True,
    bucket_key=getPath() + '{{ ds }}',
    bucket_name=bucketName,
    dag=dag)

Edit: IIRC self.my_thing doesn't change after the init, rather, the context.my_thing will get templated just before (?pre_execute and) execute is called.


问:
Bundle js vs bundle.js.gz
I used webpack to generate my bundle.js but since I was using some thrid party libraries the size is about 1MB. I use the compressed plugin and got a bundle.js.gz of 200kb. I used it and change the header to let the browser know it is compressed and it worked perfect. I am just worried about any side effects I am not seeing at first.

Can anyone tell me what could go wrong.

答:
I don't foresee any problems. Another option, depending on your host, is to configure gzip on your http server. This will gzip on the fly and cache it for future requests (dependent on config).

Here are instructions for configuring Apache & nginx:
https://www.vultr.com/docs/gzip-compression-on-apache-and-nginx

Title: Bundle js vs bundle.js.gz


问:
How to get the assembly information of an imported UserControl through MEF, without instantiating UserControl?
Is it possible get the assembly information from an imported MEF Type, without instantiating a type? I need to know the assembly name and version of the Plugin control that contains the Type. Tried the following, but it just returns the System.ComponentModel.Composition.

```<code>foreach (Lazy<UserControl, IMetadata> content in contents)
{
    // get assembly information of the Plugin control for the imported function
    string definingAssembly = content.GetType().Assembly.GetName();
    Console.WriteLine(definingAssembly);
}
</code>```

To avoid maintenance issues if possible I want to avoid specifying this information in Metadata.

答:
What you tried should fail, as the Assembly never can be the dynamically loaded module assembly.

I guess if you don't instantiating a type, that module assembly is not even loaded into memory.

Did you try to post to MEF discussion board yet? There you may meet the developers.

http://mef.codeplex.com/discussions

Body:
Is it possible get the assembly information from an imported MEF Type, without instantiating a type? I need to know the assembly name and version of the Plugin control that contains the Type. Tried the following, but it just returns the System.ComponentModel.Composition.

foreach (Lazy<UserControl, IMetadata> content in contents)
{
    // get assembly information of the Plugin control for the imported function
    string definingAssembly = content.GetType().Assembly.GetName();
    Console.WriteLine(definingAssembly);
}

To avoid maintenance issues if possible I want to avoid specifying this information in Metadata.


问:
create a folder on an SD card
I'm trying to create a folder on the SD card that is named by user inputs, I get no errors when I run it, but it also doesn't create the folder.

the following is all the code I have written for this activity:

```<code>public class Jobselection extends AppCompatActivity
     implements OnClickListener {
     Button createButton;
     EditText photogname;
     EditText projnum;
     EditText phase;
     DatePicker datePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jobselection);
        createButton = (Button) findViewById(R.id.createButton);
        createButton.setOnClickListener(this);
        photogname = (EditText) findViewById(R.id.photographername);
        projnum = (EditText) findViewById(R.id.projectnumber);
        phase = (EditText) findViewById(R.id.phase);
        datePicker = (DatePicker) findViewById(R.id.datePicker);

    }

    public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
        int day = datePicker.getDayOfMonth();
        int month = datePicker.getMonth();
        int year = datePicker.getYear();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }
    public void onClick(View createButton) {
    String date = getDateFromDatePicker(datePicker).toString();
    String photog = photogname.getText().toString();
    String proj = projnum.getText().toString() + "." + phase.getText().toString();
    String state;
    state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
        boolean isDirectoryCreated = appDirectory.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = appDirectory.mkdirs();
        }
        if (isDirectoryCreated) {
            Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
        }
        else
            Log.d("error","dir.already exists");
    }

    Intent launchUnitLoc = new Intent(this, UnitLocation.class);
    startActivity(launchUnitLoc);
}
</code>```

答:
I just modified your code, here is the full code

```<code>public class Jobselection extends AppCompatActivity
implements View.OnClickListener {
private static final int REQUEST_CODE = 200 ;
Button createButton;
EditText photogname;
EditText projnum;
EditText phase;
DatePicker datePicker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_jobselection);
    createButton = (Button) findViewById(R.id.createButton);
    createButton.setOnClickListener(this);
    photogname = (EditText) findViewById(R.id.editText);//added just to clear error
    projnum = (EditText) findViewById(R.id.editText);//added just to clear erro
    phase = (EditText) findViewById(R.id.editText);// added just to clear error
    datePicker = (DatePicker) findViewById(R.id.datePicker);

}

public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
    int day = datePicker.getDayOfMonth();
    int month = datePicker.getMonth();
    int year = datePicker.getYear();
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month, day);
    return calendar.getTime();
}

@RequiresApi(api = Build.VERSION_CODES.M)
public void onClick(View createButton) {
    String date = getDateFromDatePicker(datePicker).toString();
    String photog = "FinalTest";//photogname.getText().toString();just to clear error

    String proj = projnum.getText().toString() + "." + phase.getText().toString();
    String state;
    state = Environment.getExternalStorageState();

    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            Log.v("Permisson", "Permission is granted");
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
        }
    }
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
        boolean isDirectoryCreated = appDirectory.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = appDirectory.mkdirs();
        }
        if (isDirectoryCreated) {
            Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
        } else
            Log.d("error", "dir.already exists");
    }
}
}
Intent launchUnitLoc = new Intent(this, UnitLocation.class);
startActivity(launchUnitLoc);
</code>```

and your Manifest file should be like:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="[your package name]">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".Jobselection">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
</code>```

Title: create a folder on an SD card

Body:
I'm trying to create a folder on the SD card that is named by user inputs, I get no errors when I run it, but it also doesn't create the folder.

the following is all the code I have written for this activity:

public class Jobselection extends AppCompatActivity
     implements OnClickListener {
     Button createButton;
     EditText photogname;
     EditText projnum;
     EditText phase;
     DatePicker datePicker;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_jobselection);
        createButton = (Button) findViewById(R.id.createButton);
        createButton.setOnClickListener(this);
        photogname = (EditText) findViewById(R.id.photographername);
        projnum = (EditText) findViewById(R.id.projectnumber);
        phase = (EditText) findViewById(R.id.phase);
        datePicker = (DatePicker) findViewById(R.id.datePicker);

    }

    public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
        int day = datePicker.getDayOfMonth();
        int month = datePicker.getMonth();
        int year = datePicker.getYear();
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }
    public void onClick(View createButton) {
    String date = getDateFromDatePicker(datePicker).toString();
    String photog = photogname.getText().toString();
    String proj = projnum.getText().toString() + "." + phase.getText().toString();
    String state;
    state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
        boolean isDirectoryCreated = appDirectory.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = appDirectory.mkdirs();
        }
        if (isDirectoryCreated) {
            Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
        }
        else
            Log.d("error","dir.already exists");
    }

    Intent launchUnitLoc = new Intent(this, UnitLocation.class);
    startActivity(launchUnitLoc);
}

Body:
I just modified your code, here is the full code

public class Jobselection extends AppCompatActivity
implements View.OnClickListener {
private static final int REQUEST_CODE = 200 ;
Button createButton;
EditText photogname;
EditText projnum;
EditText phase;
DatePicker datePicker;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_jobselection);
    createButton = (Button) findViewById(R.id.createButton);
    createButton.setOnClickListener(this);
    photogname = (EditText) findViewById(R.id.editText);//added just to clear error
    projnum = (EditText) findViewById(R.id.editText);//added just to clear erro
    phase = (EditText) findViewById(R.id.editText);// added just to clear error
    datePicker = (DatePicker) findViewById(R.id.datePicker);

}

public static java.util.Date getDateFromDatePicker(DatePicker datePicker) {
    int day = datePicker.getDayOfMonth();
    int month = datePicker.getMonth();
    int year = datePicker.getYear();
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month, day);
    return calendar.getTime();
}

@RequiresApi(api = Build.VERSION_CODES.M)
public void onClick(View createButton) {
    String date = getDateFromDatePicker(datePicker).toString();
    String photog = "FinalTest";//photogname.getText().toString();just to clear error

    String proj = projnum.getText().toString() + "." + phase.getText().toString();
    String state;
    state = Environment.getExternalStorageState();

    if (Build.VERSION.SDK_INT >= 23) {
        if (checkSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            Log.v("Permisson", "Permission is granted");
        } else {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
        }
    }
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        File appDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + date + "/" + proj + "/" + photog);
        boolean isDirectoryCreated = appDirectory.exists();
        if (!isDirectoryCreated) {
            isDirectoryCreated = appDirectory.mkdirs();
        }
        if (isDirectoryCreated) {
            Toast.makeText(Jobselection.this, "Folder is created", Toast.LENGTH_LONG).show();
        } else
            Log.d("error", "dir.already exists");
    }
}
}
Intent launchUnitLoc = new Intent(this, UnitLocation.class);
startActivity(launchUnitLoc);

and your Manifest file should be like:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="[your package name]">

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".Jobselection">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>


问:
How to capture/log all errors from Amazon AWS JavaScript SDK?
I want to hook a function to log all errors from the AWS JavaScript SDK, ideally at one single point for everything.

I've dug around for several hours but not found the right point.

Can anyone suggest where/how this can be done?
thanks

答:
It would depend on what your doing actually in the AWS, but it should look something like this. You didn't give us really anything to work with.</p>

```<code>    // Depends on parameters
    AWS(function(error, response) {
     if (error) {
       console.log(error)
     } else if (response) {
    console.log("No errors + a response")
    }
  }
</code>```

Body:
It would depend on what your doing actually in the AWS, but it should look something like this. You didn't give us really anything to work with.

    // Depends on parameters
    AWS(function(error, response) {
     if (error) {
       console.log(error)
     } else if (response) {
    console.log("No errors + a response")
    }
  }


问:
Undefined index "product" on line 6
So im making an online store. index.php and view.php files are fine. When I click on the product in my index.php it properly shows its information in the view.php file. But when i click Buy Now on my view.php file, its supposed to open the cart.php file with the products information .
But I get the following error:
Notice: Undefined index: product in /storage/ssd3/036/3764036/public_html/carrillo/cart.php on line 6
How can I solve it and why does it happen?
Here is my cart.php code:

<!doctype html>

<?php
include('config.php');
$productid=$_GET['product'];
?>
<meta charset="utf-8">
<title>Cart</title>
<link rel="stylesheet" href="style.css" type="text/css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed|Rubik" rel="stylesheet">

  <?php
   include('head.php');
  ?>

<?php
if (isset($_POST['pid'])) {
    $pid = $_POST['pid'];
 $wasFound = false;
 $i = 0;
 if (!isset($_SESSION["cartshop"]) || count($_SESSION["cartshop"]) < 1) {
  $_SESSION["cartshop"] = array(0 => array("item_id" => $pid, "quantity" => 1));
 } else {
  foreach ($_SESSION["cartshop"] as $each_item) {
        $i++;
        while (list($key, $value) = each($each_item)) {
      if ($key == "item_id" && $value == $pid) {
       array_splice($_SESSION["cartshop"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));
       $wasFound = true;
      }
        }
        }
     if ($wasFound == false) {
      array_push($_SESSION["cartshop"], array("item_id" => $pid, "quantity" => 1));
     }
 }
 header("location: cart.php");
    exit();
}
?>
<?php
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") {
    unset($_SESSION["cartshop"]);
}
?>
<?php
if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") {
 $item_to_adjust = $_POST['item_to_adjust'];
 $quantity = $_POST['quantity'];
 $quantity = preg_replace('#[^0-9]#i', '', $quantity);
 if ($quantity >= 11) { $quantity = 10; }
 if ($quantity < 1) { $quantity = 1; }
 if ($quantity == "") { $quantity = 1; }
 $i = 0;
 foreach ($_SESSION["cartshop"] as $each_item) {
        $i++;
        while (list($key, $value) = each($each_item)) {
      if ($key == "item_id" && $value == $item_to_adjust) {
       array_splice($_SESSION["cartshop"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
      }
        }
 }
}
?>
<?php
if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] != "") {
  $key_to_remove = $_POST['index_to_remove'];
 if (count($_SESSION["cartshop"]) <= 1) {
  unset($_SESSION["cartshop"]);
  header('Location: ' . $_SERVER['HTTP_REFERER']);
 } else {
  unset($_SESSION["cartshop"]["$key_to_remove"]);
  sort($_SESSION["cartshop"]);
  header('Location: ' . $_SERVER['HTTP_REFERER']);
 }
}
?>

Cart

<?php
if(isset($_SESSION['cartshop'])==!NULL){
?>

      Item
      Quantity
      Unit Price
      Sub Total

<?php
}
?>
<?php
$cartTotal = "";
if (!isset($_SESSION["cartshop"]) || count($_SESSION["cartshop"]) < 1) {
    echo '

Your Shopping Cart Is Empty
';
 echo '

Continue Shopping

';
} else {
$i = 0;
    foreach ($_SESSION["cartshop"] as $each_item) {
  $item_id = $each_item['item_id'];
  $sql = mysql_query("SELECT * FROM product WHERE id='$item_id' LIMIT 1");
  while ($row = $row = $sql->fetch_assoc()) {
   $productname = $row["name"];
   $producttotalprice = $row["price"];
   $productcode = $row["id"];
   $pic=$row['pro_image'];
   $pdelc=$row['pdelc'];
   $pr=$row['price'];
  }
  $producttotalpricetotal = $producttotalprice * $each_item['quantity'];
  $cartTotal = $producttotalpricetotal + $cartTotal;
echo'

    <form action="cart.php" method="post">
     <input name="quantity" id="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" class="qnttxt"/>

   <input id="adjustBtn" name="adjustBtn' . $item_id . '" type="submit" value="Update" class="qntbtn"/>
   <input name="item_to_adjust" type="hidden" value="' . $item_id . '" />
    </form>

      '.$productname.'
      Rs. '.number_format($producttotalprice).'

Rs. '.number_format($producttotalprice*$each_item['quantity']).'

    <form action="cart.php" method="post">
   <input name="deleteBtn' . $item_id . '" type="submit" value="X" class="removebtn"/>
   <input name="index_to_remove" type="hidden" value="' . $i . '" />
        </form>

';
 $i++;
 }
echo'

Cart Total: Rs. '.number_format($cartTotal).' /-

( Empty Cart )

';
}
?>

```
</div>
</div>

Here is my view.php code:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><!doctype html>
<html>
<head>
<?php

$mysqli = new mysqli("localhost", "id3764036_alan", "agro12345", "id3764036_agrotienda");

$productid=$_GET['product'];
?>
<meta charset="utf-8">
<title>View Product <?=$productid?></title>
<link rel="stylesheet" href="style.css" type="text/css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed|Rubik" rel="stylesheet">
<style>
#undr{width:100%; height:580px; position:absolute; top:75px; left:0px;}
.bdimg{width:100%; height:100%}
.big-outer{ width:80%; height:100%; background:rgba(255,255,255,0.7); margin:auto}
.big-outer p{text-align:center; font-size:40px; margin:10px auto}
.outer{ width:270px; height:310px;  margin:auto;}
.outer img {width:88% !important;}
.price{text-align:center; margin:20px auto; background:#16B472; color:#fff; width:30%; padding:5px 0px;}
.price p{margin:0px; font-size:26px;}
.buy{text-align:center; margin:20px auto; background:#3E8BDC; width:34%; padding:5px 0px; cursor:pointer}
.buy:hover{ background:#2E5AE4;transition:all 0.4s ease-in-out}
#subaz{border:none; background-color:transparent; font-size:32px; color:#fff; font-weight:bold; cursor:pointer}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>

<body>
 <header>
  <?php
   include('head.php');
  ?>
 </header>

    <div id="undr">

 </div>
<?php
$select_query="select * from product where id='$productid'";
$sql=mysqli_query($mysqli,"select * from product where id='$productid'");

$row=$row = $sql->fetch_assoc();
?>
<form id="form1" name="form1" method="post" action="cart.php">
<input type="hidden" name="pid" id="pid" value="<?= $productid ?>" />
    <div id="lowrbdy">
  <div class="big-outer">
         <div class="outer">
             <img src="imeg/<?=$row["pro_image"]?>"/>
            </div>
            <p><?=$row["name"]?></p>
            <div class="price"><p>₡ <?=$row["price"]?></p></div>
            <div class="buy"><input type="submit" id="subaz" value="Buy Now"/></div>
        </div>
    </div>
</form>
</body>
</html></code>```

答:
Cart.php :

```<code>$productid=$_GET['product'];
</code>```

But the request provide 'pid' argument.

View.php:

```<code><input type="hidden" name="pid" id="pid" value="<?= $productid ?>" />
</code>```

So you have 2 solutions:

1- edit line 6 in cart.php to match the argument pid like

```<code>$productid=$_POST['pid'];
</code>```

2- or edit the name of your input in view.php like:

```<code><input type="hidden" name="product" id="pid" value="<?= $productid ?>" />
</code>```

And change method to GET in view.php, or use $_POST[] instead of $_GET[] in cart.php

Title: Undefined index "product" on line 6

Body:
So im making an online store. index.php and view.php files are fine. When I click on the product in my index.php it properly shows its information in the view.php file. But when i click Buy Now on my view.php file, its supposed to open the cart.php file with the products information .
But I get the following error:
Notice: Undefined index: product in /storage/ssd3/036/3764036/public_html/carrillo/cart.php on line 6
How can I solve it and why does it happen?
Here is my cart.php code:

<!doctype html>

<?php
include('config.php');
$productid=$_GET['product'];
?>
<meta charset="utf-8">
<title>Cart</title>
<link rel="stylesheet" href="style.css" type="text/css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed|Rubik" rel="stylesheet">

  <?php
   include('head.php');
  ?>

<?php
if (isset($_POST['pid'])) {
    $pid = $_POST['pid'];
 $wasFound = false;
 $i = 0;
 if (!isset($_SESSION["cartshop"]) || count($_SESSION["cartshop"]) < 1) {
  $_SESSION["cartshop"] = array(0 => array("item_id" => $pid, "quantity" => 1));
 } else {
  foreach ($_SESSION["cartshop"] as $each_item) {
        $i++;
        while (list($key, $value) = each($each_item)) {
      if ($key == "item_id" && $value == $pid) {
       array_splice($_SESSION["cartshop"], $i-1, 1, array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));
       $wasFound = true;
      }
        }
        }
     if ($wasFound == false) {
      array_push($_SESSION["cartshop"], array("item_id" => $pid, "quantity" => 1));
     }
 }
 header("location: cart.php");
    exit();
}
?>
<?php
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") {
    unset($_SESSION["cartshop"]);
}
?>
<?php
if (isset($_POST['item_to_adjust']) && $_POST['item_to_adjust'] != "") {
 $item_to_adjust = $_POST['item_to_adjust'];
 $quantity = $_POST['quantity'];
 $quantity = preg_replace('#[^0-9]#i', '', $quantity);
 if ($quantity >= 11) { $quantity = 10; }
 if ($quantity < 1) { $quantity = 1; }
 if ($quantity == "") { $quantity = 1; }
 $i = 0;
 foreach ($_SESSION["cartshop"] as $each_item) {
        $i++;
        while (list($key, $value) = each($each_item)) {
      if ($key == "item_id" && $value == $item_to_adjust) {
       array_splice($_SESSION["cartshop"], $i-1, 1, array(array("item_id" => $item_to_adjust, "quantity" => $quantity)));
      }
        }
 }
}
?>
<?php
if (isset($_POST['index_to_remove']) && $_POST['index_to_remove'] != "") {
  $key_to_remove = $_POST['index_to_remove'];
 if (count($_SESSION["cartshop"]) <= 1) {
  unset($_SESSION["cartshop"]);
  header('Location: ' . $_SERVER['HTTP_REFERER']);
 } else {
  unset($_SESSION["cartshop"]["$key_to_remove"]);
  sort($_SESSION["cartshop"]);
  header('Location: ' . $_SERVER['HTTP_REFERER']);
 }
}
?>

Cart

<?php
if(isset($_SESSION['cartshop'])==!NULL){
?>

      Item
      Quantity
      Unit Price
      Sub Total

<?php
}
?>
<?php
$cartTotal = "";
if (!isset($_SESSION["cartshop"]) || count($_SESSION["cartshop"]) < 1) {
    echo '

Your Shopping Cart Is Empty
';
 echo '

Continue Shopping

';
} else {
$i = 0;
    foreach ($_SESSION["cartshop"] as $each_item) {
  $item_id = $each_item['item_id'];
  $sql = mysql_query("SELECT * FROM product WHERE id='$item_id' LIMIT 1");
  while ($row = $row = $sql->fetch_assoc()) {
   $productname = $row["name"];
   $producttotalprice = $row["price"];
   $productcode = $row["id"];
   $pic=$row['pro_image'];
   $pdelc=$row['pdelc'];
   $pr=$row['price'];
  }
  $producttotalpricetotal = $producttotalprice * $each_item['quantity'];
  $cartTotal = $producttotalpricetotal + $cartTotal;
echo'

    <form action="cart.php" method="post">
     <input name="quantity" id="quantity" type="text" value="' . $each_item['quantity'] . '" size="1" maxlength="2" class="qnttxt"/>

   <input id="adjustBtn" name="adjustBtn' . $item_id . '" type="submit" value="Update" class="qntbtn"/>
   <input name="item_to_adjust" type="hidden" value="' . $item_id . '" />
    </form>

      '.$productname.'
      Rs. '.number_format($producttotalprice).'

Rs. '.number_format($producttotalprice*$each_item['quantity']).'

    <form action="cart.php" method="post">
   <input name="deleteBtn' . $item_id . '" type="submit" value="X" class="removebtn"/>
   <input name="index_to_remove" type="hidden" value="' . $i . '" />
        </form>

';
 $i++;
 }
echo'

Cart Total: Rs. '.number_format($cartTotal).' /-

( Empty Cart )

';
}
?>

Here is my view.php code:

<!doctype html>

<?php

$mysqli = new mysqli("localhost", "id3764036_alan", "agro12345", "id3764036_agrotienda");

$productid=$_GET['product'];
?>
<meta charset="utf-8">
<title>View Product <?=$productid?></title>
<link rel="stylesheet" href="style.css" type="text/css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.min.css">
<link href="https://fonts.googleapis.com/css?family=Roboto+Condensed|Rubik" rel="stylesheet">

  <?php
   include('head.php');
  ?>

<?php
$select_query="select * from product where id='$productid'";
$sql=mysqli_query($mysqli,"select * from product where id='$productid'");

$row=$row = $sql->fetch_assoc();
?>
<form id="form1" name="form1" method="post" action="cart.php">
<input type="hidden" name="pid" id="pid" value="<?= $productid ?>" />

             <img src="imeg/<?=$row["pro_image"]?>"/>

<?=$row["name"]?>

₡ <?=$row["price"]?>

<input type="submit" id="subaz" value="Buy Now"/>

</form>

Body:
Cart.php :

$productid=$_GET['product'];

But the request provide 'pid' argument.

View.php:

<input type="hidden" name="pid" id="pid" value="<?= $productid ?>" />

So you have 2 solutions:

1- edit line 6 in cart.php to match the argument pid like

$productid=$_POST['pid'];

2- or edit the name of your input in view.php like:

<input type="hidden" name="product" id="pid" value="<?= $productid ?>" />

And change method to GET in view.php, or use $_POST[] instead of $_GET[] in cart.php


问:
iFrame Redirect Issue - Not Changing the page
```<code><iframe src="http://runebet.com/" width="80%" height="65%"     name="runeBetAPI"></iframe>

<script src="http://code.jquery.com/jquery-latest.min.js"
    type="text/javascript"></script>
<script>
function RegisterPage() {
window.frames["runeBetAPI"].location = "http://runebet.com/register/";
}
RegisterPage();
</script>
</code>```

This doesn't seem to work/change the content..

答:
you can access iframe contents from the same domain only read here.

You can use the following to change the source of the iframe.

```<code>function changeSource(src, frameID) {
    var frame= $('#' + frameID);
    if ( frame.length ) {
        frame.attr('src',src);
        return true;
    }
    return false;
}
</code>```

But apparently what looks like looking into what your code is doing the url that you are redirecting to it actually opens a registration form inside modal window, which for some reason is not opening if you access it via an iframe, because if you put the url http://runebet.com/register/ directly in the iframe and load the page it will still be showing the landing page so it is redirecting but the modal is not popping up that leaves you with the last thing that you have to trigger the Register link click and that can only happen if you are in the same domain if not maybe someone else knows, i dont.

```<code>$(window.frames[0].frameElement.contentDocument).find('a[href="/register"]').trigger('click');
</code>```

Body:
you can access iframe contents from the same domain only read here.

You can use the following to change the source of the iframe.

function changeSource(src, frameID) {
    var frame= $('#' + frameID);
    if ( frame.length ) {
        frame.attr('src',src);
        return true;
    }
    return false;
}

But apparently what looks like looking into what your code is doing the url that you are redirecting to it actually opens a registration form inside modal window, which for some reason is not opening if you access it via an iframe, because if you put the url http://runebet.com/register/ directly in the iframe and load the page it will still be showing the landing page so it is redirecting but the modal is not popping up that leaves you with the last thing that you have to trigger the Register link click and that can only happen if you are in the same domain if not maybe someone else knows, i dont.

$(window.frames[0].frameElement.contentDocument).find('a[href="/register"]').trigger('click');


问:
gyp and node-pre-gyp fail when installing firebase with npm

I'm trying to install my dependencies with npm but installation fails when firebase installation comes in. I tried to install firebase individually with npm i firebase but it does not work. I removed the node_modules folder, cleaned the cache and install again but it does not work either.

The first error npm shows me is a 403 error code when downloading grpc-precompiled-binaries. I thinks this one is the main problem and in it depends the next errors but I'm not sure. Could someone tell me how to successfully install firebase with npm?

OUTPUT:

```<code>node-pre-gyp ERR! Tried to download(403): https://storage.googleapis.com/grpc-precompiled-binaries/node/grpc/v1.7.2/node-v57-linux-x64-musl.tar.gz
node-pre-gyp ERR! Pre-built binaries not found for grpc@1.7.2 and node@8.5.0 (node-v57 ABI, musl) (falling back to source compile with node-gyp)
node-pre-gyp http 403 status code downloading tarball https://storage.googleapis.com/grpc-precompiled-binaries/node/grpc/v1.7.2/node-v57-linux-x64-musl.tar.gz
gyp info it worked if it ends with ok
gyp info using node-gyp@3.6.2
gyp info using node@8.5.0 | linux | x64
gyp info ok
gyp info it worked if it ends with ok
gyp info using node-gyp@3.6.2
gyp info using node@8.5.0 | linux | x64
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
gyp ERR! stack     at PythonFinder.failNoPython (/app/node_modules/node-gyp/lib/configure.js:483:19)
gyp ERR! stack     at PythonFinder.<anonymous> (/app/node_modules/node-gyp/lib/configure.js:397:16)
gyp ERR! stack     at F (/app/node_modules/which/which.js:68:16)
gyp ERR! stack     at E (/app/node_modules/which/which.js:80:29)
gyp ERR! stack     at /app/node_modules/which/which.js:89:16
gyp ERR! stack     at /app/node_modules/isexe/index.js:42:5
gyp ERR! stack     at /app/node_modules/isexe/mode.js:8:5
gyp ERR! stack     at FSReqWrap.oncomplete (fs.js:153:21)
gyp ERR! System Linux 4.4.0-101-generic
gyp ERR! command "/usr/local/bin/node" "/app/node_modules/node-gyp/bin/node-gyp.js" "configure" "--fallback-to-build" "--library=static_library" "--module=/app/node_modules/grpc/src/node/extension_binary/node-v57-linux-x64-musl/grpc_node.node" "--module_name=grpc_node" "--module_path=/app/node_modules/grpc/src/node/extension_binary/node-v57-linux-x64-musl"
gyp ERR! cwd /app/node_modules/grpc
gyp ERR! node -v v8.5.0
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/bin/node /app/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --library=static_library --module=/app/node_modules/grpc/src/node/extension_binary/node-v57-linux-x64-musl/grpc_node.node --module_name=grpc_node --module_path=/app/node_modules/grpc/src/node/extension_binary/node-v57-linux-x64-musl' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/app/node_modules/grpc/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at emitTwo (events.js:125:13)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:213:7)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:927:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
node-pre-gyp ERR! System Linux 4.4.0-101-generic
node-pre-gyp ERR! command "/usr/local/bin/node" "/app/node_modules/grpc/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build" "--library=static_library"
node-pre-gyp ERR! cwd /app/node_modules/grpc
node-pre-gyp ERR! node -v v8.5.0
node-pre-gyp ERR! node-pre-gyp -v v0.6.39
node-pre-gyp ERR! not ok
Failed to execute '/usr/local/bin/node /app/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --library=static_library --module=/app/node_modules/grpc/src/node/extension_binary/node-v57-linux-x64-musl/grpc_node.node --module_name=grpc_node --module_path=/app/node_modules/grpc/src/node/extension_binary/node-v57-linux-x64-musl' (1)
npm info lifecycle grpc@1.7.2~install: Failed to exec install script
npm WARN codelyzer@3.2.2 requires a peer of @angular/compiler@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.
npm WARN codelyzer@3.2.2 requires a peer of @angular/core@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! grpc@1.7.2 install: `node-pre-gyp install --fallback-to-build --library=static_library`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the grpc@1.7.2 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
</code>```

Last part of log file

```<code>3366 info lifecycle protobufjs@5.0.2~install: protobufjs@5.0.2
3367 silly install grpc@1.7.2
3368 info lifecycle grpc@1.7.2~install: grpc@1.7.2
3369 verbose lifecycle grpc@1.7.2~install: unsafe-perm in lifecycle false
3370 verbose lifecycle grpc@1.7.2~install: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/app/node_modules/grpc/node_modules/.bin:/app/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
3371 verbose lifecycle grpc@1.7.2~install: CWD: /app/node_modules/grpc
3372 silly lifecycle grpc@1.7.2~install: Args: [ '-c',
3372 silly lifecycle   'node-pre-gyp install --fallback-to-build --library=static_library' ]
3373 silly lifecycle grpc@1.7.2~install: Returned: code: 1  signal: null
3374 info lifecycle grpc@1.7.2~install: Failed to exec install script
3375 verbose unlock done using /root/.npm/_locks/staging-bd3355550c5a469e.lock for /app/node_modules/.staging
3376 warn codelyzer@3.2.2 requires a peer of @angular/compiler@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.
3377 warn codelyzer@3.2.2 requires a peer of @angular/core@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.
3378 warn optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/fsevents):
3379 warn notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
3380 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Valid OS:    darwin
3380 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Valid Arch:  any
3380 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Actual OS:   linux
3380 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Actual Arch: x64
3381 verbose stack Error: grpc@1.7.2 install: `node-pre-gyp install --fallback-to-build --library=static_library`
3381 verbose stack Exit status 1
3381 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:289:16)
3381 verbose stack     at emitTwo (events.js:125:13)
3381 verbose stack     at EventEmitter.emit (events.js:213:7)
3381 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:40:14)
3381 verbose stack     at emitTwo (events.js:125:13)
3381 verbose stack     at ChildProcess.emit (events.js:213:7)
3381 verbose stack     at maybeClose (internal/child_process.js:927:16)
3381 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
3382 verbose pkgid grpc@1.7.2
3383 verbose cwd /app
3384 verbose Linux 4.4.0-101-generic
3385 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "i" "firebase"
3386 verbose node v8.5.0
3387 verbose npm  v5.3.0
3388 error code ELIFECYCLE
3389 error errno 1
3390 error grpc@1.7.2 install: `node-pre-gyp install --fallback-to-build --library=static_library`
3390 error Exit status 1
3391 error Failed at the grpc@1.7.2 install script.
3391 error This is probably not a problem with npm. There is likely additional logging output above.
3392 verbose exit [ 1, true ]
</code>```

ENV:

OS: Ubuntu 16.04

npm: 5.3.0

node: 8.5.0

答:
UPDATE:

This answer allowed me to get my app up and running inside my alpine container. Try running this code in your development environment. Hope this helps.

Ran into the same issue this morning. Looks like the precompiled grpc1.7.2 hasn't been uploaded for musl based distributions (alpine is musl vs glibc)

For the short term, to get your build going again, and until they upload the precompiled versions, try adding this to your dockerfile

```<code> apk update && apk upgrade &&
   apk add --no-cache python make g++
</code>```

python, make and g++ basically allow node-gyp to compile from source rather than >relying on the precompiled versions

I am running into the same problem while creating a docker image. I have noticed that when using the Linux-alpine node base image, that I get this error. However,
when using the standard node (I think Ubuntu 14.04) base image it works fine. What OS are you using? I hope you find a solution!

Body:
I'm trying to install my dependencies with npm but installation fails when firebase installation comes in. I tried to install firebase individually with npm i firebase but it does not work. I removed the node_modules folder, cleaned the cache and install again but it does not work either.

The first error npm shows me is a 403 error code when downloading grpc-precompiled-binaries. I thinks this one is the main problem and in it depends the next errors but I'm not sure. Could someone tell me how to successfully install firebase with npm?

OUTPUT:

node-pre-gyp ERR! Tried to download(403): https://storage.googleapis.com/grpc-precompiled-binaries/node/grpc/v1.7.2/node-v57-linux-x64-musl.tar.gz
node-pre-gyp ERR! Pre-built binaries not found for grpc@1.7.2 and node@8.5.0 (node-v57 ABI, musl) (falling back to source compile with node-gyp)
node-pre-gyp http 403 status code downloading tarball https://storage.googleapis.com/grpc-precompiled-binaries/node/grpc/v1.7.2/node-v57-linux-x64-musl.tar.gz
gyp info it worked if it ends with ok
gyp info using node-gyp@3.6.2
gyp info using node@8.5.0 | linux | x64
gyp info ok
gyp info it worked if it ends with ok
gyp info using node-gyp@3.6.2
gyp info using node@8.5.0 | linux | x64
gyp ERR! configure error
gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.
gyp ERR! stack     at PythonFinder.failNoPython (/app/node_modules/node-gyp/lib/configure.js:483:19)
gyp ERR! stack     at PythonFinder.<anonymous> (/app/node_modules/node-gyp/lib/configure.js:397:16)
gyp ERR! stack     at F (/app/node_modules/which/which.js:68:16)
gyp ERR! stack     at E (/app/node_modules/which/which.js:80:29)
gyp ERR! stack     at /app/node_modules/which/which.js:89:16
gyp ERR! stack     at /app/node_modules/isexe/index.js:42:5
gyp ERR! stack     at /app/node_modules/isexe/mode.js:8:5
gyp ERR! stack     at FSReqWrap.oncomplete (fs.js:153:21)
gyp ERR! System Linux 4.4.0-101-generic
gyp ERR! command "/usr/local/bin/node" "/app/node_modules/node-gyp/bin/node-gyp.js" "configure" "--fallback-to-build" "--library=static_library" "--module=/app/node_modules/grpc/src/node/extension_binary/node-v57-linux-x64-musl/grpc_node.node" "--module_name=grpc_node" "--module_path=/app/node_modules/grpc/src/node/extension_binary/node-v57-linux-x64-musl"
gyp ERR! cwd /app/node_modules/grpc
gyp ERR! node -v v8.5.0
gyp ERR! node-gyp -v v3.6.2
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/bin/node /app/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --library=static_library --module=/app/node_modules/grpc/src/node/extension_binary/node-v57-linux-x64-musl/grpc_node.node --module_name=grpc_node --module_path=/app/node_modules/grpc/src/node/extension_binary/node-v57-linux-x64-musl' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/app/node_modules/grpc/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at emitTwo (events.js:125:13)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:213:7)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:927:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
node-pre-gyp ERR! System Linux 4.4.0-101-generic
node-pre-gyp ERR! command "/usr/local/bin/node" "/app/node_modules/grpc/node_modules/.bin/node-pre-gyp" "install" "--fallback-to-build" "--library=static_library"
node-pre-gyp ERR! cwd /app/node_modules/grpc
node-pre-gyp ERR! node -v v8.5.0
node-pre-gyp ERR! node-pre-gyp -v v0.6.39
node-pre-gyp ERR! not ok
Failed to execute '/usr/local/bin/node /app/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --library=static_library --module=/app/node_modules/grpc/src/node/extension_binary/node-v57-linux-x64-musl/grpc_node.node --module_name=grpc_node --module_path=/app/node_modules/grpc/src/node/extension_binary/node-v57-linux-x64-musl' (1)
npm info lifecycle grpc@1.7.2~install: Failed to exec install script
npm WARN codelyzer@3.2.2 requires a peer of @angular/compiler@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.
npm WARN codelyzer@3.2.2 requires a peer of @angular/core@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/fsevents):
npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! grpc@1.7.2 install: `node-pre-gyp install --fallback-to-build --library=static_library`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the grpc@1.7.2 install script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

Last part of log file

3366 info lifecycle protobufjs@5.0.2~install: protobufjs@5.0.2
3367 silly install grpc@1.7.2
3368 info lifecycle grpc@1.7.2~install: grpc@1.7.2
3369 verbose lifecycle grpc@1.7.2~install: unsafe-perm in lifecycle false
3370 verbose lifecycle grpc@1.7.2~install: PATH: /usr/local/lib/node_modules/npm/bin/node-gyp-bin:/app/node_modules/grpc/node_modules/.bin:/app/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
3371 verbose lifecycle grpc@1.7.2~install: CWD: /app/node_modules/grpc
3372 silly lifecycle grpc@1.7.2~install: Args: [ '-c',
3372 silly lifecycle   'node-pre-gyp install --fallback-to-build --library=static_library' ]
3373 silly lifecycle grpc@1.7.2~install: Returned: code: 1  signal: null
3374 info lifecycle grpc@1.7.2~install: Failed to exec install script
3375 verbose unlock done using /root/.npm/_locks/staging-bd3355550c5a469e.lock for /app/node_modules/.staging
3376 warn codelyzer@3.2.2 requires a peer of @angular/compiler@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.
3377 warn codelyzer@3.2.2 requires a peer of @angular/core@^2.3.1 || >=4.0.0-beta <5.0.0 but none was installed.
3378 warn optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.1.3 (node_modules/fsevents):
3379 warn notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.3: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})
3380 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Valid OS:    darwin
3380 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Valid Arch:  any
3380 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Actual OS:   linux
3380 verbose notsup SKIPPING OPTIONAL DEPENDENCY: Actual Arch: x64
3381 verbose stack Error: grpc@1.7.2 install: `node-pre-gyp install --fallback-to-build --library=static_library`
3381 verbose stack Exit status 1
3381 verbose stack     at EventEmitter.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/lifecycle.js:289:16)
3381 verbose stack     at emitTwo (events.js:125:13)
3381 verbose stack     at EventEmitter.emit (events.js:213:7)
3381 verbose stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/npm/lib/utils/spawn.js:40:14)
3381 verbose stack     at emitTwo (events.js:125:13)
3381 verbose stack     at ChildProcess.emit (events.js:213:7)
3381 verbose stack     at maybeClose (internal/child_process.js:927:16)
3381 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)
3382 verbose pkgid grpc@1.7.2
3383 verbose cwd /app
3384 verbose Linux 4.4.0-101-generic
3385 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "i" "firebase"
3386 verbose node v8.5.0
3387 verbose npm  v5.3.0
3388 error code ELIFECYCLE
3389 error errno 1
3390 error grpc@1.7.2 install: `node-pre-gyp install --fallback-to-build --library=static_library`
3390 error Exit status 1
3391 error Failed at the grpc@1.7.2 install script.
3391 error This is probably not a problem with npm. There is likely additional logging output above.
3392 verbose exit [ 1, true ]

ENV:

OS: Ubuntu 16.04

npm: 5.3.0

node: 8.5.0

Body:
UPDATE:

This answer allowed me to get my app up and running inside my alpine container. Try running this code in your development environment. Hope this helps.

Ran into the same issue this morning. Looks like the precompiled grpc1.7.2 hasn't been uploaded for musl based distributions (alpine is musl vs glibc)

For the short term, to get your build going again, and until they upload the precompiled versions, try adding this to your dockerfile

 apk update && apk upgrade &&
   apk add --no-cache python make g++

python, make and g++ basically allow node-gyp to compile from source rather than >relying on the precompiled versions

I am running into the same problem while creating a docker image. I have noticed that when using the Linux-alpine node base image, that I get this error. However,
when using the standard node (I think Ubuntu 14.04) base image it works fine. What OS are you using? I hope you find a solution!


问:
How can I have a constrained Finite State Machine in Haskell / Idris?
EDIT: Users @apocalisp and @BenjaminHodgson left awesome answers below, skip reading most of the question and jump to their answers.

TLDR of the Question: How can I go from the first picture, where FSM states combinatorial explode, to the second picture, where you're just required to visit all of them before moving on.

I would like to build a Finite State Machine (in Haskell really, but I'm trying Idris first to see if it can guide my Haskell) where there are some interim states that must be visited before a final state can be reached. It'd be great if I could arbitrarily constrain the FSM with predicates on some state.

In the following picture, there's an Initial state, 3 interim states A, B, C, and a Final state. If I'm not mistaken, in a "normal" FSM, you will always need n! interim states to represent each combination of possible paths.

This is undesirable.

Instead, using Type Families, and maybe Dependent types, I think it should be possible to have a sort of state that is carried around, and only when it passes certain predicates will you be allowed to travel to the final state. (Does that make it Push Down Automata instead of FSM?)

My code so far (idris), which by analogy, is adding ingredients to make a salad, and the order doesn't matter, but they all need to make it in:

```<code>data SaladState = Initial | AddingIngredients | ReadyToEat

record SaladBowl where
       constructor MkSaladBowl
       lettuce, tomato, cucumber : Bool

data HasIngredient : (ingredient : SaladBowl -> Bool) -> (bowl : SaladBowl ** ingredient bowl = True) -> Type where
     Bowl : HasIngredient ingredient bowl

data HasIngredients : (ingredients : List (SaladBowl -> Bool))
                     -> (bowl : SaladBowl ** (foldl (&&) True (map (\i => i bowl) ingredients) = True))
                     -> Type where
     Bowlx : HasIngredients ingredients bowl

data SaladAction : (ty : Type) -> SaladState -> (ty -> SaladState) -> Type where
     GetBowl     : SaladAction SaladBowl Initial (const Initial)
     AddLettuce  : SaladBowl -> SaladAction (bowl ** HasIngredient lettuce bowl)  st (const AddingIngredients)
     AddTomato   : SaladBowl -> SaladAction (bowl ** HasIngredient tomato bowl)   st (const AddingIngredients)
     AddCucumber : SaladBowl -> SaladAction (bowl ** HasIngredient cucumber bowl) st (const AddingIngredients)
     MixItUp     : SaladBowl -> SaladAction (bowl ** (HasIngredients [lettuce, tomato, cucumber] bowl)) AddingIngredients (const ReadyToEat)
     Pure : (res : ty) -> SaladAction ty (state_fn res) state_fn
     (>>=) : SaladAction a state1 state2_fn
           -> ((res : a) -> SaladAction b (state2_fn res) state3_fn)
           -> SaladAction b state1 state3_fn

emptyBowl : SaladBowl
emptyBowl = MkSaladBowl False False False

prepSalad1 : SaladAction SaladBowl Initial (const ReadyToEat)
prepSalad1 = do
           (b1 ** _) <- AddTomato emptyBowl
           (b2 ** _) <- AddLettuce b1
           (b3 ** _) <- AddCucumber b2
           MixItUp b3
</code>```

And counter example programs that the compiler should error on:

```<code>BAD : SaladAction SaladBowl Initial (const ReadyToEat)
BAD = do
           (b1 ** _) <- AddTomato emptyBowl
           (b2 ** _) <- AddTomato emptyBowl
           (b3 ** _) <- AddLettuce b2
           (b4 ** _) <- AddCucumber b3
           MixItUp b4

BAD' : SaladAction SaladBowl Initial (const ReadyToEat)
BAD' = do
           (b1 ** _) <- AddTomato emptyBowl
           MixItUp b1
</code>```

I eventually want the "ingredients" to be Sums instead of Bools (data Lettuce = Romaine | Iceberg | Butterhead), and more robust semantics where I can say things like "you must first add lettuce, or spinach, but not both".

Really, I feel so quite thoroughly lost, that I imagine my above code has gone in the completely wrong direction... How can I build this FSM (PDA?) to preclude bad programs? I'd especially like to use Haskell for it, perhaps using Indexed Monads?

答:
Your question is a little vague, but I read it as "how can I incrementally build a heterogeneous 'context' and create a record once I have values of the correct types in scope?" Here's how I'd skin this particular cat: rather than threading input and output types through some monadic context, let's just work with ordinary functions. If you want to use clever type-level machinery, you can use it with the values you pass around, rather than structure your program around a particular notion of computation.

Enough waffling. I'm going to represent a heterogeneous context as a nested tuple. I'll use the unit (()) to represent an empty context, and I'll add types to the context by nesting the context into the left element of a new tuple. So, a context containing an Int, a Bool and a Char looks like this:

```<code>type IntBoolChar = ((((), Int), Bool), Char)
</code>```

Hopefully you can see how you'd incrementally add ingredients to a salad bowl:

```<code>-- we will *not* be using this type like a state monad
addLettuce :: a -> (a, Lettuce)
addLettuce = (, Romaine)

addOlives :: a -> (a, Olive)
addOlives = (, Kalamata)

addCheese :: a -> (a, Cheese)
addCheese = (, Feta)

addGreekSaladIngredients :: a -> (((a, Lettuce), Olive), Cheese)
-- yes, i know you also need tomatoes and onions for a Greek salad. i'm trying to keep the example short
addGreekSaladIngredients = addCheese . addOlives . addLettuce
</code>```

This is not advanced type magic. It'll work in any language with tuples. I've even designed real-world APIs around this idea in C#, to partially compensate for C#'s lack of currying when you might use Applicative syntax in Haskell. Here's an example from my parser combinator library: starting with an empty permutation parser, you Add a number of atomic parsers of different types, and then Build a parser which runs those parsers in an order-insensitive manner, returning a nested tuple of their results which you can then flatten by hand.

The other half of the question was about turning a value of this sort of context into a record.

```<code>data Salad = Salad {
    _lettuce :: Lettuce,
    _olive :: Olive,
    _cheese :: Cheese
}
</code>```

You can generically map nested tuples onto a record like this in an order-insensitive way using the following simple class:

```<code>class Has a s where
    has :: Lens' s a

-- this kind of function can be written generically using TH or Generics
toSalad :: (Has Lettuce s, Has Olive s, Has Cheese s) => s -> Salad
toSalad x = Salad (x^.has) (x^.has) (x^.has)
</code>```

(This is a straightforward generalisation of the HasX classes that lens generates with Template Haskell.)

The only part which requires some type cleverness is automatically instantiating Has for nested tuples. We need to distinguish between two cases: either an item of the type we're looking for is on the right of a pair, or it's somewhere inside the nested tuple on the left of the pair. The problem is that under ordinary circumstances these two cases look the same to the elaborator: instance resolution occurs by a simple-minded process of syntactic type matching; type equalities aren't inspected and backtracking doesn't happen.

The upshot is that we need The Advanced Overlap Trick. Briefly, the trick uses a closed type family to dispatch a type class based on a type equality. We're choosing between two alternatives, so this is one of the few cases when a type-level boolean is acceptable.

```<code>type family Here a as where
    Here a (_, a) = True
    Here a (_, b) = False

class Has' (here :: Bool) a s where
    has' :: Proxy here -> Lens' s a

instance Has' True a (as, a) where
    has' _ = _2
instance Has a as => Has' False a (as, b) where
    has' _ = _1.has

instance Has' (Here a (as, b)) a (as, b) => Has a (as, b) where
    has = has' (Proxy :: Proxy (Here a (as, b)))
</code>```

This program will stop the search at the first matching type. If you need two different types of lettuce in your salad, you'll have to wrap one in a newtype. In practice, when you combine this disadvantage with the complexity of the overlapping instances, I'm not convinced the Has abstraction pays its way. I'd just flatten the tuple by hand:

```<code>toSalad :: (((a, Lettuce), Olive), Cheese) -> Salad
toSalad (((_, l), o), c) = Salad l o c
</code>```

You do lose order-insensitivity though.

Here's an example usage:

```<code>greekSalad = toSalad $ addGreekSaladIngredients ()

ghci> greekSalad
Salad {_lettuce = Romaine, _olive = Kalamata, _cheese = Feta}  -- after deriving Show
</code>```

And here's the completed program

```<code>{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE ScopedTypeVariables #-}

import Control.Lens hiding (has, has')
import Data.Proxy

data Lettuce = Romaine deriving (Show)
data Olive = Kalamata deriving (Show)
data Cheese = Feta deriving (Show)

data Salad = Salad {
    _lettuce :: Lettuce,
    _olive :: Olive,
    _cheese :: Cheese
} deriving (Show)

-- we will *not* be using this type like a state monad
addLettuce :: a -> (a, Lettuce) -- <<< Tuple Sections
addLettuce = (, Romaine)

addOlives :: a -> (a, Olive)
addOlives = (, Kalamata)

addCheese :: a -> (a, Cheese)
addCheese = (, Feta)

addGreekSaladIngredients :: a -> (((a, Lettuce), Olive), Cheese)
addGreekSaladIngredients = addCheese . addOlives . addLettuce

class Has a s where
  has :: Lens' s a

type family Here a as where
    Here a (_, a) = True
    Here a (_, b) = False

class Has' (here :: Bool) a s where
    has' :: Proxy here -> Lens' s a

instance Has' True a (as, a) where
    has' _ = _2

instance Has a as => Has' False a (as, b) where
    has' _ = _1.has

instance  Has' (Here a (as, b)) a (as, b) => Has a (as, b) where -- <<< Undecidable Instances
    has = has' (Proxy :: Proxy (Here a (as, b)))

toSalad :: (Has Lettuce s, Has Olive s, Has Cheese s) => s -> Salad
toSalad x = Salad (x ^. has) (x ^. has) (x ^. has)

greekSalad = toSalad $ addGreekSaladIngredients ()

-- nonSaladsError = toSalad $ (addCheese . addOlives) ()
</code>```

Body:
EDIT: Users @apocalisp and @BenjaminHodgson left awesome answers below, skip reading most of the question and jump to their answers.

TLDR of the Question: How can I go from the first picture, where FSM states combinatorial explode, to the second picture, where you're just required to visit all of them before moving on.

I would like to build a Finite State Machine (in Haskell really, but I'm trying Idris first to see if it can guide my Haskell) where there are some interim states that must be visited before a final state can be reached. It'd be great if I could arbitrarily constrain the FSM with predicates on some state.

In the following picture, there's an Initial state, 3 interim states A, B, C, and a Final state. If I'm not mistaken, in a "normal" FSM, you will always need n! interim states to represent each combination of possible paths.

This is undesirable.

Instead, using Type Families, and maybe Dependent types, I think it should be possible to have a sort of state that is carried around, and only when it passes certain predicates will you be allowed to travel to the final state. (Does that make it Push Down Automata instead of FSM?)

My code so far (idris), which by analogy, is adding ingredients to make a salad, and the order doesn't matter, but they all need to make it in:

data SaladState = Initial | AddingIngredients | ReadyToEat

record SaladBowl where
       constructor MkSaladBowl
       lettuce, tomato, cucumber : Bool

data HasIngredient : (ingredient : SaladBowl -> Bool) -> (bowl : SaladBowl ** ingredient bowl = True) -> Type where
     Bowl : HasIngredient ingredient bowl

data HasIngredients : (ingredients : List (SaladBowl -> Bool))
                     -> (bowl : SaladBowl ** (foldl (&&) True (map (\i => i bowl) ingredients) = True))
                     -> Type where
     Bowlx : HasIngredients ingredients bowl

data SaladAction : (ty : Type) -> SaladState -> (ty -> SaladState) -> Type where
     GetBowl     : SaladAction SaladBowl Initial (const Initial)
     AddLettuce  : SaladBowl -> SaladAction (bowl ** HasIngredient lettuce bowl)  st (const AddingIngredients)
     AddTomato   : SaladBowl -> SaladAction (bowl ** HasIngredient tomato bowl)   st (const AddingIngredients)
     AddCucumber : SaladBowl -> SaladAction (bowl ** HasIngredient cucumber bowl) st (const AddingIngredients)
     MixItUp     : SaladBowl -> SaladAction (bowl ** (HasIngredients [lettuce, tomato, cucumber] bowl)) AddingIngredients (const ReadyToEat)
     Pure : (res : ty) -> SaladAction ty (state_fn res) state_fn
     (>>=) : SaladAction a state1 state2_fn
           -> ((res : a) -> SaladAction b (state2_fn res) state3_fn)
           -> SaladAction b state1 state3_fn

emptyBowl : SaladBowl
emptyBowl = MkSaladBowl False False False

prepSalad1 : SaladAction SaladBowl Initial (const ReadyToEat)
prepSalad1 = do
           (b1 ** _) <- AddTomato emptyBowl
           (b2 ** _) <- AddLettuce b1
           (b3 ** _) <- AddCucumber b2
           MixItUp b3

And counter example programs that the compiler should error on:

BAD : SaladAction SaladBowl Initial (const ReadyToEat)
BAD = do
           (b1 ** _) <- AddTomato emptyBowl
           (b2 ** _) <- AddTomato emptyBowl
           (b3 ** _) <- AddLettuce b2
           (b4 ** _) <- AddCucumber b3
           MixItUp b4

BAD' : SaladAction SaladBowl Initial (const ReadyToEat)
BAD' = do
           (b1 ** _) <- AddTomato emptyBowl
           MixItUp b1

I eventually want the "ingredients" to be Sums instead of Bools (data Lettuce = Romaine | Iceberg | Butterhead), and more robust semantics where I can say things like "you must first add lettuce, or spinach, but not both".

Really, I feel so quite thoroughly lost, that I imagine my above code has gone in the completely wrong direction... How can I build this FSM (PDA?) to preclude bad programs? I'd especially like to use Haskell for it, perhaps using Indexed Monads?

Body:
Your question is a little vague, but I read it as "how can I incrementally build a heterogeneous 'context' and create a record once I have values of the correct types in scope?" Here's how I'd skin this particular cat: rather than threading input and output types through some monadic context, let's just work with ordinary functions. If you want to use clever type-level machinery, you can use it with the values you pass around, rather than structure your program around a particular notion of computation.

Enough waffling. I'm going to represent a heterogeneous context as a nested tuple. I'll use the unit (()) to represent an empty context, and I'll add types to the context by nesting the context into the left element of a new tuple. So, a context containing an Int, a Bool and a Char looks like this:

type IntBoolChar = ((((), Int), Bool), Char)

Hopefully you can see how you'd incrementally add ingredients to a salad bowl:

-- we will *not* be using this type like a state monad
addLettuce :: a -> (a, Lettuce)
addLettuce = (, Romaine)

addOlives :: a -> (a, Olive)
addOlives = (, Kalamata)

addCheese :: a -> (a, Cheese)
addCheese = (, Feta)

addGreekSaladIngredients :: a -> (((a, Lettuce), Olive), Cheese)
-- yes, i know you also need tomatoes and onions for a Greek salad. i'm trying to keep the example short
addGreekSaladIngredients = addCheese . addOlives . addLettuce

This is not advanced type magic. It'll work in any language with tuples. I've even designed real-world APIs around this idea in C#, to partially compensate for C#'s lack of currying when you might use Applicative syntax in Haskell. Here's an example from my parser combinator library: starting with an empty permutation parser, you Add a number of atomic parsers of different types, and then Build a parser which runs those parsers in an order-insensitive manner, returning a nested tuple of their results which you can then flatten by hand.

The other half of the question was about turning a value of this sort of context into a record.

data Salad = Salad {
    _lettuce :: Lettuce,
    _olive :: Olive,
    _cheese :: Cheese
}

You can generically map nested tuples onto a record like this in an order-insensitive way using the following simple class:

class Has a s where
    has :: Lens' s a

-- this kind of function can be written generically using TH or Generics
toSalad :: (Has Lettuce s, Has Olive s, Has Cheese s) => s -> Salad
toSalad x = Salad (x^.has) (x^.has) (x^.has)

(This is a straightforward generalisation of the HasX classes that lens generates with Template Haskell.)

The only part which requires some type cleverness is automatically instantiating Has for nested tuples. We need to distinguish between two cases: either an item of the type we're looking for is on the right of a pair, or it's somewhere inside the nested tuple on the left of the pair. The problem is that under ordinary circumstances these two cases look the same to the elaborator: instance resolution occurs by a simple-minded process of syntactic type matching; type equalities aren't inspected and backtracking doesn't happen.

The upshot is that we need The Advanced Overlap Trick. Briefly, the trick uses a closed type family to dispatch a type class based on a type equality. We're choosing between two alternatives, so this is one of the few cases when a type-level boolean is acceptable.

type family Here a as where
    Here a (_, a) = True
    Here a (_, b) = False

class Has' (here :: Bool) a s where
    has' :: Proxy here -> Lens' s a

instance Has' True a (as, a) where
    has' _ = _2
instance Has a as => Has' False a (as, b) where
    has' _ = _1.has

instance Has' (Here a (as, b)) a (as, b) => Has a (as, b) where
    has = has' (Proxy :: Proxy (Here a (as, b)))

This program will stop the search at the first matching type. If you need two different types of lettuce in your salad, you'll have to wrap one in a newtype. In practice, when you combine this disadvantage with the complexity of the overlapping instances, I'm not convinced the Has abstraction pays its way. I'd just flatten the tuple by hand:

toSalad :: (((a, Lettuce), Olive), Cheese) -> Salad
toSalad (((_, l), o), c) = Salad l o c

You do lose order-insensitivity though.

Here's an example usage:

greekSalad = toSalad $ addGreekSaladIngredients ()

ghci> greekSalad
Salad {_lettuce = Romaine, _olive = Kalamata, _cheese = Feta}  -- after deriving Show

And here's the completed program

{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE TupleSections #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE ScopedTypeVariables #-}

import Control.Lens hiding (has, has')
import Data.Proxy

data Lettuce = Romaine deriving (Show)
data Olive = Kalamata deriving (Show)
data Cheese = Feta deriving (Show)

data Salad = Salad {
    _lettuce :: Lettuce,
    _olive :: Olive,
    _cheese :: Cheese
} deriving (Show)

-- we will *not* be using this type like a state monad
addLettuce :: a -> (a, Lettuce) -- <<< Tuple Sections
addLettuce = (, Romaine)

addOlives :: a -> (a, Olive)
addOlives = (, Kalamata)

addCheese :: a -> (a, Cheese)
addCheese = (, Feta)

addGreekSaladIngredients :: a -> (((a, Lettuce), Olive), Cheese)
addGreekSaladIngredients = addCheese . addOlives . addLettuce

class Has a s where
  has :: Lens' s a

type family Here a as where
    Here a (_, a) = True
    Here a (_, b) = False

class Has' (here :: Bool) a s where
    has' :: Proxy here -> Lens' s a

instance Has' True a (as, a) where
    has' _ = _2

instance Has a as => Has' False a (as, b) where
    has' _ = _1.has

instance  Has' (Here a (as, b)) a (as, b) => Has a (as, b) where -- <<< Undecidable Instances
    has = has' (Proxy :: Proxy (Here a (as, b)))

toSalad :: (Has Lettuce s, Has Olive s, Has Cheese s) => s -> Salad
toSalad x = Salad (x ^. has) (x ^. has) (x ^. has)

greekSalad = toSalad $ addGreekSaladIngredients ()

-- nonSaladsError = toSalad $ (addCheese . addOlives) ()


问:
Serverless, node and Hummus. Compiling a binary does not work
I'm trying to use HummusJS on a Lambda function using the Serverless framework for deployment.

The Hummus npm library needs a binary compiled to function. This (hummus.node) is provided in its node_modules folder. However when I require 'hummus' the library is throwing a bug.

const hummus = require('hummus');

module.exports.stamp = (event, context, callback) => {
    const response = {
        statusCode: 200,
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Credentials': true,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ url: 'url' })
    };
    callback(null, response);
};```

module initialization error: Error at Error (native) at
  Object.Module._extensions..node (module.js:597:18) at Module.load
  (module.js:487:32) at tryModuleLoad (module.js:446:12) at
  Function.Module._load (module.js:438:3) at Module.require
  (module.js:497:17) at require (internal/module.js:20:19) at
  Object.
  (/var/task/pdf-manipulator/node_modules/hummus/hummus.js:5:31) at
  Module._compile (module.js:570:32) at Object.Module._extensions..js
  (module.js:579:10)

答:
I used docker-lambda to build the binary and then copied it over to '/node_modules/hummus/bindings/hummus.node'.

https://github.com/lambci/docker-lambda

I could then run the app in docker-lambda which reproduced the lambda environment.

Body:
I'm trying to use HummusJS on a Lambda function using the Serverless framework for deployment.

The Hummus npm library needs a binary compiled to function. This (hummus.node) is provided in its node_modules folder. However when I require 'hummus' the library is throwing a bug.

const hummus = require('hummus');

module.exports.stamp = (event, context, callback) => {
    const response = {
        statusCode: 200,
        headers: {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Credentials': true,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ url: 'url' })
    };
    callback(null, response);
};

module initialization error: Error at Error (native) at
  Object.Module._extensions..node (module.js:597:18) at Module.load
  (module.js:487:32) at tryModuleLoad (module.js:446:12) at
  Function.Module._load (module.js:438:3) at Module.require
  (module.js:497:17) at require (internal/module.js:20:19) at
  Object.
  (/var/task/pdf-manipulator/node_modules/hummus/hummus.js:5:31) at
  Module._compile (module.js:570:32) at Object.Module._extensions..js
  (module.js:579:10)


问:
Facebook Pixel Event ViewContent not firing properly on Product Page Shopify
I'm trying to figure out why my facebook event "ViewContent" is not firing properly. When I visit any product page, I can see the facebook pixel helper load the viewcontent, but after the page is done loading all the scripts it disappears.
Upon page refresh it will show the event being fired. Which is weird.
It also keeps throwing a duplicate ID in my console whereas I do not have a duplicate ID anywhere else.

My ID is pasted in the online store > preferences > Facebook Pixel

```<code><!-- Additional Scripts -->
   {% if first_time_accessed %}
   <script>
    fbq('trackSingle', 'XXXXXXXXXXXXX48', 'Purchase', {
     content_type: 'product',
     value: '{{ total_price | money_without_currency }}',
     currency: '{{ shop.currency }}'
     });
   </script>
   {%endif%}
<!-- end additional Scripts -->
<!-- code in product.liquid-->
   <!-- FB -->
    <script type="text/javascript">
      $( '#AddToCartForm' ).submit(function() {
        var customVal = $(this).find('#AddToCart').attr('data-price');
        fbq('track', 'AddToCart', {
         content_ids: [{% for item in cart.items %}'{{item.variant_id}}',{% endfor %}],
         content_type: 'product',
         value: customVal,
         currency: 'USD'
         });
       });
   </script>
  <!-- fb -->
</code>```

If you visit the site www.gurunanda.com and use the facebook pixel helper tool it'll show view content is loading on a product page but disappears after everything is fully loaded. It also shows dual firing of events. Such as addtocart and viewContent (once product page is reloaded).

答:
Its possible view ViewContentdata.

However, you have duplicate Pixel on the page. (Pixel ID: 1598023190518448)

Check your console, and review all facebook pixel entries

Body:
I'm trying to figure out why my facebook event "ViewContent" is not firing properly. When I visit any product page, I can see the facebook pixel helper load the viewcontent, but after the page is done loading all the scripts it disappears.
Upon page refresh it will show the event being fired. Which is weird.
It also keeps throwing a duplicate ID in my console whereas I do not have a duplicate ID anywhere else.

My ID is pasted in the online store > preferences > Facebook Pixel

   {% if first_time_accessed %}

   {%endif%}

If you visit the site www.gurunanda.com and use the facebook pixel helper tool it'll show view content is loading on a product page but disappears after everything is fully loaded. It also shows dual firing of events. Such as addtocart and viewContent (once product page is reloaded).


问:
Error: Resource name 'foo' does not match 'projects/*/agent'
I'm trying to create a new Entity on DialogFlow:

```<code>const dialogflow = require('dialogflow');

/**
 * trains the NLP to recognize language constructs
 */
export function intTraining() {

  const ENTITY_DEFINITION_BOOLEAN = {
    parent: 'foo',
    entityType: {
      displayName: 'myBoolean',
      kind: 'KIND_MAP',
      autoExpansionMode: 'AUTO_EXPANSION_MODE_UNSPECIFIED',
      entities: [
        {value: 'true',  synonyms: [ 'yes', 'yeah', 'sure', 'okay' ]},
        {value: 'false', synonyms: [ 'no', 'no thanks', 'never' ]}
      ],
    },
  };

  // allocate
  const entityTypesClient = new dialogflow.EntityTypesClient();
  // declare promises
  const promises = [];
  // allocate entities
  prepareEntity(entityTypesClient, promises, ENTITY_DEFINITION_BOOLEAN);
  // execute state initialization
  Promise.all(promises);
}

/** Buffers an Entity onto the Promise Queue. */
function prepareEntity(entityTypesClient, promises, definition) {
  // boolean entity
  promises.push(entityTypesClient
    .createEntityType(definition)
    .then(responses => { })
    .catch(err => { console.error('', err) })
  );
}
</code>```

When I execute this code, however, I receive the following error:

Error: Resource name 'foo' does not match 'projects/*/agent'.

I've already used gcloud auth application-default login to create API access credentials on my machine, with foo configured as the currently selected project, but this hasn't helped.

What am I doing wrong?

答:
You need to include the full path to your Dialogflow agent in the create entity request because you account may have access to more than one agent.  The Dialogflow v2 Node.js library (which you seem to be using) has a helper method to construct the agent path for you using your agent's project ID (which can be found in your Dialogflow agent's settings).  Here is an modified excerpt of code from Dialogflow's v2 Node.js samples that shows how to construct and make a create entity type request:

// Imports the Dialogflow library
const dialogflow = require('dialogflow');

// Instantiates clients
const entityTypesClient = new dialogflow.EntityTypesClient();
const intentsClient = new dialogflow.IntentsClient();

// The path to the agent the created entity type belongs to.
const agentPath = intentsClient.projectAgentPath(projectId);

// Create an entity type named "size", with possible values of small, medium
// and large and some synonyms.
const sizeRequest = {
  parent: agentPath,
  entityType: {
    displayName: 'size',
    entities: [
      {value: 'small', synonyms: ['small', 'petit']},
      {value: 'medium', synonyms: ['medium']},
      {value: 'large', synonyms: ['large', 'big']},
    ],
  },
};

entityTypesClient.createEntityType(sizeRequest)
  .then(responses => {
    console.log('Created size entity type:');
    logEntityType(responses[0]);
  })
  .catch(err => {
    console.error('Failed to create size entity type:', err);
  })
);
```

Body:
I'm trying to create a new Entity on DialogFlow:

const dialogflow = require('dialogflow');

/**
 * trains the NLP to recognize language constructs
 */
export function intTraining() {

  const ENTITY_DEFINITION_BOOLEAN = {
    parent: 'foo',
    entityType: {
      displayName: 'myBoolean',
      kind: 'KIND_MAP',
      autoExpansionMode: 'AUTO_EXPANSION_MODE_UNSPECIFIED',
      entities: [
        {value: 'true',  synonyms: [ 'yes', 'yeah', 'sure', 'okay' ]},
        {value: 'false', synonyms: [ 'no', 'no thanks', 'never' ]}
      ],
    },
  };

  // allocate
  const entityTypesClient = new dialogflow.EntityTypesClient();
  // declare promises
  const promises = [];
  // allocate entities
  prepareEntity(entityTypesClient, promises, ENTITY_DEFINITION_BOOLEAN);
  // execute state initialization
  Promise.all(promises);
}

/** Buffers an Entity onto the Promise Queue. */
function prepareEntity(entityTypesClient, promises, definition) {
  // boolean entity
  promises.push(entityTypesClient
    .createEntityType(definition)
    .then(responses => { })
    .catch(err => { console.error('', err) })
  );
}

When I execute this code, however, I receive the following error:

Error: Resource name 'foo' does not match 'projects/*/agent'.

I've already used gcloud auth application-default login to create API access credentials on my machine, with foo configured as the currently selected project, but this hasn't helped.

What am I doing wrong?


问:
JaCoCo and MR Jars
There is an issue with JaCoCo and the MultiRelease JAR files. Since the same class name exist on two places, JaCoCo complains:

```<code>Caused by: java.lang.IllegalStateException: Can't add different class with same name: jodd/core/JavaBridge
        at org.jacoco.core.analysis.CoverageBuilder.visitCoverage(CoverageBuilder.java:107)
        at org.jacoco.core.analysis.Analyzer$1.visitEnd(Analyzer.java:96)
</code>```

How we can tell JaCoCo (in Gradle) to skip the classes from META-INF path? OR to behave like it should (use correct class and ignoring other versions), depending on JVM version?

答:
JaCoCo doesn't yet provide support for Java 9 Multi-Release JAR Files.

This seems to be in their plans though as tracked at jacoco/issues#407.

Title: JaCoCo and MR Jars

Body:
There is an issue with JaCoCo and the MultiRelease JAR files. Since the same class name exist on two places, JaCoCo complains:

Caused by: java.lang.IllegalStateException: Can't add different class with same name: jodd/core/JavaBridge
        at org.jacoco.core.analysis.CoverageBuilder.visitCoverage(CoverageBuilder.java:107)
        at org.jacoco.core.analysis.Analyzer$1.visitEnd(Analyzer.java:96)

How we can tell JaCoCo (in Gradle) to skip the classes from META-INF path? OR to behave like it should (use correct class and ignoring other versions), depending on JVM version?


问:
How to code a conditional program in Excel VBA
I would like to run a program if a value of a certain cell change.

For example, if the value of cell E9 changes then run the following program:

```<code>Sub macrorepeatsolveNRTL()

Dim count As Long
count = 3
Do While count <= 203
    SolverOk SetCell:=Sheets("ParametersNRTL").Cells(count, 27),
    MaxMinVal:=3, ValueOf:=1, ByChange:=Sheets("ParametersNRTL").Cells(count, 12)
SolverSolve UserFinish:=True
count = count + 1
Loop
End Sub
</code>```

答:
Put this into the code module of the worksheet that has the "E9" cell you are watching.</p>

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = Range("E9").Address Then
        Call macrorepeatsolveNRTL
    End If
End Sub
</code>```

Body:
I would like to run a program if a value of a certain cell change.

For example, if the value of cell E9 changes then run the following program:

Sub macrorepeatsolveNRTL()

Dim count As Long
count = 3
Do While count <= 203
    SolverOk SetCell:=Sheets("ParametersNRTL").Cells(count, 27),
    MaxMinVal:=3, ValueOf:=1, ByChange:=Sheets("ParametersNRTL").Cells(count, 12)
SolverSolve UserFinish:=True
count = count + 1
Loop
End Sub

Body:
Put this into the code module of the worksheet that has the "E9" cell you are watching.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address = Range("E9").Address Then
        Call macrorepeatsolveNRTL
    End If
End Sub


问:
How do I get from a type to the TryParse method?
My particular problem:

I have a string which specifies an aribitrary type in a configuration class

Config.numberType = "System.Foo";

where Foo is a type like Decimal or Double

I use Type.GetType(Config.numberType) to return the corresponding type.

How do I get from that type to being able to use, System.Foo.TryParse() ?

Some further related queries

TryParse() can be accessed from System.Foo.TryParse() as well as foo.TryParse(). Does this mean foo is some kind of class in C#? This seems weird to me that int, double etc are actually not just modifier keywords.

How can you declare variables under these circumstances? - var is not universally usable it seems i.e. only in local scope etc.

答:
As many have said - there isn't a direct route. I expect one close option is TypeConverter:

```<code>    Type type = typeof(double);
    string text = "123.45";

    object value = TypeDescriptor.GetConverter(type)
        .ConvertFromInvariantString(text);
</code>```

Of course, you may need try/catch to handle exceptions. Such is life.

OwnerDisplayName: Brendan

Body:
As many have said - there isn't a direct route. I expect one close option is TypeConverter:

    Type type = typeof(double);
    string text = "123.45";

    object value = TypeDescriptor.GetConverter(type)
        .ConvertFromInvariantString(text);

Of course, you may need try/catch to handle exceptions. Such is life.

OwnerDisplayName: Marc Gravell