问:
Find MIN value between a variable range of cells in two columns that contain TRUE
Sorry if I'm not being super clear! I'm not very adept with Excel but have been making use of it lately for some analysis on financial data. I have a normal OHLC set of data and two other columns where I have some IF statements printing True or False.

How would I accomplish the following:

I want to find the minimum value in one of the OHLC columns that is in a range between where one column has a True value and the other has a True value? This range will be variable and changing depending on the distance between the two trues in each column, if they are there.

I do not need to continually do this, just on a day by day basis. I only need a formula to select this range going back, for example, where the day in my time-series begins at 10:00 each day.

sorry for being unclear, imagine this.

```<code>date  time  open  high  low  close  condition1  condition2
xxxx  xxxx  xxxx  xxxx  xxxx xxxx   true
xxxx  xxxx  xxxx  xxxx  xxxx xxxx                         <--------this range
xxxx  xxxx  xxxx  xxxx  xxxx xxxx                         <--------i want min
xxxx  xxxx  xxxx  xxxx  xxxx xxxx                true
</code>```

but of course this range is variable each day, the conditions may be spaced out differently or might not have (2) true's but if it does. i want to know how to specify whatever range of cells is inbetween these two values

答:
This is a nice problem for us to look at.  I am assuming you are trading, and are looking at some sort of movement indicators at certain points in time (maybe some obscure Greeks or other functions rooted in advanced statistical analysis).  If you are looking to implement this in real-time, I highly recommend using some other programming languages (R is a great statistical programming language for the analysis of stock movement and rebalancing portfolios each day, as long as it is not time-sensitive to the nanosecond).  Speak with some of your colleagues who know HFT guys, they would be able to help you out with algorithmic trading.

However, assuming you are doing this analysis for long-term trading strategies, not HFT, we need a bit of clarification, however...

```<code>date  time  open  high  low  close  condition1  condition2
xxxx  xxxx  xxxx  xxxx  xxxx xxxx   true
xxxx  xxxx  xxxx  xxxx  xxxx xxxx
xxxx  xxxx  xxxx  xxxx  xxxx xxxx
xxxx  xxxx  xxxx  xxxx  xxxx xxxx                true
</code>```

You gave us this sample data.  You want the number of rows between the TRUE values of columns condition1 and condition2.  In this case, it should return either 2 or 4 ... which of these is correct?  This will affect the writing of the code.

Also, what if your data looks like this:

```<code>date  time  open  high  low  close  condition1  condition2
xxxx  xxxx  xxxx  xxxx  xxxx xxxx                 true
xxxx  xxxx  xxxx  xxxx  xxxx xxxx
xxxx  xxxx  xxxx  xxxx  xxxx xxxx
xxxx  xxxx  xxxx  xxxx  xxxx xxxx     true
</code>```

In this case, do you still want to return the minimum value?  Or are you only concerned with the first case, where condition1 is met, and then condition2 is met some time after that?

Also, what if this event happens:

```<code>date  time  open  high  low  close  condition1  condition2
    xxxx  xxxx  xxxx  xxxx  xxxx xxxx   true
    xxxx  xxxx  xxxx  xxxx  xxxx xxxx             true
    xxxx  xxxx  xxxx  xxxx  xxxx xxxx
    xxxx  xxxx  xxxx  xxxx  xxxx xxxx
</code>```

Would you like to return value 0, or do you want the program to skip over this?

I am sorry for all of the questions, but we need to know about these corner cases if we are to help you with your VBA-related request.

Finally, do you have any VBA experience?  Have you attempted to write any yourself at this point?  If so, it would be great for you to include this to show some research and effort on your end, and for us to use as a basis to help you.

Body:
Sorry if I'm not being super clear! I'm not very adept with Excel but have been making use of it lately for some analysis on financial data. I have a normal OHLC set of data and two other columns where I have some IF statements printing True or False.

How would I accomplish the following:

I want to find the minimum value in one of the OHLC columns that is in a range between where one column has a True value and the other has a True value? This range will be variable and changing depending on the distance between the two trues in each column, if they are there.

I do not need to continually do this, just on a day by day basis. I only need a formula to select this range going back, for example, where the day in my time-series begins at 10:00 each day.

sorry for being unclear, imagine this.

date  time  open  high  low  close  condition1  condition2
xxxx  xxxx  xxxx  xxxx  xxxx xxxx   true
xxxx  xxxx  xxxx  xxxx  xxxx xxxx                         <--------this range
xxxx  xxxx  xxxx  xxxx  xxxx xxxx                         <--------i want min
xxxx  xxxx  xxxx  xxxx  xxxx xxxx                true

but of course this range is variable each day, the conditions may be spaced out differently or might not have (2) true's but if it does. i want to know how to specify whatever range of cells is inbetween these two values

Body:
This is a nice problem for us to look at.  I am assuming you are trading, and are looking at some sort of movement indicators at certain points in time (maybe some obscure Greeks or other functions rooted in advanced statistical analysis).  If you are looking to implement this in real-time, I highly recommend using some other programming languages (R is a great statistical programming language for the analysis of stock movement and rebalancing portfolios each day, as long as it is not time-sensitive to the nanosecond).  Speak with some of your colleagues who know HFT guys, they would be able to help you out with algorithmic trading.

However, assuming you are doing this analysis for long-term trading strategies, not HFT, we need a bit of clarification, however...

date  time  open  high  low  close  condition1  condition2
xxxx  xxxx  xxxx  xxxx  xxxx xxxx   true
xxxx  xxxx  xxxx  xxxx  xxxx xxxx
xxxx  xxxx  xxxx  xxxx  xxxx xxxx
xxxx  xxxx  xxxx  xxxx  xxxx xxxx                true

You gave us this sample data.  You want the number of rows between the TRUE values of columns condition1 and condition2.  In this case, it should return either 2 or 4 ... which of these is correct?  This will affect the writing of the code.

Also, what if your data looks like this:

date  time  open  high  low  close  condition1  condition2
xxxx  xxxx  xxxx  xxxx  xxxx xxxx                 true
xxxx  xxxx  xxxx  xxxx  xxxx xxxx
xxxx  xxxx  xxxx  xxxx  xxxx xxxx
xxxx  xxxx  xxxx  xxxx  xxxx xxxx     true

In this case, do you still want to return the minimum value?  Or are you only concerned with the first case, where condition1 is met, and then condition2 is met some time after that?

Also, what if this event happens:

date  time  open  high  low  close  condition1  condition2
    xxxx  xxxx  xxxx  xxxx  xxxx xxxx   true
    xxxx  xxxx  xxxx  xxxx  xxxx xxxx             true
    xxxx  xxxx  xxxx  xxxx  xxxx xxxx
    xxxx  xxxx  xxxx  xxxx  xxxx xxxx

Would you like to return value 0, or do you want the program to skip over this?

I am sorry for all of the questions, but we need to know about these corner cases if we are to help you with your VBA-related request.

Finally, do you have any VBA experience?  Have you attempted to write any yourself at this point?  If so, it would be great for you to include this to show some research and effort on your end, and for us to use as a basis to help you.


来源: stackexchange

问:
Thread safe write files function in Java
My goal is to implement a function that allow to write on a file asynchronously, a prototype is

```<code>private final Object lock = new Object();

public void write(final string filename, final string message) {
    new Thread(new Runnable() {
        public void run() {
            // Create file object (if not exist create a new file)
            File file = new File(context.getFilesDir(), filename);
            // Try to write on that file
            synchronized(lock) {
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(file, true);
                    fileOutputStream.write(message.getBytes());
                    fileOutputStream.close();
                catch (...) {
                    ...
                }
            }
        }
    }).start();
}
</code>```

Is this function thread-save? It's possible to lock thread write by file, allowing asynchronous writing on different files (and show a method/pseudocode/code to accomplish this point)?

答:
For locki would create an own class, add it as public static final and prevent the class from instantiating (make constructor private). That way you make sure that there is always only one object.

Is this function thread-save?

Yes

It's possible to lock thread write by file, allowing asynchronous writing on different files?

Yes

ContentLicense: CC BY-SA 3.0

Body:
My goal is to implement a function that allow to write on a file asynchronously, a prototype is

private final Object lock = new Object();

public void write(final string filename, final string message) {
    new Thread(new Runnable() {
        public void run() {
            // Create file object (if not exist create a new file)
            File file = new File(context.getFilesDir(), filename);
            // Try to write on that file
            synchronized(lock) {
                try {
                    FileOutputStream fileOutputStream = new FileOutputStream(file, true);
                    fileOutputStream.write(message.getBytes());
                    fileOutputStream.close();
                catch (...) {
                    ...
                }
            }
        }
    }).start();
}

Is this function thread-save? It's possible to lock thread write by file, allowing asynchronous writing on different files (and show a method/pseudocode/code to accomplish this point)?


问:
vue meteor on subscription ready hook?
I use meteor vue to subcribe to a publication:

```<code> meteor: {
        $subscribe: {
            'gps': function() { return [ this.query ] }
        }
    },
</code>```

The docs only offer the following option:

```<code><div v-if="!$subReady.thread">Loading...</div>
</code>```

However, I need to execute some code when the subscription is ready. Is there some kind of onSubscriptionReady hook?

答:
If you use data from the subscription in your template, you can do something like:

```<code>beforeUpdate() {
  if (this.$subReady['gps']) {
    // do something
  }
}
</code>```

I do it this way in my app and so far it works fine. The problem is when you don't use data in the template because update hook isn't fired.

Title: vue meteor on subscription ready hook?

Body:
I use meteor vue to subcribe to a publication:

 meteor: {
        $subscribe: {
            'gps': function() { return [ this.query ] }
        }
    },

The docs only offer the following option:

Loading...

However, I need to execute some code when the subscription is ready. Is there some kind of onSubscriptionReady hook?

Body:
If you use data from the subscription in your template, you can do something like:

beforeUpdate() {
  if (this.$subReady['gps']) {
    // do something
  }
}

I do it this way in my app and so far it works fine. The problem is when you don't use data in the template because update hook isn't fired.


问:
Created thread does not run simultaneously with main C#
I have created a thread, but the thread pauses the main process after I start it. The thread loads some images from google, but when the internet connection is lost the user interface is unusable.

This is the thread:

```<code>string searchWord = "car photo";
PhotoSearchThread = new Thread(() =>
{
    Thread.CurrentThread.IsBackground = true;
    if (!string.IsNullOrWhiteSpace(searchWord))
    {
        string html = GetHtmlCode(searchWord);
        SearchedImagesUrls = GetUrls(html);
        this.Dispatcher.Invoke(() =>
        {
            if (SearchedImagesUrls.Count > 0)
            {
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.UriSource = new Uri(SearchedImagesUrls[0]);
                image.EndInit();
                SelectPhotoImage.Source = image;
            }
        });
    }
});

PhotoSearchThread.Start();
</code>```

Well threads should run simultaneously, then why this thread is interrupting other threads?

答:
I found the solution:

1.Add following using: using System.ComponentModel;

2.Declare background worker:

```<code>private readonly BackgroundWorker worker = new BackgroundWorker();
</code>```

3.Subscribe to events:

```<code>worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;
</code>```

4.Implement two methods:

```<code>private void worker_DoWork(object sender, DoWorkEventArgs e)
{
   // run all background tasks here
}

private void worker_RunWorkerCompleted(object sender,
                                       RunWorkerCompletedEventArgs e)
{
  //update ui once worker complete his work
}
</code>```

5.Run worker async whenever your need.

```<code>worker.RunWorkerAsync();
</code>```

Also if you want to report process progress you should subscribe to ProgressChanged event and use ReportProgress(Int32) in DoWork method to raise an event. Also set following: worker.WorkerReportsProgress = true; (thanks to @zagy)

source: How to use WPF Background Worker

Hope this help.

Body:
I have created a thread, but the thread pauses the main process after I start it. The thread loads some images from google, but when the internet connection is lost the user interface is unusable.

This is the thread:

string searchWord = "car photo";
PhotoSearchThread = new Thread(() =>
{
    Thread.CurrentThread.IsBackground = true;
    if (!string.IsNullOrWhiteSpace(searchWord))
    {
        string html = GetHtmlCode(searchWord);
        SearchedImagesUrls = GetUrls(html);
        this.Dispatcher.Invoke(() =>
        {
            if (SearchedImagesUrls.Count > 0)
            {
                BitmapImage image = new BitmapImage();
                image.BeginInit();
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.UriSource = new Uri(SearchedImagesUrls[0]);
                image.EndInit();
                SelectPhotoImage.Source = image;
            }
        });
    }
});

PhotoSearchThread.Start();

Well threads should run simultaneously, then why this thread is interrupting other threads?

Body:
I found the solution:

1.Add following using: using System.ComponentModel;

2.Declare background worker:

private readonly BackgroundWorker worker = new BackgroundWorker();

3.Subscribe to events:

worker.DoWork += worker_DoWork;
worker.RunWorkerCompleted += worker_RunWorkerCompleted;

4.Implement two methods:

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
   // run all background tasks here
}

private void worker_RunWorkerCompleted(object sender,
                                       RunWorkerCompletedEventArgs e)
{
  //update ui once worker complete his work
}

5.Run worker async whenever your need.

worker.RunWorkerAsync();

Also if you want to report process progress you should subscribe to ProgressChanged event and use ReportProgress(Int32) in DoWork method to raise an event. Also set following: worker.WorkerReportsProgress = true; (thanks to @zagy)

source: How to use WPF Background Worker

Hope this help.


问:
Confirmation missing in FormFlow
I have followed the HotelBol tutorial and the main idea is that I have a FormFlow. Following a model, I add a field, named BedSize (which is an enum) then I add all the remaining fields. So far so good, everything works fine.

```<code>public static IForm<RoomReservation> BuildForm()
{
    return new FormBuilder<RoomReservation>()
        .Message("Welcome to the hotel reservation bot!")
        .Field(nameof(BedSize))
        .AddRemainingFields()
        .Build();
}
</code>```

My problem is that I want in the end to have the default confirmation, from the confirmation message. The problem I face is that the Build method from the FormBuilder has that confirmation, but to me, it does not appear.

However, if I change my code to this:

```<code>public static IForm<RoomReservation> BuildForm()
{
    return new FormBuilder<RoomReservation>()
        .Message("Welcome to the hotel reservation bot!")
        .Build();
}
</code>```

it also triggers the confirmation message. Is there something that I am missing? I want to know why adding the .Field and/or .AddRemainingFields methods make the confirmation message dissapear.

答:
Every example I have seen uses a .Confirm() with a custom message.  When using .Field() or .AddRemainingFields() See the annotated sandwich bot below

For example in our formflow sample for a Simple sanwich bot does not use .Field() or .AddRemainingFields() and the auto confirm work. Whereas Annotated Shandwich Bot uses .Field() and .AddRemainingFields() .Confirm is used.

Basically it looks like you need to come up with a custom confirm implementation where you use .Field() and .AddRemainingFields() good luck.

Title: Confirmation missing in FormFlow

Body:
I have followed the HotelBol tutorial and the main idea is that I have a FormFlow. Following a model, I add a field, named BedSize (which is an enum) then I add all the remaining fields. So far so good, everything works fine.

public static IForm<RoomReservation> BuildForm()
{
    return new FormBuilder<RoomReservation>()
        .Message("Welcome to the hotel reservation bot!")
        .Field(nameof(BedSize))
        .AddRemainingFields()
        .Build();
}

My problem is that I want in the end to have the default confirmation, from the confirmation message. The problem I face is that the Build method from the FormBuilder has that confirmation, but to me, it does not appear.

However, if I change my code to this:

public static IForm<RoomReservation> BuildForm()
{
    return new FormBuilder<RoomReservation>()
        .Message("Welcome to the hotel reservation bot!")
        .Build();
}

it also triggers the confirmation message. Is there something that I am missing? I want to know why adding the .Field and/or .AddRemainingFields methods make the confirmation message dissapear.


问:
I want to get the status of running apps
Examples of app status: foreground / background!</p>

答:
```<code>    Context context = this.getApplicationContext();
    ActivityManager mgr = (ActivityManager)context.getSystemService(ACTIVITY_SERVICE);

    ConfigurationInfo config = mgr.getDeviceConfigurationInfo();
    List<RunningAppProcessInfo> processes = mgr.getRunningAppProcesses();
    List<RunningTaskInfo> tasks = mgr.getRunningTasks(100);

    String text = "";

    text += "Running tasks: \n";
    for(Iterator i = tasks.iterator(); i.hasNext(); )
    {
        RunningTaskInfo p = (RunningTaskInfo)i.next();
        text += p.baseActivity.flattenToString() + "\n";
    }
</code>```

EtCeTeRa

Body:
    Context context = this.getApplicationContext();
    ActivityManager mgr = (ActivityManager)context.getSystemService(ACTIVITY_SERVICE);

    ConfigurationInfo config = mgr.getDeviceConfigurationInfo();
    List<RunningAppProcessInfo> processes = mgr.getRunningAppProcesses();
    List<RunningTaskInfo> tasks = mgr.getRunningTasks(100);

    String text = "";

    text += "Running tasks: \n";
    for(Iterator i = tasks.iterator(); i.hasNext(); )
    {
        RunningTaskInfo p = (RunningTaskInfo)i.next();
        text += p.baseActivity.flattenToString() + "\n";
    }

EtCeTeRa

ContentLicense: CC BY-SA 2.5


问:
Nancy 2.0.0-barneyrubble JSON retain casing
Am trying to get Nancy to retain property names as they are. For example FirstName to remain so instead of firstName in Response.AsJson.
I have seen where it is mentioned to set JsonSettings.RetainCasing = true.
I couldn't find it in Nancy.Json or an example where to set this configuration. Any hint where to find this setting and where to place it?

答:
I could not make sense of the other answer, but found this solution.  Add the following line to use in your startup code.  It will prevent Nancy from converting cases on objects.

Nancy.Json.JsonSettings.RetainCasing = true;

I put it right before my host.Start() call:

NancyHost host = new NancyHost(uri, new DefaultNancyBootstrapper(), hostConfigs);
 host.Start();


问:
bootstrap-toggle checkbox is not showing up as toggle
I am using angular, and added bootstrap-toggle using bower. I also included the appropriate css, and js files in my index.html. In my resource file, I need to create a toggle switch. I include the following line:

```<code><div>
 <input type="checkbox" checked data-toggle="toggle">
</div>
</code>```

I don't want to add this line using javascript. It is showing up as a checkbox rather than a toggle. Is there something that I am missing?
css link snapshopt
js links snapshot

答:
If you are using, Bootstrap v2.3.2, then you should be using bootstrap2-toggle.min.js and bootstrap2-toggle.min.css.

Make sure you load the bootstrap-toggle.css after the main bootstrap.css file.

Also, make sure load the bootstrap-toggle.js after the main bootstrap.js. right before you close the body tag.

Don't forget the jquery, it needs to go before both js files.

Body:
I am using angular, and added bootstrap-toggle using bower. I also included the appropriate css, and js files in my index.html. In my resource file, I need to create a toggle switch. I include the following line:

 <input type="checkbox" checked data-toggle="toggle">

I don't want to add this line using javascript. It is showing up as a checkbox rather than a toggle. Is there something that I am missing?
css link snapshopt
js links snapshot


问:
Select records when month and day are less than current date
I am using SQL Server Mgmt Studio. I need to create a formula that will only select records when the month and day of a date/time field, LAW_TAEEMASTER.MASTR_ENTRY, is less than or equal to the current month and day. For example, If LAW_TAEEMASTER.MASTR_ENTRY = 8/20/2015 and current date = 7/6/2017, exclude. If LAW_TAEEMASTER.MASTR_ENTRY = 12/21/2014 and current date = 1/15/2017, include. Date formatting is my weakness. Here is what I have tried:

```<code>select LAW_TAEEMASTER.MASTR_ENTRY
    from LAW_TAEEMASTER
    WHERE day(LAW_TAEEMASTER.MASTR_ENTRY) <= DAY(GETDATE()) and MONTH(LAW_TAEEMASTER.MASTR_ENTRY) <= MONTH(getdate())
</code>```

and

```<code>select LAW_TAEEMASTER.MASTR_ENTRY
        from LAW_TAEEMASTER
        WHERE AND DATEPART(DAY,LAW_TAEEMASTER.MASTR_ENTRY) <= DATEPART(DAY,GETDATE()) AND DATEPART(MONTH,LAW_TAEEMASTER.MASTR_ENTRY) <= DATEPART(MONTH,GETDATE())
</code>```

but these just evaluate the month and day separately and as a number, greater than or less than, so it's excluding records. How can I get SQL to recognize these as part of a date and just ignore the year?

答:
I would do this using month() and day():

```<code>where month(LAW_TAEEMASTER.MASTR_ENTRY) * 100 + day(LAW_TAEEMASTER.MASTR_ENTRY) < month(getdate()) * 100 + day(getdate())
</code>```

If performance is an issue, I would recommend a computed column with an index.

Body:
I am using SQL Server Mgmt Studio. I need to create a formula that will only select records when the month and day of a date/time field, LAW_TAEEMASTER.MASTR_ENTRY, is less than or equal to the current month and day. For example, If LAW_TAEEMASTER.MASTR_ENTRY = 8/20/2015 and current date = 7/6/2017, exclude. If LAW_TAEEMASTER.MASTR_ENTRY = 12/21/2014 and current date = 1/15/2017, include. Date formatting is my weakness. Here is what I have tried:

select LAW_TAEEMASTER.MASTR_ENTRY
    from LAW_TAEEMASTER
    WHERE day(LAW_TAEEMASTER.MASTR_ENTRY) <= DAY(GETDATE()) and MONTH(LAW_TAEEMASTER.MASTR_ENTRY) <= MONTH(getdate())

and

select LAW_TAEEMASTER.MASTR_ENTRY
        from LAW_TAEEMASTER
        WHERE AND DATEPART(DAY,LAW_TAEEMASTER.MASTR_ENTRY) <= DATEPART(DAY,GETDATE()) AND DATEPART(MONTH,LAW_TAEEMASTER.MASTR_ENTRY) <= DATEPART(MONTH,GETDATE())

but these just evaluate the month and day separately and as a number, greater than or less than, so it's excluding records. How can I get SQL to recognize these as part of a date and just ignore the year?

Body:
I would do this using month() and day():

where month(LAW_TAEEMASTER.MASTR_ENTRY) * 100 + day(LAW_TAEEMASTER.MASTR_ENTRY) < month(getdate()) * 100 + day(getdate())

If performance is an issue, I would recommend a computed column with an index.


问:
Displaying text with Emojis on Flutter
I have some texts that contain emojis and I'm trying to show them on the Text widget. However, they seem to be shown as foreign characters. Does Flutter support showing emojis? should work for both iOS and Android</p>

答:
Flutter supports emoji. Here's some code that demonstrates emoji text entry. (If you're seeing foreign characters, it's likely that you're decoding bytes as ASCII instead of UTF-8; we can show you how to fix this if you update your question with code that demonstrates the problem.)

```<code>import 'dart:async';
import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _message = '';

  Future<String> _promptForString(String label, { String hintText }) {
    final TextEditingController controller = new TextEditingController();
    return showDialog(
      context: context,
      child: new AlertDialog(
        title: new Text(label),
        content: new TextFormField(
          controller: controller,
          decoration: new InputDecoration(hintText: hintText),
        ),
        actions: <Widget>[
          new FlatButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('CANCEL'),
          ),
          new FlatButton(
            onPressed: () => Navigator.pop(context, controller.text),
            child: const Text('OK'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(_message),
      ),
      body: new Center(
        child: new Text(_message, style: Theme.of(context).textTheme.display2),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.edit),
        onPressed: () async {
          String message = await _promptForString('New text', hintText: 'Try emoji!');
          if (!mounted)
            return;
          setState(() {
            _message = message;
          });
        },
      ),
    );
  }
}
</code>```

Title: Displaying text with Emojis on Flutter

Body:
Flutter supports emoji. Here's some code that demonstrates emoji text entry. (If you're seeing foreign characters, it's likely that you're decoding bytes as ASCII instead of UTF-8; we can show you how to fix this if you update your question with code that demonstrates the problem.)

import 'dart:async';
import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _message = '';

  Future<String> _promptForString(String label, { String hintText }) {
    final TextEditingController controller = new TextEditingController();
    return showDialog(
      context: context,
      child: new AlertDialog(
        title: new Text(label),
        content: new TextFormField(
          controller: controller,
          decoration: new InputDecoration(hintText: hintText),
        ),
        actions: <Widget>[
          new FlatButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('CANCEL'),
          ),
          new FlatButton(
            onPressed: () => Navigator.pop(context, controller.text),
            child: const Text('OK'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(_message),
      ),
      body: new Center(
        child: new Text(_message, style: Theme.of(context).textTheme.display2),
      ),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.edit),
        onPressed: () async {
          String message = await _promptForString('New text', hintText: 'Try emoji!');
          if (!mounted)
            return;
          setState(() {
            _message = message;
          });
        },
      ),
    );
  }
}


问:
Java XML Parsing - incorrect string version of the data with VTD-XML
I am parsing an XML document in UTF-8 encoding with Java using VTD-XML.

A small excerpt looks like:

```<code><literal></literal>
<literal></literal>
<literal></literal>
</code>```

I want to iterate through each literal and print it out to the console. However, what I get is:

```<code>¢
</code>```

I am correctly navigating to each element. The way that I get the text value is by calling:

```<code>private static String toNormalizedString(String name, int val, final VTDNav vn) throws NavException {
    String strValue = null;
    if (val != -1) {
        strValue = vn.toNormalizedString(val);
    }
    return strValue;
}
</code>```

I've also tried vn.getXPathStringVal();, however it yields the same results.

I know that each of the literals above aren't just strings of length one. Rather, they seem to be unicode "characters" composed of two characters. I am able to correctly parse and output the kanji characters if they're length is just one.

My question is - how can I correctly parse and output these characters using VTD-XML? Is there a way to get the underlying bytes of the text between the literal tags so that I can parse the bytes myself?

EDIT

Code to process each line of the XML - converting it to a byte array and then back to a String.

```<code>try (BufferedReader br = new BufferedReader(new FileReader("res/sample.xml"))) {
        String line;
        while ((line = br.readLine()) != null) {
            byte[] myBytes = null;

            try {
                myBytes = line.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(-1);
            }

            System.out.println(new String(myBytes));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
</code>```

答:
You are probably trying to get the string involving characters that is greater than 0x10000. That bug is known and is in the process of being addressed... I will notify you once the fix is out.
This question may be identical to this one...
Map supplementary Unicode characters to BMP (if possible)</p>

Body:
I am parsing an XML document in UTF-8 encoding with Java using VTD-XML.

A small excerpt looks like:

<literal></literal>
<literal></literal>
<literal></literal>

I want to iterate through each literal and print it out to the console. However, what I get is:

¢

I am correctly navigating to each element. The way that I get the text value is by calling:

private static String toNormalizedString(String name, int val, final VTDNav vn) throws NavException {
    String strValue = null;
    if (val != -1) {
        strValue = vn.toNormalizedString(val);
    }
    return strValue;
}

I've also tried vn.getXPathStringVal();, however it yields the same results.

I know that each of the literals above aren't just strings of length one. Rather, they seem to be unicode "characters" composed of two characters. I am able to correctly parse and output the kanji characters if they're length is just one.

My question is - how can I correctly parse and output these characters using VTD-XML? Is there a way to get the underlying bytes of the text between the literal tags so that I can parse the bytes myself?

EDIT

Code to process each line of the XML - converting it to a byte array and then back to a String.

try (BufferedReader br = new BufferedReader(new FileReader("res/sample.xml"))) {
        String line;
        while ((line = br.readLine()) != null) {
            byte[] myBytes = null;

            try {
                myBytes = line.getBytes("UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                System.exit(-1);
            }

            System.out.println(new String(myBytes));
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }


问:
Change ViewFinder in zxing
How can I change the viewfinder size, colors and other options when I'm using dependencies compile 'me.dm7.barcodescanner:zxing:1.9' without an access to the zxing files?
I could not find a solution for this problem.

答:
You can do it via XML

```<code><com.journeyapps.barcodescanner.BarcodeView
      android:id="@+id/zxing_barcode_surface"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:zxing_framing_rect_height="220dp"
      app:zxing_framing_rect_width="250dp" />

<com.journeyapps.barcodescanner.ViewfinderView
    android:id="@+id/zxing_viewfinder_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:zxing_possible_result_points="@color/zxing_custom_possible_result_points"
    app:zxing_result_view="@color/zxing_custom_result_view"
    app:zxing_viewfinder_laser="@color/zxing_custom_viewfinder_laser"
    app:zxing_viewfinder_mask="@color/zxing_custom_viewfinder_mask" />
</code>```

Also check this post (possible duplicate this question), and another one, if you want to change behavior programmatically.

To access the library features, you need to add the following to your build.gradle file:

```<code>repositories {
    jcenter()
}

dependencies {
    compile 'me.dm7.barcodescanner:zxing:1.9.3'
}
</code>```

And add camera permission to your AndroidManifest.xml file:

```<code><uses-permission android:name="android.permission.CAMERA" />
</code>```

Title: Change ViewFinder in zxing

Body:
You can do it via XML

<com.journeyapps.barcodescanner.BarcodeView
      android:id="@+id/zxing_barcode_surface"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      app:zxing_framing_rect_height="220dp"
      app:zxing_framing_rect_width="250dp" />

<com.journeyapps.barcodescanner.ViewfinderView
    android:id="@+id/zxing_viewfinder_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:zxing_possible_result_points="@color/zxing_custom_possible_result_points"
    app:zxing_result_view="@color/zxing_custom_result_view"
    app:zxing_viewfinder_laser="@color/zxing_custom_viewfinder_laser"
    app:zxing_viewfinder_mask="@color/zxing_custom_viewfinder_mask" />

Also check this post (possible duplicate this question), and another one, if you want to change behavior programmatically.

To access the library features, you need to add the following to your build.gradle file:

repositories {
    jcenter()
}

dependencies {
    compile 'me.dm7.barcodescanner:zxing:1.9.3'
}

And add camera permission to your AndroidManifest.xml file:

<uses-permission android:name="android.permission.CAMERA" />


问:
Use Json and AjaxLink to Toggle Link Values in ASP.NET MVC 2
I have a list of Child objects.  I would like to be able to toggle whether they are included in a smaller list of objects which have a relationship to a Parent object.  Like so:

```<code><% foreach(var child in Model.AllPossibleChildren)%>
<% { %>
<tr>
    <td>
        <%if(child.Link.Any(r => r.Id == Model.Parent.Id))
            { %>
            <%:Ajax.ActionLink("Remove", "RemoveChild", new { aId = Model.Parent.Id, rId = child.Id }, null)%>
        <% }
            else
        { %>
            <%:Ajax.ActionLink("Add", "AddChild", new { aId = Model.Parent.Id, rId = child.Id }, null)%>
        <% } %>
    </td>
</tr>
<% } %>
</code>```

The idea here is that when the user clicks on "Remove", it will remove the relationship between the Parent and Child, and then somehow (using Jquery or AjaxOptions) toggle the ActionLink parameters to match the other condition (Add instead of Remove for link text, AddChild instead of RemoveChild for action method).  That's the part I'm unclear on.

Am I approaching this correctly, or is there a better way to do this?

If this is the right approach, which would be better to use - AjaxOptions or JQuery (I'm guessing the answer is JQuery, since it's more flexible)

Depending on the answer to #2, how would I do that?

Incidentally, here's my action method.  I tested that they are called correctly and pass the correct parameters.

```<code>    public JsonResult AddChild(string aId, int rId)
    {
        //Create Relationship
        return Json(result);
    }

    public JsonResult RemoveChild(string aID, int rID)
    {
        //Remove Relationship
        return Json(result);
    }
</code>```

Thanks!

UPDATE
I've investigating using partialviews for this, but can't seem to get that to work either.  I keep coming back to this model, and continue to not be able to figure out how to get it to work!  I don't want to have to repost the whole page, although with the way I have it set up right now it would work.  Perhaps that's my problem?  Still looking for some help!

答: I gave up on using Ajax.ActionLink and went with a straight div/ jquery ajax approach. Not that I knew how to do that either...see my subsequent question and my final working answer here: Can't get jquery $ajax to call .NET MVC 2 controller method

Body:
I have a list of Child objects.  I would like to be able to toggle whether they are included in a smaller list of objects which have a relationship to a Parent object.  Like so:

<% foreach(var child in Model.AllPossibleChildren)%>
<% { %>

        <%if(child.Link.Any(r => r.Id == Model.Parent.Id))
            { %>
            <%:Ajax.ActionLink("Remove", "RemoveChild", new { aId = Model.Parent.Id, rId = child.Id }, null)%>
        <% }
            else
        { %>
            <%:Ajax.ActionLink("Add", "AddChild", new { aId = Model.Parent.Id, rId = child.Id }, null)%>
        <% } %>

<% } %>

The idea here is that when the user clicks on "Remove", it will remove the relationship between the Parent and Child, and then somehow (using Jquery or AjaxOptions) toggle the ActionLink parameters to match the other condition (Add instead of Remove for link text, AddChild instead of RemoveChild for action method).  That's the part I'm unclear on.

Am I approaching this correctly, or is there a better way to do this?

If this is the right approach, which would be better to use - AjaxOptions or JQuery (I'm guessing the answer is JQuery, since it's more flexible)

Depending on the answer to #2, how would I do that?

Incidentally, here's my action method.  I tested that they are called correctly and pass the correct parameters.

    public JsonResult AddChild(string aId, int rId)
    {
        //Create Relationship
        return Json(result);
    }

    public JsonResult RemoveChild(string aID, int rID)
    {
        //Remove Relationship
        return Json(result);
    }

Thanks!

UPDATE
I've investigating using partialviews for this, but can't seem to get that to work either.  I keep coming back to this model, and continue to not be able to figure out how to get it to work!  I don't want to have to repost the whole page, although with the way I have it set up right now it would work.  Perhaps that's my problem?  Still looking for some help!


问:
weird colormap when map the scalar value to RGB using matplotlib.colors.Colormap
I am trying to get RGB hex strings from a input scalar given a specific matplot lib colormap. I use matplotlib.get_cmap() to get the matplotlib.colors.Colormap object, and pass a scalar withing range (0, 1) to this map to get the RGBA value then plot that color. But sometimes the colors gets plotted are different from those plotted by imshow(). Am I doing something stupid here?

Code for reproduction

```<code>import matplotlib.pyplot as plt
import numpy as np
plt.ioff()

cmap = 'RdBu_r'
cmap = plt.get_cmap(cmap)

f = plt.figure(figsize=(8, 4))
ax1 = f.add_subplot(121)
ax2 = f.add_subplot(122)
plot_arr = np.arange(100).reshape((10, 10)) / 99.
ax1.imshow(plot_arr, vmin=0., vmax=1., cmap=cmap, interpolation='nearest')

for i in range(10):
    for j in range(10):
        curr_rgb = cmap(plot_arr[i, j])[0:3]
        curr_rgb = tuple([int(x * 255) for x in curr_rgb])
        r, g, b = curr_rgb
        curr_cstr = '#{:0<2}{:0<2}{:0<2}'.format(hex(r)[2:], hex(g)[2:], hex(b)[2:])
        ax2.plot(j, i, 'o', mfc=curr_cstr, lw=0, mec='none', ms=20)

ax2.set_xlim([-0.5, 9.5])
ax2.set_ylim([9.5, -0.5])
plt.show()
</code>```

Actual outcome

output image

Expected outcome
As implemented in the code, the left plot is plotted as imshow(). Right plot is plotted dots with the color from the colormap object according to the input scalar. If my understanding is right, the colors at the same grid cell should be identical. But clearly different at high and low values.

Matplotlib version

    Operating System: windows 7 64-bit

    Matplotlib Version: 2.0.2

    Python Version: 3.5.3

    numpy: 1.13.0

答:
In your format function, you're left aligning, not right aligning, causing the weird value jumps.  See this line:

```<code>curr_cstr = '#{:0<2}{:0<2}{:0<2}'.format(hex(r)[2:], hex(g)[2:], hex(b)[2:])
</code>```

And the docs for format.  Fixed version:

```<code>import matplotlib.pyplot as plt
import numpy as np
plt.ioff()

cmap = 'RdBu_r'
cmap = plt.get_cmap(cmap)

f = plt.figure(figsize=(8, 4))
ax1 = f.add_subplot(121)
ax2 = f.add_subplot(122)
plot_arr = np.arange(100).reshape((10, 10)) / 99.
ax1.imshow(plot_arr, vmin=0., vmax=1., cmap=cmap, interpolation='nearest')

for i in range(10):
    for j in range(10):
        curr_rgb = cmap(plot_arr[i, j])[0:3]
        curr_rgb = tuple([int(x * 255) for x in curr_rgb])
        r, g, b = curr_rgb
        curr_cstr = '#{:0>2}{:0>2}{:0>2}'.format(hex(r)[2:], hex(g)[2:], hex(b)[2:])
        ax2.plot(j, i, 'o', mfc=curr_cstr, lw=0, mec='none', ms=20)

ax2.set_xlim([-0.5, 9.5])
ax2.set_ylim([9.5, -0.5])
plt.show()
</code>```

Note the incorrect RGB to hex conversions in your original:

```<code>if i==9: print i ,j, curr_rgb, curr_cstr

9 0 (170, 21, 41) #001500
9 1 (161, 18, 40) #001200
9 2 (155, 16, 39) #001000
9 3 (147, 14, 38) #00e000
9 4 (138, 11, 36) #00b000
9 5 (132, 9, 35) #009000
9 6 (123, 6, 34) #006000
9 7 (117, 4, 33) #004000
9 8 (108, 1, 31) #001000
9 9 (103, 0, 31) #000000
</code>```

Body:
I am trying to get RGB hex strings from a input scalar given a specific matplot lib colormap. I use matplotlib.get_cmap() to get the matplotlib.colors.Colormap object, and pass a scalar withing range (0, 1) to this map to get the RGBA value then plot that color. But sometimes the colors gets plotted are different from those plotted by imshow(). Am I doing something stupid here?

Code for reproduction

import matplotlib.pyplot as plt
import numpy as np
plt.ioff()

cmap = 'RdBu_r'
cmap = plt.get_cmap(cmap)

f = plt.figure(figsize=(8, 4))
ax1 = f.add_subplot(121)
ax2 = f.add_subplot(122)
plot_arr = np.arange(100).reshape((10, 10)) / 99.
ax1.imshow(plot_arr, vmin=0., vmax=1., cmap=cmap, interpolation='nearest')

for i in range(10):
    for j in range(10):
        curr_rgb = cmap(plot_arr[i, j])[0:3]
        curr_rgb = tuple([int(x * 255) for x in curr_rgb])
        r, g, b = curr_rgb
        curr_cstr = '#{:0<2}{:0<2}{:0<2}'.format(hex(r)[2:], hex(g)[2:], hex(b)[2:])
        ax2.plot(j, i, 'o', mfc=curr_cstr, lw=0, mec='none', ms=20)

ax2.set_xlim([-0.5, 9.5])
ax2.set_ylim([9.5, -0.5])
plt.show()

Actual outcome

output image

Expected outcome
As implemented in the code, the left plot is plotted as imshow(). Right plot is plotted dots with the color from the colormap object according to the input scalar. If my understanding is right, the colors at the same grid cell should be identical. But clearly different at high and low values.

Matplotlib version

    Operating System: windows 7 64-bit

    Matplotlib Version: 2.0.2

    Python Version: 3.5.3

    numpy: 1.13.0

Body:
In your format function, you're left aligning, not right aligning, causing the weird value jumps.  See this line:

curr_cstr = '#{:0<2}{:0<2}{:0<2}'.format(hex(r)[2:], hex(g)[2:], hex(b)[2:])

And the docs for format.  Fixed version:

import matplotlib.pyplot as plt
import numpy as np
plt.ioff()

cmap = 'RdBu_r'
cmap = plt.get_cmap(cmap)

f = plt.figure(figsize=(8, 4))
ax1 = f.add_subplot(121)
ax2 = f.add_subplot(122)
plot_arr = np.arange(100).reshape((10, 10)) / 99.
ax1.imshow(plot_arr, vmin=0., vmax=1., cmap=cmap, interpolation='nearest')

for i in range(10):
    for j in range(10):
        curr_rgb = cmap(plot_arr[i, j])[0:3]
        curr_rgb = tuple([int(x * 255) for x in curr_rgb])
        r, g, b = curr_rgb
        curr_cstr = '#{:0>2}{:0>2}{:0>2}'.format(hex(r)[2:], hex(g)[2:], hex(b)[2:])
        ax2.plot(j, i, 'o', mfc=curr_cstr, lw=0, mec='none', ms=20)

ax2.set_xlim([-0.5, 9.5])
ax2.set_ylim([9.5, -0.5])
plt.show()

Note the incorrect RGB to hex conversions in your original:

if i==9: print i ,j, curr_rgb, curr_cstr

9 0 (170, 21, 41) #001500
9 1 (161, 18, 40) #001200
9 2 (155, 16, 39) #001000
9 3 (147, 14, 38) #00e000
9 4 (138, 11, 36) #00b000
9 5 (132, 9, 35) #009000
9 6 (123, 6, 34) #006000
9 7 (117, 4, 33) #004000
9 8 (108, 1, 31) #001000
9 9 (103, 0, 31) #000000


问:
Is it possible to remove an object in an array rather than its index? (Java)
When I tried self-answering this question, I could only find other questions regarding removing items from an array so that items past the removed object get moved down 1 in the index.

In the code below, I have two arrays that hold the class SomeObject (with a name property): SomeObject_ONE and SomeObject_TWO.

Below I put an object "some-object" in the first array, and then set the second array to equal the object in the first array. I can still change the properties of the object in the first array by changing the properties of the object in the second array (the 3rd indent.)

However, when I try setting the object in the second array to null, it doesn't set the first array to null, rather it only removes the index for the object in the second array (4th indent).

Is there anyway to delete an object in an array rather than removing its array index?

Thanks.

```<code>    SomeObject[] ObjectArray_ONE = new SomeObject[10];
    SomeObject[] ObjectArray_TWO = new SomeObject[10];

    ObjectArray_ONE[0] = new SomeObject();
    ObjectArray_TWO[0] = ObjectArray_ONE[0];

    System.out.println(ObjectArray_ONE[0].name+" outputs default name");
    ObjectArray_TWO[0].name = "Name changed from OA2";
    System.out.println(ObjectArray_ONE[0].name+" outputs Name changed from OA2");

    System.out.println("Should not be null        : "+ObjectArray_ONE[0]);
    ObjectArray_TWO[0] = null;
    System.out.println("Should be null            : "+ObjectArray_ONE[0]);
    ObjectArray_ONE[0] = null;
    System.out.println("Only now is it really null: "+ObjectArray_ONE[0]);
</code>```

答:
This is a Pass by Reference vs Pass by Value.

Java is pass by value, and in this case the value is a reference.  It's a subtle distinction.  What it means here is that if you change the object being referenced in one place, it will change everywhere.  But it will not change the reference.  If I set the reference to be equal to something else, the original object is unchanged.

Body:
When I tried self-answering this question, I could only find other questions regarding removing items from an array so that items past the removed object get moved down 1 in the index.

In the code below, I have two arrays that hold the class SomeObject (with a name property): SomeObject_ONE and SomeObject_TWO.

Below I put an object "some-object" in the first array, and then set the second array to equal the object in the first array. I can still change the properties of the object in the first array by changing the properties of the object in the second array (the 3rd indent.)

However, when I try setting the object in the second array to null, it doesn't set the first array to null, rather it only removes the index for the object in the second array (4th indent).

Is there anyway to delete an object in an array rather than removing its array index?

Thanks.

    SomeObject[] ObjectArray_ONE = new SomeObject[10];
    SomeObject[] ObjectArray_TWO = new SomeObject[10];

    ObjectArray_ONE[0] = new SomeObject();
    ObjectArray_TWO[0] = ObjectArray_ONE[0];

    System.out.println(ObjectArray_ONE[0].name+" outputs default name");
    ObjectArray_TWO[0].name = "Name changed from OA2";
    System.out.println(ObjectArray_ONE[0].name+" outputs Name changed from OA2");

    System.out.println("Should not be null        : "+ObjectArray_ONE[0]);
    ObjectArray_TWO[0] = null;
    System.out.println("Should be null            : "+ObjectArray_ONE[0]);
    ObjectArray_ONE[0] = null;
    System.out.println("Only now is it really null: "+ObjectArray_ONE[0]);


问:
Sending null parameters from Angular controller cause unreachable function
I have AngularCtrl where I receive a parameter, if it comes null, it just dont execute function:

HTML:

```<code><button type="submit" class="btn blue" ng-click="insertar();">Accept</button>
</code>```

Angular controller

```<code>    $scope.catalogoPadre = $stateParams.catalogopadre;

        if ($scope.catalogoPadre != null) {
            cargarCatalogo();
        }

        function cargarCatalogo() {
            apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
               function (res) {
                   $scope.Catalogos = res.data;

                   $scope.selected = $scope.Catalogos[0];
                   inicial
                   $scope.filtro($scope.selected);
               }, errorCatalogo);
</code>```

As you can see cargarCatalogo is a simple query that populates a select

Problem is when I try to execute insertar function (that is into ng-click of view), when I send all parameters, including $scope.selected.ID that I get into cargarCatalogo() function it runs correctly, but if I want to execute it without  $scope.selected.ID it don´t reach insertar function when I debbug chrome console.

Angular Controller second part

```<code>            $scope.filtro = function (selected) {

                $scope.selectedID = selected.ID;

                $scope.insertar = insertar;

                function insertar() {

                    if ($scope.catalogoid != null) {
                        var url = "../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo;
                        if ($scope.selected.ID != null) {
                            url = url + "/" + $scope.selected.ID;
                        }
                        apiService.post(url , null,
                            function (response) {
                                bootbox.alert("Operación Exitosa!");
                                $state.go("root.catalogosgenericos");
                            },
                            function (response) {

                                }
                            });
                    }
</code>```

What can be wrong there? why  $scope.insertar = insertar; ´dont execute if I dont send all paramters if I have a validation

```<code> if ($scope.selected.ID != null) {
         url = url + "/" + $scope.selected.ID;
            }
</code>```

Regards

Update:

I change code as alphapilgrim comment but it still dont fire insertar action when $scope.selected.ID comes null

Code:

```<code> function cargarCatalogo() {
            apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
               function (res) {
                 .
                   $scope.Catalogos = res.data;

                   $scope.selected = $scope.Catalogos[0];

                   $scope.filtro($scope.selected);
               }, errorCatalogo);

            $scope.filtro = function (selected) {
                $scope.selectedID = selected.ID;

                $scope.insertar = function() {
                    $scope.selectedID = selected.ID;
                    if ($scope.catalogoid != null) {
                        var url = "../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo;
                        if ($scope.selected.ID != null) {
                            url = url + "/" + $scope.selected.ID;
                        }
                        apiService.post(url, null,
                          function(response) {
                              bootbox.alert("Operación Exitosa!");
                              $state.go("root.catalogosgenericos");
                          },
                          function(response) {
                              if (response.status == "500") {
                                  window.location = "/";
                              } else {
                                  bootbox.alert(response.status + " " + response.statusText + "<br/>" + response.data.errores);
                              }
                          });
                      }
</code>```

Entire HTML

```<code><div class="page-head">
  <div class="page-title">
    <h1>
                Catálogos Genéricos
                <small>Nuevo Registro de: {{tipoCatalogo}}</small>
            </h1>
  </div>
</div>
<div class="row">
  <div class="col-md-12">
    <!-- BEGIN Portlet PORTLET-->
    <div class="portlet box blue">
      <div class="portlet-title">
        <div class="caption">
          Catálogos
        </div>
        <div class="tools">
          <a href="javascript:;" class="collapse" data-original-title="" title=""> </a>
          <!-- <a href="javascript:;" class="reload" data-original-title="" title=""> </a>-->
          <a href="javascript:;" class="fullscreen" data-original-title="" title=""> </a>
        </div>
      </div>
      <div class="portlet-body">
        <!-- PITE - INICIA TABS -->
        <div class="row">
          <div class="col-md-12">
            <!-- BEGIN Portlet PORTLET-->
            <div class="portlet box red">
              <div class="portlet-title">
                <div class="caption" id="tab_titulo">
                  Nuevo registro de: {{tipoCatalogo}}
                </div>
                <div class="tools">
                  <a href="javascript:;" class="collapse"> </a>
                  <a href="javascript:;" class="reload" ng-click="fill(conductor.ID); actualizardoctos();"> </a>
                  <a href="javascript:;" class="fullscreen"> </a>
                </div>
              </div>
              <div class="portlet-body">
                <div class="tab-content">
                  <div class="tab-pane fade active in" id="tab_2_1">

                    <div class="form-group">
                      <form id="detalle" name="detalle">
                        <div class="row">
                          <div class="col-xs-12 col-sm-6 col-md-4">
                            <div class="form-group">
                              <label> Código: </label>
                              <input type="text" class="form-control" id="Codigo" name="Codigo" ng-model="Codigo" maxlength="3" required/>
                              <span ng-show="detalle.Codigo.$error.maxlength || detalle.Codigo.length" class="required">El Código debe contener 3 caracteres</span>
                            </div>
                          </div>
                          <div class="col-xs-12 col-sm-6 col-md-4">
                            <div class="form-group">
                              <label> Nombre: </label>
                              <input type="text" class="form-control" id="Nombre" name="Nombre" ng-model="Nombre" maxlength="255" required />
                            </div>
                          </div>
                          <div class="col-xs-12 col-sm-4 col-md-4">
                            <div class="form-group" ng-init="cargarCatalogo()">
                              <label ng-hide="Catalogos.length==0">Catalogo Padre: </label>

                              <select class="form-control" ng-hide="Catalogos.length==0" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>
                              <br />
                            </div>
                          </div>
                        </div>

                        <hr width="100%" style="color: #2F353B;">
                        <div class="form-actions">
                          <div class="row">
                            <div class="text-right col-md-12">
                              <button type="submit" class="btn blue" ng-click="insertar();">Aceptar</button>
                              <button type="button" class="btn default" ng-click="regresar();">Cancelar</button>
                            </div>
                          </div>
                        </div>
                      </form>
                    </div>

                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>
<div ui-view> </div>
</code>```

答:
You should consider using controllerAs syntax and not attaching methods to your $scope. It will require a small bit of refactoring, but will result in much cleaner code.

Here's a plnkr showing converting a simplified version of your code to controllerAs syntax: http://plnkr.co/edit/yZuB5eEiZW15sNzqBIGS?p=preview

As alphapilgrim mentioned in the comment, you have your insertar method defined inside of filtro. If the filtro method is never called, as is most likely the case here, insertar will be null.

See https://toddmotto.com/digging-into-angulars-controller-as-syntax/ for a pretty good primer on how to switch over to controllerAs syntax. It's worth the effort in your sanity.

Body:
I have AngularCtrl where I receive a parameter, if it comes null, it just dont execute function:

HTML:

<button type="submit" class="btn blue" ng-click="insertar();">Accept</button>

Angular controller

    $scope.catalogoPadre = $stateParams.catalogopadre;

        if ($scope.catalogoPadre != null) {
            cargarCatalogo();
        }

        function cargarCatalogo() {
            apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
               function (res) {
                   $scope.Catalogos = res.data;

                   $scope.selected = $scope.Catalogos[0];
                   inicial
                   $scope.filtro($scope.selected);
               }, errorCatalogo);

As you can see cargarCatalogo is a simple query that populates a select

Problem is when I try to execute insertar function (that is into ng-click of view), when I send all parameters, including $scope.selected.ID that I get into cargarCatalogo() function it runs correctly, but if I want to execute it without  $scope.selected.ID it don´t reach insertar function when I debbug chrome console.

Angular Controller second part

            $scope.filtro = function (selected) {

                $scope.selectedID = selected.ID;

                $scope.insertar = insertar;

                function insertar() {

                    if ($scope.catalogoid != null) {
                        var url = "../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo;
                        if ($scope.selected.ID != null) {
                            url = url + "/" + $scope.selected.ID;
                        }
                        apiService.post(url , null,
                            function (response) {
                                bootbox.alert("Operación Exitosa!");
                                $state.go("root.catalogosgenericos");
                            },
                            function (response) {

                                }
                            });
                    }

What can be wrong there? why  $scope.insertar = insertar; ´dont execute if I dont send all paramters if I have a validation

 if ($scope.selected.ID != null) {
         url = url + "/" + $scope.selected.ID;
            }

Regards

Update:

I change code as alphapilgrim comment but it still dont fire insertar action when $scope.selected.ID comes null

Code:

 function cargarCatalogo() {
            apiService.get("../../api/Catalogo/GetCatalogoPadre/" + $scope.Catalogo + "/", null,
               function (res) {
                 .
                   $scope.Catalogos = res.data;

                   $scope.selected = $scope.Catalogos[0];

                   $scope.filtro($scope.selected);
               }, errorCatalogo);

            $scope.filtro = function (selected) {
                $scope.selectedID = selected.ID;

                $scope.insertar = function() {
                    $scope.selectedID = selected.ID;
                    if ($scope.catalogoid != null) {
                        var url = "../../api/Catalogo/UpdateCatalogoRegistro/" + $scope.Codigo + "/" + $scope.Nombre + "/" + $scope.catalogoid + "/" + $scope.Catalogo;
                        if ($scope.selected.ID != null) {
                            url = url + "/" + $scope.selected.ID;
                        }
                        apiService.post(url, null,
                          function(response) {
                              bootbox.alert("Operación Exitosa!");
                              $state.go("root.catalogosgenericos");
                          },
                          function(response) {
                              if (response.status == "500") {
                                  window.location = "/";
                              } else {
                                  bootbox.alert(response.status + " " + response.statusText + "
" + response.data.errores);
                              }
                          });
                      }

Entire HTML

                Catálogos Genéricos
                Nuevo Registro de: {{tipoCatalogo}}

          Catálogos

                  Nuevo registro de: {{tipoCatalogo}}

                      <form id="detalle" name="detalle">

                               Código:
                              <input type="text" class="form-control" id="Codigo" name="Codigo" ng-model="Codigo" maxlength="3" required/>
                              El Código debe contener 3 caracteres

                               Nombre:
                              <input type="text" class="form-control" id="Nombre" name="Nombre" ng-model="Nombre" maxlength="255" required />

                              Catalogo Padre:

                              <select class="form-control" ng-hide="Catalogos.length==0" ng-change="filtro(selected)" ng-model="selected" ng-options="item.Nombre for item in Catalogos "></select>

                              <button type="submit" class="btn blue" ng-click="insertar();">Aceptar</button>
                              <button type="button" class="btn default" ng-click="regresar();">Cancelar</button>

                      </form>


问:
Default field values in nested objects
I am attempting to create an object from JSON.

Part of my object looks like

```<code>a: {
   name: "A name",
   b: {
      c: {
         d: []
         }
      }
   }
</code>```

To save bandwidth, empty arrays and empty objects are stripped from the JSON, so the JSON that I receive is

```<code>{ "a": { "name": "A name" }}
</code>```

If I just convert the JSON to an object, this leads to errors when I try to do things like a.b.c.d.length, as undefined does not have a length.

At the moment, I am populating the missing fields by something like

```<code>const json = getJson();
const obj = {
    ...json,
    a: {
       ...json.a,
       b: {
          ...json.a.b,
          c: {
             ...json.a.b.c,
             d: json.a.b.c.d || []
             }
           }
        }
     };
</code>```

This is pretty verbose, and is going to get even uglier when there are several fields that need default values.

One obvious solution is to not strip out the empty arrays from the transmitted JSON.  Assuming that that is not possible, is there a better way to handle this case?

In the real case, there are multiple fields at each level, so all of the spread operators are necessary.  (Even if they were not, I would want to include them as the structure is likely to grow in the future.)

Edit: I am not using JQuery.  I am using whatwg-fetch to retrieve data.

答:
Removing empty objects/arrays from response is not a good practice, because these can be valid values.

It is premature optimization, which does not have real benefit on performance. In return it will give you a lot of headaches when you will need to specially handle each response.

But if you still think that it is worth, then I recommend lodash get function.

```<code>_.get(object, 'property.path.here')
</code>```

Title: Default field values in nested objects

Body:
I am attempting to create an object from JSON.

Part of my object looks like

a: {
   name: "A name",
   b: {
      c: {
         d: []
         }
      }
   }

To save bandwidth, empty arrays and empty objects are stripped from the JSON, so the JSON that I receive is

{ "a": { "name": "A name" }}

If I just convert the JSON to an object, this leads to errors when I try to do things like a.b.c.d.length, as undefined does not have a length.

At the moment, I am populating the missing fields by something like

const json = getJson();
const obj = {
    ...json,
    a: {
       ...json.a,
       b: {
          ...json.a.b,
          c: {
             ...json.a.b.c,
             d: json.a.b.c.d || []
             }
           }
        }
     };

This is pretty verbose, and is going to get even uglier when there are several fields that need default values.

One obvious solution is to not strip out the empty arrays from the transmitted JSON.  Assuming that that is not possible, is there a better way to handle this case?

In the real case, there are multiple fields at each level, so all of the spread operators are necessary.  (Even if they were not, I would want to include them as the structure is likely to grow in the future.)

Edit: I am not using JQuery.  I am using whatwg-fetch to retrieve data.

Body:
Removing empty objects/arrays from response is not a good practice, because these can be valid values.

It is premature optimization, which does not have real benefit on performance. In return it will give you a lot of headaches when you will need to specially handle each response.

But if you still think that it is worth, then I recommend lodash get function.

_.get(object, 'property.path.here')


答:
Instead of this:

```<code>    if ($scope.catalogoPadre != null) {
        cargarCatalogo();
    }
</code>```

please use:

```<code>    if ($scope.catalogoPadre) {
        cargarCatalogo();
    }
</code>```

It's more common and might fix your issue since it also check for undefined.

Title: Sending null parameters from Angular controller cause unreachable function

Body:
Instead of this:

    if ($scope.catalogoPadre != null) {
        cargarCatalogo();
    }

please use:

    if ($scope.catalogoPadre) {
        cargarCatalogo();
    }

It's more common and might fix your issue since it also check for undefined.


问:
Hibernate cascade remove ConstraintViolationException
It seems the situation is simply (but it does not work).
Db part (EVENT_ID is foreign key. FK_RR_E_CI constraint references on EVENT table)

```<code> |-------|            |----------------|
 | EVENT | 1 ------ ∞ | RECURRENT_RULE |
 |-------|            |----------------|
 | ID    |            | ID             |
 |-------|            | EVENT_ID       |
                      |----------------|
</code>```

Java part:

```<code>@Entity
public class Event {
  @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "event")
  private Set<RecurrentRule> recurrentRules = new HashSet<>();
}

@Entity
public class RecurrentRule {
  @ManyToOne
  @JoinColumn(columnDefinition = "event_id")
  private Event event;
}
</code>```

If I try to delete event object It will return:

```<code>could not execute statement; SQL [n/a]; constraint [MY_SCHEMA.FK_RR_E_CI];
nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
...
java.sql.SQLIntegrityConstraintViolationException: ORA-02292: integrity constraint (MY_SCHEMA.FK_RR_E_CI) violated - child record found
</code>```

SAVE and UPDATE operations work correctly.

What should I change in my mapping to be able use cascade removal?
I know that I should use @OnDelete(action=OnDeleteAction.CASCADE) but I can't understand how to use it...

答:
Instead of using cascade = CascadeType.ALL attribute in the @OneToMany annotation, use Hibernate's @Cascade() annotation like this:

```<code>@OneToMany(orphanRemoval = true, mappedBy = "event")
@Cascade({CascadeType.ALL})
private Set<RecurrentRule> recurrentRules = new HashSet<>();
</code>```

Because cascade = CascadeType.ALL is a JPA option, so when Hibernate session tries to delete the object, it will search for a Hibernate Cascade, it won't find it, that's why you should use @Cascade.

For further reading take a look at Cascade – JPA & Hibernate annotation common mistake, it gives a better explanation.

Body:
It seems the situation is simply (but it does not work).
Db part (EVENT_ID is foreign key. FK_RR_E_CI constraint references on EVENT table)

 |-------|            |----------------|
 | EVENT | 1 ------ ∞ | RECURRENT_RULE |
 |-------|            |----------------|
 | ID    |            | ID             |
 |-------|            | EVENT_ID       |
                      |----------------|

Java part:

@Entity
public class Event {
  @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "event")
  private Set<RecurrentRule> recurrentRules = new HashSet<>();
}

@Entity
public class RecurrentRule {
  @ManyToOne
  @JoinColumn(columnDefinition = "event_id")
  private Event event;
}

If I try to delete event object It will return:

could not execute statement; SQL [n/a]; constraint [MY_SCHEMA.FK_RR_E_CI];
nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
...
java.sql.SQLIntegrityConstraintViolationException: ORA-02292: integrity constraint (MY_SCHEMA.FK_RR_E_CI) violated - child record found

SAVE and UPDATE operations work correctly.

What should I change in my mapping to be able use cascade removal?
I know that I should use @OnDelete(action=OnDeleteAction.CASCADE) but I can't understand how to use it...

Body:
Instead of using cascade = CascadeType.ALL attribute in the @OneToMany annotation, use Hibernate's @Cascade() annotation like this:

@OneToMany(orphanRemoval = true, mappedBy = "event")
@Cascade({CascadeType.ALL})
private Set<RecurrentRule> recurrentRules = new HashSet<>();

Because cascade = CascadeType.ALL is a JPA option, so when Hibernate session tries to delete the object, it will search for a Hibernate Cascade, it won't find it, that's why you should use @Cascade.

For further reading take a look at Cascade – JPA & Hibernate annotation common mistake, it gives a better explanation.


问:
Can't get url request to show, 404
I'm completely new to backend, working through the djangobook tutorial. If I'm missing any vital information, let me know. The first task is to get 'Hello World' to show up on your development server, and it keeps returning 404. The two files in question being the views.py (my hello world file) and urls.py

this is the views.py:

```<code>from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello world")
</code>```

this is the urls.py:

```<code>from django.conf.urls import url
from django.contrib import admin

from mysite.views import hello

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/$', hello),
]
</code>```

I feel like its not finding the views file correctly? This is how there set up, exactly as he said to do it in the tutorial

答: It was at http://127.0.0.1:8000/hello/, also used HunkDivine's answer as another option</p>

Title: Can't get url request to show, 404

Body:
I'm completely new to backend, working through the djangobook tutorial. If I'm missing any vital information, let me know. The first task is to get 'Hello World' to show up on your development server, and it keeps returning 404. The two files in question being the views.py (my hello world file) and urls.py

this is the views.py:

from django.http import HttpResponse

def hello(request):
    return HttpResponse("Hello world")

this is the urls.py:

from django.conf.urls import url
from django.contrib import admin

from mysite.views import hello

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^hello/$', hello),
]

I feel like its not finding the views file correctly? This is how there set up, exactly as he said to do it in the tutorial


问:
Repeating image count for both directories
I'm using the glob function in PHP to browse directories and trying to also match up only the image files. This is working but when I try to count the images in each directory, it repeats the count of the first directory for the others. For example, directory 1 has 6 images and directory 2 has 4 images but when I try to display the count for each directory, it shows 6 images for directory 2 and so forth.

Here is the code I have in place:

```<code>public function viewphotoalbumsAction()
{
    $identity = $this->identity();
    $dirname = array();
    $files = array();

    foreach (glob(getcwd() . '/public/images/profile/' . $identity . '/albums/*', GLOB_ONLYDIR) as $dir) {
        $dirname[] = basename($dir);

        foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
            $files[] = $images;
        }
    }
    //var_dump($files); exit;

    $data = array(
        'albums' => array_values($dirname),
        'files'  => $files,
    );

    return new ViewModel(array('album' => $data['albums'], 'files' => $data['files']));
}
</code>```

The results of var_dump()

```<code> array(9) { [0]=> string(96) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/massive snow.jpg"
[1]=> string(91) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/mom-jon.jpg"
[2]=> string(90) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/sunset.jpg"
[3]=> string(85) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/cref.jpg"
[4]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/diploma.jpg"
[5]=> string(86) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/eeyor.jpg"
[6]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother-jaws.jpg"
[7]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother.jpg"
[8]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/goat_singing.jpg" }
</code>```

It is getting all the images from each directory as expected but what I really need to do is separate the images so I can have a accurate count for each directory and not just have it show the whole count (9)

The view code:

```<code><div class="w3-col m7">
    <div class="w3-row-padding">
        <div class="w3-col m12">
            <div class="w3-card-2 w3-round w3-white">
                <div class="w3-container w3-padding" id="view-photo-albums">
                    <p class="w3-center">Current Albums</p>
                    <br>
                    <?php
foreach ($this->album as $albums):
    ?>
                    <p>
                        <?php echo $albums; ?> - Number of images: <?php echo $this->files; ?>
                    </p>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

Any help would be appreciated.

Update:

I cannot use array_values for $data['files'] as I did for $data['albums'] as it is giving a warning of array to string conversion.

答:
May be you need to end the first foreach statement after the end of the second one not before it so each $dir has its own $images </p>

```<code> public function viewphotoalbumsAction()
    {
        $identity = $this->identity();

        foreach (glob(getcwd() . '/public/images/profile/' . $identity . '/albums/*', GLOB_ONLYDIR) as $dir) {
            $dirname[] = basename($dir);

        foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
             $files[] = $images;
        }
    }

        $data = array(
            'albums' => array_values($dirname),
            'files'  => $files,
        );

        return new ViewModel(array('album' => $data['albums'], 'files' => count($data['files'])));
    }
</code>```

Body:
I'm using the glob function in PHP to browse directories and trying to also match up only the image files. This is working but when I try to count the images in each directory, it repeats the count of the first directory for the others. For example, directory 1 has 6 images and directory 2 has 4 images but when I try to display the count for each directory, it shows 6 images for directory 2 and so forth.

Here is the code I have in place:

public function viewphotoalbumsAction()
{
    $identity = $this->identity();
    $dirname = array();
    $files = array();

    foreach (glob(getcwd() . '/public/images/profile/' . $identity . '/albums/*', GLOB_ONLYDIR) as $dir) {
        $dirname[] = basename($dir);

        foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
            $files[] = $images;
        }
    }
    //var_dump($files); exit;

    $data = array(
        'albums' => array_values($dirname),
        'files'  => $files,
    );

    return new ViewModel(array('album' => $data['albums'], 'files' => $data['files']));
}

The results of var_dump()

 array(9) { [0]=> string(96) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/massive snow.jpg"
[1]=> string(91) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/mom-jon.jpg"
[2]=> string(90) "C:\xampp\htdocs/public/images/profile/fooboy/albums/bone mom's album_2017-07-03/sunset.jpg"
[3]=> string(85) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/cref.jpg"
[4]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/diploma.jpg"
[5]=> string(86) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/eeyor.jpg"
[6]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother-jaws.jpg"
[7]=> string(88) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/frother.jpg"
[8]=> string(93) "C:\xampp\htdocs/public/images/profile/fooboy/albums/random photos_2017-07-02/goat_singing.jpg" }

It is getting all the images from each directory as expected but what I really need to do is separate the images so I can have a accurate count for each directory and not just have it show the whole count (9)

The view code:

Current Albums

                    <?php
foreach ($this->album as $albums):
    ?>

                        <?php echo $albums; ?> - Number of images: <?php echo $this->files; ?>

                    <?php endforeach; ?>

Any help would be appreciated.

Update:

I cannot use array_values for $data['files'] as I did for $data['albums'] as it is giving a warning of array to string conversion.

Body:
May be you need to end the first foreach statement after the end of the second one not before it so each $dir has its own $images

 public function viewphotoalbumsAction()
    {
        $identity = $this->identity();

        foreach (glob(getcwd() . '/public/images/profile/' . $identity . '/albums/*', GLOB_ONLYDIR) as $dir) {
            $dirname[] = basename($dir);

        foreach (glob($dir . '/*.{jpg,png,gif}', GLOB_BRACE) as $images) {
             $files[] = $images;
        }
    }

        $data = array(
            'albums' => array_values($dirname),
            'files'  => $files,
        );

        return new ViewModel(array('album' => $data['albums'], 'files' => count($data['files'])));
    }


问:
Shortening Really long Client ids
I'mm getting really long client ids one such example is below. Some of them are about 100 characters long which is ridiculous.
Is there anything or any tool i can use that will shorten the pages ids?

id="ctl00_ctl00_MainContent_MemberMain_Abc_asdsad...._DlSAdasdasdasd_ctl00_PnsadasdasdnsHF"

EDIT:
I am nesting a lot which is the cause of the problem.
I am using  .net 3.5. and collisions are not ok as some of the ids are being used by javascript funcitons

答:
What version of VS.NET/.NET are you using?  The new ClientIDMode in ASP.NET 4 allows you to control how the client IDs are generated:

http://www.dotnetcurry.com/ShowArticle.aspx?ID=492

Title: Shortening Really long Client ids


问:
Reshaping from wide to long data while collapsing variable values for same IDs in R
I am relatively new to R. I have a dataframe df that looks like this, where PMID is an ID:

```<code>PMID          Variable         Value
1             MH               Humans
1             MH               Male
1             MH               Middle Aged
1             RN               Aldosterone
1             RN               Renin
2             MH               Accidents, Traffic
2             MH               Male
2             RN               Antivenins
3             MH               Humans
3             MH               Crotulus
3             MH               Young Adult
</code>```

and so on. As you can see, some IDs have multiple MHs and/or RNs and some have none or one. I want to collapse all entries for each variable for each PMID. I also want to be able to separate each entry with a comma once collapsed, but first substitute the spaces present in the above dataframe into _ so that I can retain each value so that my final dataframe looks like this:

```<code>PMID         MH                                 RN
1            Humans, Male, Middle_Aged          Aldosterone, Renin
2            Accidents,_Traffic, Male           Antivenins
3            Humans, Crotulus, Young_Adult
</code>```

I have over 5 million rows, so please help in making the code computationally efficient. Thanks for your help.

答:
Here's one solution, using dplyr and tidyr:

```<code>library(dplyr)
library(tidyr)

d <- read.table(
text='PMID;Variable;Value
1;MH;Humans
1;MH;Male
1;MH;Middle Aged
1;RN;Aldosterone
1;RN;Renin
2;MH;Accidents, Traffic
2;MH;Male
2;RN;Antivenins
3;MH;Humans
3;MH;Crotulus
3;MH;Young Adult',
header=TRUE, sep=';', stringsAsFactors=FALSE)

d %>%
  group_by(PMID, Variable) %>%
  summarise(Value=paste(gsub(' ', '_', Value), collapse=', ')) %>%
  spread(Variable, Value)

## Source: local data frame [3 x 3]
## Groups: PMID [3]
##
## # A tibble: 3 x 3
##    PMID                            MH                  RN
## * <int>                         <chr>               <chr>
## 1     1     Humans, Male, Middle_Aged  Aldosterone, Renin
## 2     2      Accidents,_Traffic, Male          Antivenins
## 3     3 Humans, Crotulus, Young_Adult                <NA>
</code>```

Body:
I am relatively new to R. I have a dataframe df that looks like this, where PMID is an ID:

PMID          Variable         Value
1             MH               Humans
1             MH               Male
1             MH               Middle Aged
1             RN               Aldosterone
1             RN               Renin
2             MH               Accidents, Traffic
2             MH               Male
2             RN               Antivenins
3             MH               Humans
3             MH               Crotulus
3             MH               Young Adult

and so on. As you can see, some IDs have multiple MHs and/or RNs and some have none or one. I want to collapse all entries for each variable for each PMID. I also want to be able to separate each entry with a comma once collapsed, but first substitute the spaces present in the above dataframe into _ so that I can retain each value so that my final dataframe looks like this:

PMID         MH                                 RN
1            Humans, Male, Middle_Aged          Aldosterone, Renin
2            Accidents,_Traffic, Male           Antivenins
3            Humans, Crotulus, Young_Adult

I have over 5 million rows, so please help in making the code computationally efficient. Thanks for your help.

Body:
Here's one solution, using dplyr and tidyr:

library(dplyr)
library(tidyr)

d <- read.table(
text='PMID;Variable;Value
1;MH;Humans
1;MH;Male
1;MH;Middle Aged
1;RN;Aldosterone
1;RN;Renin
2;MH;Accidents, Traffic
2;MH;Male
2;RN;Antivenins
3;MH;Humans
3;MH;Crotulus
3;MH;Young Adult',
header=TRUE, sep=';', stringsAsFactors=FALSE)

d %>%
  group_by(PMID, Variable) %>%
  summarise(Value=paste(gsub(' ', '_', Value), collapse=', ')) %>%
  spread(Variable, Value)

## Source: local data frame [3 x 3]
## Groups: PMID [3]
##
## # A tibble: 3 x 3
##    PMID                            MH                  RN
## * <int>                         <chr>               <chr>
## 1     1     Humans, Male, Middle_Aged  Aldosterone, Renin
## 2     2      Accidents,_Traffic, Male          Antivenins
## 3     3 Humans, Crotulus, Young_Adult                <NA>


问:
Match a running ipython notebook to a process
My server runs many long running notebooks, and I'd like to monitor the notebooks memory.

Is there a way to match between the pid or process name and a notebook?

答:
Since the question is about monitoring notebooks' memory, I've written a complete example showing the memory consumption of the running notebooks. It is based on the excellent @jcb91 answer and a few other answers (1, 2, 3, 4).

import json
import os
import os.path
import posixpath
import subprocess
import urllib2

import pandas as pd
import psutil

def show_notebooks_table(host, port):
    """Show table with info about running jupyter notebooks.

    Args:
        host: host of the jupyter server.
        port: port of the jupyter server.

    Returns:
        DataFrame with rows corresponding to running notebooks and following columns:
            * index: notebook kernel id.
            * path: path to notebook file.
            * pid: pid of the notebook process.
            * memory: notebook memory consumption in percentage.
    """
    notebooks = get_running_notebooks(host, port)
    prefix = long_substr([notebook['path'] for notebook in notebooks])
    df = pd.DataFrame(notebooks)
    df = df.set_index('kernel_id')
    df.index.name = prefix
    df.path = df.path.apply(lambda x: x[len(prefix):])
    df['pid'] = df.apply(lambda row: get_process_id(row.name), axis=1)
    # same notebook can be run in multiple processes
    df = expand_column(df, 'pid')
    df['memory'] = df.pid.apply(memory_usage_psutil)
    return df.sort_values('memory', ascending=False)

def get_running_notebooks(host, port):
    """Get kernel ids and paths of the running notebooks.

    Args:
        host: host at which the notebook server is listening. E.g. 'localhost'.
        port: port at which the notebook server is listening. E.g. 8888.
        username: name of the user who runs the notebooks.

    Returns:
        list of dicts {kernel_id: notebook kernel id, path: path to notebook file}.
    """
    # find which kernel corresponds to which notebook
    # by querying the notebook server api for sessions
    sessions_url = posixpath.join('http://%s:%d' % (host, port), 'api', 'sessions')
    response = urllib2.urlopen(sessions_url).read()
    res = json.loads(response)
    notebooks = [{'kernel_id': notebook['kernel']['id'],
                  'path': notebook['notebook']['path']} for notebook in res]
    return notebooks

def get_process_id(name):
    """Return process ids found by (partial) name or regex.

    Source: https://stackoverflow.com/a/44712205/304209.
    >>> get_process_id('kthreadd')
    [2]
    >>> get_process_id('watchdog')
    [10, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61]  # ymmv
    >>> get_process_id('non-existent process')
    []
    """
    child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
    response = child.communicate()[0]
    return [int(pid) for pid in response.split()]

def memory_usage_psutil(pid=None):
    """Get memory usage percentage by current process or by process specified by id, like in top.

    Source: https://stackoverflow.com/a/30014612/304209.

    Args:
        pid: pid of the process to analyze. If None, analyze the current process.

    Returns:
        memory usage of the process, in percentage like in top, values in [0, 100].
    """
    if pid is None:
        pid = os.getpid()
    process = psutil.Process(pid)
    return process.memory_percent()

def long_substr(strings):
    """Find longest common substring in a list of strings.

    Source: https://stackoverflow.com/a/2894073/304209.

    Args:
        strings: list of strings.

    Returns:
        longest substring which is found in all of the strings.
    """
    substr = ''
    if len(strings) > 1 and len(strings[0]) > 0:
        for i in range(len(strings[0])):
            for j in range(len(strings[0])-i+1):
                if j > len(substr) and all(strings[0][i:i+j] in x for x in strings):
                    substr = strings[0][i:i+j]
    return substr

def expand_column(dataframe, column):
    """Transform iterable column values into multiple rows.

    Source: https://stackoverflow.com/a/27266225/304209.

    Args:
        dataframe: DataFrame to process.
        column: name of the column to expand.

    Returns:
        copy of the DataFrame with the following updates:
            * for rows where column contains only 1 value, keep them as is.
            * for rows where column contains a list of values, transform them
                into multiple rows, each of which contains one value from the list in column.
    """
    tmp_df = dataframe.apply(
        lambda row: pd.Series(row[column]), axis=1).stack().reset_index(level=1, drop=True)
    tmp_df.name = column
    return dataframe.drop(column, axis=1).join(tmp_df)
```

Here is an example output of show_notebooks_table('localhost', 8888):

Body:
Since the question is about monitoring notebooks' memory, I've written a complete example showing the memory consumption of the running notebooks. It is based on the excellent @jcb91 answer and a few other answers (1, 2, 3, 4).

import json
import os
import os.path
import posixpath
import subprocess
import urllib2

import pandas as pd
import psutil

def show_notebooks_table(host, port):
    """Show table with info about running jupyter notebooks.

    Args:
        host: host of the jupyter server.
        port: port of the jupyter server.

    Returns:
        DataFrame with rows corresponding to running notebooks and following columns:
            * index: notebook kernel id.
            * path: path to notebook file.
            * pid: pid of the notebook process.
            * memory: notebook memory consumption in percentage.
    """
    notebooks = get_running_notebooks(host, port)
    prefix = long_substr([notebook['path'] for notebook in notebooks])
    df = pd.DataFrame(notebooks)
    df = df.set_index('kernel_id')
    df.index.name = prefix
    df.path = df.path.apply(lambda x: x[len(prefix):])
    df['pid'] = df.apply(lambda row: get_process_id(row.name), axis=1)
    # same notebook can be run in multiple processes
    df = expand_column(df, 'pid')
    df['memory'] = df.pid.apply(memory_usage_psutil)
    return df.sort_values('memory', ascending=False)

def get_running_notebooks(host, port):
    """Get kernel ids and paths of the running notebooks.

    Args:
        host: host at which the notebook server is listening. E.g. 'localhost'.
        port: port at which the notebook server is listening. E.g. 8888.
        username: name of the user who runs the notebooks.

    Returns:
        list of dicts {kernel_id: notebook kernel id, path: path to notebook file}.
    """
    # find which kernel corresponds to which notebook
    # by querying the notebook server api for sessions
    sessions_url = posixpath.join('http://%s:%d' % (host, port), 'api', 'sessions')
    response = urllib2.urlopen(sessions_url).read()
    res = json.loads(response)
    notebooks = [{'kernel_id': notebook['kernel']['id'],
                  'path': notebook['notebook']['path']} for notebook in res]
    return notebooks

def get_process_id(name):
    """Return process ids found by (partial) name or regex.

    Source: https://stackoverflow.com/a/44712205/304209.
    >>> get_process_id('kthreadd')
    [2]
    >>> get_process_id('watchdog')
    [10, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61]  # ymmv
    >>> get_process_id('non-existent process')
    []
    """
    child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
    response = child.communicate()[0]
    return [int(pid) for pid in response.split()]

def memory_usage_psutil(pid=None):
    """Get memory usage percentage by current process or by process specified by id, like in top.

    Source: https://stackoverflow.com/a/30014612/304209.

    Args:
        pid: pid of the process to analyze. If None, analyze the current process.

    Returns:
        memory usage of the process, in percentage like in top, values in [0, 100].
    """
    if pid is None:
        pid = os.getpid()
    process = psutil.Process(pid)
    return process.memory_percent()

def long_substr(strings):
    """Find longest common substring in a list of strings.

    Source: https://stackoverflow.com/a/2894073/304209.

    Args:
        strings: list of strings.

    Returns:
        longest substring which is found in all of the strings.
    """
    substr = ''
    if len(strings) > 1 and len(strings[0]) > 0:
        for i in range(len(strings[0])):
            for j in range(len(strings[0])-i+1):
                if j > len(substr) and all(strings[0][i:i+j] in x for x in strings):
                    substr = strings[0][i:i+j]
    return substr

def expand_column(dataframe, column):
    """Transform iterable column values into multiple rows.

    Source: https://stackoverflow.com/a/27266225/304209.

    Args:
        dataframe: DataFrame to process.
        column: name of the column to expand.

    Returns:
        copy of the DataFrame with the following updates:
            * for rows where column contains only 1 value, keep them as is.
            * for rows where column contains a list of values, transform them
                into multiple rows, each of which contains one value from the list in column.
    """
    tmp_df = dataframe.apply(
        lambda row: pd.Series(row[column]), axis=1).stack().reset_index(level=1, drop=True)
    tmp_df.name = column
    return dataframe.drop(column, axis=1).join(tmp_df)

Here is an example output of show_notebooks_table('localhost', 8888):

ContentLicense: CC BY-SA 4.0


问:
Do browsers cache error responses?
I am setting response headers for some requests as :

```<code>Cache-Control : "Private, max-age=21600";
</code>```

If the same request fails, I retry for the same request. My doubt is whether browser caches such error responses, or not?

I tried simulating this scenario using fiddler. I returned 404-not found for a request and checked chrome://cache, the cache contained this response with 404. When I removed the request from fiddler then I got 200 OK.

But still, I am not getting why browser had that 404 response in its cache?

Thanks.

答: Late answer but yes Chrome caches 404 responses. You can add no-cache headers to prevent this; I think the HTML documentation even mentions it as well. There's some Apache/Nginx fix on this forum. </p>

Title: Do browsers cache error responses?

Body:
I am setting response headers for some requests as :

Cache-Control : "Private, max-age=21600";

If the same request fails, I retry for the same request. My doubt is whether browser caches such error responses, or not?

I tried simulating this scenario using fiddler. I returned 404-not found for a request and checked chrome://cache, the cache contained this response with 404. When I removed the request from fiddler then I got 200 OK.

But still, I am not getting why browser had that 404 response in its cache?

Thanks.