text:
Q: parsing json and save with core data swift 2.0 best practise I want to download, parse and save data from a json file using core data. Generally my code works but when the content of the json isn't as expected I run in to problems. Maybe someone can give some advice for a better approach. Here is my code:
//MARK: - REST calls
// This makes the GET call to ATI. It simply gets the some test data
and displays it on the screen.

func getATITodayHoursDataEntertain() {

print("getATITodayHoursDataEntertain")

// set up the base64-encoded credentials
let config = NSURLSessionConfiguration.defaultSessionConfiguration()
config.HTTPAdditionalHeaders = ["Authorization" : authString]

let session = NSURLSession(configuration: config)

let url = NSURL(string: "https://apirest.atinternet-solutions.com/data/v2/json/getData?code=1KVVaC&max-results=30&page-num=1")

session.dataTaskWithURL(url!, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
    guard let realResponse = response as? NSHTTPURLResponse where
        realResponse.statusCode == 200 else {
            print("Not a 200 response - getATITodayHoursDataEntertain")
            print(response)
            return
    }

    do {
        if let jsonString = NSString(data:data!, encoding: NSUTF8StringEncoding) {

            let _ = jsonString

            let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
            let jsonContext = ((jsonDictionary["DataFeed"] as! NSArray) [0] as! NSDictionary) ["Context"] as! NSDictionary
            let period = (((jsonContext) ["Periods"] as! NSArray) [0] as! NSDictionary) ["Value"] as! String

            let jsonContent = ((

                ["DataFeed"] as! NSArray) [0] as! NSDictionary) ["Rows"] as! NSArray

            let currentDayTime = jsonContent.count

            var hour0 = 0
            var hour1 = 0
            var hour2 = 0
            var hour3 = 0
            var hour4 = 0
            var hour5 = 0
            var hour6 = 0
            var hour7 = 0
            var hour8 = 0
            var hour9 = 0
            var hour10 = 0
            var hour11 = 0
            var hour12 = 0
            var hour13 = 0
            var hour14 = 0
            var hour15 = 0
            var hour16 = 0
            var hour17 = 0
            var hour18 = 0
            var hour19 = 0
            var hour20 = 0
            var hour21 = 0
            var hour22 = 0
            var hour23 = 0

            if (currentDayTime >= 1) {
                hour0 = (jsonContent[0] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 2) {
                hour1 = (jsonContent[1] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 3) {
                hour2 = (jsonContent[2] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 4) {
                hour3 = (jsonContent[3] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 5) {
                hour4 = (jsonContent[4] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 6) {
                hour5 = (jsonContent[5] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 7) {
                hour6 = (jsonContent[6] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 8) {
                hour7 = (jsonContent[7] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 9) {
                hour8 = (jsonContent[8] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 10) {
                hour9 = (jsonContent[9] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 11) {
                hour10 = (jsonContent[10] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 12) {
                hour11 = (jsonContent[11] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 13) {
                hour12 = (jsonContent[12] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 14) {
                hour13 = (jsonContent[13] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 15) {
                hour14 = (jsonContent[14] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 16) {
                hour15 = (jsonContent[15] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 17) {
                hour16 = (jsonContent[16] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 18) {
                hour17 = (jsonContent[17] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 19) {
                hour18 = (jsonContent[18] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 20) {
                hour19 = (jsonContent[19] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 21) {
                hour20 = (jsonContent[20] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 22) {
                hour21 = (jsonContent[21] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 23) {
                hour22 = (jsonContent[22] as! NSDictionary) ["m_page_loads"] as! Int
            }
            if (currentDayTime >= 24) {
                hour23 = (jsonContent[23] as! NSDictionary) ["m_page_loads"] as! Int
            }

            let jsonTotals = ((jsonDictionary["DataFeed"] as! NSArray) [0] as! NSDictionary) ["Totals"] as! NSArray
            let all = jsonTotals[0] ["m_page_loads"] as! Int

            let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
            let managedContext = appDelegate.managedObjectContext

            let entity =  NSEntityDescription.entityForName("TodayHoursDataEntertain", inManagedObjectContext:managedContext)
            let todayHour = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)

            todayHour.setValue(period, forKey: "period")
            todayHour.setValue(hour0, forKey: "hour0")
            todayHour.setValue(hour1, forKey: "hour1")
            todayHour.setValue(hour2, forKey: "hour2")
            todayHour.setValue(hour3, forKey: "hour3")
            todayHour.setValue(hour4, forKey: "hour4")
            todayHour.setValue(hour5, forKey: "hour5")
            todayHour.setValue(hour6, forKey: "hour6")
            todayHour.setValue(hour7, forKey: "hour7")
            todayHour.setValue(hour8, forKey: "hour8")
            todayHour.setValue(hour9, forKey: "hour9")
            todayHour.setValue(hour10, forKey: "hour10")
            todayHour.setValue(hour11, forKey: "hour11")
            todayHour.setValue(hour12, forKey: "hour12")
            todayHour.setValue(hour13, forKey: "hour13")
            todayHour.setValue(hour14, forKey: "hour14")
            todayHour.setValue(hour15, forKey: "hour15")
            todayHour.setValue(hour16, forKey: "hour16")
            todayHour.setValue(hour17, forKey: "hour17")
            todayHour.setValue(hour18, forKey: "hour18")
            todayHour.setValue(hour19, forKey: "hour19")
            todayHour.setValue(hour20, forKey: "hour20")
            todayHour.setValue(hour21, forKey: "hour21")
            todayHour.setValue(hour22, forKey: "hour22")
            todayHour.setValue(hour23, forKey: "hour23")
            todayHour.setValue(all, forKey: "all")

            do {
                try managedContext.save()
                TodayHoursData.append(todayHour)

                print("getATITodayHoursDataEntertain data saved")

            } catch let error as NSError  {
                print("getATITodayHoursDataEntertain - Could not save \(error), \(error.userInfo)")
            }

        }
    } catch {
        print("bad things happened - getATITodayHoursDataEntertain")
    }
}).resume()
}

Here is an example of the json:
{
DataFeed: [
{
Context: {
Spaces: [
{
Sites: [
{
Id: "560038",
Label: "Entertain VoD TopLists",
Currency: "USD",
TimeZone: "(UTC+01:00) W. Europe Standard Time",
Start: "2015-04-27",
L2s: null
}
]
}
],
Periods: [
{
Value: "2016-05-01T00:00:00,2016-05-01T20:46:59"
}
],
Ranges: [
{
Id: "page-num",
Value: "1"
},
{
Id: "max-results",
Value: "30"
},
{
Id: "url-next",
Value: "https://apirest.atinternet-solutions.com/v2/getdata?page-num=2&filter=%7bd_page_chap1%3a%7b%24eq%3a%27Buy%27%7d%7d&sort=%7bd_time_hour_event%7d&columns=%7bd_time_hour_event%2cm_page_loads%7d&include=%7btotal%3aall%2ccontext%7d&period=%7bR%3a%7bD%3a%270%27%7d%7d&space=%7bs%3a560038%7d&max-results=30"
}
],
Profile: {
Language: "EN",
FirstDayWeek: "Mo"
}
},
Columns: [
{
Name: "d_time_hour_event",
Label: "Hour (event)",
Category: "Dimension",
Type: "Integer",
CustomerType: "Hour"
},
{
Name: "m_page_loads",
Label: "Loads",
Category: "Metric",
Type: "Integer",
CustomerType: "Integer",
Summable: true,
Pie: true
}
],
Rows: [
{
d_time_hour_event: 0,
m_page_loads: 534
},
{
d_time_hour_event: 1,
m_page_loads: 315
},
{
d_time_hour_event: 2,
m_page_loads: 148
},
{
d_time_hour_event: 3,
m_page_loads: 91
},
{
d_time_hour_event: 4,
m_page_loads: 74
},
{
d_time_hour_event: 5,
m_page_loads: 74
},
{
d_time_hour_event: 6,
m_page_loads: 87
},
{
d_time_hour_event: 7,
m_page_loads: 156
},
{
d_time_hour_event: 8,
m_page_loads: 218
},
{
d_time_hour_event: 9,
m_page_loads: 344
},
{
d_time_hour_event: 10,
m_page_loads: 438
},
{
d_time_hour_event: 11,
m_page_loads: 435
},
{
d_time_hour_event: 12,
m_page_loads: 541
},
{
d_time_hour_event: 13,
m_page_loads: 739
},
{
d_time_hour_event: 14,
m_page_loads: 758
},
{
d_time_hour_event: 15,
m_page_loads: 883
},
{
d_time_hour_event: 16,
m_page_loads: 888
},
{
d_time_hour_event: 17,
m_page_loads: 821
},
{
d_time_hour_event: 18,
m_page_loads: 950
},
{
d_time_hour_event: 19,
m_page_loads: 1218
},
{
d_time_hour_event: 20,
m_page_loads: 2000
}
],
Totals: [
{
type: "all",
m_page_loads: 11712
}
]
}
]
}

My problem is that very rarely it can happen that there is no result for one or more hours of the day. In this cases my basic approach of counting the numbers of items in the json fails. Can anyone give me a suggestion for a better approach to avoid this problem?
I'm currently using Xcode 7.2 and wrote my code in swift2.
Please don't be to harsh. As you can guess I am not really a developer and also completely new to swift.
br
nikolay

A: Instead of writing your hour comparisons like this:
if (currentDayTime >= 1) {
  hour0 = (jsonContent[0] as! NSDictionary) ["m_page_loads"] as! Int
}

A safer way to write them would be something like this:
if currentDayTime >= 1, let pageLoads = (jsonContent[0] as? NSDictionary)?["m_page_loads"] as? Int {
    hour0 = pageLoads
}

This is saying "If the time of day is >= 1, and we're able to get a page load for this day, then set that value to pageLoads, and then set hour0 to pageloads"
The reason this is safer is because you have two as! operators, which are forcing a conversion to NSDictionary and Int, respectively. If jsonContent[n] isn't present, or if it's present but doesn't contain an Int for m_page_loads, then this will throw an error. My safer method uses as? for both conversions, meaning the following line:
(jsonContent[0] as? NSDictionary)?["m_page_loads"] as? Int

Will return nil if the conversions can't be performed.

Also, instead of writing each hour out individually, another solution would be to loop through all of the hours in the JSON and append them to an array representing the page loads her hour:
var pageLoadsPerHour = [Int]()
for hour in jsonContent {
    if let pageLoads = (hour as? NSDictionary)?["m_page_loads"] as? Int {
        pageLoadsPerHour.append(pageLoads)
    }
}

Hope this helps.


text:
Q: Format date input in view Angular JS I have a dynamic form that recieve data from an array and iterate over it. In case of a date field i want to send in this format into the controller "dd/MM/yyyy" or "dd/MM/yyy hh:mm" tried to use the ng-bind but the controller recieves in other format wich is "Wed Dec 23 2015 00:00:00 GMT-0100 (Local Standard Time)", that should be the format to send via $http.post in a service.
Here is my field input
Only date:

                    {{fa.title}}

                        <input type="date" class="form-control"
                               ng-model="sendForm[fa.name]"
                               placeholder="dd/MM/yyyy"
                               ng-bind="sendForm[fa.name] | date:'dd/MM/yyyy'"/>

Date and hour:

                    {{fa.title}}

                        <input type="datetime-local" class="form-control"
                               ng-model="sendForm[fa.name]"
                               placeholder="dd/MM/yyyy hh:mm"
                               ng-bind="sendForm[fa.name] | date:'dd/MM/yyyy hh:mm'"/>

controller.js
app.controller("myAppCtrl", ["$scope", "SendForm", "FORMS", function ($scope, SendForm, FORMS) {
   $scope.sendForm = function (form) {
    SendForm.sendInfo(form,
        function onSuccess() {
            $scope.success = true;
        },
        function onError(message) {
            $scope.error = true;
        },
        function onFinally() {
            $scope.clearForm(form);
        })
}]);

service.js
app.factory("SendForm", ["$http", "CONFIG", "FORMS","$httpParamSerializer", function ($http, CONFIG, FORMS,$httpParamSerializer) {
return {
    sendInfo: function (form, onSuccess, onError, onFinally, message) {
        var data = {
            absolute: CONFIG.absolute
        };

        for (var i = 0, length = FORMS.form_variables.length; i < length; i++) {
            if (angular.isUndefined(form[FORMS.form_variables[i].name])) {
                var key = FORMS.form_variables[i].name;
                var value = "";
                data[key] = value;
            } else {
                var key = FORMS.form_variables[i].name;
                var value = form[FORMS.form_variables[i].name];
                data[key] = value;
            }
        }
        var config = {
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        };

        $http.post(CONFIG.urlSendForm, $httpParamSerializer(data), config).success(function () {
            onSuccess();
            onFinally();

 }
}]);

A: The "date" you are using is just a Angualr filter used in UI to return / display the date in correct format. It doesn't change the actual value (simply returns the formatted value).
If you want to get the date as 'dd/MM/yyyy hh:mm' in you controller, use it like below -
angular.module('myModule')
       .controller('myController', ['$filter',  '$scope', function($filter, $scope) {

       var formattedDate = $filter('date')($scope.sendForm[fa.name], 'dd/MM/yyyy hh:mm');

}]);

A: You need format the date in the controller AND in the service for send this formatted date to server?? which angular version that you used? If you recognize in the service when a value it's a date, you may inject the $filter service in your factory and use it for format the date.
In your Factory
app.factory("SendForm", ["$http", "$filter","CONFIG", "FORMS","$httpParamSerializer", function ($http, $filter,CONFIG, FORMS,$httpParamSerializer) {
return {
    sendInfo: function (form, onSuccess, onError, onFinally, message) {
        var data = {
            absolute: CONFIG.absolute
        };
         var dateHourRegex = /\d{2}\/\d{2}\/\d{4}\s+\d{2}\:\d{2}/,
             onlyDateRegex = /\d{2}\/\d{2}\/\d{4}/;

        for (var i = 0, length = FORMS.form_variables.length; i < length; i++) {
            if (angular.isUndefined(form[FORMS.form_variables[i].name])) {
                var key = FORMS.form_variables[i].name;
                var value = "";
                data[key] = value;
            } else {
                var key = FORMS.form_variables[i].name;
                var value = form[FORMS.form_variables[i].name];
                if(onlyDateRegex.test(value)){
                   value = dateHourRegex.test(value) ? $filter('date')(value, 'dd/MM/yyyy hh:mm')
                                                     : $filter('date')(value, 'dd/MM/yyyy');
                }
                data[key] = value;
            }
        }
        var config = {
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        };

        $http.post(CONFIG.urlSendForm, $httpParamSerializer(data), config).success(function () {
            onSuccess();
            onFinally();

 }
}]);

redpajama_set_name: RedPajamaStackExchange


text:
Q: vmware player not working properly for blackberry 10 dev alpha I am trying to use the blackberry 10 emulator on my Core i3 laptop, but the performance is horrendous.
I am using Windows 7 and the BB10 dev alpha simulator image. I am using the safe option when booting up BB, because without it there are weird visual artefacts.
The emulator is unusably slow and I have enabled 2 cores on the VMWare emulator as detailed here:
https://developer.blackberry.com/devzone/develop/simulator/simulator_improving_performance.html
What can I do to improve the simulator performance? It takes more than half an hour to boot the simulator and it is almost completely unusable.

A: I found the problem. All I had to do was to reboot, enter my BIOS by pressing delete, Go to CPU settings and enable Virtualisation. This made a huge difference. Can't believe I missed that in the documentation.

A: The simulator is notoriously resource hungry. Your problem is probably a combination of CPU, RAM and HDD. Lack of RAM is the main culprit. I find that anything less than 8GB and it runs like a dog.
Ideal setup is:

*

*8GB RAM

*Solid State Drive (I have a Samsung 830 and it is lightning fast)

*Sandy/Ivy Bridge Intel i7 CPU


text:
Q: Como mudar as cores de uma implementação Jquery? Observe o arquivo abaixo;
https://jsfiddle.net/9ub9yk7t/1/
Eu já tentei de várias maneira mudar as cores que pertence a tag H3 de azul para vermelho e não estou conseguindo, eu conseguir mudar as outras coisas, mas não conseguir mudar a cor de Azul para vermelho, alguém poderia por favor me dá uma ajuda?

A: Creio que seria isto.. utilize o container (div#accordion) para facilitar a seleção dos elementos que vc quer estilizar.
PS: Creio que seria mais simples se você utilizasse css para reestilizar os elementos.

var accordion = $('#accordion');

accordion.children('h3').css({
 'background': 'red',
  'border': '1px solid red'
});

accordion.children('div').css({
'background': '#fcf5eb',
'color': '#3f3f40',

});
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Accordion - Default functionality</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.structure.css">

Section 1

    Mauris mauris ante, blandit et, ultrices a, suscipit eget, quam. Integer
    ut neque. Vivamus nisi metus, molestie vel, gravida in, condimentum sit
    amet, nunc. Nam a nibh. Donec suscipit eros. Nam mi. Proin viverra leo ut
    odio. Curabitur malesuada. Vestibulum a velit eu ante scelerisque vulputate.

Section 2

    Sed non urna. Donec et ante. Phasellus eu ligula. Vestibulum sit amet
    purus. Vivamus hendrerit, dolor at aliquet laoreet, mauris turpis porttitor
    velit, faucibus interdum tellus libero ac justo. Vivamus non quam. In
    suscipit faucibus urna.

Section 3

    Nam enim risus, molestie et, porta ac, aliquam ac, risus. Quisque lobortis.
    Phasellus pellentesque purus in massa. Aenean in pede. Phasellus ac libero
    ac tellus pellentesque semper. Sed ac felis. Sed commodo, magna quis
    lacinia ornare, quam ante aliquam nisi, eu iaculis leo purus venenatis dui.

List item one

List item two

List item three

Section 4

    Cras dictum. Pellentesque habitant morbi tristique senectus et netus
    et malesuada fames ac turpis egestas. Vestibulum ante ipsum primis in
    faucibus orci luctus et ultrices posuere cubilia Curae; Aenean lacinia
    mauris vel est.

    Suspendisse eu nisl. Nullam ut libero. Integer dignissim consequat lectus.
    Class aptent taciti sociosqu ad litora torquent per conubia nostra, per
    inceptos himenaeos.


text:
Q: How to display alternative text on a combobox with customized style What I have done is the effect as left image shown, I have a combobox which contain two groups of data, what I want is when I select an item in the combobox, the displayed text will be looks like the right image shown (add some prefix before the selected item), e.g. I select the item '00' in Group A and then the displayed text will be 'A_00', how to achieve this effect base on my code?

In GroupComboBoxResDic.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:helper="clr-namespace:WpfApplication3">

    <!-- Main style for ComboBox -->
    <Style x:Key="MyComboBox" TargetType="{x:Type ComboBox}">

        <Setter Property="ItemsPanel">
            <Setter.Value>
                <ItemsPanelTemplate>
                    <WrapPanel IsItemsHost="True" Orientation="Horizontal" Width="150" Height="Auto" />
                </ItemsPanelTemplate>
            </Setter.Value>
        </Setter>

        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <TextBlock Text="{Binding Item, Converter={StaticResource terminalToDisplayNameConverter}, Mode=OneWay}" Width="40"/>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!-- Style for ComboBoxItem -->
    <Style TargetType="{x:Type ComboBoxItem}">
        <Setter Property="Width" Value="50" />
    </Style>

    <!-- Style for ItemContainerStyle -->
    <Style x:Key="ComboBoxItemContainerStyle" TargetType="{x:Type ComboBoxItem}">
        <Setter Property="IsEnabled" Value="{Binding Available}" />
    </Style>

    <!-- DataTemplate for HeaderTemplate -->
    <DataTemplate x:Key="MyHeaderTemplate">
        <Border BorderBrush="Black" BorderThickness="2">
            <TextBlock Text="{Binding Name}" HorizontalAlignment="Stretch" Background="YellowGreen" />
        </Border>
    </DataTemplate>

</ResourceDictionary>

the XAML file
<Window x:Class="WpfApplication3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" xmlns:my="clr-namespace:WpfApplication3">

    <Window.Resources>
        <ResourceDictionary Source="GroupComboBoxResDic.xaml" />
    </Window.Resources>

    <Grid>
        <ComboBox x:Name="MyComboBox1"
                  Style="{StaticResource MyComboBox}"
                  IsSynchronizedWithCurrentItem="False"
                  ItemContainerStyle="{StaticResource ComboBoxItemContainerStyle}"
                  ItemsSource="{Binding InputsList}" Margin="293,50,104,234">
            <ComboBox.GroupStyle>
                <GroupStyle HeaderTemplate="{StaticResource MyHeaderTemplate}" />
            </ComboBox.GroupStyle>
        </ComboBox>
    </Grid>
</Window>

The code-behind file
public enum CategoryGroup
    {
        GroupA = 0,

        GroupB,
    }

    public class CategoryItemString
    {
        public string Item { get; set; }
        public bool Available { get; set; }

        public CategoryGroup Group { get; set; }

        public string Category
        {
            get
            {
                switch (Group)
                {
                    case CategoryGroup.GroupA:
                        return "Group A";
                    case CategoryGroup.GroupB:
                        return "Group B";
                }

                return string.Empty;
            }
        }

        public override bool Equals(object obj)
        {
            if (obj == null) return false;
            CategoryItemString rht = obj as CategoryItemString;
            if (rht == null) return false;

            return rht.Item.Equals(this.Item) &&
                rht.Group == this.Group;
        }
    }

    public class VM : INotifyPropertyChanged
    {
        private ListCollectionView lcv;

        public VM()
        {

            List<CategoryItemString> items = new List<CategoryItemString>();

            for (int i = 0; i < 18; ++i)
            {
                items.Add(new CategoryItemString { Item = string.Format("{0:D2}", i), Available = (true), Group = CategoryGroup.GroupA });
            }

            for (int i = 0; i < 4; ++i)
            {
                items.Add(new CategoryItemString { Item = string.Format("{0:D2}", i), Available = (true), Group = CategoryGroup.GroupB });
            }

            //Need the list to be ordered by the category or you might get repeating categories
            lcv = new ListCollectionView(items.OrderBy(w => w.Category).ToList());

            //Create a group description
            lcv.GroupDescriptions.Add(new PropertyGroupDescription("Category"));
        }

        public ListCollectionView InputsList
        {
            get { return lcv; }
            set
            {
                if (lcv != value)
                {
                    lcv = value;
                    OnPropertyChanged("InputsList");
                }
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string prop)
        {
            if (this.PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
    }

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            VM vm = new VM();

            this.MyComboBox1.DataContext = vm;
        }
    }

A: What you need to do is to modify the template of the ComboBox.
First create a template for the SelectionBox (a ContentControl that displays the current selected item in ComboBox's template):
<DataTemplate x:Key="mySelectionBoxItemTemplate">
    <TextBlock Text="{Binding Path=DisplayValue}" />
</DataTemplate>

Then create a DisplayValue property in CategoryItemString:
public string DisplayValue
{
    get { return String.Format("{0}_{1}", Group, Item ); }
}

Edit a default template for a ComboBox and modify the ControlTemaplate for the SelectionBox, look for the comment in the code below to find the alteration made:
<ControlTemplate x:Key="ComboBoxControlTemplate1" TargetType="{x:Type ComboBox}">
    <Grid x:Name="MainGrid" SnapsToDevicePixels="True">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition MinWidth="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}" Width="0"/>
        </Grid.ColumnDefinitions>
        <Popup x:Name="PART_Popup" AllowsTransparency="True" Grid.ColumnSpan="2" IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}" Margin="1" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}" Placement="Bottom">
            <Themes:SystemDropShadowChrome x:Name="Shdw" Color="Transparent" MaxHeight="{TemplateBinding MaxDropDownHeight}" MinWidth="{Binding ActualWidth, ElementName=MainGrid}">
                <Border x:Name="DropDownBorder" BorderBrush="{DynamicResource {x:Static SystemColors.WindowFrameBrushKey}}" BorderThickness="1" Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}">
                    <ScrollViewer x:Name="DropDownScrollViewer">
                        <Grid RenderOptions.ClearTypeHint="Enabled">
                            <Canvas HorizontalAlignment="Left" Height="0" VerticalAlignment="Top" Width="0">
                                <Rectangle x:Name="OpaqueRect" Fill="{Binding Background, ElementName=DropDownBorder}" Height="{Binding ActualHeight, ElementName=DropDownBorder}" Width="{Binding ActualWidth, ElementName=DropDownBorder}"/>
                            </Canvas>
                            <ItemsPresenter x:Name="ItemsPresenter" KeyboardNavigation.DirectionalNavigation="Contained" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                        </Grid>
                    </ScrollViewer>
                </Border>
            </Themes:SystemDropShadowChrome>
        </Popup>
        <ToggleButton BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" Grid.ColumnSpan="2" IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}">
            <ToggleButton.Style>
                <Style TargetType="{x:Type ToggleButton}">
                    <Setter Property="OverridesDefaultStyle" Value="True"/>
                    <Setter Property="IsTabStop" Value="False"/>
                    <Setter Property="Focusable" Value="False"/>
                    <Setter Property="ClickMode" Value="Press"/>
                    <Setter Property="Background" Value="Transparent"/>
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type ToggleButton}">
                                <Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" SnapsToDevicePixels="True">
                                    <Grid HorizontalAlignment="Right" Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}">
                                        <Path x:Name="Arrow" Data="M0,0L3.5,4 7,0z" Fill="Black" HorizontalAlignment="Center" Margin="3,1,0,0" VerticalAlignment="Center"/>
                                    </Grid>
                                </Themes:ButtonChrome>
                                <ControlTemplate.Triggers>
                                    <Trigger Property="IsChecked" Value="True">
                                        <Setter Property="RenderPressed" TargetName="Chrome" Value="True"/>
                                    </Trigger>
                                    <Trigger Property="IsEnabled" Value="False">
                                        <Setter Property="Fill" TargetName="Arrow" Value="#FFAFAFAF"/>
                                    </Trigger>
                                </ControlTemplate.Triggers>
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ToggleButton.Style>
        </ToggleButton>
        <!-- Only the ContentTemplate below was changed to a static resurce-->
        <ContentPresenter ContentTemplate="{StaticResource mySelectionBoxItemTemplate}"
                          Content="{TemplateBinding SelectionBoxItem}"
                          ContentStringFormat="{TemplateBinding SelectionBoxItemStringFormat}"
                          HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                          IsHitTestVisible="False"
                          Margin="{TemplateBinding Padding}"
                          SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                          VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
    </Grid>
    <ControlTemplate.Triggers>
        <Trigger Property="HasDropShadow" SourceName="PART_Popup" Value="True">
            <Setter Property="Margin" TargetName="Shdw" Value="0,0,5,5"/>
            <Setter Property="Color" TargetName="Shdw" Value="#71000000"/>
        </Trigger>
        <Trigger Property="HasItems" Value="False">
            <Setter Property="Height" TargetName="DropDownBorder" Value="95"/>
        </Trigger>
        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
            <Setter Property="Background" Value="#FFF4F4F4"/>
        </Trigger>
        <MultiTrigger>
            <MultiTrigger.Conditions>
                <Condition Property="IsGrouping" Value="True"/>
                <Condition Property="VirtualizingPanel.IsVirtualizingWhenGrouping" Value="False"/>
            </MultiTrigger.Conditions>
            <Setter Property="ScrollViewer.CanContentScroll" Value="False"/>
        </MultiTrigger>
        <Trigger Property="CanContentScroll" SourceName="DropDownScrollViewer" Value="False">
            <Setter Property="Canvas.Top" TargetName="OpaqueRect" Value="{Binding VerticalOffset, ElementName=DropDownScrollViewer}"/>
            <Setter Property="Canvas.Left" TargetName="OpaqueRect" Value="{Binding HorizontalOffset, ElementName=DropDownScrollViewer}"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

Last thing - add the Template above in your MyComboBox Style:
        <Setter Property="Template" Value="{StaticResource ComboBoxControlTemplate1}" />


text:
Q: Writing results in a text file with perl I have a problem when the script print the whole line of text file in a result text file:
use strict;
use warnings;
use autodie;
my $out = "result2.txt";
open my $outFile, ">$out" or die $!;
my %permitted = do {
open my $fh, '<', 'f1.txt';
map { /(.+?)\s+\(/, 1 } <$fh>;
};

open my $fh, '<', 'f2.txt';
while (<$fh>) {
my ($phrase) = /(.+?)\s+->/;

if ($permitted{$phrase}) {
print $outFile $fh;
 }
close $outFile;

The problem is in this line
print $outFile $fh;

Any idea please?
Thank you

A: print $outFile $fh is printing the value of the file handle $fh to the file handle $outFile. Instead you want to print the entire current line, which is in $_.
There are a couple of other improvements that can be made

*

*You should always use the three-parameter form of open, so the open mode appears on its own as the second paremeter

*There is no need to test the success of an open of autodie is in place

*If you have a variable that contains the name of the output file, then you really should have ones for the names of the two input files as well
This is how your program should look. I hope it helps.
use strict;
use warnings;
use autodie;

my ($in1, $in2, $out) = qw/ f1.txt f2.txt result2.txt /;

my %permitted = do {
  open my $fh, '<', $in1;
  map { /(.+?)\s+\(/, 1 } <$fh>;
};

open my $fh,    '<', $in2;
open my $outfh, '>', $out;

while (<$fh>) {
  my ($phrase) = /(.+?)\s+->/;
  if ($permitted{$phrase}) {
    print $outfh $_;
  }
}

close $outfh;

A: I think you want print $outfile $phrase here, don't you?  The line you currently have is trying to print out a file handle reference ($fh) to a file ($outfile).
Also, just as part of perl best practices, you'll want to use the three argument open for your first open line:
 open my $outFile, ">", $out or die $!;

(FWIW, you're already using 3-arg open for your other two calls to open.)

A: Although Borodin has provided an excellent solution to your question, here's another option where you pass your 'in' files' names to the script on the command line, and let Perl handle the opening and closing of those files:
use strict;
use warnings;

my $file2 = pop;
my %permitted = map { /(.+?)\s+\(/, 1 } <>;

push @ARGV, $file2;

while (<>) {
    my ($phrase) = /(.+?)\s+->/;
    print if $permitted{$phrase};
}

Usage: perl script.pl inFile1 inFile2 [>outFile]
The last, optional parameter directs output to a file.
The pop command implicitly removes inFile2's name off of @ARGV, and stores it in $file2.  Then, inFile1 is read using the <> directive.  The file name of inFile2 is then pushed onto @ARGV, and that file is read and a line is printed if $permitted{$phrase} is true.
Running the script without the last, optional parameter will print results (if any) to the screen.  Using the last parameter saves output to a file.
Hope this helps!


text:
Q: Retrieve data from MongoDB using spring data findAll(Example example) I have a Java application that retrieves data from mongo DB using Spring data . I have a case where i wanted to retrive all Objects from mongo collection where isDeleted flag is set to false .
I tried to use org.springframework.data.domain.ExampleMatcher as explained in https://github.com/spring-projects/spring-data-examples/tree/master/mongodb/query-by-example ,but it didn't work(returns 0 records) . Below is code snippet of my attempt.
NOTE: I tried both by adding and removing withIgnoreNullValues() in below snippet .It did not help .
    public List<Adns> getAll(){
        Adns matcherObject = new Adns();
        matcherObject.setDeleted(false);
        ExampleMatcher matcher = ExampleMatcher.matching().withIgnoreNullValues().
                                 withMatcher("isDeleted", exact());
        Example<Adns> example = Example.of(matcherObject,matcher);
        return adnsRepository.findAll(example);
    }

I am able to retrieve all the object without that boolean filter successfully . Below is the working code .
public List<Adns> getAll(){
    return adnsRepository.findAll();
}

Below is the class UML :

A: You need to create the method declaration findByDeletedIsFalse on your repository interface.
At runtime, spring data will find this interface and create an implementation for it automatically. This is in fact one of the key features of spring-data. You can read more about query methods in the docs. The spring docs are very easy to read and full of examples.
Assuming your Adns uses a Long as primary ID, and that you are using the basic CrudRepository provider you should have:
public interface AdnsRepository extends CrudRepository<Adns, Long> {
    // this method declaration is automatically implemented by the spring-data library at runtime.
    List<Adns> findByDeletedIsFalse();
}

More information about query method generation:

*

*keywords: isFalse, isLike, isNotEmpty, etc

*the valid return types that can be returned from a spring data repository query method.

A: Be careful when using example matchers if your Probe object (in this case Adns) has primitive types such as boolean.
There is no way of instantiating that object with such properties unset. This is because primitives always take a default value (false for booleans) and cannot be assigned to null.
So, any search by example using that probe might end up with an undesired side effect if your intention is to search by any other field: the primitive field will always be included (with its default 'false' value) in the example.
Now, regarding your question, I suggest you to print out the json representation of your probe object (use jackson's modelmapper to do so) to detect any field taking a default value (such as empty strings insted of null values). Besides that, your field is called deleted in the model so the proper matcher should be:
withMatcher("deleted", exact());

Anyway it's always better to use the findBy.... methods in the repository and rely on the spring-data-mongodb automatic implementation
hope it helped.


text:
Q: Using function and checking a greater value from arrays I was trying to create a function using array and getting the greater value, but I'm failing and getting these messages, anyone may help me?

\Untitled4.c  In function 'main':
25    27  \Untitled4.c    [Warning] passing argument 1 of 'quatroMaior' makes
  pointer from integer without a cast
3 5 \Untitled4.c  [Note] expected 'int *' but argument is of type 'int'

#include <stdio.h>

int greater(int array[]) {
    int i, greater;

    for (i = 0; i < 4; i++) {
        if(array[i] > greater) {
            greater = array[i];
        }
    }

    return greater;
}

int main(void) {

    int j, v[4];

    printf("Type four values\n");

    for (j = 0; j < 4; j++) {
        scanf("%d", &v[j]);
    }

    printf("%d", greater(v[4]));

    system("pause");
    return 0;
}

A: As Joseph said in the comments, you are passing an integer, not an array. You have to write greater(v) instead of greater(v[4]).
The next thing you need to do is initialize the greater variable to greater = 0.
#include <stdio.h>

int greater(int array[])
{
    int i, greater = 0;

    for (i = 0; i < 4; i++)
    {
        if (array[i] > greater)
        {
            greater = array[i];
        }
    }

    return greater;
}

int main (void)
{
    int j, v[4];

    printf("Type four values\n");
    for (j = 0; j < 4; j++)
    {
        scanf("%d", &v[j]);
    }

    printf("%d\n", greater(v));

    return 0;
}

A: #include <stdio.h>

int greater(int array[]) {
    int i, greater;
/* greater is not init so you have an Undefined behavior.
** You could init it with array[0] but remind that need that size of array is at least 1.*/

    for (i = 0; i < 4; i++) { // If you do start at 1 because 0 is already in greater.
        if (array[i] > greater) { // here greater is not init !
            greater = array[i];
        }
    }

    return greater;
}

int main(void) {

    int j, v[4];

    printf("Type four values\n");

    for (j = 0; j < 4; j++) {
        scanf("%d", &v[j]);
    }

    printf("%d", greater(v[4]));
/* you send v[4] but you array has only range from 0 to 3.
** And is not what greater function expect he expect a array so just v.*/

    system("pause");
    return 0;
}


text:
Q: Posting any text with ampersand "&" back to web service is causing issues I am posting text with ampersand "&" back to web service and it is causing issues in my Objective C application.
I have to escape it somehow.
Any ideas?... I am very new to Objective C and iPhone programming at the moment...

A: This happens when you try to pass some values in the URL and the value contains & which is used to separate parameters in the URL, hence the web server spilts the content into parts wherever it encounters an & rather than taking it as a single continuos value.
You can url encode the string to resolve the problem.
NSString *valueToSubmit = @"This is my value which contains & in it.";
NSString *urlEncodedString  = (NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)valueToSubmit,NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8));
NSLog(@"Non-Encoded: %@ \n Encoded: %@",valueToSubmit,urlEncodedString];

The output will be something like this:

Non-Encoded: This is my value which contains & in it.
URL Encoded: This%20is%20my%20value%20which%20contains%20%26%20in%20it.

A: I take it you are posting something like "bread & butter" then what you see in your web service is missing the & and possibly a few characters after it or even a weird character in its place. Try replacing & with & So in the example above, you'd post "bread  &butter". You will find similar problems if you try to send a < or > and a few other characters. If you google NSString HTML escape you will find Objective C categories that can help you do this.
For an URL like www.mysite/foo&bar.html you would want to replace they & with %26 So www.mysite/foo%26bar.html. The same would be true in a query string. Replace the & with %26


text:
Q: Date split-up based on Fiscal Year Given a From Date, To Date and a Fiscal Year system, I want to get all the split-up duration within the
given From & To Date based on the Fiscal Year system.  Explained below with examples:
Example 1:
Fiscal Year system: Apr to Mar
From Date: Jan-05-2008
To Date: May-15-2008
Based on Fiscal Year system, duration should be splitted into:
Jan-05-2008 to Mar-31-2008
Apr-01-2008 to May-15-2008

Example 2:
Fiscal Year system: Apr to Mar
From Date: Jan-17-2008
To Date: May-20-2009
Based on Fiscal Year system, duration should be splitted into:
Jan-17-2008 to Mar-31-2008
Apr-01-2008 to Mar-31-2009
Apr-01-2009 to May-20-2009

Am looking for approach/algorithm to solve this in PostgreSQL 8.2.
Regards,
Gnanam

A: I actually favor Andomar's solution (with the addition of a processes that automatically fills the Periods table), but for fun here's a solution that doesn't require it.
CREATE TABLE your_table (start_date date, end_date date);
INSERT INTO your_table VALUES ('Jan-17-2008', 'May-20-2009');

SELECT
    GREATEST(start_date, ('04-01-'||series.year)::date) AS year_start,
    LEAST(end_date, ('03-31-'||series.year + 1)::date) AS year_end
FROM
    (SELECT
        start_date,
        end_date,
        generate_series(
            date_part('year', your_table.start_date - INTERVAL '3 months')::int,
            date_part('year', your_table.end_date - INTERVAL '3 months')::int)
    FROM your_table) AS series(start_date, end_date, year)
ORDER BY
    start_date;

A: You could create a table containing the start and end of all fiscal years, f.e.
Periods (PeriodStartDt, PeriodEndDt)

Then you can join the tables together if they at least partly overlap.  Use a case statement to select the end of the period or the end of the row, depending on which is later.  For example (not tested):
select      case when yt.StartDt < p.PeriodStartDt then p.PeriodStartDt
                 else yt.StartDt
            end as SplitStart
,           case when yt.EndDt > p.PeriodEndDt then p.PeriodEndDt
                 else yt.EndDt
            end as SplitEnd
,           yt.*
from        YourTable yt
inner join  Periods p
on          yt.StartDt < p.PeriodEndDate
            and yt.EndDt >= p.PeriodStartDate

A: CREATE TABLE your_table (start_date date, end_date date);
INSERT INTO your_table VALUES (CONVERT (date, GETDATE()),CONVERT (date, DATEADD(year, -1, GETDATE())) );

WITH mycte AS
 (
 SELECT 1 as id
 UNION ALL
 SELECT id + 1
 FROM mycte
 WHERE id + 1 < = 12
 ),
 cte_distribution as
 (
 SELECT *,
 DATEPART (month,DATEADD(month, mycte.id - 1, your_table.start_date)) as month_number ,
 DATEPART (YEAR,DATEADD(month, mycte.id - 1, your_table.start_date)) as  cal_year,
 12000/12 as cash
 FROM your_table
 CROSS JOIN mycte
 )
 select
 *,
 (CASE WHEN month_number between 1 and 3 THEN '1st quarter' WHEN month_number between 4 and 6 THEN '2nd quarter'  WHEN month_number between 7 and 9 THEN '3rd quarter' WHEN month_number between 9 and 12 THEN '4th quarter' END) as Quarter,
 CASE WHEN month_number between 1 and 6 THEN  CAST(CAST((cal_year - 1) as CHAR(4)) + '-' + CAST(cal_year as CHAR(4)) AS CHAR(9))  WHEN  month_number between 6 and 12 THEN CAST(CAST((cal_year) as CHAR(4)) + '-' + CAST((cal_year + 1) as CHAR(4)) AS CHAR(9))  ELSE NULL END as fin_year
 from cte_distribution;


text:
Q: Google Sheets – Remove Row when cell in column A contains a string Scripts newbie here. I have a list of URLs in column A
I want tot create a button that helps me delete a row whenever the cell in column A contains one of a list of keywords. I was trying the code below to delete all rows where A contains "blogspot".
It is still not working. I get this error: "TypeError: thisVal.indexOf is not a function"
However, I'm not even sure I can add multiple strings in addition to "blogspot". For example, I would like to delete all rows containing blogspot, wordpress and wix.
    function cleanRows() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sh = ss.getSheetByName('Master');

  var colA_Vals = sh.getRange(1, 1, sh.getLastRow(), 1).getValues();

  var i = 0,
      j = 0,
      thisVal,
      chkVal,
      arrayValsToChk = ['blogspot'];

  for (i=colA_Vals.length;i>0;i-=1) {
    thisVal = colA_Vals[i-1][0];
    //Logger.log('i: ' + i);

    for (j=0;j<arrayValsToChk.length;j+=1) {
      chkVal = arrayValsToChk[j].toLowerCase() //Change to all lower case;

      if (thisVal.indexOf(chkVal) !== -1) {
        ss.deleteRow(i);
      };
    };
  };
};

A: Explanation:
Your goal is to delete the rows for which the cells in column A contain a string in the arrayValsToChk list.

*

*You need to get the position of the rows which satisfy the condition, namely string in cell A is included in arrayValsToChk. You can use map and filter to get the indexes.

*Delete the rows backwards as it is also explained why in this thread.
Solution:
function myFunction() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sh = ss.getSheetByName("Master");
  const colA_Vals = sh.getRange(1, 1, sh.getLastRow(), 1).getValues();
  const arrayValsToChk = ['blogspot','wordpress','wix']; // list of strings
  const indexToDlt= colA_Vals.flat()
                    .map((v,i)=>arrayValsToChk.includes(v.toString().toLowerCase())?i:'')
                    .filter(v=>v!='');
  for (let i = indexToDlt.length - 1; i>=0; i--) {
   sh.deleteRow(indexToDlt[i]+1);
  }
}


text:
Q: Comparing a boolean value before setting it In C#, when setting a boolean variable's value to false only when it is true, should I check if it is true before setting it or just set it?
Assuming the variable is true 50% of the time, checking it makes sense since a comparison is faster. If the variable is true most of the time, should I just skip the comparison?
Which is the better practice?
Method 1, checking first:
if (bVariable)
    bVariable = false;

or Method 2, Just setting it:
bVariable = false;

Under which conditions is method 2 preferred, if ever?

A: Don't complicate life. Just set it. It's actually more expensive to check first, anyway, since you now have to slurp the existing value from RAM (or cache) before sending back a new value.
(With thanks to Colin Mackay...) Testing first also incurs pipeline stall penalties due to branch mis-predictions.

A: In C# the answer is: method 2 is always preferred. Since this is a very simple optimisation, if method 1 were really faster, the compiler would do it.
EDIT:
Donald Knuth has some advice against your method 1, such as "premature optimization is the root of all evil" and "code is meant to be read by humans first, and machines second".

A: What makes you think that the comparison is faster?  If the code you were writing was done in a C compiler, the IF statement would be split into at least two instructions -- a comparison/branching instruction and a "set" instruction on a single bit on a single word.
The "set" would compile to a single instruction.  Your "optimization" could possibly make your program run slower, and would cause your program to be less readable.  Just set the variable and don't try to overthink little things.
CPUs aren't like databases.  You don't pay a high penalty for data modifications.  You pay high penalties for making trips to main memory and for branching (if statements).  Branches cost performance because pipelining CPUs actually start executing instructions after the branch before the branch instructions even make their decision!  (I know, that statement is somewhat mind-blowing).  But what that means is that the CPU has to spend resources "guessing" what the outcome of your IF statement is going to be.  If it guesses wrong, it has to "throw away" the results of all instructions that it guessed would be executed after the branch and try again.  It's bad.  It's why branches are expensive.
The moral of this particular story is not that you should never optimize, but that you should never optimize without completely understanding the implications of your optimization.  In this case, had you gone with Option 1, you could possibly end up with a slower app which is less readable to boot.
Actually, if you're really interested in this sort of thing, you should definitely pick up a copy of Code Complete.  It's full of discussions about this sort of thing, and is brilliantly written.

A: This seems like too much of a micro-optimization, I really think the compiler optimizes this bit for you anyway.
But, if you want the final value to be false no matter what, I guess simply assigning it to false makes more sense. I mean why check if you don't really need to care about the value anyway.

A: I'd say the performance difference is so insignificant just set the thing to false all the time.
If it is false, it will be set to false again.
If it is true, it will be set to false.
At the end of the code the variable will be false regardless.
By just setting it to false all the time you make the intent clearer anyway. Anyone else reading the code will instantly see that the value will be false in all instances by the end of that section of code. While if you have an if statement they will have to think about it a little harder.
For maintenance alone, I would advocate setting the value to false regardless of its original value since it will always be false at the end.

A: Method 2 should be preferred simply because it expresses the same outcome more simply, making it easier to read, as others have said - for something simple like this legibility is far more important than the vanishingly small performance concern.
However, it is possible that bVariable could be a property, in which case setting it could entail other side-effects - both in terms of performance and outcome, potentially.

A: The only reason to do the comparison is if you have extra logic you need to execute when the value changes.
If you are only going to assign it anyway, it will most likely hurt performance if you do the extra check.

A: Premature optimization is the root of all evil. There is no way you can persuade me that this "optimization" will give you any performance gain at all

A: The performance issue is not relevant here, because a simple if statement like the above essentially is close to a no-op for the processor. It is much more important that your code is clearly communicating its intention for later readers!
Thomas


text:
Q: Boto3 Python Lambda Customise Return Error Is there a way to customise a Boto3 Lambda exception message in the form of a HTTP response and return it while also sending a forced failed?
Here is an example
except Exception as e:
  print ('\nException : failed to invoke jobs.')
  print ('Error : ' + str(e) + '\n')
  return {
    'statusCode': 500,
    'body': 'Exception : failed to invoke EMR jobs'
  }

So the customised message is now returned but the Lambda still returns a job success rather than failure.
In order to send the job failure the exception block can be changed to -
except Exception as e:
  print ('\nException : failed to invoke jobs.')
  print ('Error : ' + str(e) + '\n')
  raise

But now the custom error message has been lost.
Is there a way to combine the custom response error message and to fail the Lambda job?

A: You didn't mention it, but you're probably using AWS API Gateway to in front of your lambda.
You can use API Gateway "integration response" to transform your failed result to the HTTP response.
Here's a link to the docs

A: To get the custom error message as output for the lambda, you need to actually raise the exception with the custom error message.
except Exception as e:
  custom_error = '\nException : failed to invoke jobs.\n'
  custom_error += 'Error : ' + str(e) + '\n'
  raise Exception(custom_error)

And you will get an error message like:
{
  "errorMessage": "Exception : failed to invoke jobs. ....",
  "stackTrace": [
    [
      "/var/task/lambda_function.py",
      3,
      "my_always_fails_handler",
      "raise Exception(custom_error)"
    ]
  ],
  "errorType": "Exception"
}

You can find more on the AWS documentation that you can find here Python exceptions in lambdas


text:
Q: In C# how do access my LINQ var array from another method? I am using LINQ to create tables in a WPF application, but when I try to access one of those tables using an event method, my compiler tells me "The name 'parts' does not exist in the current context". Is there something I should do to adjust the scope so that I can access a var from a separate method?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace FinalExam_SupplierPartsWPF
{

public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();

        var suppliers = new[] {
            new{SN = 1, SName = "Smith", Status = 20, City="London"},
            new{SN = 2, SName = "Jones", Status = 10, City="Paris"},
            new{SN = 3, SName = "Blake", Status = 30, City="Paris"},
            new{SN = 4, SName = "Clark", Status = 20, City="London"},
            new{SN = 5, SName = "Adams", Status = 30, City="Athens"}
        };

        var parts = new[] {
            new{PN = 1, PName="Nut", Color = "Red", Weight = 12, City="London"},
            new{PN = 2, PName="Bolt", Color = "Green", Weight = 17, City="Paris"},
            new{PN = 3, PName="Screw", Color = "Blue", Weight = 17, City="Rome"},
            new{PN = 4, PName="Screw", Color = "Red", Weight = 14, City="London"},
            new{PN = 5, PName="Cam", Color = "Blue", Weight = 12, City="Paris"},
            new{PN = 6, PName="Cog", Color = "Red", Weight = 19, City="London"}
        };

        var shipment = new[] {
            new{SN = 1, PN = 1, Qty=300},
            new{SN = 1, PN = 2, Qty=200},
            new{SN = 1, PN = 3, Qty=400},
            new{SN = 1, PN = 4, Qty=200},
            new{SN = 1, PN = 5, Qty=100},
            new{SN = 1, PN = 6, Qty=100},
            new{SN = 2, PN = 1, Qty=300},
            new{SN = 2, PN = 2, Qty=400},
            new{SN = 3, PN = 2, Qty=200},
            new{SN = 4, PN = 2, Qty=200},
            new{SN = 4, PN = 4, Qty=300},
            new{SN = 4, PN = 5, Qty=400}
        };

        IEnumerable<string> colorList = parts
            .OrderBy(part => part.Color)
            .Select(part => part.Color)
            .Distinct();

        foreach (string x in colorList)
            cbxColorSelect.Items.Add(x);

    }

    private void ColorSelectedEvent(object sender, SelectionChangedEventArgs e)
    {
        lbxPartDisplay.Items.Add("test");
        string colorChoice = cbxColorSelect.Text;

        IEnumerable<string> partResults = parts
            .Where(clr => String.Equals(clr.Color, colorChoice))
            .Select(part => String.Format("{0}", part.PName));

        foreach (string y in partResults)
            lbxPartDisplay.Items.Add(y);
    }
}

}

A: The parts, suppliers and shipments variables are declared in the scope of the MainWindow() method; they will not be accessible anywhere outside of this method.  If you want to access these variables in another method within the same class, you should declare them as private to the class.
When a variable is declared, you typically specify an access modifier.  In your example, you are creating the variables implicitly using the var keyword.  Variables created in such a manner have a default access modifier of private. This means that they are scoped to they containing block in which they are created, which in your case is the MainWindow() method.  As others have suggested, I would recommend a review of variable scope and access modifiers. You will need to have a solid grasp of these basics to be productive.
Check out this channel 9 video series on some C# fundamentals for beginners; specifically, episode 5 focuses on variables. This blog post also goes over some basics on variable scope.
The var keyword used for variable declaration means that the variable is implicitly defined based on the assignment.  What this means is that the compiler will look at what you are assigning to the variable (ie: what is on the right side of the equals sign) and figure out the type.  For technical reasons, you cannot use the var declaration operator for variables defined at the class level (also often referred to as 'fields' of a class if they are private to the class).
Since you cannot use the var keyword to define your class level variables, you must explicitly specify a type.  In the example below, I have created a class which represents the original parts anonymous type you were working with in your example.
I also concur with the advice of other on starting out learning C# using a console application.  GUI applications bring a lot of other nuances to the table which can only serve to confuse you and cause general frustration when you are learning a language.  For example: simple things such as updating a textbox from the non GUI thread  with a new value can bomb your program and leave you wondering why it doesn't work.
You can choose to continue to work with an array of anonymous types, however you would need to declare it as dynamic or object.  Working with an array of anonymous objects can be a little more challenging. I would recommend that you use a defined type (such as the one part class have illustrated below) for your class fields.
for example:
public class Part
{
    public int PN { get; set; }
    public String PName { get; set; }
    public String Color { get; set; }
    public int Weight { get; set; }
    public String City { get; set; }
}

public partial class MainWindow : Window
{

    private List<Part> _parts;
    public MainWindow()
    {
        InitializeComponent();

        _parts.Add(new Part() { PN = 1, PName = "Nut", Color = "Red", Weight = 12, City = "London" });
        _parts.Add(new Part() { PN = 2, PName = "Bolt", Color = "Green", Weight = 17, City = "Paris" });
        _parts.Add(new Part() { PN = 3, PName = "Screw", Color = "Blue", Weight = 17, City = "Rome" });
        _parts.Add(new Part() { PN = 4, PName = "Screw", Color = "Red", Weight = 14, City = "London" });
        _parts.Add(new Part() { PN = 5, PName = "Cam", Color = "Blue", Weight = 12, City = "Paris" });
        _parts.Add(new Part() { PN = 6, PName = "Cog", Color = "Red", Weight = 19, City = "London" });

    }

    private void SomeMethod()
    {
        string colorChoice = "Blue";

        IEnumerable<string> partResults = _parts
            .Where(clr => String.Equals(clr.Color, colorChoice))
            .Select(part => String.Format("{0}", part.PName));
    }
}


text:
Q: Inconsistent Error ScatteredInterpolant - Matlab I have a series of coordinates and a data set each point.
size(LON) = 720 1
size(LAT) = 1440 1
size(data) = 720 1440

when I run data_F = scatteredInterpolant(LON, LAT, data),
I get
Error using scatteredInterpolant
Data point coordinates have inconsistent dimension.

What gives? I tried data_F = scatteredInterpolant(LAT, LON, data) for kicks, and got the samer error.

A: I think this was because my data was a matrix, not a column.
Griddata ended up working. GriddedInterpolant did not because my grid was not regular.


text:
Q: A simple subquery in SQL I have a table ORDERS with columns NAME and AMOUNT.
I need to get a NAME and total AMOUNT of each product.
I have such a solution
select PRODUCT_NAME, SUM(AMOUNT) from ORDERS GROUP BY PRODUCT_NAME;

But I dont use any subqueries for achieving that. But the lesson that Im going through is about subqueries. May be Im wrong about this solution?

A: Its a simple aggregation query without a need of sub query like:
SELECT name, SUM(AMOUNT)
FROM Orders
GROUP BY name

A: This solution is perfectly fine:
selectname, sum(amount)
from Orders
group by name

But, if you must use subquery, use this:
select o2.name,
  (select sum(amount)
   from Orders o1
   where o1.name = o2.name) as total
from
(select distinct name
from Orders) o2


text:
Q: Getting coordinates from pin's annotation's disclosure, on tap i'll try to keep this very simple :
I'm very new to Objective-C (or programming actually) so i'll probably need an explanation more than just an answer.
What i'm trying to do and can't do (yet):
Getting a pin's coordinate after tapping it's disclosure, and eventually pass it through a segue.
Practically, i'm clicking my "info" icon on a pin I just created, and i'd like to see it's info in another page (a webview). This page would show coordinates (and other stuff that we don't need here).
Why :
Practically, i'm clicking my "info" icon on a pin's annotation created earlier by the user, and i'd like to see it's info in another page (a webview). This page would show coordinates (and other stuff that we don't need here).
My pins coordinates are stored into a

CLLocationCoordinate2D location;

I can't re-use the variables i used before because they might be outdated (it would only work if the user asks for the last one created...)
And I do not know how i can get a pin's coordinates ; there must be a method or something but i jsut can't find it. I've found MANY answers on the  internet, and none seemed to work, probably because i didn't understand them properly. Anyway, i couldn't use them.
I'll show you bits of my code,  it's pretty straight forward i guess :
There is the viewDidLoad, you probably want to see it, i guess :
- (void)viewDidLoad
{
    [super viewDidLoad];
    name = [[NSString alloc]init];
    detail = [[NSString alloc]init];
    UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longpressToGetLocation:)];
    lpgr.minimumPressDuration = 2.0;  //user must press for 2 seconds
    [_map addGestureRecognizer:lpgr];
    CLLocationCoordinate2D loc = CLLocationCoordinate2DMake(50.837863, 4.353616);
    MKCoordinateSpan span = MKCoordinateSpanMake(.035, .035);
    MKCoordinateRegion reg = MKCoordinateRegionMake(loc, span);
    self.map.region = reg;
    [self buildBaseAnno];
    self.map.showsUserLocation = true;
}

I know this is important but to be honest i don't fully understand how  this bit works ; still, it does work. :D
    -(MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKAnnotationView* v = nil;
    {
        static NSString* ident = @"Pin";
        v = [_map dequeueReusableAnnotationViewWithIdentifier:ident];
        if (v == nil)
        {
            v = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ident];
            ((MKPinAnnotationView*)v).pinColor = MKPinAnnotationColorRed;
            UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
            v.rightCalloutAccessoryView = infoButton;
            v.centerOffset= CGPointMake(0,-20);
            v.canShowCallout= YES;
        }
        v.annotation = annotation;
    }
    return v;
}

Touch pin creation :
- (void)longpressToGetLocation:(UIGestureRecognizer *)gestureRecognizer
{
    if (gestureRecognizer.state != UIGestureRecognizerStateBegan)
        return;

    CGPoint touchPoint = [gestureRecognizer locationInView:self.map];
    location = [self.map convertPoint:touchPoint toCoordinateFromView:self.map];

    [self showAlertName];
}

The actual annotation/pin creation method
-(void)buildAnno
{
    CLLocationCoordinate2D coordinate;
    coordinate.latitude = location.latitude;
    coordinate.longitude = location.longitude;
    MKPointAnnotation* newann = [MKPointAnnotation new];
    newann.coordinate = coordinate;

    newann.title = name;
    newann.subtitle = detail;
    [self.map addAnnotation:newann];
}

Please, do tell if you need more of the code ; i'm not really sure what i can give you, as my code is probably 'correct' (or decent), i just need to actually know how to get the information i need (that is, coordinates and other stuff from the pin i just tapped.)
And i actually don't tap the pin, i tap the disclosure in the pin's annotation. Anyway, That's enough for now !
Once i can catch these coordinates, i believe i'll be able to pass them through the segue as passing Data is already well explained here, but if there is anything 'special', i'd be really glad if you could add it to your explanation because i'm still really uncomfortable with all this and most of the tutorials/guides/links i've found didn't really help me.
Thank you very much for your time and help :)
(Edit : I had found a similar question here but i believe i need extra help/explanation.)

A: You don't need the gesture recogniser - the map view delegate protocol already has a method that tells you when the callout accessory was tapped calloutAccessoryControlTapped and this method receives the relevant annotationView.  The annotationView.annotation property gets you back to the relevant annotation object and then you can access its coordinate property to get the coordinates of the pin.
First, create a new property in your class:
 @property CLLocationCoordinate2D tappedCoord;

then implement the delegate method
- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    MKPointAnnotation *annotation=(MKPointAnnotation*)view.annotation;
    self.tappedcoord=annotation.coordinate;
    [self performSegueWithIdentifier:@"detailViewSegue"];   // Use your appropriate segue identifier
}

Then you can access the property in prepareForSegue (again, change to the appropriate segue name and destination view controller class)
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"detailViewSegue" ]){
        DetailViewController *dvc=(DetailViewController *)segue.destinationViewController;
        dvc.coord=self.tappedCoord;
}

Also, since your MapView is displaying the user's location, there will be an annotation for that.  You need to address this in your viewForAnnotation method, returning nil if the annotation isn't one of yours.  You can check the class of the annotation to determine this -
-(MKAnnotationView*)mapView:(MKMapView*)mapView viewForAnnotation:(id <MKAnnotation>)annotation
{
    MKAnnotationView* v = nil;
    if ([annotation isMemberOfClass:[MKPointAnnotation class]]) {
        static NSString* ident = @"Pin";
        v = [_map dequeueReusableAnnotationViewWithIdentifier:ident];
        if (v == nil)
        {
            v = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:ident];
            ((MKPinAnnotationView*)v).pinColor = MKPinAnnotationColorRed;
            UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
            v.rightCalloutAccessoryView = infoButton;
            v.centerOffset= CGPointMake(0,-20);
            v.canShowCallout= YES;
        }
        v.annotation = annotation;
    }
    return v;
}


text:
Q: How to skip all cucumber-jvm scenarios when first scenario is failed I have 8 cucumber-jvm scenarios and the very first scenario measures the page load time and environment availability. In order to avoid unnecessary runs, if the first scenario is failed - for instance, the environment is not available, or loading too slowly - all other scenarios should be skipped.
How can I do that?
My CucumberOptions:
@RunWith(Cucumber.class)
@CucumberOptions(
        strict = true,
        features = {"src/test/resources/features"},
        glue = {"stepDefinitions"},
        format = {  "progress", "html:target/Results",
                "json:target/Results/cucumber.json"},
        tags = {"@test"})
        public class TestRunner {
}

Thanks!

A: You can make use of Assume.assumeTrue(false) to skip tests. But this will require some changes in test runner and code changes.

*

*Create a separate runner for the scenario which checks the environment details are all working. Let's call it RunFirstTest.java and give tags a value of @Smoke. Other option values default to what you have.

@RunWith(Cucumber.class)
@CucumberOptions(plugin={ }, tags={"@Smoke"}, glue=" ", features=" ")
public class RunFirstTest {

*Add the @Smoke tag to the scenario in the feature file that checks the environment etc. Optionally you could look at splitting the feature files.

*Create a new class to hold a static flag. It is a simple implementation you might look at making this more robust.

public class SkipFlag {
     public static boolean skipFlag = false; }

*Create an After hook with the value option set to @Smoke. Thus it will run only for the smoke scenario.

@After(value={"@Smoke"})
public void afterSkip(Scenario scen) {
   if(scen.isFailed())
      SkipFlag.skipFlag = true;
}

*Create a second runner for the main tests. Let's call it RunMainTest.java and give its tags value of @MainTests. Other option values default to what you have.

@RunWith(Cucumber.class) @CucumberOptions(plugin={" "},
  tags={"@MainTests"}, glue=" ", features=" ") public class RunMainTest
  {
       @BeforeClass
        public static void before() {
            if(SkipFlag.skipFlag)
               Assume.assumeTrue(false);
        }
      }

*Add the @MainTests tag to the other scenarios in the feature file. Optionally you could look at splitting the feature files and give the name of the feature file in the features option value.

*Run this by using maven failsafe plugin. In the configuration of this plugin add the inclusion of these 2 runners in the pom.xml.

 <configuration>
      <includes>
          <include>RunFirstTest</include>
          <include>RunMainTest</include>
      </includes>
        <runOrder>alphabetical</runOrder>
 </configuration>

The includes part might be optional if you only have 2 runners. The most important point is that the RunFirstTest should be the first to run, so alphabetically should be first.

*Run it with maven.

Hope it works.

A: Instead of trying to do this in Cucumber consider just writing a simple bash script that

*

*runs the first feature file e.g. cucumber features/first_scenarios.feature

*uses the exit code of the first run to decide whether or not to run the rest of the features

You can probably do this in about 3 lines of shell script.
One of the things about features is that different people will want to run them in different ways depending on their own particular circumstances. Putting this stuff inside your set of features can make things more difficult for other users.


text:
Q: Problem uploading sketch to arduino uno/esp8266 Getting this error while uploading:
Arduino: 1.8.13 (Windows Store 1.8.42.0) (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200"
Executable segment sizes:
IROM   : 236720          - code in flash         (default or ICACHE_FLASH_ATTR)

IRAM   : 26892   / 32768 - code in IRAM          (ICACHE_RAM_ATTR, ISRs...)

DATA   : 1252  )         - initialized variables (global, static) in RAM/HEAP

RODATA : 780   ) / 81920 - constants             (global, static) in RAM/HEAP

BSS    : 24976 )         - zeroed variables      (global, static) in RAM/HEAP

Sketch uses 265644 bytes (27%) of program storage space. Maximum is 958448 bytes.

Global variables use 27008 bytes (32%) of dynamic memory, leaving 54912 bytes for local variables. Maximum is 81920 bytes.

esptool.py v2.8

Serial port COM3

Connecting........_____....._____....._____....._____....._____....._____.....____Traceback (most recent call last):

  File "C:\Users\Arsh\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.7.4/tools/upload.py", line 65, in <module>

    esptool.main(cmdline)

  File "C:/Users/Arsh/Documents/ArduinoData/packages/esp8266/hardware/esp8266/2.7.4/tools/esptool\esptool.py", line 2890, in main

    esp.connect(args.before)

  File "C:/Users/Arsh/Documents/ArduinoData/packages/esp8266/hardware/esp8266/2.7.4/tools/esptool\esptool.py", line 483, in connect

    raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))

esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header
or it says Invalid Head of Packet(0xF0)

_

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

This is the pin configuration:

Insted of the 3.3v im using a voltage regulator.
Also RX connected to RX & TX to TX.
Code:

#include <ESP8266WiFi.h>

void setup()
{
  Serial.begin(115200);
  Serial.println();

  WiFi.begin("username", "password");

  Serial.print("Connecting");
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println();

  Serial.print("Connected, IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {}

Someone suggested to ground the GPIO0, didn't work.
Tried installing different version of the Board:"Generic ESP8266 Module" still getting the same error.
The module works fine when working without the library using the Board:"arduino uno"

A: GPIO-00 needs to be held at ground while RESET goes to ground, then back to high. This reboots the ESP-01 into the FLASH mode.
For a good overview of a circuit to accomplish this, read:
https://www.allaboutcircuits.com/projects/flashing-the-ESP-01-firmware-to-SDK-v2.0.0-is-easier-now/
Read about the ESP8266 boot modes here:
https://tttapa.github.io/ESP8266/Chap04%20-%20Microcontroller.html

A: Could you give more details about the 3.3V regulator that you using?
Do you have it connected between the serial signals?
If that is the case, I suggest this connection instead:
3.3V signal voltage divisor
ESP TX and Arduino RX can be connected directly without any issue


text:
Q: list view null pointer exception in android hi all i have a list view with some values in string array and i pass it to list view by
 list1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array));

it get NullPointerException on this line.
my code:
public class SecondActivity extends Activity{

int min=00,hr=00,sec=00;
TextView tv1;
ListView list1;
private String array[] = { "Iphone", "Tutorials", "Gallery", "Android","item 1", "item 2", "item3", "item 4" };

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.secondactivity);

    tv1=(TextView)findViewById(R.id.textView1);
    list1 = (ListView) findViewById(R.id.list);

    Bundle bundle = this.getIntent().getExtras();
    hr = Integer.parseInt(bundle.getString("key1"));
    min = Integer.parseInt(bundle.getString("key2"));
    sec=Integer.parseInt(bundle.getString("key3"));

    tv1.setText(String.format("%02d:%02d:%02d", hr, min, sec));

    list1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array));      // line no 38

list1.setOnItemClickListener(
        new OnItemClickListener()
        {
            public void onItemClick(AdapterView<?> arg0, View view,int position, long id) {
                // TODO Auto-generated method stub
                Object o = list1.getItemAtPosition(position);
                String pen = o.toString();
                Toast.makeText(getApplicationContext(), "You have chosen the pen: " + " " + pen, Toast.LENGTH_LONG).show();

            }

            public void onItemClick1(AdapterView<?> arg0, View arg1,
                    int arg2, long arg3) {   // eclipse told me to add Unimplemented method(this method).
                // TODO Auto-generated method stub

            }

        }
);

 }

}
my xml file:
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
   <TextView android:text="TextView" android:id="@+id/textView1"     android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>

  <ListView android:id="@+id/list"  android:layout_width="fill_parent"   android:layout_height="wrap_content" android:layout_marginLeft="10px" android:layout_marginRight="10px" android:layout_marginTop="65px" android:layout_marginBottom="40px" android:paddingLeft="0px"
android:paddingRight="0px" />

</LinearLayout>

my Log cat file:
 05-12 17:50:12.295: ERROR/AndroidRuntime(3776): Caused by: java.lang.NullPointerException
  05-12 17:50:12.295: ERROR/AndroidRuntime(3776):     at com.stop.watch.SecondActivity.onCreate(SecondActivity.java:38)
  05-12 17:50:12.295: ERROR/AndroidRuntime(3776):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
 05-12 17:50:12.295: ERROR/AndroidRuntime(3776):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)

A: I think you should use R.layout.simple_list_item_1 and not android.R.layout.simple_list_item_1 (and clean the project before building it)

A: Try having your class extend ListActivity rather than Activity

A: It looks like there is a mismatch between the id for your ListView:
The id value in your XML layout might be different from the id that comes from the Bundle. Clean your project and rebuild, and see if that fixes it.


text:
Q: adding product quantity in the mysql field from PHP In my PHP&MYsql application I have a stock table with fields:
stock_id,
stock_name,
stock_code,
stock_desc,
quantity,
date of purchase

All the data for this table are entered by admin from the stock register screen in front end.
1  HI0001   Pen      This is a item for writing 2013-12-18          15
2  SO0002   Duster   This item is               2013-12-18          12
3  HO0003   Board    This is for demonstration  2013-12-17          15

Now My question is for example if admin again enters a new stock with stock_name:pen  and quantity:10 how can I save the quantity(10 + 15) i.e 25 in quantity field instead of creating a new row in the table?
I only have the above fields in my table and the stock_code is a field that will increment one each time when a record is added. So can't do much with the stock_code.

A: You can run a query to see if you already have a record for that stock_name and then you can run the appropriate query.
SELECT COUNT(stock_name) AS CNT FROM stock table WHERE stock_name = Pen;

IF CNT > 0 THEN
   UPDATE stock table SET quantity = quantity + new qty WHERE stock_name = pen
ELSE
   INSERT INTO ....

hope this can help you ...


text:
Q: How to use the count() method on a list excluding some items So, I want to if, in a list, there are any repeated numbers, but I want to exclude some of them. How can I do it, using the count() method? Can I?
Example:
thelist = [0,0,3,4]

for x in thelist:
    if thelist.count(x) > 1:
            print("Repeated")
            break

Obviously it says repeated. Now, how can I avoid counting the zeros? I just want it to count the following numbers:
only_numbers_the_function_should_test = [1,2,3,4]

I've searched through the web and found nothing. Maybe it's impossible. Can you give me an alternative?
Note : I don't want it to remove any list item. It's for a sudoku solver. I can't cut numbers like that.

A: Just stick in an if condition.
for x in thelist:
    if x==0:
        continue
    # rest of your code

Or if you want a specific range:
if x <= 0 or x > 9:
    continue

A: Why don't filter the 0s out of the list first and then count:
from collections import Counter
thelist = [0, 0, 3, 4]
counter = Counter([x for x in l if x != 0])
for i in Counter([x for x in thelist if x != 0]):
    if counter[i] > 1:
        print("Repeated")

EDIT: With a simple modification to your code
thelist = [0,0,3,4]

for x in [x for x in thelist if x != 0]:
    if thelist.count(x) > 1:
       print("Repeated")
       break


text:
Q: how to divide an interval into equal parts Hi how to divide an interval into  equal parts
example :
[1-100] divide by 5 part -->

1- [1-20]
2- [21-40]
3- [41-60]
4- [61-80]
5- [81-100]

or
[1-102] divide by 5 part -->

1- [1-20]
2- [21-40]
3- [41-60]
4- [61-80]
5- [81-100]
6- [100-102]*

i try a code but sometimes work and in other nums not work as it must
this is what i make (i know i am week in math :P , i code it 2 week ago and now i have no idea how i make it :D  )

Func vall($a , $b)
    Local $inval = ''
    $all  = $a
    $c    = $b ; - 1

    $evv  = Int($all/$c)
    $rrt  = Int($all/$evv)

    $trtr = $evv
    $ee   = 1
    $fg   = 0

    If Mod($a,$evv) == 0 Then
        For $ll = 1 To $rrt ; $all
            If $ll = $rrt Then
                $inval = $inval & $ee & ':-:' & $trtr
            Else
                $inval = $inval & $ee & ':-:' & $trtr &','
            EndIf

            $ee   = $ee   + $evv
            $trtr = $trtr + $evv
        Next
    Else
        For $ll = 1 To $rrt ; $all
            $inval = $inval & $ee & ':-:' & $trtr &','
            $ee    = $ee   + $evv
            $trtr  = $trtr + $evv
        Next
        $uu    = $trtr - $evv + 1
        $inval = $inval & $uu & ':-:' & $all
    EndIf

    Return $inval
EndFunc

i use autoit , but i need the algorithm to use it in any lang .
thank you .

A: Here is a python implementation which is quite easy to understand.
def divide(number, parts):
    '''number is the last number of the range and parts is no. of intervals you
        want to make'''
    chunksize = number//parts             # size of each interval
    chunkstart = 1                        # start of interval
    chunkend = chunkstart + chunksize -1  # end of that interval
    while chunkstart < number:            # don't go beyond the range
        if chunkend > number:             # interval end is beyond the range
            print chunkstart, number
            break                         # we are beyond the range now
        print chunkstart, chunkend
        chunkstart += chunksize           # take me to beginning of next interval
        chunkend += chunksize             # also tell me where to end that

Sample Input and Ouputs

divide(100, 5)
1 20
21 40
41 60
61 80
81 100

divide(102, 5)
1 20
21 40
41 60
61 80
81 100
101 102

A: @pulkit-goyal as u said i did same analyse [your code helped me to understand how it work after all the math is sweet :D ]
so i get that the best way to get the right result
is to change the parts , and test part-1 and part+1 until it get the best part
i cook a simple code :
$number = 57
$parts  = 30
$yy     = 0
$yusf   = 0

ConsoleWrite('number :' & $number & ' | parts : ' & $parts & @CRLF)
$partsplus  = $parts
$partsmoins = $parts

If Mod($number, $parts) > Int($number / $parts ) Then
    While $yusf = 0
        $partsplus  += 1
        $partsmoins -= 1

        If Mod($number, $partsplus) < Int($number / $partsplus ) Then
            ConsoleWrite("old part : " & $parts & "| new part :" & $partsplus & " | interval : " & Int($number / $partsplus ) & @CRLF)
            $parts = $partsplus
            $yusf  = 1
        ElseIf Mod($number, $partsmoins) < Int($number / $partsmoins ) Then
            ConsoleWrite("old part : " & $parts & "| new part :" & $partsmoins & " | interval : " & Int($number / $partsmoins  ) & @CRLF)
            $parts = $partsmoins
            $yusf  = 1
        EndIf
    WEnd
EndIf

$chunksize  = Int($number / $parts )      ; size of each interval
$chunkstart = 1                           ; start of interval
$chunkend   = $chunkstart + $chunksize -1 ; end of that interval

While $chunkstart <= $number              ; don't go beyond the range
    If $chunkend > $number Then           ; interval end is beyond the range
        ; print $chunkstart, $number
        ConsoleWrite("[ " & $chunkstart & " : " & $number & " ]*" & @CRLF)
        ExitLoop
    EndIf

    ; we are beyond the range now
    ConsoleWrite("[ " & $chunkstart & " : " & $chunkend & " ]" & @CRLF)
    $yy         += 1
    $chunkstart += $chunksize             ; take me to beginning of next interval
    $chunkend   += $chunksize             ; also tell me where to end that
WEnd

some test
for 57 - 30 , 30 changed to 28 to have good results
number :57 | parts : 30
old part : 30| new part :28 | interval : 2
[ 1 : 2 ]
[ 3 : 4 ]
[ 5 : 6 ]
[ 7 : 8 ]
[ 9 : 10 ]
[ 11 : 12 ]
[ 13 : 14 ]
[ 15 : 16 ]
[ 17 : 18 ]
[ 19 : 20 ]
[ 21 : 22 ]
[ 23 : 24 ]
[ 25 : 26 ]
[ 27 : 28 ]
[ 29 : 30 ]
[ 31 : 32 ]
[ 33 : 34 ]
[ 35 : 36 ]
[ 37 : 38 ]
[ 39 : 40 ]
[ 41 : 42 ]
[ 43 : 44 ]
[ 45 : 46 ]
[ 47 : 48 ]
[ 49 : 50 ]
[ 51 : 52 ]
[ 53 : 54 ]
[ 55 : 56 ]
[ 57 : 57 ]*

for 7 - 300 , 300 changed to 7 :D
number :7 | parts : 300
old part : 300| new part :7 | interval : 1
[ 1 : 1 ]
[ 2 : 2 ]
[ 3 : 3 ]
[ 4 : 4 ]
[ 5 : 5 ]
[ 6 : 6 ]
[ 7 : 7 ]

and in normal case
for 10 -2 , no change
 number :10 | parts : 2
 [ 1 : 5 ]
 [ 6 : 10 ]


text:
Q: use of separate sequence for tables in hibernate envers I know that hibernate envers uses same sequence for all the audit tables it generates but in my database there are more than 100 tables and they contain millions of data records so I want to use separate sequence for all the tables. Kindly suggest me how to achieve this because I am not able to find anything related to my problem.
Thanks in advance

A: Unfortunately currently the Envers revisions are global per Hibernate configuration.


text:
Q: How to interact with a Users webcam & inbuilt microphone using Ruby / Rails? Not sure how to frame this one, so here goes...
I have a need to develop an application which allows my boss to post a series of questions that will be answered by various consultants around the world, each question will have a time limit in which it can be answered e.g. 3 minutes.
Here is the problem, the users answering the questions must do so via their webcam & microphone built into their computer. The recording will need to be done directly through the web-app (no pop-ups, or external apps e.g. skype) & I need to limit the recording time allowed for each question.
I have no idea how to do this using Ruby / Rails or where to even start, been doing some research but not found much so far.
Does anyone have any recommendations / ideas of how this can be done?
Thanks!

A: The only technology I know of that can do this on the client is Flash. Or perhaps Java.
Ruby and/or Rails can't help you here as they are entirely server-side technologies.

A: http://dev.w3.org/html5/html-device/ might be a start, but will still take a couple of months/years/decades.


text:
Q: Quick question about relational one-to many database I'm doing a venue/events database and I've created my tables and would like some confirmation from someone if I did everything right :)
I have 2 tables:

*

*Venues

*Events

The primary key of Venues is VENUE_ID, which is set to auto_increment. I have the same column in Events, which will contain the number of the Venue ID.  This should connect them, right?
Also, the table engine is MyISAM.

A: Your db structure is right.
You can use Innodb for adding foreign key contraints. Also don't forget to add index to the second table for faster joining two tables.
More info about FK http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
Note to comments:
Innodb allows you to make concurrent select/(insert/update) but MyIsam allows you to do the same things if you don't delete from MyIsam table. Otherwise MyIsam will lock your whole table.

A: It does not automatically link the tables to each others, and the referenced columns don't necessarily have to have the same name (in fact, there are situations where this is impossible: e.g. when a table has two columns that both reference the same column in another table).
Read up on foreign keys; they're standard SQL and do exactly what you want. Note, however, that the MyISAM storage engine cannot enforce foreign key constraints, so as long as any of the tables involved uses MyISAM, the foreign key declaration doesn't add much (it does, however, document the relationship, at least in your SQL scripts).
I suggest you use InnoDB (or, if that's feasible, switch to PostgreSQL - not only does it provide foreign key constraints, it also has full support for transactions, unlike MySQL, which will silently commit a pending transaction whenever you do something that's not supported in a transaction, with potentially devastating results). If you have to / want to use MySQL, I suggest you use InnoDB for everything, unless you know you need the extra performance you can get out of MyISAM and you can afford the caveats. Also keep in mind that migrating large tables from MyISAM to InnoDB later in production can be painful or even outright impossible.

A: Generally, yes.  This is how you indicate a one-to-many relation between two tables.  You may also specifically encode the relationship into the database by setting up a Foreign Key constraint.  This will allow add'l logic such as cascading.


text:
Q: LibGdx: How to set a separate viewport for UI elements? I'm trying to code a simple maze with a character that moves using a Joystick (touchpad). I used a Fit viewport to maintain the aspect ration of my maze while keeping it at the center of the screen;
However, I find that that the joystick is also added beside the maze. sample of what it looks like currently
I want the joystick to be of the far bottom-left of the screen. I tried doing this using a different viewport for UI elements (including the joystick), but then the whole maze just gets distorted.
Here is part of my BaseScreen class, an extension I made to reuse in other games as well:
public abstract class BaseScreen implements Screen, InputProcessor {

public BaseScreen(){

    gameWorldHeight = 1024;
    gameWorldWidth = 1024;
    cam = new OrthographicCamera(gameWorldWidth, gameWorldHeight);
    port = new FitViewport(cam.viewportWidth, cam.viewportHeight, cam);
    port.apply();
    cam.update();

    mainStage = new Stage(port);
    uiStage = new Stage(port);
    uiTable = new Table();
    uiTable.setFillParent(true);
    uiStage.addActor(uiTable);

    initialize();
}

public abstract void initialize();

public void render(float dt) {
    mainStage.getCamera().update();
    uiStage.getCamera().update();

    uiStage.act(dt);
    mainStage.act(dt);

    update(dt);

    mainStage.draw();
    uiStage.draw();
}

public abstract void update(float dt);

public void resize(int width, int height) {
    mainStage.getViewport().update(width,height, true);
    uiStage.getViewport().update(width,height,false);
}
}

Here is also a part of my gameScreen class, where I actually code all the core mechanics of the game
public class gameScreen extends BaseScreen {

@Override
public void initialize() {

    //..

    uiTable.pad(10);
    uiTable.add().expandX().expandY();
    uiTable.row();
    uiTable.add(ball.touchpad).left();
    uiTable.add().expandX();
  }
}

and in case you were wondering, here is what ball.touchpad is
public class Ball extends BaseActor {

public Touchpad touchpad;
public Touchpad.TouchpadStyle touchpadStyle;
public Skin touchpadSkin;
public Drawable touchBackground;
public Drawable touchKnob;

public Ball (float x, float y, Stage s) {

    //..

    //Create a touchpad skin
    touchpadSkin = new Skin();

    //Set background image
    touchpadSkin.add("touchBackground", new Texture("touchBackground.png"));

    //Set knob image
    touchpadSkin.add("touchKnob", new Texture("touchKnob.png"));

    //Create TouchPad Style
    touchpadStyle = new Touchpad.TouchpadStyle();

    //Create Drawable's from TouchPad skin
    touchBackground = touchpadSkin.getDrawable("touchBackground");
    touchKnob = touchpadSkin.getDrawable("touchKnob");

    //Apply the Drawables to the TouchPad Style
    touchpadStyle.background = touchBackground;
    touchpadStyle.knob = touchKnob;

    //Create new TouchPad with the created style
    touchpad = new Touchpad(10, touchpadStyle);
    //setBounds(x,y,width,height)
    touchpad.setBounds(15, 15, 200, 200);

}

So how can i add this touchpad on the bottom left of the screen?


text:
Q: iOS build of React Native project stuck on User defaults from command line: IDEPackageSupportUseBuiltinSCM = YES I am trying to build a React Native Project with npx react-native run-ios --simulator='iPhone 14 Pro' --verbose to see any helpful output, but it remains stuck with the following CLI output:
    info Found Xcode workspace "myapp.xcworkspace"
    info Building (using "xcodebuild -workspace myapp.xcworkspace -configuration Debug -scheme myapp -destination id=2A2B9240-3EBA-4BF1-8B43-215151CFB12B")
    debug Command line invocation:

    debug /Applications/Xcode.app/Contents/Developer/usr/bin/xcodebuild -workspace myapp.xcworkspace -configuration Debug -scheme myapp -destination id=2A2B9240-3EBA-4BF1-8B43-215151CFB12B

    User defaults from command line:
        IDEPackageSupportUseBuiltinSCM = YES

I can't understand what User defaults from command line: IDEPackageSupportUseBuiltinSCM = YES is, I've tried to search but without success.
I have Xcode 14, iOS simulator version 16.0.0 and everything is running on a M1 chip


text:
Q: Ruby array of arrays find by inner array value I have array of arrays, which looks like this:
a = [['1','1500','SomeName','SomeSurname'],
['2','1500','SomeName2','SomeSurname2'],
['3','1500','SomeName3','SomeSurname3'],
['4','1501','SomeName','SomeSurname'],
...]

I can get sub-array of this array with all rows containing '1500' value by .each function and simple  if, but if a.length is large, it's taking too much time! How can I get all rows from  a with certain a[1] value, without iterating over  a?

A: You have a few options, you could use a find:
a.find { |l| l[1] == '5' }

This would find the array that matches the first 5
You need to use find_all to find all:
a.find_all { |l| l[1] == '5' }

A: Enumerable#find_all is what you are looking for:
a.find_all { |el| el[1] == '1500' } # a.select will do the same

A: Use select to get all matching elements:
a.select { |e| e[1] == '1500' }


text:
Q: Eclipse screws up every time I type an object's method So for example with my current object tabPanelMain, I'll type a dot after it and expect to see a drop down menu of all the object's available methods. Instead, the marker which shows my currently selected character on the editor disappears meaning I don't know where I'm typing. Worse than that is that the save and save all buttons stop working. And ctrl-s and the menu saves don't work either. I can't save my eclipse projects and have to restart, thus losing my work.
What could be wrong? This problem never used to exist but now I just can't get the methods of an object like I used to.
I hope that was clear enough, please ask me questions if not.

A: The save problem with not being able to save is one I've encountered before.
I don't know why it happens but for me it helps to minimize and then maximize eclipse again.
Not a fix but at least a workaround that lets you save.
Never heard of the other problem though.

A: I couldn't figure out what it was that was causing the problem, and while Martin Larsson provided an effective short term solution, I found it best to fresh install Eclipse.
The most annoying part about this was transferring my previous plug ins (like GWT, Subversion, etc) over to the new install. In the end I ended up re-installing them manually. If anyone could shed some light on how to keep previous plug ins, I'd like to hear how. Though I've heard this can be problematic with path urls in the files or something.