问:
Getting an error when launching a material date picker from a fragment android
I'm trying to launch an Material date picker from a fragment and I'm getting this error

java.lang.IllegalStateException: Fragment MaterialDatePicker{6058a76} (da2fbbc0-ee9f-4536-85f7-3942c18a1087) not attached to an activity.

My Fragment

```<code>@AndroidEntryPoint
class ReportFragment : Fragment() {

    private var _binding: FragmentReportBinding? = null
    private val binding get() = _binding!!

    private var stDate: Long? = null
    private var ndDate: Long? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentReportBinding.inflate(inflater, container, false)

        setUpUi()

        return binding.root
    }

    private fun setUpUi() {
        with(binding) {
            startDate.setOnClickListener {
                showDatePicker(
                    getString(R.string.select_start_date),
                    selectedStartDate,
                    DateType.START_DATE
                )
            }
        }
     }

      private fun showDatePicker(dateCategory: String, textView: TextView, dateType: DateType) {
        val datePicker = MaterialDatePicker.Builder.datePicker().apply {
            setTitleText(dateCategory)
            setInputMode(MaterialDatePicker.INPUT_MODE_CALENDAR)
            setSelection(MaterialDatePicker.todayInUtcMilliseconds())
        }.build()
        datePicker.apply {
            show(requireActivity().supportFragmentManager, "DATE_PICKER")
            addOnPositiveButtonClickListener {
                val date = this.headerText
                textView.text = date
                when (dateType) {
                    DateType.START_DATE -> stDate = it
                    DateType.END_DATE -> ndDate = it
                }
            }
        }
    }
}
</code>```
```<code>
enum class DateType {
    START_DATE,
    END_DATE
}
</code>```

This is the error I'm getting

```<code>E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.reachafrika.reachafrikapay, PID: 15162
    java.lang.IllegalStateException: Fragment MaterialDatePicker{6058a76} (da2fbbc0-ee9f-4536-85f7-3942c18a1087) not attached to an activity.
        at androidx.fragment.app.Fragment.requireActivity(Fragment.java:928)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment.showDatePicker(ReportFragment.kt:137)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment.setUpUi$lambda-4$lambda-1(ReportFragment.kt:71)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment.$r8$lambda$5X7432cB-iIkf15NUD-AuzGqT3E(Unknown Source:0)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment$$ExternalSyntheticLambda3.onClick(Unknown Source:4)
        at android.view.View.performClick(View.java:7184)
        at android.view.View.performClickInternal(View.java:7157)
        at android.view.View.access$3500(View.java:821)
        at android.view.View$PerformClick.run(View.java:27660)
        at android.os.Handler.handleCallback(Handler.java:914)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:225)
        at android.app.ActivityThread.main(ActivityThread.java:7563)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:994)
</code>```

答:
I replaced the

```<code>datePicker.apply {
        show(requireActivity() ...
</code>```

with the following code

```<code>            show(this@ReportFragment.requireActivity().supportFragmentManager, "DATE_PICKER")
</code>```

and it worked

Here is the full body function

```<code> private fun showDatePicker(dateCategory: String, textView: TextView, dateType: DateType) {
        val datePicker = MaterialDatePicker.Builder.datePicker().apply {
            setTitleText(dateCategory)
            setInputMode(MaterialDatePicker.INPUT_MODE_CALENDAR)
            setSelection(MaterialDatePicker.todayInUtcMilliseconds())
        }.build()
        datePicker.apply {
            show(this@ReportFragment.requireActivity().supportFragmentManager, "DATE_PICKER")
            addOnPositiveButtonClickListener {
                val date = this.headerText
                textView.text = date
                when (dateType) {
                    DateType.START_DATE -> stDate = it
                    DateType.END_DATE -> ndDate = it
                }
            }
        }
    }
</code>```

As the suggestion was given above.
that apply changes the receiver i.e. this, and the receiver here has requireActivity() defined too, so it resolves first.

Body:
I'm trying to launch an Material date picker from a fragment and I'm getting this error

java.lang.IllegalStateException: Fragment MaterialDatePicker{6058a76} (da2fbbc0-ee9f-4536-85f7-3942c18a1087) not attached to an activity.

My Fragment

@AndroidEntryPoint
class ReportFragment : Fragment() {

    private var _binding: FragmentReportBinding? = null
    private val binding get() = _binding!!

    private var stDate: Long? = null
    private var ndDate: Long? = null

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentReportBinding.inflate(inflater, container, false)

        setUpUi()

        return binding.root
    }

    private fun setUpUi() {
        with(binding) {
            startDate.setOnClickListener {
                showDatePicker(
                    getString(R.string.select_start_date),
                    selectedStartDate,
                    DateType.START_DATE
                )
            }
        }
     }

      private fun showDatePicker(dateCategory: String, textView: TextView, dateType: DateType) {
        val datePicker = MaterialDatePicker.Builder.datePicker().apply {
            setTitleText(dateCategory)
            setInputMode(MaterialDatePicker.INPUT_MODE_CALENDAR)
            setSelection(MaterialDatePicker.todayInUtcMilliseconds())
        }.build()
        datePicker.apply {
            show(requireActivity().supportFragmentManager, "DATE_PICKER")
            addOnPositiveButtonClickListener {
                val date = this.headerText
                textView.text = date
                when (dateType) {
                    DateType.START_DATE -> stDate = it
                    DateType.END_DATE -> ndDate = it
                }
            }
        }
    }
}

enum class DateType {
    START_DATE,
    END_DATE
}

This is the error I'm getting

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.reachafrika.reachafrikapay, PID: 15162
    java.lang.IllegalStateException: Fragment MaterialDatePicker{6058a76} (da2fbbc0-ee9f-4536-85f7-3942c18a1087) not attached to an activity.
        at androidx.fragment.app.Fragment.requireActivity(Fragment.java:928)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment.showDatePicker(ReportFragment.kt:137)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment.setUpUi$lambda-4$lambda-1(ReportFragment.kt:71)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment.$r8$lambda$5X7432cB-iIkf15NUD-AuzGqT3E(Unknown Source:0)
        at com.reachafrika.reachafrikapay.presentation.ui.fragments.reports.ReportFragment$$ExternalSyntheticLambda3.onClick(Unknown Source:4)
        at android.view.View.performClick(View.java:7184)
        at android.view.View.performClickInternal(View.java:7157)
        at android.view.View.access$3500(View.java:821)
        at android.view.View$PerformClick.run(View.java:27660)
        at android.os.Handler.handleCallback(Handler.java:914)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:225)
        at android.app.ActivityThread.main(ActivityThread.java:7563)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:994)

Body:
I replaced the

datePicker.apply {
        show(requireActivity() ...

with the following code

            show(this@ReportFragment.requireActivity().supportFragmentManager, "DATE_PICKER")

and it worked

Here is the full body function

 private fun showDatePicker(dateCategory: String, textView: TextView, dateType: DateType) {
        val datePicker = MaterialDatePicker.Builder.datePicker().apply {
            setTitleText(dateCategory)
            setInputMode(MaterialDatePicker.INPUT_MODE_CALENDAR)
            setSelection(MaterialDatePicker.todayInUtcMilliseconds())
        }.build()
        datePicker.apply {
            show(this@ReportFragment.requireActivity().supportFragmentManager, "DATE_PICKER")
            addOnPositiveButtonClickListener {
                val date = this.headerText
                textView.text = date
                when (dateType) {
                    DateType.START_DATE -> stDate = it
                    DateType.END_DATE -> ndDate = it
                }
            }
        }
    }

As the suggestion was given above.
that apply changes the receiver i.e. this, and the receiver here has requireActivity() defined too, so it resolves first.


来源: stackexchange

问:
Generic C# method with type constraint does not compile
I have an extension method with a generic type constraint. To my surprise, this code does not compile.

namespace N
{
    public interface M
    {
    }

    public class X : M
    {
        public static void DoSomething()
        {
            var x = new X();
            // ERROR: CS0407 'M X.DoSomethingWith(M)' has the wrong return type
            x.Configure(DoSomethingWith);
        }

        private static M DoSomethingWith(M obj)
        {
            return obj;
        }
    }

    public static class Extensions
    {
        public static T Configure<T>(this T obj, Func<T, T> action) where T : M
        {
            return action(obj);
        }
    }
}
```
<p>A similar construct, with a <code>void</code>-typed extension method, does compile:</p>
<pre class="lang-cs prettyprint-override"><code>    public interface M
    {
    }

    public class X : M
    {
        public static void DoSomething()
        {
            var x = new X();

            // compiles fine
            x.Configure(DoSomethingWith);
        }

        private static void DoSomethingWith(M obj)
        {
        }
    }

    public static class Extensions
    {
        public static void Configure<T>(this T obj, Action<T> action) where T : M
        {
        }
    }
</code>```

What is happening here and why is the first version not valid?

答: Because you "action" in Configure is of type Func<T, T>, which means that we receive T and return T. The factual type of T is X, not M. Method "DoSomething" returns in fact M, which cannot be casted implicitly to X, because X is more specific type. So what C# tries to do with your expression is to find a method "DoSomething", which accepts X and returns X, and there is no such method.</p>

ContentLicense: CC BY-SA 4.0

Body:
I have an extension method with a generic type constraint. To my surprise, this code does not compile.

namespace N
{
    public interface M
    {
    }

    public class X : M
    {
        public static void DoSomething()
        {
            var x = new X();
            // ERROR: CS0407 'M X.DoSomethingWith(M)' has the wrong return type
            x.Configure(DoSomethingWith);
        }

        private static M DoSomethingWith(M obj)
        {
            return obj;
        }
    }

    public static class Extensions
    {
        public static T Configure<T>(this T obj, Func<T, T> action) where T : M
        {
            return action(obj);
        }
    }
}

A similar construct, with a void-typed extension method, does compile:

    public interface M
    {
    }

    public class X : M
    {
        public static void DoSomething()
        {
            var x = new X();

            // compiles fine
            x.Configure(DoSomethingWith);
        }

        private static void DoSomethingWith(M obj)
        {
        }
    }

    public static class Extensions
    {
        public static void Configure<T>(this T obj, Action<T> action) where T : M
        {
        }
    }

What is happening here and why is the first version not valid?


问:
How to combine several iterators to one?
Can I return several iterators like one? For example in iterator() method maybe I can combine iterators like one?

```<code>import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class Addresses implements Iterable<Address> {
    private final Address main;
    private final List<Address> additional;
    private final List<Address> verified;

    public Addresses(Address main, List<Address> additional, List<Address> verified) {
        this.main = main;
        this.additional = additional;
        this.verified = verified;
    }

    public Address getMain() {
        return main;
    }

    public List<Address> getAdditional() {
        return additional;
    }

    public List<Address> getVerified() {
        return verified;
    }

    @Override
    public Iterator<Address> iterator() {
        // return 3 iterators main and additional and verified like one?
        return additional.iterator() + verified.iterator() + Collections.singletonList(main).iterator();
    }

}
</code>```

I just need to iterate through all items in both lists and the main address in one cycle but have them separated.  For example, I am going to use it like this

```<code>User user = ...
Addresses addresses = new Addresses(user.getMainAddress(), user.getAdditionalAddressess(), user.getVerifiedAddressess());
//iterate through addresses and change some fields an each address
user.setMain(addresses.getMain());
user.setAdditional(addresses.getAdditional());
user.setVerified(addresses.getVerified());
</code>```

答:
Use Stream.concat, and obtain an Iterator from the resulting Stream:

```<code>public Iterator<Address> iterator() {
    return Stream.concat(
        Stream.concat(additional.stream(), verified.stream()),
        Stream.of(main)).iterator();
}
</code>```

Be warned, if someone changes the additional or verified addresses while the Iterator is still being used, the results are “undefined.”  You can just document that in your class javadoc, or you can copy the Lists, so your method provides a snapshot and is unaffected by later changes:

```<code>public Iterator<Address> iterator() {
    Stream<String> additionalStream = new ArrayList<>(additional).stream();
    Stream<String> verifiedStream = new ArrayList<>(verified).stream();
    return Stream.concat(
        Stream.concat(additionalStream, verifiedStream),
        Stream.of(main)).iterator();
}
</code>```

Body:
Can I return several iterators like one? For example in iterator() method maybe I can combine iterators like one?

import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class Addresses implements Iterable<Address> {
    private final Address main;
    private final List<Address> additional;
    private final List<Address> verified;

    public Addresses(Address main, List<Address> additional, List<Address> verified) {
        this.main = main;
        this.additional = additional;
        this.verified = verified;
    }

    public Address getMain() {
        return main;
    }

    public List<Address> getAdditional() {
        return additional;
    }

    public List<Address> getVerified() {
        return verified;
    }

    @Override
    public Iterator<Address> iterator() {
        // return 3 iterators main and additional and verified like one?
        return additional.iterator() + verified.iterator() + Collections.singletonList(main).iterator();
    }

}

I just need to iterate through all items in both lists and the main address in one cycle but have them separated.  For example, I am going to use it like this

User user = ...
Addresses addresses = new Addresses(user.getMainAddress(), user.getAdditionalAddressess(), user.getVerifiedAddressess());
//iterate through addresses and change some fields an each address
user.setMain(addresses.getMain());
user.setAdditional(addresses.getAdditional());
user.setVerified(addresses.getVerified());

Body:
Use Stream.concat, and obtain an Iterator from the resulting Stream:

public Iterator<Address> iterator() {
    return Stream.concat(
        Stream.concat(additional.stream(), verified.stream()),
        Stream.of(main)).iterator();
}

Be warned, if someone changes the additional or verified addresses while the Iterator is still being used, the results are “undefined.”  You can just document that in your class javadoc, or you can copy the Lists, so your method provides a snapshot and is unaffected by later changes:

public Iterator<Address> iterator() {
    Stream<String> additionalStream = new ArrayList<>(additional).stream();
    Stream<String> verifiedStream = new ArrayList<>(verified).stream();
    return Stream.concat(
        Stream.concat(additionalStream, verifiedStream),
        Stream.of(main)).iterator();
}


问:
Where are playwright screenshots going - and how can I control this?
I have a really basic playwright (v1.18.1) test on Windows (11).

import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
    await page.goto('http://whatsmyuseragent.org/');
    // await page.screenshot(
    //  {path: `./tests/tmp/screenshots/whats.my.ua.${project:name}.png`});
    await page.screenshot();
});
```
<p>And when I run the test above - it says it worked.</p>
<pre class="lang-bash prettyprint-override"><code>Running :
     cd C:\playwright\tests
     && npx playwright test whats_my_user_agent.spec.ts --reporter=list

    Running 5 tests using 3 workers

       ok   [webkit] › whats_my_user_agent.spec.ts:3:1 › test   (3s)
       ok   [firefox] › whats_my_user_agent.spec.ts:3:1 › test   (4s)
       ok   [chromium] › whats_my_user_agent.spec.ts:3:1 › test   (5s)
       ok   [Mobile Chrome] › whats_my_user_agent.spec.ts:3:1 › test   (2s)
       ok   [Mobile Safari] › whats_my_user_agent.spec.ts:3:1 › test   (2s)

       5 passed   (8s)
</code>```

But I can find no sign of the screenshot file. There is no feedback giving any hints.

Where are the screenshots stored?

Is there a way to control the filename used?

Can the filename include the project name so that 5 png files are not written over each other?

答:
As I see it, if you uncomment the line in which you specify the path for your screenshot to be stored, you should find it there, for example, this:

import { test, expect } from '@playwright/test';

test('testing screenshot path', async ({ page }) => {
    await page.goto('https://playwright.dev/');
    await page.screenshot({ path:`./screenshots/screenshot.png` });
});
```
<p>The code above should result in</p>
<ul>
<li>having a screenshot of the website named <code>'screenshot.png'</code></li>
<li>in a folder named <code>'screenshots'</code></li>
<li>in the root of your project. If there's no folder by that name, it will be created.</li>
</ul>
<p>This step is executed for every browser. So the last run overwrites the previous screenshot taken.</p>
<p>TestInfo contains information about currently running test. This enables for example to store screenshots if chromium is used:</p>
<pre class="lang-js prettyprint-override"><code>test('testing chromium screenshots', async ({ page }, testInfo) => {
    await page.goto('https://playwright.dev/');
    if (testInfo.project.name === 'chromium') {
        await page.screenshot({ path:`./screenshots/${testInfo.title}.png` });
    }
});
</code>```

This would store a screenshot named testing chromium screenshots with the extension .png in the folder 'screenshots' in the root of your project, tested with chromium, while checking the test pass in every other project you might be running.

Hope all this helps.

Body:
I have a really basic playwright (v1.18.1) test on Windows (11).

import { test, expect } from '@playwright/test';

test('test', async ({ page }) => {
    await page.goto('http://whatsmyuseragent.org/');
    // await page.screenshot(
    //  {path: `./tests/tmp/screenshots/whats.my.ua.${project:name}.png`});
    await page.screenshot();
});

And when I run the test above - it says it worked.

Running :
     cd C:\playwright\tests
     && npx playwright test whats_my_user_agent.spec.ts --reporter=list

    Running 5 tests using 3 workers

       ok   [webkit] › whats_my_user_agent.spec.ts:3:1 › test   (3s)
       ok   [firefox] › whats_my_user_agent.spec.ts:3:1 › test   (4s)
       ok   [chromium] › whats_my_user_agent.spec.ts:3:1 › test   (5s)
       ok   [Mobile Chrome] › whats_my_user_agent.spec.ts:3:1 › test   (2s)
       ok   [Mobile Safari] › whats_my_user_agent.spec.ts:3:1 › test   (2s)

       5 passed   (8s)

But I can find no sign of the screenshot file. There is no feedback giving any hints.

Where are the screenshots stored?

Is there a way to control the filename used?

Can the filename include the project name so that 5 png files are not written over each other?

Body:
As I see it, if you uncomment the line in which you specify the path for your screenshot to be stored, you should find it there, for example, this:

import { test, expect } from '@playwright/test';

test('testing screenshot path', async ({ page }) => {
    await page.goto('https://playwright.dev/');
    await page.screenshot({ path:`./screenshots/screenshot.png` });
});

The code above should result in

having a screenshot of the website named 'screenshot.png'

in a folder named 'screenshots'

in the root of your project. If there's no folder by that name, it will be created.

This step is executed for every browser. So the last run overwrites the previous screenshot taken.

TestInfo contains information about currently running test. This enables for example to store screenshots if chromium is used:

test('testing chromium screenshots', async ({ page }, testInfo) => {
    await page.goto('https://playwright.dev/');
    if (testInfo.project.name === 'chromium') {
        await page.screenshot({ path:`./screenshots/${testInfo.title}.png` });
    }
});

This would store a screenshot named testing chromium screenshots with the extension .png in the folder 'screenshots' in the root of your project, tested with chromium, while checking the test pass in every other project you might be running.

Hope all this helps.


问:
show featured or sponsored products like amazon using laravel query in e-commerce Web App
I am trying to show featured products like amazon i.e. two featured products at top, two in middle and two at bottom, with non-featured/normal products in between them(, just like amazon). I have a field featured in products table of which value is true or false if its featured or non-featured. Not able to find way to write a query for the same. Is it possible to do it using single query?

I also have to use pagination and sorting with the above.

```<code>if (request()->sortBy && request()->sortBy === 'featured') {
            $usIt = $query;
            $featuredProducts = $usIt->where('featured', 1)->inRandomOrder()->paginate(6);
            $simpleProducts = $usIt->where('featured', 0)->paginate(6);

            $count = count($featuredProducts) + count($simpleProducts);
            if ($count === 12) {
                $payload = $this->sortByFeatured($featuredProducts, $simpleProducts);
            } else {
                $payload = $query->paginate(12);//todo:fix this gives empty data
            }
        } else {
            $payload = $query->paginate(12);
        }

private function sortByFeatured($featuredProducts, $simpleProducts)
    {
        $data = [];
        array_push($data,
            $featuredProducts[0], $featuredProducts[1],
            $simpleProducts[0], $simpleProducts[1], $simpleProducts[2],
            $featuredProducts[2], $featuredProducts[3],
            $simpleProducts[3], $simpleProducts[4], $simpleProducts[5],
            $featuredProducts[4], $featuredProducts[5],
        );
return $data;
}
</code>```

What I am trying to do is to make two queries one with random featured products and another with normal paginated products and put featured products in top middle and bottom of paginated normal products. But I think I am not doing it the right way. Please guide/help.

答:
I think you should have a seperate collection for featured products and in the blade you should have a different sections. I didn't understand your code entirely, so let me give a simplified solution so you can work on it.

```<code>$items = 12;

$products = Product::where('is_featured, 0)->paginate($items);

// I don't remember the key of items in the paginated collection.
// It's probably data, but you can find it, if it isn't.
$products->data = $product->data->chunk($items/2);

$featured = Product::where('is_featured, 1)->limit(6)->get()->chunk(2);
</code>```

In blade

```<code><div class="featured--top">
    @foreach($featured[0] as $product)
    ...
    @endforeach
</div>
<div class="main--top">
    @foreach($products[0] as $product)
    ...
    @endforeach
</div>
<div class="featured--center">
    @foreach($featured[1] as $product)
    ...
    @endforeach
</div>
... and other parts.
</code>```

Body:
I am trying to show featured products like amazon i.e. two featured products at top, two in middle and two at bottom, with non-featured/normal products in between them(, just like amazon). I have a field featured in products table of which value is true or false if its featured or non-featured. Not able to find way to write a query for the same. Is it possible to do it using single query?

I also have to use pagination and sorting with the above.

if (request()->sortBy && request()->sortBy === 'featured') {
            $usIt = $query;
            $featuredProducts = $usIt->where('featured', 1)->inRandomOrder()->paginate(6);
            $simpleProducts = $usIt->where('featured', 0)->paginate(6);

            $count = count($featuredProducts) + count($simpleProducts);
            if ($count === 12) {
                $payload = $this->sortByFeatured($featuredProducts, $simpleProducts);
            } else {
                $payload = $query->paginate(12);//todo:fix this gives empty data
            }
        } else {
            $payload = $query->paginate(12);
        }

private function sortByFeatured($featuredProducts, $simpleProducts)
    {
        $data = [];
        array_push($data,
            $featuredProducts[0], $featuredProducts[1],
            $simpleProducts[0], $simpleProducts[1], $simpleProducts[2],
            $featuredProducts[2], $featuredProducts[3],
            $simpleProducts[3], $simpleProducts[4], $simpleProducts[5],
            $featuredProducts[4], $featuredProducts[5],
        );
return $data;
}

What I am trying to do is to make two queries one with random featured products and another with normal paginated products and put featured products in top middle and bottom of paginated normal products. But I think I am not doing it the right way. Please guide/help.

Body:
I think you should have a seperate collection for featured products and in the blade you should have a different sections. I didn't understand your code entirely, so let me give a simplified solution so you can work on it.

$items = 12;

$products = Product::where('is_featured, 0)->paginate($items);

// I don't remember the key of items in the paginated collection.
// It's probably data, but you can find it, if it isn't.
$products->data = $product->data->chunk($items/2);

$featured = Product::where('is_featured, 1)->limit(6)->get()->chunk(2);

In blade

<div class="featured--top">
    @foreach($featured[0] as $product)
    ...
    @endforeach
</div>
<div class="main--top">
    @foreach($products[0] as $product)
    ...
    @endforeach
</div>
<div class="featured--center">
    @foreach($featured[1] as $product)
    ...
    @endforeach
</div>
... and other parts.


问:
Why not sprite larger images that are page content?
The typical rule of thumb when it comes to using CSS sprites for images is that you should only do it for smaller images (like icons) and that actual image content should always be represented through  elements. My question is: why? Aren't the advantages of spriting worthwhile for content images as well?

One reason I have read is to enable the use of alt text, to be more syntactically correct and accessible to screen-readers. However, when that is a concern, couldn't you just as easily use a single tiny transparent image with all the syntactical sugar atop a sprite that presents the real visual content?

答:
Sprites are usually usefull for static contents (images that are common on many pages).
Content pictures often appears in only one page, so you can't add it to your sprite file.

If you want to have real-time sprite generation, making custom sprite file with all your pictures, I think the generation cost is far more expensive than the duplicated HTTP calls it saves.

Sprites are here to save HTTP requests, but you should not waste server-side computation time to make it, nor put expensive and unusefull pictures in your sprite file.

ContentLicense: CC BY-SA 3.0


问:
How do I force a browser to go to my local site in IIS instead of the internet site?
I have a handful of sites set up in the root directory of IIS.  I also have them set up in the host file, to route to my local IP address.  When I open a browser and type 127.0.0.1/example/index.html, the page opens in my browser. I need to be able to type in example.com and have it open that page, but when I type example.com in a browser, I get the following:

Unable to connect

An error occurred during a connection to example.com.

The site could be temporarily unavailable or too busy. Try again in a
few moments.

If you are unable to load any pages, check your computer’s network

connection.

If your computer or network is protected by a firewall or proxy, make
sure that Firefox is permitted to access the Web.

Also, it changes in the address line of the browser to https://example.com. What could be preventing it from opening my local site?

答: Evidently it is an issue with the Firefox browser.  I tried in both Edge (ew) and Chrome, and the local site came up as expected.  I tried making a couple of network security changes in Firefox, but was not able to get it to work, so I'm just going to use Chrome.</p>


问:
Discord.js Button Links
Hello I am trying to use a discord.js button to link to a website

This is what I attempted to do

```<code>const row = new MessageActionRow()
.addComponents(
new MessageButton()
    .setCustomId('whatever')
    .setLabel('CLICK THIS')
    .setLink("google.com")
    .setStyle('LINK'),
);
</code>```

However this does not work due to set link not being a function

And the documentation doesnt help me out with this

答:
You need to use setURL instead of setLink

It is in the docs

let url 'https://google.com'
const row = new MessageActionRow()
.addComponents(
new MessageButton()
    .setLabel('Google')
    .setURL(url)
    .setStyle('LINK')
);
```

Title: Discord.js Button Links

Body:
Hello I am trying to use a discord.js button to link to a website

This is what I attempted to do

const row = new MessageActionRow()
.addComponents(
new MessageButton()
    .setCustomId('whatever')
    .setLabel('CLICK THIS')
    .setLink("google.com")
    .setStyle('LINK'),
);

However this does not work due to set link not being a function

And the documentation doesnt help me out with this


问:
Flutter sync state between 2 instances of the same widget on different pages
I have a question about my use case: assume we are currently on screen A which shows an instance of my chart-widget (amongst other things). I want to give the user the opportunity to show that chart on the full app-screen by allowing to tap on a "full-screen" button at the top-right. On full screen button click, I push a new MaterialPageRoute and show the same widget instance of the chart on the whole screen (screen B).

However I miss something important, which is that the fullscreen widget should stay in sync with the original widget. I.e. if the user makes any modification in fullscreen, after closing the fullscreen mode, the original chart should be in the same state as the fullscreen chart. I currently don't know how to achieve this. I tried by using the same GlobalKey for both, but without luck.
Any hints?

Screen A:

Screen B:

Some code:

My Fullscreenable widget which enables to show any Widget on a on the full scaffold body within a new page:

class Fullscreenable extends StatelessWidget {
  final String name;
  final Widget child;

  const Fullscreenable({
    Key? key,
    required this.child,
    this.name = "",
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        child,
        Positioned(
          top: -12,
          right: -12,
          child: IconButton(
            // visualDensity: VisualDensity.compact,
            padding: EdgeInsets.zero,
            icon: const Icon(Icons.fullscreen),
            onPressed: () {
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (BuildContext context) => FullScreenView(
                      title: name,
                      child: child,
                    ),
                  // fullscreenDialog: true,
                ),
              );
            },
          ),
        )
      ],
    );
  }
}
```
<p>Screen A:</p>
<pre class="lang-dart prettyprint-override"><code>...
Column(
  children: [
    Fullscreenable(
      name: "This is the title",
      child: MyChart()
    ),
    ...
  ],
)
...
</code>```

Screen B (FullscreenView):

class FullScreenView extends StatelessWidget {
  final String title;
  final Widget child;

  const FullScreenView({Key? key, required this.child, this.title = ""})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
        toolbarHeight: 48,
      ),
      body: child,
    );
  }
}
```

答: As a native solution, you can consider ValueNotifier and ValueListenableBuilder. Or implement some state manager.

Body:
I have a question about my use case: assume we are currently on screen A which shows an instance of my chart-widget (amongst other things). I want to give the user the opportunity to show that chart on the full app-screen by allowing to tap on a "full-screen" button at the top-right. On full screen button click, I push a new MaterialPageRoute and show the same widget instance of the chart on the whole screen (screen B).

However I miss something important, which is that the fullscreen widget should stay in sync with the original widget. I.e. if the user makes any modification in fullscreen, after closing the fullscreen mode, the original chart should be in the same state as the fullscreen chart. I currently don't know how to achieve this. I tried by using the same GlobalKey for both, but without luck.
Any hints?

Screen A:

Screen B:

Some code:

My Fullscreenable widget which enables to show any Widget on a on the full scaffold body within a new page:

class Fullscreenable extends StatelessWidget {
  final String name;
  final Widget child;

  const Fullscreenable({
    Key? key,
    required this.child,
    this.name = "",
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        child,
        Positioned(
          top: -12,
          right: -12,
          child: IconButton(
            // visualDensity: VisualDensity.compact,
            padding: EdgeInsets.zero,
            icon: const Icon(Icons.fullscreen),
            onPressed: () {
              Navigator.pushReplacement(
                context,
                MaterialPageRoute(
                  builder: (BuildContext context) => FullScreenView(
                      title: name,
                      child: child,
                    ),
                  // fullscreenDialog: true,
                ),
              );
            },
          ),
        )
      ],
    );
  }
}

Screen A:

...
Column(
  children: [
    Fullscreenable(
      name: "This is the title",
      child: MyChart()
    ),
    ...
  ],
)
...

Screen B (FullscreenView):

class FullScreenView extends StatelessWidget {
  final String title;
  final Widget child;

  const FullScreenView({Key? key, required this.child, this.title = ""})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
        toolbarHeight: 48,
      ),
      body: child,
    );
  }
}


问:
Change Pin Color when user tapped
I would change the color from red to green of an annotation when the user pin tapped addition to changing its title and subtitle.

I am truly lost. I searched how to make a custom annotation pin, ok. I found the implementation of the method when the user touches the pin didSelectAnnotationView and it works when I tap the annotation NSLog(@"Tap") ; , but now I can not change the pin that was touched.

Thank you very much everyone for your contributions.

Ciao

答:
To set the pin color, make use of MKPinAnnotationView pinColor property.

```<code>MKPinAnnotationView *pin = [[MKPinAnnotationView alloc] init]
pin.pinColor = MKPinAnnotationColorGreen;
</code>```

For custom annotation image, set the image property, as such.

```<code>UIImage *annImage = [UIImage imageNamed:@"AnnotationIcon.png"];
annView.image = annImage;
</code>```

Do note that the MKPinAnnotationView animateDrop property will not work on custom images. There's a way to duplicate that animation though. See How do I animate MKAnnotationView drop?

Update
So bascially, you do this if you wanna change from red to green upon being selected.

```<code>- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKPinAnnotationView *)view {
    view.pinColor = MKPinAnnotationColorGreen;

}

- (MKAnnotationView *)mapView:(MKMapView *)aMapView
            viewForAnnotation:(id)ann {

    NSString *identifier = @"myPin";
    MKPinAnnotationView *annView = (MKPinAnnotationView *)
    [aMapView dequeueReusableAnnotationViewWithIdentifier:identifier];
    if (annView == nil) {
        annView= [[[MKPinAnnotationView alloc] initWithAnnotation:ann
                                               reuseIdentifier:identifier]
               autorelease];
    } else {
        annView.annotation = ann;
    }
// you can define the properties here.

return annView;
}
</code>```

Title: Change Pin Color when user tapped

Body:
To set the pin color, make use of MKPinAnnotationView pinColor property.

MKPinAnnotationView *pin = [[MKPinAnnotationView alloc] init]
pin.pinColor = MKPinAnnotationColorGreen;

For custom annotation image, set the image property, as such.

UIImage *annImage = [UIImage imageNamed:@"AnnotationIcon.png"];
annView.image = annImage;

Do note that the MKPinAnnotationView animateDrop property will not work on custom images. There's a way to duplicate that animation though. See How do I animate MKAnnotationView drop?

Update
So bascially, you do this if you wanna change from red to green upon being selected.

- (void)mapView:(MKMapView *)mapView didSelectAnnotationView:(MKPinAnnotationView *)view {
    view.pinColor = MKPinAnnotationColorGreen;

}

- (MKAnnotationView *)mapView:(MKMapView *)aMapView
            viewForAnnotation:(id)ann {

    NSString *identifier = @"myPin";
    MKPinAnnotationView *annView = (MKPinAnnotationView *)
    [aMapView dequeueReusableAnnotationViewWithIdentifier:identifier];
    if (annView == nil) {
        annView= [[[MKPinAnnotationView alloc] initWithAnnotation:ann
                                               reuseIdentifier:identifier]
               autorelease];
    } else {
        annView.annotation = ann;
    }
// you can define the properties here.

return annView;
}


问:
RRDTOOL - RPN-Expression help, how to reference input in COMPUTE DS (add two DS values or the LAST DS value with a new number)?
I have a data feed that has a single value that increases over time until a forced wrap-around.
I have the wrap-around under control.
The value from the data feed I pass into a RRD GAUGE as ds1.
I want to add a couple data sources to handle exceptions where on a certain condition detected by my script (that calls rrdupdate) to add some details for reporting.
When the condition is true in the script, I want to update the RRD with:

the normal value into ds1

the difference of the prior value to the current value to be marked as batch exceptions into ds2

count (sum) all ds2 values in a similar way to ds1.

I've been playing with the below but wonder if there is a method using COMPUTE or do I need to code all the logic into the bash script to poll rrdinfo, fetch the last_ds lines and prep the data accordingly?  Does the rrd COMPUTE type have the ability to read other DS's?

If ds2.value > 0 then set ds3.value to (ds3.last_ds + ds2.value) ?

I looked at the rpn-expression and found it references 'input' but does not show how to feed those inputs into the COMPUTE operation?

eg:
Currently state

```<code>DS:ds1:GAUGE:28800:0:U
DS:ds2:COUNTER:1800:0:U
DS:ds3:GAUGE:1800:0:U
RRA:LAST:0.99999:1:72000
RRA:LAST:0.99999:4:17568
RRA:LAST:0.99999:8:18000
RRA:LAST:0.99999:32:4500
RRA:LAST:0.99999:96:1825
</code>```

Desired state?

```<code>DS:ds1:GAUGE:28800:0:U
DS:ds2:COUNTER:1800:0:U
DS:ds3:COMPUTE:1800:0:U
DS:cs1:COMPUTE:input,0,GT,ds3,ds2,+,input,IF  <-- what is 'input' is it passed via rrdupdate cs1:[value]?
RRA:LAST:0.99999:1:72000
RRA:LAST:0.99999:4:17568
RRA:LAST:0.99999:8:18000
RRA:LAST:0.99999:32:4500
RRA:LAST:0.99999:96:1825
</code>```

Alternatively ds1 could have store the total without the exceptions and I could use an AREA and a STACK to plot the total.

If someone is knowledgeable of rpn-expressions when used with rrd it would be a massive help to clarity the rpn-express input reference & what is possible.  There is very limited info online about this.  If the script has to poll the RRD files for last_ds and do the calculations that is fine just it RRA has the smarts in the COMPUTE DS type, I'd rather use them.

Thank you.

答:
A COMPUTE type datasource needs to have an RPN formula that completely describes it in terms of the other (non-compute) datasources.  So, you cannot have multiple definitions of the same source, nor can it populate until the last of the other DS for that time window have been populated.

So, for example, if you have datasources a and b, and you want a COMPUTE type datasource that is equal to a if b<0, and a+b otherwise, you can use

```<code>DS:a:COUNTER:1800:0:U
DS:b:GAUGE:1800:0:U
DS:c:COMPUTE:b,0,GT,a,b,+,a,IF
</code>```

From this, you can see how the definition of c uses RPN to define a single value using the values of a and b (and a constant).  The calculation is performed solely within the configured time interval, and subsequently all three are stored and aggregated in the defined RRAs in the same way.  You can also then use the graphs functions over c exactly as you would for a or b; the compute function is used only at data storing time.

Here is a full working example for the benefit of the original poster:

```<code>rrdtool create test.rrd --step 1800 \
 DS:a:COUNTER:28800:0:U \
 DS:b:COUNTER:28000:0:U \
 DS:c:GAUGE:3600:0:U    \
 DS:d:COUNTER:3600:0:U  \
 DS:x:COMPUTE:b,0,GT,a,b,+,a,IF  \
 RRA:LAST:0.99999:1:72000 \
 RRA:LAST:0.99999:4:17568 \
 RRA:LAST:0.99999:8:18000 \
 RRA:LAST:0.99999:32:4500 \
 RRA:LAST:0.99999:96:1825
</code>```

Body:
I have a data feed that has a single value that increases over time until a forced wrap-around.
I have the wrap-around under control.
The value from the data feed I pass into a RRD GAUGE as ds1.
I want to add a couple data sources to handle exceptions where on a certain condition detected by my script (that calls rrdupdate) to add some details for reporting.
When the condition is true in the script, I want to update the RRD with:

the normal value into ds1

the difference of the prior value to the current value to be marked as batch exceptions into ds2

count (sum) all ds2 values in a similar way to ds1.

I've been playing with the below but wonder if there is a method using COMPUTE or do I need to code all the logic into the bash script to poll rrdinfo, fetch the last_ds lines and prep the data accordingly?  Does the rrd COMPUTE type have the ability to read other DS's?

If ds2.value > 0 then set ds3.value to (ds3.last_ds + ds2.value) ?

I looked at the rpn-expression and found it references 'input' but does not show how to feed those inputs into the COMPUTE operation?

eg:
Currently state

DS:ds1:GAUGE:28800:0:U
DS:ds2:COUNTER:1800:0:U
DS:ds3:GAUGE:1800:0:U
RRA:LAST:0.99999:1:72000
RRA:LAST:0.99999:4:17568
RRA:LAST:0.99999:8:18000
RRA:LAST:0.99999:32:4500
RRA:LAST:0.99999:96:1825

Desired state?

DS:ds1:GAUGE:28800:0:U
DS:ds2:COUNTER:1800:0:U
DS:ds3:COMPUTE:1800:0:U
DS:cs1:COMPUTE:input,0,GT,ds3,ds2,+,input,IF  <-- what is 'input' is it passed via rrdupdate cs1:[value]?
RRA:LAST:0.99999:1:72000
RRA:LAST:0.99999:4:17568
RRA:LAST:0.99999:8:18000
RRA:LAST:0.99999:32:4500
RRA:LAST:0.99999:96:1825

Alternatively ds1 could have store the total without the exceptions and I could use an AREA and a STACK to plot the total.

If someone is knowledgeable of rpn-expressions when used with rrd it would be a massive help to clarity the rpn-express input reference & what is possible.  There is very limited info online about this.  If the script has to poll the RRD files for last_ds and do the calculations that is fine just it RRA has the smarts in the COMPUTE DS type, I'd rather use them.

Thank you.

Body:
A COMPUTE type datasource needs to have an RPN formula that completely describes it in terms of the other (non-compute) datasources.  So, you cannot have multiple definitions of the same source, nor can it populate until the last of the other DS for that time window have been populated.

So, for example, if you have datasources a and b, and you want a COMPUTE type datasource that is equal to a if b<0, and a+b otherwise, you can use

DS:a:COUNTER:1800:0:U
DS:b:GAUGE:1800:0:U
DS:c:COMPUTE:b,0,GT,a,b,+,a,IF

From this, you can see how the definition of c uses RPN to define a single value using the values of a and b (and a constant).  The calculation is performed solely within the configured time interval, and subsequently all three are stored and aggregated in the defined RRAs in the same way.  You can also then use the graphs functions over c exactly as you would for a or b; the compute function is used only at data storing time.

Here is a full working example for the benefit of the original poster:

rrdtool create test.rrd --step 1800 \
 DS:a:COUNTER:28800:0:U \
 DS:b:COUNTER:28000:0:U \
 DS:c:GAUGE:3600:0:U    \
 DS:d:COUNTER:3600:0:U  \
 DS:x:COMPUTE:b,0,GT,a,b,+,a,IF  \
 RRA:LAST:0.99999:1:72000 \
 RRA:LAST:0.99999:4:17568 \
 RRA:LAST:0.99999:8:18000 \
 RRA:LAST:0.99999:32:4500 \
 RRA:LAST:0.99999:96:1825


问:
MY 'image' attribute has no file associated with it
With my reading of many answers to questions similar to mine, all of those answers did not find a solution to my problem.. so I will present them so that I may find a solution that fits my problem:
my View file:
enter image description here

my Template File:
enter image description here

my Admin file:
enter image description here

The Error:
enter image description here
enter image description here

I tried every solution with no hope.

```<code>from datetime import datetime
</code>```

from ckeditor.fields import RichTextField
from multiselectfield import MultiSelectField
from django.db import models

class Car(models.Model):
state_choice = (
('AL', 'Alabama'),
('AK', 'Alaska'),
('AZ', 'Arizona'),
('AR', 'Arkansas'),
('CA', 'California'),
('CO', 'Colorado'),
('CT', 'Connecticut'),
('DE', 'Delaware'),
('DC', 'District Of Columbia'),
('FL', 'Florida'),
('GA', 'Georgia'),
('HI', 'Hawaii'),
('ID', 'Idaho'),
('IL', 'Illinois'),
('IN', 'Indiana'),
('IA', 'Iowa'),
('KS', 'Kansas'),
('KY', 'Kentucky'),
('LA', 'Louisiana'),
('ME', 'Maine'),
('MD', 'Maryland'),
('MA', 'Massachusetts'),
('MI', 'Michigan'),
('MN', 'Minnesota'),
('MS', 'Mississippi'),
('MO', 'Missouri'),
('MT', 'Montana'),
('NE', 'Nebraska'),
('NV', 'Nevada'),
('NH', 'New Hampshire'),
('NJ', 'New Jersey'),
('NM', 'New Mexico'),
('NY', 'New York'),
('NC', 'North Carolina'),
('ND', 'North Dakota'),
('OH', 'Ohio'),
('OK', 'Oklahoma'),
('OR', 'Oregon'),
('PA', 'Pennsylvania'),
('RI', 'Rhode Island'),
('SC', 'South Carolina'),
('SD', 'South Dakota'),
('TN', 'Tennessee'),
('TX', 'Texas'),
('UT', 'Utah'),
('VT', 'Vermont'),
('VA', 'Virginia'),
('WA', 'Washington'),
('WV', 'West Virginia'),
('WI', 'Wisconsin'),
('WY', 'Wyoming'),
)

```<code>features_choices = (
    ('Cruise Control', 'Cruise Control'),
    ('Audio Interface', 'Audio Interface'),
    ('Airbags', 'Airbags'),
    ('Air Conditioning', 'Air Conditioning'),
    ('Seat Heating', 'Seat Heating'),
    ('Alarm System', 'Alarm System'),
    ('ParkAssist', 'ParkAssist'),
    ('Power Steering', 'Power Steering'),
    ('Reversing Camera', 'Reversing Camera'),
    ('Direct Fuel Injection', 'Direct Fuel Injection'),
    ('Auto Start/Stop', 'Auto Start/Stop'),
    ('Wind Deflector', 'Wind Deflector'),
    ('Bluetooth Handset', 'Bluetooth Handset'),
)

door_choices = (
    ('2', '2'),
    ('3', '3'),
    ('4', '4'),
    ('5', '5'),
    ('6', '6'),
)

transmission_choice = (
    ('A', 'Auto_shift'),
    ('M', 'Manual_shift'),
)

fuel_type_choices = (
    ('P', 'Petrol'),
    ('D', 'Diesel'),
    ('CNG', 'Compressed Natural Gas'),
    ('Et', 'Ethanol'),
    ('E', 'Electricity'),
)

year_choice = []
for r in range(2000, (datetime.now().year+1)):
    year_choice.append((r, r))

car_title = models.CharField(max_length=255)
city = models.CharField(max_length=100)
state = models.CharField(choices=state_choice, max_length=100)
color = models.CharField(max_length=100)
model = models.CharField(max_length=100)
year = models.IntegerField(('year'), choices=year_choice)
condition = models.CharField(max_length=100)
price = models.IntegerField()
description = RichTextField()
car_photo = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_1 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_2 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_3 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_4 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
features = MultiSelectField(choices=features_choices)
body_style = models.CharField(max_length=100)
engine = models.CharField(max_length=100)
transmission = models.CharField(
    choices=transmission_choice, max_length=100)
interior = models.CharField(max_length=100)
miles = models.IntegerField()
doors = models.CharField(choices=door_choices, max_length=10)
passengers = models.IntegerField()
vin_no = models.CharField(max_length=100)
milage = models.IntegerField()
fuel_type = models.CharField(choices=fuel_type_choices, max_length=50)
no_of_owners = models.IntegerField()
is_featured = models.BooleanField(default=False)
created_date = models.DateTimeField(default=datetime.now, blank=True)
</code>```

after trying the proposed solution:
enter image description here

答:
Your issue here is that by checking for {% if car.car_photo_4 %}, you're effectively checking if the attribute exists for this model (which it does, it's just empty). Since we know that car_photo_4 is always defined for the Car model, you should be checking that the url attribute is not empty or null.

You can do this by:

{% if car.car_photo_4.url %}

As a side note, you should use a ManyToManyField instead of statically defining the images as attributes to the Car model as it makes it simply to add more images for the Car model.

Body:
With my reading of many answers to questions similar to mine, all of those answers did not find a solution to my problem.. so I will present them so that I may find a solution that fits my problem:
my View file:
enter image description here

my Template File:
enter image description here

my Admin file:
enter image description here

The Error:
enter image description here
enter image description here

I tried every solution with no hope.

from datetime import datetime

from ckeditor.fields import RichTextField
from multiselectfield import MultiSelectField
from django.db import models

class Car(models.Model):
state_choice = (
('AL', 'Alabama'),
('AK', 'Alaska'),
('AZ', 'Arizona'),
('AR', 'Arkansas'),
('CA', 'California'),
('CO', 'Colorado'),
('CT', 'Connecticut'),
('DE', 'Delaware'),
('DC', 'District Of Columbia'),
('FL', 'Florida'),
('GA', 'Georgia'),
('HI', 'Hawaii'),
('ID', 'Idaho'),
('IL', 'Illinois'),
('IN', 'Indiana'),
('IA', 'Iowa'),
('KS', 'Kansas'),
('KY', 'Kentucky'),
('LA', 'Louisiana'),
('ME', 'Maine'),
('MD', 'Maryland'),
('MA', 'Massachusetts'),
('MI', 'Michigan'),
('MN', 'Minnesota'),
('MS', 'Mississippi'),
('MO', 'Missouri'),
('MT', 'Montana'),
('NE', 'Nebraska'),
('NV', 'Nevada'),
('NH', 'New Hampshire'),
('NJ', 'New Jersey'),
('NM', 'New Mexico'),
('NY', 'New York'),
('NC', 'North Carolina'),
('ND', 'North Dakota'),
('OH', 'Ohio'),
('OK', 'Oklahoma'),
('OR', 'Oregon'),
('PA', 'Pennsylvania'),
('RI', 'Rhode Island'),
('SC', 'South Carolina'),
('SD', 'South Dakota'),
('TN', 'Tennessee'),
('TX', 'Texas'),
('UT', 'Utah'),
('VT', 'Vermont'),
('VA', 'Virginia'),
('WA', 'Washington'),
('WV', 'West Virginia'),
('WI', 'Wisconsin'),
('WY', 'Wyoming'),
)

features_choices = (
    ('Cruise Control', 'Cruise Control'),
    ('Audio Interface', 'Audio Interface'),
    ('Airbags', 'Airbags'),
    ('Air Conditioning', 'Air Conditioning'),
    ('Seat Heating', 'Seat Heating'),
    ('Alarm System', 'Alarm System'),
    ('ParkAssist', 'ParkAssist'),
    ('Power Steering', 'Power Steering'),
    ('Reversing Camera', 'Reversing Camera'),
    ('Direct Fuel Injection', 'Direct Fuel Injection'),
    ('Auto Start/Stop', 'Auto Start/Stop'),
    ('Wind Deflector', 'Wind Deflector'),
    ('Bluetooth Handset', 'Bluetooth Handset'),
)

door_choices = (
    ('2', '2'),
    ('3', '3'),
    ('4', '4'),
    ('5', '5'),
    ('6', '6'),
)

transmission_choice = (
    ('A', 'Auto_shift'),
    ('M', 'Manual_shift'),
)

fuel_type_choices = (
    ('P', 'Petrol'),
    ('D', 'Diesel'),
    ('CNG', 'Compressed Natural Gas'),
    ('Et', 'Ethanol'),
    ('E', 'Electricity'),
)

year_choice = []
for r in range(2000, (datetime.now().year+1)):
    year_choice.append((r, r))

car_title = models.CharField(max_length=255)
city = models.CharField(max_length=100)
state = models.CharField(choices=state_choice, max_length=100)
color = models.CharField(max_length=100)
model = models.CharField(max_length=100)
year = models.IntegerField(('year'), choices=year_choice)
condition = models.CharField(max_length=100)
price = models.IntegerField()
description = RichTextField()
car_photo = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_1 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_2 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_3 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
car_photo_4 = models.ImageField(upload_to='photo/%Y%m%d/', blank=True)
features = MultiSelectField(choices=features_choices)
body_style = models.CharField(max_length=100)
engine = models.CharField(max_length=100)
transmission = models.CharField(
    choices=transmission_choice, max_length=100)
interior = models.CharField(max_length=100)
miles = models.IntegerField()
doors = models.CharField(choices=door_choices, max_length=10)
passengers = models.IntegerField()
vin_no = models.CharField(max_length=100)
milage = models.IntegerField()
fuel_type = models.CharField(choices=fuel_type_choices, max_length=50)
no_of_owners = models.IntegerField()
is_featured = models.BooleanField(default=False)
created_date = models.DateTimeField(default=datetime.now, blank=True)

after trying the proposed solution:
enter image description here


问:
How to recognize end of line in csv file for sql for LOAD DATA INFILE method? tried Lines Terminated by '' '\r' '\r\n' or '\n'..... nothing has worked
I have tried multiple lines terminated configuration '\r'  '\n'   '\r\n', but nothing works. I even tried LINES TERMINATED BY '', but that doesn't work either as one of the columns i dont need has text with spaces.   also is there a way to skip over certain columns in the CSV data files and input the 5 columns i want using this method without control over the csv files?</p>
```<code>$sql = "LOAD DATA INFILE '$finalfile' INTO TABLE baa_load_actual_test
     FIELDS TERMINATED BY ',';
     LINES TERMINATED BY '\r\n';
     IGNORE 1 LINES;
     (INTERVALSTARTTIME_GMT, INTERVALENDTIME_GMT, LOAD_TYPE, OPR_DT, OPR_HR,
             OPR_INTERVAL, MARKET_RUN_ID, TAC_AREA_NAME, LABEL, XML_DATA_ITEM, POS, MW, nexttolastcolumn, lastcolumn) ";
</code>```
```<code>2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,AZPS,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,2654,ACTUAL,1
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,BANC,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,1515,ACTUAL,2
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,BANCMID,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,241,ACTUAL,3
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,BANCRDNG,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,81,ACTUAL,4
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,BANCRSVL,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,99,ACTUAL,5
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,BANCSMUD,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,1005,ACTUAL,6
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,BANCWASN,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,35,ACTUAL,7
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,BCHA,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,7158,ACTUAL,8
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,CA ISO-TAC,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3,22015,ACTUAL,9
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,IPCO,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,1848,ACTUAL,10
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,LADWP,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,2363,ACTUAL,11
</code>```

答:
Try 'CHAR(10)' instead of '/r/n'.

CHAR(10) means CARRIAGE RETURN ( enter key ) in SQL.

Body:
I have tried multiple lines terminated configuration '\r'  '\n'   '\r\n', but nothing works. I even tried LINES TERMINATED BY '', but that doesn't work either as one of the columns i dont need has text with spaces.   also is there a way to skip over certain columns in the CSV data files and input the 5 columns i want using this method without control over the csv files?

$sql = "LOAD DATA INFILE '$finalfile' INTO TABLE baa_load_actual_test
     FIELDS TERMINATED BY ',';
     LINES TERMINATED BY '\r\n';
     IGNORE 1 LINES;
     (INTERVALSTARTTIME_GMT, INTERVALENDTIME_GMT, LOAD_TYPE, OPR_DT, OPR_HR,
             OPR_INTERVAL, MARKET_RUN_ID, TAC_AREA_NAME, LABEL, XML_DATA_ITEM, POS, MW, nexttolastcolumn, lastcolumn) ";

2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,AZPS,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,2654,ACTUAL,1
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,BANC,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,1515,ACTUAL,2
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,BANCMID,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,241,ACTUAL,3
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,BANCRDNG,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,81,ACTUAL,4
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,BANCRSVL,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,99,ACTUAL,5
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,BANCSMUD,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,1005,ACTUAL,6
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,BANCWASN,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,35,ACTUAL,7
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,BCHA,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,7158,ACTUAL,8
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,CA ISO-TAC,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3,22015,ACTUAL,9
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,IPCO,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,1848,ACTUAL,10
2022-02-10T07:00:00-00:00,2022-02-10T08:00:00-00:00,0,2022-02-09,24,0,ACTUAL,LADWP,Total Actual Hourly Integrated Load,SYS_FCST_ACT_MW,3.8,2363,ACTUAL,11


问:
How to load MySQL blob into C# byte array
I have a mysql table with a Medium Blob field that I filled with PDFs.

The PDFs are stored in the field without issue, and are inserted using the following query:

```<code>INSERT INTO PDFHistory ( OrderId, PDFByteArray) VALUES ( 123456, Convert.ToBase64String(pdf.ByteArray))
</code>```

I am unable to pull the record and populate a byte[] object. I get the error "The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters."

```<code>dbManager.Open();
using (DataTable dt = dbManager.ExecuteDataTable(CommandType.Text, "SELECT * FROM PDFHistory WHERE OrderId = {0} ORDER BY Timestamp DESC LIMIT 1" ))
{
   if (dt.Rows.Count > 0)
   {
       byte[] PDFByteArray = Convert.FromBase64String(dt.Rows[0]["PDFByteArray"].ToString());
   }
}
</code>```

Any insight is appreciated.

Edit:

The mysql blob record looks like this (in general)

JVBERi0xLjQKJ.....too much to post.....AAAAAAAAAA==

答:
Workable code in VB (NET CORE), try to use the same logic in C#</p>
```<code>        Dim Buf1 As Byte() = New Byte() {}
        ReDim Buf1(100)
        _DB.RawSqlQuery(Of Byte())($"select aes_encrypt('{Text}','{KeyString}') as aes_encrypt", Function(X)
                                                                                CType(X("aes_encrypt"), Byte()).CopyTo(Buf1, 0)
                                                                                ReDim Preserve Buf1(CType(X("aes_encrypt"), Byte()).Length - 1)
                                                                                Return Nothing
                                                                                End Function)
</code>```

Body:
I have a mysql table with a Medium Blob field that I filled with PDFs.

The PDFs are stored in the field without issue, and are inserted using the following query:

INSERT INTO PDFHistory ( OrderId, PDFByteArray) VALUES ( 123456, Convert.ToBase64String(pdf.ByteArray))

I am unable to pull the record and populate a byte[] object. I get the error "The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters."

dbManager.Open();
using (DataTable dt = dbManager.ExecuteDataTable(CommandType.Text, "SELECT * FROM PDFHistory WHERE OrderId = {0} ORDER BY Timestamp DESC LIMIT 1" ))
{
   if (dt.Rows.Count > 0)
   {
       byte[] PDFByteArray = Convert.FromBase64String(dt.Rows[0]["PDFByteArray"].ToString());
   }
}

Any insight is appreciated.

Edit:

The mysql blob record looks like this (in general)

JVBERi0xLjQKJ.....too much to post.....AAAAAAAAAA==

Body:
Workable code in VB (NET CORE), try to use the same logic in C#

        Dim Buf1 As Byte() = New Byte() {}
        ReDim Buf1(100)
        _DB.RawSqlQuery(Of Byte())($"select aes_encrypt('{Text}','{KeyString}') as aes_encrypt", Function(X)
                                                                                CType(X("aes_encrypt"), Byte()).CopyTo(Buf1, 0)
                                                                                ReDim Preserve Buf1(CType(X("aes_encrypt"), Byte()).Length - 1)
                                                                                Return Nothing
                                                                                End Function)


问:
0 test classes found in package 'drawable' Error in Android Studio
I find an issue when running my project in android studio what i see when i try to run is

```<code> 0 test classes found in package 'drawable'

 Process finished with exit code -1
 Empty test suite.
</code>```

Though I have searched for this issue I couldn't find a solution I even tried to invalidate cache and restart the project but still it doesn't works. This issue is only being caused for only this particular project however for a new project i make everything works smooth.

My gradle file

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

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"

    defaultConfig {
        applicationId "com.jiit.minor2.shubhamjoshi.human"
        minSdkVersion 17
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),   'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'com.android.support:recyclerview-v7:+'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.android.support:design:24.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'org.jsoup:jsoup:1.8.3'
    compile 'com.firebase:firebase-client-android:2.5.2+'
    compile 'com.github.amlcurran.showcaseview:library:5.4.3'
    compile 'com.firebaseui:firebase-ui:0.3.1'
    compile files('libs/twitter4j-core-4.0.4.jar')
}
</code>```

My project structure

Thanks In advance.

答:
For Android Studio's android-tests (not unit-tests), run in bash:

```<code>./gradlew :createDebugAndroidTestCoverageReport --continue
</code>```

Which shows actual problem, instead of just not found.

For me actual error was:

```<code>error: class ActivitySignInTest is public, should be declared in a file named ActivitySignInTest.java
</code>```

Body:
I find an issue when running my project in android studio what i see when i try to run is

 0 test classes found in package 'drawable'

 Process finished with exit code -1
 Empty test suite.

Though I have searched for this issue I couldn't find a solution I even tried to invalidate cache and restart the project but still it doesn't works. This issue is only being caused for only this particular project however for a new project i make everything works smooth.

My gradle file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "24.0.1"

    defaultConfig {
        applicationId "com.jiit.minor2.shubhamjoshi.human"
        minSdkVersion 17
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),   'proguard-rules.pro'
        }
    }

    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.1.1'
    compile 'com.android.support:recyclerview-v7:+'
    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.android.support:design:24.1.0'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'org.jsoup:jsoup:1.8.3'
    compile 'com.firebase:firebase-client-android:2.5.2+'
    compile 'com.github.amlcurran.showcaseview:library:5.4.3'
    compile 'com.firebaseui:firebase-ui:0.3.1'
    compile files('libs/twitter4j-core-4.0.4.jar')
}

My project structure

Thanks In advance.

Body:
For Android Studio's android-tests (not unit-tests), run in bash:

./gradlew :createDebugAndroidTestCoverageReport --continue

Which shows actual problem, instead of just not found.

For me actual error was:

error: class ActivitySignInTest is public, should be declared in a file named ActivitySignInTest.java


问:
how to make the histogram fill option work
I want to see the distribution difference between two groups in my data.
My data looks similar to

```<code>data <- data.frame(rnorm(500,mean = 3),sample(c(0,1), replace=TRUE, size=500))
colnames(data) <- c('x','y')
</code>```

And then I draw the histogram by

```<code>ggplot(data, aes(x = x, fill = y)) +
   geom_histogram(alpha=0.6, bins = 50, position = 'identity')
</code>```

But it returns

Can you please help find what the problem is? I just followed the examples from googling.
Thank you!

答:
Assuming you want y as discrete groups, you should convert it to a factor

```<code>ggplot(data, aes(x = x, fill = factor(y))) +
  geom_histogram(alpha=0.6, bins = 50, position = 'identity')
</code>```

Body:
I want to see the distribution difference between two groups in my data.
My data looks similar to

data <- data.frame(rnorm(500,mean = 3),sample(c(0,1), replace=TRUE, size=500))
colnames(data) <- c('x','y')

And then I draw the histogram by

ggplot(data, aes(x = x, fill = y)) +
   geom_histogram(alpha=0.6, bins = 50, position = 'identity')

But it returns

Can you please help find what the problem is? I just followed the examples from googling.
Thank you!

Body:
Assuming you want y as discrete groups, you should convert it to a factor

ggplot(data, aes(x = x, fill = factor(y))) +
  geom_histogram(alpha=0.6, bins = 50, position = 'identity')


问:
How to separate approvals of multiple jobs
I have a release pipeline that consists of two jobs, for QA and Production. Each job has a corresponding environment:

```<code>jobs:
- deployment: QA
  displayName: QA Deployment
  environment: QA
...
- deployment: Production
  dependsOn: QA
  displayName: Production Deployment
  environment: Production
...
</code>```

And each environment is set to request an approval:

I expected to have a separate approval for each job, i.e. to be able to approve the QA job and run it, and not to have to approve the Production job. But for some reason, I am not able to run the QA job without approving both QA and Production. So I can run either both jobs or none. What am I doing wrong, and how can I fix this?

答:
According to the documentation, approval should be applied to stages. You should have a separate stage with deployment jobs for each environment.

Try:

```<code>stages:
- stage: QA
  jobs:
  - deployment: QA
    displayName: QA Deployment
    environment: QA
- stage: Production
  jobs:
  - deployment: Production
    dependsOn: QA
    displayName: Production Deployment
    environment: Production
</code>```

Body:
I have a release pipeline that consists of two jobs, for QA and Production. Each job has a corresponding environment:

jobs:
- deployment: QA
  displayName: QA Deployment
  environment: QA
...
- deployment: Production
  dependsOn: QA
  displayName: Production Deployment
  environment: Production
...

And each environment is set to request an approval:

I expected to have a separate approval for each job, i.e. to be able to approve the QA job and run it, and not to have to approve the Production job. But for some reason, I am not able to run the QA job without approving both QA and Production. So I can run either both jobs or none. What am I doing wrong, and how can I fix this?

Body:
According to the documentation, approval should be applied to stages. You should have a separate stage with deployment jobs for each environment.

Try:

stages:
- stage: QA
  jobs:
  - deployment: QA
    displayName: QA Deployment
    environment: QA
- stage: Production
  jobs:
  - deployment: Production
    dependsOn: QA
    displayName: Production Deployment
    environment: Production


问:
Javascript/Jquery regex for matched key and return its Value
```<code>var t = {
"Word1, Word2 Word3":"Word1, Word2",
"Word5, Word6":"Word6", "Word7":"Word7",
"Word8, Word9 and Word10":"Word8 and Word10"
}

//has value after page load, its saved from a cookie
var z = "Word9 and Word10"
</code>```

Requirement: I would like to pass the variable z and retrieve the matched value from the object t.

So in this case it should return "Word8 and Word10" so i could use that value to make API call etc. Any suggestions would be much appreciated.

答:
Depending on how you want to handle duplicates wasn't mentioned, this solution  loops through all the object's keys and checks if the key value includes the z variable

const t = {
"Word1 Word2 Word3":"Word1 Word2",
"Word5 Word6":"Word6", "Word7":"Word7",
"Word8 Word9 and Word10":"Word8 and Word10"
}
const z = "Word9 and Word10"

for (const key of Object.keys(t)) {
    if (key.includes(z)) {
        console.log(t[key])
    }
}
```

Body:
var t = {
"Word1, Word2 Word3":"Word1, Word2",
"Word5, Word6":"Word6", "Word7":"Word7",
"Word8, Word9 and Word10":"Word8 and Word10"
}

//has value after page load, its saved from a cookie
var z = "Word9 and Word10"

Requirement: I would like to pass the variable z and retrieve the matched value from the object t.

So in this case it should return "Word8 and Word10" so i could use that value to make API call etc. Any suggestions would be much appreciated.


问:
htaccess url masking
Hey im a total niewbie with htaccess.
On my site (mysite.com) i got a link that directs and sends variable to a page on a secure site (othersite.com/somepage.php?urlink='www.mysite.com').

How can I edit my htaccess file to rewrite othersite.com/somepage.php?urlink='www.mysite.com' to whatever value urlink has.

I have this in my htaccess

```<code>Options +FollowSymlinks<br>
Options All -Indexes<br>
Options Indexes Includes FollowSymLinks ExecCGI
RewriteEngine on
RewriteRule ^&urlink=(.*) http://$1 [P]
</code>```

答:
RewriteRule DOES NOT WORK with query string directly like that.

For example, if URL is http://www.example.com/kitten.php?say=meow, then RewriteRule can only match kitten.php part. Everything else can be matched via RewriteCond, for example: RewriteCond %{QUERY_STRING} ^urlink=(.*).

Please see documentation: http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond

In your case it can be something like this (sorry, I do not know what exactly you are trying to achieve, therefore I'm just editing your existing rule):

```<code>Options Indexes Includes FollowSymLinks ExecCGI
RewriteEngine on

RewriteCond %{QUERY_STRING} ^urlink=(.+)$
RewriteRule ^somepage\.php$ http://%1 [P]
</code>```

Title: htaccess url masking

Body:
Hey im a total niewbie with htaccess.
On my site (mysite.com) i got a link that directs and sends variable to a page on a secure site (othersite.com/somepage.php?urlink='www.mysite.com').

How can I edit my htaccess file to rewrite othersite.com/somepage.php?urlink='www.mysite.com' to whatever value urlink has.

I have this in my htaccess

Options +FollowSymlinks

Options All -Indexes

Options Indexes Includes FollowSymLinks ExecCGI
RewriteEngine on
RewriteRule ^&urlink=(.*) http://$1 [P]

Body:
RewriteRule DOES NOT WORK with query string directly like that.

For example, if URL is http://www.example.com/kitten.php?say=meow, then RewriteRule can only match kitten.php part. Everything else can be matched via RewriteCond, for example: RewriteCond %{QUERY_STRING} ^urlink=(.*).

Please see documentation: http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritecond

In your case it can be something like this (sorry, I do not know what exactly you are trying to achieve, therefore I'm just editing your existing rule):

Options Indexes Includes FollowSymLinks ExecCGI
RewriteEngine on

RewriteCond %{QUERY_STRING} ^urlink=(.+)$
RewriteRule ^somepage\.php$ http://%1 [P]


问:
Docker Container port access
I have created an image from an existing dotnet application I can run locally.

in my docker file I have
EXPOSE 5000

In the docker compose:
ports: [5000:5000]

I start the container using the command:
docker run -d -p 5000:5000 --name my-reports my-reports:latest

running the docker ps  command :

```<code>     NAMES
106c4929c0d6   my-reports:latest   "dotnet my-reports"   8 minutes ago   Up 8 minutes   0.0.0.0:5000->5000/tcp   my-reports
</code>```

The output of the entrypoint:

```<code>info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\app
</code>```

netstat shows:

```<code>C:\app>netstat -a

Active Connections

  Proto  Local Address          Foreign Address        State
  TCP    0.0.0.0:135            106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:5985           106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:47001          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49152          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49153          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49154          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49155          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49160          106c4929c0d6:0         LISTENING
  TCP    127.0.0.1:5000         106c4929c0d6:0         LISTENING
</code>```

But I get timeouts trying to access the port from my machine via localhost:5000

答: You have already provided flag --name my-reports but your container is reporting the name as "vpi-harmony-reports". Do kill the container and re-run the docker command. Also make sure you do not have firewall blocking 5000 port.</p>

Title: Docker Container port access

Body:
I have created an image from an existing dotnet application I can run locally.

in my docker file I have
EXPOSE 5000

In the docker compose:
ports: [5000:5000]

I start the container using the command:
docker run -d -p 5000:5000 --name my-reports my-reports:latest

running the docker ps  command :

     NAMES
106c4929c0d6   my-reports:latest   "dotnet my-reports"   8 minutes ago   Up 8 minutes   0.0.0.0:5000->5000/tcp   my-reports

The output of the entrypoint:

info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Production
info: Microsoft.Hosting.Lifetime[0]
      Content root path: C:\app

netstat shows:

C:\app>netstat -a

Active Connections

  Proto  Local Address          Foreign Address        State
  TCP    0.0.0.0:135            106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:5985           106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:47001          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49152          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49153          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49154          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49155          106c4929c0d6:0         LISTENING
  TCP    0.0.0.0:49160          106c4929c0d6:0         LISTENING
  TCP    127.0.0.1:5000         106c4929c0d6:0         LISTENING

But I get timeouts trying to access the port from my machine via localhost:5000