text:
Q: C# - Duration between two DateTimes in minutes I need to determine duration between two DateTimes in minutes.
However, there is a slight twist:

*

*exclude weekends

*only count minutes
which are between 7:00AM and 7:00PM.
for example:   [09/30/2010 6:39:00
PM] - [09/30/2010 7:39:00 PM] = 21
Minutes
I'm just having a hard time coming up with a decent way to do it and would appreciate if anyone can suggest something.
Thanks.

Edit:
I ended up going with dtb's solution. There is only one special case which needed to be taken care of:  if end time is after 7:00PM, count the minutes from 7:00AM to the actual end time.
This is how I modified it:
var minutes = from day in start.DaysInRangeUntil(end)
                where !day.IsWeekendDay()
                let st = Helpers.Max(day.AddHours(7), start)
                let en = (day.DayOfYear == end.DayOfYear ?
                            end :
                            Helpers.Min(day.AddHours(19), end)
                            )
                select (en - st).TotalMinutes;

Again, thanks for the help.

A: Take your start time, get the amount of minutes to the end of that day (Ie the 7pm).
Then from the 7am the next day, count the amount of days to the final day (excluding any time into the end day).
Calculate how many (If any) weekends have passed. (For every weekends reduce the count of days by 2).
Do some simple math from there to get the total minutes for the count of days.
Add the extra time on the final day and the start days extra time.

A: Try the following DiffRange function.
public static DateTime DayStart(DateTime date)
{
    return date.Date.AddHours(7);
}

public static DateTime DayEnd(DateTime date)
{
    return date.Date.AddHours(19);
}

public static TimeSpan DiffSingleDay(DateTime start, DateTime end)
{
    if ( start.Date != end.Date ) {
        throw new ArgumentException();
    }

    if (start.DayOfWeek == DayOfWeek.Saturday || start.DayOfWeek == DayOfWeek.Sunday )
    {
        return TimeSpan.Zero;
    }

    start = start >= DayStart(start) ? start : DayStart(start);
    end = end <= DayEnd(end) ? end : DayEnd(end);
    return end - start;
}

public static TimeSpan DiffRange(DateTime start, DateTime end)
{
    if (start.Date == end.Date)
    {
        return DiffSingleDay(start, end);
    }

    var firstDay = DiffSingleDay(start, DayEnd(start));
    var lastDay = DiffSingleDay(DayStart(end), end);

    var middle = TimeSpan.Zero;
    var current = start.AddDays(1);
    while (current.Date != end.Date)
    {
        middle = middle + DiffSingleDay(current.Date, DayEnd(current.Date));
        current = current.AddDays(1);
    }

    return firstDay + lastDay + middle;
}

A: You can, of course, use LINQ:
DateTime a = new DateTime(2010, 10, 30, 21, 58, 29);
DateTime b = a + new TimeSpan(12, 5, 54, 24, 623);

var minutes = from day in a.DaysInRangeUntil(b)
              where !day.IsWeekendDay()
              let start = Max(day.AddHours( 7), a)
              let end   = Min(day.AddHours(19), b)
              select (end - start).TotalMinutes;

var result = minutes.Sum();

// result == 6292.89

(Note: You probably need to check for a lot of corner cases which I completely ignored.)
Helper methods:
static IEnumerable<DateTime> DaysInRangeUntil(this DateTime start, DateTime end)
{
    return Enumerable.Range(0, 1 + (int)(end.Date - start.Date).TotalDays)
                     .Select(dt => start.Date.AddDays(dt));
}

static bool IsWeekendDay(this DateTime dt)
{
    return dt.DayOfWeek == DayOfWeek.Saturday
        || dt.DayOfWeek == DayOfWeek.Sunday;
}

static DateTime Max(DateTime a, DateTime b)
{
    return new DateTime(Math.Max(a.Ticks, b.Ticks));
}

static DateTime Min(DateTime a, DateTime b)
{
    return new DateTime(Math.Min(a.Ticks, b.Ticks));
}

A: I'm sure there's something I missed.
  TimeSpan CalcBusinessTime(DateTime a, DateTime b)
  {
     if (a > b)
     {
        DateTime tmp = a;
        a = b;
        b = tmp;
     }

     if (a.TimeOfDay < new TimeSpan(7, 0, 0))
        a = new DateTime(a.Year, a.Month, a.Day, 7, 0, 0);
     if (b.TimeOfDay > new TimeSpan(19, 0, 0))
        b = new DateTime(b.Year, b.Month, b.Day, 19, 0, 0);

     TimeSpan sum = new TimeSpan();
     TimeSpan fullDay = new TimeSpan(12, 0, 0);
     while (a < b)
     {
        if (a.DayOfWeek != DayOfWeek.Saturday && a.DayOfWeek != DayOfWeek.Sunday)
        {
           sum += (b - a < fullDay) ? b - a : fullDay;
        }
        a = a.AddDays(1);
     }

     return sum;
  }

A: It was a pretty hard question. For a basic, in a straightforward approach, I have written the below code:
DateTime start = new DateTime(2010, 01, 01, 21, 00, 00);
DateTime end = new DateTime(2010, 10, 01, 14, 00, 00);

// Shift start date's hour to 7 and same for end date
// These will be added after doing calculation:
double startAdjustmentMinutes = (start - start.Date.AddHours(7)).TotalMinutes;
double endAdjustmentMinutes = (end - end.Date.AddHours(7)).TotalMinutes;

// We can do some basic
// mathematical calculation to find weekdays count:
// divide by 7 multiply by 5 gives complete weeks weekdays
// and adding remainder gives the all weekdays:
int weekdaysCount = (((int)((end.Date - start.Date).Days / 7) * 5)
          + ((end.Date - start.Date).Days % 7));
// so we can multiply it by minutes between 7am to 7 pm
int minutes = weekdaysCount * (12 * 60);

// after adding adjustment we have the result:
int result = minutes + startAdjustmentMinutes + endAdjustmentMinutes;

I know this not seem programmatically beautiful but I don't know if it is good to iterate through days and hours between start and end.

A: static int WorkPeriodMinuteDifference(DateTime start, DateTime end)
{
    //easier to only have to work in one direction.
    if(start > end)
        return WorkPeriodMinuteDifference(end, start);
    //if weekend, move to start of next Monday.
    while((int)start.DayOfWeek % 6 == 0)
        start = start.Add(new TimeSpan(1, 0, 0, 0)).Date;
    while((int)end.DayOfWeek % 6 == 0)
        end = end.Add(new TimeSpan(1, 0, 0, 0)).Date;
    //Move up to 07:00 or down to 19:00
    if(start.TimeOfDay.Hours < 7)
        start = new DateTime(start.Year, start.Month, start.Day, 7, 0, 0);
    else if(start.TimeOfDay.Hours > 19)
        start = new DateTime(start.Year, start.Month, start.Day, 19, 0, 0);
    if(end.TimeOfDay.Hours < 7)
        end = new DateTime(end.Year, end.Month, end.Day, 7, 0, 0);
    else if(end.TimeOfDay.Hours > 19)
        end = new DateTime(end.Year, end.Month, end.Day, 19, 0, 0);

    TimeSpan difference = end - start;

    int weeks = difference.Days / 7;
    int weekDays = difference.Days % 7;
    if(end.DayOfWeek < start.DayOfWeek)
        weekDays -= 2;

    return (weeks * 5 * 12 * 60) + (weekDays * 12 * 60) + difference.Hours * 60 + difference.Minutes
}

A: My implementation :)  The idea is to quickly compute the total weeks, and walk the remaining week day by day...
public TimeSpan Compute(DateTime start, DateTime end)
{
    // constant start / end times per day
    TimeSpan sevenAM = TimeSpan.FromHours(7);
    TimeSpan sevenPM = TimeSpan.FromHours(19);

    if( start >= end )
    {
        throw new Exception("invalid date range");
    }

    // total # of weeks
    int completeWeeks = ((int)(end - start).TotalDays) / 7;

    // starting total
    TimeSpan total = TimeSpan.FromHours(completeWeeks * 12 * 5);

    // adjust the start date to be exactly "completeWeeks" past its original start
    start = start.AddDays(completeWeeks * 7);

    // walk days from the adjusted start to end (at most 7), accumulating time as we can...
    for(
        // start at midnight
        DateTime dt = start.Date;

        // continue while there is time left
        dt < end;

        // increment 1 day at a time
        dt = dt.AddDays(1)
    )
    {
        // ignore weekend
        if( (dt.DayOfWeek == DayOfWeek.Saturday) ||
             (dt.DayOfWeek == DayOfWeek.Sunday) )
        {
            continue;
        }

        // get the start/end time for each day...
        // typically 7am / 7pm unless we are at the start / end date
        TimeSpan dtStartTime = ((dt == start.Date) && (start.TimeOfDay > sevenAM)) ?
            start.TimeOfDay : sevenAM;
        TimeSpan dtEndTime = ((dt == end.Date) && (end.TimeOfDay < sevenPM)) ?
            end.TimeOfDay : sevenPM;

        if( dtStartTime < dtEndTime )
        {
            total = total.Add(dtEndTime - dtStartTime);
        }
    }

    return total;
}

A: Use TimeSpan.TotalMinutes, subtract non-business days, subtract superfluous hours.

A: I won't write any code, but having a DateTime you can tell the Day of the week, thus you know how many weekends are in your range, so you can tell how many minutes are in a weekend.
So it wouldn't be so hard... of course there must be an optimal one line solution... but i think you can get around with this one.
I forgot to mention that you also know the minutes btween 7:00 pm and 7:00 am so all you have to do is substract the right amount of minutes to the time difference you get.


text:
Q: jboss 6.4 add mime type i am trying to create a jsp page that has a video

Hello

<video width="400" controls>
  <source src="mov_bbb.mp4" type="video/mp4">
  <source src="mov_bbb.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

Video courtesy of
Big Buck Bunny.

this works in tomcat 8.5, but when i move it to my project in jboss 6.4
ie 11 throws the error
AUDIO/VIDEO: Unknown MIME type.

i added the Mime type to my projects web.xml as:
<mime-mapping>
    <extension>mp4</extension>
    <mime-type>video/mp4</mime-type>
</mime-mapping>

can i add the mimetype to the standalone.xml??
or what is my problem?

A: Note backup your standalone or domain xml files prior to trying this modification!
Undertow is actually part of JBoss EAP 7, for JBoss EAP 6 find this section in standalone.xml (if you're using standalone mode, if domain mode look for domain.xml)
    <subsystem xmlns="urn:jboss:domain:web:1.4" default-virtual-server="default-host" native="false">
        <connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http"/>
        <virtual-server name="default-host" enable-welcome-root="true">
            <alias name="localhost"/>
            <alias name="example.com"/>
        </virtual-server>
    </subsystem>

And add this entry
<configuration>
     <mime-mapping name="mp4" value="video/mp4"/>
 </configuration>

In the end, your web subsystem should look like this
    <subsystem xmlns="urn:jboss:domain:web:1.4" default-virtual-server="default-host" native="false">
        <connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http"/>
        <virtual-server name="default-host" enable-welcome-root="true">
            <alias name="localhost"/>
            <alias name="example.com"/>
        </virtual-server>
        <configuration>
            <mime-mapping name="mp4" value="video/mp4"/>
        </configuration>
    </subsystem>

Do not copy the entire section above verbatim and paste over what already exists as the web version, elements and attributes may be different, just add the configuration section.
Update - turns out I didn't really need to add the mime type headers, at least when testing in Chrome - the video showed fine on the webpage with the following directory structure (note though the OGG format didnt)

A: Finally got my answer. it turns out that right above where I inserted my MIME type there was a section with all the supported MIME types.
The correct way to set up the MIME type in my case was
<servlet-mapping>
    <servlet-name>fileserver</servlet-name>
    <url-pattern>*.mp4</url-pattern>
</servlet-mapping>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to bind XAML textbox to custom object? Okay I thought this is going to be a piece of cake, but obviously it is not for (I am a XAML/WPF newbie, btw)
I have got two WPF windows, say Window1 and EditCustomObjectWindow. The latter is needed to edit a CustomObject instance provided by Window1. (I have left out a lot of code irrelevant for this problem)
Window1.xaml.cs:
// first window, holding an instance of CustomObject
public partial class Window1 : Window {
    public CustomObject CustomObject {
        get;
        set;
    }

    void buttonClicked(object sender, RoutedEventArgs e) {
        new Windows(CustomObject).ShowDialog();
    }

}

EditCustomObjectWindow.xaml.cs:
public partial class EditCustomObjectWindow : Window {
    public CustomObject CustomObject {
        get;
        set;
    }
    public EditCustomObjectWindow (CustomObject customObject) {
        this.CustomObject = customObject;
    }

}

EditCustomObjectWindow.xaml:
<TextBox
        Height="22"
        Margin="5"
        Width="150"
        Text="{Binding Path=CustomObject.SomeProperty, Mode=TwoWay, PresentationTraceSources.TraceLevel=High}"></TextBox>

Of course, CustomObject has a public accessor for SomeProperty.
When clicking the button, the following information is traced to the output window. But somehow, I am not able to translate it to the source of the problem.
System.Windows.Data Warning: 54 : Created BindingExpression (hash=31654880) for Binding (hash=40799911)
System.Windows.Data Warning: 56 :   Path: 'CustomObject.SomeProperty'    System.Windows.Data Warning: 59 : BindingExpression (hash=31654880): Default update trigger resolved to LostFocus
System.Windows.Data Warning: 60 : BindingExpression (hash=31654880): Attach to
System.Windows.Controls.TextBox.Text (hash=58067579)
System.Windows.Data Warning: 65 : BindingExpression (hash=31654880): Resolving source
System.Windows.Data Warning: 68 : BindingExpression (hash=31654880): Found data context element: TextBox (hash=58067579) (OK)
System.Windows.Data Warning: 69 : BindingExpression (hash=31654880): DataContext is null
System.Windows.Data Warning: 63 : BindingExpression (hash=31654880): Resolve source deferred
System.Windows.Data Warning: 65 : BindingExpression (hash=31654880): Resolving source
System.Windows.Data Warning: 68 : BindingExpression (hash=31654880): Found data context element: TextBox (hash=58067579) (OK)
System.Windows.Data Warning: 69 : BindingExpression (hash=31654880): DataContext is null
System.Windows.Data Warning: 65 : BindingExpression (hash=31654880): Resolving source
System.Windows.Data Warning: 68 : BindingExpression (hash=31654880): Found data context element: TextBox (hash=58067579) (OK)
System.Windows.Data Warning: 69 : BindingExpression (hash=31654880): DataContext is null
System.Windows.Data Warning: 65 : BindingExpression (hash=31654880): Resolving source
System.Windows.Data Warning: 68 : BindingExpression (hash=31654880): Found data context element: TextBox (hash=58067579) (OK)
System.Windows.Data Warning: 69 : BindingExpression (hash=31654880): DataContext is null
System.Windows.Data Warning: 65 : BindingExpression (hash=31654880): Resolving source  (last chance)
System.Windows.Data Warning: 68 : BindingExpression (hash=31654880): Found data context element: TextBox (hash=58067579) (OK)
System.Windows.Data Warning: 76 : BindingExpression (hash=31654880): Activate with root item <null>
System.Windows.Data Warning: 104 : BindingExpression (hash=31654880):   Item at level 0 is null - no accessor
System.Windows.Data Warning: 101 : BindingExpression (hash=31654880): Replace item at level 1 with {NullDataItem}
System.Windows.Data Warning: 78 : BindingExpression (hash=31654880): TransferValue - got raw value {DependencyProperty.UnsetValue}
System.Windows.Data Warning: 86 : BindingExpression (hash=31654880): TransferValue - using fallback/default value ''
System.Windows.Data Warning: 87 : BindingExpression (hash=31654880): TransferValue - using final value ''

A: In your Binding you must set RelativeSource to ancestor EditCustomObjectWindow like this:
{Binding Path=CustomObject.SomeProperty, RelativeSource={RelativeSource AncestorType={x:Type local:EditCustomObjectWindow}}, Mode=TwoWay, PresentationTraceSources.TraceLevel=High}

A: The problem is that the instance you pass in to new EditCustomObjectWindow(CustomObject).ShowDialog);
is null.
It can be a little confusing to have properties that have the same names as types, maybe you ment  new EditCustomObjectWindow(new CustomObject()).ShowDialog);?
In the log you can see:
System.Windows.Data Warning: 76 : BindingExpression (hash=31654880): Activate with root item <null>
System.Windows.Data Warning: 104 : BindingExpression (hash=31654880):   Item at level 0 is null - no accessor
System.Windows.Data Warning: 101 : BindingExpression (hash=31654880): Replace item at level 1 with {NullDataItem}

telling us that the "first" property (CustomObject) is found, but that its null, so the value is replaced by a NullDataItem


text:
Q: TFS : How do you control signoff of test cases We are newbies to TFS (2015)  and one of the things we have noticed is the fact that you can mark an overall Test Case as "passed" without giving a reason or having any specific authority to do so.
This presents an issues for us, as you can mark a Test Case as "passed" even when:
 - Test steps have failed
 - Bugs have not been fixed
 - Test case have only partially been completed
 - No test steps have been run
What we really want to do is perform a supervisor review of the Test Case. We do this currently to check:
 - all bugs are addressed any marked as "fixed later" have a comments explaining
 - test evidence has been stored correctly
 - variance form test plan recorded as comment
We get audited on regular basis and supervisor review helps a lot, as an audit can can be on projects 2-4 years old, checking, recording decisions and reasons at the at the time of signing of test  off , just helps.
Question: Is there a way of controlling sign-off of a Test Case or Test Suite?
Forcing a comment to be entered or restricting access to marking Test Case as "passed" would be something

A: There is no (out of the box) way to explicitly control who can mark a test case as passed. Usually you would be able to configure such transitions using the Work Item Type Definition (WITD) by adding rules and constraints to a transitions. But since test results are not represented as work items this is not possible.
You can restrict access on a higher level, on test plans and test suites:

There might be a way to get it the way you want it using the TFS Server Object Model and building a server side validation, not sure if this is possible since I have never tried this (see: https://msdn.microsoft.com/en-us/library/bb130146(v=vs.120).aspx#ServerObjectModel). I would however try to avoid building a server side validation since it is on you to make sure it keeps working and might cause issues or blocking issues in a future upgrade for you. It would be a pity to get stuck on a version of TFS because of this.
Hope this helps!


text:
Q: How to add a user defined field and value to an elasticsearch query Goal: I want a query which adds a discriminator field to distinguish between fuzzy results and non-fuzzy results.
Consider these documents:
curl -X POST "localhost:9200/_bulk" -H 'Content-Type: application/json' -d'
{
    "index": {
        "_index": "dishes",
        "_type": "dish",
        "_id": "1"
    }
}
{
    "name": "butter chicken"
}
{
    "index": {
        "_index": "dishes",
        "_type": "dish",
        "_id": "2"
    }
}
{
    "name": "chicken burger"
}

'

Consider the following query:
curl -X POST "localhost:9200/dishes/_search?pretty" -H 'Content-Type: application/json' -d'
{
    "query": {
        "bool": {
            "should": [
                {
                    "term": {
                        "name": "burger"
                    }
                },
                {
                    "fuzzy": {
                        "name": {
                            "value": "burger"
                        }
                    }
                }
            ],
            "minimum_should_match": 1,
            "boost": 1.0
        }
    }
}
'

Can I have a result with an additional tag created during query (it is not in the document) that can be used to discriminate between what is a fuzzy result and what is a non-fuzzy result.

...

"hits" : [
    {
      "_index" : "dishes",
      "_type" : "dish",
      "_id" : "2",
      "_score" : 1.3862942,
      "_source" : {
        "name" : "chicken burger"
      },

"is_fuzzy": false

    },
    {
      "_index" : "dishes",
      "_type" : "dish",
      "_id" : "1",
      "_score" : 0.46209806,
      "_source" : {
        "name" : "butter chicken"
      },

"is_fuzzy": true

    }
  ]

Scripted fields could have been ideal. But no luck yet.
I have a requirement to present the non-fuzzy results before fuzzy results. So sorting on is_fuzzy and then _score is guaranteed to work. (The actual query is more complex.)
       sort: [
            {
                "is_fuzzy": {
                    "order": "desc"
                }
            },
            {
                "_score": {
                    "order": "desc"
                }
            }

A: One more option is to use named queries but your term filters will need to be slightly reworked:
GET dishes/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "term": {
            "name": {
              "value": "burger",
              "_name": "not_fuzzy"
            }
          }
        },
        {
          "fuzzy": {
            "name": {
              "value": "burger",
              "_name": "fuzzy"
            }
          }
        }
      ],
      "minimum_should_match": 1,
      "boost": 1
    }
  }
}

yielding
[
  {
    "_index":"dishes",
    "_type":"dish",
    "_id":"2",
    "_score":1.3862944,
    "_source":{
      "name":"chicken burger"
    },
    "matched_queries":[         <---
      "fuzzy",
      "not_fuzzy"
    ]
  },
  {
    "_index":"dishes",
    "_type":"dish",
    "_id":"1",
    "_score":0.46209806,
    "_source":{
      "name":"butter chicken"
    },
    "matched_queries":[         <---
      "fuzzy"
    ]
  }
]


text:
Q: php70-mongo install doctrine/mongodb-odm fails I try to install doctrine/mongodb-odm[1.0.5] over composer but drops me
  Problem 1
    - doctrine/mongodb 1.3.0 requires ext-mongo ^1.5 -> the requested PHP extension mongo is missing from your system.
    - doctrine/mongodb 1.2.2 requires ext-mongo ^1.2.12 -> the requested PHP extension mongo is missing from your system.
    - doctrine/mongodb 1.2.1 requires ext-mongo ^1.2.12 -> the requested PHP extension mongo is missing from your system.
    - doctrine/mongodb 1.2.0 requires ext-mongo ^1.2.12 -> the requested PHP extension mongo is missing from your system.
    - doctrine/mongodb-odm 1.0.5 requires doctrine/mongodb ~1.2 -> satisfiable by doctrine/mongodb[1.2.0, 1.2.1, 1.2.2, 1.3.0].
    - Installation request for doctrine/mongodb-odm ~1.0.5 -> satisfiable by doctrine/mongodb-odm[1.0.5].

mongo extension is already installed
php -i | grep mongo

/usr/local/etc/php/7.0/conf.d/ext-mongodb.ini
mongodb
mongodb support => enabled
mongodb version => 1.1.6
mongodb stability => stable
libmongoc version => 1.3.5
mongodb.debug => no value => no value

what went wrong in this case?

A: PHP has 2 extensions for MongoDB:

*

*The legacy one found at http://php.net/manual/en/book.mongo.php

*The current one http://php.net/manual/en/set.mongodb.php
In case of "doctrine/mongodb-odm" it expects to find the legacy one "mongo" but what you have installed is the newer one "mongodb".
In order to use the legacy extension you need to use php <= 5.6, for php 7 only mongodb is available.

A: On PHP7 you have mongodb extension as @xaben mentioned. You can use this with doctrine until it support mongodb but by installing additional library https://github.com/alcaeus/mongo-php-adapter
First install via composer:
composer require alcaeus/mongo-php-adapter

and later install doctrine. It's works very well in my case.

A: I had the problem , but install and config symfony 3.1 with php 5.6 and mysql , After  need installer mongodb, so udpate 7.1
problem composer.json :
"config": {
    "platform": {"php": "5.6"}
}

Change:
"config": {
    "platform": {"php": "7.1"}
}


text:
Q: Change size of an image appearing by hovering over text css I have a text on which when you hover (or when you click on it on mobile), a picture appear. I used this stackoverflow answer to make it work.
I'm now trying to make the picture change size automatically, so the picture fit both on mobile and computer.

a.hovertext1:after {
  content: 'Text that appears before I hover.';
}

a.hovertext1:hover:after,
a.hovertext1:focus:after {
  content: url(https://cdn.discordapp.com/attachments/1074330512925143102/1076897722075971675/5226579-le-drapeau-national-de-la-republique-federative-du-bresil-fond-d-ecran-du-drapeau-bresilien-avec-des-styles-de-degrade-d-ombre-gratuit-vectoriel.jpg);
  display: block;
}

I know I need to add width:100%; somewhere in my code, but I have no idea where. I tried putting it in the a.hovertext1:focus:after{...} block, but it didn't do anything.
Hope someone can help me!

A: Is there any reason for which you want to use pseudo elements ? There is a different approach using simple display property on hover.

img {
  display: none;
  width: 100%;
}

a:hover + img {
  display: block;
}

a:hover {
  display: none;
}
Text that appears before I hover

Also I suggest to use buttons instead of links. Buttons are used for actions that affect the website's front-end; links are used for navigation and actions that don't affect the website.


text:
Q: how to continue a loop despite error in parsing byte data my question is a continuation of this: (loop for reading different data types & sizes off very large byte array from file)
I have a raw byte stream stored on a file (rawbytes.txt or bytes.data) that I need to parse and output to a CSV-style text file.
The input of raw bytes (when read as characters/long/int etc.) looks something like this:
A2401028475764B241102847576511001200C...

Parsed it should look like:
OutputA.txt
(Field1,Field2,Field3) - heading

A,240,1028475764

OutputB.txt
(Field1,Field2,Field3,Field4,Field5) - heading

B,241,1028475765,1100,1200

OutputC.txt
C,...//and so on

Essentially, it's a hex-dump-style input of bytes that is continuous without any line terminators or gaps between data that needs to be parsed. The data, as seen above, consists of different data types one after the other.
Here's a snippet of my code - because there are no commas within any field, and no need arises to use "" (i.e. a CSV wrapper), I'm simply using TextWriter to create the CSV-style text file as follows:
if (File.Exists(fileName))
        {
        using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
            {
        while (reader.BaseStream.Position != reader.BaseStream.Length)
            {
                inputCharIdentifier = reader.ReadChar();
                switch (inputCharIdentifier)
                     case 'A':

                        field1 = reader.ReadUInt64();
                        field2 = reader.ReadUInt64();
                        field3 = reader.ReadChars(10);
                        string strtmp = new string(field3);
                        //and so on
                        using (TextWriter writer = File.AppendText("outputA.txt"))
                        {
                            writer.WriteLine(field1 + "," + field2 + "," + strtmp); // +
                        }
                        case 'B':
                        //code...

My question is based on the fact that some of the raw byte data contains null values, which are difficult to parse through - because there are an unknown number of null bytes (or non-null, out-of-place bytes) between consecutive data blocks (each starting with A, B or C if the data blocks are not corrupt).
QUESTION
So, how do I add a default case or some other mechanism to continue with the loop despite an error that might arise because of corrupt or faulty data? Is the following code something that would work?
    inputCharIdentifier = reader.ReadChar();
    ...
    case default:
    //I need to know what to add here, instead of default
    //(i.e. the case when the character could not be read)
    while (binReader.PeekChar() != -1)
    {
         filling = binReader.readByte();
         //filling is a single byte
         try {
             fillingChar = Convert.ToChar(filling);

             break;
         }
         catch (Exception ex) { break; }
         if (fillingChar == 'A' || fillingChar == 'B')
             break;

The remaining part - adding code to each switch case (eg 'A') to continue without stopping the program - is there a way to do this without multiple try-catch blocks? [i.e. the code block character identifier is A, but the bytes after A are corrupt - in which case i need to exit the loop OR read (i.e. skip over) a defined number of bytes - which here, would be known if the message header correctly identifies the remaining bytes.
[Note: Case A, B and so on have different sized input - in other words, A might be 40 bytes total, while B is 50 bytes. So the use of a fixed size buffer, say inputBuf[1000], or [50] for instance - if they were all the same size - wouldn't work well either, AFAIK.]
Any suggestions? Please help! I'm relatively new to C# (2 months)...
Update: my entire code is as follows:
         class Program
{
    const string fileName = "rawbytes.txt";
    static void Main(string[] args)
    {
                    try
        {
            var program = new Program();
            program.Parser();
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
        Console.ReadLine();
    }
    public void Parser()
    {
        char inputCharIdentifier = 'Z';
        //only because without initializing inputCharIdentifier I ended up with an error
        //note that in the real code, 'Z' is not a switch-case alphabet
        //it's an "inconsequential character", i.e. i have defined it to be 'Z'
        //just to avoid that error, and to avoid leaving it as a null value
        ulong field1common = 0;
        ulong field2common = 0;
        char[] charArray = new char[10];
        char char1;
        char char2;
        char char3;
        int valint1 = 0;
        int valint2 = 0;
        int valint3 = 0;
        int valint4 = 0;
        int valint5 = 0;
        int valint6 = 0;
        int valint7 = 0;
        double valdouble;
        /*
        char[] filler = new char[53];
        byte[] filling = new byte[4621];
        byte[] unifiller = new byte[8];
        //these values above were temporary measures to manually filter through
        //null bytes - unacceptable for the final program
        */
        if (File.Exists(fileName))
        {
            using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open)))
            {
                while (reader.BaseStream.Position != reader.BaseStream.Length)
                {
                    //inputCharIdentifier = reader.ReadChar();
                    //if (inputCharIdentifier != null)
                    //{
                        try
                        {
                            inputCharIdentifier = reader.ReadChar();
                            try
                            {
                                switch (inputCharIdentifier)
                                {
                                    case 'A':

                                        field1common = reader.ReadUInt64();
                                        field2common = reader.ReadUInt64();
                                        //unifiller = reader.ReadBytes(8);
                                        //charArray = reader.ReadString();
                                        //result.ToString("o");
                                        //Console.WriteLine(result.ToString());
                                        charArray = reader.ReadChars(10);
                                        string charArraystr = new string(charArray);
                                        char1 = reader.ReadChar();
                                        valint1 = reader.ReadInt32();
                                        valint2 = reader.ReadInt32();
                                        valint3 = reader.ReadInt32();
                                        valint4 = reader.ReadInt32();
                                        using (TextWriter writer = File.AppendText("A.txt"))
                                        {
                                            writer.WriteLine(field1common + "," + /*result.ToString("o")*/ field2common + "," + charArraystr + "," + char1 + "," + valint1 + "," + valint2 + "," + valint3 + "," + valint4);
                                            writer.Close();
                                        }
                                        break;

                                    case 'B':
                                    case 'C':

                                        field1common = reader.ReadUInt64();
                                        field2common = reader.ReadUInt64();
                                        //charArray = reader.ReadString();
                                        charArray = reader.ReadChars(10);
                                        string charArraystr2 = new string(charArray);
                                        char1 = reader.ReadChar();
                                        valint1 = reader.ReadInt32();
                                        valint2 = reader.ReadInt32();
                                        using (TextWriter writer = File.AppendText("C.txt"))
                                        {
                                            writer.WriteLine(field1common + "," + result2.ToString("o") + "," + charArraystr2 + "," + char1 + "," + valint1 + "," + valint2);
                                            writer.Close();
                                        }
                                        break;
                                    case 'S':
                                        //market status message
                                        field1common = reader.ReadUInt64();
                                        char2 = reader.ReadChar();
                                        char3 = reader.ReadChar();
                                        break;
                                    case 'L':
                                        filling = reader.ReadBytes(4);
                                        break;
                                    case 'D':
                                    case 'E':
                                        field1common = reader.ReadUInt64();
                                        field2common = reader.ReadUInt64();
                                        //charArray = reader.ReadString();
                                        charArray = reader.ReadChars(10);
                                        string charArraystr3 = new string(charArray);
                                        //char1 = reader.ReadChar();
                                        valint1 = reader.ReadInt32();
                                        valint2 = reader.ReadInt32();
                                        valint5 = reader.ReadInt32();
                                        valint7 = reader.ReadInt32();
                                        valint6 = reader.ReadInt32();
                                        valdouble = reader.ReadDouble();
                                        using (TextWriter writer = File.AppendText("D.txt"))
                                        {
                                            writer.WriteLine(field1common + "," + result3.ToString("o") + "," + charArraystr3 + "," + valint1 + "," + valint2 + "," + valint5 + "," + valint7 + "," + valint6 + "," + valdouble);
                                            writer.Close();
                                        }
                                        break;
                                    }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Parsing didn't work");
                                Console.WriteLine(ex.ToString());
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Here's why the character read attempt didn't work");
                            Console.WriteLine(ex.ToString());

                            continue;
                            //continue;
                        }
                    //}
                }
            }
            }
            }

The error I receive is as follows:
    Here's why the character read attempt didn't work

    System.ArgumentException: The output char buffer is too small to contain the decoded characters, encoding 'Unicode (UTF-8)' fallback 'System.Text.DecoderReplacementFallback'.
    Parameter name: chars
    at System.Text.Encoding.ThrowCharsOverflow()
    at System.Text.Encoding.ThrowCharsOverflow(DecoderNLS decoder, Boolean nothingDecoded)
    at System.Text.UTF8Encoding.GetChars(Byte* bytes, Int32 byteCount, Char* chars, Int32 charCount, DecoderNLS baseDecoder)
    at System.Text.DecoderNLS.GetChars(Byte* bytes, Int32 byteCount, Char* chars, Int32 charCount, Boolean flush)
    at System.Text.DecoderNLS.GetChars(Byte[] bytes, Int32 byteIndex, Int32 byteCount, Char[] chars, Int32 charIndex, Boolean flush)
    at System.Text.DecoderNLS.GetChars(Byte[] bytes, Int32 byteIndex, Int32 byteCount, Char[] chars, Int32 charIndex)
    at System.IO.BinaryReader.InternalReadOneChar()
    at System.IO.BinaryReader.Read()
    at System.IO.BinaryReader.ReadChar()
    at line 69: i.e. inputCharIdentifier = reader.ReadChar();

Update: A sample file that generates the same error above is at the following link:
http://www.wikisend.com/download/106394/rawbytes.txt
Notice in particular the 8 unexpected null bytes between successive data blocks, even though the data block header - i.e. inputCharIdentifier - is valid. The number of bytes that follows such a header is always unpredictable and generally varies. My issue is that I need to be able to either delete or skip over such a situation when it arises to the next non-corrupt data block available - in the case of the sample file, the last (single) data block that occurs after the 8 out-of-place null bytes.
The 8 null bytes can be located in the file as follows:
Byte Counter: 1056
Line 2, Column 783 (according to Notepad++)
The crux of the problem is that the 8 null bytes can be any size - 3, 7, 15, 50, etc. It is always unknown - as a direct result of data corruption. But unlike "traditional" data corruption, i.e. where a fixed number of bytes, say 50, inside a data block that might be unreadable and can therefore be skipped over (by that exact number of bytes) - the data corruption i face consists of an unknown number of bytes between valid data blocks.

A: You cannot assign a case for these situations because the target variable (inputCharIdentifier) is null; thus it is enough with a condition avoiding these cases. I have also included a try...catch, just to make completely sure (any error while performing all the given actions would make the code to automatically skip to the following iteration).
try
{
    using (BinaryReader reader = new BinaryReader(File.Open(fileName, FileMode.Open), Encoding.ASCII))
    {
        while (reader.BaseStream.Position != reader.BaseStream.Length)
        {
            inputCharIdentifier = reader.ReadChar();
            if(inputCharIdentifier != null)
            {
               switch (inputCharIdentifier)
                 case 'A':
                    field1 = reader.ReadUInt64();
                    field2 = reader.ReadUInt64();
                    field3 = reader.ReadChars(10);
                    string strtmp = new string(field3);
                    //and so on
                    using (TextWriter writer = File.AppendText("outputA.txt"))
                    {
                       writer.WriteLine(field1 + "," + field2 + "," + strtmp);
                    }
                 case 'B':
                   //code...
            }
        }
    }
}
catch
{
}


text:
Q: Can someone tell me what Strong typing and weak typing means and which one is better? Can someone tell me what Strong typing and weak typing means and which one is better?

A: That'll be the theory answers taken care of, but the practice side seems to have been neglected...
Strong-typing means that you can't use one type of variable where another is expected (or have restrictions to doing so). Weak-typing means you can mix different types. In PHP for example, you can mix numbers and strings and PHP won't complain because it is a weakly-typed language.
$message = "You are visitor number ".$count;

If it was strongly typed, you'd have to convert $count from an integer to a string, usually with either with casting:
$message = "you are visitor number ".(string)$count;

...or a function:
$message = "you are visitor number ".strval($count);

As for which is better, that's subjective. Advocates of strong-typing will tell you that it will help you to avoid some bugs and/or errors and help communicate the purpose of a variable etc. They'll also tell you that advocates of weak-typing will call strong-typing "unnecessary language fluff that is rendered pointless by common sense", or something similar. As a card-carrying member of the weak-typing group, I'd have to say that they've got my number... but I have theirs too, and I can put it in a string :)

A: I would like to reiterate that weak typing is not the same as dynamic typing.
This is a rather well written article on the subject and I would definitely recommend giving it a read if you are unsure about the differences between strong, weak, static and dynamic type systems. It details the differences much better than can be expected in a short answer, and has some very enlightening examples.
http://en.wikipedia.org/wiki/Type_system

A: Strong typing is the most common type model in modern programming languages. Those languages have one simple feature - knowing about type values in run time. We can  say that strong typed languages prevent mixing operations between two or more different kind of types. Here is an example in Java:
String foo = "Hello, world!";
Object obj = foo;

String bar = (String) obj;
Date baz = (Date) obj; // This line will throw an error

The previous example will work perfectly well until program hit the last line of code where the ClassCastException is going to be thrown because Java is strong typed programming language.
When we talk about weak typed languages, Perl is one of them. The following example shows how Perl doesn't have any problems with mixing two different types.
$a = 10;
$b = "a";
$c = $a . $b;
print $c; # returns 10a

I hope you find this useful,
Thanks.

A: This article is a great read: http://blogs.perl.org/users/ovid/2010/08/what-to-know-before-debating-type-systems.html Cleared up a lot of things for me when researching trying to answer a similar question, hope others find it useful too.
Strong and Weak Typing:

Probably the most common way type systems are classified is "strong"
  or "weak." This is unfortunate, since these words have nearly no
  meaning at all. It is, to a limited extent, possible to compare two
  languages with very similar type systems, and designate one as having
  the stronger of those two systems. Beyond that, the words mean nothing
  at all.

Static and Dynamic Types

This is very nearly the only common classification of type systems
  that has real meaning. As a matter of fact, it's significance is
  frequently under-estimated [...] Dynamic and static type systems are
  two completely different things, whose goals happen to partially
  overlap.
A static type system is a mechanism by which a compiler examines
  source code and assigns labels (called "types") to pieces of the
  syntax, and then uses them to infer something about the program's
  behavior. A dynamic type system is a mechanism by which a compiler
  generates code to keep track of the sort of data (coincidentally, also
  called its "type") used by the program. The use of the same word
  "type" in each of these two systems is, of course, not really entirely
  coincidental; yet it is best understood as having a sort of weak
  historical significance. Great confusion results from trying to find a
  world view in which "type" really means the same thing in both
  systems. It doesn't.

Explicit/Implicit Types:

When these terms are used, they refer to the extent to which a
  compiler will reason about the static types of parts of a program. All
  programming languages have some form of reasoning about types. Some
  have more than others. ML and Haskell have implicit types, in that no
  (or very few, depending on the language and extensions in use) type
  declarations are needed. Java and Ada have very explicit types, and
  one is constantly declaring the types of things. All of the above have
  (relatively, compared to C and C++, for example) strong static type
  systems.

A: "Strong typing" and its opposite "weak typing" are rather weak in meaning, partly since the notion of what is considered to be "strong" can vary depending on whom you ask. E.g. C has been been called both "strongly typed" and "weakly typed" by different authors, it really depends on what you compare it to.
Generally a type system should be considered stronger if it can express the same constraints as another and more. Quite often two type systems are not be comparable, though -- one might have features the other lacks and vice versa. Any discussion of relative strengths is then up to personal taste.
Having a stronger type system means that either the compiler or the runtime will report more errors, which is usually a good thing, although it might come at the cost of having to provide more type information manually, which might be considered effort not worthwhile. I would claim "strong typing" is generally better, but you have to look at the cost.
It's also important to realize that "strongly typed" is often incorrectly used instead of "statically typed" or even "manifest typed". "Statically typed" means that there are type checks at compile-time, "manifest typed" means that the types are declared explicitly. Manifest-typing is probably the best known way of making a type system stronger (think Java), but you can add strength by other means such as type-inference.

A: Strong/weak typing in a language is related to how easily you can do type conversions:
For example in Python:
str = 5 + 'a'
# would throw an error since it does not want to cast one type to the other implicitly.

Where as in C language:
int a = 5;
a = 5 + 'c';
/* is fine, because C treats 'c' as an integer in this case */

Thus Python is more strongly typed than C (from this perspective).

A: May be this can help you to understand Strong and Weak Typing.......
Strong typing: It checks the type of variables  as soon as possible, usually at compile time. It  prevents mixing operations between mismatched types.
A strong-typed programming language is one in which:

*

*All variables (or data types) are known at compile time

*There is strict enforcement of typing rules (a String can't be used
where an Integer would be expected)

*All exceptions to typing rules results in a compile time error

Weak Typing: While weak typing is delaying checking the types of the system as late as possible, usually to run-time. In this you can mix types without an explicit conversion.
A "weak-typed" programming language is simply one which is not strong-typed.
which is preferred depends on what you want. for scripts and good stuff you will usually want weak typing, because you want to write as much less code as possible. in big programs, strong typing can reduce errors at compile time.

A: Weak typing means that you don't specify what type a variable is, and strong typing means you give a strict type to each variable.
Each has its advantages, with weak typing (or dynamic typing, as it is often called), being more flexible and requiring less code from the programmer. Strong typing, on the other hand, requires more work from the developer, but in return it can alert you of many mistakes when compiling your code, before you run it. Dynamic typing may delay the discovery of these simple problems until the code is executed.
Depending on the task at hand, weak typing may be better than strong typing, or vice versa, but it is mostly a matter of taste. Weak typing is commonly used in scripting languages, while strong typing is used in most compiled languages.


text:
Q: splinter web error from splinter import Browser
with Browser() as browser:
  browser.visit("http://www.google.co.uk")
  browser.fill('q', 'Testing')
  browser.find_by_name('Submit').click()

That code opens up Firefox and gives me an error Url is not valid.

A: I do not think this is any issue with the code, rather it is the versions of Python/Splinter/Selenium/browser/webdriver (there are a lot of components at play)
This should be working.
from splinter import Browser
url = 'https://www.google.co.uk/?gws_rd=ssl'
with Browser() as browser:
  browser.visit(url)
  browser.fill('q', 'Testing\n')

If this is helpful, here are my versions:
Python: 3.3.5
Splinter: 0.7.2
Selenium: 2.45.0
Browser: Chrome
Webdriver: 2.25

If you are unsure of which versions you have of selenium and splinter, here's an easy way to check:
import pkg_resources
pkg_resources.get_distribution("splinter").version
>>> 0.7.2


text:
Q: JavaFX select item in org.controlsfx.control.GridView.GridView How do I select item like ListView to handler clickListener? is there gridView sample?love u
        ObservableList<Image> images = FXCollections.<Image>observableArrayList(list);

        GridView<Image> gridView = new GridView<Image>(images);
        gridView.setOnMouseClicked(new EventHandler<MouseEvent>(){

            @Override
            public void handle(MouseEvent event) {
                //TODO
            }
        });

        gridView.setCellFactory(new Callback<GridView<Image>, GridCell<Image>>() {

            @Override
            public GridCell<Image> call(GridView<Image> param) {

                return new ImageGridCell() ;
            }

         });

How do I select item like ListView to handler clickListener?

A: You can just do it like this as a simple way.
class ImageCell extends GridCell<String>{
    ImageCell(){
      setOnMouseClicked(new EventHandler<Event>() {

        @Override
        public void handle(Event event) {
            // TODO Auto-generated method stub
            if (((MouseEvent) event).getClickCount() >= 2) {
                  //do something when it's clicked

            }

         }
      });
    }
    protected void updateItem(String item, boolean empty) {
        // TODO Auto-generated method stub
        super.updateItem(item, empty);
        if (!empty) {
            // you can set content of cell here just as you do in
            //javaFX apllcation
            // and call setGraphic(root) eventually.
            // you can also call setOnAction on sub node in root rather
            // than do it in constructor.
        }
    }

}


text:
Q: Java JUnit: Reset SSLContext in JUnit Test I'm writing some methods to manipulate the SSLContext. I wrote JUnit-Test to test the functionality. Unfortunately I'm stuck, because I can't find a way to reset the SSLContext. So I have to run every test on it's own within it's own JVM, because the affect of previous test will affect the next test. The SSLContext seams not to be resetable, because it is not written in a DI manner.
Is there a way to reset the SSLContext?
Is there a way to run every JUnit-Test in its own JVM? (I use Maven as Build-Management-Tool)
This won't work This will only partly work:
SSLContext defaultSSLContext = SSLContext.getDefault();

// manipulate SSLContext

SSLContext.setDefault(defaultSSLContext);

Edit 2017-02-02
My Java Installation was broken
My Java installtion was broken, so in my case the default SSLContext was null (null == SSLContext.getDefault()). So I could not set the SSLContext. The method raises a NullPointerException. I reinstalled Java and now the SSLContext is working again and the default SSLContext will not be null.
Reseting the SSLContext
Storing the SSLContext in an interim variable and restoring it afterwards will work for the SSLContext. But not for implementation like java.net.URL. These implementations seam to keep a Singleton instance of the SSLContext from the first call and will never change it during the runtime of the JVM.
JUnit forked Run with Maven
I followed Stefan Birkner's proposal and used Maven Surefire Plugin.
I added in the project pom.xml:
</plugins>
    [...]
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.19.1</version>
        <configuration>
            <reuseForks>false</reuseForks>
            <forkCount>2</forkCount>
        </configuration>
    </plugin>
</plugins>

I split the JUnit Test into parts, that could run on their own without interfering. So FooTest.java became Foo01Test.java ... Foo03Test.java. Now the tests are running within Eclipse and with Maven.

A: The Maven Surefire Plugin allows you to specify that a new JVM is used for each test: https://maven.apache.org/surefire/maven-surefire-plugin/examples/fork-options-and-parallel-execution.html


text:
Q: Fill a portion of a list in Python / Equivalent of std::fill I was just wondering if there is a clean solution in python to filling a portion of a list with some value (apart from simply iterating over the sublist). E.g., in C++ I would use std::fill. So far, I found the following syntax:
x = [0]*10       # some array
x[2:5] = [7]*3

A solution using numpy would be fine as well.

A: You can use np.repeat:
import numpy as np

x = np.repeat(0, 10)
x[2:5] = np.repeat(7, 3)

A: Each class has its own methods.  For numpy`
x = np.zeros(10, int)

makes an array of zeros.
x[2:7] = 3

assigns 3 to a portion of it.
That's similar to your list example, but critically different in some ways.  List slice assignment is different from numpy's.


text:
Q: Displaying the actual value of the field in textbox Im making an insert record code in php then i need to make a auto code, or the user just can look at the prepared value of the textbox, Ill just use this code.
$ayos = mysql_fetch_array(mysql_query("select ib_code from item_brand order by ib_code desc limit 1"));
            $new_val = $ayos['ib_code'] + 1;

when you display it just use:
echo $ayos['ib_code'];

for example the output is 006. the thing i cant resolve was when i try to display value of $new_val in the textbox, for sure our expected result if the $ayos['ib_code'] = 006 then the $new_val is equal to 007, but the problem is it is only 7 not 007, when displaying inside the textbox.. thx

A: Try
if you want to display a number left-padded with zeros, consider using printf() (or one of its numerous relatives).
Tested Example:
<?php
    $a = '006';
    $b = $a + 1;
?>
<input type="text" value="<?php printf("%03d", $b); ?>" />
Above code is tested.
sprintf() can do that:
echo sprintf('%03d', $ayos['ib_code']);

Or use str_pad() - but that's a little bit longer in code:
echo str_pad($ayos['ib_code'], 3, 0, STR_PAD_LEFT);

Response to Some User Comment
well if there are value like 0006 or 000006 then we can use above code is as below.
<?php
    $a = '000006';
    $b = $a + 1;
?>
<input type="text" value="<?php printf("%0".strlen($a)."d", $b); ?>" />
what i am doing is passing length dynamically so if in future number size increase code will still work as expected.

A: Using the + operator forces PHP to interpret the variable as a number, which will truncate any leading zeroes. You'll have to do some interesting string manipulation most likely.

A: The 006 ins converted to number and after that it adds 1 to it, It becomes 7 , When it becomes number it truncates zeros from left side.Use below code, it will pad 0 to left.
echo str_pad($ayos['ib_code'], 3, "0", STR_PAD_LEFT); //becomes 007

A: Use $realnumber = intval($new_val);
echo  $realnumber;

A: Assign $new_val variable like below:
//GET count of leading 0's into variable
$leading_zero_count = strspn($ayos['ib_code'], "0");
$new_val = $ayos['ib_code']+1;
/**
  * Pad the $new_val variable with 0's so that
  * new length = total leading 0's + new length of $new_val
**/
$new_val = str_pad ($new_val, $leading_zero_count+strlen($new_val),0, STR_PAD_LEFT);


text:
Q: Is there any rigorous treatment of Markov Decision Process? I am trying to find a mathematically rigorous introduction to MDP.
There are tons of resouces online but all of them are ... frankly terrible (and not even properly typesetted).
Just picking a few: top three links Google returns for "MDP tutorials"
https://engineering.purdue.edu/~givan/talks/mdp-tutorial.pdf
http://www.cs.cmu.edu/~./awm/tutorials/mdp09.pdf
https://hub.packtpub.com/reinforcement-learning-mdp-markov-decision-process-tutorial/
I don't know why, but they all read something like:

A MDP is a tuple $(S,A,R,P)$ (sometimes $(S,A,R,P,\pi)$, or
  $(S,A,R,P,\pi,\gamma)$ or $(S,A,R,P,\pi,\gamma, T)$) where $S$ is a set of states, $A$ is a set of
  action, $R$ is (depending on who the author is) a determinstic function, a set containing a finite set of values, or a probability distribution over the
  action and the states, $P$ is a conditional probability or sometimes
  conditional probability distribution.

In addition, almost all of the references use different notations (various subscripts and superscripts will be added) and have different assumptions and they are all called MDP. I just want one standard reference that eliminates all these ambiguities and conflicting definitions.


text:
Q: Displaying HTML encoded styling in WPF I get a string from database that includes a HTML styling (not sure what it's called) and I wan't to display it in my WPF app.
I can decode in the ViewModel so I can use the .net library.
I tried using WebUtility.HtmlDecode(string) method but it doesn't do anything (and probably isn't supposed to).
this is what the string might look like:
This
is

a

weird

look

Getting just the text I could do with a little XML coding but I'd rather use something that already exists. Being able to get the styles as well would be great but I'm not looking towards including the WinForms browser thingy.
Notice I only need to display the data, not edit it.

A: This has nothing to do with encoding, this is about conversion. If you don't want to use the WebBrowser control you need to convert from HTML to flow content which can be displayed in a FlowDocument. You can either write the necessary code yourself or see if this converter which converts both ways (or any other existing converter for that matter) fits your needs.

You don't necessarily need a proper HTML page to make the WebBrowser display it, you can just do this:
string htmlString = "This
is

a

weird

look

";
wb.NavigateToString(htmlString);

But ideally you can wrap your incomming string in a proper html-frame first, which should be rather easy to do.


text:
Q: Permanent redirect after removing html extension in htaccess I have these htaccess rules to remove html extension from urls:
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html

It works fine but I can still access from the URL with extension. How to make it so that when a user click the url with extension, will be redirected with a permanent (301) redirect to the extensionless url?
Thanks

A: Just add the little snippet at the end which indicates it is a 301 redirect.
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [R=301,L]


text:
Q: ActionListener to trigger on text input from JTextField I would like to ask the user a question through a JTextArea, and have the answer evaluated inside of an ActionListener. Here is my (example) code:
textField.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            final String text = textField.getText();
            textArea.setText("Is your favorite color Red?");
            if (text.replaceAll("'", "").toLowerCase().contains("yes")){
                textArea.setText("Cool!");
            }else if (text.replaceAll("'", "").toLowerCase().equals("no")){
                textArea.setText(":(");
            }
        }
    });

The problem is that because there are other questions, whenever the user types "yes", the response is "Cool!". I want it to only say "Cool!" when the answer is "yes" and the question is "Is your favorite color Red?".

A: You're operating in an event driven environment, so you need to ask the question and wait for a response from the user.
Think about it a little differently.  You have a "question", which has prescribed output in response to user input.
What you need is some way to associate the response from the question with the question, lucky for us, Java is a OO language...
Start with some concept of question
public interface Question {
    public String getPrompt();
    public String getResponse(String input);
}

public abstract class AbstractQuestion implements Question {

    private String prompt;

    public AbstractQuestion(String prompt) {
        this.prompt = prompt;
    }

    @Override
    public String getPrompt() {
        return prompt;
    }

}

Now, we need some way to apply the current question...
private JTextArea ta;
//...
private Question question;
//...
public void setQuestion(Question q) {
    if (question != q) {
        question = q;
        if (question != null) {
            ta.append(question.getPrompt() + "\n");
            ta.setCaretPosition(ta.getDocument().getLength());
        }
    }
}

Now, when the ActionListener, we need to ask the Question for the response to the input...
@Override
public void actionPerformed(ActionEvent e) {
    if (question != null) {
        String response = question.getResponse(tf.getText().trim());
        ta.append(response + "\n");
        ta.setCaretPosition(ta.getDocument().getLength());
    }
}

This way, you can control the response based on the current Question
For example...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JTextArea ta;
        private JTextField tf;

        private Question question;

        public TestPane() {
            setLayout(new BorderLayout());
            ta = new JTextArea(10, 30);
            ta.setEditable(false);
            add(new JScrollPane(ta));

            tf = new JTextField(10);
            add(tf, BorderLayout.SOUTH);

            tf.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    if (question != null) {
                        String response = question.getResponse(tf.getText().trim());
                        ta.append(response + "\n");
                        ta.setCaretPosition(ta.getDocument().getLength());
                    }
                }
            });

            setQuestion(new AbstractQuestion("Is your favorite color Red?") {
                @Override
                public String getResponse(String input) {
                    String response = "To bad, mine is";
                    if ("yes".equalsIgnoreCase(input)) {
                        response = "Cool!";
                    }
                    return response;
                }
            });
        }

        public void setQuestion(Question q) {
            if (question != q) {
                question = q;
                if (question != null) {
                    ta.append(question.getPrompt() + "\n");
                    ta.setCaretPosition(ta.getDocument().getLength());
                }
            }
        }

    }

    public interface Question {

        public String getPrompt();

        public String getResponse(String input);
    }

    public abstract class AbstractQuestion implements Question {

        private String prompt;

        public AbstractQuestion(String prompt) {
            this.prompt = prompt;
        }

        @Override
        public String getPrompt() {
            return prompt;
        }

    }

}

This kind of approach decouples the UI/user input from the logic of the question and allows you to isolate the responsibility for generating the response to the instance of the question, allowing you to make a potentially unlimited number of questions with out the need to generate a very long list of if-else statements

A: Try something like
String question = "Is your favorite color Red?";
textArea.setText(question);
if(textArea.getText().equals(question))
{
        if (text.replaceAll("'", "").toLowerCase().contains("yes")){
            textArea.setText("Cool!");
        }else if (text.replaceAll("'", "").toLowerCase().equals("no")){
            textArea.setText(":(");
        }
}

A: You are setting the text area to "Is your favorite color Red?", but then later replacing that with "Cool!".  Instead, you should use something like the following so that you only set the text of the JTextArea once with everything you need.
textField.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
         final String text = textField.getText();

         StringBuilder sb = new StringBuilder();
         sb.append("Is your favorite color Red?\n");
         if (text.replaceAll("'", "").toLowerCase().contains("yes")){
             sb.append("yes\nCool!");
         } else if (text.replaceAll("'", "").toLowerCase().equals("no")){
             sb.append("no\n:(");
         }
         textArea.setText(sb.toString());
    }
});

My code inserts the "yes" and "no" answers into a specific place in the JTextArea, so you may have to change it around and figure out how exactly you want it.
Note, however, that if I were programming this with Swing, I would use JLabel's for the questions and responses, and JRadioButton's for the multiple choice answers.


text:
Q: Why doesn't the id of a list change even if the list is moved in memory? As I know, dynamic arrays (list in Python) move in memory when its size reaches its capacity. And as far as I know the id of an object corresponds to its memory address.
But when appending values to a list many times, its id doesn't change (so it stays in the same place in memory).
Why?
a = []

print(id(a))  # 2539296050560

for i in range(1_000_000):
    a.append(i)

print(id(a))  # 2539296050560

A: You are making a confusion between the address of the list (what is the id in CPython) and the address of the data. Under the hood and in CPython, a list is an object that contains a pointer to the beginning of its data. So when you extend the list, the data will be moved in memory but the list object will not, allowing it to keep a fix id - which is required per the language.


text:
Q: Maven run plugin goal and preceding phases Usually when we run a plugin goal in maven directly from the command line, the build phases preceding the one the plugin goal is bound to will not be run.
How can we run the plugin goal and all its preceding build phases?

A: There is no special support for this. But you can call
mvn preceding-phase goal:you-want-to-call
which will be essentially what you want.


text:
Q: Get user dimensions in Parse using Javascript One of the columns in my User class is their passport number (called "passport").
How can I query all their passport numbers for a specific group of users saved in an group (team) using javascript if I have them in an array?
This is my best try so far:

var team = [Paul, Ringo, George, John]
var query = new Parse.Query(Parse.User);
query.equalTo("username", team[i])
query.find({
  success: function(results) {
    alert(results.get('passport'));
    },
    error: function(error) {
      // handle error
    }
 })

A: You can use containedIn in order to get something based on an array:
var team = ["Paul", "Ringo", "George", "John"];
var query = new Parse.Query(Parse.User);
query.containedIn("username", team);
var passports = [];
query.find({
    success: function(results) {
        results.map(function(result){
            //just an example, handle results however you need
            passports.push(result.get("passport"));
            if(passports.length == results.length){
                console.log(passports);
            }
        });
    },
    error: function(error) {
        // handle error
    }
});

Edit: You can read up more about querying using parse here:
https://parse.com/docs/js/guide#queries-query-constraints


text:
Q: Selecting attributes of a filtered nodeset in XPath I'm trying to learn XPath syntax. I'm using the w3schools example here:
http://www.w3schools.com/xsl/tryit.asp?filename=try_xpath_select_pricenodes_high
..which is based on the following XML:
<?xml version="1.0" encoding="UTF-8""?>

<bookstore>

<book category="COOKING">
  <title la="en">Everyday Italian</title>
  <author>Giada De Laurentiis</author>
  <year>2005</year>
  <price>30.00</price>
</book>

<book category="CHILDREN">
  <title lang="en">Harry Potter</title>
  <author>J K. Rowling</author>
  <year>2005</year>
  <price>29.99</price>
</book>

</bookstore>

The example selects the title of books having a price greater than 35. I wanted to play with this example and select the category names instead of titles. So, I tried this:
/bookstore/book[price>35]/@category

And, as you can see by testing it yourself on that site, it produces no output. What am I getting wrong?
Thanks for your time.

A: The query is OK. But since you're dealing with attribute nodes and not elements, you have to adjust the code that prints the result. Change the lines
document.write(nodes[i].childNodes[0].nodeValue);
document.write(result.childNodes[0].nodeValue);

to
document.write(nodes[i].nodeValue);
document.write(result.nodeValue);

and you'll get the expected result.


text:
Q: Line integral problem / integrating a vector equation Example: Example problem link
For this problem, I'm just confused on how to start by coming up with an equation $f(x,y)$ such that $F = \nabla \cdot f$. Everything I've been trying seems to not work. How should I get started?
Thanks!

A: You're basically calculating the work exerted by a force field
$$\mathbf f : \mathbb R^2 \to \mathbb R^2, \qquad \mathbf f(\mathbf x) = (-2x_2,x_2)$$
along the segment $S = \{\mathbf x \in \mathbb R^2\ |\ \mathbf x = (0,0)+t(1,2),\ t \in [0,1] \}$.
Therefore you may parametrize your segment with the function
$$\mathbf r : [0,1] \to \mathbb R^2, \qquad \mathbf r(t) = (t,2t), $$
whose derivative is $\mathbf r'(t) = (1,2)$. Then your integral becomes
$$\begin{split}
\int_C \mathbf f(\mathbf x) \cdot d\mathbf r &= \int_0^1 \mathbf f(\mathbf r(t)) \cdot \mathbf r'(t)\ dt \\ &= \int_0^1 (-2(2t),(2t)) \cdot (1,2)\ dt \\ &= \int_0^1 (-4t + 4t )\ dt = \int_0^1 0\ dt = 0.
\end{split}$$


text:
Q: php get url from dropbox I am using the php script dropbox recommended https://github.com/BenTheDesigner, and can get a json response, and also list files.
ie This is an output of files in my developer account from test.php.
This is a list of all files in your [APP] Dropbox.

 api_upload_test.txt45 bytes
 dsdsdsdsdsdsd0 bytes
  ghhhhhhhhhhhh0 bytes
If I Fell - The Beatles.mp31 MB
 Koala.jpg762.5 KB
 test_download_api_upload_test.txt45 bytes

But I need the absolute url for these files. ie
    http://something/sandbox/folder/Koala.jpg
or
    http://something/fileget/http://something/koala.jpg
I cannot find anything about specifying a url, or whether I use a dropbox url. Probably a stupid and simple answer.
This is an example of the array;
    array(3) {
       ["code"]=>
      string(3) "200"
      ["body"]=>
     object(stdClass)#8 (9) {
        ["hash"]=>
    string(32) "df98863d80aa0c89f5e359a4f3e10b5a"
    ["thumb_exists"]=>
    bool(false)
    ["bytes"]=>
    int(0)
    ["path"]=>
    string(1) "/"
    ["is_dir"]=>
    bool(true)
    ["size"]=>
    string(7) "0 bytes"
    ["root"]=>
    string(10) "app_folder"
    ["contents"]=>
    array(6) {
      [0]=>
      object(stdClass)#9 (12) {
        ["revision"]=>
        int(1)
        ["rev"]=>
        string(9) "109a31b3c"
        ["thumb_exists"]=>
        bool(false)
        ["bytes"]=>
        int(45)
        ["modified"]=>
        string(31) "Tue, 21 Aug 2012 12:26:04 +0000"
        ["client_mtime"]=>
        string(31) "Tue, 21 Aug 2012 12:26:04 +0000"
        ["path"]=>
        string(20) "/api_upload_test.txt"
        ["is_dir"]=>
        bool(false)
        ["icon"]=>
        string(15) "page_white_text"
        ["root"]=>
        string(7) "dropbox"
        ["mime_type"]=>
        string(10) "text/plain"
        ["size"]=>
        string(8) "45 bytes"
      }
      [1]=>
      object(stdClass)#10 (10) {
        ["revision"]=>
        int(3)
        ["rev"]=>
        string(9) "309a31b3c"
        ["thumb_exists"]=>
        bool(false)
        ["bytes"]=>
        int(0)
        ["modified"]=>
        string(31) "Tue, 21 Aug 2012 14:09:26 +0000"
        ["path"]=>
        string(14) "/dsdsdsdsdsdsd"
        ["is_dir"]=>
        bool(true)
        ["icon"]=>
        string(6) "folder"
        ["root"]=>
        string(7) "dropbox"
        ["size"]=>
        string(7) "0 bytes"
      }
      [2]=>
      object(stdClass)#11 (10) {
        ["revision"]=>
        int(4)
        ["rev"]=>
        string(9) "409a31b3c"
        ["thumb_exists"]=>
        bool(false)
        ["bytes"]=>
        int(0)
        ["modified"]=>
        string(31) "Tue, 21 Aug 2012 15:29:22 +0000"
        ["path"]=>
        string(14) "/ghhhhhhhhhhhh"
        ["is_dir"]=>
        bool(true)
        ["icon"]=>
        string(6) "folder"
        ["root"]=>
        string(7) "dropbox"
        ["size"]=>
        string(7) "0 bytes"
      }

A: Found a way of getting the url. The full path is not given in the array from dropbox. You have to specify media in the request, and the full path is given, which expires every 4 hours.
ie
$media = $dropbox->media($path);


text:
Q: how can i read strings from multiple lines and print them out respectively? class MusicPlayer {
    private var songs: Array<String> = arrayOf("")
    var index = songs.size

    fun add(track: String) {
        songs[index-1] = track
    }
    fun show() {
        for (item in songs) {
            println(item)
        }
    }
}

fun main(args: Array<String>) {
    val m = MusicPlayer()

    while(true) {
        var input = readLine()!!
        if(input == "stop") {
            break
        }
        m.add(input)
    }
    m.show()
}

my inputs are
>Purple Haze
>Under Pressure
>Walk This Way
>stop

expected output
>Purple Haze
>Under Pressure
>Walk This Way
>Playing Purple Haze

but what i get is
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 0

A: If you work with a mutable list, you don't need an index-variable. With mutable list it is much easier than with an array.
class MusicPlayer {

    private val songs = mutableListOf<String>()

    fun add(track: String) {
        songs.add(track)
    }
    fun show() {
        for (item in songs) {
            println(item)
        }
    }
}

A: add function in MusicPlayer class has no sense. First, imagine first three iterations. We call add method 3 times, like this:
m.add("song1")
m.add("song2")
m.add("song3")

In MusicPlayer it will look like this:
(You are not modifying "index" variable anywhere, so...)
// index = 1
// songs[index - 1] = songs[1 - 1] = songs[0]

//first add
songs[0] = "song1"

//second add
songs[0] = "song2"

//third add
songs[0] = "song3"

Second, the size of the array is not dynamic. If you declare an array with size = 1, its size will always be 1. You can't do something like that
private var songs: Array<Stirng> = arrayOf("")
songs[2] = "exampleText" //ArrayIndexOutOfBoundsException

Array reserved memory for just 1 element. There are ways to deal with it, but in your example, I recommeng you to use ArraysList or MutableList (Almost the same). Such collection allows you to freely modify it's size/length.
Your MusicPlayer with ArrayList would look like this
    private var songs: ArrayList<String> = ArrayList()

    fun add(track: String) {
        songs.add(track)
    }
    fun show() {
        for (item in songs) {
            println(item)
        }
    }


text:
Q: app inventor webviewer can't upload files from a html form I have made a html/php form that allows me to upload files. And when I open it in my pc browser works perfectly. It also works when I open this website wiht my mobile's browser and when I click on select file I can chose which app I want to use to get the file I want to upload.
But when I open this website with webviewer from my app, When I click the button to upload the sound,  nothing happens. The whole line is selected and clicking the button does nothing.
Thanks for your help.

A: The webviewer is no full browser, this does not work therefore.
But you can use the activity starter instead, see the documentation about Using the Activity Starter

Open the browser to a Web page
  Use these activity starter properties
  to open a specific web page:
Action: android.intent.action.VIEW
DataUri: http://news.google.com

Alternatively use the web component together with the PostFile block, see an example here


text:
Q: Can XML element have '$' sign in the value? Can an XML element contain $ sign in the value:
<root>
<data>This is a $ sign.</data>
</root>

A: The XML 1.1 specification says:

CharData    ::=    [^<&]* - ([^<&]* ']]>' [^<&]*)

which means that only < and & are disallowed for consideration as character data. (So long as the data meets the character set requirements, of course, which is any Unicode character, excluding the surrogate blocks, U+FFFE, and U+FFFF)
Of course, XML is a very basic specification of a document tree; the program you want to read the XML document may impose other requirements.

A: Yes
You can use cdata casting
<root>
<data><![CDATA[This is a $ sign.]]></data>
</root>

A: Yes
YesYesYesYesYesYesYesYesYesYesYesYesYesYesYes (repeated only because SO won't accept short answers).


text:
Q: How do I pass data values from a particular column or field in a database into a variable in java? Is there a way to pass data values for a MySQL database into a variable in Java?
This is what I have tried so far:
try {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/Login", "root", "****");
        String query = "Select username, passphrase from student where username=?";
        statement = connection.prepareStatement(query);
        resultSet = statement.executeQuery(query);
        if (resultSet.next()) {
            _name = resultSet.getString(2);
            _pass_phrase = resultSet.getString(3);
        }
    } catch (Exception e) {
        System.out.println(Arrays.toString(e.getStackTrace()));
        assert resultSet != null;
        resultSet.close();
        statement.close();
    }

but I keep on getting a NullPointerException that points to my _name variable, telling me it empty. Could someone please point out to me what it is doing, and how to correct it?


text:
Q: Alignment of table issue in HTML I want to add 4 tables on my page , two towards left(one above the other) and two towards right(one above the other). Currently I am able to display only two tables towards left alignment but when I am trying towards right alignment property in div as
 I am getting  distortions.  Please find the code as below:-
Can anyone suggest what can be the cause for the issue, I don't want to use CSS but want to accomplish with the alignment property alone.
HTML

UK

USA

India

Australia

SouthAfrica

Countries

UK

USA

India

Australia

SouthAfrica

A: i think this is what you needed. check here

A: Instead of using any alignment property just use tables to make such 4 table alignment.
Try this

UK

USA

India

Australia

SouthAfrica

UK

USA

India

Australia

SouthAfrica

UK

USA

India

Australia

SouthAfrica

UK

USA

India

Australia

SouthAfrica

DEMO HERE

A: You can do something like this