问:
Find style properties of element that I'm creating dynamically
If I have a CSS style:

.myClass {
    width: 1234px;
}
```

<p>And an element that I add dynamically with JS thus:</p>

<pre class="lang-js prettyprint-override"><code>document.onload = function(){
    myParent = document.getElementById("parent");
    let myNewElmt = document.createElement("div");
    myNewElmt.className = "myClass";
    myParent.appendChild(MyNewElmt);
    console.log(myNewElmt.style.width);//expect "1234px" returns ""
}
</code>```

I can't access the style properties. It renders fine, and if I subsequently look at myNewElmt.style.width, say in a document.onmousedown function it works, but not when it's created.

How do I access css styles of a dynamically created element, at the time that it is created?

答:
You can set an attribute to your element

yourElement.setAttribute("class", "nameClass");

or classList()

Body:
If I have a CSS style:

.myClass {
    width: 1234px;
}

And an element that I add dynamically with JS thus:

document.onload = function(){
    myParent = document.getElementById("parent");
    let myNewElmt = document.createElement("div");
    myNewElmt.className = "myClass";
    myParent.appendChild(MyNewElmt);
    console.log(myNewElmt.style.width);//expect "1234px" returns ""
}

I can't access the style properties. It renders fine, and if I subsequently look at myNewElmt.style.width, say in a document.onmousedown function it works, but not when it's created.

How do I access css styles of a dynamically created element, at the time that it is created?


来源: stackexchange

问:
How to convert List<NameValuePair> into a List<Map.Entry<String, String>>?
I'm capturing parameters from a request url using com.apache.http.NameValuePair which basically store those params in a List<NameValuePair>. To do certain checks and verifications on those params, I need to convert that list into a List<Map.Entry<String, String>>. Is there a way to do this conversion?

something like this:

http://127.0.0.1:9898/v3/{project_id}/eip/publicips?fields=id&fields=owner

from How to convert List<NameValuePair> into a hashMap<String, String>?

```<code>Map<String, String> mapped = list.stream().collect(
        Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));
</code>```

It is not work for me. because there are many fields key.

答:
Probably you've messed something else that's not included in the code excerpt. I've tried to reproduce your case and it works in my setup.</p>

```<code>
public class Main {

    public static void main(String[] args) {
        List<NameValuePair> list = new ArrayList<>();
        MyNameValuePair myNameValuePair = new MyNameValuePair();
        myNameValuePair.setKvKey("i");
        list.add(myNameValuePair);
        myNameValuePair = new MyNameValuePair();
        myNameValuePair.setKvKey("j");
        list.add(myNameValuePair);
        myNameValuePair = new MyNameValuePair();
        myNameValuePair.setKvKey("k");
        list.add(myNameValuePair);
        Map<String, String> mapped = new HashMap<>();
        mapped = list.stream().collect(
                Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));

        System.out.println(mapped);
    }
}

class MyNameValuePair implements NameValuePair {
    private String kvKey;
    public void setKvKey(String kvKey){
        this.kvKey = kvKey;
    }

    @Override
    public String getName() {
        return kvKey;
    }

    @Override
    public String getValue() {
        return "val";
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm capturing parameters from a request url using com.apache.http.NameValuePair which basically store those params in a List<NameValuePair>. To do certain checks and verifications on those params, I need to convert that list into a List<Map.Entry<String, String>>. Is there a way to do this conversion?

something like this:

http://127.0.0.1:9898/v3/{project_id}/eip/publicips?fields=id&fields=owner

from How to convert List<NameValuePair> into a hashMap<String, String>?

Map<String, String> mapped = list.stream().collect(
        Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));

It is not work for me. because there are many fields key.

Body:
Probably you've messed something else that's not included in the code excerpt. I've tried to reproduce your case and it works in my setup.

public class Main {

    public static void main(String[] args) {
        List<NameValuePair> list = new ArrayList<>();
        MyNameValuePair myNameValuePair = new MyNameValuePair();
        myNameValuePair.setKvKey("i");
        list.add(myNameValuePair);
        myNameValuePair = new MyNameValuePair();
        myNameValuePair.setKvKey("j");
        list.add(myNameValuePair);
        myNameValuePair = new MyNameValuePair();
        myNameValuePair.setKvKey("k");
        list.add(myNameValuePair);
        Map<String, String> mapped = new HashMap<>();
        mapped = list.stream().collect(
                Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));

        System.out.println(mapped);
    }
}

class MyNameValuePair implements NameValuePair {
    private String kvKey;
    public void setKvKey(String kvKey){
        this.kvKey = kvKey;
    }

    @Override
    public String getName() {
        return kvKey;
    }

    @Override
    public String getValue() {
        return "val";
    }
}


问:
Making an Image widget disabled / grayed out
I have a bunch of Image widgets which when in a disabled state, should look grayed out.

Is there a way to alter an existing image make it look disabled / grayed out?

I want to avoid having both an enabled image asset and a disabled image asset increasing the overall APK size instead of having the single asset.

答:
According flutter documentation of ColorFiltered you can use ColorFilter.matrix link like this:

```<code>const ColorFilter greyscale = ColorFilter.matrix(<double>[
  0.2126, 0.7152, 0.0722, 0, 0,
  0.2126, 0.7152, 0.0722, 0, 0,
  0.2126, 0.7152, 0.0722, 0, 0,
  0,      0,      0,      1, 0,
]);

ColorFiltered(
  colorFilter: greyscale,
  child: child,
);
</code>```

In this case ColorFilter will ignore transparent areas of your images.

Body:
According flutter documentation of ColorFiltered you can use ColorFilter.matrix link like this:

const ColorFilter greyscale = ColorFilter.matrix(<double>[
  0.2126, 0.7152, 0.0722, 0, 0,
  0.2126, 0.7152, 0.0722, 0, 0,
  0.2126, 0.7152, 0.0722, 0, 0,
  0,      0,      0,      1, 0,
]);

ColorFiltered(
  colorFilter: greyscale,
  child: child,
);

In this case ColorFilter will ignore transparent areas of your images.


问:
Is there a way in Kotlin Retrofit that works equivalent as OnPreExecute of Kotlin AsyncTask?
I have a MainActivity.ktthat call service provided by aNetworkConfig.kt class (I'm quite a beginner in Android Development).

MainActivity.kt

```<code>class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        NetworkConfig().getService()
            .getUsers()
            .enqueue(object : Callback<List<UserDataClassItem>> {

                override fun onFailure(call: Call<List<UserDataClassItem>>, t: Throwable) {
                    Toast.makeText(this@MainActivity, "No Connection. Check your Connectivity", Toast.LENGTH_SHORT).show()
                }

                override fun onResponse(
                    call: Call<List<UserDataClassItem>>,
                    response: Response<List<UserDataClassItem>>
                ) {
                    rvUser.adapter = UserAdapter(response.body())
                }
            })
    }
}
</code>```

NetworkConfig.kt

```<code>class NetworkConfig {
    // set interceptor
    private fun getInterceptor() : OkHttpClient {
        val logging = HttpLoggingInterceptor()
        logging.level = HttpLoggingInterceptor.Level.BODY

        return OkHttpClient.Builder()
            .addInterceptor(logging)
            .build()
    }

    private fun getRetrofit() : Retrofit {
        return Retrofit.Builder()
            .baseUrl("https://jsonplaceholder.typicode.com/")
            .client(getInterceptor())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    fun getService() = getRetrofit().create(Users::class.java)
}

//Access https://jsonplaceholder.typicode.com/users
interface Users {
    @GET("users")
    fun getUsers(): Call<List<UserDataClassItem>>
}
</code>```

What I want to know is that is there a way in Retrofit to execute a task when the App is fetching the service on background (Such as showing a progressBar) ?
Something that works equivalent as AsyncTask's onPreExecute function.

If there's anything unclear, let me know.

答:
Before your network call you can set your ProgressBar visibility to View.VISIBLE, and then in your Retrofit's onResponse() and onFailure(), set its visibility to View.GONE.

Like this:

```<code>progressbar.visibility = View.VISIBLE
NetworkConfig().getService()
.getUsers()
.enqueue(object : Callback<List<UserDataClassItem>> {

    override fun onFailure(call: Call<List<UserDataClassItem>>, t: Throwable) {
        progressbar.visibility = View.GONE
        Toast.makeText(this@MainActivity, "No Connection. Check your Connectivity", Toast.LENGTH_SHORT).show()
    }

    override fun onResponse(
        call: Call<List<UserDataClassItem>>,
        response: Response<List<UserDataClassItem>>
    ) {
        progressbar.visibility = View.GONE
        rvUser.adapter = UserAdapter(response.body())
    }
})
</code>```

Body:
I have a MainActivity.ktthat call service provided by aNetworkConfig.kt class (I'm quite a beginner in Android Development).

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        NetworkConfig().getService()
            .getUsers()
            .enqueue(object : Callback<List<UserDataClassItem>> {

                override fun onFailure(call: Call<List<UserDataClassItem>>, t: Throwable) {
                    Toast.makeText(this@MainActivity, "No Connection. Check your Connectivity", Toast.LENGTH_SHORT).show()
                }

                override fun onResponse(
                    call: Call<List<UserDataClassItem>>,
                    response: Response<List<UserDataClassItem>>
                ) {
                    rvUser.adapter = UserAdapter(response.body())
                }
            })
    }
}

NetworkConfig.kt

class NetworkConfig {
    // set interceptor
    private fun getInterceptor() : OkHttpClient {
        val logging = HttpLoggingInterceptor()
        logging.level = HttpLoggingInterceptor.Level.BODY

        return OkHttpClient.Builder()
            .addInterceptor(logging)
            .build()
    }

    private fun getRetrofit() : Retrofit {
        return Retrofit.Builder()
            .baseUrl("https://jsonplaceholder.typicode.com/")
            .client(getInterceptor())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    fun getService() = getRetrofit().create(Users::class.java)
}

//Access https://jsonplaceholder.typicode.com/users
interface Users {
    @GET("users")
    fun getUsers(): Call<List<UserDataClassItem>>
}

What I want to know is that is there a way in Retrofit to execute a task when the App is fetching the service on background (Such as showing a progressBar) ?
Something that works equivalent as AsyncTask's onPreExecute function.

If there's anything unclear, let me know.

Body:
Before your network call you can set your ProgressBar visibility to View.VISIBLE, and then in your Retrofit's onResponse() and onFailure(), set its visibility to View.GONE.

Like this:

progressbar.visibility = View.VISIBLE
NetworkConfig().getService()
.getUsers()
.enqueue(object : Callback<List<UserDataClassItem>> {

    override fun onFailure(call: Call<List<UserDataClassItem>>, t: Throwable) {
        progressbar.visibility = View.GONE
        Toast.makeText(this@MainActivity, "No Connection. Check your Connectivity", Toast.LENGTH_SHORT).show()
    }

    override fun onResponse(
        call: Call<List<UserDataClassItem>>,
        response: Response<List<UserDataClassItem>>
    ) {
        progressbar.visibility = View.GONE
        rvUser.adapter = UserAdapter(response.body())
    }
})


问:
How do I integrate Oracle container registry with Azure DevOps?
I am having trouble creating a connection between Azure DevOps and Oracle Container Registry.

Has anyone experience how I get the fields requested by azure devops in oracle cloud?

The requested fields are:

Docker registry

Docker id

Docker password

Docker Service Connection

答:
According to this document from Azure DevOps Service:

```<code>Docker Registry  Required.   The URL of the Docker registry.
Docker ID        Required.   The identifier of the Docker account user.
Password         Required.   The password for the account user identified above.
Email            Optional.   An email address to receive notifications.
</code>```

And here's one document from Oracle Cloud: Managing Docker Registry Definitions
.

In my opinion(I don't purchase the Oracle account and can't test it for you :-(), you should enter your Docker Registry in Oracle for Docker Registry in Service Connection, and User Name for Docker ID, your password in Oracle for Password, Your email in Oracle page for Email in service connection.

Check the relationship between these two pages:

Body:
According to this document from Azure DevOps Service:

Docker Registry  Required.   The URL of the Docker registry.
Docker ID        Required.   The identifier of the Docker account user.
Password         Required.   The password for the account user identified above.
Email            Optional.   An email address to receive notifications.

And here's one document from Oracle Cloud: Managing Docker Registry Definitions
.

In my opinion(I don't purchase the Oracle account and can't test it for you :-(), you should enter your Docker Registry in Oracle for Docker Registry in Service Connection, and User Name for Docker ID, your password in Oracle for Password, Your email in Oracle page for Email in service connection.

Check the relationship between these two pages:


问:
Keep check box checked after refreshing the page
I have checkboxes as below in my rails app

```<code><% if field["field_type"] == "checklist"%>
 <% templat = @custom_templates.select{|s| s["id"] == m["startup_field_template_id"]}.first%>
 <small>
   <% vals = field["options"].to_s.gsub(/[\[\"\]]/, '').split(',') %>
   <% vals.each do |v| %>
   <% if templat["option_multi"]%>
     <input type="checkbox" />    <%= v %><br/>
   <% else %>
     <input type="checkbox" class="check" />    <%= v %><br/>
   <% end %>
   <% end %>
 </small>
<% else %>
 n/a
<% end %>
</code>```

I used below code to keep checked checkbox 'checked' after refreshing the page

```<code><sript>
$(function(){
var test = localStorage.input === 'true'? true: false;
$('input').prop('checked', test || false);
});

$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
</script>
</code>```

But it keep all check boxes checked after refreshing the page. how can I solve this?

答:
The selector you are using will set all checkbox input state, so you have to set the checked attribute to each input individually, also not that a better way to use localStorage is to use setItem and getItem() methods:

here is a snippet (it will not work here because its a sandbox check the fiddle) and a fiddle:

$(function(){
  var test = localStorage.input === 'true'? true: false;
  $('input').each(function(i, el) {
   //console.log(localStorage.input);
   test = (localStorage.getItem(`input-${i}`) === 'true') ? true: false;
   $(el).prop('checked', test || false);
  });

});
$('input').on('change', function() {
    localStorage.setItem(`input-${$(this).index('input')}`, $(this).is(':checked'));
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script
  src="https://code.jquery.com/jquery-3.5.1.min.js"
  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
  crossorigin="anonymous"></script>
<input type="checkbox" class="check" /> checkbox
<input type="checkbox" class="check" /> checkbox
<input type="checkbox" class="check" /> checkbox
<input type="checkbox" class="check" /> checkbox
<input type="checkbox" class="check" /> checkbox</code>```

Body:
I have checkboxes as below in my rails app

<% if field["field_type"] == "checklist"%>
 <% templat = @custom_templates.select{|s| s["id"] == m["startup_field_template_id"]}.first%>

   <% vals = field["options"].to_s.gsub(/[\[\"\]]/, '').split(',') %>
   <% vals.each do |v| %>
   <% if templat["option_multi"]%>
     <input type="checkbox" />    <%= v %>

   <% else %>
     <input type="checkbox" class="check" />    <%= v %>

   <% end %>
   <% end %>

<% else %>
 n/a
<% end %>

I used below code to keep checked checkbox 'checked' after refreshing the page

<sript>
$(function(){
var test = localStorage.input === 'true'? true: false;
$('input').prop('checked', test || false);
});

$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
</script>

But it keep all check boxes checked after refreshing the page. how can I solve this?

Body:
The selector you are using will set all checkbox input state, so you have to set the checked attribute to each input individually, also not that a better way to use localStorage is to use setItem and getItem() methods:

here is a snippet (it will not work here because its a sandbox check the fiddle) and a fiddle:

$(function(){
  var test = localStorage.input === 'true'? true: false;
  $('input').each(function(i, el) {
   //console.log(localStorage.input);
   test = (localStorage.getItem(`input-${i}`) === 'true') ? true: false;
   $(el).prop('checked', test || false);
  });

});
$('input').on('change', function() {
    localStorage.setItem(`input-${$(this).index('input')}`, $(this).is(':checked'));
  });

<script
  src="https://code.jquery.com/jquery-3.5.1.min.js"
  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
  crossorigin="anonymous"></script>
<input type="checkbox" class="check" /> checkbox
<input type="checkbox" class="check" /> checkbox
<input type="checkbox" class="check" /> checkbox
<input type="checkbox" class="check" /> checkbox
<input type="checkbox" class="check" /> checkbox


问:
Angular 8 Typescript How to set value of export const from another component?
I would like to change the value of the variable named bdg_m_1 from an another component. I am able to change the value of bdg_m_1 from the same typescript file.. Here is my code..

Filename : nav.ts

```<code>var bdg_m_1:string = "10" ; // HOW TO CHANGE THIS VALUE FROM ANOTHER COMPONENT

export const navItems: INavData[] = [
  {
    name: "Menu 1",
    url: "/menu_1",
    icon: "icon-speedometer",
     badge: {
       variant: 'info',
       text: bdg_m_1,
     }
  },
];
</code>```

答:
You could type the following code in nav.ts

```<code>let config = {
    bdg_m_1 : "10",
    navItems: [{
        ...
    }]
}
module.exports = config;
</code>```

And when you want to include config object,

```<code>var Config = require('nav.ts');
console.log(Config.bdg_m_1);
</code>```

Body:
I would like to change the value of the variable named bdg_m_1 from an another component. I am able to change the value of bdg_m_1 from the same typescript file.. Here is my code..

Filename : nav.ts

var bdg_m_1:string = "10" ; // HOW TO CHANGE THIS VALUE FROM ANOTHER COMPONENT

export const navItems: INavData[] = [
  {
    name: "Menu 1",
    url: "/menu_1",
    icon: "icon-speedometer",
     badge: {
       variant: 'info',
       text: bdg_m_1,
     }
  },
];

Body:
You could type the following code in nav.ts

let config = {
    bdg_m_1 : "10",
    navItems: [{
        ...
    }]
}
module.exports = config;

And when you want to include config object,

var Config = require('nav.ts');
console.log(Config.bdg_m_1);


问:
Change location that VS Code terminal is using
for some reason my VS Code terminal is based in some random folder, and I have to use an extension to refer to my folder every time I use it. Any settings I can change to make the terminal refer to a different folder?</p>

答: you can use code -r "Working Directory", to change working directory through terminal.


答:
Retrofit enqueue will execute in Asynchronous way</p>

```<code>//You could show progress bar here
NetworkConfig().getService()
        .getUsers()
        .enqueue(object : Callback<List<UserDataClassItem>> {

            override fun onFailure(call: Call<List<UserDataClassItem>>, t: Throwable) {
//You could hide progressBar here
                Toast.makeText(this@MainActivity, "No Connection. Check your Connectivity", Toast.LENGTH_SHORT).show()
            }

            override fun onResponse(
                call: Call<List<UserDataClassItem>>,
                response: Response<List<UserDataClassItem>>
            ) {
               //You could hide progressBar here
                rvUser.adapter = UserAdapter(response.body())
            }
        })
</code>```

Title: Is there a way in Kotlin Retrofit that works equivalent as OnPreExecute of Kotlin AsyncTask?

Body:
Retrofit enqueue will execute in Asynchronous way

//You could show progress bar here
NetworkConfig().getService()
        .getUsers()
        .enqueue(object : Callback<List<UserDataClassItem>> {

            override fun onFailure(call: Call<List<UserDataClassItem>>, t: Throwable) {
//You could hide progressBar here
                Toast.makeText(this@MainActivity, "No Connection. Check your Connectivity", Toast.LENGTH_SHORT).show()
            }

            override fun onResponse(
                call: Call<List<UserDataClassItem>>,
                response: Response<List<UserDataClassItem>>
            ) {
               //You could hide progressBar here
                rvUser.adapter = UserAdapter(response.body())
            }
        })


问:
Regex Negative Lookbehind to Negate a Full Capture
I'm want to detect numbers that don't have letters before them.

example:

ignore: covid19

accept: 19

I have this regex: (?<![a-z])(\d+) that uses a negative lookbehind to check if there's letters b4 the numbers, and if so, don't capture.

The problem is that if I type covid1 then it is ignored as expected, but if I type covid19 or covid1+[any more numbers] it doesn't get ignored.

How do I do a negative lookbehind that negates the whole capture following it?

答:
Your regex was very close. Although with some changes if you want only the numbers to matched i.e. it doesn't has any letters associated with it.

```<code>(?<![\S])(\b\d+\b)
     ^^   ^^   ^^ changes
</code>```

Explanation of the above regex:

\b - Represents a word-boundary.

\d+ - Matches digit[0-9] one or more times.

\S - Matches any non-whitespace character.

(?<![\S]) - Negative look-behind asserts that non-whitespace characters should not be matched before and after the 1st capturing group.

You can find the demo in here.

Body:
Your regex was very close. Although with some changes if you want only the numbers to matched i.e. it doesn't has any letters associated with it.

(?<![\S])(\b\d+\b)
     ^^   ^^   ^^ changes

Explanation of the above regex:

\b - Represents a word-boundary.

\d+ - Matches digit[0-9] one or more times.

\S - Matches any non-whitespace character.

(?<![\S]) - Negative look-behind asserts that non-whitespace characters should not be matched before and after the 1st capturing group.

You can find the demo in here.


问:
JQuery GanttChart - Apply Data
I tried to use the gantview jquery plugin
(https://github.com/thegrubbsian/jquery.ganttView)

So the needed data is like:

```<code>    {
        id: 1, name: "Feature 1", series: [
            { name: "Planned", start: new Date(2010,00,01), end: new Date(2010,00,03) },
            { name: "Actual", start: new Date(2010,00,02), end: new Date(2010,00,05), color: "#f0f0f0" }
        ]
    },
    {
        id: 2, name: "Feature 2", series: [
            { name: "Planned", start: new Date(2010,00,05), end: new Date(2010,00,20) },
            { name: "Actual", start: new Date(2010,00,06), end: new Date(2010,00,17), color: "#f0f0f0" },
            { name: "Projected", start: new Date(2010,00,06), end: new Date(2010,00,17), color: "#e0e0e0" }
        ]
    },
    {
        id: 3, name: "Feature 3", series: [
            { name: "Planned", start: new Date(2010,00,11), end: new Date(2010,01,03) },
            { name: "Actual", start: new Date(2010,00,15), end: new Date(2010,01,03), color: "#f0f0f0" }
        ]
    },
    {
        id: 4, name: "Feature 4", series: [
            { name: "Planned", start: new Date(2010,01,01), end: new Date(2010,01,03) },
            { name: "Actual", start: new Date(2010,01,01), end: new Date(2010,01,05), color: "#f0f0f0" }
        ]
    }
</code>```

Ok I think its JSON :-) So I built it in php, my funcs output is:

```<code>SERIES DATA
Array
(
    [name] => Krank
    [start] => 1317420000
    [end] => 1320102000
)
DATA
Array
(
    [id] => 1
    [name] => 15
    [series] => Array
        (
            [name] => Krank
            [start] => 1317420000
            [end] => 1320102000
        )

)
JSON
{"id":1,"name":15,"series":{"name":"Krank","start":1317420000,"end":1320102000}}
</code>```

Of course I submit only the json part to the plugin ;)

I built an array and encode it to json.

So with this data the plugin doesn't work. I have no idea how to rebuild this data with php.

some hints? ;)

答:
```<code>    $(function () {
        var ganttData = [];
        function onDataReceived(Data) {
            $.each(Data, function (i, j) {
                var obj = { id: j.id,name:j.name,series:[] }
                $.each(j.series, function (i1, j1) {
                    obj['series'].push({ name: j1.name, start: new Date(2010, 00, 05), end: new Date(2010, 00, 20) });
              });
                ganttData.push(obj)        });

             $("#ganttChart").ganttView({
                data: ganttData,
                slideWidth: 900,
                behavior: {
                    onClick: function (data) {

                    },
                    onResize: function (data) {

                    },
                    onDrag: function (data) {

                    }
                }
            });

        }
        var dataUrl = "/Engineering/GetData";
        $.ajax({
            type: "POST",
            url: dataUrl,
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: onDataReceived
        });

    });
</code>```

Model

```<code>public class GanttModel
{
    public int id { get; set; }
    public string name { get; set; }
    public List<GanttProperties> series { get; set; }
}

public class GanttProperties
{
    public string name { get; set; }
    public DateTime start { get; set; }
    public DateTime end { get; set; }
    public string color { get; set; }

}
</code>```

ACTION method

```<code>public ActionResult GetData()
{
    List<GanttProperties> series;
    List<GanttModel> gantdata = new List<GanttModel>
    {

        new GanttModel {id=  1,name="Brick Work", series=new List<GanttProperties> { new GanttProperties {name = "Scope work" ,start= DateTime.Now,end =DateTime.Now.AddDays(20),color = "green"} } },
        new GanttModel {id=  2,name="Common Work", series=new List<GanttProperties> { new GanttProperties {name = "No Of days to Complete 6th Slab", start= DateTime.Now,end =DateTime.Now.AddDays(20),color = "green"} } }

    };

    return Json(gantdata, JsonRequestBehavior.AllowGet);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: JQuery GanttChart - Apply Data

Body:
I tried to use the gantview jquery plugin
(https://github.com/thegrubbsian/jquery.ganttView)

So the needed data is like:

    {
        id: 1, name: "Feature 1", series: [
            { name: "Planned", start: new Date(2010,00,01), end: new Date(2010,00,03) },
            { name: "Actual", start: new Date(2010,00,02), end: new Date(2010,00,05), color: "#f0f0f0" }
        ]
    },
    {
        id: 2, name: "Feature 2", series: [
            { name: "Planned", start: new Date(2010,00,05), end: new Date(2010,00,20) },
            { name: "Actual", start: new Date(2010,00,06), end: new Date(2010,00,17), color: "#f0f0f0" },
            { name: "Projected", start: new Date(2010,00,06), end: new Date(2010,00,17), color: "#e0e0e0" }
        ]
    },
    {
        id: 3, name: "Feature 3", series: [
            { name: "Planned", start: new Date(2010,00,11), end: new Date(2010,01,03) },
            { name: "Actual", start: new Date(2010,00,15), end: new Date(2010,01,03), color: "#f0f0f0" }
        ]
    },
    {
        id: 4, name: "Feature 4", series: [
            { name: "Planned", start: new Date(2010,01,01), end: new Date(2010,01,03) },
            { name: "Actual", start: new Date(2010,01,01), end: new Date(2010,01,05), color: "#f0f0f0" }
        ]
    }

Ok I think its JSON :-) So I built it in php, my funcs output is:

SERIES DATA
Array
(
    [name] => Krank
    [start] => 1317420000
    [end] => 1320102000
)
DATA
Array
(
    [id] => 1
    [name] => 15
    [series] => Array
        (
            [name] => Krank
            [start] => 1317420000
            [end] => 1320102000
        )

)
JSON
{"id":1,"name":15,"series":{"name":"Krank","start":1317420000,"end":1320102000}}

Of course I submit only the json part to the plugin ;)

I built an array and encode it to json.

So with this data the plugin doesn't work. I have no idea how to rebuild this data with php.

some hints? ;)

Body:
    $(function () {
        var ganttData = [];
        function onDataReceived(Data) {
            $.each(Data, function (i, j) {
                var obj = { id: j.id,name:j.name,series:[] }
                $.each(j.series, function (i1, j1) {
                    obj['series'].push({ name: j1.name, start: new Date(2010, 00, 05), end: new Date(2010, 00, 20) });
              });
                ganttData.push(obj)        });

             $("#ganttChart").ganttView({
                data: ganttData,
                slideWidth: 900,
                behavior: {
                    onClick: function (data) {

                    },
                    onResize: function (data) {

                    },
                    onDrag: function (data) {

                    }
                }
            });

        }
        var dataUrl = "/Engineering/GetData";
        $.ajax({
            type: "POST",
            url: dataUrl,
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: onDataReceived
        });

    });

Model

public class GanttModel
{
    public int id { get; set; }
    public string name { get; set; }
    public List<GanttProperties> series { get; set; }
}

public class GanttProperties
{
    public string name { get; set; }
    public DateTime start { get; set; }
    public DateTime end { get; set; }
    public string color { get; set; }

}

ACTION method

public ActionResult GetData()
{
    List<GanttProperties> series;
    List<GanttModel> gantdata = new List<GanttModel>
    {

        new GanttModel {id=  1,name="Brick Work", series=new List<GanttProperties> { new GanttProperties {name = "Scope work" ,start= DateTime.Now,end =DateTime.Now.AddDays(20),color = "green"} } },
        new GanttModel {id=  2,name="Common Work", series=new List<GanttProperties> { new GanttProperties {name = "No Of days to Complete 6th Slab", start= DateTime.Now,end =DateTime.Now.AddDays(20),color = "green"} } }

    };

    return Json(gantdata, JsonRequestBehavior.AllowGet);
}


问:
'Express.js Async Handler' - Difficulty writing tests for it
I have this function I use to pass any failures directly to the express error handler. I am writing tests for it and I am trying to wrap my head around how I can test this properly by passing in the function correctly.

asyncHandlerUtil.js

```<code>const asyncHandlerUtil = fn => (req, res, next) => {
    return Promise
        .resolve(fn(req, res, next))
        .catch(next);
};

module.exports = asyncHandlerUtil;
</code>```

Right now I have (Aware it's wrong atm)

asyncHandlerUtil.spec.js

```<code>import asyncHandlerUtil from './asyncHandlerUtil';

describe('Given the asyncHandlerUtil function', () => {
  describe('when is is called', () => {
    let middleware;
    let fn;
    let subFn;

    beforeEach(() => {
      subFn = jest.fn();
      fn = jest.fn(() => subFn);
      middleware = asyncHandlerUtil(fn);
      middleware();
    });
    it('should call fn', () => {
      expect(fn).toHaveBeenCalledWith(subFn);
    });
  // other tests needed for rejection and catching errors.
  });
});

</code>```

Thanks!

答:
Here is the unit test solution:

asyncHandlerUtil.js:

const asyncHandlerUtil = (fn) => (req, res, next) => {
  return Promise.resolve(fn(req, res, next)).catch(next);
};

module.exports = asyncHandlerUtil;
```

<p><code>asyncHandlerUtil.test.js</code>:</p>

<pre class="lang-js prettyprint-override"><code>const asyncHandlerUtil = require('./asyncHandlerUtil');

describe('62063369', () => {
  it('should pass', async () => {
    const mFn = jest.fn().mockResolvedValueOnce('mocked value');
    const mReq = {};
    const mRes = {};
    const mNext = jest.fn();
    const got = await asyncHandlerUtil(mFn)(mReq, mRes, mNext);
    expect(got).toBe('mocked value');
    expect(mFn).toBeCalledWith({}, {}, mNext);
  });
});
</code>```

Unit test results with coverage report:

 PASS  stackoverflow/62063369/asyncHandlerUtil.test.js (12.14s)
  62063369
    ✓ should pass (5ms)

---------------------|---------|----------|---------|---------|-------------------
File                 | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------------|---------|----------|---------|---------|-------------------
All files            |     100 |      100 |     100 |     100 |
 asyncHandlerUtil.js |     100 |      100 |     100 |     100 |
---------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        14.218s
```

Body:
I have this function I use to pass any failures directly to the express error handler. I am writing tests for it and I am trying to wrap my head around how I can test this properly by passing in the function correctly.

asyncHandlerUtil.js

const asyncHandlerUtil = fn => (req, res, next) => {
    return Promise
        .resolve(fn(req, res, next))
        .catch(next);
};

module.exports = asyncHandlerUtil;

Right now I have (Aware it's wrong atm)

asyncHandlerUtil.spec.js

import asyncHandlerUtil from './asyncHandlerUtil';

describe('Given the asyncHandlerUtil function', () => {
  describe('when is is called', () => {
    let middleware;
    let fn;
    let subFn;

    beforeEach(() => {
      subFn = jest.fn();
      fn = jest.fn(() => subFn);
      middleware = asyncHandlerUtil(fn);
      middleware();
    });
    it('should call fn', () => {
      expect(fn).toHaveBeenCalledWith(subFn);
    });
  // other tests needed for rejection and catching errors.
  });
});

Thanks!

Body:
Here is the unit test solution:

asyncHandlerUtil.js:

const asyncHandlerUtil = (fn) => (req, res, next) => {
  return Promise.resolve(fn(req, res, next)).catch(next);
};

module.exports = asyncHandlerUtil;

asyncHandlerUtil.test.js:

const asyncHandlerUtil = require('./asyncHandlerUtil');

describe('62063369', () => {
  it('should pass', async () => {
    const mFn = jest.fn().mockResolvedValueOnce('mocked value');
    const mReq = {};
    const mRes = {};
    const mNext = jest.fn();
    const got = await asyncHandlerUtil(mFn)(mReq, mRes, mNext);
    expect(got).toBe('mocked value');
    expect(mFn).toBeCalledWith({}, {}, mNext);
  });
});

Unit test results with coverage report:

 PASS  stackoverflow/62063369/asyncHandlerUtil.test.js (12.14s)
  62063369
    ✓ should pass (5ms)

---------------------|---------|----------|---------|---------|-------------------
File                 | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
---------------------|---------|----------|---------|---------|-------------------
All files            |     100 |      100 |     100 |     100 |
 asyncHandlerUtil.js |     100 |      100 |     100 |     100 |
---------------------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        14.218s


问:
Checking for TextField changes once a form was submitted in Coldfusion
I have code that displays database entries, and allows for editing/deletion.

I am trying to find some way on submission to see if a particular field has been changed, so if the old data of the field is not referenced by any database entries, I can delete it. Any ideas on how to do this?

To respond to the first comment / Edit: It is somewhat hard to put code of this problem up here, but I will try to grab some snippets that help.

```<code><td>Upload File:</td>
<td>
    <input type="file" name="txtName" size="50" />
</td>
<cfif url.filesid neq "0">
<td>Or Use Server File:</td>
    <td>
    <select name="ddlFilesNames">
        <option value="" selected></option>
            <cfoutput query="qfiles">
                <option
                  value="#qfiles.name#"
                  #iif(qfiles.name eq recEditFiles.fileName,DE("selected"),DE(""))#
                >#qfiles.name#</option>
            </cfoutput>
    </select>
    </td>
</cfif>
</code>```

These are the two fields I need to check if they changed, when the edit button is hit the select drop down list has the current server file displayed, but during editing they can either add a file to the textfield (through a browse option to upload a new file) or they can select another file from the dropdown list, and then hit an update button that submits the changes.

When the update button is hit I need to somehow check to see if the fields were changed at all.

I feel that one of the main problems is that once the button is hit, a javascript method is called, and so far I have been unsuccessful is lacing coldfusion within javascript methods, everytime I try to do this or visa-versa it breaks the program.

答:
Some code would help.  Sounds like you have a <input type="file" ... /> and you want to know if the user "removes" the file from the DB record being entered?

Usually I handle this by showing the current file associated with the record and a "delete" button or icon that allows you to remove that image.  I also include a "replace" or "upload new" or "upload another" button that allows the user to select another file to replace the current file, or add a file to a record without a file.

If you don't do something like this, then you have no way of knowing if the user just didn't feel like uploading the same file again (because its already there, why would they?) or if they intended to have your system remove that file and its association with the database record.

Body:
I have code that displays database entries, and allows for editing/deletion.

I am trying to find some way on submission to see if a particular field has been changed, so if the old data of the field is not referenced by any database entries, I can delete it. Any ideas on how to do this?

To respond to the first comment / Edit: It is somewhat hard to put code of this problem up here, but I will try to grab some snippets that help.

Upload File:

    <input type="file" name="txtName" size="50" />

<cfif url.filesid neq "0">
Or Use Server File:

    <select name="ddlFilesNames">
        <option value="" selected></option>
            <cfoutput query="qfiles">
                <option
                  value="#qfiles.name#"
                  #iif(qfiles.name eq recEditFiles.fileName,DE("selected"),DE(""))#
                >#qfiles.name#</option>
            </cfoutput>
    </select>

</cfif>

These are the two fields I need to check if they changed, when the edit button is hit the select drop down list has the current server file displayed, but during editing they can either add a file to the textfield (through a browse option to upload a new file) or they can select another file from the dropdown list, and then hit an update button that submits the changes.

When the update button is hit I need to somehow check to see if the fields were changed at all.

I feel that one of the main problems is that once the button is hit, a javascript method is called, and so far I have been unsuccessful is lacing coldfusion within javascript methods, everytime I try to do this or visa-versa it breaks the program.


问:
Smooth the edges of binary images (Face) using Python and Open CV
I am looking for a perfect way to smooth edges of binary images. The problem is the binary image appears to be a staircase like borders which is very unpleasing for my further masking process.

I am attaching a raw binary image that is to be converted into smooth edges and I am also providing the expected outcome. I am also looking for a solution that would work even if we increase the dimensions of the image.

Problem Image    Expected Outcome

答:
You can do that in Python/OpenCV with the help of Skimage by blurring the binary image. Then apply a one-sided clip.

Input:

```<code>import cv2
import numpy as np
import skimage.exposure

# load image
img = cv2.imread('bw_image.png')

# blur threshold image
blur = cv2.GaussianBlur(img, (0,0), sigmaX=3, sigmaY=3, borderType = cv2.BORDER_DEFAULT)

# stretch so that 255 -> 255 and 127.5 -> 0
# C = A*X+B
# 255 = A*255+B
# 0 = A*127.5+B
# Thus A=2 and B=-127.5
#aa = a*2.0-255.0 does not work correctly, so use skimage
result = skimage.exposure.rescale_intensity(blur, in_range=(127.5,255), out_range=(0,255))

# save output
cv2.imwrite('bw_image_antialiased.png', result)

# Display various images to see the steps
cv2.imshow('result', result)

cv2.waitKey(0)
cv2.destroyAllWindows()
</code>```

You will have to adjust the amount of blur for the degree of aliasing in the image.

Body:
You can do that in Python/OpenCV with the help of Skimage by blurring the binary image. Then apply a one-sided clip.

Input:

import cv2
import numpy as np
import skimage.exposure

# load image
img = cv2.imread('bw_image.png')

# blur threshold image
blur = cv2.GaussianBlur(img, (0,0), sigmaX=3, sigmaY=3, borderType = cv2.BORDER_DEFAULT)

# stretch so that 255 -> 255 and 127.5 -> 0
# C = A*X+B
# 255 = A*255+B
# 0 = A*127.5+B
# Thus A=2 and B=-127.5
#aa = a*2.0-255.0 does not work correctly, so use skimage
result = skimage.exposure.rescale_intensity(blur, in_range=(127.5,255), out_range=(0,255))

# save output
cv2.imwrite('bw_image_antialiased.png', result)

# Display various images to see the steps
cv2.imshow('result', result)

cv2.waitKey(0)
cv2.destroyAllWindows()

You will have to adjust the amount of blur for the degree of aliasing in the image.


问:
Read iOS toast message through Appium
Could anyone suggest to me the code to read an iOS toast message. I have read android toast messages using AndroidElement toastElement = driver.findElementByXPath("//android.widget.Toast[1]");
        String toastMessage = toastElement.getAttribute("name");

But for iOS toast the above is not working

IOSElement toastElement = driver.findElementByXPath("//ios.widget.Toast[1]");
        String toastMessage = toastElement.getAttribute("name");

答:
Use below method , it uses page source to verify the toast message.
Works for both iOS and Android.</p>

```<code>public boolean isToastMessageDisplayed(String message)
{
    boolean isDisplayed = false;
    int count=0;
    do {
        if(mobileDriver.getPageSource().contains(message))
        {
            isDisplayed=true;
            break;
        }
        Thread.sleep(200);//Add your custom wait if exists
        count++;

    }while(count<10);
    return isDisplayed;
}
</code>```

Title: Read iOS toast message through Appium

Body:
Use below method , it uses page source to verify the toast message.
Works for both iOS and Android.

public boolean isToastMessageDisplayed(String message)
{
    boolean isDisplayed = false;
    int count=0;
    do {
        if(mobileDriver.getPageSource().contains(message))
        {
            isDisplayed=true;
            break;
        }
        Thread.sleep(200);//Add your custom wait if exists
        count++;

    }while(count<10);
    return isDisplayed;
}


问:
Nomad job using exec fails when running any bash command
I have tried everything and I just can’t get an exec type job to run. I tried it on 3 different clusters and it fails on all.

The job prunes docker containers and just runs docker system prune -a.

This is the config section:

```<code>driver = "exec"
config {
  command = "bash"
  args = ["-c",
  " docker system prune -a "]
}
</code>```

No logs and containers are not pruned:

```<code>job "docker-cleanup" {
  type = "system"
  constraint {
    attribute = "${attr.kernel.name}"
    operator  = "="
    value     = "linux"
  }
  datacenters = ["dc1"]
  group "docker-cleanup" {

    restart {
      interval = "24h"
      attempts = 0
      mode     = "fail"
    }
    task "docker-system-prune" {
      driver = "exec"
      config {
        command = "bash"
        args = ["-c",
        " docker system prune -a "]
      }
      resources {
        cpu    = 100
        memory = 50
        network {
          mbits = 1
        }
      }
    }
  }
}
</code>```

What am I doing wrong?

答:
I would suggest you provide the output to make it easier to analyze.

One thing you can try, is to add the full path to the bash executable.

```<code>   driver = "exec"
    config {
      command = "/bin/bash"
      args = ["-c",
      " docker system prune -a "]
    }
</code>```

Further you are missing the "--force" parameter on system prune, without it - docker system prune asks for confirmation.

```<code>docker system prune --all --force
</code>```

Body:
I have tried everything and I just can’t get an exec type job to run. I tried it on 3 different clusters and it fails on all.

The job prunes docker containers and just runs docker system prune -a.

This is the config section:

driver = "exec"
config {
  command = "bash"
  args = ["-c",
  " docker system prune -a "]
}

No logs and containers are not pruned:

job "docker-cleanup" {
  type = "system"
  constraint {
    attribute = "${attr.kernel.name}"
    operator  = "="
    value     = "linux"
  }
  datacenters = ["dc1"]
  group "docker-cleanup" {

    restart {
      interval = "24h"
      attempts = 0
      mode     = "fail"
    }
    task "docker-system-prune" {
      driver = "exec"
      config {
        command = "bash"
        args = ["-c",
        " docker system prune -a "]
      }
      resources {
        cpu    = 100
        memory = 50
        network {
          mbits = 1
        }
      }
    }
  }
}

What am I doing wrong?

Body:
I would suggest you provide the output to make it easier to analyze.

One thing you can try, is to add the full path to the bash executable.

   driver = "exec"
    config {
      command = "/bin/bash"
      args = ["-c",
      " docker system prune -a "]
    }

Further you are missing the "--force" parameter on system prune, without it - docker system prune asks for confirmation.

docker system prune --all --force


问:
Passing a variable set of arguments from one function to a macro in C
I see this link Passing variable arguments to another function that accepts a variable argument list. What is the syntax to pass it to a macro as well?</p>

```<code>#include <stdarg.h>
#define exampleW(int b, args...) function2(b, va_args)
static void exampleV(int b, va_list args);

void exampleB(int b, ...)
{
    va_list args;
    va_start(args, b);
    exampleV(b, args);
    //also pass args to a macro which takes multiple args after this step
    ??? [Is it exampleW(b, ##args)]
    va_end(args);
}

static void exampleV(int b, va_list args)
{
    ...whatever you planned to have exampleB do...
    ...except it calls neither va_start nor va_end...
}
</code>```

答:
This is not possible.  Macros are expanded at compile time, and so their arguments need to be known at compile time, at the point where the macro is used.  The arguments to your function exampleB are in general not known until run time.  And even though in many cases the arguments may be known when the call to the function is compiled, that may be in a different source file, which does not help you with macros in this source file.

You'll need to either:

have exampleB instead call a function like vfunction2 which is  function2 rewritten to take a va_list parameter

reimplement exampleB as a macro

if there are a finite number of possible combinations of arguments to exampleB, then write code to handle all the cases separately:

```<code>if (b == TWO_INTS) {
    int i1 = va_arg(args, int);
    int i2 = va_arg(args, int);
    exampleW(i1, i2);
} else if (b == STRING_AND_DOUBLE) {
    char *s = va_arg(args, char *);
    double d = va_arg(args, double);
    exampleW(s,d);
} else // ...
</code>```

do something non-portable to call the function function2 with the same arguments as were passed to exampleB, e.g. with assembly language tricks, or gcc's __builtin_apply().

Body:
I see this link Passing variable arguments to another function that accepts a variable argument list. What is the syntax to pass it to a macro as well?

#include <stdarg.h>
#define exampleW(int b, args...) function2(b, va_args)
static void exampleV(int b, va_list args);

void exampleB(int b, ...)
{
    va_list args;
    va_start(args, b);
    exampleV(b, args);
    //also pass args to a macro which takes multiple args after this step
    ??? [Is it exampleW(b, ##args)]
    va_end(args);
}

static void exampleV(int b, va_list args)
{
    ...whatever you planned to have exampleB do...
    ...except it calls neither va_start nor va_end...
}

Body:
This is not possible.  Macros are expanded at compile time, and so their arguments need to be known at compile time, at the point where the macro is used.  The arguments to your function exampleB are in general not known until run time.  And even though in many cases the arguments may be known when the call to the function is compiled, that may be in a different source file, which does not help you with macros in this source file.

You'll need to either:

have exampleB instead call a function like vfunction2 which is  function2 rewritten to take a va_list parameter

reimplement exampleB as a macro

if there are a finite number of possible combinations of arguments to exampleB, then write code to handle all the cases separately:

if (b == TWO_INTS) {
    int i1 = va_arg(args, int);
    int i2 = va_arg(args, int);
    exampleW(i1, i2);
} else if (b == STRING_AND_DOUBLE) {
    char *s = va_arg(args, char *);
    double d = va_arg(args, double);
    exampleW(s,d);
} else // ...

do something non-portable to call the function function2 with the same arguments as were passed to exampleB, e.g. with assembly language tricks, or gcc's __builtin_apply().


问:
GLib-ERROR : Creating pipes for GWakeup: Too many open files
I am getting this error when running my c++ program under ubuntu 20.04 with clang 9 :

GLib-ERROR : Creating pipes for GWakeup: Too many open files

I know I have a lot of open files, this is a CGI renderer with a mip-map tiled texture cache, it loads only parts of images in the cache when needed and not the full images, thus keeping files open. There are about 3000 images but it opened only about 1000 before crashing.

What I don't understand is that these texture files are read using stdlib fopen(), not GLib/GTK. So why is the error coming from GLib?

答: The limit on open files is process- or system-wide. So it doesn't matter whether they are opened by GLib or not (which also uses the same operating system calls to open files, anyway). If you have 1000 files opened at the same time with fopen(), consider closing them if you can.


问:
How to catch the longest sequence of a group
The task is to find the longest sequence of a group

for instance, given DNA sequence: "AGATCAGATCTTTTTTCTAATGTCTAGGATATATCAGATCAGATCAGATCAGATCAGATC"
and it has 7 occurrences of AGATC. (AGATC) matches all occurrences.
Is it possible to write a regular expression that catches only the longest sequence, i.e. AGATCAGATCAGATCAGATCAGATC in the given text?
If this is not possible only with regex, how can I iterate through each sequence (i.e. 1st sequence is AGATCAGATC, 2nd - AGATCAGATCAGATCAGATCAGATC et cetera) in python?

答:
Use:

```<code>import re

sequence = "AGATCAGATCTTTTTTCTAATGTCTAGGATATATCAGATCAGATCAGATCAGATCAGATC"
matches = re.findall(r'(?:AGATC)+', sequence)

# To find the longest subsequence
longest = max(matches, key=len)
</code>```

Explanation:

Non-capturing group (?:AGATC)+

+ Quantifier — Matches between one and unlimited times, as many times as possible.

AGATC matches the characters AGATC literally (case sensitive)

Result:

```<code># print(matches)
['AGATCAGATC', 'AGATCAGATCAGATCAGATCAGATC']

# print(longest)
'AGATCAGATCAGATCAGATCAGATC'
</code>```

You can test the regex here.

Body:
Use:

import re

sequence = "AGATCAGATCTTTTTTCTAATGTCTAGGATATATCAGATCAGATCAGATCAGATCAGATC"
matches = re.findall(r'(?:AGATC)+', sequence)

# To find the longest subsequence
longest = max(matches, key=len)

Explanation:

Non-capturing group (?:AGATC)+

+ Quantifier — Matches between one and unlimited times, as many times as possible.

AGATC matches the characters AGATC literally (case sensitive)

Result:

# print(matches)
['AGATCAGATC', 'AGATCAGATCAGATCAGATCAGATC']

# print(longest)
'AGATCAGATCAGATCAGATCAGATC'

You can test the regex here.


问:
Creating pod in swift which have dependency on another objective-c pod

As I explained in image I want to create Pod lib in swift which have another Pod lib dependency written in Objective-c.

Now I know that to use objective-c code in swift we need bridge file and I created it too.
but When I set it into Pod's build phase I got this error<unknown>:0: error: using bridging headers with framework targets is unsupported

I got hint in internet that I should put .h file into pod-umbrella.h file, But that also gave me error Include of non-modular header inside framework module 'DemoPod'

Please help me if you had similar issue in past and resolved it.

Some hint/suggestions are also welcome.

Here is my demopod project for you if you want to play around.

Demo Pod Project

EDIT
As per Ashsis suggestion I added below code into DemoPod.modulemap

```<code>framework module AdaptiveCard {
  umbrella header "/Users/jageen.shukla/Documents/Project/ai answer/DemoPod/Example/Pods/AdaptiveCards/AdaptiveCards.framework/Headers/ACFramework.h"
  requires ios
  export *
}
</code>```

But still I can not build project because it give me error in target project that can not find module "AdaptiveCard".

I change code in DemoPod.modulemap

```<code>framework module DemoPod {
  umbrella header "DemoPod-umbrella.h"

  // Solution 2
  framework module AdaptiveCard {
      umbrella header "/Users/jageen.shukla/Downloads/DemoPod/Example/Pods/AdaptiveCards/AdaptiveCards.framework/Headers/ACFramework.h"
      export *
      module * { export * }
  }
  // ----

  export *
  module * { export * }
}
</code>```

Now I am able to compile my project. but I am not sure what I am doing is good practice or not? Plus I am also not know why I have to mention `absolute path` of adaptive card's header file.

Latest code : [Demo_2][4]
https://drive.google.com/file/d/1Xve0DUAy4bQ7sx4d3H8WLbJJwTqlJnCt/view?usp=sharing

答:
As the error says, bridging headers aren't allowed in frameworks, only in applications.

The detailed documentation is here

The Swift code will be able to access everything from objc that is included in the public umbrella header for your framework where it says

```<code>// In this header, you should import all the public headers of your framework using statements like #import <YourFramework/PublicHeader.h>
</code>```

You'll need to remove the bridging header from where you added it in the Build Settings, in order to get your framework to compile.

what should you do now ?

do this:

Remove your bridging header file.

Remove references to the bridging header file in the build settings for the framework

Add the necessary headers to your umbrella file ([Name].h)

Make the included files public in the framework's "Headers" section of its "Build Phases".

Clean and rebuild.

Note: The "umbrella header file" is a file (named [ProductName].h) that generally represents all public headers of a framework. It is usually just a list of #import statements to other headers contained in the framework. In Xcode, if you open UIKit.h, you will see a good example of an umbrella file.

Body:
As I explained in image I want to create Pod lib in swift which have another Pod lib dependency written in Objective-c.

Now I know that to use objective-c code in swift we need bridge file and I created it too.
but When I set it into Pod's build phase I got this error<unknown>:0: error: using bridging headers with framework targets is unsupported

I got hint in internet that I should put .h file into pod-umbrella.h file, But that also gave me error Include of non-modular header inside framework module 'DemoPod'

Please help me if you had similar issue in past and resolved it.

Some hint/suggestions are also welcome.

Here is my demopod project for you if you want to play around.

Demo Pod Project

EDIT
As per Ashsis suggestion I added below code into DemoPod.modulemap

framework module AdaptiveCard {
  umbrella header "/Users/jageen.shukla/Documents/Project/ai answer/DemoPod/Example/Pods/AdaptiveCards/AdaptiveCards.framework/Headers/ACFramework.h"
  requires ios
  export *
}

But still I can not build project because it give me error in target project that can not find module "AdaptiveCard".

I change code in DemoPod.modulemap

framework module DemoPod {
  umbrella header "DemoPod-umbrella.h"

  // Solution 2
  framework module AdaptiveCard {
      umbrella header "/Users/jageen.shukla/Downloads/DemoPod/Example/Pods/AdaptiveCards/AdaptiveCards.framework/Headers/ACFramework.h"
      export *
      module * { export * }
  }
  // ----

  export *
  module * { export * }
}

Now I am able to compile my project. but I am not sure what I am doing is good practice or not? Plus I am also not know why I have to mention `absolute path` of adaptive card's header file.

Latest code : [Demo_2][4]
https://drive.google.com/file/d/1Xve0DUAy4bQ7sx4d3H8WLbJJwTqlJnCt/view?usp=sharing

Body:
As the error says, bridging headers aren't allowed in frameworks, only in applications.

The detailed documentation is here

The Swift code will be able to access everything from objc that is included in the public umbrella header for your framework where it says

// In this header, you should import all the public headers of your framework using statements like #import <YourFramework/PublicHeader.h>

You'll need to remove the bridging header from where you added it in the Build Settings, in order to get your framework to compile.

what should you do now ?

do this:

Remove your bridging header file.

Remove references to the bridging header file in the build settings for the framework

Add the necessary headers to your umbrella file ([Name].h)

Make the included files public in the framework's "Headers" section of its "Build Phases".

Clean and rebuild.

Note: The "umbrella header file" is a file (named [ProductName].h) that generally represents all public headers of a framework. It is usually just a list of #import statements to other headers contained in the framework. In Xcode, if you open UIKit.h, you will see a good example of an umbrella file.


问:
Yup validate password contains at least one special character
I am using the following yup:

```<code>export const validationSchema = Yup.object().shape({
  password: Yup.string()
    .required('Password is required')
    .matches(
      /^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/,
      'Need one special character',
    ),
  confirmPassword: Yup.string()
    .oneOf([Yup.ref('password'), null], 'Passwords must match')
    .required('Password confirm is required'),
});
</code>```

to validate if there is one special character in password string.

```<code>@ => valid
@a => invalid
a@ => invalid
aa => invalid, of course
</code>```

I also test the regex pattern online to make sure this pattern will catch any special character in string
I wonder it could be yup bug or I do something wrong

答:
You may try using the following regex pattern:

```<code>^.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?].*$
</code>```

This just matches any input so long as it has a special character.  Your updated React code:

```<code>export const validationSchema = Yup.object().shape({
    password: Yup.string()
       .required('Password is required')
       .matches(
           /^.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?].**$/,
          'Need one special character',
       ),
   confirmPassword: Yup.string()
      .oneOf([Yup.ref('password'), null], 'Passwords must match')
    .required('Password confirm is required'),
});
</code>```

Body:
I am using the following yup:

export const validationSchema = Yup.object().shape({
  password: Yup.string()
    .required('Password is required')
    .matches(
      /^[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]*$/,
      'Need one special character',
    ),
  confirmPassword: Yup.string()
    .oneOf([Yup.ref('password'), null], 'Passwords must match')
    .required('Password confirm is required'),
});

to validate if there is one special character in password string.

@ => valid
@a => invalid
a@ => invalid
aa => invalid, of course

I also test the regex pattern online to make sure this pattern will catch any special character in string
I wonder it could be yup bug or I do something wrong

Body:
You may try using the following regex pattern:

^.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?].*$

This just matches any input so long as it has a special character.  Your updated React code:

export const validationSchema = Yup.object().shape({
    password: Yup.string()
       .required('Password is required')
       .matches(
           /^.*[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?].**$/,
          'Need one special character',
       ),
   confirmPassword: Yup.string()
      .oneOf([Yup.ref('password'), null], 'Passwords must match')
    .required('Password confirm is required'),
});


问:
vue-router Route with name does not exist
I have a vue component that contains a method, the method contains this router push that tries to push to another vue component:

GetAnimal.vue:

...
this.$router.push({
    name: "/viewanimal",
});
...
```

<p>I have this mappings for the router:</p>

<p><strong>router.js</strong>:</p>

<pre class="lang-js prettyprint-override"><code>{
    path: "/viewanimal",
    component: () => import('./views/DisplayAnimal.vue')
},
{
    path: "/getanimal",
    component: () => import('./views/GetAnimal.vue')
}
</code>```

However when the code inside the GetAnimal.vue gets executed I get this in console:

And I get directed to http://localhost:8080/.

I also tried

...
this.$router.push({
    name: "viewanimal",
});
...
```

<p>but it doesn't work either.</p>

<p><strong>EDIT</strong>:</p>

<p>I've tried:
<strong>router.js</strong>:</p>

```  {
            path: "/viewanimal",
            name: "viewanimal",
            component: () => import('./views/DisplayAnimal.vue')
        },
        {
            path: "/getanimal",
            name: "getanimal",
            component: () => import('./views/GetAnimal.vue')
        }
```

<p><strong>GetAnimal.vue</strong>:</p>

``` console.log("this.animal: " + JSON.stringify(this.animal));  //displays good JSON

                this.$router.push({
                     name: "viewanimal",
                    params: this.animal
                 });
```

<p><strong>DisplayAnimal.vue</strong>:</p>

```created() {
            console.log("animal param: " +
                JSON.stringify(this.$route.params.animal)); //prints undefined
          }
```

<p>---The animal parameter doesn't seem to have been passed. I'm not sure if it's the problem with the router's path/name thing or something else---.</p>

<p><strong>UPDATE</strong>:</p>

<p>Managed to make it work. This should be in <code>GetAnimal.vue</code>:</p>

```    this.$router.push({
                     name: "viewanimal",
                    params: {
                         animal: this.animal
                     }
                 });
```

答:
You have to define the routes as named route in the router.js file. Your routes missing the name attribute. For named routes, the name attribute is must. It should be like the given example,

const router = new VueRouter({
  routes: [
    {
        path: "/viewanimal",
        name: "animal",
        component: () => import('./views/DisplayAnimal.vue')
    },
    {
        path: "/getanimal",
        name: "animal.get",
        component: () => import('./views/GetAnimal.vue')
    }
  ]
})
```

<p>Focus on the <code>name</code> attribute, this is the route name you can use in template as given,</p>

<pre class="lang-html prettyprint-override"><code><router-link :to="{ name: 'animal'}">Animals</router-link>
</code>```

Alternatively, here is the code to push new route,

router.push({ name: 'animal'})
```

If you don't want to go through naming all of the routes you can push the route path as router.push({ path: '/viewanimal' }), but the named routes are more clean approach.

Body:
I have a vue component that contains a method, the method contains this router push that tries to push to another vue component:

GetAnimal.vue:

...
this.$router.push({
    name: "/viewanimal",
});
...

I have this mappings for the router:

router.js:

{
    path: "/viewanimal",
    component: () => import('./views/DisplayAnimal.vue')
},
{
    path: "/getanimal",
    component: () => import('./views/GetAnimal.vue')
}

However when the code inside the GetAnimal.vue gets executed I get this in console:

And I get directed to http://localhost:8080/.

I also tried

...
this.$router.push({
    name: "viewanimal",
});
...

but it doesn't work either.

EDIT:

I've tried:
router.js:

  {
            path: "/viewanimal",
            name: "viewanimal",
            component: () => import('./views/DisplayAnimal.vue')
        },
        {
            path: "/getanimal",
            name: "getanimal",
            component: () => import('./views/GetAnimal.vue')
        }

GetAnimal.vue:

 console.log("this.animal: " + JSON.stringify(this.animal));  //displays good JSON

                this.$router.push({
                     name: "viewanimal",
                    params: this.animal
                 });

DisplayAnimal.vue:

created() {
            console.log("animal param: " +
                JSON.stringify(this.$route.params.animal)); //prints undefined
          }

---The animal parameter doesn't seem to have been passed. I'm not sure if it's the problem with the router's path/name thing or something else---.

UPDATE:

Managed to make it work. This should be in GetAnimal.vue:

    this.$router.push({
                     name: "viewanimal",
                    params: {
                         animal: this.animal
                     }
                 });

Body:
You have to define the routes as named route in the router.js file. Your routes missing the name attribute. For named routes, the name attribute is must. It should be like the given example,

const router = new VueRouter({
  routes: [
    {
        path: "/viewanimal",
        name: "animal",
        component: () => import('./views/DisplayAnimal.vue')
    },
    {
        path: "/getanimal",
        name: "animal.get",
        component: () => import('./views/GetAnimal.vue')
    }
  ]
})

Focus on the name attribute, this is the route name you can use in template as given,

<router-link :to="{ name: 'animal'}">Animals</router-link>

Alternatively, here is the code to push new route,

router.push({ name: 'animal'})

If you don't want to go through naming all of the routes you can push the route path as router.push({ path: '/viewanimal' }), but the named routes are more clean approach.


问:
Help with updating vb.net formview using storedprocedure
I have followed this tutorial for the most part to explain what I am doing. http://www.asp.net/data-access/tutorials/creating-a-business-logic-layer-vb

What i need to do is figure out the best way to approach to be able to update my formview. I do not understand what the tutorial is trying to explain to me so i tried it the way i have updated a gridview before. But I am receiving "No parameterless constructor defined for this object." I tried to debug and view the callstack but it does not really tell me much.

I have my sql stored procedure to update which when executed works fine.

I also have another class in which i reference the application details class

applicant.vb

This is the code in order for when you click the view details link on the gridview it passes you off to another page that shows that applicants details it is within the same applicant.vb class

I am trying to update using the following method on the .aspx page but i receive the following error "No parameterless constructor defined for this object."

Memberdetails.aspx

答:
Without knowing which line of code is causing that error, I can't say for sure, however, my guess is that your error is on this line of code.

_applicantadapter = New applicantTableAdapter

Put an open parentheses after applicantTableAdapter to see the different constructor signatures available to you for that type.  I bet you'll see none of the options allow no parameters.

That error means that the object type you are trying to instantiate requires that you include parameter(s) (and you are not).


问:
Node error Cannot read property 'resolve' of undefined
I am using reactjs and am unable to install any packages using npm install. The error message I'm getting is :

```<code>npm ERR! Cannot read property 'resolve' of undefined

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/stash/.npm/_logs/2019-03-11T10_07_30_264Z-debug.log
</code>```

When I do npm install -verbose:

```<code>npm info it worked if it ends with ok
npm verb cli [ '/usr/local/bin/node',
npm verb cli   '/usr/local/bin/npm',
npm verb cli   'install',
npm verb cli   '-verbose' ]
npm info using npm@6.7.0
npm info using node@v11.10.1
npm verb npm-session 869376d36eca27b5
npm info lifecycle proj-lite@1.0.0-alpha.6~preinstall: proj-lite@1.0.0-alpha.6
npm timing stage:loadCurrentTree Completed in 22ms
npm timing stage:loadIdealTree:cloneCurrentTree Completed in 1ms
npm timing stage:loadIdealTree:loadShrinkwrap Completed in 1231ms
npm timing stage:rollbackFailedOptional Completed in 1ms
npm timing stage:runTopLevelLifecycles Completed in 2661ms
npm verb stack TypeError: Cannot read property 'resolve' of undefined
npm verb stack     at regFetch (/usr/local/lib/node_modules/npm/node_modules/npm-registry-fetch/index.js:76:23)
npm verb stack     at fetchPackument (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/packument.js:42:10)
npm verb stack     at packument (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/packument.js:20:10)
npm verb stack     at getManifest (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/manifest.js:22:10)
npm verb stack     at manifest (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/manifest.js:13:10)
npm verb stack     at Object.manifest (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/index.js:17:12)
npm verb stack     at Object.Fetcher#manifest [as manifest] (/usr/local/lib/node_modules/npm/node_modules/genfun/lib/genfun.js:15:38)
npm verb stack     at manifest (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetch.js:23:18)
npm verb stack     at pinflight (/usr/local/lib/node_modules/npm/node_modules/pacote/manifest.js:24:12)
npm verb stack     at /usr/local/lib/node_modules/npm/node_modules/promise-inflight/inflight.js:29:24
npm verb stack     at Promise._execute (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/debuggability.js:313:9)
npm verb stack     at Promise._resolveFromExecutor (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:483:18)
npm verb stack     at new Promise (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:79:10)
npm verb stack     at _inflight (/usr/local/lib/node_modules/npm/node_modules/promise-inflight/inflight.js:28:25)
npm verb stack     at /usr/local/lib/node_modules/npm/node_modules/promise-inflight/inflight.js:22:14
npm verb stack     at tryCatcher (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
npm verb cwd /var/www/html/lite-proj/lite-proj
npm verb Linux 4.4.0-142-generic
npm verb argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-verbose"
npm verb node v11.10.1
npm verb npm  v6.7.0
npm ERR! Cannot read property 'resolve' of undefined
npm verb exit [ 1, true ]
npm timing npm Completed in 3862ms

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/stash/.npm/_logs/2019-03-11T10_12_15_921Z-debug.log
</code>```

I am not even able to  uninstall npm and reinstall it as I am getting the same error when I try to uninstall. What is the issue here and how do I fix it?

答:
Anyone having this issue and have scrolled this far, if you are installing node manually and you have nvm installed then this might be the issue, don't do it manually, and don't uninstall nvm to fix the issue, just let nvm install the version for you rather than doing it manually, if you don't have nvm installed and you are lost trying upgrading/downgrading node/npm versions, then install nvm and let it handle all these things for you.

Use nvm install x.x.x, then nvm use x.x.x, and everything worked just fine.

more about nvm

Body:
I am using reactjs and am unable to install any packages using npm install. The error message I'm getting is :

npm ERR! Cannot read property 'resolve' of undefined

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/stash/.npm/_logs/2019-03-11T10_07_30_264Z-debug.log

When I do npm install -verbose:

npm info it worked if it ends with ok
npm verb cli [ '/usr/local/bin/node',
npm verb cli   '/usr/local/bin/npm',
npm verb cli   'install',
npm verb cli   '-verbose' ]
npm info using npm@6.7.0
npm info using node@v11.10.1
npm verb npm-session 869376d36eca27b5
npm info lifecycle proj-lite@1.0.0-alpha.6~preinstall: proj-lite@1.0.0-alpha.6
npm timing stage:loadCurrentTree Completed in 22ms
npm timing stage:loadIdealTree:cloneCurrentTree Completed in 1ms
npm timing stage:loadIdealTree:loadShrinkwrap Completed in 1231ms
npm timing stage:rollbackFailedOptional Completed in 1ms
npm timing stage:runTopLevelLifecycles Completed in 2661ms
npm verb stack TypeError: Cannot read property 'resolve' of undefined
npm verb stack     at regFetch (/usr/local/lib/node_modules/npm/node_modules/npm-registry-fetch/index.js:76:23)
npm verb stack     at fetchPackument (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/packument.js:42:10)
npm verb stack     at packument (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/packument.js:20:10)
npm verb stack     at getManifest (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/manifest.js:22:10)
npm verb stack     at manifest (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/manifest.js:13:10)
npm verb stack     at Object.manifest (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetchers/registry/index.js:17:12)
npm verb stack     at Object.Fetcher#manifest [as manifest] (/usr/local/lib/node_modules/npm/node_modules/genfun/lib/genfun.js:15:38)
npm verb stack     at manifest (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/fetch.js:23:18)
npm verb stack     at pinflight (/usr/local/lib/node_modules/npm/node_modules/pacote/manifest.js:24:12)
npm verb stack     at /usr/local/lib/node_modules/npm/node_modules/promise-inflight/inflight.js:29:24
npm verb stack     at Promise._execute (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/debuggability.js:313:9)
npm verb stack     at Promise._resolveFromExecutor (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:483:18)
npm verb stack     at new Promise (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:79:10)
npm verb stack     at _inflight (/usr/local/lib/node_modules/npm/node_modules/promise-inflight/inflight.js:28:25)
npm verb stack     at /usr/local/lib/node_modules/npm/node_modules/promise-inflight/inflight.js:22:14
npm verb stack     at tryCatcher (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
npm verb cwd /var/www/html/lite-proj/lite-proj
npm verb Linux 4.4.0-142-generic
npm verb argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "-verbose"
npm verb node v11.10.1
npm verb npm  v6.7.0
npm ERR! Cannot read property 'resolve' of undefined
npm verb exit [ 1, true ]
npm timing npm Completed in 3862ms

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/stash/.npm/_logs/2019-03-11T10_12_15_921Z-debug.log

I am not even able to  uninstall npm and reinstall it as I am getting the same error when I try to uninstall. What is the issue here and how do I fix it?


问:
Flutter - Pop until a screen without route
I have a Flutter app that starts like this :

```<code>void main() async {

  // Check if user is logged in

  runApp(
    MaterialApp(
      home: (isLoggedIn) ? MainPage() : PageLogin(),
    ),
  );
}
</code>```

My MainPage (and my LoginPage) are just 2 regular Stateful Widgets.

```<code>class MainPage extends StatefulWidget {
  MainPage({Key key, this.selectedPageDefault = 0}) : super(key: key);

  @override
  _MainPageState createState() => _MainPageState();
}
</code>```

Let's say I have 2 more pages, just like MainPage : PageOne and PageTwo.

When I click on a button on MainPage, it takes me to PageOne, and when I click on a button on PageOne, it takes me to PageTwo.

I go to them using :

```<code>Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) => PageOne(), // Or PageTwo
  ),
);
</code>```

Now, when I click on a button in PageTwo, I want to go back to MainPage.

I could use Navigator.of(context).popUntil(...), however it needs to use routes, and I did not go to MainPage using a route.

This is just an example, but on the real app I have more than just 2 pages after MainPage, so I can't just use pushReplacement or a tricky way to achieve this.

How can I go back to MainPage ?

答: Use this Navigator.of(context).popUntil((route) => route.isFirst)

Body:
I have a Flutter app that starts like this :

void main() async {

  // Check if user is logged in

  runApp(
    MaterialApp(
      home: (isLoggedIn) ? MainPage() : PageLogin(),
    ),
  );
}

My MainPage (and my LoginPage) are just 2 regular Stateful Widgets.

class MainPage extends StatefulWidget {
  MainPage({Key key, this.selectedPageDefault = 0}) : super(key: key);

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

Let's say I have 2 more pages, just like MainPage : PageOne and PageTwo.

When I click on a button on MainPage, it takes me to PageOne, and when I click on a button on PageOne, it takes me to PageTwo.

I go to them using :

Navigator.of(context).push(
  MaterialPageRoute(
    builder: (context) => PageOne(), // Or PageTwo
  ),
);

Now, when I click on a button in PageTwo, I want to go back to MainPage.

I could use Navigator.of(context).popUntil(...), however it needs to use routes, and I did not go to MainPage using a route.

This is just an example, but on the real app I have more than just 2 pages after MainPage, so I can't just use pushReplacement or a tricky way to achieve this.

How can I go back to MainPage ?


问:
Access and disable ToolStripItems (ToolStripButtons, ToolStripMenuItems) using their names
I would like to disable UI elements (Controls, Components etc.) which names are stored in a database.

My code works for Controls, but I would like to access (to disable them) ToolStripItems such as ToolStripButtons, ToolStripMenuItems etc..

This is my current code:

```<code>Dim df_command As New SqlCommand("select * from treftab where ref_data = 'INTERVENTION' and ref_code  = '0'", sfacon)
Dim df_reader As SqlDataReader = df_command.ExecuteReader

If df_reader.HasRows Then
    While df_reader.Read
        Dim reftext As String = df_reader("ref_text")
        Dim someVariable As Control = Nothing
        Dim SearchedControls = Me.Controls.Find(key:=reftext, searchAllChildren:=True)
        someVariable = SearchedControls(0)
        someVariable.Enabled = False
    End While
End If
</code>```

答:
The items collection of the ToolStrip and the derived controls, MenuStrip, ContextMenuStrip, StatusStrip is the ToolStripItemCollection which has a Find method for the deep search just like the ControlCollection.Find method. So you have to search this collection through the Items properties of the mentioned controls for a ToolStripItem or any derived type.

Create a search function for the mentioned classes:

Public Function GetToolStripItem(toolStrip As ToolStrip, key As String) As ToolStripItem
    Return toolStrip.Items.Find(key, True).FirstOrDefault
End Function
```

<p>... and call it as follows:</p>

<pre class="lang-vb prettyprint-override"><code>'Search a MenuStrip
Dim tsi = GetToolStripItem(MenuStrip1, key)

'Search a ToolStrip
Dim tsi = GetToolStripItem(ToolStrip1, key)

'Search a ContextMenuStrip
Dim tsi = GetToolStripItem(ContextMenuStrip1, key)

'Search a StatusStrip
Dim tsi = GetToolStripItem(StatusStrip1, key)

If tsi IsNot Nothing Then
    tsi.Enabled = False
End If
</code>```

Also, you can use the TypeOf operator to determine the type of an item:

If TypeOf tsi Is ToolStripMenuItem Then
    '...
End If

If TypeOf tsi Is ToolStripDropDownItem Then
    '...
End If

If TypeOf tsi Is ToolStripButton Then
    '...
End If
```

<p>... and use the <em>iterator functions</em> to get all or a specific type of items from the collections:</p>

<pre class="lang-vb prettyprint-override"><code>Public Iterator Function GetAllToolStripItems(items As ToolStripItemCollection) As _
    IEnumerable(Of ToolStripItem)
    For Each tsi As ToolStripItem In items
        Yield tsi

        If TypeOf tsi Is ToolStripDropDownItem Then
            For Each ddi As ToolStripItem In
            GetAllToolStripItems(DirectCast(tsi, ToolStripDropDownItem).DropDownItems)
                Yield ddi
            Next
        End If
    Next
End Function

Public Iterator Function GetAllToolStripItems(Of T)(items As ToolStripItemCollection) As _
    IEnumerable(Of T)
    For Each tsi In items
        If TypeOf tsi Is T Then
            Yield DirectCast(tsi, T)
        ElseIf TypeOf tsi Is ToolStripDropDownItem Then
            For Each ddi In
            GetAllToolStripItems(Of T)(DirectCast(tsi, ToolStripDropDownItem).DropDownItems)
                Yield ddi
            Next
        End If
    Next
End Function
</code>```

... and the usage:

'Get them all...
Dim items = GetAllToolStripItems(TooStrip1.Items) 'or any derived control...

'Get for example the ToolStripComboBox items...
Dim items = GetAllToolStripItems(Of ToolStripComboBox)(MenuStrip1.Items)
```

Note that in the iterators, identifying the ToolStripDropDownItem is necessary to get the ToolStripItemCollection of derived classes including:

ToolStripDropDownButton

ToolStripMenuItem

ToolStripSplitButton

Each of which inherits the DropDownItems property which of course should be passed to the iterator.

Body:
I would like to disable UI elements (Controls, Components etc.) which names are stored in a database.

My code works for Controls, but I would like to access (to disable them) ToolStripItems such as ToolStripButtons, ToolStripMenuItems etc..

This is my current code:

Dim df_command As New SqlCommand("select * from treftab where ref_data = 'INTERVENTION' and ref_code  = '0'", sfacon)
Dim df_reader As SqlDataReader = df_command.ExecuteReader

If df_reader.HasRows Then
    While df_reader.Read
        Dim reftext As String = df_reader("ref_text")
        Dim someVariable As Control = Nothing
        Dim SearchedControls = Me.Controls.Find(key:=reftext, searchAllChildren:=True)
        someVariable = SearchedControls(0)
        someVariable.Enabled = False
    End While
End If

Body:
The items collection of the ToolStrip and the derived controls, MenuStrip, ContextMenuStrip, StatusStrip is the ToolStripItemCollection which has a Find method for the deep search just like the ControlCollection.Find method. So you have to search this collection through the Items properties of the mentioned controls for a ToolStripItem or any derived type.

Create a search function for the mentioned classes:

Public Function GetToolStripItem(toolStrip As ToolStrip, key As String) As ToolStripItem
    Return toolStrip.Items.Find(key, True).FirstOrDefault
End Function

... and call it as follows:

'Search a MenuStrip
Dim tsi = GetToolStripItem(MenuStrip1, key)

'Search a ToolStrip
Dim tsi = GetToolStripItem(ToolStrip1, key)

'Search a ContextMenuStrip
Dim tsi = GetToolStripItem(ContextMenuStrip1, key)

'Search a StatusStrip
Dim tsi = GetToolStripItem(StatusStrip1, key)

If tsi IsNot Nothing Then
    tsi.Enabled = False
End If

Also, you can use the TypeOf operator to determine the type of an item:

If TypeOf tsi Is ToolStripMenuItem Then
    '...
End If

If TypeOf tsi Is ToolStripDropDownItem Then
    '...
End If

If TypeOf tsi Is ToolStripButton Then
    '...
End If

... and use the iterator functions to get all or a specific type of items from the collections:

Public Iterator Function GetAllToolStripItems(items As ToolStripItemCollection) As _
    IEnumerable(Of ToolStripItem)
    For Each tsi As ToolStripItem In items
        Yield tsi

        If TypeOf tsi Is ToolStripDropDownItem Then
            For Each ddi As ToolStripItem In
            GetAllToolStripItems(DirectCast(tsi, ToolStripDropDownItem).DropDownItems)
                Yield ddi
            Next
        End If
    Next
End Function

Public Iterator Function GetAllToolStripItems(Of T)(items As ToolStripItemCollection) As _
    IEnumerable(Of T)
    For Each tsi In items
        If TypeOf tsi Is T Then
            Yield DirectCast(tsi, T)
        ElseIf TypeOf tsi Is ToolStripDropDownItem Then
            For Each ddi In
            GetAllToolStripItems(Of T)(DirectCast(tsi, ToolStripDropDownItem).DropDownItems)
                Yield ddi
            Next
        End If
    Next
End Function

... and the usage:

'Get them all...
Dim items = GetAllToolStripItems(TooStrip1.Items) 'or any derived control...

'Get for example the ToolStripComboBox items...
Dim items = GetAllToolStripItems(Of ToolStripComboBox)(MenuStrip1.Items)

Note that in the iterators, identifying the ToolStripDropDownItem is necessary to get the ToolStripItemCollection of derived classes including:

ToolStripDropDownButton

ToolStripMenuItem

ToolStripSplitButton

Each of which inherits the DropDownItems property which of course should be passed to the iterator.


问:
Update existing table of contents and table of tables officer r
Is there a way using officer to update an existing table of contents and table of tables with in my document? I know about the function body_add_toc() but is there a way to update these elements without having to recreate them?

答:
As far as I'm aware David is correct.

If you need to automate this process you can use the update_toc(x) function found in the officerWinTools R package.

The officerWinTools R package requires a Windows operating system with Microsoft Office installed (the functions of this package rely upon VBScript ran in Command Prompt).

The update_toc(x) function is also embedded in the print_docx_pdf(x, target = "path") function which will export a document created with the officer R package as a .PDF to a given path.

You can install the officerWinTools R package from GitHub:

devtools::install_github("joshmire/officerWinTools")
```

Also, shout outs to David; your R packages have made my work much less of a headache.

Body:
As far as I'm aware David is correct.

If you need to automate this process you can use the update_toc(x) function found in the officerWinTools R package.

The officerWinTools R package requires a Windows operating system with Microsoft Office installed (the functions of this package rely upon VBScript ran in Command Prompt).

The update_toc(x) function is also embedded in the print_docx_pdf(x, target = "path") function which will export a document created with the officer R package as a .PDF to a given path.

You can install the officerWinTools R package from GitHub:

devtools::install_github("joshmire/officerWinTools")

Also, shout outs to David; your R packages have made my work much less of a headache.


问:
Trying to run 2 queries in one connection
I have a small piece of code I am trying to run in which I first check if the value exists and then update my database if it does not. My problem is I can run one query or the other but not both, because then it states the database is open and cannot be accessed. I know for sure I can write to the database. It is not read protected, located where I can't access it etc. The routine runs if I just try to update and not check. The check definitely results in no record. I have tried separate routines using completely different variables for the connection. I am stumped big time. I have tried closing, using, disposing, but I need someone a lot smarter than me to advise me of what I am doing wrong...

```<code>For Each strfile As String In flist
    Dim pth As String = Path.GetDirectoryName(strfile)
    Dim objReader As New System.IO.StreamReader(strfile)
    Dim dVal As String = String.Empty
    TextLine = objReader.ReadLine()
    SplitLine = Split(TextLine, ",")
    dVal = SplitLine(1)

    Using Dcon As New OleDbConnection
        Dcon.ConnectionString = dbProvider
        Dcon.Open()

        Dim q1 As String = "SELECT Shares.[_Date] FROM Shares WHERE (((Shares.[_Date])=" & dVal & "))"
        Dim comd As OleDbCommand = New OleDbCommand(q1, Dcon)
        comd.ExecuteReader()

        Dim q2 As String = "INSERT INTO Shares (Code, _Date, _Open, _High, _Low, _Close, _Volume) " &
                                                                  "SELECT F1, F2, F3, F4, F5, F6, F7 FROM [Text;HDR=NO;DATABASE=" & pth & "].[" & Path.GetFileName(strfile) & "];"

        Dim cmd As OleDbCommand = New OleDbCommand(q2, Dcon)

        cmd.ExecuteNonQuery()
        Dcon.Close()
    End Using
Next
</code>```

I have tried separate routines, I have tried opening, closing and then re-opening. I have tried one connection, I have tried two. Does anybody know what I am doing wrong and why it keeps telling me the database is exclusively opened and why it won't let me write to it?

Thank you in advance to those who help.

答:
I use this code when I try to execute multiple sql-statements:

Dim ConnectionString As String = ("Connection_String")
        'LoginsVal is a Table,
        Dim SqlStr1 As String = ("Select Count(Accounts.DtCrtd) FROM Accounts WHERE Accounts.DtCrtd > " & Now.Date & ";")
        Dim SqlStr2 As String = ("INSERT INTO LoginsVal(LoginNm,DtMdfd) VALUES ('Test1'," & Now.Date & ");")
        'DtCtrtd is Date DataType, Accounts is the Table Name
        Dim ThisCmd1, ThisCmd2 As New OleDbCommand
        Using ThisConn As New OleDbConnection With {.ConnectionString = ConnectionString}
            ThisConn.Open() 'Open connection
            With ThisCmd1
                .Connection = ThisConn
                .CommandType = CommandType.Text
                .CommandText = SqlStr1
            End With
            'Debug.WriteLine(ThisCmd1.ExecuteScalar) 'use to test only without if statement below.
            If Convert.ToInt32(ThisCmd1.ExecuteScalar) <= 0 Then
                Debug.WriteLine("No records found")
            Else
                'Your Next SqlStatement
                With ThisCmd2
                    .Connection = ThisConn
                    .CommandType = CommandType.Text
                    .CommandText = SqlStr2
                End With
                Debug.WriteLine("Num of Rows affects is : " & ThisCmd2.ExecuteNonQuery)
            End If
            ThisCmd1.Dispose()
            ThisCmd2.Dispose()
            ThisConn.Close() 'Close connection
        End Using
```

Body:
I have a small piece of code I am trying to run in which I first check if the value exists and then update my database if it does not. My problem is I can run one query or the other but not both, because then it states the database is open and cannot be accessed. I know for sure I can write to the database. It is not read protected, located where I can't access it etc. The routine runs if I just try to update and not check. The check definitely results in no record. I have tried separate routines using completely different variables for the connection. I am stumped big time. I have tried closing, using, disposing, but I need someone a lot smarter than me to advise me of what I am doing wrong...

For Each strfile As String In flist
    Dim pth As String = Path.GetDirectoryName(strfile)
    Dim objReader As New System.IO.StreamReader(strfile)
    Dim dVal As String = String.Empty
    TextLine = objReader.ReadLine()
    SplitLine = Split(TextLine, ",")
    dVal = SplitLine(1)

    Using Dcon As New OleDbConnection
        Dcon.ConnectionString = dbProvider
        Dcon.Open()

        Dim q1 As String = "SELECT Shares.[_Date] FROM Shares WHERE (((Shares.[_Date])=" & dVal & "))"
        Dim comd As OleDbCommand = New OleDbCommand(q1, Dcon)
        comd.ExecuteReader()

        Dim q2 As String = "INSERT INTO Shares (Code, _Date, _Open, _High, _Low, _Close, _Volume) " &
                                                                  "SELECT F1, F2, F3, F4, F5, F6, F7 FROM [Text;HDR=NO;DATABASE=" & pth & "].[" & Path.GetFileName(strfile) & "];"

        Dim cmd As OleDbCommand = New OleDbCommand(q2, Dcon)

        cmd.ExecuteNonQuery()
        Dcon.Close()
    End Using
Next

I have tried separate routines, I have tried opening, closing and then re-opening. I have tried one connection, I have tried two. Does anybody know what I am doing wrong and why it keeps telling me the database is exclusively opened and why it won't let me write to it?

Thank you in advance to those who help.


问:
What is the standard (or best supported) big number (arbitrary precision) library for Lua?
I'm working with large numbers that I can't have rounded off.  Using Lua's standard math library, there seem to be no convenient way to preserve precision past some internal limit.  I also see there are several libraries that can be loaded to work with big numbers:

http://oss.digirati.com.br/luabignum/

http://www.tc.umn.edu/~ringx004/mapm-main.html

http://lua-users.org/lists/lua-l/2002-02/msg00312.html (might be identical to #2)

http://www.gammon.com.au/scripts/doc.php?general=lua_bc (but I can't find any source)

Further, there are many libraries in C that could be called from Lua, if the bindings where established.

Have you had any experience with one or more of these libraries?

答:
I used Norman Ramsey's suggestion to solve Project Euler problem #16.  I don't think it's a spoiler to say that the crux of the problem is calculating a 303 digit integer accurately.

Here are the steps I needed to install and use the library:

Lua needs to be built with dynamic loading enabled.  I use Cygwin, but I changed PLAT in src/Makefile to be linux.  The default, none, doesn't enable dynamic loading.

The MAMP needs to be built and installed somewhere that your C compiler can find it.  I put libmapm.a in /usr/local/lib/.  Next m_apm.h and m_apm_lc.h went to /usr/local/include/.

The makefile for lmamp needs to be altered to the correct location of the Lua and MAMP libraries.  For me, that means uncommenting the second declaration of LUA,  LUAINC, LUALIB, and LUABIN and editing the declaration of MAMP.

Finally, mapm.so needs to be placed somewhere that Lua will find it.  I put it at /usr/local/lib/lua/5.1/.

Thank you all for the suggestions!

OwnerDisplayName: Jon Ericson

ContentLicense: CC BY-SA 2.5