问:
Powershell silent / unattended install of Delphi Tokyo 10.2 - for CI use in win docker container
I'm attempting to create a powershell command that silently installs Delphi Tokyo 10.2 - to be used as an automated compiler in a Windows Docker container. I've not been able to find any recent documentation on how to implement an unattended/silent installation using the proper installer commands / switches.

I was able to determine that the Tokyo and Rio installers use Inno Setup  - and should be given Inno Setup installer commands/switches.

From the Tokyo installer about page:

https://photos.app.goo.gl/88jY7PF2mPAipwEA9

This is the command I've messed with thus far:

```<code>.\radstudio10_2_3_esd__93231.exe /sp- /verysilent /suppressmsgboxes /norestart/ /log="c:\somelocation\install.log"
</code>```

However I am not able to get the install process to go past the first page or EULA checkbox. The failed silent install log shows:

```<code>Log opened. (Time zone: UTC-05:00)
Setup version: Inno Setup version 5.5.6 (u)
Original Setup EXE: C:\somelocation\radstudio10_2_3_esd__93231.exe
Setup command line: /SL5="$18051C,138809719,642048,C:\somelocation\radstudio10_2_3_esd__93231.exe" /sp- /verysilent /suppressmsgboxes /norestart/ /log=c:\somelocation\install.log
Windows version: 10.0.18363  (NT platform: Yes)
64-bit Windows: Yes
Processor architecture: x64
User privileges: Administrative
64-bit install mode: No
Created temporary directory: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp\innocallback.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp\UnlockFirewall.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp\mOasisRuntime.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp\topbanner96.bmp
Failed to proceed to next wizard page; aborting.
Got EAbort exception.
Deinitializing Setup.
Log closed.
</code>```

Here's a portion of the logs from a non-silent install of the same installer package:

```<code>Log opened. (Time zone: UTC-05:00)
Setup version: Inno Setup version 5.5.6 (u)
Original Setup EXE: C:\somelocation\radstudio10_2_3_esd__93231.exe
Setup command line: /SL5="$405F0,138809719,642048,C:\somelocation\radstudio10_2_3_esd__93231.exe" /log=c:\somelocation\install.log /saveinf=c:\somelocation\install.inf
Windows version: 10.0.18363  (NT platform: Yes)
64-bit Windows: Yes
Processor architecture: x64
User privileges: Administrative
264-bit install mode: No
Created temporary directory: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\innocallback.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\UnlockFirewall.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\mOasisRuntime.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\topbanner96.bmp
Message box (OK):
Inno Setup version 5.5.6 (u)
Copyright © 1997-2015 Jordan Russell
Portions Copyright © 2000-2015 Martijn Laan
All rights reserved.

Inno Setup home page:
http://www.innosetup.com/

RemObjects Pascal Script home page:
http://www.remobjects.com/ps
User chose OK.
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Starting the installation process.
Creating directory: C:\Program Files (x86)\Embarcadero
Creating directory: C:\Program Files (x86)\Embarcadero\Studio
Creating directory: C:\Program Files (x86)\Embarcadero\Studio\19.0
Directory for uninstall files: C:\Program Files (x86)\Embarcadero\Studio\19.0\
...
...
...
</code>```

So in the above successful non-silent install - notice the line in the logs that says Message box (OK) this occurs after I accept the EULA. So at present i'm not sure how to pass an installer switch to suffice the EULA page silently.

Has anyone had success with creating a silent / unattended install of Delphi Tokyo or Rio? Or has found documentation that helped them achieve something similar?

Any help is much appreciated!

Kind Regards,

答:
For Delphi 2007 and Delphi XE2 we were able to do a silent installation with setup.exe /s, see https://delphisorcery.blogspot.com/2011/07/unattended-delphi-installation-how.html for reference.

But this did not work for Delphi 10.2 Tokyo anymore. So our IT department called Embarcadero directly for more information on how to do a silent installation. But unfortunately they told us, the installation process can not be done silently!

Body:
I'm attempting to create a powershell command that silently installs Delphi Tokyo 10.2 - to be used as an automated compiler in a Windows Docker container. I've not been able to find any recent documentation on how to implement an unattended/silent installation using the proper installer commands / switches.

I was able to determine that the Tokyo and Rio installers use Inno Setup  - and should be given Inno Setup installer commands/switches.

From the Tokyo installer about page:

https://photos.app.goo.gl/88jY7PF2mPAipwEA9

This is the command I've messed with thus far:

.\radstudio10_2_3_esd__93231.exe /sp- /verysilent /suppressmsgboxes /norestart/ /log="c:\somelocation\install.log"

However I am not able to get the install process to go past the first page or EULA checkbox. The failed silent install log shows:

Log opened. (Time zone: UTC-05:00)
Setup version: Inno Setup version 5.5.6 (u)
Original Setup EXE: C:\somelocation\radstudio10_2_3_esd__93231.exe
Setup command line: /SL5="$18051C,138809719,642048,C:\somelocation\radstudio10_2_3_esd__93231.exe" /sp- /verysilent /suppressmsgboxes /norestart/ /log=c:\somelocation\install.log
Windows version: 10.0.18363  (NT platform: Yes)
64-bit Windows: Yes
Processor architecture: x64
User privileges: Administrative
64-bit install mode: No
Created temporary directory: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp\innocallback.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp\UnlockFirewall.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp\mOasisRuntime.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-1QQ8P.tmp\topbanner96.bmp
Failed to proceed to next wizard page; aborting.
Got EAbort exception.
Deinitializing Setup.
Log closed.

Here's a portion of the logs from a non-silent install of the same installer package:

Log opened. (Time zone: UTC-05:00)
Setup version: Inno Setup version 5.5.6 (u)
Original Setup EXE: C:\somelocation\radstudio10_2_3_esd__93231.exe
Setup command line: /SL5="$405F0,138809719,642048,C:\somelocation\radstudio10_2_3_esd__93231.exe" /log=c:\somelocation\install.log /saveinf=c:\somelocation\install.inf
Windows version: 10.0.18363  (NT platform: Yes)
64-bit Windows: Yes
Processor architecture: x64
User privileges: Administrative
264-bit install mode: No
Created temporary directory: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\innocallback.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\UnlockFirewall.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\mOasisRuntime.dll
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\topbanner96.bmp
Message box (OK):
Inno Setup version 5.5.6 (u)
Copyright © 1997-2015 Jordan Russell
Portions Copyright © 2000-2015 Martijn Laan
All rights reserved.

Inno Setup home page:
http://www.innosetup.com/

RemObjects Pascal Script home page:
http://www.remobjects.com/ps
User chose OK.
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Extracting temporary file: C:\Users\username\AppData\Local\Temp\is-K4M7F.tmp\ProductCodes.ini
Starting the installation process.
Creating directory: C:\Program Files (x86)\Embarcadero
Creating directory: C:\Program Files (x86)\Embarcadero\Studio
Creating directory: C:\Program Files (x86)\Embarcadero\Studio\19.0
Directory for uninstall files: C:\Program Files (x86)\Embarcadero\Studio\19.0\
...
...
...

So in the above successful non-silent install - notice the line in the logs that says Message box (OK) this occurs after I accept the EULA. So at present i'm not sure how to pass an installer switch to suffice the EULA page silently.

Has anyone had success with creating a silent / unattended install of Delphi Tokyo or Rio? Or has found documentation that helped them achieve something similar?

Any help is much appreciated!

Kind Regards,


来源: stackexchange

问:
Adding an extra parenthesis into a method in JavaScript?
Whenever I go through JavaScript code, I see a method that haves a pair of extra parentheses.

For example:

```<code>if( (typeOf VariableName) === "function" )
</code>```

or

```<code>alert(("Hello World"))
</code>```

What does these do, and why are they needed?

答:
In JS, parentheses used for multiple purposes.

Grouping operator (like in mathematical expressions)

Function call (if placed after an identifier)

Several statements require them

The examples you've provided are of type where they act as grouping operators.

In your scenario, they aren't needed, both examples would work without them as well.

However, there are cases when you have to use additional parens, for example:

Forcing a statement into expression context:

```<code>function(){}() //This is evaluated like a function declaration, SyntaxError

(function(){})() //Works

x => {'x': x} //Returns undefined

x => ({'x': x}) //Returns the object
</code>```

Changing the evaluation order:

```<code>1+2*3 //7

(1+2)*3 //9
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Whenever I go through JavaScript code, I see a method that haves a pair of extra parentheses.

For example:

if( (typeOf VariableName) === "function" )

or

alert(("Hello World"))

What does these do, and why are they needed?

Body:
In JS, parentheses used for multiple purposes.

Grouping operator (like in mathematical expressions)

Function call (if placed after an identifier)

Several statements require them

The examples you've provided are of type where they act as grouping operators.

In your scenario, they aren't needed, both examples would work without them as well.

However, there are cases when you have to use additional parens, for example:

Forcing a statement into expression context:

function(){}() //This is evaluated like a function declaration, SyntaxError

(function(){})() //Works

x => {'x': x} //Returns undefined

x => ({'x': x}) //Returns the object

Changing the evaluation order:

1+2*3 //7

(1+2)*3 //9


问:
Convert layout in pdf java
I have the following form, created using LinearLayout

Code:

```<code>private LinearLayout buildBox(Integer w){
    LinearLayout.LayoutParams boxParams =
            new LinearLayout.LayoutParams(
                    getDpToInt(w),
                    LinearLayout.LayoutParams.WRAP_CONTENT);
    LinearLayout whiteBox = new LinearLayout(this.getContext());
    whiteBox.setLayoutParams(boxParams);
    whiteBox.setOrientation(LinearLayout.VERTICAL);
    whiteBox.setBackgroundResource(R.color.colorAccent);
    return whiteBox;
}
</code>```

I need to convert this form after it is rendered to pdf or bitmap. On that same screen, you will have a button to print it. I tried some solutions found on the site, but I was not successful. Can someone help me?

答:
write code on pdf file button click like,

```<code>btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("size"," "+llPdf.getWidth() +"  "+llPdf.getWidth());
                bitmap = loadBitmapFromView(llPdf, llPdf.getWidth(), llPdf.getHeight());
                createPdfFile();
            }
        });
</code>```

and implement these methods,

```<code>public static Bitmap loadBitmapFromView(View v, int width, int height) {
        Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.draw(c);

        return b;
    }

    private void createPdfFile(){
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

        DisplayMetrics displaymetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        float hight = displaymetrics.heightPixels ;
        float width = displaymetrics.widthPixels ;

        int convertHighet = (int) hight, convertWidth = (int) width;

        PdfDocument document = new PdfDocument();
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(convertWidth, convertHighet, 1).create();
        PdfDocument.Page page = document.startPage(pageInfo);

        Canvas canvas = page.getCanvas();

        Paint paint = new Paint();
        canvas.drawPaint(paint);

        bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, true);

        paint.setColor(Color.BLUE);
        canvas.drawBitmap(bitmap, 0, 0 , null);
        document.finishPage(page);

        String targetPdf = "/storage/mypdflayout.pdf";
        File filePath;
        filePath = new File(targetPdf);
        try {
            document.writeTo(new FileOutputStream(filePath));

         } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
        }

        document.close();
        Toast.makeText(this, "PDF is created successfully!!!", Toast.LENGTH_SHORT).show();

        openGeneratedPDFFile();

    }

    private void openGeneratedPDFFile(){
        File file = new File("/sdcard/pdffromlayout.pdf");
        if (file.exists())
        {
            Intent i=new Intent(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(file);
            i.setDataAndType(uri, "application/pdf");
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            try
            {
                startActivity(i);
            }
            catch(ActivityNotFoundException e)
            {
                Toast.makeText(MainActivity.this, "No pdf view available", Toast.LENGTH_LONG).show();
            }
        }
    }
</code>```

Title: Convert layout in pdf java

Body:
I have the following form, created using LinearLayout

Code:

private LinearLayout buildBox(Integer w){
    LinearLayout.LayoutParams boxParams =
            new LinearLayout.LayoutParams(
                    getDpToInt(w),
                    LinearLayout.LayoutParams.WRAP_CONTENT);
    LinearLayout whiteBox = new LinearLayout(this.getContext());
    whiteBox.setLayoutParams(boxParams);
    whiteBox.setOrientation(LinearLayout.VERTICAL);
    whiteBox.setBackgroundResource(R.color.colorAccent);
    return whiteBox;
}

I need to convert this form after it is rendered to pdf or bitmap. On that same screen, you will have a button to print it. I tried some solutions found on the site, but I was not successful. Can someone help me?

Body:
write code on pdf file button click like,

btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("size"," "+llPdf.getWidth() +"  "+llPdf.getWidth());
                bitmap = loadBitmapFromView(llPdf, llPdf.getWidth(), llPdf.getHeight());
                createPdfFile();
            }
        });

and implement these methods,

public static Bitmap loadBitmapFromView(View v, int width, int height) {
        Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        v.draw(c);

        return b;
    }

    private void createPdfFile(){
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);

        DisplayMetrics displaymetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        float hight = displaymetrics.heightPixels ;
        float width = displaymetrics.widthPixels ;

        int convertHighet = (int) hight, convertWidth = (int) width;

        PdfDocument document = new PdfDocument();
        PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(convertWidth, convertHighet, 1).create();
        PdfDocument.Page page = document.startPage(pageInfo);

        Canvas canvas = page.getCanvas();

        Paint paint = new Paint();
        canvas.drawPaint(paint);

        bitmap = Bitmap.createScaledBitmap(bitmap, convertWidth, convertHighet, true);

        paint.setColor(Color.BLUE);
        canvas.drawBitmap(bitmap, 0, 0 , null);
        document.finishPage(page);

        String targetPdf = "/storage/mypdflayout.pdf";
        File filePath;
        filePath = new File(targetPdf);
        try {
            document.writeTo(new FileOutputStream(filePath));

         } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "Something wrong: " + e.toString(), Toast.LENGTH_LONG).show();
        }

        document.close();
        Toast.makeText(this, "PDF is created successfully!!!", Toast.LENGTH_SHORT).show();

        openGeneratedPDFFile();

    }

    private void openGeneratedPDFFile(){
        File file = new File("/sdcard/pdffromlayout.pdf");
        if (file.exists())
        {
            Intent i=new Intent(Intent.ACTION_VIEW);
            Uri uri = Uri.fromFile(file);
            i.setDataAndType(uri, "application/pdf");
            i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            try
            {
                startActivity(i);
            }
            catch(ActivityNotFoundException e)
            {
                Toast.makeText(MainActivity.this, "No pdf view available", Toast.LENGTH_LONG).show();
            }
        }
    }


问:
how to detect if Aero Peek mode is on
I'm trying to find out how to detect if windows desktop Aero Peek mode is on. In particular I'm need to detect if my window content is shown or drawn as a frame with transparent background. I know I can exclude my window from Aero Peek, but this not what I need at this moment. </p>

<p>TIA </p>

答:
If you read from windows Registry, there you can find the status of Aero Peek

\HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM

Is a DWORD value named EnableAeroPeek which is set as following:

1 = Enabled
  0 = disabled

Just compare to 0 or 1 to find out if AeroPeek is on.

In C# something like this:

```<code>Using Microsoft.Win32;
</code>```

...

```<code>RegistryKey AeroPeek = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\DWM", true);
       if ((int)AeroPeek.GetValue("EnableAeroPeek") == 1)
        {
            MessageBox.Show("Aero Peek is ON");
        }
        else MessageBox.Show("Aero Peek is OFF");
</code>```

You can also change those values and instantly Aero Peek status will change.

ContentLicense: CC BY-SA 2.5

Title: how to detect if Aero Peek mode is on

Body:
I'm trying to find out how to detect if windows desktop Aero Peek mode is on. In particular I'm need to detect if my window content is shown or drawn as a frame with transparent background. I know I can exclude my window from Aero Peek, but this not what I need at this moment.

TIA

Body:
If you read from windows Registry, there you can find the status of Aero Peek

\HKEY_CURRENT_USER\Software\Microsoft\Windows\DWM

Is a DWORD value named EnableAeroPeek which is set as following:

1 = Enabled
  0 = disabled

Just compare to 0 or 1 to find out if AeroPeek is on.

In C# something like this:

Using Microsoft.Win32;

...

RegistryKey AeroPeek = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\DWM", true);
       if ((int)AeroPeek.GetValue("EnableAeroPeek") == 1)
        {
            MessageBox.Show("Aero Peek is ON");
        }
        else MessageBox.Show("Aero Peek is OFF");

You can also change those values and instantly Aero Peek status will change.

ContentLicense: CC BY-SA 3.0


问:
Opening Python code with a specific version
while there are multiple versions of Python installed on a Linux machine, is there a way to mention in the script to be open with a specific version, say, 3.8 even if we issue the #python script.py as opposed to python3.8 script.py ?
I don't want to use Linux alias command. I wanna know if that is possible to be accomplished within the script</p>

答:
You can select the interpreter by adding
#!/usr/bin/env pythonXX
as the first line in your script, provided the version is in the path.
You can also invoke the interpreter directly with the script as the argument.

pythonXX script.py

Depending on your situation

pythonXX -E script.py

might be better. That way the interpreter ignores paths set by environmental variables.
For more details view
https://docs.python.org/3/using/cmdline.html


问:
What can I replace here since I can't have a lambda function with implicit variable in C#?
I'm trying to implement a tile-based platforming system for a 2D game demo from this C++ code into C#,

This is what I have written, It doesn't compile though due to the var variable usage.

```<code> class GameLogic
{
    // Level storage
    String sLevel;
    int nLevelWidth;
    int nLevelHeight;

    // Player Properties
    float fPlayerPosX = 1.0f;
    float fPlayerPosY = 1.0f;
    float fPlayerVelX = 0.0f;
    float fPlayerVelY = 0.0f;
    bool bPlayerOnGround = false;

    // Camera properties
    float fCameraPosX = 0.0f;
    float fCameraPosY = 0.0f;

    public GameLogic()
    {
         var GetTile = (ref int x, ref int y) =>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                return sLevel[y * nLevelWidth + x];
            else
                return "";
        };

        var SetTile = (ref int x, ref int y, string c)=>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                sLevel[y * nLevelWidth + x] = c;
        };

    }
}
</code>```

What do you suggest I should do here, to implement this functionality. Thank you for your time.

答:
You can declare two delegates like below:

```<code>delegate void ActionRef(ref int x, ref int y, string c);
delegate string FuncRef(ref int x, ref int y);
</code>```

And instead of using var, you can these delegates as the type of function.

```<code>public GameLogic()
{
    FuncRef GetTile = (ref int x, ref int y) =>
    {
        if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
            return sLevel[y * nLevelWidth + x];
        else
            return "";
    };

    ActionRef SetTile = (ref int x, ref int y, string c) =>
    {
        if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
            sLevel[y * nLevelWidth + x] = c;
    };
}
</code>```

Body:
I'm trying to implement a tile-based platforming system for a 2D game demo from this C++ code into C#,

This is what I have written, It doesn't compile though due to the var variable usage.

 class GameLogic
{
    // Level storage
    String sLevel;
    int nLevelWidth;
    int nLevelHeight;

    // Player Properties
    float fPlayerPosX = 1.0f;
    float fPlayerPosY = 1.0f;
    float fPlayerVelX = 0.0f;
    float fPlayerVelY = 0.0f;
    bool bPlayerOnGround = false;

    // Camera properties
    float fCameraPosX = 0.0f;
    float fCameraPosY = 0.0f;

    public GameLogic()
    {
         var GetTile = (ref int x, ref int y) =>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                return sLevel[y * nLevelWidth + x];
            else
                return "";
        };

        var SetTile = (ref int x, ref int y, string c)=>
        {
            if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
                sLevel[y * nLevelWidth + x] = c;
        };

    }
}

What do you suggest I should do here, to implement this functionality. Thank you for your time.

Body:
You can declare two delegates like below:

delegate void ActionRef(ref int x, ref int y, string c);
delegate string FuncRef(ref int x, ref int y);

And instead of using var, you can these delegates as the type of function.

public GameLogic()
{
    FuncRef GetTile = (ref int x, ref int y) =>
    {
        if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
            return sLevel[y * nLevelWidth + x];
        else
            return "";
    };

    ActionRef SetTile = (ref int x, ref int y, string c) =>
    {
        if (x >= 0 && x < nLevelWidth && y >= 0 && y < nLevelHeight)
            sLevel[y * nLevelWidth + x] = c;
    };
}


问:
Target iphone XR in Zoomed mode and not iphone6 with media queries
I know it's possible to target specific iphone models with media queries like this:

```<code>@media only screen
and (min-device-width : 375px)
and (max-device-width : 667px)
and (orientation : portrait) { /* STYLES GO HERE */ }
</code>```

However the iphone XR in zoomed mode has exactly the same pixel size/ratio as the 6,7,8 models, does anyone know of a way to target just the iphone XR in zoomed mode?

答:
We can recognize device with its screen height and width, I did this for getting heights        </p>

```<code>  extension UIScreen {
    var isPhone4: Bool {
        return self.nativeBounds.size.height == 960;
    }
    var isPhone5: Bool {
        return self.nativeBounds.size.height == 1136;
    }
    var isPhone6: Bool {
        return self.nativeBounds.size.height == 1334;
    }
    var isPhone6Plus: Bool {
        return self.nativeBounds.size.height == 2208;
    }
    var isPhoneX: Bool {
        return self.nativeBounds.size.height == 2436;
    }
    var isPhoneXsMax: Bool{
        return self.nativeBounds.size.height == 2688;
    }
    var isPhoneXR:Bool{
        return self.nativeBounds.size.height == 1792;
    }

}
</code>```

Body:
I know it's possible to target specific iphone models with media queries like this:

@media only screen
and (min-device-width : 375px)
and (max-device-width : 667px)
and (orientation : portrait) { /* STYLES GO HERE */ }

However the iphone XR in zoomed mode has exactly the same pixel size/ratio as the 6,7,8 models, does anyone know of a way to target just the iphone XR in zoomed mode?

Body:
We can recognize device with its screen height and width, I did this for getting heights

  extension UIScreen {
    var isPhone4: Bool {
        return self.nativeBounds.size.height == 960;
    }
    var isPhone5: Bool {
        return self.nativeBounds.size.height == 1136;
    }
    var isPhone6: Bool {
        return self.nativeBounds.size.height == 1334;
    }
    var isPhone6Plus: Bool {
        return self.nativeBounds.size.height == 2208;
    }
    var isPhoneX: Bool {
        return self.nativeBounds.size.height == 2436;
    }
    var isPhoneXsMax: Bool{
        return self.nativeBounds.size.height == 2688;
    }
    var isPhoneXR:Bool{
        return self.nativeBounds.size.height == 1792;
    }

}


问:
Expression type '@lvalue CGFloat' is ambiguous without more context
I try to make fade out animation and the code like below.
But I got the error like title, I don't know how to fix it.
Anyone who can help me ?Thx advance!!!</p>

```<code>private func showAnimation(){
    if self.resultPresent.alpha == 1.0{
          UIView.animate(withDuration: 2,option: .curveEaseOut, animations: {
              self.resultPresent.alpha = CGFloat(0)→Expression type '@lvalue CGFloat' is ambiguous without more context
          })
      }
}
</code>```

答:
There is no version of UIView.animate with the parameters you're using.

Try this instead:

```<code>UIView.animate(withDuration: 2, delay: 0, options: .curveEaseInOut, animations: {
    self.resultPresent.alpha = 0
})
</code>```

or, this shorter form that uses .curveEaseInOut by default:

```<code>UIView.animate(withDuration: 2, animations: {
    self.resultPresent.alpha = 0
})
</code>```

Body:
I try to make fade out animation and the code like below.
But I got the error like title, I don't know how to fix it.
Anyone who can help me ?Thx advance!!!

private func showAnimation(){
    if self.resultPresent.alpha == 1.0{
          UIView.animate(withDuration: 2,option: .curveEaseOut, animations: {
              self.resultPresent.alpha = CGFloat(0)→Expression type '@lvalue CGFloat' is ambiguous without more context
          })
      }
}

Body:
There is no version of UIView.animate with the parameters you're using.

Try this instead:

UIView.animate(withDuration: 2, delay: 0, options: .curveEaseInOut, animations: {
    self.resultPresent.alpha = 0
})

or, this shorter form that uses .curveEaseInOut by default:

UIView.animate(withDuration: 2, animations: {
    self.resultPresent.alpha = 0
})


问:
how to convert url to string in ios/swift?
In my code ios/SWIFT I an trying to read the url from a previous image that I successful saved at Storage Firebase. There is an error at instruction let url1 = url as! String
I need to convert url to string but the cast doesn't work
The print instruction is ok I see the correct url at log screen print(url?.absoluteURL as Any )</p>

```<code>   let armazenamento = Storage.storage().reference()
    let imagens = armazenamento.child("imagens")
    if let imagemSelecionada=imagem.image {
        if let imagemDados = imagemSelecionada.jpegData(compressionQuality: 0.1) {
            imagens.child("\(self.idImagem).jpg").putData(imagemDados, metadata: nil, completion: {(metaDados, erro) in
                if erro == nil {
                    print("Sucess upload")
                    imagens.child("\(self.idImagem).jpg").downloadURL(completion: { (url, erro) in
                        if(erro == nil)
                        {
                            print(url?.absoluteURL as Any )
                            let url1 = url as! String
                            self.performSegue(withIdentifier: "selecionarUsuarioSegue", sender: url1)
                        }else{
                            print(err!);
                        }
                    })
</code>```

答:
Go through this link
Here you can find url to string and string to url

https://www.zerotoappstore.com/swift-url-to-string.html

Body:
In my code ios/SWIFT I an trying to read the url from a previous image that I successful saved at Storage Firebase. There is an error at instruction let url1 = url as! String
I need to convert url to string but the cast doesn't work
The print instruction is ok I see the correct url at log screen print(url?.absoluteURL as Any )

   let armazenamento = Storage.storage().reference()
    let imagens = armazenamento.child("imagens")
    if let imagemSelecionada=imagem.image {
        if let imagemDados = imagemSelecionada.jpegData(compressionQuality: 0.1) {
            imagens.child("\(self.idImagem).jpg").putData(imagemDados, metadata: nil, completion: {(metaDados, erro) in
                if erro == nil {
                    print("Sucess upload")
                    imagens.child("\(self.idImagem).jpg").downloadURL(completion: { (url, erro) in
                        if(erro == nil)
                        {
                            print(url?.absoluteURL as Any )
                            let url1 = url as! String
                            self.performSegue(withIdentifier: "selecionarUsuarioSegue", sender: url1)
                        }else{
                            print(err!);
                        }
                    })


问:
Update part of page automatically when the data from an object changes without reloading the page
I have data being inserted into various divs collected from the backend.
This data gets updated, what i need is for the divs to also automatically update the data within the divs without actually refreshing the whole page.
Right now a page refresh would update the divs but I want the divs to auto update without affecting users experience.
Any suggestions.
As an example, I have a vote up/down button in the frontend, the vote gets sent to the backend then sent back through to the front and inserted into a div, however they wouldnt see their vote registered in the frontend unless they refreshed the page, So I would need the users vote result to be updated in the front end everytime then make a vote or change a vote ect automatically.
This is just one example, there is more data inserted in this table which could be updated at any time.

Update,
Not sure people understand fully what I need or trying to do.
Basically have and object coming through from back-end,  on page load, data from that object is inserted into a table such as new posts,  votes ect.

What I need to be able to do is check if the object has changed since the page load and if so to then update the data on the page without refreshing the page.

Ideally need this to happen instantaneously, so it recognises as soon as there is a difference between the object data and that being displayed in the browser and updates it.

Hope that makes it more clear as to what I want to do.

I have and object  with information such as the  suggestiontitle, description, votestatus, etc,  these get inserted into a row, when a new.  A new row gets added when a new object with main object comes through.
So I need to be able to check for changes in the main object so that I can then add the new objects as rows into the table and also Detect and update any changes with current objects already inserted.

答:
If I understood correctly, all you want is a way to interact with the backend without refreshing the page, correct? If that's the case, you should look into AJAX. Here's a simple way to use it for the voting system example(requires jQuery):

```<code>$.post(url_to_interact_with,{key: 1232,vote:1}, function(data){
   console.log(data);
}
</code>```

In this case you sent a post request with key=1232 and a vote of 1. The variable in the function (data) is the output of the request.

However, if this isn't such a simple matter for you, I would recommend looking into websockets. To summarize what they are: A back and forth interaction between backend and front end. The back end can send info at any time without refreshing the page. If websockets are too confusing, then use this: https://pusher.com/

But honestly, you shouldn't try to go for the approach of knowing all info of div in real time unless absolutely necessary. Good luck! :)

Body:
If I understood correctly, all you want is a way to interact with the backend without refreshing the page, correct? If that's the case, you should look into AJAX. Here's a simple way to use it for the voting system example(requires jQuery):

$.post(url_to_interact_with,{key: 1232,vote:1}, function(data){
   console.log(data);
}

In this case you sent a post request with key=1232 and a vote of 1. The variable in the function (data) is the output of the request.

However, if this isn't such a simple matter for you, I would recommend looking into websockets. To summarize what they are: A back and forth interaction between backend and front end. The back end can send info at any time without refreshing the page. If websockets are too confusing, then use this: https://pusher.com/

But honestly, you shouldn't try to go for the approach of knowing all info of div in real time unless absolutely necessary. Good luck! :)


问:
Resource compilation failed on updating material library to 1.1.0
I have updated my material library from com.google.android.material:material:1.0.0 to com.google.android.material:material:1.1.0

I am getting the following error after the update. The only solution that I found is to revert it to an older version.

Also, I have tried updating every dependency to latest version, but that didn't work either.

/home/name/.gradle/caches/transforms-2/files-2.1/03d95e2ec81bf572bcb58974acba7470/material-1.1.0-alpha06/res/values/values.xml:718:5-725:23:
  AAPT: error: duplicate value for resource 'attr/checkedButton' with
  config ''.

adding my dependencies for reference:

```<code> // Support libraries
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0'

//Retrofit and ok http
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'

//Multidex
implementation 'androidx.multidex:multidex:2.0.1'

// Flex
implementation 'com.hopenlib.library:cflextools:1.0.0'
implementation 'com.google.android:flexbox:1.0.0'

// Testing
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
</code>```

答:
if you are getting AAPT issue than issue might be in your any of your XML file.
or if this not the issue please try to add

implementation 'com.google.android.material:material:1.0.0''

Body:
I have updated my material library from com.google.android.material:material:1.0.0 to com.google.android.material:material:1.1.0

I am getting the following error after the update. The only solution that I found is to revert it to an older version.

Also, I have tried updating every dependency to latest version, but that didn't work either.

/home/name/.gradle/caches/transforms-2/files-2.1/03d95e2ec81bf572bcb58974acba7470/material-1.1.0-alpha06/res/values/values.xml:718:5-725:23:
  AAPT: error: duplicate value for resource 'attr/checkedButton' with
  config ''.

adding my dependencies for reference:

 // Support libraries
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0'

//Retrofit and ok http
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'

//Multidex
implementation 'androidx.multidex:multidex:2.0.1'

// Flex
implementation 'com.hopenlib.library:cflextools:1.0.0'
implementation 'com.google.android:flexbox:1.0.0'

// Testing
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'


问:
how to create array of json object without key in javascript
I want to create an array of JSON object without a key.How can this is achieved ..??

for example [{8,0,2}, {20,0,2}].

```<code>var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push({hh,mm,qty})
</code>```

it gives data like [{hh:9,mm:8,qty:2}]
I want array like [{9,8,2},{9,3,4}]

答:
You can wrap it over another JSON object with a key I assume you want a JSON object.

Like this { [{8,0,2}, {20,0,2}] } but this with a problem - It is not a valid JSON.

I had a similar problem for one of my scenario. Then I realised

A top level JSON can't exist without a key!

Consider this example, you have another KV pair in JSON and also this array.

```<code>{
  "somekey" : "somevalue",
  [ {8,0,2}, {20,0,2} ]
}
</code>```

You can fetch "somevalue" with the key "somekey". But how would you access the array? you can't :(

I would suggest you to use a top level key for the JSON and make this array as value of it's. Example:

```<code>{
  "my array" : [ {8,0,2}, {20,0,2} ]
}
</code>```

Body:
I want to create an array of JSON object without a key.How can this is achieved ..??

for example [{8,0,2}, {20,0,2}].

var hh = 9
var mm = 8
var qty = 2
var data = [];
data.push({hh,mm,qty})

it gives data like [{hh:9,mm:8,qty:2}]
I want array like [{9,8,2},{9,3,4}]

Body:
You can wrap it over another JSON object with a key I assume you want a JSON object.

Like this { [{8,0,2}, {20,0,2}] } but this with a problem - It is not a valid JSON.

I had a similar problem for one of my scenario. Then I realised

A top level JSON can't exist without a key!

Consider this example, you have another KV pair in JSON and also this array.

{
  "somekey" : "somevalue",
  [ {8,0,2}, {20,0,2} ]
}

You can fetch "somevalue" with the key "somekey". But how would you access the array? you can't :(

I would suggest you to use a top level key for the JSON and make this array as value of it's. Example:

{
  "my array" : [ {8,0,2}, {20,0,2} ]
}


问:
What is the proper way to create an Admin UI based on a model in Sails?
In Sails, I want to create kind of an Admin Area, like an interface to populate the database based on the models I created.

As far as I know, there is only a couple CLI Tools that can be used to create Actions and Models and so on, but nothing to have a proper EJS template defined on the models.

I found a couple npm modules that were going in this direction but they seem old.

答:
I think there is nothing quite like that. Yet, you can archive similar things with other tools provided by sails.

If you want to populate the database for development or testing, blueprint.js is a good option.

If you want to populate the database for production, you can create a new controller like:

//AdminController.js

```<code>module.exports = {

    createNewRace: function(name) {

        Races.create({...});

    },

    addDog: function(name, owner, race) {

        Races.update({...});
        Dogs.create({...});

    },

    ... and so

};
</code>```

Then...

```<code>sudo sails console
var adminC = require('./AdminController');
adminC.createNewRace('Argentine Dogo');
</code>```

This had been really useful for me, I've been trying to learn how to automate it, but I didn't find anything yet.

If you really need an UI because not only you will be populating the db

Create it your self, otherwise, some database servers have UI plugins available for doing those things. Like phpmyadmin for mysql and php. I think redis has one of those too. But if other admins are also user, it is not a good idea to give them access to your database without a secure api in the middle.

Body:
I think there is nothing quite like that. Yet, you can archive similar things with other tools provided by sails.

If you want to populate the database for development or testing, blueprint.js is a good option.

If you want to populate the database for production, you can create a new controller like:

//AdminController.js

module.exports = {

    createNewRace: function(name) {

        Races.create({...});

    },

    addDog: function(name, owner, race) {

        Races.update({...});
        Dogs.create({...});

    },

    ... and so

};

Then...

sudo sails console
var adminC = require('./AdminController');
adminC.createNewRace('Argentine Dogo');

This had been really useful for me, I've been trying to learn how to automate it, but I didn't find anything yet.

If you really need an UI because not only you will be populating the db

Create it your self, otherwise, some database servers have UI plugins available for doing those things. Like phpmyadmin for mysql and php. I think redis has one of those too. But if other admins are also user, it is not a good idea to give them access to your database without a secure api in the middle.


问:
Possible to add a cancel method to Promise in Typescript?
I'd like to create a QueryPromise that is just a concrete promise with a cancel method.  Here's how it would be used:

```<code>function runQuery(text: string): QueryPromise {
  return new QueryPromise((resolve,reject) => {nativeQuery(resolve)})
}
</code>```

Here is my first attempt, hopefully pretty understandable:

```<code>interface CancellablePromise<T> extends Promise<T> {
  cancel: () => void
}

// create the promise my app will use
type QueryPromise = CancellablePromise<string|boolean>
</code>```

But that's not sufficient.

After a few hours of trial and error I managed to get close, but this seems tedious and anything but DRY.

```<code>interface CancellablePromise<T> extends Promise<T> {
  cancel: () => void
}
// also need this interface so the variable can be declared
// plus need to redeclare methods to return the new type
interface CancellablePromiseConstructor extends PromiseConstructor {
  new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): CancellablePromise<T>;
  cancel: () => void
}

type QueryPromise = CancellablePromise<string|boolean>    // for parameter types
var QueryPromise: CancellablePromiseConstructor = Promise // for the new operator

// some example code to exercise the promise
function runQuery(text: string): QueryPromise {
  return new QueryPromise((resolve,reject) => {nativeQuery(resolve)})
}
</code>```

I feel like I've gone a long way down the wrong road...  Does anyone know of a better way to do this?

答:
How about this implementation?

```<code>declare class CancelablePromise<T> extends Promise<T> {
  declare readonly cancel: () => void
}

interface Promise<T> {
  asCancelable(): CancelablePromise<T>
}

Promise.prototype.asCancelable = function () {
  let cancel: (reason: {cancelled: boolean}) => void
  const wrappedPromise = new Promise((resolve, reject) => {
    cancel = reject
    Promise.resolve(this)
      .then(resolve)
      .catch(reject)
  }) as any
  wrappedPromise.cancel = () => {
    cancel({cancelled: true})
  }
  return wrappedPromise as CancelablePromise<unknown>
}
</code>```

Usage:

```<code>const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
const waiting = sleep(1000).asCancelable()
waiting.then(() => {
  console.info('this never get called')
})
waiting.cancel()
</code>```

Body:
I'd like to create a QueryPromise that is just a concrete promise with a cancel method.  Here's how it would be used:

function runQuery(text: string): QueryPromise {
  return new QueryPromise((resolve,reject) => {nativeQuery(resolve)})
}

Here is my first attempt, hopefully pretty understandable:

interface CancellablePromise<T> extends Promise<T> {
  cancel: () => void
}

// create the promise my app will use
type QueryPromise = CancellablePromise<string|boolean>

But that's not sufficient.

After a few hours of trial and error I managed to get close, but this seems tedious and anything but DRY.

interface CancellablePromise<T> extends Promise<T> {
  cancel: () => void
}
// also need this interface so the variable can be declared
// plus need to redeclare methods to return the new type
interface CancellablePromiseConstructor extends PromiseConstructor {
  new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): CancellablePromise<T>;
  cancel: () => void
}

type QueryPromise = CancellablePromise<string|boolean>    // for parameter types
var QueryPromise: CancellablePromiseConstructor = Promise // for the new operator

// some example code to exercise the promise
function runQuery(text: string): QueryPromise {
  return new QueryPromise((resolve,reject) => {nativeQuery(resolve)})
}

I feel like I've gone a long way down the wrong road...  Does anyone know of a better way to do this?

Body:
How about this implementation?

declare class CancelablePromise<T> extends Promise<T> {
  declare readonly cancel: () => void
}

interface Promise<T> {
  asCancelable(): CancelablePromise<T>
}

Promise.prototype.asCancelable = function () {
  let cancel: (reason: {cancelled: boolean}) => void
  const wrappedPromise = new Promise((resolve, reject) => {
    cancel = reject
    Promise.resolve(this)
      .then(resolve)
      .catch(reject)
  }) as any
  wrappedPromise.cancel = () => {
    cancel({cancelled: true})
  }
  return wrappedPromise as CancelablePromise<unknown>
}

Usage:

const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
const waiting = sleep(1000).asCancelable()
waiting.then(() => {
  console.info('this never get called')
})
waiting.cancel()


问:
I cannot run the react native project in android studio emulator
```<code>error ENOENT: no such file or directory, open 'app\build\intermediates\merged_manifests\debug\AndroidManifest.xml'. Run CLI with --verbose flag for more details.
Error: ENOENT: no such file or directory, open 'app\build\intermediates\merged_manifests\debug\AndroidManifest.xml'
    at Object.openSync (fs.js:457:3)
    at Object.readFileSync (fs.js:359:35)
    at getLaunchPackageName (E:\ReactJS\project1\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\getLaunchPackageName.js:161:33)
    at buildAndRun (E:\ReactJS\project1\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:163:63)
    at E:\ReactJS\project1\node_modules\@react-native-community\cli-platform-android\build\commands\runAndroid\index.js:135:12
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
    at async Command.handleAction (E:\ReactJS\project1\node_modules\@react-native-community\cli\build\index.js:182:9)
</code>```

答:
add in your package.json :</p>

```<code>"resolutions": {
"@react-native-community/cli-platform-android": "2.9.0"
},
</code>```

Body:
add in your package.json :

"resolutions": {
"@react-native-community/cli-platform-android": "2.9.0"
},


问:
Jquery plugin DataTables individual column filtering on top?
I use this api with DataTables : http://www.sprymedia.co.uk/dataTables/example_multi_filter.html

But How I can put seach inputs above the table, next to "Search all columns"??

答:
You can use column filter add-on for DataTables. It can be configured to place filters below and above the heading row. See http://jquery-datatables-column-filter.googlecode.com/svn/trunk/dateRange.html, http://jquery-datatables-column-filter.googlecode.com/svn/trunk/numberRange.html and other examples on the site.

Quick update: The two URLs above are invalid now.  Here's a working one: https://code.google.com/archive/p/jquery-datatables-column-filter/


问:
How can i create multiple tabs based on the dropdown selection using javascript?
I am posting this question because I couldn't find a definite answer or method of doing so anywhere. What I want to do is, I have created a dropdown named as 'Number of Chasis'. Now according to the dropdown selected in this field (either '1' or '2')I want one tab 'UUT1' if the user selects '1' in the dropdown and I want two tabs 'UUT1' and 'UUT2' if the user selects '2' in the dropdown. And then on Clicking the UUT1 and UUT2 tabs if want to display the template which I have defined below. Attaching the html part here and also the screenshot of potentially what I am looking for.

```<code>            <fieldset id='extra'>
                <h6>Additional Details Required for Controller A</h6>
                <label for='Controller_ID1'>Controller_ID:</label>
                    <select name='Controller_ID1' required>
                    <option value=""> - Select the Controller ID - </option>
                    <option value='A'>A </select>
                <label for='iSCSI1'>iSCSI IPs:</label><input type='text' name='iSCSIip1' id="ip1" placeholder='Enter iSCSI ips'  disabled="disabled" />
                <label for='HBA_Ports_A'>HBA_Ports:</label><input type='text' id="hba" name='hba_ports1'  placeholder='Enter the HBA Ports' disabled="disabled" />
                <label for='MC_IP_A'>MC_IP:</label><input type='text' name='extra_ip1' placeholder='Enter the MC_IP' />
                <label for='MC_Netmask_A'>MC_Netmask:</label><input type='text' name='netmask_ip1' placeholder='Enter the MC_Netmask' />
                <label for='MC_Gateway_A'>MC_Gateway:</label><input type='text' name='gateway_ip1' placeholder='Enter the MC_Gateway' />
                <label for='MC_A'>MC:</label><input type='text' name='rbod_mc1' placeholder='Enter the MC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
                <label for='SC_A'>SC:</label><input type='text' name='rbod_sc1' placeholder='Enter the SC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
                <label for='FU_A'>FU:</label><input type='text' name='rbod_fu1' placeholder='Enter the FU Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)"/>
                <label for='EC_A'>EC:</label><input type='text' name='rbod_ec1' placeholder='Enter the EC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
<br>
<br>
                <h6>Additional Details Required for Controller B</h6>
                <label for='Controller_ID'>Controller_ID:</label>
                    <select name='Controller_ID' id="ctlid" required>
                    <option value=""> - Select the Controller ID - </option>
                    <option value='B'>B </select>
                <label for='iSCSI2'>iSCSI IPs:</label><input type='text' name='iSCSIip2' id="ip2" placeholder='Enter iSCSI ips' disabled="disabled" />
                <label for='HBA_Ports'>HBA_Ports:</label><input type='text' id="hba1" name='hba_ports' placeholder='Enter the HBA Ports' disabled="disabled" />
                <label for='MC_IP'>MC_IP:</label><input type='text' name='extra_ip' id='mcip' placeholder='Enter the MC_IP'  />
                <label for='MC_Netmask'>MC_Netmask:</label><input type='text' name='netmask_ip' id="netmaskip" placeholder='Enter the MC_Netmask' />
                <label for='MC_Gateway'>MC_Gateway:</label><input type='text' name='gateway_ip' id="gatewayip" placeholder='Enter the MC_Gateway'  />
                <label for='MC'>MC:</label><input type='text' name='rbod_mc' placeholder='Enter the MC Port' id="rbodmc"onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
                <label for='SC'>SC:</label><input type='text' name='rbod_sc' placeholder='Enter the SC Port' id="rbodsc" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
                <label for='FU'>FU:</label><input type='text' name='rbod_fu' placeholder='Enter the FU Port' id="rbodfu" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
                <label for='EC'>EC:</label><input type='text' name='rbod_ec' placeholder='Enter the EC Port' id="rbodec" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />

            </fieldset>
        </template>
<fieldset>
                <label for='Chasis Input'><strong>Number of Chasis</strong></label>
                <select input type='text' name='chassis'   required >
                <option value=""> - Number of Controllers - </option>
                <option data-extra=true value='1'>1
                <option data-extra=true value='2'>2
                </select>
            </fieldset>
            <fieldset>
                <label for='Number of Controllers'><strong>Number of Controllers</strong></label>
                <select input type='text' name='ctrls' onchange="EnableDisableDropDown(this);"  required >
                <option value=""> - Number of Controllers - </option>
                <option data-extra=true value='1'>1
                <option data-extra=true value='2'>2
                </select>
            </fieldset>
</code>```

答:
Please refer below code. also please find fiddle link in comment. If you need more help please create fiddle of your example.</p>

```<code><h2>Tabs</h2>
<select id="tabsToDisplay">
<option value="1">1</option>
<option value="2">2</option>
</select><br/><br/>

<div class="tab">
  <button class="tablinks" id= "tab1btn" >tab1</button>
  <button class="tablinks" id= "tab2btn" >tab2</button>
</div>

<div id="tab1" class="tabcontent">
  <h3>Tab1</h3>
  <p>You selected tab1</p>
</div>

<div id="tab2" class="tabcontent">
  <h3>Tab2</h3>
  <p>You selected tab2</p>
</div>
// A $( document ).ready() block.
$( document ).ready(function() {
 function displaySelectedTabs(selectedNumber){
 switch(selectedNumber){
  case "1":
  $("#tab2btn").hide();
  $("#tab2").hide();
  break;
  case "2":
  $("#tab2btn").show();
  break;
 }
}
var selectedNumber = $("#tabsToDisplay").val();
displaySelectedTabs(selectedNumber);
 function tabClick(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
$("#tab1btn" ).click(function() {
  tabClick(event, 'tab1');
});
$("#tab2btn" ).click(function() {
  tabClick(event, 'tab2');
});
$( "#tabsToDisplay" ).change(function() {
  var selectedNumber = $("#tabsToDisplay").val();
displaySelectedTabs(selectedNumber);
});
});
</code>```

Body:
I am posting this question because I couldn't find a definite answer or method of doing so anywhere. What I want to do is, I have created a dropdown named as 'Number of Chasis'. Now according to the dropdown selected in this field (either '1' or '2')I want one tab 'UUT1' if the user selects '1' in the dropdown and I want two tabs 'UUT1' and 'UUT2' if the user selects '2' in the dropdown. And then on Clicking the UUT1 and UUT2 tabs if want to display the template which I have defined below. Attaching the html part here and also the screenshot of potentially what I am looking for.

            <fieldset id='extra'>

Additional Details Required for Controller A

                Controller_ID:
                    <select name='Controller_ID1' required>
                    <option value=""> - Select the Controller ID - </option>
                    <option value='A'>A </select>
                iSCSI IPs:<input type='text' name='iSCSIip1' id="ip1" placeholder='Enter iSCSI ips'  disabled="disabled" />
                HBA_Ports:<input type='text' id="hba" name='hba_ports1'  placeholder='Enter the HBA Ports' disabled="disabled" />
                MC_IP:<input type='text' name='extra_ip1' placeholder='Enter the MC_IP' />
                MC_Netmask:<input type='text' name='netmask_ip1' placeholder='Enter the MC_Netmask' />
                MC_Gateway:<input type='text' name='gateway_ip1' placeholder='Enter the MC_Gateway' />
                MC:<input type='text' name='rbod_mc1' placeholder='Enter the MC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
                SC:<input type='text' name='rbod_sc1' placeholder='Enter the SC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
                FU:<input type='text' name='rbod_fu1' placeholder='Enter the FU Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)"/>
                EC:<input type='text' name='rbod_ec1' placeholder='Enter the EC Port' onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />

Additional Details Required for Controller B

                Controller_ID:
                    <select name='Controller_ID' id="ctlid" required>
                    <option value=""> - Select the Controller ID - </option>
                    <option value='B'>B </select>
                iSCSI IPs:<input type='text' name='iSCSIip2' id="ip2" placeholder='Enter iSCSI ips' disabled="disabled" />
                HBA_Ports:<input type='text' id="hba1" name='hba_ports' placeholder='Enter the HBA Ports' disabled="disabled" />
                MC_IP:<input type='text' name='extra_ip' id='mcip' placeholder='Enter the MC_IP'  />
                MC_Netmask:<input type='text' name='netmask_ip' id="netmaskip" placeholder='Enter the MC_Netmask' />
                MC_Gateway:<input type='text' name='gateway_ip' id="gatewayip" placeholder='Enter the MC_Gateway'  />
                MC:<input type='text' name='rbod_mc' placeholder='Enter the MC Port' id="rbodmc"onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
                SC:<input type='text' name='rbod_sc' placeholder='Enter the SC Port' id="rbodsc" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
                FU:<input type='text' name='rbod_fu' placeholder='Enter the FU Port' id="rbodfu" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />
                EC:<input type='text' name='rbod_ec' placeholder='Enter the EC Port' id="rbodec" onkeypress="return (event.charCode > 64 &&
                event.charCode < 91) || (event.charCode > 96 && event.charCode < 123)" />

            </fieldset>
        </template>
<fieldset>
                Number of Chasis
                <select input type='text' name='chassis'   required >
                <option value=""> - Number of Controllers - </option>
                <option data-extra=true value='1'>1
                <option data-extra=true value='2'>2
                </select>
            </fieldset>
            <fieldset>
                Number of Controllers
                <select input type='text' name='ctrls' onchange="EnableDisableDropDown(this);"  required >
                <option value=""> - Number of Controllers - </option>
                <option data-extra=true value='1'>1
                <option data-extra=true value='2'>2
                </select>
            </fieldset>

Body:
Please refer below code. also please find fiddle link in comment. If you need more help please create fiddle of your example.

<h2>Tabs</h2>
<select id="tabsToDisplay">
<option value="1">1</option>
<option value="2">2</option>
</select><br/><br/>

<div class="tab">
  <button class="tablinks" id= "tab1btn" >tab1</button>
  <button class="tablinks" id= "tab2btn" >tab2</button>
</div>

<div id="tab1" class="tabcontent">
  <h3>Tab1</h3>
  <p>You selected tab1</p>
</div>

<div id="tab2" class="tabcontent">
  <h3>Tab2</h3>
  <p>You selected tab2</p>
</div>
// A $( document ).ready() block.
$( document ).ready(function() {
 function displaySelectedTabs(selectedNumber){
 switch(selectedNumber){
  case "1":
  $("#tab2btn").hide();
  $("#tab2").hide();
  break;
  case "2":
  $("#tab2btn").show();
  break;
 }
}
var selectedNumber = $("#tabsToDisplay").val();
displaySelectedTabs(selectedNumber);
 function tabClick(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
$("#tab1btn" ).click(function() {
  tabClick(event, 'tab1');
});
$("#tab2btn" ).click(function() {
  tabClick(event, 'tab2');
});
$( "#tabsToDisplay" ).change(function() {
  var selectedNumber = $("#tabsToDisplay").val();
displaySelectedTabs(selectedNumber);
});
});


问:
how to check the textbox value user enter the value in textbox is right or wrong using ajax Jquery?
I m working with ajax jquery Search Functionality.

when I search the record in textbox then get the record but when I search false record then get the false record? that is the issue

table:

Emploee.aspx

```<code>                  <tr>
                    <td>
                        Search Record:   <asp:TextBox ID="txtsearch" runat="server"></asp:TextBox>
                                         <input id="btnsearch" type="button" value="Search" onclick="searchrecord()" />
                    </td>
                </tr>
            </table>
        </div>

        <div class="row">
            <div>
                <table id="tbl" border="1">
                    <thead>
                        <tr>
                            <th>StudentName</th>
                            <th>StudentAddress</th><br /><br />
                            <th>Edit</th>
                        </tr>
                    </thead>
                </table>
            </div>
        </div>

       function searchrecord(studname) {

                jQuery.ajax({
                    url: "WebForm1.aspx/search",
                    type: 'post',
                    contentType: 'application/json;charset=utf-8',
                    datatype: 'json',
                    data: "{ studname:'" + $("#txtsearch").val() + "' }",
                    success: function (data) {
                        debugger

                        if (data.d == $("#txtsearch").val()) {

                            debugger

                            txt = "<tr><td>" + data.d + "</td></tr>";
                            $("#tbl").append(txt);
                            alert('you enter right record');

                        }

                        else if (data.d != $("#txtsearch").val()) {

                            alert('you enter wrong record');

                        }

                    },
                    error: function () {
                        alert('search Error');  //now whatever i search then this run
                    },
                });
            }
</code>```

Emploee.aspx

```<code>        [WebMethod]
        public static string search(string studname,bool flg)
        {
            string data = "";
            SqlConnection con = new SqlConnection(cn);

            SqlCommand cmd = new SqlCommand("SELECT studname FROM tblstud WHERE studname LIKE @studname and active=@flagTrueOrFalse", con);
            con.Open();

            cmd.Parameters.AddWithValue("@studname", "%" + studname + "%");
            cmd.Parameters.AddWithValue("@flag", SqlDbType.Bit).Value = flg;

            SqlDataReader reader = cmd.ExecuteReader();

            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    studname = reader[0].ToString();
                }
            }
            else
            {
                Console.WriteLine("No rows found.");
            }

            reader.Close();
            data = studname;
            return data;
        }
</code>```

how to solve if-else condition ajax logic?

main get data list:

```<code>function GetData() {
                $.ajax({

                    url: 'Emploee.aspx/GetData',
                    type: 'post',
                    contentType: 'application/json;charset=utf-8',
                    datatype: 'json',
                    success: function (data) {
                        data = JSON.parse(data.d);
                        $.each(data, function (index, element) {
                            $("#tbl").append('<td>' + element.studname + '</td>');
                            $("#tbl").append('<td>' + element.studaddress + '</td>');
                            $("#tbl").append('<td><input type="button" id="btnupdate" value="Update" onclick="Update(' + element.studid + ', \'' + element.studname + '\' ,\'' + element.studaddress + '\')" /></td>');
                        });
                    },
                    error: function (error) {
                        alert('Not Get Data')
                    },
                });
            }
</code>```

simple, I want the add an if-else condition when the user enters the true record then add the record and the user gets a false record then gets the alert message box?

I want to set below condition in the above ajax:

```<code>if(textbox value match then going inside)
{
  txt = "<tr><td>" + data.d + "</td></tr>";
  $("#tbl").append(txt);
}
else if(textbox value not match then going inside)
{alert("please proper record enter");}
</code>```

Console log:

preview:

```<code>{Message: "Invalid web service call, missing value for parameter: 'flg'.",…}
Message: "Invalid web service call, missing value for parameter: 'flg'."
StackTrace: "   at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)
↵   at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)
↵   at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)
↵   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)"
ExceptionType: "System.InvalidOperationException"

</code>```

Response

```<code>{"Message":"Invalid web service call, missing value for parameter: \u0027flg\u0027.","StackTrace":"   at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n   at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n   at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
</code>```

答:
the first thing that I would like to whenever you try to search the student, please remove Html before appending the response data. so it would avoid confusion if you update content multiple times.

Also, one thing that I notice is that you have taken 2 parameters in the SQL query but you are not passing @flagTrueOrFalse  parameter. so make it proper. if still facing the problem then please give us more details so we cal helps you.

Body:
I m working with ajax jquery Search Functionality.

when I search the record in textbox then get the record but when I search false record then get the false record? that is the issue

table:

Emploee.aspx

                        Search Record:   <asp:TextBox ID="txtsearch" runat="server"></asp:TextBox>
                                         <input id="btnsearch" type="button" value="Search" onclick="searchrecord()" />

                            StudentName
                            StudentAddress

                            Edit

       function searchrecord(studname) {

                jQuery.ajax({
                    url: "WebForm1.aspx/search",
                    type: 'post',
                    contentType: 'application/json;charset=utf-8',
                    datatype: 'json',
                    data: "{ studname:'" + $("#txtsearch").val() + "' }",
                    success: function (data) {
                        debugger

                        if (data.d == $("#txtsearch").val()) {

                            debugger

                            txt = "
" + data.d + "
";
                            $("#tbl").append(txt);
                            alert('you enter right record');

                        }

                        else if (data.d != $("#txtsearch").val()) {

                            alert('you enter wrong record');

                        }

                    },
                    error: function () {
                        alert('search Error');  //now whatever i search then this run
                    },
                });
            }

Emploee.aspx

        [WebMethod]
        public static string search(string studname,bool flg)
        {
            string data = "";
            SqlConnection con = new SqlConnection(cn);

            SqlCommand cmd = new SqlCommand("SELECT studname FROM tblstud WHERE studname LIKE @studname and active=@flagTrueOrFalse", con);
            con.Open();

            cmd.Parameters.AddWithValue("@studname", "%" + studname + "%");
            cmd.Parameters.AddWithValue("@flag", SqlDbType.Bit).Value = flg;

            SqlDataReader reader = cmd.ExecuteReader();

            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    studname = reader[0].ToString();
                }
            }
            else
            {
                Console.WriteLine("No rows found.");
            }

            reader.Close();
            data = studname;
            return data;
        }

how to solve if-else condition ajax logic?

main get data list:

function GetData() {
                $.ajax({

                    url: 'Emploee.aspx/GetData',
                    type: 'post',
                    contentType: 'application/json;charset=utf-8',
                    datatype: 'json',
                    success: function (data) {
                        data = JSON.parse(data.d);
                        $.each(data, function (index, element) {
                            $("#tbl").append('' + element.studname + '	');
                            $("#tbl").append('' + element.studaddress + '	');
                            $("#tbl").append('<input type="button" id="btnupdate" value="Update" onclick="Update(' + element.studid + ', \'' + element.studname + '\' ,\'' + element.studaddress + '\')" />	');
                        });
                    },
                    error: function (error) {
                        alert('Not Get Data')
                    },
                });
            }

simple, I want the add an if-else condition when the user enters the true record then add the record and the user gets a false record then gets the alert message box?

I want to set below condition in the above ajax:

if(textbox value match then going inside)
{
  txt = "
" + data.d + "
";
  $("#tbl").append(txt);
}
else if(textbox value not match then going inside)
{alert("please proper record enter");}

Console log:

preview:

{Message: "Invalid web service call, missing value for parameter: 'flg'.",…}
Message: "Invalid web service call, missing value for parameter: 'flg'."
StackTrace: "   at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)
↵   at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)
↵   at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)
↵   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)"
ExceptionType: "System.InvalidOperationException"

Response

{"Message":"Invalid web service call, missing value for parameter: \u0027flg\u0027.","StackTrace":"   at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n   at System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object target, IDictionary`2 parameters)\r\n   at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}


答:
Use shebang. #!/usr/bin/python

In the first line of the code with the serial number of Python you want at the end.

You'll need to then run your script like ./my_script.py

Title: Opening Python code with a specific version

Body:
while there are multiple versions of Python installed on a Linux machine, is there a way to mention in the script to be open with a specific version, say, 3.8 even if we issue the #python script.py as opposed to python3.8 script.py ?
I don't want to use Linux alias command. I wanna know if that is possible to be accomplished within the script


问:
ansbile stdout_line to new strings
I try to get bash tool for db output to ansbisle string,s but doesn't found no any working solution

```<code>   - set_fact:
        db_data: "{{ db.stdout_lines  }}"
   - debug: var=db_data
</code>```

Here is debug output

```<code>TASK [debug] ***********************************************************************************************************************************************************************
ok: [localhost] => {
    "db_data": [
        "host: localhost",
        "username: user",
        "password: pass",
        "database: db_name"
    ]
}
</code>```

How possible get host, username, password, database as unique strings?

答:
Q: "Get host, username, password, database as unique strings."

A: Instead of a list, create a dictionary. Then simply reference the attributes. For example

```<code>   - set_fact:
        db_data: "{{ db_data|default({})|combine(item|from_yaml) }}"
      loop: "{{ db.stdout_lines }}"
    - debug:
        var: db_data
    - debug:
        var: db_data.username
</code>```

give

```<code>    "db_data": {
        "database": "db_name",
        "host": "localhost",
        "password": "pass",
        "username": "user"
    }

    "db_data.username": "user"
</code>```

Title: ansbile stdout_line to new strings

Body:
I try to get bash tool for db output to ansbisle string,s but doesn't found no any working solution

   - set_fact:
        db_data: "{{ db.stdout_lines  }}"
   - debug: var=db_data

Here is debug output

TASK [debug] ***********************************************************************************************************************************************************************
ok: [localhost] => {
    "db_data": [
        "host: localhost",
        "username: user",
        "password: pass",
        "database: db_name"
    ]
}

How possible get host, username, password, database as unique strings?

Body:
Q: "Get host, username, password, database as unique strings."

A: Instead of a list, create a dictionary. Then simply reference the attributes. For example

   - set_fact:
        db_data: "{{ db_data|default({})|combine(item|from_yaml) }}"
      loop: "{{ db.stdout_lines }}"
    - debug:
        var: db_data
    - debug:
        var: db_data.username

give

    "db_data": {
        "database": "db_name",
        "host": "localhost",
        "password": "pass",
        "username": "user"
    }

    "db_data.username": "user"


问:
Disallow plugin activation on multi-site
My plugin currently does not support multi-site wordpress. How can I gracefully disallow my plugin being activated on a multi-site website? When I say gracefully I mean, I want the user to try to click activate and receive a message such as 'This plugin does not support Mult-Site WordPress. Plugin cannot be activated.'.

Or can I remove the activate option on the Installed Plugins page? Whats the convention here?

答:
I found this page which can be very handy for you:
https://developer.wordpress.org/plugins/plugin-basics/activation-deactivation-hooks/

You can use the register_activation_hook( FILE, 'pluginprefix_function_to_run' );
hook to check if the current site is a wpmu if it is you can then trigger a fnction to deactivate your plugin.

```<code>    register_activation_hook( __FILE__, 'check_wpmu' );

function check_wpmu() {
if( is_multisite() ){
     add_action('update_option_active_plugins', 'deactivate_my_plugin');
   }
}

function deactivate_my_plugin(){
   deactivate_plugins('your_plugin_folder/your_plugin_file.php');
}
</code>```

check_wpmu: is the function that WP will trigger when your plugin is first activated.
deactivate_my_plugin: is the function that will be triggered by check_wpmu if the wp is multisite and it will reactivate your plugin immediately.

Thanks,

Body:
I found this page which can be very handy for you:
https://developer.wordpress.org/plugins/plugin-basics/activation-deactivation-hooks/

You can use the register_activation_hook( FILE, 'pluginprefix_function_to_run' );
hook to check if the current site is a wpmu if it is you can then trigger a fnction to deactivate your plugin.

    register_activation_hook( __FILE__, 'check_wpmu' );

function check_wpmu() {
if( is_multisite() ){
     add_action('update_option_active_plugins', 'deactivate_my_plugin');
   }
}

function deactivate_my_plugin(){
   deactivate_plugins('your_plugin_folder/your_plugin_file.php');
}

check_wpmu: is the function that WP will trigger when your plugin is first activated.
deactivate_my_plugin: is the function that will be triggered by check_wpmu if the wp is multisite and it will reactivate your plugin immediately.

Thanks,


问:
ngrams analysis in tidytext in R
I am trying to do ngram analysis for in tidytext, I have a corpus of 770 speeches. However the function unnest_tokens in tidytext takes data frame as input. when i checked with the example (jane austin books) each line of the book is stored as row in a data frame. i am not able to convert the corpus into a dataframe, neither for one speech at a time nor for all the corpus at once.

What is the way i can run ngrams (n=2,3, etc) analysis on tidytext using unnest tokens on my corpus. Can someone please suggest?

Thanks

答:
You can use library ngram & tm for this.You can replace "myCorpus" with the corpus you created.

```<code>library(tm)
library(ngarm)
myCorpus<-c("Hi How are you","Hello World","I love Stackoverflow","Good Bye All")
ng <- ngram (myCorpus , n =2)
get.phrasetable (ng)
</code>```

If you want to tokenize and convert your corpus into a dataframe then use the below code.

```<code> tokenizedCorpus <- lapply(myCorpus, scan_tokenizer)
 mydata <- data.frame(text = sapply(tokenizedCorpus, paste, collapse = " "),stringsAsFactors = FALSE)
</code>```

Title: ngrams analysis in tidytext in R

Body:
You can use library ngram & tm for this.You can replace "myCorpus" with the corpus you created.

library(tm)
library(ngarm)
myCorpus<-c("Hi How are you","Hello World","I love Stackoverflow","Good Bye All")
ng <- ngram (myCorpus , n =2)
get.phrasetable (ng)

If you want to tokenize and convert your corpus into a dataframe then use the below code.

 tokenizedCorpus <- lapply(myCorpus, scan_tokenizer)
 mydata <- data.frame(text = sapply(tokenizedCorpus, paste, collapse = " "),stringsAsFactors = FALSE)


答:
Please, use following code.The parameters to the functions you are using seems to have changed</p>

```<code> private func showAnimation()
    {
    if self.resultPresent.alpha == 1.0
    {
        UIView.animate(withDuration: 2.0, delay: 0.0, options: .curveEaseOut, animations: {
            self.resultPresent.alpha = 1.0 // Final value of alpha
        }, completion: nil)
      }
}
</code>```

Body:
I try to make fade out animation and the code like below.
But I got the error like title, I don't know how to fix it.
Anyone who can help me ?Thx advance!!!

private func showAnimation(){
    if self.resultPresent.alpha == 1.0{
          UIView.animate(withDuration: 2,option: .curveEaseOut, animations: {
              self.resultPresent.alpha = CGFloat(0)→Expression type '@lvalue CGFloat' is ambiguous without more context
          })
      }
}

Body:
Please, use following code.The parameters to the functions you are using seems to have changed

 private func showAnimation()
    {
    if self.resultPresent.alpha == 1.0
    {
        UIView.animate(withDuration: 2.0, delay: 0.0, options: .curveEaseOut, animations: {
            self.resultPresent.alpha = 1.0 // Final value of alpha
        }, completion: nil)
      }
}


问:
Vertical Scroll doesn't work outside div(col-md-6) within row
I am using Slick slider and bootstrap 4. I used slick slider inside col-md-6 within row , and I want the scroll to work outside div(col-md-6) with row. but I am not able find the solutions for the problem. Can anybody suggest me or help me how to solve the problem? I have attached the jsfiddle and codepen Code for reference

var $ = jQuery;
$(document).ready(function () {
  $('.customer-logos').slick({
    vertical: true,
    infinite: false,
    arrows: false,
    draggable: true,
    dots: true });

});

const slider = $(".customer-logos");

slider.on('wheel', function (e) {

  var slideCount = $(this)[0].slick["slideCount"];
  var currentIndex = $(this).slick("slickCurrentSlide");
  var totalSildeToShow = $(this)[0].slick.options["slidesToShow"];

  if (e.originalEvent.deltaY < 0) {
   e.preventDefault();
   if (currentIndex == slideCount)
    return;

    $(this).slick('slickPrev');
  } else {
    if (slideCount - totalSildeToShow === currentIndex)
    return;
    e.preventDefault();
    $(this).slick('slickNext');
  }

});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h2{
  text-align:center;
  padding: 20px;
}
/* Slider */

.slick-slide {
    margin: 0px 20px;
}

.slick-slide img {
    width:500px;
    height:250px;
}
.slick-dots {
    position: absolute;
    bottom: 37% !important;
    display: grid !important;
    width: 0 !important;
    padding: 0;
    margin: 0;
    list-style: none;
    text-align: center;
    top: 15%;
    right: 0;
}</code>```

<link rel="stylesheet" href="https://unpkg.com/slick-carousel@1.7.1/slick/slick.css">
<link rel="stylesheet" href="https://unpkg.com/slick-carousel@1.7.1/slick/slick-theme.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />

Our Partners

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed gravida, metus sit amet ornare pretium, sem velit facilisis arcu, id laoreet nibh augue ac justo. Duis pellentesque, elit id semper gravida, tellus ante porttitor nisl, et molestie nisi elit eu libero. Suspendisse ornare tincidunt tellus, vitae fermentum enim suscipit vitae. Proin et nisl sed neque commodo euismod aliquet consequat lectus. Integer vitae quam rhoncus, blandit enim ut, mollis justo. Donec pulvinar ex in facilisis venenatis. Ut ullamcorper eros sit amet leo dictum elementum eget sed urna.

```

答:
@pavankumar, check the snippet and jsFiddle. This is a workaround of what you asked. But you have to work on responsive part. Please use full screen to see the actual O/P

var $ = jQuery;
$(document).ready(function() {
  $('#slider_block').bind('mousewheel DOMMouseScroll', function(e) {
    const slider = $(".customer-logos");
    var slideCount = $(slider)[0].slick["slideCount"];
    var currentIndex = $(slider).slick("slickCurrentSlide");
    var totalSildeToShow = $(slider)[0].slick.options["slidesToShow"];

    if (e.originalEvent.deltaY >= 0) {
      if ((slideCount - 1) !== currentIndex) {
        e.preventDefault();
        var delta = e.wheelDelta || e.detail;
        this.scrollTop += (delta < 0 ? 1 : -1) * 30;
        $(".customer-logos").slick('slickNext')
      }
    } else {
      if (currentIndex != 0) {
        e.preventDefault();
        var delta = e.wheelDelta || e.detail;
        this.scrollTop += (delta < 0 ? 1 : -1) * 30;
        $(".customer-logos").slick('slickPrev')
      }
    }

  });

  $('.customer-logos').slick({
    vertical: true,
    infinite: false,
    arrows: false,
    dots: true
  });

});

const slider = $(".customer-logos");

slider.on('wheel', function(e) {

  var slideCount = $(this)[0].slick["slideCount"];
  var currentIndex = $(this).slick("slickCurrentSlide");
  var totalSildeToShow = $(this)[0].slick.options["slidesToShow"];

  if (e.originalEvent.deltaY < 0) {
    e.preventDefault();
    $(this).slick('slickPrev');
  } else {
    if (slideCount - totalSildeToShow === currentIndex)
      return;
    e.preventDefault();
    $(this).slick('slickNext');
  }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>h2{
  text-align:center;
  padding: 20px;
}
/* Slider */

.slick-slide {
    margin: 0px 20px;
}

.slick-slide img {
    width:500px;
    height:250px;
}
.slick-dots {
    position: absolute;
    bottom: 37% !important;
    display: grid !important;
    width: 0 !important;
    padding: 0;
    margin: 0;
    list-style: none;
    text-align: center;
    top: 15%;
    right: 0;
}</code>```

<link rel="stylesheet" href="https://unpkg.com/slick-carousel@1.7.1/slick/slick.css">
<link rel="stylesheet" href="https://unpkg.com/slick-carousel@1.7.1/slick/slick-theme.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />

Our Partners

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed gravida, metus sit amet ornare pretium, sem velit facilisis arcu, id laoreet nibh augue ac justo. Duis pellentesque, elit id semper gravida, tellus ante porttitor nisl, et molestie nisi elit eu libero. Suspendisse ornare tincidunt tellus, vitae fermentum enim suscipit vitae. Proin et nisl sed neque commodo euismod aliquet consequat lectus. Integer vitae quam rhoncus, blandit enim ut, mollis justo. Donec pulvinar ex in facilisis venenatis. Ut ullamcorper eros sit amet leo dictum elementum eget sed urna.

```

Body:
I am using Slick slider and bootstrap 4. I used slick slider inside col-md-6 within row , and I want the scroll to work outside div(col-md-6) with row. but I am not able find the solutions for the problem. Can anybody suggest me or help me how to solve the problem? I have attached the jsfiddle and codepen Code for reference

var $ = jQuery;
$(document).ready(function () {
  $('.customer-logos').slick({
    vertical: true,
    infinite: false,
    arrows: false,
    draggable: true,
    dots: true });

});

const slider = $(".customer-logos");

slider.on('wheel', function (e) {

  var slideCount = $(this)[0].slick["slideCount"];
  var currentIndex = $(this).slick("slickCurrentSlide");
  var totalSildeToShow = $(this)[0].slick.options["slidesToShow"];

  if (e.originalEvent.deltaY < 0) {
   e.preventDefault();
   if (currentIndex == slideCount)
    return;

    $(this).slick('slickPrev');
  } else {
    if (slideCount - totalSildeToShow === currentIndex)
    return;
    e.preventDefault();
    $(this).slick('slickNext');
  }

});

h2{
  text-align:center;
  padding: 20px;
}
/* Slider */

.slick-slide {
    margin: 0px 20px;
}

.slick-slide img {
    width:500px;
    height:250px;
}
.slick-dots {
    position: absolute;
    bottom: 37% !important;
    display: grid !important;
    width: 0 !important;
    padding: 0;
    margin: 0;
    list-style: none;
    text-align: center;
    top: 15%;
    right: 0;
}

<link rel="stylesheet" href="https://unpkg.com/slick-carousel@1.7.1/slick/slick.css">
<link rel="stylesheet" href="https://unpkg.com/slick-carousel@1.7.1/slick/slick-theme.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />

Our Partners

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed gravida, metus sit amet ornare pretium, sem velit facilisis arcu, id laoreet nibh augue ac justo. Duis pellentesque, elit id semper gravida, tellus ante porttitor nisl, et molestie nisi elit eu libero. Suspendisse ornare tincidunt tellus, vitae fermentum enim suscipit vitae. Proin et nisl sed neque commodo euismod aliquet consequat lectus. Integer vitae quam rhoncus, blandit enim ut, mollis justo. Donec pulvinar ex in facilisis venenatis. Ut ullamcorper eros sit amet leo dictum elementum eget sed urna.

Body:
@pavankumar, check the snippet and jsFiddle. This is a workaround of what you asked. But you have to work on responsive part. Please use full screen to see the actual O/P

var $ = jQuery;
$(document).ready(function() {
  $('#slider_block').bind('mousewheel DOMMouseScroll', function(e) {
    const slider = $(".customer-logos");
    var slideCount = $(slider)[0].slick["slideCount"];
    var currentIndex = $(slider).slick("slickCurrentSlide");
    var totalSildeToShow = $(slider)[0].slick.options["slidesToShow"];

    if (e.originalEvent.deltaY >= 0) {
      if ((slideCount - 1) !== currentIndex) {
        e.preventDefault();
        var delta = e.wheelDelta || e.detail;
        this.scrollTop += (delta < 0 ? 1 : -1) * 30;
        $(".customer-logos").slick('slickNext')
      }
    } else {
      if (currentIndex != 0) {
        e.preventDefault();
        var delta = e.wheelDelta || e.detail;
        this.scrollTop += (delta < 0 ? 1 : -1) * 30;
        $(".customer-logos").slick('slickPrev')
      }
    }

  });

  $('.customer-logos').slick({
    vertical: true,
    infinite: false,
    arrows: false,
    dots: true
  });

});

const slider = $(".customer-logos");

slider.on('wheel', function(e) {

  var slideCount = $(this)[0].slick["slideCount"];
  var currentIndex = $(this).slick("slickCurrentSlide");
  var totalSildeToShow = $(this)[0].slick.options["slidesToShow"];

  if (e.originalEvent.deltaY < 0) {
    e.preventDefault();
    $(this).slick('slickPrev');
  } else {
    if (slideCount - totalSildeToShow === currentIndex)
      return;
    e.preventDefault();
    $(this).slick('slickNext');
  }
});

h2{
  text-align:center;
  padding: 20px;
}
/* Slider */

.slick-slide {
    margin: 0px 20px;
}

.slick-slide img {
    width:500px;
    height:250px;
}
.slick-dots {
    position: absolute;
    bottom: 37% !important;
    display: grid !important;
    width: 0 !important;
    padding: 0;
    margin: 0;
    list-style: none;
    text-align: center;
    top: 15%;
    right: 0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.6.0/slick.js"></script>
<link rel="stylesheet" href="https://unpkg.com/slick-carousel@1.7.1/slick/slick.css">
<link rel="stylesheet" href="https://unpkg.com/slick-carousel@1.7.1/slick/slick-theme.css">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" />
<section style="height: 100vh;background: #f436e3"></section>
<section id="slider_block">
  <div class="container ">
    <h2>Our Partners</h2>
    <div class="row">
      <div class="col-md-6">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed gravida, metus sit amet ornare pretium, sem velit facilisis arcu, id laoreet nibh augue ac justo. Duis pellentesque, elit id semper gravida, tellus ante porttitor nisl, et molestie nisi elit eu libero. Suspendisse ornare tincidunt tellus, vitae fermentum enim suscipit vitae. Proin et nisl sed neque commodo euismod aliquet consequat lectus. Integer vitae quam rhoncus, blandit enim ut, mollis justo. Donec pulvinar ex in facilisis venenatis. Ut ullamcorper eros sit amet leo dictum elementum eget sed urna.</p>
      </div>
      <div class="col-md-6">
        <div class="customer-logos slider">
          <div class="slide"><img src="https://image.freepik.com/free-vector/luxury-letter-e-logo-design_1017-8903.jpg"></div>
          <div class="slide"><img src="https://image.freepik.com/free-vector/3d-box-logo_1103-876.jpg"></div>
          <div class="slide"><img src="https://image.freepik.com/free-vector/blue-tech-logo_1103-822.jpg"></div>
          <div class="slide"><img src="https://image.freepik.com/free-vector/colors-curl-logo-template_23-2147536125.jpg"></div>
          <div class="slide"><img src="https://image.freepik.com/free-vector/abstract-cross-logo_23-2147536124.jpg"></div>
          <div class="slide"><img src="https://image.freepik.com/free-vector/football-logo-background_1195-244.jpg"></div>
          <div class="slide"><img src="https://image.freepik.com/free-vector/background-of-spots-halftone_1035-3847.jpg"></div>
          <div class="slide"><img src="https://image.freepik.com/free-vector/retro-label-on-rustic-background_82147503374.jpg"></div>

        </div>

      </div>
    </div>
  </div>
</section>
<section style="height: 100vh;background: #f436e3"></section>


问:
create a resultset of calendar dates
I should use a stored procedure to fill a calendar for 10 years in a SQL database!

Three columns should I fill in with the records: date,weekday or weekend, dayname( monday,...).

Can somebody help me?

答:
I apporached this as a tally table problem.  I am using spt_values from Master as my tally table.  It only goes up to 2048 which is enough data for 5.5 years.  You can create your own tally table with as many numbers as you need.

```<code>Declare @startDate Date = '1/1/2011';

SELECT DateAdd(d, number, @startDate) [Date],
       CASE WHEN DATEPART(dw, DateAdd(d, number, @startDate)) IN (1,7) THEN 'Weekend' ELSE 'Weekday' END [WeekDayEnd],
       DateName(weekday, DateAdd(d, number, @startDate)) DayOfWeek
FROM spt_values
WHERE type = 'P';
</code>```

This gets the following results:

```<code>Date        WeekDayEnd  DayOfWeek
2011-01-01  Weekend     Saturday
2011-01-02  Weekend     Sunday
2011-01-03  Weekday     Monday
2011-01-04  Weekday     Tuesday
2011-01-05  Weekday     Wednesday
2011-01-06  Weekday     Thursday
2011-01-07  Weekday     Friday
2011-01-08  Weekend     Saturday
2011-01-09  Weekend     Sunday
2011-01-10  Weekday     Monday
</code>```

Title: create a resultset of calendar dates

Body:
I apporached this as a tally table problem.  I am using spt_values from Master as my tally table.  It only goes up to 2048 which is enough data for 5.5 years.  You can create your own tally table with as many numbers as you need.

Declare @startDate Date = '1/1/2011';

SELECT DateAdd(d, number, @startDate) [Date],
       CASE WHEN DATEPART(dw, DateAdd(d, number, @startDate)) IN (1,7) THEN 'Weekend' ELSE 'Weekday' END [WeekDayEnd],
       DateName(weekday, DateAdd(d, number, @startDate)) DayOfWeek
FROM spt_values
WHERE type = 'P';

This gets the following results:

Date        WeekDayEnd  DayOfWeek
2011-01-01  Weekend     Saturday
2011-01-02  Weekend     Sunday
2011-01-03  Weekday     Monday
2011-01-04  Weekday     Tuesday
2011-01-05  Weekday     Wednesday
2011-01-06  Weekday     Thursday
2011-01-07  Weekday     Friday
2011-01-08  Weekend     Saturday
2011-01-09  Weekend     Sunday
2011-01-10  Weekday     Monday