问:
Multiple options menu showing up on app bar
Let me add more context:

I run bottom view navigation with a ViewPager2. For all 4 of my tab/fragments of my bottom navigation view I have an options menu which I created separately dynamically in each fragment.

Now, when we navigate through the app, it behaves correctly as every options menu is displayed ONLY for their respective fragment.

Problem is: Only when the app is launched, all the options menus from all the the 4 fragments show up on the start destination fragment's tab. BUT, once we swipe and swipe back, only the start destinations options menu is shown on the app bar. As is for every of the other 3 fragment/tabs.

Theory: I think it has something to do with onCreateOptionsMenu which is called when all four fragments are also created to which they share an app bar.

Is anybody familiar with this type of issue? Here is my PagerAdapters code for my ViewPager:

```<code>const val F1_PAGE_INDEX = 0
const val F2_PAGE_INDEX = 1
const val F3_PAGE_INDEX = 2
const val F4_PAGE_INDEX = 3

class PagerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {

    /**
     * Mapping of the ViewPager page indexes to their respective Fragments
     */
    private val tabFragmentsCreators: Map<Int, () -> Fragment> = mapOf(
        F1_PAGE_INDEX to { FirstFragment() },
        F2_PAGE_INDEX to { SecondFragment() },
        F3_PAGE_INDEX to { ThirdFragment() },
        F4_PAGE_INDEX to { FourthFragment() }
    )

    override fun getItemCount() = tabFragmentsCreators.size

    override fun createFragment(position: Int): Fragment {
        return tabFragmentsCreators[position]?.invoke() ?: throw IndexOutOfBoundsException()
    }

}
</code>```

Here is also my Home View Pager Fragment where I create my bottom Navigation and affect to to the main fragments:

```<code>class HomeViewPagerFragment(): Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val binding = FragmentViewPagerBinding.inflate(inflater, container, false)

        val viewPager = binding.viewPager

        viewPager.isUserInputEnabled = false

        viewPager.adapter = PagerAdapter(this)

        //Save states of four fragments
        viewPager.offscreenPageLimit = 4

        (activity as AppCompatActivity).setSupportActionBar(binding.toolbar)

        val bottomNavigation = binding.bottomNavView

        bottomNavigation.setOnNavigationItemSelectedListener(
            BottomNavigationView.OnNavigationItemSelectedListener { item ->
                when (item.itemId) {
                    R.id.fragment1_destination -> viewPager.currentItem = F1_PAGE_INDEX
                    R.id.fragment2_destination -> viewPager.currentItem = F2_PAGE_INDEX
                    R.id.fragment3_destination -> viewPager.currentItem = F3_PAGE_INDEX
                    R.id.fragment4_destination -> viewPager.currentItem = F4_PAGE_INDEX
                }
                true
            })
        return binding.root
    }

}
</code>```

The starting destination (first fragment) is where all the fragment's menu are shown at app start.

Any kind of help is appreciated! Thank you!

答:
Issue: After endless hours, we have found a solution. The issue was directly created when we set the off screen page limit to 4. That causes all the fragments to be created at the same time, thus, obligates the option menus to be shown at launch on the starting destinations fragment since we instructed setHasOptionsMenu(true) in the onCreate of each fragment.

Solution: Simply, set the options menu to true in the onResumeof the fragment to only be called when we swipe to the respective fragment in this manner:

```<code>override fun onResume() {
    super.onResume()
    setHasOptionsMenu(true)
}
</code>```

Body:
Let me add more context:

I run bottom view navigation with a ViewPager2. For all 4 of my tab/fragments of my bottom navigation view I have an options menu which I created separately dynamically in each fragment.

Now, when we navigate through the app, it behaves correctly as every options menu is displayed ONLY for their respective fragment.

Problem is: Only when the app is launched, all the options menus from all the the 4 fragments show up on the start destination fragment's tab. BUT, once we swipe and swipe back, only the start destinations options menu is shown on the app bar. As is for every of the other 3 fragment/tabs.

Theory: I think it has something to do with onCreateOptionsMenu which is called when all four fragments are also created to which they share an app bar.

Is anybody familiar with this type of issue? Here is my PagerAdapters code for my ViewPager:

const val F1_PAGE_INDEX = 0
const val F2_PAGE_INDEX = 1
const val F3_PAGE_INDEX = 2
const val F4_PAGE_INDEX = 3

class PagerAdapter(fragment: Fragment) : FragmentStateAdapter(fragment) {

    /**
     * Mapping of the ViewPager page indexes to their respective Fragments
     */
    private val tabFragmentsCreators: Map<Int, () -> Fragment> = mapOf(
        F1_PAGE_INDEX to { FirstFragment() },
        F2_PAGE_INDEX to { SecondFragment() },
        F3_PAGE_INDEX to { ThirdFragment() },
        F4_PAGE_INDEX to { FourthFragment() }
    )

    override fun getItemCount() = tabFragmentsCreators.size

    override fun createFragment(position: Int): Fragment {
        return tabFragmentsCreators[position]?.invoke() ?: throw IndexOutOfBoundsException()
    }

}

Here is also my Home View Pager Fragment where I create my bottom Navigation and affect to to the main fragments:

class HomeViewPagerFragment(): Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {

        val binding = FragmentViewPagerBinding.inflate(inflater, container, false)

        val viewPager = binding.viewPager

        viewPager.isUserInputEnabled = false

        viewPager.adapter = PagerAdapter(this)

        //Save states of four fragments
        viewPager.offscreenPageLimit = 4

        (activity as AppCompatActivity).setSupportActionBar(binding.toolbar)

        val bottomNavigation = binding.bottomNavView

        bottomNavigation.setOnNavigationItemSelectedListener(
            BottomNavigationView.OnNavigationItemSelectedListener { item ->
                when (item.itemId) {
                    R.id.fragment1_destination -> viewPager.currentItem = F1_PAGE_INDEX
                    R.id.fragment2_destination -> viewPager.currentItem = F2_PAGE_INDEX
                    R.id.fragment3_destination -> viewPager.currentItem = F3_PAGE_INDEX
                    R.id.fragment4_destination -> viewPager.currentItem = F4_PAGE_INDEX
                }
                true
            })
        return binding.root
    }

}

The starting destination (first fragment) is where all the fragment's menu are shown at app start.

Any kind of help is appreciated! Thank you!

Body:
Issue: After endless hours, we have found a solution. The issue was directly created when we set the off screen page limit to 4. That causes all the fragments to be created at the same time, thus, obligates the option menus to be shown at launch on the starting destinations fragment since we instructed setHasOptionsMenu(true) in the onCreate of each fragment.

Solution: Simply, set the options menu to true in the onResumeof the fragment to only be called when we swipe to the respective fragment in this manner:

override fun onResume() {
    super.onResume()
    setHasOptionsMenu(true)
}


来源: stackexchange

问:
Can the VS WebBrowser Control Be made to Emulate MS Edge?
I have a Web Page that employs a "Date" type <Input> control. When using any browser other then IE or the WebBrowser Control supplied in VS this type of control allows the user to select a date via a calendar. Is there a way to configure the WebBrowser control to allow a "Date" input control type work and function like Edge or Chrome on my web pages?

I have ventured into the worlds of CefSharp and WebView2, but this question seems so basic that I feel like it must be possible. I know I have used the Web Browser control for at least 10 years and it's hard to believe it has not been updated for what seems like a basic control. VS sure has this type of control for its forms!.

答:
The <input> elements of type="date" will not support IE browser, so, it will not select dates in the WebBrowser control. More detail information, please check input date type Browser compatibility.

To selected date in WebBrowser control with IE browser, you could try to use <input type="text">, and then using a JQuery DatePicker plugin to select the date on your web page. Finally, using the WebBrowser control to view the web page. By using this method, you could also use the same calendar style.

Please refer to the following date picker sample (using JQuery UI DatePicker):

```<code><head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#datepicker" ).datepicker();
  } );
  </script>
</head>
<body>
<p>Date: <input type="text" id="datepicker"></p>
</body>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
The <input> elements of type="date" will not support IE browser, so, it will not select dates in the WebBrowser control. More detail information, please check input date type Browser compatibility.

To selected date in WebBrowser control with IE browser, you could try to use <input type="text">, and then using a JQuery DatePicker plugin to select the date on your web page. Finally, using the WebBrowser control to view the web page. By using this method, you could also use the same calendar style.

Please refer to the following date picker sample (using JQuery UI DatePicker):

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Datepicker - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#datepicker" ).datepicker();
  } );
  </script>
</head>
<body>
<p>Date: <input type="text" id="datepicker"></p>
</body>


问:
Flask in Docker unable to detect FLASK_ENV
I built a flask app and launch it in docker with the Dockerfile as below.

```<code>FROM python:3.7

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
WORKDIR /app

CMD export FLASK_ENV=production
ENTRYPOINT [ "python", "-u", "app.py" ]
</code>```

In the flask app, I specified some configuration for development & production

```<code>if os.environ['FLASK_ENV'] == 'production':
    UPLOAD_URL = '/v1/path/to/production/server'
elif os.environ['FLASK_ENV'] == 'development':
    UPLOAD_URL = '/upload'
</code>```

However, launching the script caused an error, where the container cannot detect the FLASK_ENV, even though the command was set in the Dockerfile. Can anyone help?

```<code>Traceback (most recent call last):
  File "app.py", line 14, in <module>
    import config
  File "/app/config.py", line 14, in <module>
    if os.environ['FLASK_ENV'] == 'production':
  File "/usr/local/lib/python3.7/os.py", line 681, in __getitem__
    raise KeyError(key) from None
KeyError: 'FLASK_ENV'
</code>```

答:
Replace :
CMD export FLASK_ENV=production

with :
ENV FLASK_ENV=production

ENV instruction is also useful for providing environment variables to services you wish to containerize.

Body:
I built a flask app and launch it in docker with the Dockerfile as below.

FROM python:3.7

COPY requirements.txt .
RUN pip install -r requirements.txt

COPY . .
WORKDIR /app

CMD export FLASK_ENV=production
ENTRYPOINT [ "python", "-u", "app.py" ]

In the flask app, I specified some configuration for development & production

if os.environ['FLASK_ENV'] == 'production':
    UPLOAD_URL = '/v1/path/to/production/server'
elif os.environ['FLASK_ENV'] == 'development':
    UPLOAD_URL = '/upload'

However, launching the script caused an error, where the container cannot detect the FLASK_ENV, even though the command was set in the Dockerfile. Can anyone help?

Traceback (most recent call last):
  File "app.py", line 14, in <module>
    import config
  File "/app/config.py", line 14, in <module>
    if os.environ['FLASK_ENV'] == 'production':
  File "/usr/local/lib/python3.7/os.py", line 681, in __getitem__
    raise KeyError(key) from None
KeyError: 'FLASK_ENV'


问:
How can I retrieve the net value of a payment intent once i've stored it on Stripe php
When storing a PaymentIntent Charge on Stripe lets say for 40.00 Stripe fee is $1.46 and the balance of that is 38.54 is there a way I can retrieve this 38.54 balance i've tried selected the PaymentIntent like how it shows in the Stripe Docs but I can only retrieve the price of the charge which is $40.00 not the balance

here's what it looks like

and here's my retrieving code

$order_total = sprintf('%.2f', $stripe->paymentIntents->retrieve(
        ''.$paymentIntent->id.'',
            []
          )['amount'] / 100);

答:
There is no direct way to get the net amount from the API call, however, you could easily obtain both the original charge amount and the fee amount from payment_intent.

Use Stripe PaymentIntent Retrieval API

Expand the payment_intent.charges.data.balance_transaction to get the balance transaction where you can find the fee parameter

e.g.

```<code>  curl https://api.stripe.com/v1/payment_intents/pi_1GmxGNxxxxxWi \
  -u sk_test_uxxxxxxL: \
  -d "expand[]"="charges.data.balance_transaction"
</code>```

You will just need to subtract the payment_intent amount from the fee parameter to get the net amount.

Body:
There is no direct way to get the net amount from the API call, however, you could easily obtain both the original charge amount and the fee amount from payment_intent.

Use Stripe PaymentIntent Retrieval API

Expand the payment_intent.charges.data.balance_transaction to get the balance transaction where you can find the fee parameter

e.g.

  curl https://api.stripe.com/v1/payment_intents/pi_1GmxGNxxxxxWi \
  -u sk_test_uxxxxxxL: \
  -d "expand[]"="charges.data.balance_transaction"

You will just need to subtract the payment_intent amount from the fee parameter to get the net amount.


问:
Can I use a collection initializer with LINQ to return a fully populated collection?
I would like to rewrite the following code in one line, using LINQ. Is it possible?

```<code>var to = new MailAddressCollection();

foreach(string recipient in recipients)
{
    to.Add(new MailAddress(recipient));
}
</code>```

Something like the following would be ideal. As written it returns multiple MailAddressCollections:

```<code>var to = recipients.Select(r => new MailAddressCollection() {new MailAddress(r)});
</code>```

Note that these are framework classes, so I cannot rewrite MailAddressCollection to include a constructor argument.

答:
MailAddressCollection doesn't have a constructor that takes list of recipients. If you really want to do it in one line, you can write the following:

```<code>    var to = recipients.Aggregate(new MailAddressCollection(),
        (c, r) => { c.Add(new MailAddress(r)); return c; });
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I would like to rewrite the following code in one line, using LINQ. Is it possible?

var to = new MailAddressCollection();

foreach(string recipient in recipients)
{
    to.Add(new MailAddress(recipient));
}

Something like the following would be ideal. As written it returns multiple MailAddressCollections:

var to = recipients.Select(r => new MailAddressCollection() {new MailAddress(r)});

Note that these are framework classes, so I cannot rewrite MailAddressCollection to include a constructor argument.

Body:
MailAddressCollection doesn't have a constructor that takes list of recipients. If you really want to do it in one line, you can write the following:

    var to = recipients.Aggregate(new MailAddressCollection(),
        (c, r) => { c.Add(new MailAddress(r)); return c; });


问:
How to get my build directory for appcenter appium test in Azure deveops Pipeline
i created a YAML file, for azure DevOps pipeline, Apium build directory is a required argument, I set it as appiumBuildDir ='target/upload' i keep getting the message that the directory doesn't exist. How do I get my build directory to use on Devops azure? Thanks.</p>

答:
You can try to specify $(System.DefaultWorkingDirectory) in appiumBuildDir argument.

System.DefaultWorkingDirectory :   The local path on the agent where
  your source code files are downloaded. For example: c:\agent_work\1\s

For details about predefined variable , please refer to this document.


问:
ACTION_SHUTDOWN broadcastreceiver from android doesn't work at all
I'm trying to make beep sound when android device power on and shutdown.
Power on receiver works perfect but shutdown doesn't.
I made Broadcastreceiver detect Intent.BOOT_COMPLETED and Intent.ACTION_SHUTDOWN but only ACTION_SHUTDOWN doesn't work.

Below is manifest for shutdown receiver :

```<code><receiver
        android:name=".AutoRun"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter >
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            <action android:name="android.intent.action.ACTION_SHUTDOWN"/>
            <action android:name="android.intent.action.QUICKBOOT_POWEROFF"/>
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>
</code>```

And below is my AutoRun.java code :

```<code>public class AutoRun extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    ToneGenerator tone = new ToneGenerator(AudioManager.STREAM_MUSIC, ToneGenerator.MAX_VOLUME);
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
        tone.startTone(ToneGenerator.TONE_DTMF_5, 50);
        Intent i = new Intent(context, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    } else if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) { // "android.intent.action.ACTION_SHUTDOWN"
        Log.d("AUTO RUN", "Power Off");
        tone.startTone(ToneGenerator.TONE_DTMF_5, 100);
    }
}
</code>```

}

I don't understand why boot_completed works but shutdown doesn't.
Any advice of opinion must be great helpful for me.
Thanks in advance.

答:
Please read here for broadcast behavior

Note: If your app targets API level 26 or higher, you cannot use the manifest to declare a receiver for implicit broadcasts (broadcasts that do not target your app specifically), except for a few implicit broadcasts that are exempted from that restriction. In most cases, you can use scheduled jobs instead.

Finally, you can get action BOOT_COMPLETED when declare by Manifest but action ACTION_SHUTDOWN you have to Context#registerReceiver in your app (check here).

Body:
I'm trying to make beep sound when android device power on and shutdown.
Power on receiver works perfect but shutdown doesn't.
I made Broadcastreceiver detect Intent.BOOT_COMPLETED and Intent.ACTION_SHUTDOWN but only ACTION_SHUTDOWN doesn't work.

Below is manifest for shutdown receiver :

<receiver
        android:name=".AutoRun"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
        <intent-filter >
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            <action android:name="android.intent.action.ACTION_SHUTDOWN"/>
            <action android:name="android.intent.action.QUICKBOOT_POWEROFF"/>
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

And below is my AutoRun.java code :

public class AutoRun extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    ToneGenerator tone = new ToneGenerator(AudioManager.STREAM_MUSIC, ToneGenerator.MAX_VOLUME);
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
        tone.startTone(ToneGenerator.TONE_DTMF_5, 50);
        Intent i = new Intent(context, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    } else if (intent.getAction().equals(Intent.ACTION_SHUTDOWN)) { // "android.intent.action.ACTION_SHUTDOWN"
        Log.d("AUTO RUN", "Power Off");
        tone.startTone(ToneGenerator.TONE_DTMF_5, 100);
    }
}

}

I don't understand why boot_completed works but shutdown doesn't.
Any advice of opinion must be great helpful for me.
Thanks in advance.


问:
React Native: RenderItem in FlatList. How to map array stored in local state?
I'm creating a small application with React Native that has a local SQLite database for storing images but having trouble rendering my array of images (fetched from the local database and stored in the local state).

Before I was rendered by mapping the data and that worked fine.

```<code>  state = {
    items:[when the user uses the app this array fills with images],
  };
</code>```

```<code><ScrollView>
        {items.map(({ id, value }) => (
          <TouchableOpacity onPress={this.deletePhoto}
            key={id}>
            <Image source={{ uri: value }} style={{ width: null, height: 400 }} />
          </TouchableOpacity>

        ))}
      </ScrollView>
    );
  }
</code>```

But now I would like to go a step further and render the data in a FlatList with my choice of formatting (a grid). Although I can get the FlatList to render the number of images within the array, I can't get the actual image to show. I'm not sure how to pass the data successfully?

```<code>  renderItem = ({ id, value }) => {
  const { items } = this.state;
  if (items.empty === true) {
    return <View style={[styles.item, styles.itemInvisible]} />;
  }
  return (
    <TouchableOpacity style={styles.item} onPress={this.deletePhoto} key={id}>
            <Image source={{ uri: value }} style={{ width: null, height: 400 }} />
    </TouchableOpacity>
  );
  };
</code>```

For context, this is the creation of the 'items' SQL Table with the 'id' and 'value' attributes:

```<code>componentDidMount() {
    db.transaction(tx => {
      tx.executeSql(
        'create table if not exists items (id integer primary key not null, value text);'
      );
    });
  }
</code>```

I guess the question is, how do I pass/access the attributes of the items array into a functional component?

Update:

https://ibb.co/hMY1qBy (What I'm getting - e.g DB Entry creating a View but no image rendering)
https://ibb.co/RN4rqyK (What I'm getting from the answer below)

答:
After getting a reproducible code from your repo that you shared I manage to render the images in the list.

Here is your renderItem function

```<code>renderItem = ({ item }) => {
  const { items } = this.state;
  if (items.empty === true) {
    return <View style={[styles.item, styles.itemInvisible]} />;
  }
  return (
    <TouchableOpacity style={styles.item} onPress={this.deletePhoto} key={item.id}>
            <Image source={{ uri: item.value }} style={{ width: 400, height: 120 }} />
    </TouchableOpacity>
  );
  };
</code>```

You have to get the item from your params of the renderItem function as well you have to pass width to image for rendering, The above code is working fine.

Body:
I'm creating a small application with React Native that has a local SQLite database for storing images but having trouble rendering my array of images (fetched from the local database and stored in the local state).

Before I was rendered by mapping the data and that worked fine.

  state = {
    items:[when the user uses the app this array fills with images],
  };

<ScrollView>
        {items.map(({ id, value }) => (
          <TouchableOpacity onPress={this.deletePhoto}
            key={id}>
            <Image source={{ uri: value }} style={{ width: null, height: 400 }} />
          </TouchableOpacity>

        ))}
      </ScrollView>
    );
  }

But now I would like to go a step further and render the data in a FlatList with my choice of formatting (a grid). Although I can get the FlatList to render the number of images within the array, I can't get the actual image to show. I'm not sure how to pass the data successfully?

  renderItem = ({ id, value }) => {
  const { items } = this.state;
  if (items.empty === true) {
    return <View style={[styles.item, styles.itemInvisible]} />;
  }
  return (
    <TouchableOpacity style={styles.item} onPress={this.deletePhoto} key={id}>
            <Image source={{ uri: value }} style={{ width: null, height: 400 }} />
    </TouchableOpacity>
  );
  };

For context, this is the creation of the 'items' SQL Table with the 'id' and 'value' attributes:

componentDidMount() {
    db.transaction(tx => {
      tx.executeSql(
        'create table if not exists items (id integer primary key not null, value text);'
      );
    });
  }

I guess the question is, how do I pass/access the attributes of the items array into a functional component?

Update:

https://ibb.co/hMY1qBy (What I'm getting - e.g DB Entry creating a View but no image rendering)
https://ibb.co/RN4rqyK (What I'm getting from the answer below)

Body:
After getting a reproducible code from your repo that you shared I manage to render the images in the list.

Here is your renderItem function

renderItem = ({ item }) => {
  const { items } = this.state;
  if (items.empty === true) {
    return <View style={[styles.item, styles.itemInvisible]} />;
  }
  return (
    <TouchableOpacity style={styles.item} onPress={this.deletePhoto} key={item.id}>
            <Image source={{ uri: item.value }} style={{ width: 400, height: 120 }} />
    </TouchableOpacity>
  );
  };

You have to get the item from your params of the renderItem function as well you have to pass width to image for rendering, The above code is working fine.


问:
Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.collect.ImmutableList.toImmutableList()Ljava/util/stream/Collector;
I'm using the Closure Compiler in Google. I'm a beginner at this. When I run my code, I get an error.

I want to know what is the reason or is there any demo used.

my code：

```<code>public class JsClosureCompiler {
    public static String compileJs(String code){

        Compiler compiler = new Compiler();

        CompilerOptions options = new CompilerOptions();
        // Simple mode is used here, but additional options could be set, too.
        CompilationLevel.ADVANCED_OPTIMIZATIONS.setOptionsForCompilationLevel(options);

        // To get the complete set of externs, the logic in
        // CompilerRunner.getDefaultExterns() should be used here.
        SourceFile extern = SourceFile.fromCode("externs.js",
                "function textDiv(text){};");

        // The dummy input name "input.js" is used here so that any warnings or
        // errors will cite line numbers in terms of input.js.
        SourceFile input = SourceFile.fromCode("input.js", code);

        // compile() returns a Result, but it is not needed here.
        compiler.compile(extern, input, options);

        // The compiler is responsible for generating the compiled code; it is not
        // accessible via the Result.
        if(compiler.getErrorCount() > 0){
            StringBuilder erroInfo = new StringBuilder();
            for(JSError jsError: compiler.getErrors()) {
                erroInfo.append(jsError.toString());
            }
        }
        return compiler.toSource();
    }

    public static void main(String[] args) {
        String code = "function makeNoteDom(noteTitle, noteContent, noteContainer) {\n" +
                "  // Create DOM structure to represent the note.\n" +
                "  var headerElement = textDiv(noteTitle);\n" +
                "  var contentElement = textDiv(noteContent);\n" +
                "\n" +
                "  var newNote = document.createElement('div');\n" +
                "  newNote.appendChild(headerElement);\n" +
                "  newNote.appendChild(contentElement);\n" +
                "\n" +
                "  // Add the note's DOM structure to the document.\n" +
                "  noteContainer.appendChild(newNote);\n" +
                "}\n" +
                "\n" +
                "/**\n" +
                " * Iterates over a list of note data objects and creates a DOM\n" +
                " */\n" +
                "function makeNotes(data, noteContainer) {\n" +
                "  for (var i = 0; i < data.length; i++) {\n" +
                "    makeNoteDom(data[i].title, data[i].content, noteContainer);\n" +
                "  }\n" +
                "}\n" +
                "\n" +
                "function main() {\n" +
                "  var noteData = [\n" +
                "      {title: 'Note 1', content: 'Content of Note 1'},\n" +
                "      {title: 'Note 2', content: 'Content of Note 2'}];\n" +
                "  var noteListElement = document.getElementById('notes');\n" +
                "  makeNotes(noteData, noteListElement);\n" +
                "}\n" +
                "\n" +
                "main();";
        String s = compileJs(code);
        System.out.println(s);
    }
}
</code>```

--------------------------------error--error--------------------------------

```<code>Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.collect.ImmutableList.toImmutableList()Ljava/util/stream/Collector;
    at com.google.javascript.jscomp.deps.DependencyInfo$Require.asSymbolList(DependencyInfo.java:60)
    at com.google.javascript.jscomp.deps.DependencyInfo$Base.getRequiredSymbols(DependencyInfo.java:163)
    at com.google.javascript.jscomp.Compiler.findModulesFromInput(Compiler.java:1901)
    at com.google.javascript.jscomp.Compiler.findModulesFromEntryPoints(Compiler.java:1857)
    at com.google.javascript.jscomp.Compiler.parseInputs(Compiler.java:1666)
    at com.google.javascript.jscomp.Compiler.parseForCompilationInternal(Compiler.java:939)
    at com.google.javascript.jscomp.Compiler.lambda$parseForCompilation$4(Compiler.java:922)
    at com.google.javascript.jscomp.CompilerExecutor$2.call(CompilerExecutor.java:102)
    at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
    at java.util.concurrent.FutureTask.run(FutureTask.java)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
</code>```

答:
put guava into pom.xml</p>

```<code><dependency>
   <groupId>com.google.guava</groupId>
   <artifactId>guava</artifactId>
   <version>22.0</version>
</dependency>
</code>```

Body:
I'm using the Closure Compiler in Google. I'm a beginner at this. When I run my code, I get an error.

I want to know what is the reason or is there any demo used.

my code：

public class JsClosureCompiler {
    public static String compileJs(String code){

        Compiler compiler = new Compiler();

        CompilerOptions options = new CompilerOptions();
        // Simple mode is used here, but additional options could be set, too.
        CompilationLevel.ADVANCED_OPTIMIZATIONS.setOptionsForCompilationLevel(options);

        // To get the complete set of externs, the logic in
        // CompilerRunner.getDefaultExterns() should be used here.
        SourceFile extern = SourceFile.fromCode("externs.js",
                "function textDiv(text){};");

        // The dummy input name "input.js" is used here so that any warnings or
        // errors will cite line numbers in terms of input.js.
        SourceFile input = SourceFile.fromCode("input.js", code);

        // compile() returns a Result, but it is not needed here.
        compiler.compile(extern, input, options);

        // The compiler is responsible for generating the compiled code; it is not
        // accessible via the Result.
        if(compiler.getErrorCount() > 0){
            StringBuilder erroInfo = new StringBuilder();
            for(JSError jsError: compiler.getErrors()) {
                erroInfo.append(jsError.toString());
            }
        }
        return compiler.toSource();
    }

    public static void main(String[] args) {
        String code = "function makeNoteDom(noteTitle, noteContent, noteContainer) {\n" +
                "  // Create DOM structure to represent the note.\n" +
                "  var headerElement = textDiv(noteTitle);\n" +
                "  var contentElement = textDiv(noteContent);\n" +
                "\n" +
                "  var newNote = document.createElement('div');\n" +
                "  newNote.appendChild(headerElement);\n" +
                "  newNote.appendChild(contentElement);\n" +
                "\n" +
                "  // Add the note's DOM structure to the document.\n" +
                "  noteContainer.appendChild(newNote);\n" +
                "}\n" +
                "\n" +
                "/**\n" +
                " * Iterates over a list of note data objects and creates a DOM\n" +
                " */\n" +
                "function makeNotes(data, noteContainer) {\n" +
                "  for (var i = 0; i < data.length; i++) {\n" +
                "    makeNoteDom(data[i].title, data[i].content, noteContainer);\n" +
                "  }\n" +
                "}\n" +
                "\n" +
                "function main() {\n" +
                "  var noteData = [\n" +
                "      {title: 'Note 1', content: 'Content of Note 1'},\n" +
                "      {title: 'Note 2', content: 'Content of Note 2'}];\n" +
                "  var noteListElement = document.getElementById('notes');\n" +
                "  makeNotes(noteData, noteListElement);\n" +
                "}\n" +
                "\n" +
                "main();";
        String s = compileJs(code);
        System.out.println(s);
    }
}

--------------------------------error--error--------------------------------

Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.collect.ImmutableList.toImmutableList()Ljava/util/stream/Collector;
    at com.google.javascript.jscomp.deps.DependencyInfo$Require.asSymbolList(DependencyInfo.java:60)
    at com.google.javascript.jscomp.deps.DependencyInfo$Base.getRequiredSymbols(DependencyInfo.java:163)
    at com.google.javascript.jscomp.Compiler.findModulesFromInput(Compiler.java:1901)
    at com.google.javascript.jscomp.Compiler.findModulesFromEntryPoints(Compiler.java:1857)
    at com.google.javascript.jscomp.Compiler.parseInputs(Compiler.java:1666)
    at com.google.javascript.jscomp.Compiler.parseForCompilationInternal(Compiler.java:939)
    at com.google.javascript.jscomp.Compiler.lambda$parseForCompilation$4(Compiler.java:922)
    at com.google.javascript.jscomp.CompilerExecutor$2.call(CompilerExecutor.java:102)
    at java.util.concurrent.FutureTask.run$$$capture(FutureTask.java:266)
    at java.util.concurrent.FutureTask.run(FutureTask.java)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Body:
put guava into pom.xml

<dependency>
   <groupId>com.google.guava</groupId>
   <artifactId>guava</artifactId>
   <version>22.0</version>
</dependency>


问:
How to move a project to another folder by Git in Visual Studio
I have solution that looks like this in Visual Studio and I committed them in Git:

```<code>--project.a
--project.b
</code>```

How should I move them (to for example srcFolder) to look like the following without loosing Git history:

```<code>--srcFolder
  ---project.a
  ---project.b
</code>```

答:
as mentioned here

CMD and PowerShell does not expand globing characters, use git bash instead

```<code>git mv project.a srcFolder
</code>```

should work then.

Body:
I have solution that looks like this in Visual Studio and I committed them in Git:

--project.a
--project.b

How should I move them (to for example srcFolder) to look like the following without loosing Git history:

--srcFolder
  ---project.a
  ---project.b

Body:
as mentioned here

CMD and PowerShell does not expand globing characters, use git bash instead

git mv project.a srcFolder

should work then.


问:
How to pass parameters toolbar bar button selector method
I am developing an ios application using swift and storyboard. I need to pass parameters inside the toolbar bar button selector method. my objc selector method like

```<code>@objc func FetchDate(inputField:UITextField)
{
inputField.resignFirstResponder()
}
</code>```

I am setting toolbar bar button item and calling the selector item like this:

```<code>let toolbar = UIToolbar()
toolbar.sizeToFit()

let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(AppointmentConfig.FetchDate(inputField:)))
toolbar.setItems([doneBtn], animated: true)
</code>```

But app crashed when I pass the parameter above this. how to fix this?

答:
Action methods only accept the sender (the UIBarButton in your case) or the sender and a UIEvent, see here https://developer.apple.com/documentation/uikit/uicontrol
So you'll the object that implements the action method will have to "know" about the UITextField you want to access... it can then forward the message to the appropriate object with the reference to the textfield as a parameter. PS generally accepted style is that method names should start with a lower case like methodName.</p>

Body:
I am developing an ios application using swift and storyboard. I need to pass parameters inside the toolbar bar button selector method. my objc selector method like

@objc func FetchDate(inputField:UITextField)
{
inputField.resignFirstResponder()
}

I am setting toolbar bar button item and calling the selector item like this:

let toolbar = UIToolbar()
toolbar.sizeToFit()

let doneBtn = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector(AppointmentConfig.FetchDate(inputField:)))
toolbar.setItems([doneBtn], animated: true)

But app crashed when I pass the parameter above this. how to fix this?


问:
how to handle root path request with node.js on firebase hosting?
I'm developing web system using firebase hosting + functions.
Inspite of specifying rewrite rules on firebase.json,
a part of routing doesn't work.

```<code>root/
　├ functions/
　│  ├index.js
　│  ├routes/
　│  │  └ index.js
　│  └views/
　│    ├ index.jade
　│    └ sub.jade
　└ public/
    └index.html // this is created by default. I don't want to use this.
</code>```

This is my firebase.json

```<code>"rewrites": [{
      "source": "**",
      "function": "app"
    }],
</code>```

And this is node.js code.

```<code>router.get('/', function(req, res, next) {
    res.render('index');
});

router.get('/subdir', function(req, res, next) {
    res.render('sub');
});
</code>```

result

```<code>https://myurl/ -> public/index.html is shown.(not handled on node.js)
https://myurl/ -> handled on node.js
</code>```

Do you know how to handle root path request with node.js on firebase hosting.

答:
It's simple! Just rename the index.html file in the public directory into some other name. Also, just in case: In the firebase.json file, Change the public property's value
from public to .

Body:
I'm developing web system using firebase hosting + functions.
Inspite of specifying rewrite rules on firebase.json,
a part of routing doesn't work.

root/
　├ functions/
　│  ├index.js
　│  ├routes/
　│  │  └ index.js
　│  └views/
　│    ├ index.jade
　│    └ sub.jade
　└ public/
    └index.html // this is created by default. I don't want to use this.

This is my firebase.json

"rewrites": [{
      "source": "**",
      "function": "app"
    }],

And this is node.js code.

router.get('/', function(req, res, next) {
    res.render('index');
});

router.get('/subdir', function(req, res, next) {
    res.render('sub');
});

result

https://myurl/ -> public/index.html is shown.(not handled on node.js)
https://myurl/ -> handled on node.js

Do you know how to handle root path request with node.js on firebase hosting.


问:
How to use CoinMarketCap API in flutter
I'm following a tutorial for an app that displays cryptocurrency prices and I have trouble with the new API. The code below is just from the tutorial and the tutor is using the old coinmarketcap API. Coinmarketcap has migrated to a new one and you need to sign up to get a free API key. Documentation for new API: https://coinmarketcap.com/api/documentation/v1.

I think I need to change _apiURL to https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD and somehow use the APIKey. Does anyone have a solution? Still kinda new to flutter and API's so i'm sorry if the question is hard to answer.

```<code>Future<void> getCryptoPrices() async {
//async to use await, which suspends the current function, while it does other stuff and resumes when data ready
print('getting crypto prices'); //print
String _apiURL =
    "https://api.coinmarketcap.com/v1/ticker/"; //url to get data
setState(() {
  this._loading = true; //before calling the api, set the loading to true
});
http.Response response = await http.get(_apiURL); //waits for response
setState(() {
  this._cryptoList =
      jsonDecode(response.body); //sets the state of our widget
  this._loading = false; //set the loading to false after we get a response
  print(_cryptoList); //prints the list
});
return;  }
</code>```

答:
You can copy paste run full code below and replace your-key before run

You can put API key in headers and parse json response with payloadFromJson and display with FutureBuilder

You can see Payload class definition in full code

```<code>Future<Payload> getCryptoPrices() async {
    var response = await http.get(
        "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD",
        headers: {
          'X-CMC_PRO_API_KEY': 'your-key',
          "Accept": "application/json",
        });

    if (response.statusCode == 200) {
      return payloadFromJson(response.body);
    }
  }
</code>```

working demo

full code

```<code>import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
  Payload({
    this.status,
    this.data,
  });

  Status status;
  List<Datum> data;

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        status: Status.fromJson(json["status"]),
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "status": status.toJson(),
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
      };
}

class Datum {
  Datum({
    this.id,
    this.name,
    this.symbol,
    this.slug,
    this.numMarketPairs,
    this.dateAdded,
    this.tags,
    this.maxSupply,
    this.circulatingSupply,
    this.totalSupply,
    this.platform,
    this.cmcRank,
    this.lastUpdated,
    this.quote,
  });

  int id;
  String name;
  String symbol;
  String slug;
  int numMarketPairs;
  DateTime dateAdded;
  List<Tag> tags;
  double maxSupply;
  double circulatingSupply;
  double totalSupply;
  Platform platform;
  int cmcRank;
  DateTime lastUpdated;
  Quote quote;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        id: json["id"],
        name: json["name"],
        symbol: json["symbol"],
        slug: json["slug"],
        numMarketPairs: json["num_market_pairs"],
        dateAdded: DateTime.parse(json["date_added"]),
        tags: List<Tag>.from(json["tags"].map((x) => tagValues.map[x])),
        maxSupply:
            json["max_supply"] == null ? null : json["max_supply"].toDouble(),
        circulatingSupply: json["circulating_supply"] == null
            ? null
            : json["circulating_supply"].toDouble(),
        totalSupply: json["total_supply"] == null
            ? null
            : json["total_supply"].toDouble(),
        platform: json["platform"] == null
            ? null
            : Platform.fromJson(json["platform"]),
        cmcRank: json["cmc_rank"],
        lastUpdated: DateTime.parse(json["last_updated"]),
        quote: Quote.fromJson(json["quote"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "symbol": symbol,
        "slug": slug,
        "num_market_pairs": numMarketPairs,
        "date_added": dateAdded.toIso8601String(),
        "tags": List<dynamic>.from(tags.map((x) => tagValues.reverse[x])),
        "max_supply": maxSupply == null ? null : maxSupply,
        "circulating_supply":
            circulatingSupply == null ? null : circulatingSupply,
        "total_supply": totalSupply == null ? null : totalSupply,
        "platform": platform == null ? null : platform.toJson(),
        "cmc_rank": cmcRank,
        "last_updated": lastUpdated.toIso8601String(),
        "quote": quote.toJson(),
      };
}

class Platform {
  Platform({
    this.id,
    this.name,
    this.symbol,
    this.slug,
    this.tokenAddress,
  });

  int id;
  Name name;
  Symbol symbol;
  Slug slug;
  String tokenAddress;

  factory Platform.fromJson(Map<String, dynamic> json) => Platform(
        id: json["id"],
        name: nameValues.map[json["name"]],
        symbol: symbolValues.map[json["symbol"]],
        slug: slugValues.map[json["slug"]],
        tokenAddress: json["token_address"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": nameValues.reverse[name],
        "symbol": symbolValues.reverse[symbol],
        "slug": slugValues.reverse[slug],
        "token_address": tokenAddress,
      };
}

enum Name {
  ETHEREUM,
  TRON,
  OMNI,
  RSK_SMART_BITCOIN,
  BINANCE_COIN,
  STELLAR,
  NEO,
  V_SYSTEMS,
  ARDOR,
  QTUM,
  XRP,
  WAVES,
  ONTOLOGY,
  EOS,
  NEBULAS,
  NEM,
  BIT_SHARES,
  BITCOIN_CASH,
  INT_CHAIN,
  COSMOS,
  UBIQ,
  VE_CHAIN,
  NU_BITS,
  PIVX,
  COUNTERPARTY,
  KOMODO,
  ICON,
  GX_CHAIN,
  VITE,
  WANCHAIN,
  IOST,
  TRUE_CHAIN,
  ETHEREUM_CLASSIC
}

final nameValues = EnumValues({
  "Ardor": Name.ARDOR,
  "Binance Coin": Name.BINANCE_COIN,
  "Bitcoin Cash": Name.BITCOIN_CASH,
  "BitShares": Name.BIT_SHARES,
  "Cosmos": Name.COSMOS,
  "Counterparty": Name.COUNTERPARTY,
  "EOS": Name.EOS,
  "Ethereum": Name.ETHEREUM,
  "Ethereum Classic": Name.ETHEREUM_CLASSIC,
  "GXChain": Name.GX_CHAIN,
  "ICON": Name.ICON,
  "INT Chain": Name.INT_CHAIN,
  "IOST": Name.IOST,
  "Komodo": Name.KOMODO,
  "Nebulas": Name.NEBULAS,
  "NEM": Name.NEM,
  "Neo": Name.NEO,
  "NuBits": Name.NU_BITS,
  "Omni": Name.OMNI,
  "Ontology": Name.ONTOLOGY,
  "PIVX": Name.PIVX,
  "Qtum": Name.QTUM,
  "RSK Smart Bitcoin": Name.RSK_SMART_BITCOIN,
  "Stellar": Name.STELLAR,
  "TRON": Name.TRON,
  "TrueChain": Name.TRUE_CHAIN,
  "Ubiq": Name.UBIQ,
  "VeChain": Name.VE_CHAIN,
  "VITE": Name.VITE,
  "v.systems": Name.V_SYSTEMS,
  "Wanchain": Name.WANCHAIN,
  "Waves": Name.WAVES,
  "XRP": Name.XRP
});

enum Slug {
  ETHEREUM,
  TRON,
  OMNI,
  RSK_SMART_BITCOIN,
  BINANCE_COIN,
  STELLAR,
  NEO,
  V_SYSTEMS,
  ARDOR,
  QTUM,
  XRP,
  WAVES,
  ONTOLOGY,
  EOS,
  NEBULAS_TOKEN,
  NEM,
  BITSHARES,
  BITCOIN_CASH,
  INT_CHAIN,
  COSMOS,
  UBIQ,
  VECHAIN,
  NUBITS,
  PIVX,
  COUNTERPARTY,
  KOMODO,
  ICON,
  GXCHAIN,
  VITE,
  WANCHAIN,
  IOSTOKEN,
  TRUECHAIN,
  ETHEREUM_CLASSIC
}

final slugValues = EnumValues({
  "ardor": Slug.ARDOR,
  "binance-coin": Slug.BINANCE_COIN,
  "bitcoin-cash": Slug.BITCOIN_CASH,
  "bitshares": Slug.BITSHARES,
  "cosmos": Slug.COSMOS,
  "counterparty": Slug.COUNTERPARTY,
  "eos": Slug.EOS,
  "ethereum": Slug.ETHEREUM,
  "ethereum-classic": Slug.ETHEREUM_CLASSIC,
  "gxchain": Slug.GXCHAIN,
  "icon": Slug.ICON,
  "int-chain": Slug.INT_CHAIN,
  "iostoken": Slug.IOSTOKEN,
  "komodo": Slug.KOMODO,
  "nebulas-token": Slug.NEBULAS_TOKEN,
  "nem": Slug.NEM,
  "neo": Slug.NEO,
  "nubits": Slug.NUBITS,
  "omni": Slug.OMNI,
  "ontology": Slug.ONTOLOGY,
  "pivx": Slug.PIVX,
  "qtum": Slug.QTUM,
  "rsk-smart-bitcoin": Slug.RSK_SMART_BITCOIN,
  "stellar": Slug.STELLAR,
  "tron": Slug.TRON,
  "truechain": Slug.TRUECHAIN,
  "ubiq": Slug.UBIQ,
  "vechain": Slug.VECHAIN,
  "vite": Slug.VITE,
  "v-systems": Slug.V_SYSTEMS,
  "wanchain": Slug.WANCHAIN,
  "waves": Slug.WAVES,
  "xrp": Slug.XRP
});

enum Symbol {
  ETH,
  TRX,
  OMNI,
  RBTC,
  BNB,
  XLM,
  NEO,
  VSYS,
  ARDR,
  QTUM,
  XRP,
  WAVES,
  ONT,
  EOS,
  NAS,
  XEM,
  BTS,
  BCH,
  INT,
  ATOM,
  UBQ,
  VET,
  USNBT,
  PIVX,
  XCP,
  KMD,
  ICX,
  GXC,
  VITE,
  WAN,
  IOST,
  TRUE,
  ETC
}

final symbolValues = EnumValues({
  "ARDR": Symbol.ARDR,
  "ATOM": Symbol.ATOM,
  "BCH": Symbol.BCH,
  "BNB": Symbol.BNB,
  "BTS": Symbol.BTS,
  "EOS": Symbol.EOS,
  "ETC": Symbol.ETC,
  "ETH": Symbol.ETH,
  "GXC": Symbol.GXC,
  "ICX": Symbol.ICX,
  "INT": Symbol.INT,
  "IOST": Symbol.IOST,
  "KMD": Symbol.KMD,
  "NAS": Symbol.NAS,
  "NEO": Symbol.NEO,
  "OMNI": Symbol.OMNI,
  "ONT": Symbol.ONT,
  "PIVX": Symbol.PIVX,
  "QTUM": Symbol.QTUM,
  "RBTC": Symbol.RBTC,
  "TRUE": Symbol.TRUE,
  "TRX": Symbol.TRX,
  "UBQ": Symbol.UBQ,
  "USNBT": Symbol.USNBT,
  "VET": Symbol.VET,
  "VITE": Symbol.VITE,
  "VSYS": Symbol.VSYS,
  "WAN": Symbol.WAN,
  "WAVES": Symbol.WAVES,
  "XCP": Symbol.XCP,
  "XEM": Symbol.XEM,
  "XLM": Symbol.XLM,
  "XRP": Symbol.XRP
});

class Quote {
  Quote({
    this.usd,
  });

  Usd usd;

  factory Quote.fromJson(Map<String, dynamic> json) => Quote(
        usd: Usd.fromJson(json["USD"]),
      );

  Map<String, dynamic> toJson() => {
        "USD": usd.toJson(),
      };
}

class Usd {
  Usd({
    this.price,
    this.volume24H,
    this.percentChange1H,
    this.percentChange24H,
    this.percentChange7D,
    this.marketCap,
    this.lastUpdated,
  });

  double price;
  double volume24H;
  double percentChange1H;
  double percentChange24H;
  double percentChange7D;
  double marketCap;
  DateTime lastUpdated;

  factory Usd.fromJson(Map<String, dynamic> json) => Usd(
        price: json["price"] == null ? null : json["price"].toDouble(),
        volume24H:
            json["volume_24h"] == null ? null : json["volume_24h"].toDouble(),
        percentChange1H: json["percent_change_1h"] == null
            ? null
            : json["percent_change_1h"].toDouble(),
        percentChange24H: json["percent_change_24h"] == null
            ? null
            : json["percent_change_24h"].toDouble(),
        percentChange7D: json["percent_change_7d"] == null
            ? null
            : json["percent_change_7d"].toDouble(),
        marketCap:
            json["market_cap"] == null ? null : json["market_cap"].toDouble(),
        lastUpdated: DateTime.parse(json["last_updated"]),
      );

  Map<String, dynamic> toJson() => {
        "price": price == null ? null : price,
        "volume_24h": volume24H == null ? null : volume24H,
        "percent_change_1h": percentChange1H == null ? null : percentChange1H,
        "percent_change_24h":
            percentChange24H == null ? null : percentChange24H,
        "percent_change_7d": percentChange7D == null ? null : percentChange7D,
        "market_cap": marketCap == null ? null : marketCap,
        "last_updated": lastUpdated.toIso8601String(),
      };
}

enum Tag { MINEABLE }

final tagValues = EnumValues({"mineable": Tag.MINEABLE});

class Status {
  Status({
    this.timestamp,
    this.errorCode,
    this.errorMessage,
    this.elapsed,
    this.creditCount,
    this.notice,
  });

  DateTime timestamp;
  int errorCode;
  dynamic errorMessage;
  int elapsed;
  int creditCount;
  dynamic notice;

  factory Status.fromJson(Map<String, dynamic> json) => Status(
        timestamp: DateTime.parse(json["timestamp"]),
        errorCode: json["error_code"],
        errorMessage: json["error_message"],
        elapsed: json["elapsed"],
        creditCount: json["credit_count"],
        notice: json["notice"],
      );

  Map<String, dynamic> toJson() => {
        "timestamp": timestamp.toIso8601String(),
        "error_code": errorCode,
        "error_message": errorMessage,
        "elapsed": elapsed,
        "credit_count": creditCount,
        "notice": notice,
      };
}

class EnumValues<T> {
  Map<String, T> map;
  Map<T, String> reverseMap;

  EnumValues(this.map);

  Map<T, String> get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap;
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Future<Payload> _future;

  Future<Payload> getCryptoPrices() async {
    var response = await http.get(
        "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD",
        headers: {
          'X-CMC_PRO_API_KEY': 'your-key',
          "Accept": "application/json",
        });

    if (response.statusCode == 200) {
      return payloadFromJson(response.body);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _future = getCryptoPrices();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<Payload> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.data.length,
                        itemBuilder: (context, index) {
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot.data.data[index].name),
                                    Spacer(),
                                    Text(snapshot.data.data[index].lastUpdated
                                        .toIso8601String()),
                                    Spacer(),
                                    Text(
                                      snapshot.data.data[index].quote.usd.price
                                          .toString(),
                                    ),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}
</code>```

Title: How to use CoinMarketCap API in flutter

Body:
I'm following a tutorial for an app that displays cryptocurrency prices and I have trouble with the new API. The code below is just from the tutorial and the tutor is using the old coinmarketcap API. Coinmarketcap has migrated to a new one and you need to sign up to get a free API key. Documentation for new API: https://coinmarketcap.com/api/documentation/v1.

I think I need to change _apiURL to https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD and somehow use the APIKey. Does anyone have a solution? Still kinda new to flutter and API's so i'm sorry if the question is hard to answer.

Future<void> getCryptoPrices() async {
//async to use await, which suspends the current function, while it does other stuff and resumes when data ready
print('getting crypto prices'); //print
String _apiURL =
    "https://api.coinmarketcap.com/v1/ticker/"; //url to get data
setState(() {
  this._loading = true; //before calling the api, set the loading to true
});
http.Response response = await http.get(_apiURL); //waits for response
setState(() {
  this._cryptoList =
      jsonDecode(response.body); //sets the state of our widget
  this._loading = false; //set the loading to false after we get a response
  print(_cryptoList); //prints the list
});
return;  }

Body:
You can copy paste run full code below and replace your-key before run

You can put API key in headers and parse json response with payloadFromJson and display with FutureBuilder

You can see Payload class definition in full code

Future<Payload> getCryptoPrices() async {
    var response = await http.get(
        "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD",
        headers: {
          'X-CMC_PRO_API_KEY': 'your-key',
          "Accept": "application/json",
        });

    if (response.statusCode == 200) {
      return payloadFromJson(response.body);
    }
  }

working demo

full code

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
  Payload({
    this.status,
    this.data,
  });

  Status status;
  List<Datum> data;

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        status: Status.fromJson(json["status"]),
        data: List<Datum>.from(json["data"].map((x) => Datum.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "status": status.toJson(),
        "data": List<dynamic>.from(data.map((x) => x.toJson())),
      };
}

class Datum {
  Datum({
    this.id,
    this.name,
    this.symbol,
    this.slug,
    this.numMarketPairs,
    this.dateAdded,
    this.tags,
    this.maxSupply,
    this.circulatingSupply,
    this.totalSupply,
    this.platform,
    this.cmcRank,
    this.lastUpdated,
    this.quote,
  });

  int id;
  String name;
  String symbol;
  String slug;
  int numMarketPairs;
  DateTime dateAdded;
  List<Tag> tags;
  double maxSupply;
  double circulatingSupply;
  double totalSupply;
  Platform platform;
  int cmcRank;
  DateTime lastUpdated;
  Quote quote;

  factory Datum.fromJson(Map<String, dynamic> json) => Datum(
        id: json["id"],
        name: json["name"],
        symbol: json["symbol"],
        slug: json["slug"],
        numMarketPairs: json["num_market_pairs"],
        dateAdded: DateTime.parse(json["date_added"]),
        tags: List<Tag>.from(json["tags"].map((x) => tagValues.map[x])),
        maxSupply:
            json["max_supply"] == null ? null : json["max_supply"].toDouble(),
        circulatingSupply: json["circulating_supply"] == null
            ? null
            : json["circulating_supply"].toDouble(),
        totalSupply: json["total_supply"] == null
            ? null
            : json["total_supply"].toDouble(),
        platform: json["platform"] == null
            ? null
            : Platform.fromJson(json["platform"]),
        cmcRank: json["cmc_rank"],
        lastUpdated: DateTime.parse(json["last_updated"]),
        quote: Quote.fromJson(json["quote"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "symbol": symbol,
        "slug": slug,
        "num_market_pairs": numMarketPairs,
        "date_added": dateAdded.toIso8601String(),
        "tags": List<dynamic>.from(tags.map((x) => tagValues.reverse[x])),
        "max_supply": maxSupply == null ? null : maxSupply,
        "circulating_supply":
            circulatingSupply == null ? null : circulatingSupply,
        "total_supply": totalSupply == null ? null : totalSupply,
        "platform": platform == null ? null : platform.toJson(),
        "cmc_rank": cmcRank,
        "last_updated": lastUpdated.toIso8601String(),
        "quote": quote.toJson(),
      };
}

class Platform {
  Platform({
    this.id,
    this.name,
    this.symbol,
    this.slug,
    this.tokenAddress,
  });

  int id;
  Name name;
  Symbol symbol;
  Slug slug;
  String tokenAddress;

  factory Platform.fromJson(Map<String, dynamic> json) => Platform(
        id: json["id"],
        name: nameValues.map[json["name"]],
        symbol: symbolValues.map[json["symbol"]],
        slug: slugValues.map[json["slug"]],
        tokenAddress: json["token_address"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": nameValues.reverse[name],
        "symbol": symbolValues.reverse[symbol],
        "slug": slugValues.reverse[slug],
        "token_address": tokenAddress,
      };
}

enum Name {
  ETHEREUM,
  TRON,
  OMNI,
  RSK_SMART_BITCOIN,
  BINANCE_COIN,
  STELLAR,
  NEO,
  V_SYSTEMS,
  ARDOR,
  QTUM,
  XRP,
  WAVES,
  ONTOLOGY,
  EOS,
  NEBULAS,
  NEM,
  BIT_SHARES,
  BITCOIN_CASH,
  INT_CHAIN,
  COSMOS,
  UBIQ,
  VE_CHAIN,
  NU_BITS,
  PIVX,
  COUNTERPARTY,
  KOMODO,
  ICON,
  GX_CHAIN,
  VITE,
  WANCHAIN,
  IOST,
  TRUE_CHAIN,
  ETHEREUM_CLASSIC
}

final nameValues = EnumValues({
  "Ardor": Name.ARDOR,
  "Binance Coin": Name.BINANCE_COIN,
  "Bitcoin Cash": Name.BITCOIN_CASH,
  "BitShares": Name.BIT_SHARES,
  "Cosmos": Name.COSMOS,
  "Counterparty": Name.COUNTERPARTY,
  "EOS": Name.EOS,
  "Ethereum": Name.ETHEREUM,
  "Ethereum Classic": Name.ETHEREUM_CLASSIC,
  "GXChain": Name.GX_CHAIN,
  "ICON": Name.ICON,
  "INT Chain": Name.INT_CHAIN,
  "IOST": Name.IOST,
  "Komodo": Name.KOMODO,
  "Nebulas": Name.NEBULAS,
  "NEM": Name.NEM,
  "Neo": Name.NEO,
  "NuBits": Name.NU_BITS,
  "Omni": Name.OMNI,
  "Ontology": Name.ONTOLOGY,
  "PIVX": Name.PIVX,
  "Qtum": Name.QTUM,
  "RSK Smart Bitcoin": Name.RSK_SMART_BITCOIN,
  "Stellar": Name.STELLAR,
  "TRON": Name.TRON,
  "TrueChain": Name.TRUE_CHAIN,
  "Ubiq": Name.UBIQ,
  "VeChain": Name.VE_CHAIN,
  "VITE": Name.VITE,
  "v.systems": Name.V_SYSTEMS,
  "Wanchain": Name.WANCHAIN,
  "Waves": Name.WAVES,
  "XRP": Name.XRP
});

enum Slug {
  ETHEREUM,
  TRON,
  OMNI,
  RSK_SMART_BITCOIN,
  BINANCE_COIN,
  STELLAR,
  NEO,
  V_SYSTEMS,
  ARDOR,
  QTUM,
  XRP,
  WAVES,
  ONTOLOGY,
  EOS,
  NEBULAS_TOKEN,
  NEM,
  BITSHARES,
  BITCOIN_CASH,
  INT_CHAIN,
  COSMOS,
  UBIQ,
  VECHAIN,
  NUBITS,
  PIVX,
  COUNTERPARTY,
  KOMODO,
  ICON,
  GXCHAIN,
  VITE,
  WANCHAIN,
  IOSTOKEN,
  TRUECHAIN,
  ETHEREUM_CLASSIC
}

final slugValues = EnumValues({
  "ardor": Slug.ARDOR,
  "binance-coin": Slug.BINANCE_COIN,
  "bitcoin-cash": Slug.BITCOIN_CASH,
  "bitshares": Slug.BITSHARES,
  "cosmos": Slug.COSMOS,
  "counterparty": Slug.COUNTERPARTY,
  "eos": Slug.EOS,
  "ethereum": Slug.ETHEREUM,
  "ethereum-classic": Slug.ETHEREUM_CLASSIC,
  "gxchain": Slug.GXCHAIN,
  "icon": Slug.ICON,
  "int-chain": Slug.INT_CHAIN,
  "iostoken": Slug.IOSTOKEN,
  "komodo": Slug.KOMODO,
  "nebulas-token": Slug.NEBULAS_TOKEN,
  "nem": Slug.NEM,
  "neo": Slug.NEO,
  "nubits": Slug.NUBITS,
  "omni": Slug.OMNI,
  "ontology": Slug.ONTOLOGY,
  "pivx": Slug.PIVX,
  "qtum": Slug.QTUM,
  "rsk-smart-bitcoin": Slug.RSK_SMART_BITCOIN,
  "stellar": Slug.STELLAR,
  "tron": Slug.TRON,
  "truechain": Slug.TRUECHAIN,
  "ubiq": Slug.UBIQ,
  "vechain": Slug.VECHAIN,
  "vite": Slug.VITE,
  "v-systems": Slug.V_SYSTEMS,
  "wanchain": Slug.WANCHAIN,
  "waves": Slug.WAVES,
  "xrp": Slug.XRP
});

enum Symbol {
  ETH,
  TRX,
  OMNI,
  RBTC,
  BNB,
  XLM,
  NEO,
  VSYS,
  ARDR,
  QTUM,
  XRP,
  WAVES,
  ONT,
  EOS,
  NAS,
  XEM,
  BTS,
  BCH,
  INT,
  ATOM,
  UBQ,
  VET,
  USNBT,
  PIVX,
  XCP,
  KMD,
  ICX,
  GXC,
  VITE,
  WAN,
  IOST,
  TRUE,
  ETC
}

final symbolValues = EnumValues({
  "ARDR": Symbol.ARDR,
  "ATOM": Symbol.ATOM,
  "BCH": Symbol.BCH,
  "BNB": Symbol.BNB,
  "BTS": Symbol.BTS,
  "EOS": Symbol.EOS,
  "ETC": Symbol.ETC,
  "ETH": Symbol.ETH,
  "GXC": Symbol.GXC,
  "ICX": Symbol.ICX,
  "INT": Symbol.INT,
  "IOST": Symbol.IOST,
  "KMD": Symbol.KMD,
  "NAS": Symbol.NAS,
  "NEO": Symbol.NEO,
  "OMNI": Symbol.OMNI,
  "ONT": Symbol.ONT,
  "PIVX": Symbol.PIVX,
  "QTUM": Symbol.QTUM,
  "RBTC": Symbol.RBTC,
  "TRUE": Symbol.TRUE,
  "TRX": Symbol.TRX,
  "UBQ": Symbol.UBQ,
  "USNBT": Symbol.USNBT,
  "VET": Symbol.VET,
  "VITE": Symbol.VITE,
  "VSYS": Symbol.VSYS,
  "WAN": Symbol.WAN,
  "WAVES": Symbol.WAVES,
  "XCP": Symbol.XCP,
  "XEM": Symbol.XEM,
  "XLM": Symbol.XLM,
  "XRP": Symbol.XRP
});

class Quote {
  Quote({
    this.usd,
  });

  Usd usd;

  factory Quote.fromJson(Map<String, dynamic> json) => Quote(
        usd: Usd.fromJson(json["USD"]),
      );

  Map<String, dynamic> toJson() => {
        "USD": usd.toJson(),
      };
}

class Usd {
  Usd({
    this.price,
    this.volume24H,
    this.percentChange1H,
    this.percentChange24H,
    this.percentChange7D,
    this.marketCap,
    this.lastUpdated,
  });

  double price;
  double volume24H;
  double percentChange1H;
  double percentChange24H;
  double percentChange7D;
  double marketCap;
  DateTime lastUpdated;

  factory Usd.fromJson(Map<String, dynamic> json) => Usd(
        price: json["price"] == null ? null : json["price"].toDouble(),
        volume24H:
            json["volume_24h"] == null ? null : json["volume_24h"].toDouble(),
        percentChange1H: json["percent_change_1h"] == null
            ? null
            : json["percent_change_1h"].toDouble(),
        percentChange24H: json["percent_change_24h"] == null
            ? null
            : json["percent_change_24h"].toDouble(),
        percentChange7D: json["percent_change_7d"] == null
            ? null
            : json["percent_change_7d"].toDouble(),
        marketCap:
            json["market_cap"] == null ? null : json["market_cap"].toDouble(),
        lastUpdated: DateTime.parse(json["last_updated"]),
      );

  Map<String, dynamic> toJson() => {
        "price": price == null ? null : price,
        "volume_24h": volume24H == null ? null : volume24H,
        "percent_change_1h": percentChange1H == null ? null : percentChange1H,
        "percent_change_24h":
            percentChange24H == null ? null : percentChange24H,
        "percent_change_7d": percentChange7D == null ? null : percentChange7D,
        "market_cap": marketCap == null ? null : marketCap,
        "last_updated": lastUpdated.toIso8601String(),
      };
}

enum Tag { MINEABLE }

final tagValues = EnumValues({"mineable": Tag.MINEABLE});

class Status {
  Status({
    this.timestamp,
    this.errorCode,
    this.errorMessage,
    this.elapsed,
    this.creditCount,
    this.notice,
  });

  DateTime timestamp;
  int errorCode;
  dynamic errorMessage;
  int elapsed;
  int creditCount;
  dynamic notice;

  factory Status.fromJson(Map<String, dynamic> json) => Status(
        timestamp: DateTime.parse(json["timestamp"]),
        errorCode: json["error_code"],
        errorMessage: json["error_message"],
        elapsed: json["elapsed"],
        creditCount: json["credit_count"],
        notice: json["notice"],
      );

  Map<String, dynamic> toJson() => {
        "timestamp": timestamp.toIso8601String(),
        "error_code": errorCode,
        "error_message": errorMessage,
        "elapsed": elapsed,
        "credit_count": creditCount,
        "notice": notice,
      };
}

class EnumValues<T> {
  Map<String, T> map;
  Map<T, String> reverseMap;

  EnumValues(this.map);

  Map<T, String> get reverse {
    if (reverseMap == null) {
      reverseMap = map.map((k, v) => new MapEntry(v, k));
    }
    return reverseMap;
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;
  Future<Payload> _future;

  Future<Payload> getCryptoPrices() async {
    var response = await http.get(
        "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=5000&convert=USD",
        headers: {
          'X-CMC_PRO_API_KEY': 'your-key',
          "Accept": "application/json",
        });

    if (response.statusCode == 200) {
      return payloadFromJson(response.body);
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _future = getCryptoPrices();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<Payload> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.data.length,
                        itemBuilder: (context, index) {
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot.data.data[index].name),
                                    Spacer(),
                                    Text(snapshot.data.data[index].lastUpdated
                                        .toIso8601String()),
                                    Spacer(),
                                    Text(
                                      snapshot.data.data[index].quote.usd.price
                                          .toString(),
                                    ),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}


问:
How to insert new user data into database in codeigniter 4
I am trying to post user data into the database but I got an error on the password section, please help

```<code>Call to undefined method App\Controllers\Register::encrypt()
</code>```

the model

```<code> public function register()
    {
        $model = new RegisterModel();

        if (!$this->validate([
            'username' => 'required|min_length[3]|max_length[25]',
            'password'  => 'required',
            'user_phone' => 'required|min_length[11]|max_length[11]'

        ])) {
            echo view('templates/header', ['page_title' => 'Register']);
            echo view('dashboard/register');
            echo view('templates/footer');
        } else {
            $model->save([
                'username' => $this->request->getVar('username'),
                'password'  => $this->encryption->encrypt($this->input->post('password')),
                'user_phone'  => $this->request->getVar('user_phone'),
            ]);

            echo view('news/success');
        }
    }
</code>```

and this is not reporting anything if a user already exists

```<code><?= \Config\Services::validation()->listErrors(); ?>
</code>```

答:
Go to app/config/encryption.php and set your secret key and driver.

or

You can replace the config file’s settings by passing a configuration object of your own to the Services call. The $config variable must be an instance of either the Config\Encryption class or an object that extends CodeIgniter\Config\BaseConfig.

```<code>$config         = new Config\Encryption();
$config->key    = 'aBigsecret_ofAtleast32Characters';
$config->driver = 'OpenSSL';
$encrypter = \Config\Services::encrypter($config);
</code>```

By the way codeigniter documnentation says:

DO NOT use this or any other encryption library for password storage! Passwords must be hashed instead, and you should do that through PHP’s Password Hashing extension.

password_hash() creates a new password hash using a strong one-way hashing algorithm. password_hash() is compatible with crypt(). Therefore, password hashes created by crypt() can be used with password_hash().

Various hash algorithms are supported by password_hash you can use anyone of them, here is an example.

```<code> $hashedpass = password_hash($password, PASSWORD_ARGON2I);
</code>```

To verify your password on login for example, use password_verify function it took the users password and the hash and returns boolean value.

```<code> password_verify($usepassword, $hash));
</code>```

For more details about hashing passwords see this link:
https://www.php.net/manual/en/function.password-hash.php

Body:
I am trying to post user data into the database but I got an error on the password section, please help

Call to undefined method App\Controllers\Register::encrypt()

the model

 public function register()
    {
        $model = new RegisterModel();

        if (!$this->validate([
            'username' => 'required|min_length[3]|max_length[25]',
            'password'  => 'required',
            'user_phone' => 'required|min_length[11]|max_length[11]'

        ])) {
            echo view('templates/header', ['page_title' => 'Register']);
            echo view('dashboard/register');
            echo view('templates/footer');
        } else {
            $model->save([
                'username' => $this->request->getVar('username'),
                'password'  => $this->encryption->encrypt($this->input->post('password')),
                'user_phone'  => $this->request->getVar('user_phone'),
            ]);

            echo view('news/success');
        }
    }

and this is not reporting anything if a user already exists

<?= \Config\Services::validation()->listErrors(); ?>

Body:
Go to app/config/encryption.php and set your secret key and driver.

or

You can replace the config file’s settings by passing a configuration object of your own to the Services call. The $config variable must be an instance of either the Config\Encryption class or an object that extends CodeIgniter\Config\BaseConfig.

$config         = new Config\Encryption();
$config->key    = 'aBigsecret_ofAtleast32Characters';
$config->driver = 'OpenSSL';
$encrypter = \Config\Services::encrypter($config);

By the way codeigniter documnentation says:

DO NOT use this or any other encryption library for password storage! Passwords must be hashed instead, and you should do that through PHP’s Password Hashing extension.

password_hash() creates a new password hash using a strong one-way hashing algorithm. password_hash() is compatible with crypt(). Therefore, password hashes created by crypt() can be used with password_hash().

Various hash algorithms are supported by password_hash you can use anyone of them, here is an example.

 $hashedpass = password_hash($password, PASSWORD_ARGON2I);

To verify your password on login for example, use password_verify function it took the users password and the hash and returns boolean value.

 password_verify($usepassword, $hash));

For more details about hashing passwords see this link:
https://www.php.net/manual/en/function.password-hash.php


问:
How to apply lifecycle patters in AWS elasticsearch to many indexs
I am trying to do this in AWS elasticsearch, whereby I create a template for the pattern application-logs-*, and then I want to apply a index policy log-rotation-policy for all indexes which match that expression. I have created my policy successfully, but when I try to create a template like so:

```<code>PUT _template/application-logs
{
  "index_patterns" : [
      "application-logs-*"
    ],
    "settings" : {
      "index.lifecycle.name": "log-rotation-policy",
    }
}
</code>```

I get an error:

```<code>    "type": "illegal_argument_exception",
    "reason": "unknown setting [index.policy_id] please check that any required plugins are installed, or check the breaking changes documentation for removed settings"
</code>```

The AWS documentation is extremely vague,

答:
Ok sorry I thought I would post this answer anyway because as I was writing this I figured out the problem, the correct key o use is: opendistro.index_state_management.policy_id so it should be:

```<code>PUT _template/application-logs
{
  "index_patterns" : [
      "application-logs-*"
    ],
    "settings" : {
      "opendistro.index_state_management.policy_id": "log-rotation-policy",
    }
}
</code>```

I found the answer here.

Body:
I am trying to do this in AWS elasticsearch, whereby I create a template for the pattern application-logs-*, and then I want to apply a index policy log-rotation-policy for all indexes which match that expression. I have created my policy successfully, but when I try to create a template like so:

PUT _template/application-logs
{
  "index_patterns" : [
      "application-logs-*"
    ],
    "settings" : {
      "index.lifecycle.name": "log-rotation-policy",
    }
}

I get an error:

    "type": "illegal_argument_exception",
    "reason": "unknown setting [index.policy_id] please check that any required plugins are installed, or check the breaking changes documentation for removed settings"

The AWS documentation is extremely vague,

Body:
Ok sorry I thought I would post this answer anyway because as I was writing this I figured out the problem, the correct key o use is: opendistro.index_state_management.policy_id so it should be:

PUT _template/application-logs
{
  "index_patterns" : [
      "application-logs-*"
    ],
    "settings" : {
      "opendistro.index_state_management.policy_id": "log-rotation-policy",
    }
}

I found the answer here.


问:
How to Make Transition Left Only with CSS
Hello I have a search arrow on my website and right it transitions on both left and right.
Because the arrow is on the right side of my website I want it to only transition left only.

In other words I want the search icon to stay in place and not move and input to transition to the left only so you can type in the input. I hope this makes sense.

body {
  background: darkgrey;
}

.search-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #2f3640;
  height: 40px;
  border-radius: 40px;
  padding: 10px;
}

.search-box:hover>.search-txt {
  width: 240px;
  padding: 0 6px;
}

.search-box:hover>.search-btn {
  background: white;
}

.search-btn {
  /*   position: absolute; */
  color: lightblue;
  float: right;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #2f3640;
  display: flex;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  transition: 0.4s;
}

.search-txt {
  border: none;
  background: none;
  outline: none;
  float: left;
  padding: 0;
  color: white;
  font-size: 16px;
  transition: 0.4s;
  line-height: 40px;
  width: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
</head>

<div class="search-box">
  <input class="search-txt" type="text" name="" placeholder="Type to Search">

    <i class="fas fa-search"></i>

</div></code>```

答:
You only need to change few properties as below:

```<code>.search-box {
  position: absolute;
  top:50%;
  right:50%;
  transform: translate(0, -50%);
  background: #2f3640;
  height: 40px;
  border-radius: 40px;
  padding: 10px;
}
</code>```

Please, find the complete code below. Hope it helps.

body {
  background: darkgrey;
}

.search-box {
  position: absolute;
  top:50%;
  right:50%;
  transform: translate(0, -50%);
  background: #2f3640;
  height: 40px;
  border-radius: 40px;
  padding: 10px;
}

.search-box:hover>.search-txt {
  width: 240px;
  padding: 0 6px;
}

.search-box:hover>.search-btn {
  background: white;
}

.search-btn {
  /*   position: absolute; */
  color: lightblue;
  float: right;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #2f3640;
  display: flex;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  transition: 0.4s;
}

.search-txt {
  border: none;
  background: none;
  outline: none;
  float: left;
  padding: 0;
  color: white;
  font-size: 16px;
  transition: 0.4s;
  line-height: 40px;
  width: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
</head>

<div class="search-box">
  <input class="search-txt" type="text" name="" placeholder="Type to Search">

    <i class="fas fa-search"></i>

</div></code>```

Body:
Hello I have a search arrow on my website and right it transitions on both left and right.
Because the arrow is on the right side of my website I want it to only transition left only.

In other words I want the search icon to stay in place and not move and input to transition to the left only so you can type in the input. I hope this makes sense.

body {
  background: darkgrey;
}

.search-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #2f3640;
  height: 40px;
  border-radius: 40px;
  padding: 10px;
}

.search-box:hover>.search-txt {
  width: 240px;
  padding: 0 6px;
}

.search-box:hover>.search-btn {
  background: white;
}

.search-btn {
  /*   position: absolute; */
  color: lightblue;
  float: right;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #2f3640;
  display: flex;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  transition: 0.4s;
}

.search-txt {
  border: none;
  background: none;
  outline: none;
  float: left;
  padding: 0;
  color: white;
  font-size: 16px;
  transition: 0.4s;
  line-height: 40px;
  width: 0px;
}

  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />

  <input class="search-txt" type="text" name="" placeholder="Type to Search">

Body:
You only need to change few properties as below:

.search-box {
  position: absolute;
  top:50%;
  right:50%;
  transform: translate(0, -50%);
  background: #2f3640;
  height: 40px;
  border-radius: 40px;
  padding: 10px;
}

Please, find the complete code below. Hope it helps.

body {
  background: darkgrey;
}

.search-box {
  position: absolute;
  top:50%;
  right:50%;
  transform: translate(0, -50%);
  background: #2f3640;
  height: 40px;
  border-radius: 40px;
  padding: 10px;
}

.search-box:hover>.search-txt {
  width: 240px;
  padding: 0 6px;
}

.search-box:hover>.search-btn {
  background: white;
}

.search-btn {
  /*   position: absolute; */
  color: lightblue;
  float: right;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #2f3640;
  display: flex;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  transition: 0.4s;
}

.search-txt {
  border: none;
  background: none;
  outline: none;
  float: left;
  padding: 0;
  color: white;
  font-size: 16px;
  transition: 0.4s;
  line-height: 40px;
  width: 0px;
}

<head>
  <link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous" />
</head>

<div class="search-box">
  <input class="search-txt" type="text" name="" placeholder="Type to Search">
  <a class="search-btn" href="#">
    <i class="fas fa-search"></i>
  </a>
</div>


问:
SQL Function to Replace specific text with Count
I'm looking for a function to get result in below format:

Input:

```<code>| name     |
| -------- |
| DFHG     |
| DRTYFGJN |
| FGH      |
| FGH      |
| NBHFGD   |
| OIUKJH   |
| RTFHGJ   |
| TDHG     |
</code>```

Desired output:

```<code>| id  | name     |
| --- | -------- |
| 1   | DFHG     |
| 2   | DRTYFGJN |
| 3   | FGH      |
| 4   | FGH      |
| 5   | NBHFGD   |
| 6   | OIUKJH   |
| 7   | RTFHGJ   |
| 8   | TDHG     |
</code>```

Thank you in advance :)

答:
First option is by using variable

```<code>set @rank=0;

select
    @rank:=@rank+1 as id,
    name
from myTable
order by
    name;
</code>```

Second option is by using row_number(), only if you are using MySQL 8.0.

```<code>select
    row_number() over (order by name) as id,
    name
from myTable;
</code>```

Body:
I'm looking for a function to get result in below format:

Input:

| name     |
| -------- |
| DFHG     |
| DRTYFGJN |
| FGH      |
| FGH      |
| NBHFGD   |
| OIUKJH   |
| RTFHGJ   |
| TDHG     |

Desired output:

| id  | name     |
| --- | -------- |
| 1   | DFHG     |
| 2   | DRTYFGJN |
| 3   | FGH      |
| 4   | FGH      |
| 5   | NBHFGD   |
| 6   | OIUKJH   |
| 7   | RTFHGJ   |
| 8   | TDHG     |

Thank you in advance :)

Body:
First option is by using variable

set @rank=0;

select
    @rank:=@rank+1 as id,
    name
from myTable
order by
    name;

Second option is by using row_number(), only if you are using MySQL 8.0.

select
    row_number() over (order by name) as id,
    name
from myTable;


问:
What are XAND and XOR
What are XAND and XOR? Also is there an XNot</p>

答:
In the book written by Charles Petzold titled "Code" he says there are 6 gates. There is the AND logical gate, the OR gate, the NOR gate, the NAND gate, and the XOR gate. He also mentions the 6th gate briefly calling it the "coincidence gate" and implies it's not used very often. He says it has the opposite output of a XOR gate because a XOR gate has the output of "false" when it has two true or two false sides of the equation and the only way for a XOR gate to have its output be true is for one of the sides of the equation to be true and the other to be false, it doesn't matter which. The coincidence is the exact opposite of this because with the coincidence gate if one is true and the other is false (doesn't matter which is which) then it will have its output be "false" in both those cases. And the way for a coincidence gate to have its output be "true" is for both sides to be either false or true. If both are false the coincidence gate will evaluate as true. If both are true then the coincidence gate will also output "true" in that case as well.

So in the cases where the XOR gate outputs "false", the coincidence gate will output "true". And in the cases where the XOR gate will output "true", the coincidence gate will output "false".

ContentLicense: CC BY-SA 2.5

Title: What are XAND and XOR


问:
How to pivot table in dolphindb python api?
I have a dataframe like following in python:

```<code>  time                 A    B    C      D  E  F
0 2019-12-19 15:00:00  foo  one  small  1  2  2
1 2019-12-19 15:00:30  foo  one  large  2  4  4
2 2019-12-19 15:01:00  foo  one  large  2  5  5
3 2019-12-19 15:01:30  foo  two  small  3  5  5
4 2019-12-19 15:02:00  foo  two  small  3  6  6
5 2019-12-19 15:02:30  bar  one  large  4  6  6
6 2019-12-19 15:03:00  bar  one  small  5  8  8
7 2019-12-19 15:03:30  bar  two  small  6  9  9
8 2019-12-19 15:04:00  bar  two  large  7  9  9
</code>```

How can I get the following dataframe by dolphindb python orca api?

```<code>E    2    4    5     6  8    9
A
bar  NaN  NaN  NaN   4  5.0  13.0
foo  1.0  2.0  5.0   3  NaN   NaN
</code>```

The number in the dataframe means sum(D) in same A and E.

答:
In pandas, you can pivot a table by pd.pivot_table(df, values='D', index='A', columns='E', aggfunc='sum'). As for Orca, you just replace the pd with orca:

```<code>orca.pivot_table(df, values='D', index='A', columns='E', aggfunc='sum')
</code>```

It returns the following DataFrame:

```<code>E     C2   C4   C5  C6   C8    C9
A
bar  NaN  NaN  NaN   4  5.0  13.0
foo  1.0  2.0  5.0   3  NaN   NaN
</code>```

As you can see, the DataFrame has an extra prefix 'C' in its column names. This is because DolphinDB does not allow a column name starting with a digit.

Body:
I have a dataframe like following in python:

  time                 A    B    C      D  E  F
0 2019-12-19 15:00:00  foo  one  small  1  2  2
1 2019-12-19 15:00:30  foo  one  large  2  4  4
2 2019-12-19 15:01:00  foo  one  large  2  5  5
3 2019-12-19 15:01:30  foo  two  small  3  5  5
4 2019-12-19 15:02:00  foo  two  small  3  6  6
5 2019-12-19 15:02:30  bar  one  large  4  6  6
6 2019-12-19 15:03:00  bar  one  small  5  8  8
7 2019-12-19 15:03:30  bar  two  small  6  9  9
8 2019-12-19 15:04:00  bar  two  large  7  9  9

How can I get the following dataframe by dolphindb python orca api?

E    2    4    5     6  8    9
A
bar  NaN  NaN  NaN   4  5.0  13.0
foo  1.0  2.0  5.0   3  NaN   NaN

The number in the dataframe means sum(D) in same A and E.

Body:
In pandas, you can pivot a table by pd.pivot_table(df, values='D', index='A', columns='E', aggfunc='sum'). As for Orca, you just replace the pd with orca:

orca.pivot_table(df, values='D', index='A', columns='E', aggfunc='sum')

It returns the following DataFrame:

E     C2   C4   C5  C6   C8    C9
A
bar  NaN  NaN  NaN   4  5.0  13.0
foo  1.0  2.0  5.0   3  NaN   NaN

As you can see, the DataFrame has an extra prefix 'C' in its column names. This is because DolphinDB does not allow a column name starting with a digit.