问:
How to get ID dynamic in Jquery?
I am making dynamic input, when the user clicks "Add From Checklist" there will be an input form, and if clicked again "Add From Checklist" then the input form becomes two and so on, for the actual select code there is already data such as
'1-022020-001', now for inputting stations and equipment, the data is where the value '1-022020-001' is in the database, now I'm still confused about how to get results from value '1-022020-001' can be sent to the controller and returned to js to display the input Station and Equipment.

DEMO:

var html = '';
    $('.btnSend').attr('disabled', true);

    $("#inputCode, #inputStasiun, #inputPeralatan").select2({
        placeholder: "Choose one",
        allowClear: true
    });

    var runNumberAdd = 1;
    $("#add-more").click(function() {
        html =
        '
'+
            '
'+
                '
'+
                    '
'+
                        'Tanggal'+
                        '
'+
                            '<input name="inputTgl[]" type="date" id="inputTglClone'+ runNumberAdd +'" class="form-control inputTglClone">'+
                        '
'+
                    '
'+
                    '
'+
                        'Code'+
                        '
'+
                            '<select name="inputCode[]" id="inputCodeClone'+ runNumberAdd +'" class="form-control select2 inputCodeClone">'+
                            '</select>'+
                        '
'+
                    '
'+
                    '
'+
                        'Stasiun'+
                        '
'+
                            '<select name="inputStasiun[]" id="inputStasiunClone'+ runNumberAdd +'" class="form-control select2 inputStasiunClone">'+
                            '</select>'+
                            '<input name="inputStasiunHidden[]" type="text" id="inputStasiunHiddenClone'+ runNumberAdd +'" class="form-control inputStasiunHiddenClone">'+
                        '
'+
                    '
'+
                    '
'+
                        'Peralatan'+
                        '
'+
                            '<select name="inputPeralatan[]" id="inputPeralatanClone'+ runNumberAdd +'" class="form-control select2 inputPeralatanClone">'+
                            '</select>'+
                        '
'+
                    '
'+
                    '
'+
                        'Deskripsi'+
                        '
'+
                            '<textarea name="inputDeskripsi[]" id="inputDeskripsiClone'+ runNumberAdd +'" class="form-control inputDeskripsiClone"></textarea>'+
                        '
'+
                    '
'+
                    '
'+
                        'Resume'+
                        '
'+
                            ''+
                                '<input type="radio" name="inputChecklist[]" id="inputChecklist1Clone'+ runNumberAdd +'" class="inputChecklist1Clone'+ runNumberAdd +'" value="1"> OK'+
                            ''+
                            ''+
                                '<input type="radio" name="inputChecklist[]" id="inputChecklist2Clone'+ runNumberAdd +'" class="inputChecklist2Clone'+ runNumberAdd +'" value="0"> NOK'+
                            ''+
                            '
'+
                                '<button type="button" class="btn btn-danger btn-sm remove_list"> Hapus From Checklist</button>'+
                            '
'+
                        '
'+
                    '
'+
                '
'+
            '
'+
        '
';
        $('.clone-form').append(html);
        $(".inputCodeClone, .inputStasiunClone, .inputPeralatanClone").select2({
            placeholder: "Choose one",
            allowClear: true
        });
        $.ajax({
            url   : 'showDataCode',
            dataType : 'JSON',
            async : true,
            success : function(data) {
                var minrunNumberAdd = runNumberAdd - 1;
                var attrCode = '#inputCodeClone' + minrunNumberAdd;
                $(attrCode).append($("<option selected disabled></option>").attr("value", '').text(''));
                $.each(data, function(key, value) {
                    $(attrCode).append($("<option></option>").attr("value", value.id).text(value.code));
                });
            }
        });
        $('.btnSend').attr('disabled', false);
        $('.inputStasiunClone').attr("disabled", true);
        $('.inputPeralatanClone').attr("disabled", true);
        runNumberAdd++;
    });

    $("body").on("click", ".remove_list",function() {
        var numItems = $('.control-group').length;
        $(this).parents(".control-group").remove();
        if (numItems == 1) {
            $('.btnSend').attr('disabled', true);
        } else {
            $('.btnSend').attr('disabled', false);
        }
    });

    // How to get attribut ID
    // My Xample
    $('input[id^="inputCodeClone"]').on('click', function() {
        alert('A');
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<div class="box-header">
                    <div class="pull-right">
                        <button type="button"  id="add-more" class="btn btn-success btn-sm"> Tambah From Checklist</button>
                    </div>
                </div>
                <form action="<?= base_url('GeneralFormChecklist/submitChecklist'); ?>" method="post" id="formInput">
                    <div class="box-body">
                        <div class="clone-form">
                        </div>
                    </div>
                    <div class="box-footer">
                        <div class="pull-right">
                            <button type="submit" class="btn btn-primary btn-sm btnSend">Kirim Checklist</button>
                        </div>
                    </div>
                </form></code>```

Sample data in a database

The question is:

how to be able to display id_location in the input station and id_equipment_name in the input equipment by selecting code as where in the database later?

NOTE: the code that I have stuck when looking for a dynamic ID

答:
I just try to add some fields .You modify

<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

                        <button type="button"  id="add-more" class="btn btn-success btn-sm"> Tambah From Checklist</button>

                <form action="<?= base_url('GeneralFormChecklist/submitChecklist'); ?>" method="post" id="formInput">

                            <button type="submit" class="btn btn-primary btn-sm btnSend">Kirim Checklist</button>

                </form>
```

Title: How to get ID dynamic in Jquery?

Body:
I am making dynamic input, when the user clicks "Add From Checklist" there will be an input form, and if clicked again "Add From Checklist" then the input form becomes two and so on, for the actual select code there is already data such as
'1-022020-001', now for inputting stations and equipment, the data is where the value '1-022020-001' is in the database, now I'm still confused about how to get results from value '1-022020-001' can be sent to the controller and returned to js to display the input Station and Equipment.

DEMO:

var html = '';
    $('.btnSend').attr('disabled', true);

    $("#inputCode, #inputStasiun, #inputPeralatan").select2({
        placeholder: "Choose one",
        allowClear: true
    });

    var runNumberAdd = 1;
    $("#add-more").click(function() {
        html =
        '
'+
            '
'+
                '
'+
                    '
'+
                        'Tanggal'+
                        '
'+
                            '<input name="inputTgl[]" type="date" id="inputTglClone'+ runNumberAdd +'" class="form-control inputTglClone">'+
                        '
'+
                    '
'+
                    '
'+
                        'Code'+
                        '
'+
                            '<select name="inputCode[]" id="inputCodeClone'+ runNumberAdd +'" class="form-control select2 inputCodeClone">'+
                            '</select>'+
                        '
'+
                    '
'+
                    '
'+
                        'Stasiun'+
                        '
'+
                            '<select name="inputStasiun[]" id="inputStasiunClone'+ runNumberAdd +'" class="form-control select2 inputStasiunClone">'+
                            '</select>'+
                            '<input name="inputStasiunHidden[]" type="text" id="inputStasiunHiddenClone'+ runNumberAdd +'" class="form-control inputStasiunHiddenClone">'+
                        '
'+
                    '
'+
                    '
'+
                        'Peralatan'+
                        '
'+
                            '<select name="inputPeralatan[]" id="inputPeralatanClone'+ runNumberAdd +'" class="form-control select2 inputPeralatanClone">'+
                            '</select>'+
                        '
'+
                    '
'+
                    '
'+
                        'Deskripsi'+
                        '
'+
                            '<textarea name="inputDeskripsi[]" id="inputDeskripsiClone'+ runNumberAdd +'" class="form-control inputDeskripsiClone"></textarea>'+
                        '
'+
                    '
'+
                    '
'+
                        'Resume'+
                        '
'+
                            ''+
                                '<input type="radio" name="inputChecklist[]" id="inputChecklist1Clone'+ runNumberAdd +'" class="inputChecklist1Clone'+ runNumberAdd +'" value="1"> OK'+
                            ''+
                            ''+
                                '<input type="radio" name="inputChecklist[]" id="inputChecklist2Clone'+ runNumberAdd +'" class="inputChecklist2Clone'+ runNumberAdd +'" value="0"> NOK'+
                            ''+
                            '
'+
                                '<button type="button" class="btn btn-danger btn-sm remove_list"> Hapus From Checklist</button>'+
                            '
'+
                        '
'+
                    '
'+
                '
'+
            '
'+
        '
';
        $('.clone-form').append(html);
        $(".inputCodeClone, .inputStasiunClone, .inputPeralatanClone").select2({
            placeholder: "Choose one",
            allowClear: true
        });
        $.ajax({
            url   : 'showDataCode',
            dataType : 'JSON',
            async : true,
            success : function(data) {
                var minrunNumberAdd = runNumberAdd - 1;
                var attrCode = '#inputCodeClone' + minrunNumberAdd;
                $(attrCode).append($("<option selected disabled></option>").attr("value", '').text(''));
                $.each(data, function(key, value) {
                    $(attrCode).append($("<option></option>").attr("value", value.id).text(value.code));
                });
            }
        });
        $('.btnSend').attr('disabled', false);
        $('.inputStasiunClone').attr("disabled", true);
        $('.inputPeralatanClone').attr("disabled", true);
        runNumberAdd++;
    });

    $("body").on("click", ".remove_list",function() {
        var numItems = $('.control-group').length;
        $(this).parents(".control-group").remove();
        if (numItems == 1) {
            $('.btnSend').attr('disabled', true);
        } else {
            $('.btnSend').attr('disabled', false);
        }
    });

    // How to get attribut ID
    // My Xample
    $('input[id^="inputCodeClone"]').on('click', function() {
        alert('A');
    });

<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

                        <button type="button"  id="add-more" class="btn btn-success btn-sm"> Tambah From Checklist</button>

                <form action="<?= base_url('GeneralFormChecklist/submitChecklist'); ?>" method="post" id="formInput">

                            <button type="submit" class="btn btn-primary btn-sm btnSend">Kirim Checklist</button>

                </form>

Sample data in a database

The question is:

how to be able to display id_location in the input station and id_equipment_name in the input equipment by selecting code as where in the database later?

NOTE: the code that I have stuck when looking for a dynamic ID

Body:
I just try to add some fields .You modify

<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/css/select2.min.css" rel="stylesheet"/>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.0.13/dist/js/select2.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="box-header">
                    <div class="pull-right">
                        <button type="button"  id="add-more" class="btn btn-success btn-sm"> Tambah From Checklist</button>
                    </div>
                </div>
                <form action="<?= base_url('GeneralFormChecklist/submitChecklist'); ?>" method="post" id="formInput">
                    <div class="box-body">
                        <div class="clone-form">
                        </div>
                    </div>
                    <div class="box-footer">
                        <div class="pull-right">
                            <button type="submit" class="btn btn-primary btn-sm btnSend">Kirim Checklist</button>
                        </div>
                    </div>
                </form>
<script>
$(document).ready(function(){

var html = '';

    $('.btnSend').attr('disabled', true);

    $("#inputCode, #inputStasiun, #inputPeralatan").select2({
        placeholder: "Choose one",
        allowClear: true
    });

    var runNumberAdd = 1;
    $("#add-more").click(function() {
 html =  $('<div/>', {
        'class': 'col-sm-6 control-group'
    });
 var firstchild =  $('<div/>', {
        'class': 'form-group'
    });
   var lable1 =  $('<label/>', {
        'class': 'col-sm-2 control-label',
 text: 'Tanggal',
 id: 'lbl1'
    }).on('click',function(){
 alert("First lable");
});
var innerchild =  $('<div/>', {
        'class': 'col-sm-10'

    });
var firstinput =  $('<input/>', {
        'class': 'form-control inputTglClone',
 id: 'inputTglClone'+ runNumberAdd,
 type: 'date'
    });
innerchild.append(firstinput);
firstchild.append(lable1);
firstchild.append(innerchild);

 html.append(firstchild);

  var lable2 =  $('<label/>', {
        'class': 'col-sm-2 control-label',
 text: 'Code',
 id: 'lbl2'
    }).on('click',function(){
 alert("First lable");
});
 runNumberAdd = 2;
        var firstselectinput =  $('<select/>', {
        'class': 'form-control select2 inputCodeClone',
 id: 'inputTglClone_select',

    });
var innerchild1 =  $('<div/>', {
        'class': 'col-sm-10'

    });
var secondchild =  $('<div/>', {
        'class': 'form-group'
    });
 innerchild1.append(firstselectinput);
 secondchild.append(lable2);
 secondchild.append(innerchild1);
 html.append(secondchild);
        $('.clone-form').html(html);
        $(".inputCodeClone, .inputStasiunClone, .inputPeralatanClone").select2({
            placeholder: "Choose two",
            allowClear: true,
     data:[{id:'1',text:'one'},{id:'2',text:'two'}],
 createTag: function (params) {
      var term = $.trim(params.term);
      if (term === '') {
        return null;
      }
      return {id: term,text: term}

  }
        }).on("change", function (e) {
 var selectedvalue = e.currentTarget.selectedOptions[0].value;
 alert(selectedvalue);

});

        $('.btnSend').attr('disabled', false);
        $('.inputStasiunClone').attr("disabled", true);
        $('.inputPeralatanClone').attr("disabled", true);
        runNumberAdd++;
    });

    $("body").on("click", ".remove_list",function() {
        var numItems = $('.control-group').length;
        $(this).parents(".control-group").remove();
        if (numItems == 1) {
            $('.btnSend').attr('disabled', true);
        } else {
            $('.btnSend').attr('disabled', false);
        }
    });

});
</script
</body>


来源: stackexchange

问:
C#: How do I call a static method of a base class from a static method of a derived class?
In C#, I have base class Product and derived class Widget.

Product contains a static method MyMethod().

I want to call static method Product.MyMethod() from static method Widget.MyMethod().

I can't use the base keyword, because that only works with instance methods.

I can call Product.MyMethod() explicitly, but if I later change Widget to derive from another class, I have to revise the method.

Is there some syntax in C# similar to base that allows me to call a static method from a base class from a static method of a derived class?

答:
static methods are basically a method to fallback from object oriented concepts. As a consequence, they are not very flexible in inheritance hierarchies and it's not possible to do such a thing directly.

The closest thing I can think of is a using directive.

```<code>using mybaseclass = Namespace.BaseClass;

class MyClass : mybaseclass {

  static void MyMethod() {  mybaseclass.BaseStaticMethod();  }

}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
static methods are basically a method to fallback from object oriented concepts. As a consequence, they are not very flexible in inheritance hierarchies and it's not possible to do such a thing directly.

The closest thing I can think of is a using directive.

using mybaseclass = Namespace.BaseClass;

class MyClass : mybaseclass {

  static void MyMethod() {  mybaseclass.BaseStaticMethod();  }

}

OwnerDisplayName: Mehrdad Afshari


问:
ReportExecutionService2005 soap4r SOAP::FaultError: The session identifier is missing
How I should set the session identifier for communication with the server ?

```<code>@service = SOAP::WSDLDriverFactory.new(WSDL_URL).create_rpc_driver

@service.getExecutionInfo({})
</code>```

SOAP::FaultError: The session identifier is missing. A session identifier is required for this operation.  ---> The session identifier is missing. A session identifier is required for this operation. from #< SOAP::Mapping::Object:0xb5bfef2c>

答:
First I need to note I don't know anything about ruby-on-rails or soap4r but I've had a similar issue using the ReportExecutionService2005 web service from Java, so I can point you in the right direction.

The session identifier is generated once you load a report, so you need to call the LoadReport method of the web serivice which returns an ExecutionInfo object on which you call getExecutionID which gives you the session identifier you need.

This identifier needs to go into the SOAP headers for all subsequent requests for that report (change reports and you need to change the identifier in your header).  Your SOAP header should end up looking something like this:

```<code><env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
    <env:Header>
        <ssrs:ExecutionHeader xmlns:ssrs='http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices'>
            <ssrs:ExecutionID>your-execution-id</SSRS:ExecutionID>
        </ssrs:ExecutionHeader>
        ...
    </env:Header>
    ...
</env:Envelope>
</code>```

Obviously the your-execution-id will be replace with the return from getExecution ID.

How you get the header there in ruby and soap4r is not something I can help with.

Body:
How I should set the session identifier for communication with the server ?

@service = SOAP::WSDLDriverFactory.new(WSDL_URL).create_rpc_driver

@service.getExecutionInfo({})

SOAP::FaultError: The session identifier is missing. A session identifier is required for this operation.  ---> The session identifier is missing. A session identifier is required for this operation. from #< SOAP::Mapping::Object:0xb5bfef2c>

Body:
First I need to note I don't know anything about ruby-on-rails or soap4r but I've had a similar issue using the ReportExecutionService2005 web service from Java, so I can point you in the right direction.

The session identifier is generated once you load a report, so you need to call the LoadReport method of the web serivice which returns an ExecutionInfo object on which you call getExecutionID which gives you the session identifier you need.

This identifier needs to go into the SOAP headers for all subsequent requests for that report (change reports and you need to change the identifier in your header).  Your SOAP header should end up looking something like this:

<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
    <env:Header>
        <ssrs:ExecutionHeader xmlns:ssrs='http://schemas.microsoft.com/sqlserver/2005/06/30/reporting/reportingservices'>
            <ssrs:ExecutionID>your-execution-id</SSRS:ExecutionID>
        </ssrs:ExecutionHeader>
        ...
    </env:Header>
    ...
</env:Envelope>

Obviously the your-execution-id will be replace with the return from getExecution ID.

How you get the header there in ruby and soap4r is not something I can help with.

ContentLicense: CC BY-SA 3.0


问:
How to query database column names?
I have a table with multiple columns starting with one keyword link_. I.E. link_0_10, link_10_20, link_20_30 and so on.

I want to select only columns starting with these link_ keywords. How to do that? I can query by RegEx on the value, but on the columns? I have not been able to.

P.S.: I have no prior idea of how many columns may be present.

答:
SELECT *
FROM information_schema.columns
WHERE table_name = 'mytable' and column_name like 'link_%'
```

ContentLicense: CC BY-SA 4.0

Title: How to query database column names?


问:
Use custom path for naked main domain (except path) in apche2
I have the following apache config file

```<code><VirtualHost *:443>
    ServerName example.io
    ServerAlias *.*

    Alias /static /var/www/user/master/workbench/workbench/static
    DocumentRoot /var/www/user/master/workbench/workbench/static

    # Redirect naked URL to the specified URL
    # RedirectMatch ^/$ http://other-example.io

    # Load custom index page as homepage
    AliasMatch ^/$ /var/www/user/master/workbench/scnv_home

    WSGIDaemonProcess example.io   processes=1 threads=5 python-path=/var/www/user/master/workbench:/home/ubuntu/.virtualenv/app/lib/python2.7/site-packages/
    WSGIProcessGroup example.io
    WSGIScriptAlias / /var/www/user/master/workbench/workbench/wsgi.py

    <Directory /var/www/user/master/workbench/workbench/static >
        Order deny,allow
        Allow from all
        AllowOverride All
    </Directory>

</VirtualHost>
</code>```

The domain is used to access Django site using WSGI and RedirectMatch configuration option is used to redirect user to some other domain.

```<code>https://example.io        -> Redirects to http://other-example.io
https://example.io/path    # Served by Django
</code>```

Now I want to show a custom index.html page instead of redirecting user to some other domain.

For that I tried to use the AliasMatch option to point to the directory where index.html file exists, but it is still being served by Django and gives 404 page by Django.

How can I setup apache to serve request by Django if url has path, otherwise load custom index page?

答:
<VirtualHost _default_:443>

#JkMount /* worker1

DocumentRoot "/var/www/html"

ProxyPass /error/404.html !

ErrorDocument 404 /error/404.html

ProxyPass / "ajp://localhost:443/

ProxyPassReverse / "ajp://localhost:443/

ServerName yourdomain.com:443

Try to use above code in your ssl.conf file hope that will help you...!!!!

Body:
I have the following apache config file

<VirtualHost *:443>
    ServerName example.io
    ServerAlias *.*

    Alias /static /var/www/user/master/workbench/workbench/static
    DocumentRoot /var/www/user/master/workbench/workbench/static

    # Redirect naked URL to the specified URL
    # RedirectMatch ^/$ http://other-example.io

    # Load custom index page as homepage
    AliasMatch ^/$ /var/www/user/master/workbench/scnv_home

    WSGIDaemonProcess example.io   processes=1 threads=5 python-path=/var/www/user/master/workbench:/home/ubuntu/.virtualenv/app/lib/python2.7/site-packages/
    WSGIProcessGroup example.io
    WSGIScriptAlias / /var/www/user/master/workbench/workbench/wsgi.py

    <Directory /var/www/user/master/workbench/workbench/static >
        Order deny,allow
        Allow from all
        AllowOverride All
    </Directory>

</VirtualHost>

The domain is used to access Django site using WSGI and RedirectMatch configuration option is used to redirect user to some other domain.

https://example.io        -> Redirects to http://other-example.io
https://example.io/path    # Served by Django

Now I want to show a custom index.html page instead of redirecting user to some other domain.

For that I tried to use the AliasMatch option to point to the directory where index.html file exists, but it is still being served by Django and gives 404 page by Django.

How can I setup apache to serve request by Django if url has path, otherwise load custom index page?


问:
How to convert from a list of string to a list of int in array in python
```<code>a= pd.DataFrame({"A": [['1','2'], '2','3']}).to_numpy()
</code>```

I want to get a = {"A": [[1, 2], 2, 3]}
I cannot use astype for the list in array

答:
```<code> df.apply(lambda x: int(x), index=['A', ]), axis=1)
</code>```

the conversion is done with casting the string to int, i.e. '3' to int('3')

Body:
a= pd.DataFrame({"A": [['1','2'], '2','3']}).to_numpy()

I want to get a = {"A": [[1, 2], 2, 3]}
I cannot use astype for the list in array

Body:
 df.apply(lambda x: int(x), index=['A', ]), axis=1)

the conversion is done with casting the string to int, i.e. '3' to int('3')


问:
Prevent user from pasting images into CKEditor 5
Our users are copy pasting images into the editor (CKEditor 5), which is something we don't want to support.

The suggested fix for CKEditor 4 does not seem to work in 5.

How can I change the editor to disable this feature?

This is my config:

```<code>const editorConfig = {
  toolbar: ['heading', 'bold', 'italic', 'bulletedList', 'numberedList'],
  removePlugins: ['Image', 'ImageToolbar', 'ImageStyle', 'ImageUpload', 'ImageCaption'],
  heading: {
    options: [
      {
        model: 'paragraph',
        title: 'Paragraph',
        class: 'ck-heading_paragraph',
      },
      {
        model: 'heading2',
        view: 'h2',
        title: 'Heading',
        class: 'ck-heading_heading2',
      },
    ],
  },
};
</code>```

答:
If you want to completely disable the image feature, this is – make it impossible for images to be inserted/loaded in any way to the editor, then you should remove the Image, ImageToolbar, ImageStyle, 'ImageUpload, and ImageCaption plugins from your editor. The easiest way to achieve that is to use config.removePlugins. You can also check how to install plugins cause uninstalling is just the opposite process.

If you want to disallow inserting images, but still keep support for those images which are already present in the content, you need to handle it a bit differently. You'd have to block pasting/dropping them which can be done with the features exposed by the clipboard integration. You may also want to remove the ImageUpload plugin in thi case too. Finally, you probably won't need the imageUpload button in the toolbar, so you have to reconfigure it.

Body:
Our users are copy pasting images into the editor (CKEditor 5), which is something we don't want to support.

The suggested fix for CKEditor 4 does not seem to work in 5.

How can I change the editor to disable this feature?

This is my config:

const editorConfig = {
  toolbar: ['heading', 'bold', 'italic', 'bulletedList', 'numberedList'],
  removePlugins: ['Image', 'ImageToolbar', 'ImageStyle', 'ImageUpload', 'ImageCaption'],
  heading: {
    options: [
      {
        model: 'paragraph',
        title: 'Paragraph',
        class: 'ck-heading_paragraph',
      },
      {
        model: 'heading2',
        view: 'h2',
        title: 'Heading',
        class: 'ck-heading_heading2',
      },
    ],
  },
};


问:
Symfony/Doctrine/authentication, I can't recover the roles
I have a problem when i want to connect. Let me explain, I have two User and Role entities that are linked to a ManyToMany relationship, so I have a dynamic user_role table. I would like to connect with the user who has the ROLE_ADMIN but the problem is that I cannot read the object so that it reads this role. This shows me this error.

Warning: Illegal offset type in isset or empty

I think the problem comes from the line "$ role = $ this-> roles-> toArray ();" in getRoles.

Here is the code for User.php

```<code>class User implements UserInterface, \Serializable
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     */
    private $username;

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;

    /**
     * @ORM\Column(type="boolean", nullable=false, options={"default" : 0})
     */
    private $isActive;

    /**
     * @ORM\Column(type="string", unique=true, length=64)
     */
    private $token;

    /**
     * @ORM\Column(type="datetime")
     */
    private $expiresAt;

    /**
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="users", fetch="LAZY")
     * @ORM\JoinTable(name="user_role",
     *     joinColumns={
     *      @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="role_id", referencedColumnName="id")
     *   }
     *  )
     */
    private $role;

    public function __construct()
    {
        //$this->repository = $repository;
        $this->role = new ArrayCollection();
        //$this->roles = new Role();
    }

    /**
     * Add userRoles
     *
     * @param \App\Entity\Role $roles
     * @return User
     */
    public function addRoles(\App\Entity\Role $role)
    {
        $this->role[] = $role;

        return $this;
    }

    /**
     * Remove userRoles
     *
     * @param \App\Entity\Role $roles
     */
    public function removeRoles(\App\Entity\Role $role)
    {
        $this->role->removeElement($role);
    }

    /**
     * Get Role
     */
    public function getRoles() : array //Role return
    {
        //$role = $this->repository->find($this->getId());
        //$role = $role->getName();
        $role = $this->role->toArray();

        //$roles = ['ROLE_ADMIN'];
        //$role = $this->serialize($role);
        var_dump($role);
        //$role = $role[0]['name'];

        if (empty($role)) {
            $role[] = ['ROLE_ADMIN'];
        }
        return array_unique($role);
    }

    public function setRoles($role): self
    {
        //$this->roles = $roles;
        if (is_array($role)) {
            $this->role = $role;
        } else {
            $this->role->clear();
            $this->role->add($role);
        }
        return $this;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return (string)$this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getPassword(): string
    {
        return (string)$this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getSalt()
    {
        // not needed when using the "bcrypt" algorithm in security.yaml
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    public function getIsActive(): ?bool
    {
        return $this->isActive;
    }

    public function setIsActive(bool $isActive): self
    {
        $this->isActive = $isActive;

        return $this;
    }

    public function getToken(): ?string
    {
        return $this->token;
    }

    public function setToken(string $token): self
    {
        $this->token = $token;

        return $this;
    }

    public function getExpiresAt(): ?\DateTimeInterface
    {
        return $this->expiresAt;
    }

    public function setExpiresAt(\DateTimeInterface $expiresAt): self
    {
        $this->expiresAt = $expiresAt;

        return $this;
    }

    public function isExpired(): bool
    {
        return $this->getExpiresAt() <= new \DateTime();
    }

    public function createToken()
    {
        return substr(str_replace(['+', '/'], ['-', '_'], base64_encode(random_bytes(50))), 0, 63);
    }

    /**
     * String representation of object
     * @link https://php.net/manual/en/serializable.serialize.php
     * @return string the string representation of the object or null
     * Transform object to string
     */
    public function serialize()
    {
        return serialize([
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            $this->token,
            $this->expiresAt
        ]);
    }

    /**
     * @param string $serialized
     * Transform string to object
     */
    public function unserialize($serialized)
    {
        list(
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            $this->token,
            $this->expiresAt
            ) = unserialize($serialized, ['allowed_classes' => false]);
    }

}
</code>```

And here is the code for Role.php

```<code>class Role implements \Serializable
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $role;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $description;

    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
     */
    private $users;

    public function __construct()
    {
        $this->users = new ArrayCollection();
    }

    public function getUsers()
    {
        return $this->users;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getRole(): ?string
    {
        return $this->role;
    }

    public function setRole($role)
    {
        $this->role = $role;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(string $description): self
    {
        $this->description = $description;

        return $this;
    }

    /*
    * methods for RoleInterface
    */
    /*public function getRoles()
    {
        return $this->getRole();
    }*/

    /**
     * Add users
     *
     * @param \App\Entity\User $users
     * @return Role
     */
    public function addUser(\App\Entity\User $users)
    {
        $this->users[] = $users;

        return $this;
    }

    /**
     * Remove users
     *
     * @param \App\Entity\User $users
     */
    public function removeUser(App\Entity\User $users)
    {
        $this->users->removeElement($users);
    }

    /**
     * String representation of object
     * @link https://php.net/manual/en/serializable.serialize.php
     * @return string the string representation of the object or null
     * Transform object to string
     */
    public function serialize()
    {
        return serialize([
            $this->id,
            $this->role,
            $this->description
        ]);
    }

    /**
     * @param string $serialized
     * Transform string to object
     */
    public function unserialize($serialized)
    {
        list(
            $this->id,
            $this->role,
            $this->description
            ) = unserialize($serialized, ['allowed_classes' => false]);
    }
}
</code>```

then in my controller I did a findAll

```<code>/**
* @Route("/admin/user", name="admin_user_index")
* @return \Symfony\Component\HttpFoundation\Response
*/
public function listUser(UserRepository $user)
{
return $this->render('admin/security_user/list_user.html.twig', ['user' => $user->findAll()]);
}
</code>```

var_dump($role)

```<code>/var/www/api/symfony/src/Entity/User.php:108:
array (size=1)
  0 =>
    object(App\Entity\Role)[423]
      private 'id' => int 2
      private 'role' => string '['ROLE_ADMIN']' (length=14)
      private 'description' => string 'administrateur' (length=14)
      private 'users' =>
        object(Doctrine\ORM\PersistentCollection)[425]
          private 'snapshot' =>
            array (size=0)
              ...
          private 'owner' =>
            &object(App\Entity\Role)[423]
          private 'association' =>
            array (size=16)
              ...
          private 'em' =>
            object(Doctrine\ORM\EntityManager)[205]
              ...
          private 'backRefFieldName' => string 'roles' (length=5)
          private 'typeClass' =>
            object(Doctrine\ORM\Mapping\ClassMetadata)[262]
              ...
          private 'isDirty' => boolean false
          protected 'collection' =>
            object(Doctrine\Common\Collections\ArrayCollection)[426]
              ...
          protected 'initialized' => boolean false
</code>```

Here is the user list code:

```<code>{% extends '/admin/base_admin.html.twig' %}

{% block style %}
    <style>
        h1#titlelist{
            float: left;
        }
        button#edit {
            float: right;
        }
        button#create{
            float: right;
            margin-left: 15px;
        }
    </style>
{% endblock %}

{% block logout %}
    <a style="color: grey" href="{{ path('security_logout') }}">Deconnexion</a>
{% endblock %}

{% block body %}
    <br /><br />
    <h1 id="titlelist" class="h3 mb-3 font-weight-normal">Liste des utilisateurs</h1>
    {% for message in app.flashes('success') %}
        <div class="alert alert-success">
            {{ message }}
        </div>
    {% endfor %}
    <a href="{{ path('admin_index') }}">
        <button id="create" class="btn btn-lg btn-primary">
            Annuler
        </button>
    </a>
    <a href="{{ path('admin_user_create') }}">
        <button id="create" class="btn btn-lg btn-primary">
            Ajouter
        </button>
    </a>

    <br />
    <br />
    <br />
    <TABLE  class="table table-striped">
        <thead>
        <TR>
            <TH>ID</TH>
            <TH>Utilisateur</TH>
            <TH>Password</TH>
            <TH>Rôles</TH>
            <TH>Actif</TH>
            <TH>Editer</TH>
        </TR>
        </thead>
        <tbody>
        {% for list in user %}
            <TR>
                <TD>{{ list.id }}</TD>
                <TD>{{ list.username }}</TD>
                <TD>{{ list.password }}</TD>
                <TD>
                    {% for role in list.roles %}
                        {{ role.name }},
                    {% endfor %}
                </TD>
                <TD>{{ list.isActive }}</TD>

                <TD>
                    <a href="{{ path('admin_user_edit', {id: list.id}) }}" class="btn btn-primary">Editer</a>
                    <form method="post" action="{{ path('admin_user_delete', {id: list.id}) }}" style="display: inline-block"
                          onsubmit="return confirm('Voulez-vous vraiment supprimer l\'utilisateur ?')">
                        <input type="hidden" name="_method" value="DELETE">
                        <input type="hidden" name="_token" value="{{ csrf_token('delete' ~ list.id) }}">
                        <button class="btn btn-primary">Supprimer</button>
                    </form>
                </TD>
            </TR>
        {% endfor %}
        </tbody>
    </TABLE>
{% endblock %}
</code>```

I would like to retrieve the role store in the role table.

If any of you can enlighten me, thank you in advance.

答:
For those who want to add multiple roles for modules for example</p>

```<code>public function getRoles() : array //Role return
    {
        $role = [];
        $name = [];
        $roles = $this->roles;

        $tab = $roles->toArray();
        dump($tab);
        $longTab = count($tab);

        for ($i = 0; $i < $longTab; $i++){
            $role[] = $roles->get($i)->getRole();
            $name[] = $roles->get($i)->getName();
        }

        $role = [$role, $name];

        if (empty($roles)){
            $role = ['ROLE_USER'];
        }
        return $role;
    }
</code>```

Body:
I have a problem when i want to connect. Let me explain, I have two User and Role entities that are linked to a ManyToMany relationship, so I have a dynamic user_role table. I would like to connect with the user who has the ROLE_ADMIN but the problem is that I cannot read the object so that it reads this role. This shows me this error.

Warning: Illegal offset type in isset or empty

I think the problem comes from the line "$ role = $ this-> roles-> toArray ();" in getRoles.

Here is the code for User.php

class User implements UserInterface, \Serializable
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=180, unique=true)
     */
    private $username;

    /**
     * @var string The hashed password
     * @ORM\Column(type="string")
     */
    private $password;

    /**
     * @ORM\Column(type="boolean", nullable=false, options={"default" : 0})
     */
    private $isActive;

    /**
     * @ORM\Column(type="string", unique=true, length=64)
     */
    private $token;

    /**
     * @ORM\Column(type="datetime")
     */
    private $expiresAt;

    /**
     * @ORM\ManyToMany(targetEntity="Role", inversedBy="users", fetch="LAZY")
     * @ORM\JoinTable(name="user_role",
     *     joinColumns={
     *      @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     *   },
     *   inverseJoinColumns={
     *     @ORM\JoinColumn(name="role_id", referencedColumnName="id")
     *   }
     *  )
     */
    private $role;

    public function __construct()
    {
        //$this->repository = $repository;
        $this->role = new ArrayCollection();
        //$this->roles = new Role();
    }

    /**
     * Add userRoles
     *
     * @param \App\Entity\Role $roles
     * @return User
     */
    public function addRoles(\App\Entity\Role $role)
    {
        $this->role[] = $role;

        return $this;
    }

    /**
     * Remove userRoles
     *
     * @param \App\Entity\Role $roles
     */
    public function removeRoles(\App\Entity\Role $role)
    {
        $this->role->removeElement($role);
    }

    /**
     * Get Role
     */
    public function getRoles() : array //Role return
    {
        //$role = $this->repository->find($this->getId());
        //$role = $role->getName();
        $role = $this->role->toArray();

        //$roles = ['ROLE_ADMIN'];
        //$role = $this->serialize($role);
        var_dump($role);
        //$role = $role[0]['name'];

        if (empty($role)) {
            $role[] = ['ROLE_ADMIN'];
        }
        return array_unique($role);
    }

    public function setRoles($role): self
    {
        //$this->roles = $roles;
        if (is_array($role)) {
            $this->role = $role;
        } else {
            $this->role->clear();
            $this->role->add($role);
        }
        return $this;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    /**
     * A visual identifier that represents this user.
     *
     * @see UserInterface
     */
    public function getUsername(): string
    {
        return (string)$this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getPassword(): string
    {
        return (string)$this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    /**
     * @see UserInterface
     */
    public function getSalt()
    {
        // not needed when using the "bcrypt" algorithm in security.yaml
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }

    public function getIsActive(): ?bool
    {
        return $this->isActive;
    }

    public function setIsActive(bool $isActive): self
    {
        $this->isActive = $isActive;

        return $this;
    }

    public function getToken(): ?string
    {
        return $this->token;
    }

    public function setToken(string $token): self
    {
        $this->token = $token;

        return $this;
    }

    public function getExpiresAt(): ?\DateTimeInterface
    {
        return $this->expiresAt;
    }

    public function setExpiresAt(\DateTimeInterface $expiresAt): self
    {
        $this->expiresAt = $expiresAt;

        return $this;
    }

    public function isExpired(): bool
    {
        return $this->getExpiresAt() <= new \DateTime();
    }

    public function createToken()
    {
        return substr(str_replace(['+', '/'], ['-', '_'], base64_encode(random_bytes(50))), 0, 63);
    }

    /**
     * String representation of object
     * @link https://php.net/manual/en/serializable.serialize.php
     * @return string the string representation of the object or null
     * Transform object to string
     */
    public function serialize()
    {
        return serialize([
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            $this->token,
            $this->expiresAt
        ]);
    }

    /**
     * @param string $serialized
     * Transform string to object
     */
    public function unserialize($serialized)
    {
        list(
            $this->id,
            $this->username,
            $this->password,
            $this->isActive,
            $this->token,
            $this->expiresAt
            ) = unserialize($serialized, ['allowed_classes' => false]);
    }

}

And here is the code for Role.php

class Role implements \Serializable
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $role;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $description;

    /**
     * @ORM\ManyToMany(targetEntity="User", mappedBy="roles")
     */
    private $users;

    public function __construct()
    {
        $this->users = new ArrayCollection();
    }

    public function getUsers()
    {
        return $this->users;
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getRole(): ?string
    {
        return $this->role;
    }

    public function setRole($role)
    {
        $this->role = $role;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(string $description): self
    {
        $this->description = $description;

        return $this;
    }

    /*
    * methods for RoleInterface
    */
    /*public function getRoles()
    {
        return $this->getRole();
    }*/

    /**
     * Add users
     *
     * @param \App\Entity\User $users
     * @return Role
     */
    public function addUser(\App\Entity\User $users)
    {
        $this->users[] = $users;

        return $this;
    }

    /**
     * Remove users
     *
     * @param \App\Entity\User $users
     */
    public function removeUser(App\Entity\User $users)
    {
        $this->users->removeElement($users);
    }

    /**
     * String representation of object
     * @link https://php.net/manual/en/serializable.serialize.php
     * @return string the string representation of the object or null
     * Transform object to string
     */
    public function serialize()
    {
        return serialize([
            $this->id,
            $this->role,
            $this->description
        ]);
    }

    /**
     * @param string $serialized
     * Transform string to object
     */
    public function unserialize($serialized)
    {
        list(
            $this->id,
            $this->role,
            $this->description
            ) = unserialize($serialized, ['allowed_classes' => false]);
    }
}

then in my controller I did a findAll

/**
* @Route("/admin/user", name="admin_user_index")
* @return \Symfony\Component\HttpFoundation\Response
*/
public function listUser(UserRepository $user)
{
return $this->render('admin/security_user/list_user.html.twig', ['user' => $user->findAll()]);
}

var_dump($role)

/var/www/api/symfony/src/Entity/User.php:108:
array (size=1)
  0 =>
    object(App\Entity\Role)[423]
      private 'id' => int 2
      private 'role' => string '['ROLE_ADMIN']' (length=14)
      private 'description' => string 'administrateur' (length=14)
      private 'users' =>
        object(Doctrine\ORM\PersistentCollection)[425]
          private 'snapshot' =>
            array (size=0)
              ...
          private 'owner' =>
            &object(App\Entity\Role)[423]
          private 'association' =>
            array (size=16)
              ...
          private 'em' =>
            object(Doctrine\ORM\EntityManager)[205]
              ...
          private 'backRefFieldName' => string 'roles' (length=5)
          private 'typeClass' =>
            object(Doctrine\ORM\Mapping\ClassMetadata)[262]
              ...
          private 'isDirty' => boolean false
          protected 'collection' =>
            object(Doctrine\Common\Collections\ArrayCollection)[426]
              ...
          protected 'initialized' => boolean false

Here is the user list code:

{% extends '/admin/base_admin.html.twig' %}

{% block style %}

{% endblock %}

{% block logout %}
    Deconnexion
{% endblock %}

{% block body %}

Liste des utilisateurs

    {% for message in app.flashes('success') %}

            {{ message }}

    {% endfor %}

        <button id="create" class="btn btn-lg btn-primary">
            Annuler
        </button>

        <button id="create" class="btn btn-lg btn-primary">
            Ajouter
        </button>

            ID
            Utilisateur
            Password
            Rôles
            Actif
            Editer

        {% for list in user %}

                {{ list.id }}
                {{ list.username }}
                {{ list.password }}

                    {% for role in list.roles %}
                        {{ role.name }},
                    {% endfor %}

                {{ list.isActive }}

                    Editer
                    <form method="post" action="{{ path('admin_user_delete', {id: list.id}) }}" style="display: inline-block"
                          onsubmit="return confirm('Voulez-vous vraiment supprimer l\'utilisateur ?')">
                        <input type="hidden" name="_method" value="DELETE">
                        <input type="hidden" name="_token" value="{{ csrf_token('delete' ~ list.id) }}">
                        <button class="btn btn-primary">Supprimer</button>
                    </form>

        {% endfor %}

{% endblock %}

I would like to retrieve the role store in the role table.

If any of you can enlighten me, thank you in advance.

Body:
For those who want to add multiple roles for modules for example

public function getRoles() : array //Role return
    {
        $role = [];
        $name = [];
        $roles = $this->roles;

        $tab = $roles->toArray();
        dump($tab);
        $longTab = count($tab);

        for ($i = 0; $i < $longTab; $i++){
            $role[] = $roles->get($i)->getRole();
            $name[] = $roles->get($i)->getName();
        }

        $role = [$role, $name];

        if (empty($roles)){
            $role = ['ROLE_USER'];
        }
        return $role;
    }


问:
Making at least One Checkbox mandatory out of the given checkboxes on submit
I have the several check boxes inside of the form group. How can I made this Area of Interest checkbox mandatory on submit? At least the user clicks on one checkbox before submitting. I have used react-bootstrap.

Any help are appreciated.

<Form.Group>
    <Form.Label>Area of Interest</Form.Label>
    <Form.Check
        name="areaOfInterest"
        label="Dedicated Teams"
        id="dt"
        value={"Dedicated Teams" || formInput.areaOfInterest}
        onChange={handleCheck}
    />
    <Form.Check
        name="areaOfInterest"
        label="Cloud Expert Advice & Support"
        id="ceas"
        value="Cloud Expert Advice & Support"
        onChange={handleCheck}
    />
    <Form.Check
        name="areaOfInterest"
        label="Software Development"
        id="sd"
        value="Software Development"
        onChange={handleCheck}
    />
    <Form.Check
        name="areaOfInterest"
        label="Digital Transformation"
        id="dit"
        value="Digital Transformation"
        onChange={handleCheck}
    />
</Form.Group>
```

答: Depends on how you handle state. I assume you are saving the checkbox's state somehow, like an array or object. One way to do this is to make a function to check the checkbox's state. If it's empty you can disable save or either send an error message. </p>


问:
iOS - How To Remove Previously Added Sublayers Of a UIView
I have a custom view which is a subclass of UIView. I added some sublayers to the custom view but now I want remove them.

I tried doing this:

```<code>self.layer.sublayers = nil;
</code>```

But this will remove everything including the initial sublayers of the view.

Is there any way to achieve this? Or do I have to reinitialise a new custom view every time?

Note: App runs in iOS 7 and above.

Thanks!

答:
Here is my solution for removing AVPlayerLayer without keeping a reference to it:

```<code>- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    // Remove player layer when screen gone
    NSUInteger layerIndex = [self.view.layer.sublayers indexOfObjectPassingTest:^BOOL(__kindof CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return [obj isKindOfClass:[AVPlayerLayer class]];
    }];
    if (layerIndex != NSNotFound) {
        AVPlayerLayer *playerLayer = self.view.layer.sublayers[layerIndex];
        [playerLayer removeFromSuperlayer];
    }
}
</code>```

Body:
I have a custom view which is a subclass of UIView. I added some sublayers to the custom view but now I want remove them.

I tried doing this:

self.layer.sublayers = nil;

But this will remove everything including the initial sublayers of the view.

Is there any way to achieve this? Or do I have to reinitialise a new custom view every time?

Note: App runs in iOS 7 and above.

Thanks!

Body:
Here is my solution for removing AVPlayerLayer without keeping a reference to it:

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    // Remove player layer when screen gone
    NSUInteger layerIndex = [self.view.layer.sublayers indexOfObjectPassingTest:^BOOL(__kindof CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        return [obj isKindOfClass:[AVPlayerLayer class]];
    }];
    if (layerIndex != NSNotFound) {
        AVPlayerLayer *playerLayer = self.view.layer.sublayers[layerIndex];
        [playerLayer removeFromSuperlayer];
    }
}


问:
MS SQL Server 2008 How can I know whether table/Stored Procedure is in use or not?
Is there any way to determine if any table is in use or not by any project?
Of course question would be when table is only read-only; otherwise, I could see from
new inserted rows. Same question is for a stored procedure. SQL Server Profiler should probably help for SP, not sure about table.
But I don't want to sit and observe SQL Server Profiler. I wish to have a kind of notification.
So basically, I would like to set up a trigger or something, if table gets hit, read then
it notifies me.

Thanks for your help

答:
Without some form of planning ahead, I believe the answer is "No, you can't determine usage with 100% accurarcy".

If you reviewed the code to identify all reference objects, there could always be something you misread, misinterpreted, or just plain missed. (Edge cases: Maintenance routines, administrator scripts, forgotten legacy code)

If you observed all activity on the database for T period of time, there could always be some process that did not happen to run during that period of time. (Edge cases: annual processes, disaster recovery routines)

An intersection of the above, there might be ad hoc activities performed by users or administrators that are undocumented and/or very infrequently performed

The point is, SQL Server simply cannot know that such actions and activities might occur. You should be able to pick out 90%, 98%, or maybe 99.9% of all database activities, but if you need that 100% assurance that table dbo.LegacyDump is flat-out irrelevant junk, without having been in on the original design and implementation (and having total recall) you just can't get to 100%.

When you get to that point, your best bet is to come up with a risk assessment (how bad might it be if we drop the table), a contingency plan (what to do if it turned out we should not have dropped that table), and documentation (so you or whoever can clearly recall the decisions made when it is found out you killed the system that calculates the C-level annual bonuses.)


问:
I want to make an Android API to keep a screen wake in home screen
I want to make an api that makes the screen awake.
I have tried this way:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

But this is only available when app is running foreground.
If I leave this app, the screen is turn off after a few seconds.
I want somebody to help me with making this api.
Thank you.

答:
you can use wakelock screen to wakeup the device using api

https://developer.android.com/training/scheduling/wakelock#java


问:
Describing properties in swagger example
Try to add multiline example in definition of JSON response in swagger. Need to get structure like

```<code>{
    "result": {
        "urls": {
            "site/index": true,
            "site/create": true,
            "site/update": true,
            "site/delete": true,
            "site/types": true,
            "site/save": false
        }
    }
}
</code>```

but now everything I've got only

```<code>{
  "result": {
    "urls": [
      {
        "site/index": true
      },
      {
        "site/create": true
      },
      {
        "site/update": true
      },
      {
        "site/delete": true
      },
      {
        "site/types": true
      },
      {
        "site/save": false
      }
    ]
  }
}
</code>```

My YAML file looks like

```<code>swagger: "2.0"
info:
  description: "xxx"
  version: 1.2.8
  title: "xxx"
host: "xxx"
basePath: "xxx"
schemes:
- "https"

consumes:
  - application/json
produces:
  - application/json

  /site/check:
    post:
      summary: ""
      description: ""
      parameters:
        - in: body
          name: urls
          required: true
          schema:
            $ref: '#/definitions/CheckAccess'
      responses:
        200:
          description: OK
          schema:
            $ref: '#/definitions/CheckAccessOKResponse'

definitions:
  CheckAccess:
    properties:
      urls:
        type: string
        example:
          - "site/index"
          - "site/create"
          - "site/update"
          - "site/delete"
          - "site/types"
          - "site/save"
    required:
      - urls

  CheckAccessOKResponse:
    properties:
      result:
        type: object
        properties:
          urls:
            type: object
            example:
              - "site/index": true
              - "site/create": true
              - "site/update": true
              - "site/delete": true
              - "site/types": true
              - "site/save": false
</code>```

Strings in example can be different, it's just a block of paths.
How can I fix my example or structure of CheckAccessOKResponse to get the needed view of JSON?
Thank you.

答:
Remove the leading dashes from the example value list. Dashes indicate array items, you don't need that.

Also, result.urls is currently defined as a free-form object, but you probably want a string-to-boolean map instead.

  CheckAccessOKResponse:
    properties:
      result:
        type: object
        properties:
          urls:
            type: object
            additionalProperties:  # <--- this means the object is
              type: boolean        #      a string-to-boolean map
            example:
              "site/index": true   # <--- no leading dashes
              "site/create": true
              "site/update": true
              "site/delete": true
              "site/types": true
              "site/save": false
```

Body:
Try to add multiline example in definition of JSON response in swagger. Need to get structure like

{
    "result": {
        "urls": {
            "site/index": true,
            "site/create": true,
            "site/update": true,
            "site/delete": true,
            "site/types": true,
            "site/save": false
        }
    }
}

but now everything I've got only

{
  "result": {
    "urls": [
      {
        "site/index": true
      },
      {
        "site/create": true
      },
      {
        "site/update": true
      },
      {
        "site/delete": true
      },
      {
        "site/types": true
      },
      {
        "site/save": false
      }
    ]
  }
}

My YAML file looks like

swagger: "2.0"
info:
  description: "xxx"
  version: 1.2.8
  title: "xxx"
host: "xxx"
basePath: "xxx"
schemes:
- "https"

consumes:
  - application/json
produces:
  - application/json

  /site/check:
    post:
      summary: ""
      description: ""
      parameters:
        - in: body
          name: urls
          required: true
          schema:
            $ref: '#/definitions/CheckAccess'
      responses:
        200:
          description: OK
          schema:
            $ref: '#/definitions/CheckAccessOKResponse'

definitions:
  CheckAccess:
    properties:
      urls:
        type: string
        example:
          - "site/index"
          - "site/create"
          - "site/update"
          - "site/delete"
          - "site/types"
          - "site/save"
    required:
      - urls

  CheckAccessOKResponse:
    properties:
      result:
        type: object
        properties:
          urls:
            type: object
            example:
              - "site/index": true
              - "site/create": true
              - "site/update": true
              - "site/delete": true
              - "site/types": true
              - "site/save": false

Strings in example can be different, it's just a block of paths.
How can I fix my example or structure of CheckAccessOKResponse to get the needed view of JSON?
Thank you.


问:
Scalamock : How to specify arbitrary sequence of tuples
I am trying to create a mock for Play's WSClient like this:

  def mockGet[A](url : String, method : String, headers : Seq[(String, String)], timeout : Duration)(
    response: Future[AhcWSResponse]
  ) =
    (mockWsClient
      .url(_ : String)
        .withMethod(_ : String)
        .withHttpHeaders(_: (String, String)*)
        .withRequestTimeout(_ : Duration)
        .stream())
      .expects(url, method, headers, timeout)
      .returning(response)
```

<p>The problem is the <code>withHttpHeaders</code> - this actually takes (String, String)* but when I specify that type as above I get a compiler error like this:</p>

<pre class="lang-scala prettyprint-override"><code>[error]  found   : Seq[(String, String)]
[error]  required: (String, String)
[error]       .withHttpHeaders(_: Seq[(String, String)])
</code>```

What type do I need to specify for this method because (String, String) is not correct. The actual real definition of this method is:

  override def withHttpHeaders(headers: (String, String)*): Self
```

<p><strong><em>UPDATE</em></strong></p>

<p>I tried this after @Mario's suggestion:</p>

<pre class="lang-scala prettyprint-override"><code>  def mockGet[A](url: String, method: String, headers: Seq[(String, String)], timeout: Duration)(
    response: (String, String, Duration) => Future[ws.WSResponse]
  ) =
    (
      (
        xs: Seq[(String, String)]
      ) =>
        mockWsClient
          .url(_: String)
          .withMethod(_: String)
          .withRequestTimeout(_: Duration)
          .withHttpHeaders(xs: _*)
          .stream()
      )
      .expects(headers)
      .returning(response)
</code>```

but this crashes the compiler with:

[error] value x$1

```

答:
The key is to understand how the anonymous function placeholder parameter syntax works. For example, given

```<code>def f(i: Int*) = ???
</code>```

then

```<code>f(_: Int)
</code>```

expands to

```<code>(i: Int) => f(i)
</code>```

Hence try

```<code>def mockGet(headers : Seq[(String, String)) =
  ((xs: Seq[(String, String)]) => mockWsClient.withHttpHeaders(xs: _*)).expects(headers)
</code>```

Here is a simplified example

```<code>trait Zar {
  def f(i: Int*) = i
}

class ScalamockVarargsSpec extends FlatSpec with Matchers with MockFactory {
  "Varargs" should "be mockable" in {
    val zar = mock[Zar]
    ((xs: Seq[Int]) => zar.f(xs: _*)).expects(Seq(1,2))
    zar.f(1,2)
  }
}
</code>```

In your particular case there are multiple anonymous function placeholder parameters, so try expanding them all, for example

```<code>def mockGet(url: String, headers : Seq[(String, String)) =
  ((u: String, xs: Seq[(String, String)]) => mockWsClient.url(u).withHttpHeaders(xs: _*))
    .expects(url, headers)
</code>```

Body:
I am trying to create a mock for Play's WSClient like this:

  def mockGet[A](url : String, method : String, headers : Seq[(String, String)], timeout : Duration)(
    response: Future[AhcWSResponse]
  ) =
    (mockWsClient
      .url(_ : String)
        .withMethod(_ : String)
        .withHttpHeaders(_: (String, String)*)
        .withRequestTimeout(_ : Duration)
        .stream())
      .expects(url, method, headers, timeout)
      .returning(response)

The problem is the withHttpHeaders - this actually takes (String, String)* but when I specify that type as above I get a compiler error like this:

[error]  found   : Seq[(String, String)]
[error]  required: (String, String)
[error]       .withHttpHeaders(_: Seq[(String, String)])

What type do I need to specify for this method because (String, String) is not correct. The actual real definition of this method is:

  override def withHttpHeaders(headers: (String, String)*): Self

UPDATE

I tried this after @Mario's suggestion:

  def mockGet[A](url: String, method: String, headers: Seq[(String, String)], timeout: Duration)(
    response: (String, String, Duration) => Future[ws.WSResponse]
  ) =
    (
      (
        xs: Seq[(String, String)]
      ) =>
        mockWsClient
          .url(_: String)
          .withMethod(_: String)
          .withRequestTimeout(_: Duration)
          .withHttpHeaders(xs: _*)
          .stream()
      )
      .expects(headers)
      .returning(response)

but this crashes the compiler with:

[error] value x$1

Body:
The key is to understand how the anonymous function placeholder parameter syntax works. For example, given

def f(i: Int*) = ???

then

f(_: Int)

expands to

(i: Int) => f(i)

Hence try

def mockGet(headers : Seq[(String, String)) =
  ((xs: Seq[(String, String)]) => mockWsClient.withHttpHeaders(xs: _*)).expects(headers)

Here is a simplified example

trait Zar {
  def f(i: Int*) = i
}

class ScalamockVarargsSpec extends FlatSpec with Matchers with MockFactory {
  "Varargs" should "be mockable" in {
    val zar = mock[Zar]
    ((xs: Seq[Int]) => zar.f(xs: _*)).expects(Seq(1,2))
    zar.f(1,2)
  }
}

In your particular case there are multiple anonymous function placeholder parameters, so try expanding them all, for example

def mockGet(url: String, headers : Seq[(String, String)) =
  ((u: String, xs: Seq[(String, String)]) => mockWsClient.url(u).withHttpHeaders(xs: _*))
    .expects(url, headers)


问:
GET request of an object from server
I'm using vanilla Javascript with Node (HTTP) for server side and XMLHttpRequest for client side.
Not sure how i could send an object that i've read on the server to the client.

For example i've this server code, to read the data and store it on data array to send later to the client:

```<code>            data = []
            fs.readFile("./client.json", function(err, jsonData){
                if(err){
                    throw err;
                }else{
                    data.push(JSON.parse(jsonData));
                }
            });
</code>```

Now i'm kinda lost of how client side would be to GET the data array.
I've tried this but couldn't get any

```<code>let xhttp = new XMLHttpRequest();

    xhttp.open("GET", "http://localhost:3000/data", true);
    xhttp.send(null);
</code>```

I don't want to use Fetch nor Express. using HTTP for learning purpose.

答:
Use URL module to parse request URL  to write logic for individual endpoints.

In your case the endpoint would be /data. Here you can return the data array as response.

Refer URL | Node.js

Title: GET request of an object from server

Body:
I'm using vanilla Javascript with Node (HTTP) for server side and XMLHttpRequest for client side.
Not sure how i could send an object that i've read on the server to the client.

For example i've this server code, to read the data and store it on data array to send later to the client:

            data = []
            fs.readFile("./client.json", function(err, jsonData){
                if(err){
                    throw err;
                }else{
                    data.push(JSON.parse(jsonData));
                }
            });

Now i'm kinda lost of how client side would be to GET the data array.
I've tried this but couldn't get any

let xhttp = new XMLHttpRequest();

    xhttp.open("GET", "http://localhost:3000/data", true);
    xhttp.send(null);

I don't want to use Fetch nor Express. using HTTP for learning purpose.


问:
How can I return in a ObsevableCollection<T> using C# Linq, all items if no one is selected or just selected items if at least one is selected?
I'm trying to get items in C# in an ObservableCollection<MyClassSelectable> using Linq and Lambda in the following cases :

Returns All items if no one is selected

Or

Returns just selected items if at least one is selected.

MyClassSelectable has a property named Selected of bool type.

Is it possible to do it, in only one Linq query line ?

Thank you.

答:
To answer @Pavel Anikhouski and updating @GregaMohorko answer, the below code does the job rightly.

```<code>using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace Test
{
    public class MyClassSelectable
    {
        public bool Selected { get; set; }
        public string Name { get; set; } = "";
    }

    public class Class1
    {

        public ObservableCollection<MyClassSelectable> myClassesSelectable = new ObservableCollection<MyClassSelectable>();

        public Class1()
        {
            myClassesSelectable.Add(new MyClassSelectable { Selected = true, Name = "Item 1" });
            myClassesSelectable.Add(new MyClassSelectable { Selected = true, Name = "Item 2" });
            myClassesSelectable.Add(new MyClassSelectable { Selected = false, Name = "Item 3" });
            myClassesSelectable.Add(new MyClassSelectable { Selected = false, Name = "Item 4" });

            IEnumerable<MyClassSelectable> myCollection = myClassesSelectable
                            // group by the Selected property
                            .GroupBy(mcs => mcs.Selected)
                            // order (=> true first, false second)
                            .OrderByDescending(g => g.Key)
                            // return the first OR an empty collection if there are no items
                            .FirstOrDefault()
                            ?.ToList();
        }

    }
}
</code>```

If 2 items are Selected, it returns a list of the two items.

If no item are Selected, it returns all 4 items.

Thank you very much for your job @GregaMohorko.

Body:
To answer @Pavel Anikhouski and updating @GregaMohorko answer, the below code does the job rightly.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;

namespace Test
{
    public class MyClassSelectable
    {
        public bool Selected { get; set; }
        public string Name { get; set; } = "";
    }

    public class Class1
    {

        public ObservableCollection<MyClassSelectable> myClassesSelectable = new ObservableCollection<MyClassSelectable>();

        public Class1()
        {
            myClassesSelectable.Add(new MyClassSelectable { Selected = true, Name = "Item 1" });
            myClassesSelectable.Add(new MyClassSelectable { Selected = true, Name = "Item 2" });
            myClassesSelectable.Add(new MyClassSelectable { Selected = false, Name = "Item 3" });
            myClassesSelectable.Add(new MyClassSelectable { Selected = false, Name = "Item 4" });

            IEnumerable<MyClassSelectable> myCollection = myClassesSelectable
                            // group by the Selected property
                            .GroupBy(mcs => mcs.Selected)
                            // order (=> true first, false second)
                            .OrderByDescending(g => g.Key)
                            // return the first OR an empty collection if there are no items
                            .FirstOrDefault()
                            ?.ToList();
        }

    }
}

If 2 items are Selected, it returns a list of the two items.

If no item are Selected, it returns all 4 items.

Thank you very much for your job @GregaMohorko.


问:
Android, how to toast my simplexml class?
Sorry, I'm quite new in Android...
I have an activity which creates an object instance of my class:

```<code>file MyActivity.java:

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class MyActivity extends Activity {
    Artworks myArtworks;

    ...
    myArtworks = serial.read(Artworks.class, artworksXmlFile);
    ...
}
--------------------------------------------------------------

file Artworks.java:

import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;

@Element
public class Artworks {
    @ElementList(entry = "artwork", inline = true)
    private List<Artwork> list;
    ...
}
--------------------------------------------------------------

file Artwork.java:
public class Artwork {
    // how to use here Toast.makeText(..., text, Toast.LENGTH_SHORT).show() ???
}
--------------------------------------------------------------
</code>```

How do I use the Toast class (or any UI class) in my class Artwork, which I do never instantiate directly, but it's indirectly created by a call to serial.read(Artworks.class)?
How do I do it, exactly?

Thanks in advance!

答: You can use a "static" helper class to maintain a static reference to your Activity's context.  So, before you deserialize your Artwork class, call UtilClass.setContext(getApplicationContext());. Then, within your Artwork class, you can retrieve that context and then do something like Toast.makeText(UtilClass.getContext(), "text", Toast.LENGTH_LONG).show();.

Body:
Sorry, I'm quite new in Android...
I have an activity which creates an object instance of my class:

file MyActivity.java:

import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class MyActivity extends Activity {
    Artworks myArtworks;

    ...
    myArtworks = serial.read(Artworks.class, artworksXmlFile);
    ...
}
--------------------------------------------------------------

file Artworks.java:

import org.simpleframework.xml.Element;
import org.simpleframework.xml.ElementList;

@Element
public class Artworks {
    @ElementList(entry = "artwork", inline = true)
    private List<Artwork> list;
    ...
}
--------------------------------------------------------------

file Artwork.java:
public class Artwork {
    // how to use here Toast.makeText(..., text, Toast.LENGTH_SHORT).show() ???
}
--------------------------------------------------------------

How do I use the Toast class (or any UI class) in my class Artwork, which I do never instantiate directly, but it's indirectly created by a call to serial.read(Artworks.class)?
How do I do it, exactly?

Thanks in advance!


问:
vba code to copy a column from sap window and paste the values in excel sheet
i have a code that do some SAP transactions on the sap then select a whole column from a grid on a sap i am successful till here but i want to copy the column and past it in an excel sheet but i cant do that. i tried to open the context menu to choose copy text but it doesn't work i tried to send CTRL+C stroke from keyboard but also failed. if someone can help me with that i will be very grateful. here is my code:</p>

```<code>Sub lolo()

If Not IsObject(App) Then
    Set SapGuiAuto = GetObject("SAPGUI")
    Set App = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
     Set Connection = App.Children(0)
End If
If Not IsObject(session) Then
    Set session = Connection.Children(0)
End If
If IsObject(WScript) Then
    WScript.ConnectObject session, "on"
    WScript.ConnectObject App, "on"
End If
session.findById("wnd[0]").maximize
session.findById("wnd[0]/usr/btn%_EQUNR_%_APP_%-VALU_PUSH").press
session.findById("wnd[1]/tbar[0]/btn[24]").press
session.findById("wnd[1]/tbar[0]/btn[8]").press
session.findById("wnd[0]/usr/txtSELCOUNT").Text = "1"
session.findById("wnd[0]/usr/txtSELCOUNT").SetFocus
session.findById("wnd[0]/usr/txtSELCOUNT").caretPosition = 14
session.findById("wnd[0]/tbar[1]/btn[8]").press
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").setCurrentCell -1, "PTTXT"
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").selectColumn "PTTXT"
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").contextMenu
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").selectContextMenuItem "&FILTER"
session.findById("wnd[1]").sendVKey 4
session.findById("wnd[2]/usr/lbl[1,23]").SetFocus
session.findById("wnd[2]/usr/lbl[1,23]").caretPosition = 2
session.findById("wnd[2]").sendVKey 2
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").setCurrentCell -1, "CNTRC"
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").selectColumn "CNTRC"
Application.Wait (Now + TimeValue("0:00:03"))
SendKeys "^C"
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").contextMenu

End Sub
</code>```

答:
I had the same problem, depending on the transaction I either got

```<code>session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").contextMenu
session.findById("wnd[1]/tbar[0]/btn[0]").press
</code>```

or

```<code>session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").contextMenu
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").selectContextMenuItemBytext "Copy Text"
</code>```

which both didn't copy the column.

What solved my predicament was this handy line:

```<code>session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").SelectContextMenuItemByPosition "0"
</code>```

Body:
i have a code that do some SAP transactions on the sap then select a whole column from a grid on a sap i am successful till here but i want to copy the column and past it in an excel sheet but i cant do that. i tried to open the context menu to choose copy text but it doesn't work i tried to send CTRL+C stroke from keyboard but also failed. if someone can help me with that i will be very grateful. here is my code:

Sub lolo()

If Not IsObject(App) Then
    Set SapGuiAuto = GetObject("SAPGUI")
    Set App = SapGuiAuto.GetScriptingEngine
End If
If Not IsObject(Connection) Then
     Set Connection = App.Children(0)
End If
If Not IsObject(session) Then
    Set session = Connection.Children(0)
End If
If IsObject(WScript) Then
    WScript.ConnectObject session, "on"
    WScript.ConnectObject App, "on"
End If
session.findById("wnd[0]").maximize
session.findById("wnd[0]/usr/btn%_EQUNR_%_APP_%-VALU_PUSH").press
session.findById("wnd[1]/tbar[0]/btn[24]").press
session.findById("wnd[1]/tbar[0]/btn[8]").press
session.findById("wnd[0]/usr/txtSELCOUNT").Text = "1"
session.findById("wnd[0]/usr/txtSELCOUNT").SetFocus
session.findById("wnd[0]/usr/txtSELCOUNT").caretPosition = 14
session.findById("wnd[0]/tbar[1]/btn[8]").press
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").setCurrentCell -1, "PTTXT"
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").selectColumn "PTTXT"
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").contextMenu
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").selectContextMenuItem "&FILTER"
session.findById("wnd[1]").sendVKey 4
session.findById("wnd[2]/usr/lbl[1,23]").SetFocus
session.findById("wnd[2]/usr/lbl[1,23]").caretPosition = 2
session.findById("wnd[2]").sendVKey 2
session.findById("wnd[1]/tbar[0]/btn[0]").press
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").setCurrentCell -1, "CNTRC"
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").selectColumn "CNTRC"
Application.Wait (Now + TimeValue("0:00:03"))
SendKeys "^C"
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").contextMenu

End Sub

Body:
I had the same problem, depending on the transaction I either got

session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").contextMenu
session.findById("wnd[1]/tbar[0]/btn[0]").press

or

session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").contextMenu
session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").selectContextMenuItemBytext "Copy Text"

which both didn't copy the column.

What solved my predicament was this handy line:

session.findById("wnd[0]/usr/cntlGRID1/shellcont/shell").SelectContextMenuItemByPosition "0"


问:
"Task failed because AXImp.exe was not found" when using MSBuild 12 to build a MVC 4.0 project
I am trying to set up a build server using CruiseControl.Net and MSBuild. However, it's failing with the error:

```<code> "C:\Builds\PremiumStore\checkout\PremiumStore.sln" (default target) (1) ->
    "C:\Builds\PremiumStore\checkout\Web\PremiumStoreWeb.csproj" (default target) (37) ->
    (ResolveComReferences target) ->
    C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets(2151,5):
    error MSB3091: Task failed because "AxImp.exe" was not found, or the correct Microsoft
    Windows SDK is not installed.
 The task is looking for "AxImp.exe" in the "bin" subdirectory beneath the location specified in the InstallationFolder value of the registry key `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.1A\WinSDK-  NetFx40Tools-x86.`

 You may be able to solve the problem by doing one of the following:

 1. Install the Microsoft Windows SDK.

 2. Install Visual Studio

 3. Manually set

    the above registry key to the correct location.  4) Pass the correct location into the
    "ToolPath" parameter of the task.
    [C:\Builds\PremiumStore\checkout\Web\PremiumStoreWeb.csproj]
</code>```

The same thing builds fine on my own machine, just not on the server.

I've tried searching all over the Internet for a solution but is unable to find one. If possible, I'd prefer not to have to install Visual Studio on the build server. It's kind of overkill to install an entire IDE just to do command line builds. I've installed the Microsoft Build Tools 2013 on that server but it does not seem to help.

I've tried to put in the path into the registry as suggested by the error message, but that didn't work either. I've also checked the path indicated in the registry and the aximp.exe is indeed present, but in a subfolder called "NetFx 4.5.1 Tools". However, copying the files from here one level up to the "bin" parent folder does not appear to help either.

If it helps, my build server runs on Windows Server 2012.

Thanks in advance.

答:
I ended up using the following C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\MSBuild\Current\Bin\msbuild.

I think the solution is to look for the msbuild inside your visual studio install.
This is obviously only if you have visual studio installed, if you have a clean build server this is not good.

Body:
I am trying to set up a build server using CruiseControl.Net and MSBuild. However, it's failing with the error:

 "C:\Builds\PremiumStore\checkout\PremiumStore.sln" (default target) (1) ->
    "C:\Builds\PremiumStore\checkout\Web\PremiumStoreWeb.csproj" (default target) (37) ->
    (ResolveComReferences target) ->
    C:\Program Files (x86)\MSBuild\12.0\bin\Microsoft.Common.CurrentVersion.targets(2151,5):
    error MSB3091: Task failed because "AxImp.exe" was not found, or the correct Microsoft
    Windows SDK is not installed.
 The task is looking for "AxImp.exe" in the "bin" subdirectory beneath the location specified in the InstallationFolder value of the registry key `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.1A\WinSDK-  NetFx40Tools-x86.`

 You may be able to solve the problem by doing one of the following:

 1. Install the Microsoft Windows SDK.

 2. Install Visual Studio

 3. Manually set

    the above registry key to the correct location.  4) Pass the correct location into the
    "ToolPath" parameter of the task.
    [C:\Builds\PremiumStore\checkout\Web\PremiumStoreWeb.csproj]

The same thing builds fine on my own machine, just not on the server.

I've tried searching all over the Internet for a solution but is unable to find one. If possible, I'd prefer not to have to install Visual Studio on the build server. It's kind of overkill to install an entire IDE just to do command line builds. I've installed the Microsoft Build Tools 2013 on that server but it does not seem to help.

I've tried to put in the path into the registry as suggested by the error message, but that didn't work either. I've also checked the path indicated in the registry and the aximp.exe is indeed present, but in a subfolder called "NetFx 4.5.1 Tools". However, copying the files from here one level up to the "bin" parent folder does not appear to help either.

If it helps, my build server runs on Windows Server 2012.

Thanks in advance.


问:
React. How to pass an arg to a function called by an onClick without autotriggering it
I have this piece of code.
Where the problem I am facing is that  is missing a prop which I want to be an id, obtained inside the map function.
Since I am unable to find a way to send the id to the component outside map, I figured I would do this:

This is my render function

```<code>render() {
    var users = this.state.userList;

    const Table = Reactable.Table,
          Td = Reactable.Td,
          Tr = Reactable.Tr;

    if (users.length === 0) {
        return <p>loading</p>
    }

    return (

        <div class="maincontainer">
            <div className="content-landing">

                <Table
                     className="table"
                     filterable={['Email']}
                     itemsPerPage={8}
                     currentPage={0}
                     sortable={true}
                >
                    {users.map((row) => {
                        return (

                            <Tr className={row.className}>
                                <Td column="Email">{row.email}</Td>
                                <Td column="Edit" ><FontAwesomeIcon className="editIcon" onClick={this.showModal(row.id)} icon={faEdit} /></Td> //----THIS.SHOWMODAL IS BEING AUTOEXECUTED WITHOUT ACCOUNTING FOR THE CLICKING

                            </Tr>

                        )
                    })}
                </Table>
                 <EditUserModal show={this.state.showModal} close={this.closeModal} row={this.state.rowId}/> //---I WANT THIS TO RECEIVE A row.id FROM THE ABOVE MAP

            </div>
        </div>

    )
}
</code>```

I have written a couple comments in the parts where I want to make the changes.
I also thought about putting <EditUserModal> , inside the  , but since its an external npm module it crashes, it only admits text.

So my solution was, to pass the row.id to the showModal function, and try to set is a state from there.

```<code>showModal(rowId) {
    // console.log("showmodal state before any click")
    // console.log(this.state.showModal)
    console.log("triggered show modal")
    console.log(rowId)
    this.setState({
        showModal: true,
        rowId: rowId
    }, () => {
        // console.log("clicked show modal")
        // console.log(this.state.showModal)
    });

}
</code>```

I think it should work, but since the function has a () , it auto executes without waiting for any click, making my app to crash.

答:
You can use a callBack function in the onClick like this:

```<code>onClick={()=> this.showModal(row.id)}
</code>```

Or you can define the showModal function like this:

```<code>showModal = (rowId) => () => {
    ...
}
</code>```

and onClick={this.showModal(row.id)}

For people who does not understand arrow functions, the above solution is similar to this:

```<code>function showModal(rowId) {
    return function () {
        ...
    }
}
</code>```

The showModal function returns another function that will be triggered in the onClick event.

Body:
I have this piece of code.
Where the problem I am facing is that  is missing a prop which I want to be an id, obtained inside the map function.
Since I am unable to find a way to send the id to the component outside map, I figured I would do this:

This is my render function

render() {
    var users = this.state.userList;

    const Table = Reactable.Table,
          Td = Reactable.Td,
          Tr = Reactable.Tr;

    if (users.length === 0) {
        return
loading

    }

    return (

                    {users.map((row) => {
                        return (

                                {row.email}
                                <FontAwesomeIcon className="editIcon" onClick={this.showModal(row.id)} icon={faEdit} />	 //----THIS.SHOWMODAL IS BEING AUTOEXECUTED WITHOUT ACCOUNTING FOR THE CLICKING

                        )
                    })}

                 <EditUserModal show={this.state.showModal} close={this.closeModal} row={this.state.rowId}/> //---I WANT THIS TO RECEIVE A row.id FROM THE ABOVE MAP

    )
}

I have written a couple comments in the parts where I want to make the changes.
I also thought about putting <EditUserModal> , inside the  , but since its an external npm module it crashes, it only admits text.

So my solution was, to pass the row.id to the showModal function, and try to set is a state from there.

showModal(rowId) {
    // console.log("showmodal state before any click")
    // console.log(this.state.showModal)
    console.log("triggered show modal")
    console.log(rowId)
    this.setState({
        showModal: true,
        rowId: rowId
    }, () => {
        // console.log("clicked show modal")
        // console.log(this.state.showModal)
    });

}

I think it should work, but since the function has a () , it auto executes without waiting for any click, making my app to crash.

Body:
You can use a callBack function in the onClick like this:

onClick={()=> this.showModal(row.id)}

Or you can define the showModal function like this:

showModal = (rowId) => () => {
    ...
}

and onClick={this.showModal(row.id)}

For people who does not understand arrow functions, the above solution is similar to this:

function showModal(rowId) {
    return function () {
        ...
    }
}

The showModal function returns another function that will be triggered in the onClick event.


问:
UIImageView is not scrolling inside a scrollView
I am creating a scrollview with a page control. I have a scrollview added to my viewcontroller and inside the scrollview there is a UIImageView. But for some reason I cannot scroll it to the left or right side. Can anyone help me out to fix this problem?

My Code:

```<code>    var tutorialImages: [String] = ["1", "2", "3"]
var frame = CGRect.zero

func pageControll() {
    pageControllTutorial.numberOfPages = tutorialImages.count

    for i in 0..<tutorialImages.count {

        imageViewTutorial.frame = frame
        imageViewTutorial.image = UIImage(named: tutorialImages[i])
        scrollViewTutorial.addSubview(imageViewTutorial)
    }

    scrollViewTutorial.contentSize = CGSize(width: imageViewTutorial.frame.size.width * CGFloat(tutorialImages.count), height: imageViewTutorial.frame.size.height)

    scrollViewTutorial.delegate = self
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    var pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width
    pageControllTutorial.currentPage = Int(pageNumber)
}
</code>```

答:
The frame of each UIImageView is being set to CGRect.zero so they all have a 0 height and width, which means your scroll views contentSize is also 0x0. As far as the scroll view is concerned, there's nothing to scroll here.

Do this instead:

```<code>let image = UIImage(named: tutorialImages[i])
imageViewTutorial.frame = CGRect(x: widthSoFar, y: 0, width: image.width, height: image.height)
imageViewTutorial.image = image
scrollViewTutorial.addSubview(imageViewTutorial)
widthSoFar += image.size.width
</code>```

Initialize widthSoFar outside the for loop to 0.

Body:
I am creating a scrollview with a page control. I have a scrollview added to my viewcontroller and inside the scrollview there is a UIImageView. But for some reason I cannot scroll it to the left or right side. Can anyone help me out to fix this problem?

My Code:

    var tutorialImages: [String] = ["1", "2", "3"]
var frame = CGRect.zero

func pageControll() {
    pageControllTutorial.numberOfPages = tutorialImages.count

    for i in 0..<tutorialImages.count {

        imageViewTutorial.frame = frame
        imageViewTutorial.image = UIImage(named: tutorialImages[i])
        scrollViewTutorial.addSubview(imageViewTutorial)
    }

    scrollViewTutorial.contentSize = CGSize(width: imageViewTutorial.frame.size.width * CGFloat(tutorialImages.count), height: imageViewTutorial.frame.size.height)

    scrollViewTutorial.delegate = self
}

func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
    var pageNumber = scrollView.contentOffset.x / scrollView.frame.size.width
    pageControllTutorial.currentPage = Int(pageNumber)
}

Body:
The frame of each UIImageView is being set to CGRect.zero so they all have a 0 height and width, which means your scroll views contentSize is also 0x0. As far as the scroll view is concerned, there's nothing to scroll here.

Do this instead:

let image = UIImage(named: tutorialImages[i])
imageViewTutorial.frame = CGRect(x: widthSoFar, y: 0, width: image.width, height: image.height)
imageViewTutorial.image = image
scrollViewTutorial.addSubview(imageViewTutorial)
widthSoFar += image.size.width

Initialize widthSoFar outside the for loop to 0.


问:
How to socialize GWT application?
I am developing a GWT application that displays services provided by a company and I must allow users to share links of services in social networks like Facebook, LinkedIn and Twitter.
Have you any idea how to do such a thing?
Any help is appreciated
Thank you in advance for your help :)

Edit

i have tried AddThis but nothing was displayed
there is the code :

```<code>    HTML socialNetworkLink = new HTML(
            "<div class=\"addthis_toolbox addthis_default_style addthis_32x32_style\">"
                    + "<a class=\"addthis_button_preferred_1\"></a>"
                    + "<a class=\"addthis_button_preferred_2\"></a>"
                    + "<a class=\"addthis_button_preferred_3\"></a>"
                    + "<a class=\"addthis_button_preferred_4\"></a>"
                    + "<a class=\"addthis_button_compact\"></a>"
                    + "<a class=\"addthis_counter addthis_bubble_style\"></a>"
                    + "</div>"
                    + "<script type=\"text/javascript\">var addthis_config = {\"data_track_clickback\":true};</script>"
                    + "<script type=\"text/javascript\" src=\"http://s7.addthis.com/js/250/addthis_widget.js#pubid=ra-4dd380ca4d8393c9\"></script>");
    sharePanel.add(socialNetworkLink);
</code>```

答:
You can use content sharing tools like addthis.com.

EDITED: or sharethis.com

Title: How to socialize GWT application?

Body:
I am developing a GWT application that displays services provided by a company and I must allow users to share links of services in social networks like Facebook, LinkedIn and Twitter.
Have you any idea how to do such a thing?
Any help is appreciated
Thank you in advance for your help :)

Edit

i have tried AddThis but nothing was displayed
there is the code :

    HTML socialNetworkLink = new HTML(
            "
"
                    + ""
                    + ""
                    + ""
                    + ""
                    + ""
                    + ""
                    + "
"
                    + ""
                    + "");
    sharePanel.add(socialNetworkLink);