问:
Missing required argument "[authorizer-properties]" apache kafka simple producer api error
While writing kafka producer code inside eclipse I am getting a error mention below,Here I want to write a simple producer code and show the message on kafka console consumer I started the zookeeper and kafka server and created topic perfectly.

Here is code:

```<code>import java.util.Properties;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;

public class ProducerTest {
    public static void mian(String ar[]){
        Properties prop=new Properties();

        prop.put("zk.connect","localhost:2181");
        prop.put("serializer.class","kafka.serializer.StringEncoder");
        prop.put("metadata.broker.list","localhost:9092");

        ProducerConfig config=new ProducerConfig(prop);

        Producer producer=new Producer(config);

        String msg="Sa resta rasta ra";

        producer.send(new KeyedMessage("test",msg));
    }
}

Missing required argument "[authorizer-properties]"
Option                                  Description
----*emphasized text*--                                  -----------
--add                                   Indicates you are trying to add ACLs.
--allow-host <allow-host>               Host from which principals listed in --
                                       allow-principal will have access. If
                                        you have specified --allow-principal
                                         then the default for this option
                                          will be set to * which allows access
                                          from all hosts.
--allow-principal <allow-principal>     principal is in principalType:name
                                         format. User:* is the wild card
</code>```

Anyone please help me to solve this error.

答:
I don't know why I was getting this error message But now it's gone automatically I just create separated method for connection and call this method from the main method.</p>

```<code> public static void main(String ar[]){
 ProducerTest producer=new ProducerTest();
 producer.messageConnetion();
 }

 public void messageConnetion(){
 Properties properties=new Properties();

 properties.put("zk.connect","localhost:8121");
 properties.put("serializer.class","kafka.serializer.StringEncoder");
 properties.put("metadata.broker.list","localhost:9092");

 ProducerConfig config=new ProducerConfig(prop);

 Producer<String, String> producer=new Producer<String, String> (config)

 producer.send(new KeyedMessage<String, String> ("test","JaySiyaRam"));
}
</code>```

Body:
While writing kafka producer code inside eclipse I am getting a error mention below,Here I want to write a simple producer code and show the message on kafka console consumer I started the zookeeper and kafka server and created topic perfectly.

Here is code:

import java.util.Properties;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;

public class ProducerTest {
    public static void mian(String ar[]){
        Properties prop=new Properties();

        prop.put("zk.connect","localhost:2181");
        prop.put("serializer.class","kafka.serializer.StringEncoder");
        prop.put("metadata.broker.list","localhost:9092");

        ProducerConfig config=new ProducerConfig(prop);

        Producer producer=new Producer(config);

        String msg="Sa resta rasta ra";

        producer.send(new KeyedMessage("test",msg));
    }
}

Missing required argument "[authorizer-properties]"
Option                                  Description
----*emphasized text*--                                  -----------
--add                                   Indicates you are trying to add ACLs.
--allow-host <allow-host>               Host from which principals listed in --
                                       allow-principal will have access. If
                                        you have specified --allow-principal
                                         then the default for this option
                                          will be set to * which allows access
                                          from all hosts.
--allow-principal <allow-principal>     principal is in principalType:name
                                         format. User:* is the wild card

Anyone please help me to solve this error.

Body:
I don't know why I was getting this error message But now it's gone automatically I just create separated method for connection and call this method from the main method.

 public static void main(String ar[]){
 ProducerTest producer=new ProducerTest();
 producer.messageConnetion();
 }

 public void messageConnetion(){
 Properties properties=new Properties();

 properties.put("zk.connect","localhost:8121");
 properties.put("serializer.class","kafka.serializer.StringEncoder");
 properties.put("metadata.broker.list","localhost:9092");

 ProducerConfig config=new ProducerConfig(prop);

 Producer<String, String> producer=new Producer<String, String> (config)

 producer.send(new KeyedMessage<String, String> ("test","JaySiyaRam"));
}


来源: stackexchange

问:
A new table in R based on fields and data from existing one
I need to raise the question again as it was closed as duplicated, but the issue hasn't been resolved.

So, I'm working on international trade data and have the following table at the moment with 5 different values for commodity_code (commod_codes = c('85','84','87','73','29')):

```<code>year trade_flow reporter partner commodity_code                 commodity trade_value_usd
1 2012     Import  Belarus   China             29         Organic chemicals       150863100
2 2013     Import  Belarus   China             29         Organic chemicals       151614000
3 2014     Import  Belarus   China             29         Organic chemicals        73110200
4 2015     Import  Belarus   China             29         Organic chemicals       140396300
5 2016     Import  Belarus   China             29         Organic chemicals       135311600
6 2012     Import  Belarus   China             73 Articles of iron or steel       100484600
</code>```

I need to create a new table that looks simple (commodity codes in top row, years in first column and corresponding trade values in cells):

```<code>year             commodity_code
             29   73  84  85  87
1998        value1      ...   value 5
1999
…
2016
</code>```

* I used reshape() but didn't succeed.

Would appreciate your support.

答:
In case there are duplicate permutations, I would suggest to use this code (though not in base R - uses dplyr and tidyr packages)</p>

```<code>as.data.frame(trade_data[,c("year","commodity_code","trade_value_usd")] %>% group_by (year,commodity_code)%>% summarise( sum(trade_value_usd))%>%spread(commodity_code,3))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I need to raise the question again as it was closed as duplicated, but the issue hasn't been resolved.

So, I'm working on international trade data and have the following table at the moment with 5 different values for commodity_code (commod_codes = c('85','84','87','73','29')):

year trade_flow reporter partner commodity_code                 commodity trade_value_usd
1 2012     Import  Belarus   China             29         Organic chemicals       150863100
2 2013     Import  Belarus   China             29         Organic chemicals       151614000
3 2014     Import  Belarus   China             29         Organic chemicals        73110200
4 2015     Import  Belarus   China             29         Organic chemicals       140396300
5 2016     Import  Belarus   China             29         Organic chemicals       135311600
6 2012     Import  Belarus   China             73 Articles of iron or steel       100484600

I need to create a new table that looks simple (commodity codes in top row, years in first column and corresponding trade values in cells):

year             commodity_code
             29   73  84  85  87
1998        value1      ...   value 5
1999
…
2016

* I used reshape() but didn't succeed.

Would appreciate your support.

Body:
In case there are duplicate permutations, I would suggest to use this code (though not in base R - uses dplyr and tidyr packages)

as.data.frame(trade_data[,c("year","commodity_code","trade_value_usd")] %>% group_by (year,commodity_code)%>% summarise( sum(trade_value_usd))%>%spread(commodity_code,3))


问:
R : How to resolve invalid subscript type 'list'
Origianl dataframe is

```<code>id status name ...
1  0      V
1  0      S
1  1      V
1  0      V
2  0      V
2  1      V
2  1      S
3  0      V
3  1      S
4  1      S
4  0      V
4  1      V
</code>```

Out of this, I expect to fetch id 2 and 3 as in their subset I have a "0-V" combination followed by "1-S"

I have split that into a list of dataframes and I want to fetch the id's for some particular conditions on those dataframes but I get the error

```<code>invalid subscript type 'list'
</code>```

The structure is like follows

```<code>"1"
id status name ...
1  0      V
1  0      S
1  1      V
1  0      V

"2"
id status name ...
2  0      V
2  1      V
2  1      S
...
</code>```

Now I need to find a condition such that I get the id where there is a record of 0 status and name 'V' followed by a 1 status and name "S" like for id 2.

For doing so, I'm trying to write a function for sapply but I'm not able to subscript the data as I'm assuming it to be

Here is the code

```<code>q4 <- result1[,c("id", "name", "date", "status")]

lstQ <- split(q4, result1$id)

f3 <- function(g) {
  g[g$status == 0 & g$name == "V",]
}

 e <- as.data.frame(names(lstQ)[sapply(lstQ, f3)])
</code>```

How can I subscript my dataframe to get the desired check condition?

答:
Your data:

```<code>DF <- read.table(text = "id status name
                 1  0      V
                 1  0      S
                 1  1      V
                 1  0      V
                 2  0      V
                 2  1      V
                 2  1      S
                 3  0      V
                 3  1      S
                 4  1      S
                 4  0      V
                 4  1      V", header = TRUE)
</code>```

Let's write a function:

```<code>fun <- function(DF) {
  one <- DF$status == 0 & DF$name == "V"
  two <- DF$status == 1 & DF$name == "S"

  #Is two TRUE after one is TRUE?
  if (any(one) && any(two)) return(any(which(two) > which.max(one)))
  return(FALSE)
}
</code>```

Use a "group by" type function. I like data.table, others prefer dplyr:

```<code>library(data.table)
setDT(DF)
DF[, fun(.SD), by = id]
#   id    V1
#1:  1 FALSE
#2:  2  TRUE
#3:  3  TRUE
#4:  4 FALSE
</code>```

You can then use setDF if you prefer or keep working with data.table and its syntax. Subsetting could be the trivial next step.

Body:
Origianl dataframe is

id status name ...
1  0      V
1  0      S
1  1      V
1  0      V
2  0      V
2  1      V
2  1      S
3  0      V
3  1      S
4  1      S
4  0      V
4  1      V

Out of this, I expect to fetch id 2 and 3 as in their subset I have a "0-V" combination followed by "1-S"

I have split that into a list of dataframes and I want to fetch the id's for some particular conditions on those dataframes but I get the error

invalid subscript type 'list'

The structure is like follows

"1"
id status name ...
1  0      V
1  0      S
1  1      V
1  0      V

"2"
id status name ...
2  0      V
2  1      V
2  1      S
...

Now I need to find a condition such that I get the id where there is a record of 0 status and name 'V' followed by a 1 status and name "S" like for id 2.

For doing so, I'm trying to write a function for sapply but I'm not able to subscript the data as I'm assuming it to be

Here is the code

q4 <- result1[,c("id", "name", "date", "status")]

lstQ <- split(q4, result1$id)

f3 <- function(g) {
  g[g$status == 0 & g$name == "V",]
}

 e <- as.data.frame(names(lstQ)[sapply(lstQ, f3)])

How can I subscript my dataframe to get the desired check condition?

Body:
Your data:

DF <- read.table(text = "id status name
                 1  0      V
                 1  0      S
                 1  1      V
                 1  0      V
                 2  0      V
                 2  1      V
                 2  1      S
                 3  0      V
                 3  1      S
                 4  1      S
                 4  0      V
                 4  1      V", header = TRUE)

Let's write a function:

fun <- function(DF) {
  one <- DF$status == 0 & DF$name == "V"
  two <- DF$status == 1 & DF$name == "S"

  #Is two TRUE after one is TRUE?
  if (any(one) && any(two)) return(any(which(two) > which.max(one)))
  return(FALSE)
}

Use a "group by" type function. I like data.table, others prefer dplyr:

library(data.table)
setDT(DF)
DF[, fun(.SD), by = id]
#   id    V1
#1:  1 FALSE
#2:  2  TRUE
#3:  3  TRUE
#4:  4 FALSE

You can then use setDF if you prefer or keep working with data.table and its syntax. Subsetting could be the trivial next step.


问:
Clear table before reloding the data in a table
I am trying to bind data from the database. what is happening is that it binds every 5 seconds. Now its binding properly but it does not clear the earlier data. it keeps pilling up. So if there is 3 rows .. it needs to show only 3 rows. now what is happening is it is adding 3 rows every 5 seconds and keeps pilling 6-9-12 every 5 seconds.
I need to clear the data and then load every 5 seconds.</p>

```<code><script type="text/javascript">
        $(document).ready(function () {
            Get();
            setInterval(function () {
                Get() // this will run after every 5 seconds
            }, 5000);
        });

    function Get() {
        $.ajax({
            type: "POST",
            url: "../adminpage/noti.ashx",
            data: {},
            dataType: "json",
            success: function (response) {
                $.each(response, function (index, itemData) {
                    var tr = "<tr>" +
                                  "<td>" + itemData.msg + "</td>" +
                                  "<td>" + itemData.dt + "</td>" +
                                  "</tr>";

                    $("#testTable").find("tbody").append(tr);
                });

                BindTable();
            }
        });
    }
    function BindTable() {

        try {
            $('#testTable thead th').each(function (i) {
                var title = $('#testTable thead th').eq($(this).index()).text();

                if (title != "") {
                    $(this).html('<div style="width:40%;text-align:center;white-space:nowrap">' + title + '</div>');
                }
            });

        }
        catch (e) { }
    }
</script>

<table id="testTable" class="display" cellspacing="0" width="100%">
                                        <thead>
                                            <tr>
                                                <th class="m-list-timeline__text" style="width:70%">msg</th>
                                                <th class="m-list-timeline__time" style="width:30%">dt</th>
                                            </tr>
                                        </thead>
                                          <tbody></tbody>
                                    </table>
</code>```

答:
Try clearing all
nodes from your tbody before you append your results:

```<code>success: function (response) {
    $("#testTable").find("tbody").empty(); //clear all the content from tbody here.
    $.each(response, function (index, itemData) {
         /*do stuff*/
         $("#testTable").find("tbody").append(tr);
    });
    BindTable();
}
</code>```

Body:
I am trying to bind data from the database. what is happening is that it binds every 5 seconds. Now its binding properly but it does not clear the earlier data. it keeps pilling up. So if there is 3 rows .. it needs to show only 3 rows. now what is happening is it is adding 3 rows every 5 seconds and keeps pilling 6-9-12 every 5 seconds.
I need to clear the data and then load every 5 seconds.

                                                msg
                                                dt

Body:
Try clearing all <tr>nodes from your tbody before you append your results:

success: function (response) {
    $("#testTable").find("tbody").empty(); //clear all the content from tbody here.
    $.each(response, function (index, itemData) {
         /*do stuff*/
         $("#testTable").find("tbody").append(tr);
    });
    BindTable();
}


问:
Setup Min Date in Bootstrap Datepicker
In My case i want to change mindate dynamically when changing of one input

```<code>$('#text1').on('changeDate', function () {
                var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                (<any>$("#LossDate")).datepicker('minDate', sdate.format("MM-DD-YYYY"));
            });
</code>```

i am also try with

```<code>$('#text1').on('changeDate', function () {
                    var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                    (<any>$("#LossDate")).datepicker('setStartDate', sdate.format("MM-DD-YYYY"));
                });
</code>```

and

```<code> $('#text1').on('changeDate', function () {
                        var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                        (<any>$("#LossDate")).datepicker('startDate', sdate.format("MM-DD-YYYY"));
                    });
</code>```

and

```<code> $('#text1').on('changeDate', function () {
                            var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                            (<any>$("#LossDate")).datepicker('SetstartDate', sdate.format("MM-DD-YYYY"));
                        });
</code>```

but nothing is working in my case

答:
Here is the working javascript:

$(document).ready(function(){

    $("#startdate").datepicker({
        todayBtn:  1,
        autoclose: true,
    }).on('changeDate', function (selected) {
        var minDate = new Date(selected.date.valueOf());
        $('#enddate').datepicker('setStartDate', minDate);
    });

    $("#enddate").datepicker()
        .on('changeDate', function (selected) {
            var minDate = new Date(selected.date.valueOf());
            $('#startdate').datepicker('setEndDate', minDate);
        });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.0/css/bootstrap-datepicker.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.0/js/bootstrap-datepicker.min.js"></script>

<div class="row">
    <div class="col-xs-6">
        <div class="form-group">
            <label class="control-label">Start</label>
            <input class="form-control" type="text" placehoder="Start Date" id="startdate"/>
        </div>
    </div>
    <div class="col-xs-6">
        <div class="form-group">
            <label class="control-label">End</label>
            <input class="form-control" type="text" placehoder="End Date" id="enddate"/>
        </div>
    </div>
</div></code>```

Happy Coding

Title: Setup Min Date in Bootstrap Datepicker

Body:
In My case i want to change mindate dynamically when changing of one input

$('#text1').on('changeDate', function () {
                var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                (<any>$("#LossDate")).datepicker('minDate', sdate.format("MM-DD-YYYY"));
            });

i am also try with

$('#text1').on('changeDate', function () {
                    var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                    (<any>$("#LossDate")).datepicker('setStartDate', sdate.format("MM-DD-YYYY"));
                });

and

 $('#text1').on('changeDate', function () {
                        var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                        (<any>$("#LossDate")).datepicker('startDate', sdate.format("MM-DD-YYYY"));
                    });

and

 $('#text1').on('changeDate', function () {
                            var sdate = moment.utc((<any>$('#text1')).datepicker('getFormattedDate')).subtract(1, "days");
                            (<any>$("#LossDate")).datepicker('SetstartDate', sdate.format("MM-DD-YYYY"));
                        });

but nothing is working in my case

Body:
Here is the working javascript:

$(document).ready(function(){

    $("#startdate").datepicker({
        todayBtn:  1,
        autoclose: true,
    }).on('changeDate', function (selected) {
        var minDate = new Date(selected.date.valueOf());
        $('#enddate').datepicker('setStartDate', minDate);
    });

    $("#enddate").datepicker()
        .on('changeDate', function (selected) {
            var minDate = new Date(selected.date.valueOf());
            $('#startdate').datepicker('setEndDate', minDate);
        });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.0/css/bootstrap-datepicker.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.4.0/js/bootstrap-datepicker.min.js"></script>

<div class="row">
    <div class="col-xs-6">
        <div class="form-group">
            <label class="control-label">Start</label>
            <input class="form-control" type="text" placehoder="Start Date" id="startdate"/>
        </div>
    </div>
    <div class="col-xs-6">
        <div class="form-group">
            <label class="control-label">End</label>
            <input class="form-control" type="text" placehoder="End Date" id="enddate"/>
        </div>
    </div>
</div>

Happy Coding


问:
SQLite - alter a table's column type?
I am starting a project involving a small database and I am considering to use SQLite.
If I create a table and I defined one of the columns as text, but all the values stored are integers - is there a way to change the data type of a column? I am using SQLite Manager and I can't find a function that allows me to do that. Can I do it using a SQL command, or is it a restriction of SQLite?
Probably, even with this restriction, one can find some way around and create a new table with the required column types and then import data into it.

Regards,
Nick

答:
Alter table in SqliteManger

Steps

Open database in sqlite manage

double click on table name

will popup alter window.

Title: SQLite - alter a table's column type?


问:
when to set a table without primary key on a join table
Hey I am using the following tables. My table course_enrollments references the user_id and the course_id. Both columns combined are set unique.

users

course_enrollments

courses

Rails sets primary keys by default. I have read some articles of people who used these kind of join tables without any pk. e.g. by defining :id => false

Is it appropriate for this kind of join table? what about people enrolling or leaving courses or the search for enrollments. Thanks for your time!

答:
You generally see :id => false on the migration for your join table when you want to use has_and_belongs_to_many, since Rails really doesn't like finding an :id primary key on these.

From the has_and_belongs_to_many docs

The join table should not have a
  primary key or a model associated with
  it.

ContentLicense: CC BY-SA 2.5


问:
Map function in NodeJS not working as expected
I am trying to migrate some data from an old MongoDB schema to a new one.  All the schema stuff is working fine.  What I cannot understand is why the old documents are not being converted before being saved as new documents.  I am reading all the documents, using a map function to convert them to the new schema then saving them.  But they are all failing validation because, it turns out, they haven't been modified to the new schema at all.  Is this an async issue?  Any clues would be great.</p>

```<code>let User = require('./api/models/user.model');

let newUser;
let mapUsers = () => {

    let makeUser = (u) => {
        return {
            firstName: u.first_name,
            lastName: u.last_name,
            avatarUrl: u.avatar_url,
            email: u.email,
            loginCount: u.login_count,
            loginTime: u.login_time,
            logoutTime: u.logout_time
        }
    };
    h2User.find({}).limit(1).exec((err, users) => {
        if (err) {
            console.error(err);
        } else {
            users.map(user => {
                newUser = new User(makeUser(user));  // like this doesn't work
                newUser.save((err, nu) => {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log(nu._id)
                    }
                });
            });
        }
    });
};

mapUsers();
</code>```

答:
You would have to convert the Mongo document into an object with new User(makeUser(user.toObject())).

As Mongoose returns a document, it will contain other attributes that may not be apparent. When you do console.log(user) it usually prints the output of toObject so it can get confusing.

Body:
I am trying to migrate some data from an old MongoDB schema to a new one.  All the schema stuff is working fine.  What I cannot understand is why the old documents are not being converted before being saved as new documents.  I am reading all the documents, using a map function to convert them to the new schema then saving them.  But they are all failing validation because, it turns out, they haven't been modified to the new schema at all.  Is this an async issue?  Any clues would be great.

let User = require('./api/models/user.model');

let newUser;
let mapUsers = () => {

    let makeUser = (u) => {
        return {
            firstName: u.first_name,
            lastName: u.last_name,
            avatarUrl: u.avatar_url,
            email: u.email,
            loginCount: u.login_count,
            loginTime: u.login_time,
            logoutTime: u.logout_time
        }
    };
    h2User.find({}).limit(1).exec((err, users) => {
        if (err) {
            console.error(err);
        } else {
            users.map(user => {
                newUser = new User(makeUser(user));  // like this doesn't work
                newUser.save((err, nu) => {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log(nu._id)
                    }
                });
            });
        }
    });
};

mapUsers();


问:
ORMLite DISTINCT With Where Condition
I am developing an android project using ORMLite and i have a problem to figure out. There is a picture below and how can i use DISTINCT sql query in ORMLite?
I have some parameters giving to where condition and according to this conditions i am getting number list...

In this picture you are going to see some numbers and some of these numbers are same but i don't want to get same numbers so how can i use DISTINCT in ORMLite with where condition.

Thanks for helping

Also some of my code is like this:

```<code>  private void modalShowEbat() {
    dbHelper = (DBHelper) OpenHelperManager.getHelper(this, DBHelper.class);
    RuntimeExceptionDao<Segment, Integer> segmentDao = dbHelper.getSegmentExceptionDao();
    List<Segment> list = segmentDao.queryForEq(Constant.QUERY_SEGMENT, editTextSegment.getText().toString().trim());

    final CharSequence items[] = new CharSequence[list.size()];
    for (int i = 0; i < list.size(); i++) {
        items[i] = list.get(i).getColumnEbat();
    }
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Segment seçiniz");
    builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // the user clicked on colors[which]
            editTextEbat.setText(items[which].toString());
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
        }
    });
    alertDialog = builder.create();
    alertDialog.show();
}
</code>```

This is my image of result

答:
Hi I solved my problem with below code. Maybe you can say this is long way for this. I wrote my code like below because i couldn't do other ways(using .distinct() method in ORMLite or other ORMLite's method)

If you have any other ways to solve this, i am waiting your suggestions. Thanks for everybody, happy coding...

```<code>private void modalShowEbat() {
    dbHelper = (DBHelper) OpenHelperManager.getHelper(this, DBHelper.class);
    RuntimeExceptionDao<Segment, Integer> segmentDao = dbHelper.getSegmentExceptionDao();
    List<Segment> list = segmentDao.queryForEq(Constant.QUERY_SEGMENT, editTextSegment.getText().toString().trim());

    GenericRawResults<String[]> rawResults = segmentDao.queryRaw("SELECT DISTINCT Ebat FROM Segment WHERE Segment = ? ", editTextSegment.getText().toString().trim());
    final CharSequence items[] = new CharSequence[list.size()];
    int i = 0;
    for (String[] resultColumns : rawResults) {
        String author = resultColumns[0];
        items[i] = author;
        i++;
    }
    int newLenght = 0;
    for (int j = 0; j < items.length; j++) {
        if (items[j] != null) {
            newLenght++;
        }
    }
    final CharSequence newItems[] = new CharSequence[newLenght];
    for (int j = 0; j < newLenght; j++) {
        if (items[j] != null) {
            newItems[j] = items[j];
        }
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Choose Segment");
    builder.setSingleChoiceItems(newItems, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // the user clicked on colors[which]
            editTextEbat.setText(newItems[which].toString());
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
        }
    });
    alertDialog = builder.create();
    alertDialog.show();
}
</code>```

Title: ORMLite DISTINCT With Where Condition

Body:
I am developing an android project using ORMLite and i have a problem to figure out. There is a picture below and how can i use DISTINCT sql query in ORMLite?
I have some parameters giving to where condition and according to this conditions i am getting number list...

In this picture you are going to see some numbers and some of these numbers are same but i don't want to get same numbers so how can i use DISTINCT in ORMLite with where condition.

Thanks for helping

Also some of my code is like this:

  private void modalShowEbat() {
    dbHelper = (DBHelper) OpenHelperManager.getHelper(this, DBHelper.class);
    RuntimeExceptionDao<Segment, Integer> segmentDao = dbHelper.getSegmentExceptionDao();
    List<Segment> list = segmentDao.queryForEq(Constant.QUERY_SEGMENT, editTextSegment.getText().toString().trim());

    final CharSequence items[] = new CharSequence[list.size()];
    for (int i = 0; i < list.size(); i++) {
        items[i] = list.get(i).getColumnEbat();
    }
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Segment seçiniz");
    builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // the user clicked on colors[which]
            editTextEbat.setText(items[which].toString());
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
        }
    });
    alertDialog = builder.create();
    alertDialog.show();
}

This is my image of result

Body:
Hi I solved my problem with below code. Maybe you can say this is long way for this. I wrote my code like below because i couldn't do other ways(using .distinct() method in ORMLite or other ORMLite's method)

If you have any other ways to solve this, i am waiting your suggestions. Thanks for everybody, happy coding...

private void modalShowEbat() {
    dbHelper = (DBHelper) OpenHelperManager.getHelper(this, DBHelper.class);
    RuntimeExceptionDao<Segment, Integer> segmentDao = dbHelper.getSegmentExceptionDao();
    List<Segment> list = segmentDao.queryForEq(Constant.QUERY_SEGMENT, editTextSegment.getText().toString().trim());

    GenericRawResults<String[]> rawResults = segmentDao.queryRaw("SELECT DISTINCT Ebat FROM Segment WHERE Segment = ? ", editTextSegment.getText().toString().trim());
    final CharSequence items[] = new CharSequence[list.size()];
    int i = 0;
    for (String[] resultColumns : rawResults) {
        String author = resultColumns[0];
        items[i] = author;
        i++;
    }
    int newLenght = 0;
    for (int j = 0; j < items.length; j++) {
        if (items[j] != null) {
            newLenght++;
        }
    }
    final CharSequence newItems[] = new CharSequence[newLenght];
    for (int j = 0; j < newLenght; j++) {
        if (items[j] != null) {
            newItems[j] = items[j];
        }
    }

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Choose Segment");
    builder.setSingleChoiceItems(newItems, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // the user clicked on colors[which]
            editTextEbat.setText(newItems[which].toString());
            if (alertDialog != null && alertDialog.isShowing()) {
                alertDialog.dismiss();
            }
        }
    });
    alertDialog = builder.create();
    alertDialog.show();
}


问:
Can anyone recommend solution to my situation with XML
Sorry for not being clear.
The problem I am trying to convey is that XML::Simple does not allow me direct access to the hash, I must refer to the key in question through the XML::Simple module. Using something like $xml->{key}.

Here is the code I am using and a copy of the hash output.

The reason this is a problem is because I need to construct a series of loops using the keys of the hash [seen below], and I cannot build a foreach loop with a hash referrence, when I tried it, perl gave me an error.

So what I am looking for is a module or solution to allow me to dump the contents of the XML file to a hash that I declare in my script. I also need the ability to write back out to an XML file.

```<code>#!/usr/bin/perl
use strict;
use warnings;
use XML::Simple;
use Data::Dumper;

system ("clear");

my $xml = XML::Simple->new;

# Using the XML::Simple object, read guest_os.xml to a hash

my $xml_file = $xml->XMLin('config.xml',

                SearchPath => './config',

                SuppressEmpty => 1);

$VAR1 = \{
        'esxi01' => {
                    'password' => 'myspoonistoobig!',
                    'user' => 'root',
                    'port' => '22'
                  },
        'esxi02' => {
                    'password' => 'myspoonistoobig!',
                    'user' => 'root',
                    'port' => '22'
                  },
        'Setup' => 'FALSE'
      };
</code>```

For me to access a single key/values in the hash that is created [above] I have to use something like this.

$xml_file->{esxi01}{password}.

Oh yeah I forgot the actual XML file.

```<code><Config>
  <esxi01>
    <password>password</password>
    <port>22</port>
    <user>root</user>
  </esxi01>
  <esxi02>
    <password>password</password>
    <port>22</port>
    <user>root</user>
  </esxi02>
  <Setup>FALSE</Setup>
</Config>
</code>```

This is the simplest of the 3 or so I have.

Update:

The first part of the loop works with no problem, the problem happens when I try to use the second part of the loop.

Here is the way my code looks

```<code>my $xml = XML::Simple->new;

# Using the XML::Simple object, read guest_os.xml to a hash

my $xml_file = $xml->XMLin('config.xml',

                SearchPath => './config',

                SuppressEmpty => 1);

foreach my $server (keys %$xml_file) {
    foreach my $attribute (keys %{$xml_file->{$server}}) {
        print "$attribute\n";
    }
}
</code>```

The output looks like this,

Can't use string ("password") as a HASH ref while "strict refs" in use at foreach_test line 21.

I have tried using quotes in several places to fix the problem but nothing seems to work.

答:
You can iterate through the hash using each or keys:

```<code>while(($key, $value) = each(%$xml)) {
    print "key: $key, value: $value\n";
}

foreach my $key (keys %$xml) {
    print "key: $key, value: $xml->{$key}\n";
}
</code>```

Body:
Sorry for not being clear.
The problem I am trying to convey is that XML::Simple does not allow me direct access to the hash, I must refer to the key in question through the XML::Simple module. Using something like $xml->{key}.

Here is the code I am using and a copy of the hash output.

The reason this is a problem is because I need to construct a series of loops using the keys of the hash [seen below], and I cannot build a foreach loop with a hash referrence, when I tried it, perl gave me an error.

So what I am looking for is a module or solution to allow me to dump the contents of the XML file to a hash that I declare in my script. I also need the ability to write back out to an XML file.

#!/usr/bin/perl
use strict;
use warnings;
use XML::Simple;
use Data::Dumper;

system ("clear");

my $xml = XML::Simple->new;

# Using the XML::Simple object, read guest_os.xml to a hash

my $xml_file = $xml->XMLin('config.xml',

                SearchPath => './config',

                SuppressEmpty => 1);

$VAR1 = \{
        'esxi01' => {
                    'password' => 'myspoonistoobig!',
                    'user' => 'root',
                    'port' => '22'
                  },
        'esxi02' => {
                    'password' => 'myspoonistoobig!',
                    'user' => 'root',
                    'port' => '22'
                  },
        'Setup' => 'FALSE'
      };

For me to access a single key/values in the hash that is created [above] I have to use something like this.

$xml_file->{esxi01}{password}.

Oh yeah I forgot the actual XML file.

<Config>
  <esxi01>
    <password>password</password>
    <port>22</port>
    <user>root</user>
  </esxi01>
  <esxi02>
    <password>password</password>
    <port>22</port>
    <user>root</user>
  </esxi02>
  <Setup>FALSE</Setup>
</Config>

This is the simplest of the 3 or so I have.

Update:

The first part of the loop works with no problem, the problem happens when I try to use the second part of the loop.

Here is the way my code looks

my $xml = XML::Simple->new;

# Using the XML::Simple object, read guest_os.xml to a hash

my $xml_file = $xml->XMLin('config.xml',

                SearchPath => './config',

                SuppressEmpty => 1);

foreach my $server (keys %$xml_file) {
    foreach my $attribute (keys %{$xml_file->{$server}}) {
        print "$attribute\n";
    }
}

The output looks like this,

Can't use string ("password") as a HASH ref while "strict refs" in use at foreach_test line 21.

I have tried using quotes in several places to fix the problem but nothing seems to work.

Body:
You can iterate through the hash using each or keys:

while(($key, $value) = each(%$xml)) {
    print "key: $key, value: $value\n";
}

foreach my $key (keys %$xml) {
    print "key: $key, value: $xml->{$key}\n";
}


问:
Excel 2016 for Mac, having issues using a Macro that normally works on 2011
I am attempting to run macros on my Mac Excel 2016 version. Unfortunately, I get a run-time error 1004. The code normally works on Mac Excel 2011. Please help, assistance is much appreciated; I am not a coder.

```<code>Option Explicit
Sub copyallworksheets()
'
' copyallworksheets Macro
' copy all worksheets to new workbooks
'
' Keyboard Shortcut: Option+Cmd+b
'
    Sheets("Beverages").Select
    Sheets("Beverages").Copy
    Cells.Select
    Range("A13").Activate
    Selection.Copy
    Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=False
    Cells.Select
    Range("A13").Activate
    ActiveWorkbook.SaveAs Filename:= _
        "Macintosh HD:Users:Jay:Desktop:EOM Uploads:Beverage Purchases.csv", _
        FileFormat:=xlCSV, CreateBackup:=False
    ActiveWorkbook.Close savechanges:=False
</code>```

The 1004 error occurs on the following line:

```<code>ActiveWorkbook.SaveAs Filename:= _
        "Macintosh HD:Users:Jay:Desktop:EOM Uploads:Beverage Purchases.csv", _
        FileFormat:=xlCSV, CreateBackup:=False
</code>```

答:
This is likely a security issue, try these steps:

Click the Microsoft Office Button, and then click Excel Options.

Click Trust Center.

Click Trust Center Settings.

Click Macro Settings.

Click to select the Trust access to the VBA project object model check box.

Click OK to close the Excel Options dialog box.

Credit to https://support.microsoft.com/en-us/help/813969/you-may-receive-an-run-time-error-when-you-programmatically-allow-acce

Body:
I am attempting to run macros on my Mac Excel 2016 version. Unfortunately, I get a run-time error 1004. The code normally works on Mac Excel 2011. Please help, assistance is much appreciated; I am not a coder.

Option Explicit
Sub copyallworksheets()
'
' copyallworksheets Macro
' copy all worksheets to new workbooks
'
' Keyboard Shortcut: Option+Cmd+b
'
    Sheets("Beverages").Select
    Sheets("Beverages").Copy
    Cells.Select
    Range("A13").Activate
    Selection.Copy
    Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=False
    Cells.Select
    Range("A13").Activate
    ActiveWorkbook.SaveAs Filename:= _
        "Macintosh HD:Users:Jay:Desktop:EOM Uploads:Beverage Purchases.csv", _
        FileFormat:=xlCSV, CreateBackup:=False
    ActiveWorkbook.Close savechanges:=False

The 1004 error occurs on the following line:

ActiveWorkbook.SaveAs Filename:= _
        "Macintosh HD:Users:Jay:Desktop:EOM Uploads:Beverage Purchases.csv", _
        FileFormat:=xlCSV, CreateBackup:=False


问:
Best approach to insert delta records from view into a table
I have a requirement where I do a daily load from a view to a table. After the initial load, there may be scenarios where the original records get deleted from the view's source table. There are also scenarios where these records are updated.

When the stored procedure is run, the table that is loaded should pick up delta records. This means only new inserts. Also, it should mark deleted lines as D. In addition to this, any updates in source data must also updated in this table and marked as U.
Please refer to the attached image which shows in case 1 , 2 inserts on the initial load and then an update and then a delete.
Left side represents the view and right side represents the table I am trying to load.

Thanks!

Shyam

答:
If you prefer to use triggers on HANA database tables you can use following samples on a column table, if you are working with row tables then you can prefer statement based approach</p>

```<code>create trigger Salary_A_DEL after DELETE on Salary
REFERENCING OLD ROW myoldrow
FOR EACH ROW
begin

INSERT INTO SalaryLog (
    Employee,
    Salary,
    Operation,
    DateTime
) VALUES (
    :myoldrow.Employee,
    :myoldrow.Salary,
    'D',
    CURRENT_DATE
);

end;

create trigger Salary_A_UPD after UPDATE on Salary
REFERENCING NEW ROW mynewrow, OLD ROW myoldrow
FOR EACH ROW
begin

INSERT INTO SalaryLog (
    Employee,
    Salary,
    Operation,
    DateTime
) VALUES (
    :mynewrow.Employee,
    :mynewrow.Salary,
    'U',
    CURRENT_DATE
);

end;

create trigger Salary_A_INS after INSERT on Salary
REFERENCING NEW ROW mynewrow
FOR EACH ROW
begin

INSERT INTO SalaryLog (
    Employee,
    Salary,
    Operation,
    DateTime
) VALUES (
    :mynewrow.Employee,
    :mynewrow.Salary,
    'I',
    CURRENT_DATE
);

end;
</code>```

Body:
If you prefer to use triggers on HANA database tables you can use following samples on a column table, if you are working with row tables then you can prefer statement based approach

create trigger Salary_A_DEL after DELETE on Salary
REFERENCING OLD ROW myoldrow
FOR EACH ROW
begin

INSERT INTO SalaryLog (
    Employee,
    Salary,
    Operation,
    DateTime
) VALUES (
    :myoldrow.Employee,
    :myoldrow.Salary,
    'D',
    CURRENT_DATE
);

end;

create trigger Salary_A_UPD after UPDATE on Salary
REFERENCING NEW ROW mynewrow, OLD ROW myoldrow
FOR EACH ROW
begin

INSERT INTO SalaryLog (
    Employee,
    Salary,
    Operation,
    DateTime
) VALUES (
    :mynewrow.Employee,
    :mynewrow.Salary,
    'U',
    CURRENT_DATE
);

end;

create trigger Salary_A_INS after INSERT on Salary
REFERENCING NEW ROW mynewrow
FOR EACH ROW
begin

INSERT INTO SalaryLog (
    Employee,
    Salary,
    Operation,
    DateTime
) VALUES (
    :mynewrow.Employee,
    :mynewrow.Salary,
    'I',
    CURRENT_DATE
);

end;


问:
calling previous fragment from another fragment inside navigation drawer
Hi I have a navigation drawer and I have 4 fragments. I want to go from fragment 3 to fragment 2 on back press and on back press from fragment 4 it should go to fragment 1.How can I do this ??

I have tried adding fragments to back stack. If I add fragment to back stack when I click from home fragment the app should actually close.Instead of closing the fragment which I added to backstack is showing and when back pressing from that it showing the home fragment again and then the app is closing.

答:
//try this code add fragment number while opening new fragment and remove last positions from the list on backpress</p>

```<code>public ArrayList<Integer> list = new ArrayList<>();

public void addToStack(int pos)
{
    if (!list.contains(pos))
    {
        list.add(pos);
    }
}
</code>```

Body:
//try this code add fragment number while opening new fragment and remove last positions from the list on backpress

public ArrayList<Integer> list = new ArrayList<>();

public void addToStack(int pos)
{
    if (!list.contains(pos))
    {
        list.add(pos);
    }
}


问:
Specify C++ object attributes in a fancy way with no constructor provided
Consider this trivial class:

```<code>#include <string>
class A
{
public:
    A( int i, const std::string& str ) : i(i), str(str)
    {
    }

    inline int getValue() const { return i; }
    inline std::string getName() const { return str; }

private:
    int i;
    std::string str;
};

int main()
{
    A a(3,"dkd");
    //...
    return 0;
}
</code>```

It's "a pain" to have to maintain the constructor when new attributes are added to the class. OK, not that painful, but when the constructor is so obvious (it gets the parameters of the same type than attributes and in the same order), it would be nice not to have to declare any, and have a default one provided that would simply work!

I was thinking of something like:

```<code>#include <string>
class A
{
public:
    inline int getValue() const { return i; }
    inline std::string getName() const { return str; }

private:
    int i;
    std::string str;
};

int main()
{
    A a{ 3, "ff" };
    ///...
    return 0;
}
</code>```

Is this doable in C++?

答:
Read about http://en.cppreference.com/w/cpp/language/aggregate_initialization,
your code will not be compiled bacause members of your class are privated.

If members of your class are public, your code will work.

Body:
Consider this trivial class:

#include <string>
class A
{
public:
    A( int i, const std::string& str ) : i(i), str(str)
    {
    }

    inline int getValue() const { return i; }
    inline std::string getName() const { return str; }

private:
    int i;
    std::string str;
};

int main()
{
    A a(3,"dkd");
    //...
    return 0;
}

It's "a pain" to have to maintain the constructor when new attributes are added to the class. OK, not that painful, but when the constructor is so obvious (it gets the parameters of the same type than attributes and in the same order), it would be nice not to have to declare any, and have a default one provided that would simply work!

I was thinking of something like:

#include <string>
class A
{
public:
    inline int getValue() const { return i; }
    inline std::string getName() const { return str; }

private:
    int i;
    std::string str;
};

int main()
{
    A a{ 3, "ff" };
    ///...
    return 0;
}

Is this doable in C++?


答:
Unfortunately not for your case. Something exists which allows you to do this, and it's called aggregate initialisation. It can't be used in your example, because it can only be used on classes which

Have no private/protected non-static members

Have no constructors

Have no virtual functions

From the link itself:

Aggregate initialization is a form of list-initialization, which initializes aggregates

  An aggregate is one of the following types:

  * array type

  * class type (typically, struct or union), that has

  no private or protected non-static data members

  no user-provided, inherited, or explicit (since C++17) constructors (explicitly defaulted or deleted constructors are allowed) (since C++11)

  no virtual, private, or protected (since C++17) base classes

  no virtual member functions

  no default member initializers

If your class had public members instead, you would be able to have the following:

```<code>class A
{
public:
    int i;
    std::string str;
};

int main()
{
    A a{ 3, "ff" };
}
</code>```

If you then extend your class by adding a new member to it, you don't need to update old code. Members not included in the initialiser list are default initialised:

If the number of initializer clauses is less than the number of members or initializer list is completely empty, the remaining members are value-initialized.

```<code>class A
{
public:
    int i;
    std::string str;
    double d;
};

int main()
{
    A a{ 3, "ff" }; // your old code still works, a.d becomes 0.0
    A b{ 3, "ff", 1.0 };
    A c{}; // 0, "", 0.0
}
</code>```

Title: Specify C++ object attributes in a fancy way with no constructor provided

Body:
Unfortunately not for your case. Something exists which allows you to do this, and it's called aggregate initialisation. It can't be used in your example, because it can only be used on classes which

Have no private/protected non-static members

Have no constructors

Have no virtual functions

From the link itself:

Aggregate initialization is a form of list-initialization, which initializes aggregates

  An aggregate is one of the following types:

  * array type

  * class type (typically, struct or union), that has

  no private or protected non-static data members

  no user-provided, inherited, or explicit (since C++17) constructors (explicitly defaulted or deleted constructors are allowed) (since C++11)

  no virtual, private, or protected (since C++17) base classes

  no virtual member functions

  no default member initializers

If your class had public members instead, you would be able to have the following:

class A
{
public:
    int i;
    std::string str;
};

int main()
{
    A a{ 3, "ff" };
}

If you then extend your class by adding a new member to it, you don't need to update old code. Members not included in the initialiser list are default initialised:

If the number of initializer clauses is less than the number of members or initializer list is completely empty, the remaining members are value-initialized.

class A
{
public:
    int i;
    std::string str;
    double d;
};

int main()
{
    A a{ 3, "ff" }; // your old code still works, a.d becomes 0.0
    A b{ 3, "ff", 1.0 };
    A c{}; // 0, "", 0.0
}


问:
Adjust EditText icon away from the left border
I created an EditText with a drawable image. The problem is that the image is very close to the border of the EditText, is there a way to adjust it?

Note: Im using an svg file for the image

Image: In the image you can see the shoulder of the person is almost touching the left border

Code:

```<code>        <EditText

            android:id="@+id/sampleName"
            android:drawableStart="@drawable/sampleImage"
            android:drawablePadding="10dp"
            android:layout_height="wrap_content"
            android:maxLines="1"
            android:layout_width="match_parent"
            android:background="@color/white"

            android:layout_marginLeft="5dp"
            />
</code>```

答: You can try android:padding to the EditText along with the android:drawablePadding

Body:
I created an EditText with a drawable image. The problem is that the image is very close to the border of the EditText, is there a way to adjust it?

Note: Im using an svg file for the image

Image: In the image you can see the shoulder of the person is almost touching the left border

Code:

        <EditText

            android:id="@+id/sampleName"
            android:drawableStart="@drawable/sampleImage"
            android:drawablePadding="10dp"
            android:layout_height="wrap_content"
            android:maxLines="1"
            android:layout_width="match_parent"
            android:background="@color/white"

            android:layout_marginLeft="5dp"
            />


问:
Is IBDesignable broken for AppKit in Xcode 9.2 and Swift 4?
Most questions, and answers related to this, are based on older versions of both Xcode and Swift. Additionally, 90 percent of the questions relate to UIKit and drawing custom controls.

I am adding a standard button, that is centered inside a custom control, decorated with IBDesignable.

```<code>import Cocoa

@IBDesignable public class ButtonPresetView: NSView {
    public override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        initialControlSetup()
    }

    public required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
        initialControlSetup()
    }

    private func initialControlSetup() {
        let button = NSButton(title: "Hello", target: nil, action: nil)
        button.translatesAutoresizingMaskIntoConstraints = false
        addSubview(button)

        // Configure button
        centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true
        centerYAnchor.constraint(equalTo: button.centerYAnchor).isActive = true
    }
}
</code>```

I add a custom view to the application and set the class property in the Identity Inspector to my custom class (ButtonPresetView).

It should show the button centered on the canvas, but the canvas is blank.
Not sure many people use it this way, but it worked gloriously with Swift 3 in Xcode 8.3.

Does anyone else have this problem?

答:
I was able to get this to work in the latest Xcode by adding the following two lines to the top of the initialControlSetup function:

```<code>wantsLayer = true
canDrawSubviewsIntoLayer = true
</code>```

I think this basically tells the NSView to render in a way that is more similar to how iOS works. If this worked in Xcode 8.3 as you say, it's possible that Apple introduced this regression in Xcode 9 without realizing it.

Body:
Most questions, and answers related to this, are based on older versions of both Xcode and Swift. Additionally, 90 percent of the questions relate to UIKit and drawing custom controls.

I am adding a standard button, that is centered inside a custom control, decorated with IBDesignable.

import Cocoa

@IBDesignable public class ButtonPresetView: NSView {
    public override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        initialControlSetup()
    }

    public required init?(coder decoder: NSCoder) {
        super.init(coder: decoder)
        initialControlSetup()
    }

    private func initialControlSetup() {
        let button = NSButton(title: "Hello", target: nil, action: nil)
        button.translatesAutoresizingMaskIntoConstraints = false
        addSubview(button)

        // Configure button
        centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true
        centerYAnchor.constraint(equalTo: button.centerYAnchor).isActive = true
    }
}

I add a custom view to the application and set the class property in the Identity Inspector to my custom class (ButtonPresetView).

It should show the button centered on the canvas, but the canvas is blank.
Not sure many people use it this way, but it worked gloriously with Swift 3 in Xcode 8.3.

Does anyone else have this problem?

Body:
I was able to get this to work in the latest Xcode by adding the following two lines to the top of the initialControlSetup function:

wantsLayer = true
canDrawSubviewsIntoLayer = true

I think this basically tells the NSView to render in a way that is more similar to how iOS works. If this worked in Xcode 8.3 as you say, it's possible that Apple introduced this regression in Xcode 9 without realizing it.


问:
Java: How to delete a file
In the code below how come when it say that it has successfully deleted the file, but when I check the file is still there. How would I remove the file. Basically I'm trying the delete the first file that I made after I was done using it to create the second file. </p>

```<code>public static void main(String[] args) {
    File file = new File("Hello");
    try {
        file.createNewFile();
    } catch (Exception e) { }

    try {
        PrintWriter e = new PrintWriter(file);
        e.println("Hello hi");
        e.close();
    }catch (Exception e) {}

    File file2 = new File("Hello2");
    try {
        file2.createNewFile();
    } catch (Exception e) {}

    try {
        Scanner x = new Scanner(file);
        PrintWriter e = new PrintWriter(file);
        while (x.hasNextLine()) {
            System.out.println("Hello");}
             e.close();
    } catch (Exception e) {}
    try {
        file.delete();
        System.out.println("It was deleted");
    } catch (Exception e) { }
 }
}
</code>```

答:
file.delete() doesn't throw an IOException, it returns a boolean check into if condition

```<code> if(file.delete())
    {
        System.out.println("File deleted successfully");
    }
    else
    {
        System.out.println("Failed to delete the file");
    }
</code>```

Title: Java: How to delete a file

Body:
In the code below how come when it say that it has successfully deleted the file, but when I check the file is still there. How would I remove the file. Basically I'm trying the delete the first file that I made after I was done using it to create the second file.

public static void main(String[] args) {
    File file = new File("Hello");
    try {
        file.createNewFile();
    } catch (Exception e) { }

    try {
        PrintWriter e = new PrintWriter(file);
        e.println("Hello hi");
        e.close();
    }catch (Exception e) {}

    File file2 = new File("Hello2");
    try {
        file2.createNewFile();
    } catch (Exception e) {}

    try {
        Scanner x = new Scanner(file);
        PrintWriter e = new PrintWriter(file);
        while (x.hasNextLine()) {
            System.out.println("Hello");}
             e.close();
    } catch (Exception e) {}
    try {
        file.delete();
        System.out.println("It was deleted");
    } catch (Exception e) { }
 }
}

Body:
file.delete() doesn't throw an IOException, it returns a boolean check into if condition

 if(file.delete())
    {
        System.out.println("File deleted successfully");
    }
    else
    {
        System.out.println("Failed to delete the file");
    }


问:
Grabbing content off webpage that is in script tags
OK, I have this page I want to get the content off.. however the stats are made in JavaScript.  Is there ANY way I can get the stats? I tried using PHP get_content thingy...

Here is an example that is in the page I want to get. This

Body:
I expect you mean you have the page's source by getting it remotely via file_get_contents(). Then you just need to use a regular expression to match all lines in that source code that start with S[na], then explode on | to get them in an array form. That should get you the data in a workable format.

$content = <<<END
<script>

na=0;
S=new Array;
S[na]="|Beal|3266561|137|131|1170664|714062|1378742|2375|128|322|"; na++;
S[na]="|Marine|2446933|165554|125613|1116688|652869|187250|23773|27019|148167|"; na++;
S[na]="|Krackle1|2306919|342794|440503|372482|238609|442226|146516|177399|146390|"; na++;
S[na]="|LawyerUpSir|1666817|60579|236847|379476|219395|446057|149787|151306|23370|"; na++;
S[na]="|IKillToWin|1657426|94695|214229|800157|446579|59618|9132|8861|24155|"; na++;
S[na]="|Farts|1644623|6885|8790|972072|586678|49249|10558|2838|7553|"; na++;

</script>

...some HTML here..

END;

$matches = array() ;
preg_match_all("/S\[na\]\=\"\|(.*)\"\;\sna\+\+\;/", $content, $matches) ;

$stats = array() ;
if (count($matches) > 0 && is_array($matches[1])) {
    foreach ($matches[1] as $match) {
        $stats[] = $match ;
    }
}


答:
Removing Below Line from your code will solve the problem :  </p>

```<code>android:layout_marginLeft="5dp"
</code>```

Title: Adjust EditText icon away from the left border

Body:
Removing Below Line from your code will solve the problem :

android:layout_marginLeft="5dp"


问:
In dynet, can I save a model in a compressed file?
In dynet, it is possible to save a model to a text file.
When I save my model, it is over 40 MB. I save 100 models in a single run, which is 4 GB.

Is there a way to save a model in a compressed format, so that it does not take so much disk space?

答:
This is not currently possible, but there is an issue about it.
Of course, you can zip the files and unzip them later:

After save(filename, ...):

```<code>import zipfile
from glob import glob
import os
files = glob(filename + ".*")
with zipfile.ZipFile(filename + ".zip", "w", zipfile.ZIP_DEFLATED) as zh:
    for fname in files:
        zh.write(fname)
for fname in files:
    os.remove(fname)
</code>```

Before load(filename):

```<code>import zipfile
import os
with zipfile.ZipFile(filename + ".zip", "r") as zh:
    zh.extractall(os.path.dirname(filename))
os.remove(filename + ".zip")
</code>```

Body:
This is not currently possible, but there is an issue about it.
Of course, you can zip the files and unzip them later:

After save(filename, ...):

import zipfile
from glob import glob
import os
files = glob(filename + ".*")
with zipfile.ZipFile(filename + ".zip", "w", zipfile.ZIP_DEFLATED) as zh:
    for fname in files:
        zh.write(fname)
for fname in files:
    os.remove(fname)

Before load(filename):

import zipfile
import os
with zipfile.ZipFile(filename + ".zip", "r") as zh:
    zh.extractall(os.path.dirname(filename))
os.remove(filename + ".zip")


问:
LinkedIn SDK ios swift
I am trying to integrate LinkedIn SDK in iOS using swift

I found the below code in objective-C (https://developer.linkedin.com/docs/signin-with-linkedin)

```<code>NSString *url = [NSString initWithString:@"https://api.linkedin.com/v1/people/~"];
if ([LISDKSessionManager hasValidSession]) {
    [[LISDKAPIHelper sharedInstance] getRequest:url
    success:^(LISDKAPIResponse *response) {
        // do something with response
    }
    error:^(LISDKAPIError *apiError) {
        // do something with error
    }];
]}
</code>```

How to convert this to swift.

I am very new to swift

答:
```<code>var url = "https://api.linkedin.com/v1/people/~"

if LISDKSessionManager.hasValidSession()
{
 try? LISDKAPIHelper.sharedInstance().getRequest(url, success: {(_ response: LISDKAPIResponse) -> Void in
        // do something with response
    })
}
</code>```

this is in swift 4

Title: LinkedIn SDK ios swift

Body:
I am trying to integrate LinkedIn SDK in iOS using swift

I found the below code in objective-C (https://developer.linkedin.com/docs/signin-with-linkedin)

NSString *url = [NSString initWithString:@"https://api.linkedin.com/v1/people/~"];
if ([LISDKSessionManager hasValidSession]) {
    [[LISDKAPIHelper sharedInstance] getRequest:url
    success:^(LISDKAPIResponse *response) {
        // do something with response
    }
    error:^(LISDKAPIError *apiError) {
        // do something with error
    }];
]}

How to convert this to swift.

I am very new to swift

Body:
var url = "https://api.linkedin.com/v1/people/~"

if LISDKSessionManager.hasValidSession()
{
 try? LISDKAPIHelper.sharedInstance().getRequest(url, success: {(_ response: LISDKAPIResponse) -> Void in
        // do something with response
    })
}

this is in swift 4


问:
How can I make this css animation smooth
In the below example you can see the boxes jumping a little bit, How can I make that transition smooth?

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite ease-out;
}

.box:nth-child(2) {
  animation-delay: 1.2s;
}

.box:nth-child(3) {
  animation-delay: 1.4s;
}

@keyframes updn {
  0% {
    transform: translateY(-10px) translateX(10px);
  }
  50% {
    transform: translateY(0px);
  }
  75% {
    transform: translateY(10px);
  }
  100% {
    transform: translateY(0px) translateX(0px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div></code>```

答:
What about this one

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite ease-out;
}

.box:nth-child(2) {
  animation-delay: 1.2s;
}

.box:nth-child(3) {
  animation-delay: 1.4s;
}

@keyframes updn {
  0% {
    transform: translateY(0px) translateX(10px);
  }
  50% {
    transform: translateY(10px);
  }

  75% {
    transform: translateY(10px);
  }
  100% {
    transform: translateY(1px) translateX(10px);
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div></code>```

Body:
What about this one

.container {
  text-align: center;
  margin-top: 30px;
}

.box {
  background: rgba(0, 10, 103, 0.5);
  height: 50px;
  width: 50px;
  border: 3px solid rgba(0, 10, 103, 0.9);
  margin: 10px;
  display: inline-block;
  animation: updn 1s infinite ease-out;
}

.box:nth-child(2) {
  animation-delay: 1.2s;
}

.box:nth-child(3) {
  animation-delay: 1.4s;
}

@keyframes updn {
  0% {
    transform: translateY(0px) translateX(10px);
  }
  50% {
    transform: translateY(10px);
  }

  75% {
    transform: translateY(10px);
  }
  100% {
    transform: translateY(1px) translateX(10px);
  }
}

<div class="container">
  <div class="box"></div>
  <div class="box"></div>
  <div class="box"></div>
</div>


答:
You can use drawablePadding and paddingto give space to the image. Try it like this:

```<code><EditText
    android:id="@+id/sampleName"
    android:drawableStart="@drawable/sampleImage"
    android:drawablePadding="10dp"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:layout_width="match_parent"
    android:background="@color/white"
    android:drawablePadding="5dp"
    android:padding="5dp"
    android:layout_marginLeft="5dp"
    />
</code>```

Body:
You can use drawablePadding and paddingto give space to the image. Try it like this:

<EditText
    android:id="@+id/sampleName"
    android:drawableStart="@drawable/sampleImage"
    android:drawablePadding="10dp"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:layout_width="match_parent"
    android:background="@color/white"
    android:drawablePadding="5dp"
    android:padding="5dp"
    android:layout_marginLeft="5dp"
    />


问:
CSS: hide
 on hover
I would like that menu with class "bbb" occurs only when user hover on link in class "aaa" (as a drop-down menu...)

I use css and I created some code:

```<code>.aaa:hover .bbb {
  opacity: 1;
}

.bbb {
  opacity: 0;
}
</code>```

But it doesn't work as intended. Can you help mi to get where i am wrong? I tried also do i with display:none & display:block instead of opacity.

Modification: resolution below doesn't work because i have other css metods. Pasted it:

.footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  text-align: center;
  font: inherit;
  font-size: 10px;
  color: white;
}

a, a:hover, a:active, a:visited {
  color: white;
}

.buttons {
  position: absolute;
  text-align: center;
}

.set:not(:last-child) {
  border-bottom: 1px dotted #aaa;
}

html, body, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
  z-index: 1;
}

/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
  display: block;
}

body {
  line-height: 1;
}

ol, ul {
  list-style: none;
}

blockquote, q {
  quotes: none;
}

blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

/* Default Styles
--------------------------------------------------------------------*/

body {
  background: url('img/denim.png');
  font-family: 'Droid Sans', sans-serif;;
}

.clearfix {
  clear: both;
}

.wrap {
  width: 940px;
  margin: 4em auto;
}

nav {
  background: -webkit-gradient(linear, center top, center bottom, from(#fff), to(#ccc));
  background-image: linear-gradient(#fff, #ccc);
  border-radius: 6px;
  box-shadow: 0px 0px 4px 2px rgba(0,0,0,0.4);
  padding: 0 10px;
  position: relative;
}

.menu li {
  float: left;
  position: relative;
}

.menu li a {
  color: #444;
  display: block;
  font-size: 14px;
  line-height: 20px;
  padding: 6px 12px;
  margin: 8px 8px;
  vertical-align: middle;
  text-decoration: none;
}

.menu li a:hover {
  background: -webkit-gradient(linear, center top, center bottom, from(#ededed), to(#fff));
  background-image: linear-gradient(#ededed, #fff);
  border-radius: 12px;
  box-shadow: inset 0px 0px 1px 1px rgba(0,0,0,0.1);
  color: #222;
}

/* Dropdown styles */

.menu ul {
  position: absolute;
  left: -9999px;
  list-style: none;
  opacity: 0;
  transition: opacity 1s ease;
}

.menu ul li {
  float: none;
}

.menu ul a {
  white-space: nowrap;
}

/* Displays the dropdown on hover and moves back into position */
.menu li:hover ul {
  background: rgba(255,255,255,0.7);
  border-radius: 0 0 6px 6px;
  box-shadow: inset 0px 2px 4px rgba(0,0,0,0.4);
  left: 5px;
  opacity: 1;
}

.aaa:hover .bbb {
  display: block;
}

.bbb {
  display: none;
}

/* Persistant Hover State */

.menu li:hover a {
  background: -webkit-gradient(linear, center top, center bottom, from(#ccc), to(#ededed));
  background-image: linear-gradient(#ccc, #ededed);
  border-radius: 12px;
  box-shadow: inset 0px 0px 1px 1px rgba(0,0,0,0.1);
  color: #222;
}

.menu li:hover ul a {
  background: none;
  border-radius: 0;
  box-shadow: none;
}

.menu li:hover ul li a:hover {
  background: -webkit-gradient(linear, center top, center bottom, from(#eee), to(#fff));
  background-image: linear-gradient(#ededed, #fff);
  border-radius: 12px;
  box-shadow: inset 0px 0px 4px 2px rgba(0,0,0,0.3);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">
  <nav>
    <ul class="menu">
      <li><span class="iconic home"></span> Home</li>
      <li><span class="iconic magnifying-glass"></span> newIB
        <ul>
          <li>111</li>
          <li>222</li>
          <li>333</li>
          <li>444</li>
          <li class="aaa">555
            <ul class="bbb">
              <li>test</li>
              <li>test</li>
              <li>test</li>
              <li>test</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </nav>
</div></code>```

答:
Apply the class on .bbb on ul instead of li (this is because you're trying to make a drop down and display the entire unordered-list instead of just one of the nested li) which is a direct child of class .aaa and use display:none and display:block as shown and it should work fine. The same criteria is applied on the "newIB" parent dropdown container given the class .ccc and the underlying nested ul as .ddd.

.footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  text-align: center;
  font: inherit;
  font-size: 10px;
  color: white;
}

a, a:hover, a:active, a:visited {
    color: white;
}

.buttons {
  position: absolute;
  text-align: center;
}

.set:not(:last-child) {
  border-bottom: 1px dotted #aaa;
}

html, body, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
    z-index: 1;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

/* Default Styles
--------------------------------------------------------------------*/

body {
    background: url('img/denim.png');
    font-family: 'Droid Sans', sans-serif;;
}

.clearfix {
    clear: both;
}

.wrap {
    width: 940px;
    margin: 4em auto;
}

nav {
    background: -webkit-gradient(linear, center top, center bottom, from(#fff), to(#ccc));
    background-image: linear-gradient(#fff, #ccc);
    border-radius: 6px;
    box-shadow: 0px 0px 4px 2px rgba(0,0,0,0.4);
    padding: 0 10px;
    position: relative;
}

.menu li {
    float: left;
    position: relative;
}

.menu li a {
    color: #444;
    display: block;
    font-size: 14px;
    line-height: 20px;
    padding: 6px 12px;
    margin: 8px 8px;
    vertical-align: middle;
    text-decoration: none;
}

.menu li a:hover {
    background: -webkit-gradient(linear, center top, center bottom, from(#ededed), to(#fff));
    background-image: linear-gradient(#ededed, #fff);
    border-radius: 12px;
    box-shadow: inset 0px 0px 1px 1px rgba(0,0,0,0.1);
    color: #222;
}

/* Dropdown styles */

.menu ul {
    position: absolute;
    list-style: none;
}

.menu ul a {
    white-space: nowrap;
}

/* Displays the dropdown on hover and moves back into position */
.menu li:hover ul {
    background: rgba(255,255,255,0.7);
    border-radius: 0 0 6px 6px;
    box-shadow: inset 0px 2px 4px rgba(0,0,0,0.4);
}

.aaa:hover .bbb {
  display: block;
}

.bbb {
  display: none;
}

.ccc:hover .ddd {
  display: block;
}

.ddd {
  display: none;
}

/* Persistant Hover State */

.menu li:hover a {
    background: -webkit-gradient(linear, center top, center bottom, from(#ccc), to(#ededed));
    background-image: linear-gradient(#ccc, #ededed);
    border-radius: 12px;
    box-shadow: inset 0px 0px 1px 1px rgba(0,0,0,0.1);
    color: #222;
}

.menu li:hover ul a {
    background: none;
    border-radius: 0;
    box-shadow: none;
}

.menu li:hover ul li a:hover {
    background: -webkit-gradient(linear, center top, center bottom, from(#eee), to(#fff));
    background-image: linear-gradient(#ededed, #fff);
    border-radius: 12px;
    box-shadow: inset 0px 0px 4px 2px rgba(0,0,0,0.3);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="wrap">

  <nav>
    <ul class="menu">
      <li><span class="iconic home"></span> Home</li>
      <li class="ccc"><span class="iconic magnifying-glass"></span> newIB
        <ul class="ddd">
          <li>111</li>
          <li>222</li>
          <li>333</li>
          <li>444</li>
          <li class="aaa">555
            <ul class="bbb">
              <li>test</li>
              <li>test</li>
              <li>test</li>
              <li>test</li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </nav>
</div></code>```

Modification: So that the drop-down doesn't disappear as pointed out by Vxp.

Title: CSS: hide <ul> on hover

Body:
I would like that menu with class "bbb" occurs only when user hover on link in class "aaa" (as a drop-down menu...)

I use css and I created some code:

.aaa:hover .bbb {
  opacity: 1;
}

.bbb {
  opacity: 0;
}

But it doesn't work as intended. Can you help mi to get where i am wrong? I tried also do i with display:none & display:block instead of opacity.

Modification: resolution below doesn't work because i have other css metods. Pasted it:

.footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  text-align: center;
  font: inherit;
  font-size: 10px;
  color: white;
}

a, a:hover, a:active, a:visited {
  color: white;
}

.buttons {
  position: absolute;
  text-align: center;
}

.set:not(:last-child) {
  border-bottom: 1px dotted #aaa;
}

html, body, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
  margin: 0;
  padding: 0;
  border: 0;
  font-size: 100%;
  font: inherit;
  vertical-align: baseline;
  z-index: 1;
}

/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
  display: block;
}

body {
  line-height: 1;
}

ol, ul {
  list-style: none;
}

blockquote, q {
  quotes: none;
}

blockquote:before, blockquote:after,
q:before, q:after {
  content: '';
  content: none;
}

table {
  border-collapse: collapse;
  border-spacing: 0;
}

/* Default Styles
--------------------------------------------------------------------*/

body {
  background: url('img/denim.png');
  font-family: 'Droid Sans', sans-serif;;
}

.clearfix {
  clear: both;
}

.wrap {
  width: 940px;
  margin: 4em auto;
}

nav {
  background: -webkit-gradient(linear, center top, center bottom, from(#fff), to(#ccc));
  background-image: linear-gradient(#fff, #ccc);
  border-radius: 6px;
  box-shadow: 0px 0px 4px 2px rgba(0,0,0,0.4);
  padding: 0 10px;
  position: relative;
}

.menu li {
  float: left;
  position: relative;
}

.menu li a {
  color: #444;
  display: block;
  font-size: 14px;
  line-height: 20px;
  padding: 6px 12px;
  margin: 8px 8px;
  vertical-align: middle;
  text-decoration: none;
}

.menu li a:hover {
  background: -webkit-gradient(linear, center top, center bottom, from(#ededed), to(#fff));
  background-image: linear-gradient(#ededed, #fff);
  border-radius: 12px;
  box-shadow: inset 0px 0px 1px 1px rgba(0,0,0,0.1);
  color: #222;
}

/* Dropdown styles */

.menu ul {
  position: absolute;
  left: -9999px;
  list-style: none;
  opacity: 0;
  transition: opacity 1s ease;
}

.menu ul li {
  float: none;
}

.menu ul a {
  white-space: nowrap;
}

/* Displays the dropdown on hover and moves back into position */
.menu li:hover ul {
  background: rgba(255,255,255,0.7);
  border-radius: 0 0 6px 6px;
  box-shadow: inset 0px 2px 4px rgba(0,0,0,0.4);
  left: 5px;
  opacity: 1;
}

.aaa:hover .bbb {
  display: block;
}

.bbb {
  display: none;
}

/* Persistant Hover State */

.menu li:hover a {
  background: -webkit-gradient(linear, center top, center bottom, from(#ccc), to(#ededed));
  background-image: linear-gradient(#ccc, #ededed);
  border-radius: 12px;
  box-shadow: inset 0px 0px 1px 1px rgba(0,0,0,0.1);
  color: #222;
}

.menu li:hover ul a {
  background: none;
  border-radius: 0;
  box-shadow: none;
}

.menu li:hover ul li a:hover {
  background: -webkit-gradient(linear, center top, center bottom, from(#eee), to(#fff));
  background-image: linear-gradient(#ededed, #fff);
  border-radius: 12px;
  box-shadow: inset 0px 0px 4px 2px rgba(0,0,0,0.3);
}

 Home

 newIB

111

222

333

444

555

test

test

test

test

Body:
Apply the class on .bbb on ul instead of li (this is because you're trying to make a drop down and display the entire unordered-list instead of just one of the nested li) which is a direct child of class .aaa and use display:none and display:block as shown and it should work fine. The same criteria is applied on the "newIB" parent dropdown container given the class .ccc and the underlying nested ul as .ddd.

.footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 1rem;
  text-align: center;
  font: inherit;
  font-size: 10px;
  color: white;
}

a, a:hover, a:active, a:visited {
    color: white;
}

.buttons {
  position: absolute;
  text-align: center;
}

.set:not(:last-child) {
  border-bottom: 1px dotted #aaa;
}

html, body, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
    margin: 0;
    padding: 0;
    border: 0;
    font-size: 100%;
    font: inherit;
    vertical-align: baseline;
    z-index: 1;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure,
footer, header, hgroup, menu, nav, section {
    display: block;
}
body {
    line-height: 1;
}
ol, ul {
    list-style: none;
}
blockquote, q {
    quotes: none;
}
blockquote:before, blockquote:after,
q:before, q:after {
    content: '';
    content: none;
}
table {
    border-collapse: collapse;
    border-spacing: 0;
}

/* Default Styles
--------------------------------------------------------------------*/

body {
    background: url('img/denim.png');
    font-family: 'Droid Sans', sans-serif;;
}

.clearfix {
    clear: both;
}

.wrap {
    width: 940px;
    margin: 4em auto;
}

nav {
    background: -webkit-gradient(linear, center top, center bottom, from(#fff), to(#ccc));
    background-image: linear-gradient(#fff, #ccc);
    border-radius: 6px;
    box-shadow: 0px 0px 4px 2px rgba(0,0,0,0.4);
    padding: 0 10px;
    position: relative;
}

.menu li {
    float: left;
    position: relative;
}

.menu li a {
    color: #444;
    display: block;
    font-size: 14px;
    line-height: 20px;
    padding: 6px 12px;
    margin: 8px 8px;
    vertical-align: middle;
    text-decoration: none;
}

.menu li a:hover {
    background: -webkit-gradient(linear, center top, center bottom, from(#ededed), to(#fff));
    background-image: linear-gradient(#ededed, #fff);
    border-radius: 12px;
    box-shadow: inset 0px 0px 1px 1px rgba(0,0,0,0.1);
    color: #222;
}

/* Dropdown styles */

.menu ul {
    position: absolute;
    list-style: none;
}

.menu ul a {
    white-space: nowrap;
}

/* Displays the dropdown on hover and moves back into position */
.menu li:hover ul {
    background: rgba(255,255,255,0.7);
    border-radius: 0 0 6px 6px;
    box-shadow: inset 0px 2px 4px rgba(0,0,0,0.4);
}

.aaa:hover .bbb {
  display: block;
}

.bbb {
  display: none;
}

.ccc:hover .ddd {
  display: block;
}

.ddd {
  display: none;
}

/* Persistant Hover State */

.menu li:hover a {
    background: -webkit-gradient(linear, center top, center bottom, from(#ccc), to(#ededed));
    background-image: linear-gradient(#ccc, #ededed);
    border-radius: 12px;
    box-shadow: inset 0px 0px 1px 1px rgba(0,0,0,0.1);
    color: #222;
}

.menu li:hover ul a {
    background: none;
    border-radius: 0;
    box-shadow: none;
}

.menu li:hover ul li a:hover {
    background: -webkit-gradient(linear, center top, center bottom, from(#eee), to(#fff));
    background-image: linear-gradient(#ededed, #fff);
    border-radius: 12px;
    box-shadow: inset 0px 0px 4px 2px rgba(0,0,0,0.3);
}

<div class="wrap">

  <nav>
    <ul class="menu">
      <li><a href="#"><span class="iconic home"></span> Home</a></li>
      <li class="ccc"><a href="#"><span class="iconic magnifying-glass"></span> newIB</a>
        <ul class="ddd">
          <li><a href="#">111</a></li>
          <li><a href="#">222</a></li>
          <li><a href="#">333</a></li>
          <li><a href="#">444</a></li>
          <li class="aaa"><a href="www.example.pl">555</a>
            <ul class="bbb">
              <li><a href="https://www.example.pl">test</a></li>
              <li><a href="https://www.example.pl">test</a></li>
              <li><a href="https://www.example.pl">test</a></li>
              <li><a href="https://www.example.pl">test</a></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </nav>
</div>

Modification: So that the drop-down doesn't disappear as pointed out by Vxp.


答:
I'm not sure if I understand what you need correctly - the question is very confusing. What you SEEM to be asking is:

You have a complicated nested XML. E.g. <t1><t2><t3>value</t3></t2></t1>

You seem to want to access contents of tag <t3> but without needing to go through the hash keys in a hash-of-hash-of... data structure that XML::Simple creates to represent the DOM. E.g. you don't want to do $xml->{t1}->{t2}->{t3}.

If that's the case, your problem is that you are using a DOM parser. A SAX parser (like XML::Twig) lets you execute events upon parsing specific tags, e.g. t3 no matter where in the sructure that tag is.

If your problem is that you just don't know which tags exist (as keys in the hash),
you can do keys %$xml or keys %{ $xml->{t1} } to list them.

UPDATE

To loop using your example:

```<code>foreach my $key (keys %$xml) { # $key will be esxi01, etc...
    foreach my $attribute (keys %{ $xml->{$key} }) {
        "Key: $key; attribute: $attribute; value: $xml->{$key}->{$attribute}\n";
    }
    print "Port for $key: $xml->{$key}->{port}\n"; # Hardcoded
}
</code>```

UPDATE2

The problem is in the <Setup>FALSE</Setup> XML tag. It has no subtags, so in the hash its value will be a SCALAR and not a hash.  To fix, you need to check that the inner element is, indeed, a hash:

```<code>foreach my $server (keys %$xml_file) {
    next if (ref ($xml_file->{$server}) ne ref({})); # Not a hash
    foreach my $attribute (keys %{$xml_file->{$server}}) {
        print "$attribute\n";
    }
}
</code>```

Title: Can anyone recommend solution to my situation with XML

Body:
Sorry for not being clear.
The problem I am trying to convey is that XML::Simple does not allow me direct access to the hash, I must refer to the key in question through the XML::Simple module. Using something like $xml->{key}.

Here is the code I am using and a copy of the hash output.

The reason this is a problem is because I need to construct a series of loops using the keys of the hash [seen below], and I cannot build a foreach loop with a hash referrence, when I tried it, perl gave me an error.

So what I am looking for is a module or solution to allow me to dump the contents of the XML file to a hash that I declare in my script. I also need the ability to write back out to an XML file.

#!/usr/bin/perl
use strict;
use warnings;
use XML::Simple;
use Data::Dumper;

system ("clear");

my $xml = XML::Simple->new;

# Using the XML::Simple object, read guest_os.xml to a hash

my $xml_file = $xml->XMLin('config.xml',

                SearchPath => './config',

                SuppressEmpty => 1);

$VAR1 = \{
        'esxi01' => {
                    'password' => 'myspoonistoobig!',
                    'user' => 'root',
                    'port' => '22'
                  },
        'esxi02' => {
                    'password' => 'myspoonistoobig!',
                    'user' => 'root',
                    'port' => '22'
                  },
        'Setup' => 'FALSE'
      };

For me to access a single key/values in the hash that is created [above] I have to use something like this.

$xml_file->{esxi01}{password}.

Oh yeah I forgot the actual XML file.

<Config>
  <esxi01>
    <password>password</password>
    <port>22</port>
    <user>root</user>
  </esxi01>
  <esxi02>
    <password>password</password>
    <port>22</port>
    <user>root</user>
  </esxi02>
  <Setup>FALSE</Setup>
</Config>

This is the simplest of the 3 or so I have.

Update:

The first part of the loop works with no problem, the problem happens when I try to use the second part of the loop.

Here is the way my code looks

my $xml = XML::Simple->new;

# Using the XML::Simple object, read guest_os.xml to a hash

my $xml_file = $xml->XMLin('config.xml',

                SearchPath => './config',

                SuppressEmpty => 1);

foreach my $server (keys %$xml_file) {
    foreach my $attribute (keys %{$xml_file->{$server}}) {
        print "$attribute\n";
    }
}

The output looks like this,

Can't use string ("password") as a HASH ref while "strict refs" in use at foreach_test line 21.

I have tried using quotes in several places to fix the problem but nothing seems to work.

Body:
I'm not sure if I understand what you need correctly - the question is very confusing. What you SEEM to be asking is:

You have a complicated nested XML. E.g. <t1><t2><t3>value</t3></t2></t1>

You seem to want to access contents of tag <t3> but without needing to go through the hash keys in a hash-of-hash-of... data structure that XML::Simple creates to represent the DOM. E.g. you don't want to do $xml->{t1}->{t2}->{t3}.

If that's the case, your problem is that you are using a DOM parser. A SAX parser (like XML::Twig) lets you execute events upon parsing specific tags, e.g. t3 no matter where in the sructure that tag is.

If your problem is that you just don't know which tags exist (as keys in the hash),
you can do keys %$xml or keys %{ $xml->{t1} } to list them.

UPDATE

To loop using your example:

foreach my $key (keys %$xml) { # $key will be esxi01, etc...
    foreach my $attribute (keys %{ $xml->{$key} }) {
        "Key: $key; attribute: $attribute; value: $xml->{$key}->{$attribute}\n";
    }
    print "Port for $key: $xml->{$key}->{port}\n"; # Hardcoded
}

UPDATE2

The problem is in the <Setup>FALSE</Setup> XML tag. It has no subtags, so in the hash its value will be a SCALAR and not a hash.  To fix, you need to check that the inner element is, indeed, a hash:

foreach my $server (keys %$xml_file) {
    next if (ref ($xml_file->{$server}) ne ref({})); # Not a hash
    foreach my $attribute (keys %{$xml_file->{$server}}) {
        print "$attribute\n";
    }
}


问:
How to add string to file using sed instead of from file
```<code>red
blue
water
gray
white
</code>```

I want to use

sed '/blue/,/gray/!b;//!d;/blue/r file2' file1

As mentioned in this Replace text between two lines with contents of a file stored in a variable in sed thread

But instead of file2 i want to enter new string directly in command. Can any one show me how to do that.

答:
You can use this sed:

```<code>sed '/blue/,/gray/!b;//!d;/blue/a SOMEDATA' file
</code>```

From man sed:

```<code>a \
  text
</code>```

Append text, which has each embedded newline preceded by a backslash.

Another example:

```<code>$ sed '/blue/,/gray/!b;//!d;/blue/a \
> LINE 1 \
> LINE 2 \
> LINE 3' file

red
blue
LINE 1
LINE 2
LINE 3
gray
white
</code>```

Body:
red
blue
water
gray
white

I want to use

sed '/blue/,/gray/!b;//!d;/blue/r file2' file1

As mentioned in this Replace text between two lines with contents of a file stored in a variable in sed thread

But instead of file2 i want to enter new string directly in command. Can any one show me how to do that.

Body:
You can use this sed:

sed '/blue/,/gray/!b;//!d;/blue/a SOMEDATA' file

From man sed:

a \
  text

Append text, which has each embedded newline preceded by a backslash.

Another example:

$ sed '/blue/,/gray/!b;//!d;/blue/a \
> LINE 1 \
> LINE 2 \
> LINE 3' file

red
blue
LINE 1
LINE 2
LINE 3
gray
white


答: Just add android:padding="5dp" . It will work .

Body:
I created an EditText with a drawable image. The problem is that the image is very close to the border of the EditText, is there a way to adjust it?

Note: Im using an svg file for the image

Image: In the image you can see the shoulder of the person is almost touching the left border

Code:

        <EditText

            android:id="@+id/sampleName"
            android:drawableStart="@drawable/sampleImage"
            android:drawablePadding="10dp"
            android:layout_height="wrap_content"
            android:maxLines="1"
            android:layout_width="match_parent"
            android:background="@color/white"

            android:layout_marginLeft="5dp"
            />


问:
Getting Same Rectangle Position from Scaled Small Size Image
I'm trying to process a large size image.Since the processing takes too much time to complete i'm resizing the image prior processing.After processing i'm drawing a rectangle on the small size image.How can i translate the the coordinates of this rectangle to original unscaled image ie:Draw the rectangle at the same position on the unscaled image.

I'm using the following code to resize the image

```<code>public static Size ResizeKeepAspect(Size CurrentDimensions, int maxWidth, int maxHeight)
{
    int newHeight = CurrentDimensions.Height;
    int newWidth = CurrentDimensions.Width;
    if (maxWidth > 0 && newWidth > maxWidth) //WidthResize
    {
        Decimal divider = Math.Abs((Decimal)newWidth / (Decimal)maxWidth);
        newWidth = maxWidth;
        newHeight = (int)Math.Round((Decimal)(newHeight / divider));
    }
    if (maxHeight > 0 && newHeight > maxHeight) //HeightResize
    {
        Decimal divider = Math.Abs((Decimal)newHeight / (Decimal)maxHeight);
        newHeight = maxHeight;
        newWidth = (int)Math.Round((Decimal)(newWidth / divider));
    }
    return new Size(newWidth, newHeight);
}
</code>```

This is what im trying to achieve

答:
It's a simple relation calculation. For example:</p>

```<code>Image A 100 (w) x 100 (h): Pixel x = 10, y = 30
Image B 200 (w) x 200 (h): Pixel x = a, y = b

10 / 100 (w) = a / 200 (w)
200 (w) * 10 / 100 (w) = a //Image B's x value
a = 20

30 / 100 (h) = b / 200 (h)
200 (h) * 30 / 100 (h) = b //Image A's y value
b = 60
</code>```

Body:
I'm trying to process a large size image.Since the processing takes too much time to complete i'm resizing the image prior processing.After processing i'm drawing a rectangle on the small size image.How can i translate the the coordinates of this rectangle to original unscaled image ie:Draw the rectangle at the same position on the unscaled image.

I'm using the following code to resize the image

public static Size ResizeKeepAspect(Size CurrentDimensions, int maxWidth, int maxHeight)
{
    int newHeight = CurrentDimensions.Height;
    int newWidth = CurrentDimensions.Width;
    if (maxWidth > 0 && newWidth > maxWidth) //WidthResize
    {
        Decimal divider = Math.Abs((Decimal)newWidth / (Decimal)maxWidth);
        newWidth = maxWidth;
        newHeight = (int)Math.Round((Decimal)(newHeight / divider));
    }
    if (maxHeight > 0 && newHeight > maxHeight) //HeightResize
    {
        Decimal divider = Math.Abs((Decimal)newHeight / (Decimal)maxHeight);
        newHeight = maxHeight;
        newWidth = (int)Math.Round((Decimal)(newWidth / divider));
    }
    return new Size(newWidth, newHeight);
}

This is what im trying to achieve

Body:
It's a simple relation calculation. For example:

Image A 100 (w) x 100 (h): Pixel x = 10, y = 30
Image B 200 (w) x 200 (h): Pixel x = a, y = b

10 / 100 (w) = a / 200 (w)
200 (w) * 10 / 100 (w) = a //Image B's x value
a = 20

30 / 100 (h) = b / 200 (h)
200 (h) * 30 / 100 (h) = b //Image A's y value
b = 60

ContentLicense: CC BY-SA 4.0