问:
How to setState the object of the object of state
Goal: I have two square and I want to change selected square's location. While I'm doing it, I need to change selected square's x-coordinate, y-coordinate, width, and height.

Here is my state which holds the data for square information.

```<code>state = {
    gestureState: {},
    thumbSize: 100,
    left: width(100) / 2,
    top: height(100) / 2,
    taggedClothes: {
      0: {id:0, left:100, top:100, thumbSize:100}, <- I want to setState this
      1: {id:1, left:200, top:200, thumbSize:200},
    },
    selectedClothId : 0,
  }
</code>```

Problem: taggedClothes have two square information and I want to change only selected problem but I'm getting compile error

Here I'm performing setState its taggedClothes[0]

```<code>// this.state.selectedColorId = 0
var deep = _.cloneDeep(this.state.taggedClothes[this.state.selectedColorId]);
          deep.left = left
          deep.top = top
          deep.thumbSize = thumbSize
          this.setState({
            gestureState: {
              ...gestureState
            },
            taggedClothes[0]: deep  <- Getting Compile Error
          })
</code>```

If your have any other suggestion, Please suggest other option!

答:
The key taggedClothes[0] is not valid.  You need to spread the taggedClothes and only replace the one that changed:

```<code>  var deep = _.cloneDeep(this.state.taggedClothes[this.state.selectedColorId]);
  deep.left = left
  deep.top = top
  deep.thumbSize = thumbSize
  this.setState({
    gestureState: {
      ...gestureState
    },
    taggedClothes: {
      ...taggedClothes,
      [this.state.selectedColorId]: deep
    }
  })
</code>```

Body:
Goal: I have two square and I want to change selected square's location. While I'm doing it, I need to change selected square's x-coordinate, y-coordinate, width, and height.

Here is my state which holds the data for square information.

state = {
    gestureState: {},
    thumbSize: 100,
    left: width(100) / 2,
    top: height(100) / 2,
    taggedClothes: {
      0: {id:0, left:100, top:100, thumbSize:100}, <- I want to setState this
      1: {id:1, left:200, top:200, thumbSize:200},
    },
    selectedClothId : 0,
  }

Problem: taggedClothes have two square information and I want to change only selected problem but I'm getting compile error

Here I'm performing setState its taggedClothes[0]

// this.state.selectedColorId = 0
var deep = _.cloneDeep(this.state.taggedClothes[this.state.selectedColorId]);
          deep.left = left
          deep.top = top
          deep.thumbSize = thumbSize
          this.setState({
            gestureState: {
              ...gestureState
            },
            taggedClothes[0]: deep  <- Getting Compile Error
          })

If your have any other suggestion, Please suggest other option!

Body:
The key taggedClothes[0] is not valid.  You need to spread the taggedClothes and only replace the one that changed:

  var deep = _.cloneDeep(this.state.taggedClothes[this.state.selectedColorId]);
  deep.left = left
  deep.top = top
  deep.thumbSize = thumbSize
  this.setState({
    gestureState: {
      ...gestureState
    },
    taggedClothes: {
      ...taggedClothes,
      [this.state.selectedColorId]: deep
    }
  })


来源: stackexchange

问:
Log4j2 does not change logging level at runtime
Yes, I've read all the related questions. I am using log4j2 (tried both version 2.4 and updating to latest, version 2.6.2).

I have a small utility program for customers. I'm keen to keep exposed configurations at minimum. But for problematic cases, I'd also want to add a -debug flag to enable debug logs at runtime.

Here is my code to enable debug logging

```<code>private static void enableDebugLogs(){
    LoggerContext ctx = (LoggerContext) LogManager.getContext();
    LoggerConfig log = ctx.getConfiguration().getRootLogger();

    System.out.println(log.getLevel()); // INFO

    log.setLevel(Level.DEBUG);

    System.out.println(log.getLevel()); // DEBUG

    ctx.updateLoggers();

    System.out.println(ctx.getRootLogger().getLevel()); // DEBUG, hey it works, right?
}
</code>```

But it does not actually work with any of these cases:

```<code>enableDebugLogs();
logger.debug("Debug mode on"); // static, already made logger. Level did not change

LogManager.getLogger(Main.class).debug("Debug"); // Nope, not printing

Logger root = LogManager.getRootLogger();
root.info("Level: " + root.getLevel());  // Level: INFO, should be DEBUG
</code>```

The utility program is finished usually in less than 30 seconds, so the change should be instant. Here is the log4j2.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level - %msg%n"/>
        </Console>
        <RollingFile name="File" fileName="program_name.log" filePattern="program_name-archived.log">
            <PatternLayout>
                <Pattern>%d{HH:mm:ss.SSS} %-5level - %msg%n</Pattern>
            </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="10 KB" />
            </Policies>
            <DefaultRolloverStrategy min="1" max="1"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="File"/>
        </Root>
    </Loggers>
</Configuration>
</code>```

Is the problem with usings AppenderRefs? Can I somehow tell the Appenders to update logging level from Root logger?

答:
You can change switch the logging configuration between two or multiple log4j2.xml files.

For example, create two log4j2.xml files with different configurations. log4j2.xml & log4j2-debug.xml and pass it to below code.

```<code>ConfigurationFactory configFactory = XmlConfigurationFactory.getInstance();
            ConfigurationFactory.setConfigurationFactory(configFactory);
            LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            InputStream inputStream = classloader.getResourceAsStream(logFileName);
            ConfigurationSource configurationSource = new ConfigurationSource(inputStream);

            ctx.start(configFactory.getConfiguration(ctx, configurationSource));
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Yes, I've read all the related questions. I am using log4j2 (tried both version 2.4 and updating to latest, version 2.6.2).

I have a small utility program for customers. I'm keen to keep exposed configurations at minimum. But for problematic cases, I'd also want to add a -debug flag to enable debug logs at runtime.

Here is my code to enable debug logging

private static void enableDebugLogs(){
    LoggerContext ctx = (LoggerContext) LogManager.getContext();
    LoggerConfig log = ctx.getConfiguration().getRootLogger();

    System.out.println(log.getLevel()); // INFO

    log.setLevel(Level.DEBUG);

    System.out.println(log.getLevel()); // DEBUG

    ctx.updateLoggers();

    System.out.println(ctx.getRootLogger().getLevel()); // DEBUG, hey it works, right?
}

But it does not actually work with any of these cases:

enableDebugLogs();
logger.debug("Debug mode on"); // static, already made logger. Level did not change

LogManager.getLogger(Main.class).debug("Debug"); // Nope, not printing

Logger root = LogManager.getRootLogger();
root.info("Level: " + root.getLevel());  // Level: INFO, should be DEBUG

The utility program is finished usually in less than 30 seconds, so the change should be instant. Here is the log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level - %msg%n"/>
        </Console>
        <RollingFile name="File" fileName="program_name.log" filePattern="program_name-archived.log">
            <PatternLayout>
                <Pattern>%d{HH:mm:ss.SSS} %-5level - %msg%n</Pattern>
            </PatternLayout>
            <Policies>
                <SizeBasedTriggeringPolicy size="10 KB" />
            </Policies>
            <DefaultRolloverStrategy min="1" max="1"/>
        </RollingFile>
    </Appenders>
    <Loggers>
        <Root level="info">
            <AppenderRef ref="Console"/>
            <AppenderRef ref="File"/>
        </Root>
    </Loggers>
</Configuration>

Is the problem with usings AppenderRefs? Can I somehow tell the Appenders to update logging level from Root logger?

Body:
You can change switch the logging configuration between two or multiple log4j2.xml files.

For example, create two log4j2.xml files with different configurations. log4j2.xml & log4j2-debug.xml and pass it to below code.

ConfigurationFactory configFactory = XmlConfigurationFactory.getInstance();
            ConfigurationFactory.setConfigurationFactory(configFactory);
            LoggerContext ctx = (LoggerContext) LogManager.getContext(false);
            ClassLoader classloader = Thread.currentThread().getContextClassLoader();
            InputStream inputStream = classloader.getResourceAsStream(logFileName);
            ConfigurationSource configurationSource = new ConfigurationSource(inputStream);

            ctx.start(configFactory.getConfiguration(ctx, configurationSource));


问:
Get all values related to id (ASP.NET MVC)
I have two tables Patients and appointments.

Here is model of patients

```<code> public partial class Patient
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Patient()
    {
        this.Appointments = new HashSet<Appointment>();
        this.Patient_to_investigation = new HashSet<Patient_to_investigation>();
        this.Patient_to_appointment = new HashSet<Patient_to_appointment>();
    }
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Sex { get; set; }
    public string Date_of_Birthday { get; set; }
    public string Adress { get; set; }
    public string Kind_of_medical_insurance { get; set; }
    public string Name_of_medical_insurance { get; set; }
    public string Patients_med_insurance { get; set; }
    public string Status_of_medical_insurance { get; set; }
    public string Index { get; set; }
    public string Country_code { get; set; }
    public string Phone { get; set; }
    public string Refering_organization { get; set; }
    public string Refering_health_center { get; set; }
    public string Refering_doctor { get; set; }
    public string Refering_organization_adress { get; set; }
    public string Additional_fuse { get; set; }
    public Nullable<System.DateTime> Last_edit { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Appointment> Appointments { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_investigation> Patient_to_investigation { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_appointment> Patient_to_appointment { get; set; }
}
</code>```

Here is Appointment model

```<code> public partial class Appointment
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Appointment()
    {
        this.Patient_to_appointment = new HashSet<Patient_to_appointment>();
        this.Appointments_to_Doctors = new HashSet<Appointments_to_Doctors>();
    }

    [Key]
    public int Id { get; set; }
    public string Start_appointment { get; set; }
    public string End_appointment { get; set; }
    public string Title { get; set; }
    public string Type_of_appointment { get; set; }
    [ForeignKey("Patient")]
    public Nullable<int> Patient_id { get; set; }
    public string Kasse { get; set; }
    public Nullable<System.DateTime> Date { get; set; }

    public virtual Patient Patient { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_appointment> Patient_to_appointment { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Appointments_to_Doctors> Appointments_to_Doctors { get; set; }
}
</code>```

Also I have table to connect patient with appointments (because of one patient may have several appointments)

```<code>public partial class Patient_to_appointment
{
    [Key]
    public int Id { get; set; }
    public int Patient_id { get; set; }
    public Nullable<int> Appointment_id { get; set; }
    [ForeignKey("Appointment_id")]
    public virtual Appointment Appointment { get; set; }
    [ForeignKey("Patient_id")]
    public virtual Patient Patient { get; set; }
}
</code>```

In view I have button that on click get patients name and get id of this patient.

Here is code how I do this on back end

```<code>  var id = ctx.Patients.Where(x => x.Name == name).Select(x=> new
            {
                id = x.Id
            });
</code>```

After this I need to get all appointments Title for this patient id.

How I need to write query correctly?

答:
Please note that the 'id' is going to be enumerable type.

So you could write

```<code>List<string> appointmentTitles = new List<string>();
foreach (int patientId in id)
{
    var patientAppointment = ctx.Appointments.Where(x => x.Patient_id == patientId);
    if (patientAppointment != null && patientAppointment.Any())
    {
    // note there can be multiple appointments
        foreach (var appointment from patientAppointment)
        {
            appointmentTitles.Add(appointment.Title)
        }
    }
}
</code>```

Body:
I have two tables Patients and appointments.

Here is model of patients

 public partial class Patient
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Patient()
    {
        this.Appointments = new HashSet<Appointment>();
        this.Patient_to_investigation = new HashSet<Patient_to_investigation>();
        this.Patient_to_appointment = new HashSet<Patient_to_appointment>();
    }
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Sex { get; set; }
    public string Date_of_Birthday { get; set; }
    public string Adress { get; set; }
    public string Kind_of_medical_insurance { get; set; }
    public string Name_of_medical_insurance { get; set; }
    public string Patients_med_insurance { get; set; }
    public string Status_of_medical_insurance { get; set; }
    public string Index { get; set; }
    public string Country_code { get; set; }
    public string Phone { get; set; }
    public string Refering_organization { get; set; }
    public string Refering_health_center { get; set; }
    public string Refering_doctor { get; set; }
    public string Refering_organization_adress { get; set; }
    public string Additional_fuse { get; set; }
    public Nullable<System.DateTime> Last_edit { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Appointment> Appointments { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_investigation> Patient_to_investigation { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_appointment> Patient_to_appointment { get; set; }
}

Here is Appointment model

 public partial class Appointment
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Appointment()
    {
        this.Patient_to_appointment = new HashSet<Patient_to_appointment>();
        this.Appointments_to_Doctors = new HashSet<Appointments_to_Doctors>();
    }

    [Key]
    public int Id { get; set; }
    public string Start_appointment { get; set; }
    public string End_appointment { get; set; }
    public string Title { get; set; }
    public string Type_of_appointment { get; set; }
    [ForeignKey("Patient")]
    public Nullable<int> Patient_id { get; set; }
    public string Kasse { get; set; }
    public Nullable<System.DateTime> Date { get; set; }

    public virtual Patient Patient { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Patient_to_appointment> Patient_to_appointment { get; set; }
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<Appointments_to_Doctors> Appointments_to_Doctors { get; set; }
}

Also I have table to connect patient with appointments (because of one patient may have several appointments)

public partial class Patient_to_appointment
{
    [Key]
    public int Id { get; set; }
    public int Patient_id { get; set; }
    public Nullable<int> Appointment_id { get; set; }
    [ForeignKey("Appointment_id")]
    public virtual Appointment Appointment { get; set; }
    [ForeignKey("Patient_id")]
    public virtual Patient Patient { get; set; }
}

In view I have button that on click get patients name and get id of this patient.

Here is code how I do this on back end

  var id = ctx.Patients.Where(x => x.Name == name).Select(x=> new
            {
                id = x.Id
            });

After this I need to get all appointments Title for this patient id.

How I need to write query correctly?

Body:
Please note that the 'id' is going to be enumerable type.

So you could write

List<string> appointmentTitles = new List<string>();
foreach (int patientId in id)
{
    var patientAppointment = ctx.Appointments.Where(x => x.Patient_id == patientId);
    if (patientAppointment != null && patientAppointment.Any())
    {
    // note there can be multiple appointments
        foreach (var appointment from patientAppointment)
        {
            appointmentTitles.Add(appointment.Title)
        }
    }
}


问:
How can i get this warn out from my project?
How can I get rid of the following warning out in my project? My team doesn't have this warning like me.

npm WARN @angular/compiler-cli@5.0.1 requires a peer of typescript@>=2.4.2 <2.5 but none is installed. You must install peer dependencies yourself.

npm WARN angular2-daterangepicker@0.0.5 requires a peer of @angular/core@2.0.0 but none is installed. You must install peer dependencies yourself.

npm WARN angular2-daterangepicker@0.0.5 requires a peer of bootstrap@^3.3.6 but none is installed. You must install peer dependencies yourself.

npm WARN angular2-daterangepicker@0.0.5 requires a peer of jquery@^2.2.4 but none is installed. You must install peer dependencies yourself.

npm WARN angular2-daterangepicker@0.0.5 requires a peer of rxjs@5.0.0-beta.6 but none is installed. You must install peer dependencies yourself.

npm WARN angular2-daterangepicker@0.0.5 requires a peer of zone.js@^0.6.12 but none is installed. You must install peer dependencies yourself.

npm WARN ng2-daterangepicker@2.0.12 requires a peer of @types/jquery@^3.2.12 but none is installed. You must install peer dependencies yourself.

npm WARN thruway.js@1.2.13 requires a peer of ws@^2.2.1 but none is installed. You must install peer dependencies yourself.

npm WARN tsickle@0.24.1 requires a peer of typescript@2.4.2 but none is installed. You must install peer dependencies yourself.

答:
You can try updating all angular packages as follows:</p>

```<code>npm install typescript@latest --save-dev

npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest --save
</code>```

Body:
You can try updating all angular packages as follows:

npm install typescript@latest --save-dev

npm install @angular/common@latest @angular/compiler@latest @angular/compiler-cli@latest @angular/core@latest @angular/forms@latest @angular/http@latest @angular/platform-browser@latest @angular/platform-browser-dynamic@latest @angular/platform-server@latest @angular/router@latest @angular/animations@latest --save


问:
Methods to insert or replace values in to object
I've got an object like this

```<code>var obj2= {
        'home' : {
            '1' : {
                  'year' : '1999'
                  },
            '2' : {
                  'year' : '2000'
                  'month' : '11'
                  },
        },
        'company' : {
            '1' : {
                  'year' : '2010'
                  'month' : '2'
                  },
        }
    };
</code>```

And I would like to add some more keys inside the object or replace value if this key chain already exists, for ex:

```<code>buss_type = "home",
type_id = "1",
date_type = "month",
value = "9"

var tmp_obj1 = {[buss_type]: {[type_id]: {[date_type]: value}}};
</code>```

and

```<code>buss_type = "company",
type_id = "2",
date_type = "month",
value = "12"

var tmp_obj2 = {[buss_type]: {[type_id]: {[date_type]: value}}};
</code>```

to make object:

```<code>obj = {
    'home' : {
        '1' : {
            'year' : '1999',
            'month' : '9'
        },
        '2' : {
            'year' : '2000',
            'month' : '11'
        },
    },
    'company' : {
        '1' : {
            'year' : '2020',
            'month' : '10'
        },
        '2' : {
            'month' : '12'
        }
    },
};
</code>```

Arrays methods like .push() or .concat() adding new keys on the end only instead of replacing values of existing ones.

Are there any object methods that can make it easy to manage or should I just use loops and check all keys before adding new or changing value of existing one?

Thanks.

答:
If you will only have objects without any methods inside, just simple JSON style objects. Then you can use something like

```<code>JSON.stringify(obj1) === JSON.stringify(obj2)
</code>```

Just be careful that the order of the object data is important. For example, this will return false

```<code> x = {a: 1, b: 2};
 y = {b: 2, a: 1};
</code>```

Body:
I've got an object like this

var obj2= {
        'home' : {
            '1' : {
                  'year' : '1999'
                  },
            '2' : {
                  'year' : '2000'
                  'month' : '11'
                  },
        },
        'company' : {
            '1' : {
                  'year' : '2010'
                  'month' : '2'
                  },
        }
    };

And I would like to add some more keys inside the object or replace value if this key chain already exists, for ex:

buss_type = "home",
type_id = "1",
date_type = "month",
value = "9"

var tmp_obj1 = {[buss_type]: {[type_id]: {[date_type]: value}}};

and

buss_type = "company",
type_id = "2",
date_type = "month",
value = "12"

var tmp_obj2 = {[buss_type]: {[type_id]: {[date_type]: value}}};

to make object:

obj = {
    'home' : {
        '1' : {
            'year' : '1999',
            'month' : '9'
        },
        '2' : {
            'year' : '2000',
            'month' : '11'
        },
    },
    'company' : {
        '1' : {
            'year' : '2020',
            'month' : '10'
        },
        '2' : {
            'month' : '12'
        }
    },
};

Arrays methods like .push() or .concat() adding new keys on the end only instead of replacing values of existing ones.

Are there any object methods that can make it easy to manage or should I just use loops and check all keys before adding new or changing value of existing one?

Thanks.

Body:
If you will only have objects without any methods inside, just simple JSON style objects. Then you can use something like

JSON.stringify(obj1) === JSON.stringify(obj2)

Just be careful that the order of the object data is important. For example, this will return false

 x = {a: 1, b: 2};
 y = {b: 2, a: 1};


问:
Correct way to write an ASP.NET MVC action returning a PartialViewResult
I have written an Action method for an ASP.NET MVC controller, which is being used to provide a model to a usercontrol.

public class ProductsController : Controller
    {

```<code>    public PartialViewResult ProductSummary()
    {
        ViewData.Model = new ProductSummaryModel("42"); // dummy data for now

        return new PartialViewResult()
        {
            ViewData = ViewData
        };
    }
}
</code>```

I am using the 'futures' Microsoft.Web.Mvc dll and rendering the control in my main view like this :

```<code><% Html.RenderAction<ProductsController>(x => x.ProductSummary()); %>
</code>```

What I have here appears to work just fine, but i attempted to google new PartialResult() to see if what I was doing was following the correct patterns.

Currently this search only comes up with 4 results!

So I figured I'm doing somethin wrong here in my controller. Whats the correct way to create an action method that returns a partial view? And what (if anything) is wrong or bad about what I'm doing.

答:
I usually just use:

```<code>return PartialView("MyView", myModel);
</code>```

But this just returns a new PartialViewResult("MyView", myModel) so it is potatoes/potatoes.

OwnerDisplayName: Simon

ContentLicense: CC BY-SA 2.5

Body:
I have written an Action method for an ASP.NET MVC controller, which is being used to provide a model to a usercontrol.

public class ProductsController : Controller
    {

    public PartialViewResult ProductSummary()
    {
        ViewData.Model = new ProductSummaryModel("42"); // dummy data for now

        return new PartialViewResult()
        {
            ViewData = ViewData
        };
    }
}

I am using the 'futures' Microsoft.Web.Mvc dll and rendering the control in my main view like this :

<% Html.RenderAction<ProductsController>(x => x.ProductSummary()); %>

What I have here appears to work just fine, but i attempted to google new PartialResult() to see if what I was doing was following the correct patterns.

Currently this search only comes up with 4 results!

So I figured I'm doing somethin wrong here in my controller. Whats the correct way to create an action method that returns a partial view? And what (if anything) is wrong or bad about what I'm doing.

Body:
I usually just use:

return PartialView("MyView", myModel);

But this just returns a new PartialViewResult("MyView", myModel) so it is potatoes/potatoes.

OwnerDisplayName: veggerby


问:
Xamarin Android spinner adapter strange bug
I'm having a problem creating a custom spinner adapter. I'm trying to make a country picker with the country's image on the left of each country item in the list. It runs with no errors, however there's a weird bug where the list items change positions when selecting an item and re-opening the spinner.

Here is my adapter class:

```<code>class SpinnerAdapter : BaseAdapter, ISpinnerAdapter
{
    private string[] data;
    private string[] dataValues;
    private Context context;
    private LayoutInflater inflater;
    private bool drawableFlags;

    public SpinnerAdapter(Context _context, string[] _data, string[] _dataValues, bool _drawableFlags)
        :base()
    {
        context = _context;
        data = _data;
        dataValues = _dataValues;
        drawableFlags = _drawableFlags;

    }
    public override int Count => data.Length;

    public override Java.Lang.Object GetItem(int position)
    {
        return data[position];
    }

    public override long GetItemId(int position)
    {
        //throw new NotImplementedException();
        return (long)position;
    }

    public string GetItemValue(int position)
    {
        return data[position];
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        //throw new NotImplementedException();
        View view = convertView;
        SpinnerAdapterViewHolder holder = null;
        if (view != null)
        {
            holder = view.Tag as SpinnerAdapterViewHolder;
            string name = holder.CountryName.Text;

        }

        if(holder == null)
        {
            holder = new SpinnerAdapterViewHolder();
            var inflater = context.GetSystemService(Context.LayoutInflaterService).JavaCast<LayoutInflater>();
            //replace with your item and your holder items
            //comment back in
            view = inflater.Inflate(Resource.Layout.Spinner_Item_Layout, parent, false);
            holder.CountryName = view.FindViewById<TextView>(Resource.Id.SpinnerItem);
            holder.CountryName.Text = data[position];
            //holder.CountryValue = dataValues[position];
            if (drawableFlags)
            {
                Drawable flag = AppCommon.GetDrawableResourceByName("flag_" + dataValues[position], context);
                flag.SetBounds(10, 10, 10, 10);
                holder.CountryName.SetCompoundDrawablesWithIntrinsicBounds(flag, null, null, null);
            }
            view.Tag = holder;
        }
        return view;
    }

}

class SpinnerAdapterViewHolder : Java.Lang.Object
{
    public TextView CountryName { get; set; }
    public string CountryValue { get; set; }
}
</code>```

答:
Turns out I don't need any of the ViewHolder stuff. I just replaced the whole of the GetView function with this:

```<code>public override View GetView(int position, View convertView, ViewGroup parent)
    {
        var inflater = context.GetSystemService(Context.LayoutInflaterService).JavaCast<LayoutInflater>();

        convertView = inflater.Inflate(Resource.Layout.Spinner_Item_Layout, parent, false);
        TextView textview = convertView.FindViewById<TextView>(Resource.Id.SpinnerItem);
        textview.Text = data[position];
        if (drawableFlags)
            {
                Drawable flag = AppCommon.GetDrawableResourceByName("flag_" + dataValues[position], context);
                flag.SetBounds(10, 10, 10, 10);
                textview.SetCompoundDrawablesWithIntrinsicBounds(flag, null, null, null);
            }

        return convertView;
    }
</code>```

Problem solved :D

Body:
I'm having a problem creating a custom spinner adapter. I'm trying to make a country picker with the country's image on the left of each country item in the list. It runs with no errors, however there's a weird bug where the list items change positions when selecting an item and re-opening the spinner.

Here is my adapter class:

class SpinnerAdapter : BaseAdapter, ISpinnerAdapter
{
    private string[] data;
    private string[] dataValues;
    private Context context;
    private LayoutInflater inflater;
    private bool drawableFlags;

    public SpinnerAdapter(Context _context, string[] _data, string[] _dataValues, bool _drawableFlags)
        :base()
    {
        context = _context;
        data = _data;
        dataValues = _dataValues;
        drawableFlags = _drawableFlags;

    }
    public override int Count => data.Length;

    public override Java.Lang.Object GetItem(int position)
    {
        return data[position];
    }

    public override long GetItemId(int position)
    {
        //throw new NotImplementedException();
        return (long)position;
    }

    public string GetItemValue(int position)
    {
        return data[position];
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        //throw new NotImplementedException();
        View view = convertView;
        SpinnerAdapterViewHolder holder = null;
        if (view != null)
        {
            holder = view.Tag as SpinnerAdapterViewHolder;
            string name = holder.CountryName.Text;

        }

        if(holder == null)
        {
            holder = new SpinnerAdapterViewHolder();
            var inflater = context.GetSystemService(Context.LayoutInflaterService).JavaCast<LayoutInflater>();
            //replace with your item and your holder items
            //comment back in
            view = inflater.Inflate(Resource.Layout.Spinner_Item_Layout, parent, false);
            holder.CountryName = view.FindViewById<TextView>(Resource.Id.SpinnerItem);
            holder.CountryName.Text = data[position];
            //holder.CountryValue = dataValues[position];
            if (drawableFlags)
            {
                Drawable flag = AppCommon.GetDrawableResourceByName("flag_" + dataValues[position], context);
                flag.SetBounds(10, 10, 10, 10);
                holder.CountryName.SetCompoundDrawablesWithIntrinsicBounds(flag, null, null, null);
            }
            view.Tag = holder;
        }
        return view;
    }

}

class SpinnerAdapterViewHolder : Java.Lang.Object
{
    public TextView CountryName { get; set; }
    public string CountryValue { get; set; }
}

Body:
Turns out I don't need any of the ViewHolder stuff. I just replaced the whole of the GetView function with this:

public override View GetView(int position, View convertView, ViewGroup parent)
    {
        var inflater = context.GetSystemService(Context.LayoutInflaterService).JavaCast<LayoutInflater>();

        convertView = inflater.Inflate(Resource.Layout.Spinner_Item_Layout, parent, false);
        TextView textview = convertView.FindViewById<TextView>(Resource.Id.SpinnerItem);
        textview.Text = data[position];
        if (drawableFlags)
            {
                Drawable flag = AppCommon.GetDrawableResourceByName("flag_" + dataValues[position], context);
                flag.SetBounds(10, 10, 10, 10);
                textview.SetCompoundDrawablesWithIntrinsicBounds(flag, null, null, null);
            }

        return convertView;
    }

Problem solved :D


问:
Jquery resizable does not work
i am trying to use jquery-ui resizable.

here i am creating the resizable:

```<code>jQuery("#id404").resizable();
</code>```

here is the div after i created the resizable.

```<code><div style="right: 7px; top: 120px; left:0%; bottom:340px; position:absolute; overflow:visible; z-index:2; cursor:pointer;">
   <div
      id="id404"
      name="resizable_div"
      class="ui-resizable"
      style="position:relative; width:100%; height:100%; overflow:hidden;">
   <div class="ui-resizable-handle ui-resizable-e"></div>
   <div class="ui-resizable-handle ui-resizable-s"></div>
   <div class="ui-resizable-handle ui-resizable-se ui-icon ui-icon-gripsmall-diagonal-se" style="z-index: 1001; "></div>
</div>
</div>
</code>```

now, this does not work.

although the div becomes resizable (the handles appear, the icon changes etc) when i'm trying to resize the div box, it stays the same size no matter what i'm doing.
The resize process does occur, because while debugging this, the onStop and onStart callbacks did fire.

anyone can tell me what i did wrong?

i assume it is something to do with absolute divs.

thanks,

Tal

答:
I think you have a styling issue here. You have a container DIV with fixed High and Width. You are putting your re-sizable DIV inside it. So I think the container DIV is blocking the resize process.

Try to get rid of that DIV first to check if it's not the problem.

Title: Jquery resizable does not work

Body:
i am trying to use jquery-ui resizable.

here i am creating the resizable:

jQuery("#id404").resizable();

here is the div after i created the resizable.

now, this does not work.

although the div becomes resizable (the handles appear, the icon changes etc) when i'm trying to resize the div box, it stays the same size no matter what i'm doing.
The resize process does occur, because while debugging this, the onStop and onStart callbacks did fire.

anyone can tell me what i did wrong?

i assume it is something to do with absolute divs.

thanks,

Tal


问:
Get date string without separators in Rails
How to remove the -'s from the following string:

```<code>Date.today.to_s #=> "2016-04-11"
</code>```

using a single line of code.

Expected Result is

"2016 04 11"

答:
```<code>    puts 'Enter dob in dd-mm-yyyy format: '
    birthdate = Date.parse(gets)
    today = Time.now.strftime("%Y-%m-%d")
    (today.to_s.split('-').join.to_i - birthdate.to_s.split('-').join.to_i) / 10000
</code>```

Body:
How to remove the -'s from the following string:

Date.today.to_s #=> "2016-04-11"

using a single line of code.

Expected Result is

"2016 04 11"


问:
Submitting Spark job in HDInsight cluster for secure enabled storage account
When we try to submit Spark job using ADF or Livy in HDInsight 3.6, Spark 2.1 with Secure transfer required "Enabled" in associated storage account. It is not submitting Spark job and we are unable to see Spark Job in YARN UI, but the same way we are able to submit, if we disable this
Secure transfer required in associated storage account.

Please let us know how to Submit Spark job if Secure transfer required is "Enabled" in storage account.

答:
I got the solution for this problem.
Before creating HDinsight cluster keep ready below points.
**

```<code>1 Create azure storage account and create container where you want to put your jar or Spark related code.
2 While Configuring HDInsight cluster you use the above created storage account and container.
</code>```

**

Thanks,
Sudeep

Body:
I got the solution for this problem.
Before creating HDinsight cluster keep ready below points.
**

1 Create azure storage account and create container where you want to put your jar or Spark related code.
2 While Configuring HDInsight cluster you use the above created storage account and container.

**

Thanks,
Sudeep


答:
As mentioned by mkaran PCA requires a Vector column as an input. You have to assemble your data first, for example using VectorAsssembler or RFormula.

Please follow the examples in Encode and assemble multiple features in PySpark for details.

```<code>data = RFormula(formula=" ~ {0}".format(" + ".join(data.columns))).fit(data).transform(data)
dataPCA.setInputCol("features").fit(data).transform(data)
</code>```

Title: Perform PCA on pyspark dataframe

Body:
I have build a PySpark dataframe using:

data = sqlContext.read.load('data.csv' , format='com.databricks.spark.csv', delimiter = ',' ,header='true',inferSchema='true')

And I want to perform PCA on my dataframe
my dataframe schema is

>>data
DataFrame[col0: double, col1: double, col2: double, col3: double, col4: double]

>>> data.show()
+---------------+---------------+---------------+---------------+---------------+
|           col0|           col1|           col2|           col3|           col4|
+---------------+---------------+---------------+---------------+---------------+
|   -8.801490628| -1.68848604044|  6.29108688718|  1.68614762629| -2.78418041902|
|  6.99040350558| -2.79455708195| -5.57115314522|  4.22337477957|-0.366589003047|
|   6.8950808389|  7.65514024658|   8.0214838208| -5.12100927058|  3.17467779733|
|  6.74150161414|  1.19627062139| 0.821181991602|  5.12589137044| -3.86248588187|
|  9.15545404244|  7.80553468656|  -8.1232517076|   2.6242726214| -7.59049824307|
|   -6.014643738|-0.470165781449|-0.226389435704| -2.55837378209| -2.06405566854|
| -9.49629160445| -9.85331556717| -7.44474566663|  6.48359295657|  9.75680835864|
| 0.450876020546| -3.55454445478| -2.82100689682|  5.15104966779| -7.70810268078|
| -7.21960567005| 0.102168086158| -1.46779736909| -3.87897074493| -3.17592118456|
| -8.75820987524| -8.63519048007| -4.20447284625|-0.394878764685| -5.79070138764|
|  9.47825273869|  6.02827892008|  -9.7181540689|  -9.0341215112|  5.96203870171|
| -1.56616611175|  1.64353225245|  9.20883287312|-0.158689954569|  4.92646032432|
|-0.952144934546|  -2.9114138684|  2.99204980215| -4.64479019591| -5.99952901402|
|  3.55670956201|-0.812146671595| -1.81243042667|  -1.0765836636|   4.9669633757|
| -2.28427448245| 0.982018554172|   2.2453332695|  1.02432988704| -7.42272905399|
|   5.5901346625|   9.7266134961| 0.372411854139|  4.62762920616| -7.39599025974|
|  9.54828822231| -2.99982461624|  2.17542923571|  6.98459564802|  4.17077742377|
| -6.93309333389|  6.54244346903| 0.783827506295|  4.51631424946|  5.14605443379|
| -1.39844067044|  5.94842772889| 0.270728638304|  4.71245951003|  7.60767471606|
| -7.45885401935| -2.17059549479|  9.13976371571| -7.59189334493|  -2.3924001937|
+---------------+---------------+---------------+---------------+---------------+

To do that I have to work with pyspark.ml.feature so this is how I am doing it

dataPCA = PCA(k=2, inputCol=str(data.columns), outputCol="pcaFeatures")
model = dataPCA.fit(data)

and I am getting this error:

pyspark.sql.utils.IllegalArgumentException: u'Field "[\'col0\', \'col1\', \'col2\', \'col3\', \'col4\']" does not exist.

what's wrong and how to fix that?

Body:
As mentioned by mkaran PCA requires a Vector column as an input. You have to assemble your data first, for example using VectorAsssembler or RFormula.

Please follow the examples in Encode and assemble multiple features in PySpark for details.

data = RFormula(formula=" ~ {0}".format(" + ".join(data.columns))).fit(data).transform(data)
dataPCA.setInputCol("features").fit(data).transform(data)


问:
How to center 3 divs horizontally with itselfs?
I'm facing a problem:

I want to put 3 divs horizontally with itself, but i'm not getting to do it right.

Could someone help?

I've already searched a lot about properties in css and html, but i couldn't apply to what i'm doing.

With the normal zoom:
http://i.imgur.com/ylk5pm2.png

What i want:
http://i.imgur.com/47kzlpv.png

Codes:

    .container {
  width:100%;
  border-color: #FF0000;
  border-style: solid;
  border-width:medium;
  text-align:center;
  margin-bottom: 1%;
 }

 .menu_box_filtro{
  display:inline;
 }

 .conteudo_box_filtro{
  display:inline-block;
 }
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="border_preta">
  <div class="menu_box_filtro">
    <div class="grid_10 border_brown conteudo_box_filtro">

    </div>
  </div>
  <div class="menu_box_filtro">
    <div class="grid_63 border_brown conteudo_box_filtro">
      menu centro
    </div>
  </div>

  <div class="menu_box_filtro">
    <div class="grid_10 border_brown conteudo_box_filtro">
      menu direita
    </div>
  </div>
</div></code>```

答:
Check this

.container{
  width: 90%;
  max-width: 900px;
  margin: 0 auto;
  background-color:#F0A202;
}

.group{
content:"";
display:table;
clear:both;
}

div:nth-of-type(1) {
  width: 36%;
  float: left;

}

div:nth-of-type(2) {
  width: 30%;
  float: left;
  margin-left: 4%;

}

div:nth-of-type(3) {
  width: 26%;
  float: right;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container group">
  <div>
    <p>First<p>
  </div>

  <div>
    <p>Second<p>
  </div>

  <div>
    <p>Third<p>
  </div>
</div></code>```

Body:
I'm facing a problem:

I want to put 3 divs horizontally with itself, but i'm not getting to do it right.

Could someone help?

I've already searched a lot about properties in css and html, but i couldn't apply to what i'm doing.

With the normal zoom:
http://i.imgur.com/ylk5pm2.png

What i want:
http://i.imgur.com/47kzlpv.png

Codes:

    .container {
  width:100%;
  border-color: #FF0000;
  border-style: solid;
  border-width:medium;
  text-align:center;
  margin-bottom: 1%;
 }

 .menu_box_filtro{
  display:inline;
 }

 .conteudo_box_filtro{
  display:inline-block;
 }

      menu centro

      menu direita

Body:
Check this

.container{
  width: 90%;
  max-width: 900px;
  margin: 0 auto;
  background-color:#F0A202;
}

.group{
content:"";
display:table;
clear:both;
}

div:nth-of-type(1) {
  width: 36%;
  float: left;

}

div:nth-of-type(2) {
  width: 30%;
  float: left;
  margin-left: 4%;

}

div:nth-of-type(3) {
  width: 26%;
  float: right;

}

<div class="container group">
  <div>
    <p>First<p>
  </div>

  <div>
    <p>Second<p>
  </div>

  <div>
    <p>Third<p>
  </div>
</div>


问:
How to upload empty file with Retrofit 2?
I successfully set up an uploading images to my REST API via retrofit with this code:

```<code>        File imageFile = ImagePicker.getFileFromResult(this, resultCode, data);
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("userpic", imageFile.getName(), requestFile);

        RetrofitClient.compositeSubscription.add(RetrofitClient.getService().updateProfileUserpic("Token " + RevolutionApp.getInstance().getUserToken(), body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Profile>() {
                    @Override
                    public void onCompleted() { }

                    @Override
                    public void onError(Throwable e) { }

                    @Override
                    public void onNext(Profile profile) {
                        mProfileFragment.fetchProfileData();
                    }
                }));
</code>```

Now I need to send empty file (null) to my my API. How to implement it?

```<code>MultipartBody.Part.createFormData("userpic", imageFile.getName(), requestFile)
</code>```

does not work

答:
Here is final solution:

API interface method to update model:

```<code>public void updateProfileData(ProfilePost profile, final OnProfileUpdatedListener listener) {

    Observable<Profile> observable;
    if (profile.getUserpicPart() != null) {
        observable = RetrofitClient.getService().updateProfileData(profile.asHashMap(), profile.getUserpicPart());
    } else {
        observable = RetrofitClient.getService().updateProfileData(profile.asHashMap());
    }

    RetrofitClient.compositeSubscription.add(observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<Profile>() {
                ...
            }));
}
</code>```

Retrofit method signature:

```<code>@PUT("/api/v1/profile/")
@Multipart
Observable<Profile> updateProfileData(@Header("Authorization") String authorization, @PartMap() Map<String, RequestBody> partMap, @Part MultipartBody.Part image);

@PUT("/api/v1/profile/")
@Multipart
Observable<Profile> updateProfileData(@Header("Authorization") String authorization, @PartMap() Map<String, RequestBody> partMap);
</code>```

and model to post:

```<code>public class ProfilePost {
    MultipartBody.Part userpicPart;

    public HashMap<String, RequestBody> asHashMap() {
        HashMap<String, RequestBody> result = new HashMap<>();
        result.put("first_name", RequestBody.create(MediaType.parse("text/plain"), this.firstName));
        result.put("last_name", RequestBody.create(MediaType.parse("text/plain"), this.lastName));
        result.put("email", RequestBody.create(MediaType.parse("text/plain"), this.email));
    }
    public void getUserpicPart() {
        if (this.userpicFile == null) {
            return null;
        }
        return MultipartBody.Part.createFormData("userpic", this.userpicFile.getName(), requestFile);
    }
}
</code>```

Body:
I successfully set up an uploading images to my REST API via retrofit with this code:

        File imageFile = ImagePicker.getFileFromResult(this, resultCode, data);
        RequestBody requestFile =
                RequestBody.create(MediaType.parse("multipart/form-data"), imageFile);
        MultipartBody.Part body =
                MultipartBody.Part.createFormData("userpic", imageFile.getName(), requestFile);

        RetrofitClient.compositeSubscription.add(RetrofitClient.getService().updateProfileUserpic("Token " + RevolutionApp.getInstance().getUserToken(), body).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Profile>() {
                    @Override
                    public void onCompleted() { }

                    @Override
                    public void onError(Throwable e) { }

                    @Override
                    public void onNext(Profile profile) {
                        mProfileFragment.fetchProfileData();
                    }
                }));

Now I need to send empty file (null) to my my API. How to implement it?

MultipartBody.Part.createFormData("userpic", imageFile.getName(), requestFile)

does not work

Body:
Here is final solution:

API interface method to update model:

public void updateProfileData(ProfilePost profile, final OnProfileUpdatedListener listener) {

    Observable<Profile> observable;
    if (profile.getUserpicPart() != null) {
        observable = RetrofitClient.getService().updateProfileData(profile.asHashMap(), profile.getUserpicPart());
    } else {
        observable = RetrofitClient.getService().updateProfileData(profile.asHashMap());
    }

    RetrofitClient.compositeSubscription.add(observable
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<Profile>() {
                ...
            }));
}

Retrofit method signature:

@PUT("/api/v1/profile/")
@Multipart
Observable<Profile> updateProfileData(@Header("Authorization") String authorization, @PartMap() Map<String, RequestBody> partMap, @Part MultipartBody.Part image);

@PUT("/api/v1/profile/")
@Multipart
Observable<Profile> updateProfileData(@Header("Authorization") String authorization, @PartMap() Map<String, RequestBody> partMap);

and model to post:

public class ProfilePost {
    MultipartBody.Part userpicPart;

    public HashMap<String, RequestBody> asHashMap() {
        HashMap<String, RequestBody> result = new HashMap<>();
        result.put("first_name", RequestBody.create(MediaType.parse("text/plain"), this.firstName));
        result.put("last_name", RequestBody.create(MediaType.parse("text/plain"), this.lastName));
        result.put("email", RequestBody.create(MediaType.parse("text/plain"), this.email));
    }
    public void getUserpicPart() {
        if (this.userpicFile == null) {
            return null;
        }
        return MultipartBody.Part.createFormData("userpic", this.userpicFile.getName(), requestFile);
    }
}


问:
Display a number from array in PHP
Hello I would like to have a code that displays randomly from an array a number and displays it.
For example this code

```<code><?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>
</code>```

will return

```<code>Array
(
    [1] => January
    [2] => February
    [3] => March
)
</code>```

Instead of this, I would like to display on

答:
You need array_rand():

```<code>echo $firstquarter[array_rand($firstquarter)];
</code>```

I'm not sure if this is what you want but here it goes:

```<code>echo mt_rand(intval(date('H') / 3) * 4, intval(date('H') / 3) * 5);
</code>```

Title: Display a number from array in PHP

Body:
Hello I would like to have a code that displays randomly from an array a number and displays it.
For example this code

<?php
$firstquarter = array(1 => 'January', 'February', 'March');
print_r($firstquarter);
?>

will return

Array
(
    [1] => January
    [2] => February
    [3] => March
)

Instead of this, I would like to display on

Body:
You need array_rand():

echo $firstquarter[array_rand($firstquarter)];

I'm not sure if this is what you want but here it goes:

echo mt_rand(intval(date('H') / 3) * 4, intval(date('H') / 3) * 5);


问:
Spring CrudRepository not working save & delete operation
In Spring, CrudRepository findAll() operation working good for fetching data from the database but with the same configuration in case of saving, update & delete it's not working.

EmployeeService.java

```<code> @Service
    public class EmployeeService {

        @Autowired
        private EmployeeRepo employeeRepoI;

        @Transactional
        public List<Employee> getAllEmployee() {
            return (List<Employee>) employeeRepoI.findAll();
        }

        @Transactional
        public Employee getEmployee(int id) {
            return (Employee) employeeRepoI.findOne(id);
        }

        @Transactional
        public Employee addEmployee(Employee employee) {
            return (Employee) employeeRepoI.save(employee);
        }

        @Transactional
        public Employee updateEmployee(Employee employee) {
            return (Employee) employeeRepoI.save(employee);

        }

        @Transactional
        public void deleteEmployee(int id) {
             employeeRepoI.delete(id);
        }

    }
</code>```

EmployeeRapo.java

```<code>@Repository
public interface EmployeeRepo<T, ID extends Serializable> extends CrudRepository<Employee, Long> {

    List<Employee> findAll();

}
</code>```

答:
As pointed out by @Sergey Your EmployeeRepo has a wrong definition there

Try this

```<code>@Repository
public interface EmployeeRepo extends CrudRepository<Employee, Long> {
    List<Employee> findAll();
}
</code>```

Also your deleteEmployee() method takes an int while it should take Long as a parameter.

```<code>@Transactional
public void deleteEmployee(Long id) {
    employeeRepoI.delete(id);
}
</code>```

Body:
In Spring, CrudRepository findAll() operation working good for fetching data from the database but with the same configuration in case of saving, update & delete it's not working.

EmployeeService.java

 @Service
    public class EmployeeService {

        @Autowired
        private EmployeeRepo employeeRepoI;

        @Transactional
        public List<Employee> getAllEmployee() {
            return (List<Employee>) employeeRepoI.findAll();
        }

        @Transactional
        public Employee getEmployee(int id) {
            return (Employee) employeeRepoI.findOne(id);
        }

        @Transactional
        public Employee addEmployee(Employee employee) {
            return (Employee) employeeRepoI.save(employee);
        }

        @Transactional
        public Employee updateEmployee(Employee employee) {
            return (Employee) employeeRepoI.save(employee);

        }

        @Transactional
        public void deleteEmployee(int id) {
             employeeRepoI.delete(id);
        }

    }

EmployeeRapo.java

@Repository
public interface EmployeeRepo<T, ID extends Serializable> extends CrudRepository<Employee, Long> {

    List<Employee> findAll();

}

Body:
As pointed out by @Sergey Your EmployeeRepo has a wrong definition there

Try this

@Repository
public interface EmployeeRepo extends CrudRepository<Employee, Long> {
    List<Employee> findAll();
}

Also your deleteEmployee() method takes an int while it should take Long as a parameter.

@Transactional
public void deleteEmployee(Long id) {
    employeeRepoI.delete(id);
}


答:
You are trying to access your taggedClothes object like an array.
change this:

```<code> taggedClothes: {
      0: {id:0, left:100, top:100, thumbSize:100}, <- I want to setState this
      1: {id:1, left:200, top:200, thumbSize:200},
 },
</code>```

to that:

```<code> taggedClothes: [
      {id:0, left:100, top:100, thumbSize:100},
      {id:1, left:200, top:200, thumbSize:200},
 ],
</code>```

now you should be able to access taggedClothes.

Title: How to setState the object of the object of state

Body:
Goal: I have two square and I want to change selected square's location. While I'm doing it, I need to change selected square's x-coordinate, y-coordinate, width, and height.

Here is my state which holds the data for square information.

state = {
    gestureState: {},
    thumbSize: 100,
    left: width(100) / 2,
    top: height(100) / 2,
    taggedClothes: {
      0: {id:0, left:100, top:100, thumbSize:100}, <- I want to setState this
      1: {id:1, left:200, top:200, thumbSize:200},
    },
    selectedClothId : 0,
  }

Problem: taggedClothes have two square information and I want to change only selected problem but I'm getting compile error

Here I'm performing setState its taggedClothes[0]

// this.state.selectedColorId = 0
var deep = _.cloneDeep(this.state.taggedClothes[this.state.selectedColorId]);
          deep.left = left
          deep.top = top
          deep.thumbSize = thumbSize
          this.setState({
            gestureState: {
              ...gestureState
            },
            taggedClothes[0]: deep  <- Getting Compile Error
          })

If your have any other suggestion, Please suggest other option!

Body:
You are trying to access your taggedClothes object like an array.
change this:

 taggedClothes: {
      0: {id:0, left:100, top:100, thumbSize:100}, <- I want to setState this
      1: {id:1, left:200, top:200, thumbSize:200},
 },

to that:

 taggedClothes: [
      {id:0, left:100, top:100, thumbSize:100},
      {id:1, left:200, top:200, thumbSize:200},
 ],

now you should be able to access taggedClothes.


问:
how to iterate a List that contains Map and get the key and value of that map
I have a list that contains a map on class type. I want to iterate that list and get the key and values of the inner map.

Here is the List :

```<code>quotationList =  quotationService.searchByIdList(accountId, Account.class);
</code>```

It contains one index i.e at 0 index it contains a map. i need to get the key and values of that map.

My attempt:

```<code>for (int i = 0; i < quotationList.size(); i++) {
            Map myMap = (Map) quotationList.get(i);
            System.out.println("Data For Map" + i);
            for (Entry<String, Object> entrySet : ((Map<String, Object>) myMap).entrySet()) {
                System.out.println("Key = " + entrySet.getKey() + " , Value = " + entrySet.getValue());
            }
        }
</code>```

答:
In case list contains element then your code should print the contents of the map.

Here is your code having one map element in the list and it is printing the contents of the map:

List> quotationList= new ArrayList>();

```<code>    Map<String, Object> map= new HashMap<String, Object>();
    map.put("key1", "value1");

    quotationList.add(map);

    for (int i = 0; i < quotationList.size(); i++) {
        Map myMap = (Map) quotationList.get(i);
        System.out.println("Data For Map" + i);
        for (Entry<String, Object> entrySet : ((Map<String, Object>) myMap).entrySet()) {
            System.out.println("Key = " + entrySet.getKey() + " , Value = " + entrySet.getValue());
        }
    }
</code>```

It will produce the output as:

Data For Map0
Key = key1 , Value = value1

Body:
I have a list that contains a map on class type. I want to iterate that list and get the key and values of the inner map.

Here is the List :

quotationList =  quotationService.searchByIdList(accountId, Account.class);

It contains one index i.e at 0 index it contains a map. i need to get the key and values of that map.

My attempt:

for (int i = 0; i < quotationList.size(); i++) {
            Map myMap = (Map) quotationList.get(i);
            System.out.println("Data For Map" + i);
            for (Entry<String, Object> entrySet : ((Map<String, Object>) myMap).entrySet()) {
                System.out.println("Key = " + entrySet.getKey() + " , Value = " + entrySet.getValue());
            }
        }

Body:
In case list contains element then your code should print the contents of the map.

Here is your code having one map element in the list and it is printing the contents of the map:

List> quotationList= new ArrayList>();

    Map<String, Object> map= new HashMap<String, Object>();
    map.put("key1", "value1");

    quotationList.add(map);

    for (int i = 0; i < quotationList.size(); i++) {
        Map myMap = (Map) quotationList.get(i);
        System.out.println("Data For Map" + i);
        for (Entry<String, Object> entrySet : ((Map<String, Object>) myMap).entrySet()) {
            System.out.println("Key = " + entrySet.getKey() + " , Value = " + entrySet.getValue());
        }
    }

It will produce the output as:

Data For Map0
Key = key1 , Value = value1


问:
Are there any better javascript org charts compared with Google Org Chart API?
We are using google org chart API to display our org charts.  This works well but we need something that supports:

One person reporting to multiple managers

Co heads of a functional areas.

Are there any competing tools that give better support for the above.

NOTE: For Gorka LLona, who suggested this solution below in one of the answers, i found a few bugs, here is a screenshot of the issue i am running into using your test example.

答: You could use Jit (The JavaScript Infoviz Toolkit), there's a good example here. This is what I used to create an org chart at my company (backed by a PHP script that turns AD relationships into JSON).</p>


问:
Jitpack - unable to import android library
I forked a public MediaPicker library and forked it on Github. After making some changes to the library, I made a release of the project. I checked JitPack which is showing all ok for the release but I am still unable to import it. Following is the library url for JitPack

https://jitpack.io/#rohankandwal/MediaPicker/2.3.4

I have checked my root Gradle's setting and made sure that I have following lines added-

```<code>allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }
</code>```

I tried importing the library by using following code -

compile 'com.github.rohankandwal:MediaPicker:2.3.4'

or

compile 'com.github.rohankandwal:libary:2.3.4'

I have also asked another developer to import library but he is also unable to do so, please advice what am I missing ? The Github link to library is
https://github.com/rohankandwal/MediaPicker

答:
Just replace this from :

```<code>allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }
</code>```

to:

```<code>allprojects {
        repositories {
           maven {
    name "jitpack"
    url "https://jitpack.io"
}
    }
</code>```

Happy coding!!

Body:
I forked a public MediaPicker library and forked it on Github. After making some changes to the library, I made a release of the project. I checked JitPack which is showing all ok for the release but I am still unable to import it. Following is the library url for JitPack

https://jitpack.io/#rohankandwal/MediaPicker/2.3.4

I have checked my root Gradle's setting and made sure that I have following lines added-

allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }

I tried importing the library by using following code -

compile 'com.github.rohankandwal:MediaPicker:2.3.4'

or

compile 'com.github.rohankandwal:libary:2.3.4'

I have also asked another developer to import library but he is also unable to do so, please advice what am I missing ? The Github link to library is
https://github.com/rohankandwal/MediaPicker

Body:
Just replace this from :

allprojects {
        repositories {
            ...
            maven { url 'https://jitpack.io' }
        }
    }

to:

allprojects {
        repositories {
           maven {
    name "jitpack"
    url "https://jitpack.io"
}
    }

Happy coding!!


问:
Grafana Legend format :9100 removal
I have ":9100" showing up at the end of my metrics. I am using a prometheus datasource with my company and can't change it. Has anyone figured out how to remove this? I was thinking maybe templates or regex but I haven't been successful yet.

Configuration:

Legend Format = {{hostname}}

Result = myhostname.mydomain.com:9100

答:
I presume you are statically mentioning targets in the Prometheus config file as follows:

```<code>- job_name: "node_exporter"
  static_configs:
    - targets: ['localhost:9100']
</code>```

In that case, if you see the {{instance_name}} in grafana, it will give you the same as your target name ['localhost:9100']. This is because it uses the static_configs to avail labels for your metrics.

In order to remove the :9100 from the labels, you can use service discovery to recognize targets.

For example: ec2_sd_config where the labels will be availed from labels mentioned in AWS EC2 dashboard, file_sd_config where you can provide the targets and their labels in json or yaml format, etc.

Please refer to the link for detailed information.

Hope this helps!

Title: Grafana Legend format :9100 removal

Body:
I presume you are statically mentioning targets in the Prometheus config file as follows:

- job_name: "node_exporter"
  static_configs:
    - targets: ['localhost:9100']

In that case, if you see the {{instance_name}} in grafana, it will give you the same as your target name ['localhost:9100']. This is because it uses the static_configs to avail labels for your metrics.

In order to remove the :9100 from the labels, you can use service discovery to recognize targets.

For example: ec2_sd_config where the labels will be availed from labels mentioned in AWS EC2 dashboard, file_sd_config where you can provide the targets and their labels in json or yaml format, etc.

Please refer to the link for detailed information.

Hope this helps!


问:
How do I copy the contents of one ArrayList into another?
I have some data structures, and I would like to use one as a temporary, and another as not temporary.

```<code>ArrayList<Object> myObject = new ArrayList<Object>();
ArrayList<Object> myTempObject = new ArrayList<Object>();

//fill myTempObject here
....

//make myObject contain the same values as myTempObject
myObject = myTempObject;

//free up memory by clearing myTempObject
myTempObject.clear();
</code>```

now the problem with this of course is that myObject is really just pointing to myTempObject, and so once myTempObject is cleared, so is myObject.

How do I retain the values from myTempObject in myObject using java?

答:
Copy of one list into second is quite simple , you can do that as below:-

```<code>ArrayList<List1> list1= new ArrayList<>();
ArrayList<List1> list2= new ArrayList<>();
//this will your copy your list1 into list2
list2.addAll(list1);
</code>```

Body:
I have some data structures, and I would like to use one as a temporary, and another as not temporary.

ArrayList<Object> myObject = new ArrayList<Object>();
ArrayList<Object> myTempObject = new ArrayList<Object>();

//fill myTempObject here
....

//make myObject contain the same values as myTempObject
myObject = myTempObject;

//free up memory by clearing myTempObject
myTempObject.clear();

now the problem with this of course is that myObject is really just pointing to myTempObject, and so once myTempObject is cleared, so is myObject.

How do I retain the values from myTempObject in myObject using java?

Body:
Copy of one list into second is quite simple , you can do that as below:-

ArrayList<List1> list1= new ArrayList<>();
ArrayList<List1> list2= new ArrayList<>();
//this will your copy your list1 into list2
list2.addAll(list1);


问:
SQL - Display Minimum Value
I am new to SQL Oracle and have been working on this for nearly 10 hrs.  I am trying to show record that has minimum share amount. Here is my code:

```<code>SELECT b.first_name||' '||b.last_name AS broker,
       MIN(t.share_amount)
FROM brokers b RIGHT OUTER JOIN
     trades t
     ON b.broker_id = t.broker_id
GROUP BY b.first_name||' '||b.last_name;
</code>```

All this provides is a list of brokers and their share amounts. I just want the minimum.

Please help! I know it will be something simple but I cant figure out what.

答:
Your code should be like </p>

```<code>SELECT b.first_name||' '||b.last_name AS broker,
       MIN(t.share_amount)
FROM brokers b RIGHT OUTER JOIN
     trades t
     ON b.broker_id = t.broker_id
GROUP BY b.first_name||' '||b.last_name, t.share_amount;
</code>```

Title: SQL - Display Minimum Value

Body:
I am new to SQL Oracle and have been working on this for nearly 10 hrs.  I am trying to show record that has minimum share amount. Here is my code:

SELECT b.first_name||' '||b.last_name AS broker,
       MIN(t.share_amount)
FROM brokers b RIGHT OUTER JOIN
     trades t
     ON b.broker_id = t.broker_id
GROUP BY b.first_name||' '||b.last_name;

All this provides is a list of brokers and their share amounts. I just want the minimum.

Please help! I know it will be something simple but I cant figure out what.

Body:
Your code should be like

SELECT b.first_name||' '||b.last_name AS broker,
       MIN(t.share_amount)
FROM brokers b RIGHT OUTER JOIN
     trades t
     ON b.broker_id = t.broker_id
GROUP BY b.first_name||' '||b.last_name, t.share_amount;


问:
WebSocket compression in Vert.x?
Is there a way to enable WebSocket compression in Vert.x 3.x? I see it uses Netty 4, which apparently has support for permessage-deflate and deflate-frame compression extensions – but I see no way to enable them (or any other WebSocket extension) in Vert.x.

答: It seems it’s going to be included, and enabled by default, in Vertx 3.5.1. EDIT: the PR has not yet (as of Vertx 3.5.1) been merged and is now planned for 3.6.0.</p>

Title: WebSocket compression in Vert.x?


问:
How can I run something Async in OncreateView?
I have a problem with my app. Firstly, I made two Tabs using fragments which inflates an activity. The tabs implemented is working fine. Secondly i have  displayed the XAML right.

However, I now need to run something asynchronously in
OnCreateView in the Fragment. How can i manage this without getting errors?

Any help is greatly appreciated! Thanks

Here is my Fragment:

```<code>public class FragmentSettings : SupportFragment
{
    private Button mBtnOk;

    public FragmentSettings(Context context)
    {
        mContext = context;
    }

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        //Inflate the fragment XML
        View view = inflater.Inflate(Resource.Layout.FragmentSettings, container, false);

        //Grab the butten from the inflated fragment
        mBtnOk = view.FindViewById<Button>(Resource.Id.mBtnOk);
        mBtnOk.Click += (object sender, EventArgs e) =>
        {
            //DO stuff
        };
        //=====================================
        //Want to do something async stuff here
        //=====================================

        return view;
    }
}
</code>```

答:
For example you can simply run

AsyncTask

Just put there something like this:

```<code> new AsyncTask<Void, Void, Void>() {
     @Override
     protected Void doInBackground(Void... voids) {
         //do your work here
         return null;
     }
 }.execute();
</code>```

Body:
I have a problem with my app. Firstly, I made two Tabs using fragments which inflates an activity. The tabs implemented is working fine. Secondly i have  displayed the XAML right.

However, I now need to run something asynchronously in
OnCreateView in the Fragment. How can i manage this without getting errors?

Any help is greatly appreciated! Thanks

Here is my Fragment:

public class FragmentSettings : SupportFragment
{
    private Button mBtnOk;

    public FragmentSettings(Context context)
    {
        mContext = context;
    }

    public override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
    }

    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        //Inflate the fragment XML
        View view = inflater.Inflate(Resource.Layout.FragmentSettings, container, false);

        //Grab the butten from the inflated fragment
        mBtnOk = view.FindViewById<Button>(Resource.Id.mBtnOk);
        mBtnOk.Click += (object sender, EventArgs e) =>
        {
            //DO stuff
        };
        //=====================================
        //Want to do something async stuff here
        //=====================================

        return view;
    }
}

Body:
For example you can simply run

AsyncTask

Just put there something like this:

 new AsyncTask<Void, Void, Void>() {
     @Override
     protected Void doInBackground(Void... voids) {
         //do your work here
         return null;
     }
 }.execute();


问:
css adding delimeters to nav
I have a navigation menu that is basically a list of links that wraps on to multiple with n number of links on each dependent of length of link etc,

Above is what I am trying to recreate, as you can the last link on each line does not have a delimeter, is it possible to replicate this? Currently I have managed to get a delimeter between each link and at the end of every row.

I have no control over the HTML other wise I would loop through the links and only display x number of links on each line, I could then do nth-child() however I will never know how many links will be shown on each line.

Here is a link to a test, as you can last link on each line has a border-right ideally I would want to turn these off if there is no sibling on the same line.

https://jsbin.com/givaquyozu/edit?html,css,output

答:
A 'hacky' solution would be to add the | using a :before pseudoelement on the li, and simply cover it with a pseudoelement on the ul

ul {
  padding: 0;
  list-style: none;
  width: 400px;
  position: relative;
  background: #eee;
}

ul:before {
  content: '';
  display: inline-block;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 5px;
  background: #eee;
}

li {
  display: inline-block;
  font-size: 2em;
}

li:before {
  content: ' | ';
  display: inline-block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>some link</li>
  <li>some link dfd</li>
  <li>some link</li>
  <li>some link d</li>
  <li>some</li>
  <li>some link</li>
</ul>
<ul>
  <li>some link</li>
  <li>some link dfd</li>
  <li>some link</li>
  <li>som</li>
  <li>some link</li>
</ul></code>```

Title: css adding delimeters to nav

Body:
A 'hacky' solution would be to add the | using a :before pseudoelement on the li, and simply cover it with a pseudoelement on the ul

ul {
  padding: 0;
  list-style: none;
  width: 400px;
  position: relative;
  background: #eee;
}

ul:before {
  content: '';
  display: inline-block;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  width: 5px;
  background: #eee;
}

li {
  display: inline-block;
  font-size: 2em;
}

li:before {
  content: ' | ';
  display: inline-block;
}

<ul>
  <li>some link</li>
  <li>some link dfd</li>
  <li>some link</li>
  <li>some link d</li>
  <li>some</li>
  <li>some link</li>
</ul>
<ul>
  <li>some link</li>
  <li>some link dfd</li>
  <li>some link</li>
  <li>som</li>
  <li>some link</li>
</ul>


问:
Wget output document and headers to STDOUT
I'm trying to output the document body and its headers to STDOUT by doing

```<code>wget -S -O - http://google.com
</code>```

...but it shows only the HTML document.

Update: Got it to work with

```<code>wget --save-headers --output-document - http://google.com
</code>```

wget --version shows my version is GNU Wget 1.11.4 Red Hat modified.

答:
This will not work:

```<code>wget -q -S -O - google.com 1>wget.txt 2>&1
</code>```

since redirects are evaluated right to left, this sends html to wget.txt and the header to STDOUT:

```<code>wget -q -S -O - google.com 2>&1 1>wget.txt
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to output the document body and its headers to STDOUT by doing

wget -S -O - http://google.com

...but it shows only the HTML document.

Update: Got it to work with

wget --save-headers --output-document - http://google.com

wget --version shows my version is GNU Wget 1.11.4 Red Hat modified.

Body:
This will not work:

wget -q -S -O - google.com 1>wget.txt 2>&1

since redirects are evaluated right to left, this sends html to wget.txt and the header to STDOUT:

wget -q -S -O - google.com 2>&1 1>wget.txt


问:
Not getting Firebase database data
I am developing app to display user score that store in firebase database but after running application it won't display data in listview

below is my code:-

```<code>listViewLeaderBoard = (ListView) findViewById(R.id.listView_leader_board);

        reference = FirebaseDatabase.getInstance().getReference("score");

        leaderBoards = new ArrayList<>();

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                    LeaderBoard leaderBoard = postSnapshot.getValue(LeaderBoard.class);
                    leaderBoards.add(0,leaderBoard);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        //Collections.sort(leaderBoards);
        CustomLeaderBoardAdapter adapter = new CustomLeaderBoardAdapter(getApplicationContext(),R.layout.leader_board_list_layout,leaderBoards);
        listViewLeaderBoard.setAdapter(adapter);
        adapter.notifyDataSetChanged();
</code>```

Database snapshot:-

Output:-

答:
You can find and change the rules for your database in the Firebase console.Simply choose your project, click on the Database section on the left, and then select the Rules tab.I don't know you have done this or not try this hope this will help you.</p>

```<code>{
"rules": {
".read": true,
".write": true
}
}
</code>```

Title: Not getting Firebase database data

Body:
I am developing app to display user score that store in firebase database but after running application it won't display data in listview

below is my code:-

listViewLeaderBoard = (ListView) findViewById(R.id.listView_leader_board);

        reference = FirebaseDatabase.getInstance().getReference("score");

        leaderBoards = new ArrayList<>();

        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()){
                    LeaderBoard leaderBoard = postSnapshot.getValue(LeaderBoard.class);
                    leaderBoards.add(0,leaderBoard);
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        //Collections.sort(leaderBoards);
        CustomLeaderBoardAdapter adapter = new CustomLeaderBoardAdapter(getApplicationContext(),R.layout.leader_board_list_layout,leaderBoards);
        listViewLeaderBoard.setAdapter(adapter);
        adapter.notifyDataSetChanged();

Database snapshot:-

Output:-

Body:
You can find and change the rules for your database in the Firebase console.Simply choose your project, click on the Database section on the left, and then select the Rules tab.I don't know you have done this or not try this hope this will help you.

{
"rules": {
".read": true,
".write": true
}
}


问:
issue in OutOfMemoryError - Android
I'm getting following error. I have tried  android:largeHeap="true" and android:hardwareAccelerated="false". But still app is crashing and showing the same error

```<code>java.lang.OutOfMemoryError: Failed to allocate a 39306252 byte allocation with 16777216 free bytes and 27MB until OOM

at dalvik.system.VMRuntime.newNonMovableArray(Native Method)

at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
</code>```

答:
if your BitMap size is large then you have to resize/rescale it to show it in your app otherwise OutOfMemory error will be thrown , you can try to use

```<code>android:largeHeap="true"
</code>```

in your manifest or you have to manually resize them in your code ,have a look
How to Resize a Bitmap in Android?

Title: issue in OutOfMemoryError - Android

Body:
I'm getting following error. I have tried  android:largeHeap="true" and android:hardwareAccelerated="false". But still app is crashing and showing the same error

java.lang.OutOfMemoryError: Failed to allocate a 39306252 byte allocation with 16777216 free bytes and 27MB until OOM

at dalvik.system.VMRuntime.newNonMovableArray(Native Method)

at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)

Body:
if your BitMap size is large then you have to resize/rescale it to show it in your app otherwise OutOfMemory error will be thrown , you can try to use

android:largeHeap="true"

in your manifest or you have to manually resize them in your code ,have a look
How to Resize a Bitmap in Android?


问:
Compare a String to the elements of the ArrayList and return a String
I have an arrayList which I created using this code:

```<code>public List<String> Apps = new ArrayList<String>();
</code>```

This list contains strings in this format:

```<code>Data1+Description1
Data2+Description2
Data3+Description3
Data4+Description4
Data5+Description5
....
</code>```

Assume that the strings above have 3 parts. 1st part is the Data part. 2nd part is the + symbol and the 3rd part is the Description part.

and I have another function somewhere else in the code which returns a string. Now this string is of the form:

```<code>Retrieved_Name
</code>```

This Retrieved_Name will always match with one of the Data1...Data n above .i.e it will match with the 1st part of the above string till before the + symbol.

NOTE : This Retrieved_Name string always matches with the above strings till the + sign. and not after that.

My problem is that whenever the Retrieved_Name matches with the 1st part of the above String, I need to return the 3rd part .i.e. the description part of the string.

How can I implement this?

答:
```<code>import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String s="anupam+singh"; /* here the string is composed of three parts*/
        String s1="anupam"; /* this is the first part of the string, in your case it is retrieved name */

        if(s.substring(0,s.indexOf("+")).equals(s1)) /*we use a substring function of String class, it takes two arguments starting and end index and returns the substring from the given string, the end index is exclusive*/
        {
            String s2=s.substring(s.indexOf("+")+1); /*the substring function can work on one argument even, if you just give the starting index then it will return the substring from that starting index till the end of string */
            System.out.println(s2);
        }
    }
}
</code>```

I have explained the code in comments. Hope it helps.

Body:
I have an arrayList which I created using this code:

public List<String> Apps = new ArrayList<String>();

This list contains strings in this format:

Data1+Description1
Data2+Description2
Data3+Description3
Data4+Description4
Data5+Description5
....

Assume that the strings above have 3 parts. 1st part is the Data part. 2nd part is the + symbol and the 3rd part is the Description part.

and I have another function somewhere else in the code which returns a string. Now this string is of the form:

Retrieved_Name

This Retrieved_Name will always match with one of the Data1...Data n above .i.e it will match with the 1st part of the above string till before the + symbol.

NOTE : This Retrieved_Name string always matches with the above strings till the + sign. and not after that.

My problem is that whenever the Retrieved_Name matches with the 1st part of the above String, I need to return the 3rd part .i.e. the description part of the string.

How can I implement this?

Body:
import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String s="anupam+singh"; /* here the string is composed of three parts*/
        String s1="anupam"; /* this is the first part of the string, in your case it is retrieved name */

        if(s.substring(0,s.indexOf("+")).equals(s1)) /*we use a substring function of String class, it takes two arguments starting and end index and returns the substring from the given string, the end index is exclusive*/
        {
            String s2=s.substring(s.indexOf("+")+1); /*the substring function can work on one argument even, if you just give the starting index then it will return the substring from that starting index till the end of string */
            System.out.println(s2);
        }
    }
}

I have explained the code in comments. Hope it helps.


问:
Get json from google analytics
I've a website with google analytics implemented. Everything shows fine on google analytics page eg. pageviews, gender, age.... but I need to get this data in JSON form for creating my own dashboard on my website. Simply, I need to get age and gender data via the URL link. Something like here:
http://api.opentracker.net/api/trends/trends.jsp?login=demo@opentracker.net&password=demo123&site=www.opentracker.net&period=1d
There is any solution to make this ?
PS: google analytics is implemented on page X and I'm making the dashboard on page Y. Thanks.</p>

答:
1º GET YOURAPIKEY - https://developers.google.com/url-shortener/v1/getting_started

2º Use link below with your XXXXXX goo.gl short link

https://www.googleapis.com/urlshortener/v1/url?shortUrl=http:// goo.gl/XXXXXX&projection=FULL&key=YOURAPIKEY

Title: Get json from google analytics


问:
XHR request from previous Capybara js spec surfacing (and failing) in next spec
We're using Chrome headless with Capybara and Selenium for three js feature tests.

We're having a predictable (only on CI) failure when one specific js test (using xhr) follows another which also uses xhr (see https://github.com/thredded/thredded/tree/separate-out-js-from-non-js-in-ci for the code or https://travis-ci.org/thredded/thredded/jobs/302376004 for a sample run).

The server error is always being surfaced in the next spec "User creates new topic with title and content" but the url is evidently from the previous spec "User replying to a topic starts a quote-reply (js)".

The obvious thing is that there is a race condition between a request that falls off the end of the spec and happens after DatabaseCleaner.clean. However, my understanding is that with Capybara 2.7+ [1] after_each should happen after a reset_session! which should prevent this precise problem. In any case I am pretty sure there is nothing in the page that could be creating this request (we have a specific wait/test for the completion of this ajax request).

This is happening with 3 different databases and 3 different rails versions (4.2, 5.0, 5.1).
We've upgraded to latest Capybara.

Have tried disabling turbolinks, adding in a massive (10s) sleep at the end of the offending spec... Have tried manually resetting sessions too.

Must be missing something. Any pointers?

[1] https://github.com/teamcapybara/capybara/pull/1637 referenced from https://bibwild.wordpress.com/2016/02/18/struggling-towards-reliable-capybara-javascript-testing/

UPDATE: Have added references to xhr, as another (new) js spec is having the problem, and that it isn't the first two requests (login form, and post to login) that is surfacing the error, but the first xhr request that surfaces the error. In the new case the xhr that is getting requested is being requested with POST in the subsequent spec even though it was originall requested with GET

答:
Looks like it was a chromedriver bug.

We fixed this by upgrading chromedriver (on travis) to v2.33 (linux).
https://travis-ci.org/thredded/thredded/builds/302431113

The previous version was v2.31. Oddly we couldn't get this to break locally with 2.31 (mac).


问:
CSS position type change (absolute to relative) on child div causes odd effect on parent div. Why is that?
I'm trying to understand CSS positioning and I'm having trouble figuring out why a simple change that apparently should have no effect on the layout is causing a very disruptive change. I'm obviously missing something.

The initial objective was to place an inner div
 vertically and horizontally within another div. That was fairly simple:

```<code>html, body {
 margin:0;
 padding:0;
 height:100%;
}

div#container {
 position:relative;
 background:#4444ff;
 margin: 0 auto; /* center, not in IE5 */

 height:80%;
 min-height:80%;
}

div#childDiv {
 position:absolute;
 background:#ff5555;

 /* next we center it vertically and horizontally */
 width:900px;
 height:600px;
 top:50%;
 margin-top:-300px;
 left:50%;
 margin-left:-450px;
}
</code>```

...and in the HTML page I used:

```<code><body>
<div id=container>
 <div id=childDiv>
  test
    </div>
</div>

</body>
</code>```

which worked fine.

The curious part is what happens when I change the position attribute of the #childDiv div from absolute to relative.

My understanding is that first is should not affect the #container div at all since I'm changing only the position of the child element, and second that it should not change the layout since it is the only child element, its parent uses relative position and third I have not specified any offsets (tp, left, etc).

Instead, when I make this change, the parent #container is messed up (shows only up to the half of the viewport instead of 80% height as previously), and the position of #childDiv changes accordingly (also upwards, half outside the viewport).

My questions is: why does that happen? What concepts I'm not taking into account and why was the parent div affected by a change in the children's position setting?

If I remove #childDiv from within #container and place it inside body, then #container is no longer affected by that change so it seems something is propagating up in the DOM, which is odd to me. I've seen the same in firefox, opera, IE and chrome.

I have read W3C's spec on this topic but I haven't been able to figure this one out so far...

UPDATE: I created examples in JS fiddle to show the problem. You can see the original is here: jsfiddle.net/7Pr9y/1 and the affected one is here: jsfiddle.net/7Pr9y/3

Thank you!
Eduardo

答:
OK, I figured out why it becomes smaller when I change the size to relative.

Happens that because I have set the margins of the #childDiv to a negative value in order to center it, when I change it to relative that negative margin is taken into account when calculating the height of #container, resulting in a smaller #container.

I'm obviously a beginner in this, but seriously, it looks like CSS made it as complicated as possible to lay things out. No surprise most folks coming from table layouts start frustrated. :(

Body:
I'm trying to understand CSS positioning and I'm having trouble figuring out why a simple change that apparently should have no effect on the layout is causing a very disruptive change. I'm obviously missing something.

The initial objective was to place an inner div
 vertically and horizontally within another div. That was fairly simple:

html, body {
 margin:0;
 padding:0;
 height:100%;
}

div#container {
 position:relative;
 background:#4444ff;
 margin: 0 auto; /* center, not in IE5 */

 height:80%;
 min-height:80%;
}

div#childDiv {
 position:absolute;
 background:#ff5555;

 /* next we center it vertically and horizontally */
 width:900px;
 height:600px;
 top:50%;
 margin-top:-300px;
 left:50%;
 margin-left:-450px;
}

...and in the HTML page I used:

  test

which worked fine.

The curious part is what happens when I change the position attribute of the #childDiv div from absolute to relative.

My understanding is that first is should not affect the #container div at all since I'm changing only the position of the child element, and second that it should not change the layout since it is the only child element, its parent uses relative position and third I have not specified any offsets (tp, left, etc).

Instead, when I make this change, the parent #container is messed up (shows only up to the half of the viewport instead of 80% height as previously), and the position of #childDiv changes accordingly (also upwards, half outside the viewport).

My questions is: why does that happen? What concepts I'm not taking into account and why was the parent div affected by a change in the children's position setting?

If I remove #childDiv from within #container and place it inside body, then #container is no longer affected by that change so it seems something is propagating up in the DOM, which is odd to me. I've seen the same in firefox, opera, IE and chrome.

I have read W3C's spec on this topic but I haven't been able to figure this one out so far...

UPDATE: I created examples in JS fiddle to show the problem. You can see the original is here: jsfiddle.net/7Pr9y/1 and the affected one is here: jsfiddle.net/7Pr9y/3

Thank you!
Eduardo


问:
EF 7 Database datetime generated value
I have this model

```<code> public class Comment
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CommentId { get; set; }

        public DateTime CreatedAt { get; set; }
        public DateTime LastEditedAt { get; set; }
    }
</code>```

I'm trying to let the db generate the value of CreatedAt and LastEditedAt  so in my OnModelCreating method  of my DbContext I used

```<code>modelBuilder.Entity<Comment>(c =>
            {
                c.Property(p => p.CreatedAt).ValueGeneratedOnAdd();
                c.Property(p => p.LastEditedAt).ValueGeneratedOnAddOrUpdate();
            });
</code>```

When trying to insert I get an inner exception in SaveChanges() saying

```<code>{"Cannot insert the value NULL into column 'CreatedAt', table 'WX.dbo.Comment'; column does not allow nulls. INSERT fails."}
</code>```

Does that mean that I have to assign values to those two columns manually?

Fixed by making LastEditedAt nullable

```<code> public DateTime  CreatedAt { get; set; }
 public DateTime? LastEditedAt { get; set; }
</code>```

and setting an SQL default value to CreatedAt

```<code>  modelBuilder.Entity<Comment>(c =>
            {
                c.Property(p => p.CreatedAt).HasDefaultValueSql("GETUTCDATE()");
                c.Property(p => p.LastEditedAt).ValueGeneratedOnAddOrUpdate();
            });
</code>```

答:
I have used the following solution to be able to set value to the creation and modification date fields:

```<code>modelBuilder.Entity<ExampleEntity>(c =>
{
   c.Property(p => p.CreatedDate).HasDefaultValueSql("GETDATE()").ValueGeneratedOnAdd();
   c.Property(p => p.UpdatedDate).HasDefaultValueSql("GETDATE()").ValueGeneratedOnAddOrUpdate();
});
</code>```

You should look this issues on EntityFrameworkCore github repository:

Issue3955

Issue4501

In those links shows several ways to solve the generation problem of create/update date fields.

Title: EF 7 Database datetime generated value

Body:
I have this model

 public class Comment
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CommentId { get; set; }

        public DateTime CreatedAt { get; set; }
        public DateTime LastEditedAt { get; set; }
    }

I'm trying to let the db generate the value of CreatedAt and LastEditedAt  so in my OnModelCreating method  of my DbContext I used

modelBuilder.Entity<Comment>(c =>
            {
                c.Property(p => p.CreatedAt).ValueGeneratedOnAdd();
                c.Property(p => p.LastEditedAt).ValueGeneratedOnAddOrUpdate();
            });

When trying to insert I get an inner exception in SaveChanges() saying

{"Cannot insert the value NULL into column 'CreatedAt', table 'WX.dbo.Comment'; column does not allow nulls. INSERT fails."}

Does that mean that I have to assign values to those two columns manually?

Fixed by making LastEditedAt nullable

 public DateTime  CreatedAt { get; set; }
 public DateTime? LastEditedAt { get; set; }

and setting an SQL default value to CreatedAt

  modelBuilder.Entity<Comment>(c =>
            {
                c.Property(p => p.CreatedAt).HasDefaultValueSql("GETUTCDATE()");
                c.Property(p => p.LastEditedAt).ValueGeneratedOnAddOrUpdate();
            });

Body:
I have used the following solution to be able to set value to the creation and modification date fields:

modelBuilder.Entity<ExampleEntity>(c =>
{
   c.Property(p => p.CreatedDate).HasDefaultValueSql("GETDATE()").ValueGeneratedOnAdd();
   c.Property(p => p.UpdatedDate).HasDefaultValueSql("GETDATE()").ValueGeneratedOnAddOrUpdate();
});

You should look this issues on EntityFrameworkCore github repository:

Issue3955

Issue4501

In those links shows several ways to solve the generation problem of create/update date fields.