text:
Q: count lines in array and split into 2 divs php I have a table in my website with 4 columns. I'm using ACF custom field to enter my content.
 $string = get_field('projets');

my strings are split into two divs, date_index & texte_index... date_index display the date, and text_index displays the text, so each strings is split when finding a blank space.
like this :
here is the content I enter = 2013-07 PARIS COLLÈGE DE FRANCE
and here is how it is displayed :

2013-07

PARIS COLLÈGE DE FRANCE

it works fine.
then my frist array is split into two column, when first column have 130 lines, then the next lines are displayed in another column.
here is my code :

<?php
$string = get_field('projets');
$array = explode("\n", $string);
for($i = 0; $i <130; $i++){
$dateAndText= explode(' ', $array[$i], 2);
echo '
'.$dateAndText[0].'
';
echo '
'.$dateAndText[1].'
';
}
?>

<?php
$string = get_field('projets');
$array = explode("\n", $string);
for($i = 130; $i <count($array)-1; $i++){
$dateAndText= explode(' ', $array[$i], 2);
echo '
'.$dateAndText[0].'
';
echo '
'.$dateAndText[1].'
';
}
?>

then I have a 3rd column, here is the code :

<?php
$string = get_field('conferences');
$array = explode("\n", $string);
for($i = 0; $i <300; $i++){
$dateAndText= explode(' ', $array[$i], 2);
echo '
'.$dateAndText[0].'
';
echo '
'.$dateAndText[1].'
';
}
?>

and my 4th column :

<?php
$string = get_field('monographies');
$array = explode("\n", $string);
for($i = 0; $i <300; $i++){
$dateAndText= explode(' ', $array[$i], 2);
echo '
'.$dateAndText[0].'
';
echo '
'.$dateAndText[1].'
';
}
?>

first of all I would like to delete the condition ( $i <300 )on the 3rd and 4th column, I don't want to have limits in this two columns, but when I try to delete the condition nothing is displayed...
secondly I would like to count the lines in the 3rd column, and this number will be the limit of my first column. so my 1st and 3rd column will have the same lines number.
do you understand what I mean ?
it should be something like that but I can't manage to make it work :
in my 1st column :
for($i = 0; $i <130; $i++){
instead of 130, the number of lines of my 3rd column array.
and for 2nd column ;
for($i = 130; $i

instead of 130, the number of lines of my 3rd column array.
I really hope you can help me with this,
here is a github link :
https://gist.github.com/mattieumoreau/7431037
thanks a lot for your help,

A: To fix your first issue, use sizeof(array) rather than a specific number, e.g.:
for($i = 0; $i < sizeof($array); $i++){
    $dateAndText= explode(' ', $array[$i], 2);
    echo '
'.$dateAndText[0].'
';
    echo '
'.$dateAndText[1].'
';
}

Edit:
Your third column would look a bit like this:

<?php
        $string = get_field('conferences');
        $array = explode("\n", $string);
        for($i = 0; $i < sizeof($array); $i++){
            $dateAndText= explode(' ', $array[$i], 2);
            echo '
'.$dateAndText[0].'
';
            echo '
'.$dateAndText[1].'
';
        }
        ?>

A: There are a few issues going on here.

*

*If you delete the condition, either your for loop is erroring out or it's going on forever (depends on how you're trying to delete it). To get all the records, you want for ($i = 0; $i < count($array); $i += 1) { ...

*To limit the length of the first column of 'projets' to the length of 'conferences', you'll need to pick up the data ahead of time, then display it. Here's what I mean:
$projets = explode("\n", get_field('projets'));
$conferences = explode("\n", get_field('conferences'));
$monographies = explode("\n", get_field('monographies'));

// Now we want to limit the length of the first column of projets (col 1) to the
// length of conferences (col 3).
$projets = array_chunk($projets, count($conferences)); // Split the projets into a set of arrays of the right length.
$projets1 = array_shift($projets); // Grab the first one... that's the data for the first column.
$projets2 = array_reduce($projets, 'array_merge', array()); // Merge the remaining arrays into a single array for display.

and then :
function displayDateAndText ($obj)
{
    $dateAndText = explode(' ', $obj, 2);
    echo "
{$dateAndText[0]}
";
    echo "
{$dateAndText[1]}
";
}
function displayRecords ($records)
{
    echo '
';
    $limit = count($records);
    for ($i = 0; $i < $limit; $i += 1)
    {
        displayDateAndText($records[$i]);
    }
    echo '
';
}
?>

    <?php
       displayRecords($projets1);
    ?>

    <?php
       displayRecords($projets2);
    ?>

    <?php
       displayRecords($conferences);
    ?>

    <?php
        displayRecords($monographies);
    ?>


text:
Q: Clock and dynamic layout How can i show hour minutes and seconds of clock in Textview continuously as i am using dynamic linear layout`this format works on static layout but not on dynamic layout please help me thanks?

*

*List item
public class ButtonActivity extends Activity {

Button b;
ScrollView scrollview;
int count = 4;`enter code here`
private int mHour,mMinute,mSecond;
int min,hr,sec;
private Handler mHandler = new Handler();

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_button);
  Runnable mUpdate = new Runnable() {
      @Override
      public void run() {
      Calendar c = Calendar.getInstance();
      mHour = c.get(Calendar.HOUR_OF_DAY);
      mMinute = c.get(Calendar.MINUTE);
      mSecond = c.get(Calendar.SECOND);
      min = mMinute;
      hr = mHour;
      sec = mSecond;
      String timeSet = "";

      if (hr > 12) {
        hr -= 12;
        timeSet = "PM";
      } else if (hr == 0) {
        hr += 12;
        timeSet = "AM";
      } else if (hr == 12)
        timeSet = "PM";
        else
        timeSet = "AM";
        String minutes = "";
        if (min < 10)
        minutes = "0" + min;
        else
        minutes=String.valueOf(min);
        String secs = "";
        if (sec < 10)
        secs = "0" + sec;
        else
        secs = String.valueOf(sec);

        mHandler.postDelayed(this, 1000);

        }
     };

       mHandler.post(mUpdate);
       scrollview = new ScrollView(this);
       LinearLayout linearlayout = new LinearLayout(this);
     linearlayout.setOrientation(LinearLayout.VERTICAL);
     scrollview.addView(linearlayout);
     TextView t = new TextView(this);

   t.setText(hr + ":" + minutes + ":" + secs+""+timeSet);
  linearlayout.addView(t);
  for(int i = 0; i<count;i++)
  {
   LinearLayout linear1 = new LinearLayout(this);
      linear1.setOrientation(LinearLayout.HORIZONTAL);
      linearlayout.addView(linear1);
      b = new Button(this);
      b.setText(""+i);
      b.setId(i);
      b.setTextSize(10);
      b.setPadding(8, 3, 8, 3);
      b.setTypeface(Typeface.SERIF,Typeface.BOLD_ITALIC);
      b.setLayoutParams(newLayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
      linear1.addView(b);
  }
  this.setContentView(scrollview);

}
  }

A: You have to call setText() on your TextView inside your Runnable run() method. The way it is now the text will only be set once when the Activity is created.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swift 3 | JSON Value of optional type '[String : Any] not unwrapped, did mean to use '!' or '?'? I'm currently learning Swift, and right now I'm learning about how to serialize / deserialize JSON objects, however I've come across an issue, in which I cannot get around! I'm receiving the error mentioned in the title, and I've tried everything, and still receive the error! Can someone please point me in the right direction as to how to resolve this error?
I believe that somewhere in my code a value is not getting unwrapped properly, however I can't pinpoint which value is causing the issue. The error highlights this line of code: if let Users = json["User"] as? [String: Any]
Using '!' instead of '?' in the json["User"] line of code, as well as the code above it, still causes the error to be received.
I've run out of ideas, and don't know what else to try.
Code:
let requestURL: URL = URL(string:
    "url")!
let urlRequest = URLRequest(url: requestURL)
let session = URLSession.shared
let task = session.dataTask(with: urlRequest) { (data, response, error)
-> Void in

    let json = try? JSONSerialization.jsonObject(with: data!,
        options: .allowFragments) as? [String: Any]

    if let Users = json["User"] as? [String: Any] {

}

JSON:
{
   "User":[
      {
         "Coin":"4",
         "Email":"email@blank.com",
         "NumberBusinesses":"2",
         "NumberBusinessesSold":"4"
      },
      {
         "Coin":"12",
         "Email":"email2@blank.com",
         "NumberBusinesses":"3",
         "NumberBusinessesSold":"6"
      }
   ]
}

A: json is optional (since you are using as?).
The best solution is to conditionally unwrap it:
if let json = (try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)) as? [String: Any] {
    if let Users = dict["User"] as? [String: Any] {
    }
}

Note, you should also be safely unwrapping data. If the data can't be obtained, using data! will crash your app.

A: The try statement here returns nil if the casting fails, as @rmaddy mentioned the conditional binding should prevent the json from being nil. But after trying it out the type of json is [String:Any]? even after the conditional binding which is the reason it was throwing that error.
But when I tried enclosing it in a do..catch block instead of optional try statement poof the error was gone. It's a bit confusing why the value of json is optional even after the conditional binding, but I'm convinced the optional try statement is causing the problem.

A: The error is resolved, thanks to ebby94! (also a thank you to rmaddy for helping!)
ebby94 advised to change this code: json["User"] as? [String: Any] to json?["User"] as? [String: Any]

A: The following is deprecated
.allowFragments

instead use
.fragmentsAllowed

If you're fetching JSON it should return an array or dictionary already. So perhaps you can replace
let json = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]

if let Users = json["User"] as? [String: Any]

with something like the following
let jsonDictionary try? JSONSerialization.jsonObject(with:data!, options: .fragmentsAllowed)
let Users = jsonDictionary["User"] as? NSMutableDictionary


text:
Q: Dynamically Create and Set Nested Div in JavaScript I would only want to render/create
Hello
 on page load.
I don't want to declare them already but I want to trigger JS and create them once page loads.
Pls see "Expected Output" below
EXPECTED OUTPUT

Hello

Current Code

A: Okay, I got it;
Use this code:

const newSyndicationModalContainer = document.querySelector(".newSyndicationModalContainer")
const newSyndicationModalContent = document.querySelector(".newSyndicationModalContent")
if (newSyndicationModalContainer != undefined) {
  var p = document.createElement('p');
  p.innerText = "Hello!";
  var iframe = document.createElement('iframe');
  iframe.id = "syndicationPanelModalIFrame";
  iframe.src = "http://sample.com";
  iframe.width = "100%";
  iframe.height = "100%";
  iframe.style.border = "none";
  newSyndicationModalContent.append(p, iframe);
  newSyndicationModalContainer.style.display = 'block';
}
.newSyndicationModalContainer {
  display: none;
  position: fixed;
  z-index: 9999;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.4);
}

.newSyndicationModalContent {
  background-color: transparent;
  margin: auto;
  width: 100%;
  height: 100%;
}

Another way of doing it with innerHTML
Although it's not a good way to do it, I'll do it for you as you asked:

const newSyndicationModalContainer = document.querySelector(".newSyndicationModalContainer")
const newSyndicationModalContent = document.querySelector(".newSyndicationModalContent")
if (newSyndicationModalContainer != undefined) {
  newSyndicationModalContent.innerHTML = `<p>Hello</p><iframe src="https://sample.com" id="syndicationPanelModalIFrame" width="100%" height="100% style="border: none;"`;
  newSyndicationModalContainer.style.display = 'block';
}
.newSyndicationModalContainer {
  display: none;
  position: fixed;
  z-index: 9999;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgb(0, 0, 0);
  background-color: rgba(0, 0, 0, 0.4);
}

.newSyndicationModalContent {
  background-color: transparent;
  margin: auto;
  width: 100%;
  height: 100%;
}

Regarding the question in the comments

let's say its not always iframe inside there is always. So I don't want to declare iframe src = ... Can we do it like innerHtml? –

You can always create an element and edit its outerHTML/innerHTML/innerText/etc.
For instance:
let div = document.createElement("div");
div.innerHTML = `<span class="innerSpan" style="border: 5px ridge red" data-blablablah="I-don't-say-bla-bla-blah">Bla Bla Bla Blah</span>`;
div.style = "dispaly: grid";


text:
Q: Ansible looping over nested variables I have a set of variables which define FQDNs.
domains:
  - erp: erp.mycompany.com
  - crm: crm.mycompany.com
  - git: git.mycompany.com

Indeed, I both need to loop over them and access them namely (in a template file). So accessing them like domains.erpworks like a charm. But I can't get ansible to loop over these.
Obviously, if I do:
- name: Print domains
  debug:
    msg: test {{ item }}
  with_items:
    - "{{ domains }}"

It prints both the key and the value… And if I do:
- name: Print domains
  debug:
    msg: test {{ domains[{{ item }}] }}
  with_items:
    - "{{ domain }}"

But that doesn't work. I also tried the hashes form as mentionned in the docs, but didn't get any luck either…

A: Finally, I had to use a dict.
It didn't work the first time because unlike with_items, which has the items going each on their own line, with_dict is a one liner without - before the element to loop through.
domains:
  erp:
    address: erp.mycompany.com
  crm:
    address: crm.mycompany.com
  git:
    address: git.mycompany.com

# used by letsencrypt
webserverType: apache2
withCerts: true

tasks:

- name: Print phone records
  debug:
    msg: "{{ item.value.address }}"
  with_dict: "{{ domains }}"

# I can still access a given domain by its name when needed like so:
{{ domains.erp.address }}

A: Looks like you figured out your issue. Your original attempt uses a list of dictionaries that do not contain the same keys, making it difficult to access the values uniformly across each list item.
Your second solution creates a dictionary where the keys refer to other dictionaries.
Another solution than what you posted if you still wanted to use a list:
    - hosts: localhost
      vars:
        domains:
          - name: erp
            address: erp.mycompany.com
          - name: crm
            address: crm.mycompany.com
          - name: git
            address: git.mycompany.com
      tasks:
        - name: Print phone records
          debug:
            msg: "{{ item.address }}"
          with_items: "{{ domains }}"

To me this approach is simpler but your second approach works as well.


text:
Q: Ardinio convert string to const unsigned char String abc ="0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff"

const unsigned char displaydata={ '"+abc+"'};

display.drawBitmap(displaydata, startX, startY, bmpWidth, bmpHeight, GxEPD_WHITE);

This is not display but
const unsigned char displaydata={ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};

display.drawBitmap(displaydata, startX, startY, bmpWidth, bmpHeight, GxEPD_WHITE);

This is working and displayed
I need convert a string to const unsigned char with code
is it possible ?
The data coming from the server is returning to me as stirng, I am trying to reflect it on the screen.
So I'm trying to convert

A: If you are trying to parse a string 0xff, 0xff, ..., 0xff, 0xff to produce an array of unsigned char, then you have a bit of code to write.
But I suspect you simply want to type those characters in a manner that declares them to be a constant array of unsigned char.
To do the latter, you simply type this:
const unsigned char abc[] = {0xff, 0xff, ..., 0xff, 0xff};

Mostly it's about replacing your " with { and } after using the proper datatype on the left-hand side of the =.
If you do indeed need to visually display the array as a string and you need to process that string as an array of unsigned char, then you need both representations but then you should consider which conversion is easier and less prone to error.
If we assume that your code rarely needs to display the string compared to the often processing of the array, then you should consider how much easier and less error prone it is to produce the string than it is to parse the string to produce the array.

A: Define your data as a raw string literal.
Essentially if you have a string "your string" define it as
std::string str  = R"(your string)";
A raw string literal is a string in which the escape characters (like \n \t or " ) of C++ are not processed. A raw string literal which starts with R"( and ends in )" was introduced in C++11.


text:
Q: Jest Enzyme Warning of ReactTestUtils location I am using Jest with Enzyme (the former for a while, just starting with the latter).
The relevant versions from my package.json:
"devDependencies": {
  "enzyme": "^2.8.2",
  "jest": "^19.0.2",
  "react-addons-test-utils": "^15.5.1",
  "react-dom": "^15.4.2",
  "react-test-context-provider": "^2.1.2",
  "react-test-renderer": "^15.4.2"
},

And a simplified version of the test I'm trying to run:
import React from 'react';
import { shallow, mount, render } from 'enzyme';
import Dashboard from '../../../javascript/components/ecosystems/Dashboard';

describe('<Dashboard />', () =>{
  it('renders', () => {
    const wrapper = shallow(
      <Dashboard routeParams={{}} />,
      {
          context: {
              executeAction: () => {},
          }
      }
    );
    expect(wrapper).toMatchSnapshot();
  });
});

which is giving me no errors, but the warning:

Ran all test suites matching "Dashboard.test.js".
console.error node_modules/fbjs/lib/warning.js:36
  Warning: ReactTestUtils has been moved to react-dom/test-utils. Update references to remove this warning.

But I am trying out Enzyme rather than React's TestUtils. How do remove this warning?


text:
Q: Symfony Edit Form Using Popup On listing Page I am displaying the List of Record using KNPPaginationBundle. What I want to edit these record in popup model while staying on the same list page. I have read about it. A Lot of people are doing this using jquery. But i wanted to this in Symfony Way.

Is it possible to have edit form on listing page?

A: You have to use Ajax to edit records and staying in the same page so you have to use jquery

A: As @NinjaTN say you need to use ajax to use popup.
If you don't want to use ajax you need to send user on form view via an edit button on your listing view.
Form from Symfony doc
or you can use bundle like  easyadmin
Another way will be to populate your form on clickevent from your listing grid, send with JS all element you need to your form and then show your popup.

A: At first you're mixing two different things. Symfony is only php framework, nothing to do with jQuery or javascript. So with symfony you cannot do things as you can do with jQuery.
If you want to do this without jQuery that means you want to do it without javascript in plain twig? If so you have to render a form for each row in a modal window.
If you want to use javascript without an ajax request, you can do this:

*

*Render a one edit form on a list page.

*When user choose row to edit, display a modal window and change at least the id in a route with javascript.

*After submitting, be sure that edit action will redirect user back to the list.

If this is your definition on "stay on page", you're done. If it's not you cannot do this without ajax and symfony will not help you, because it has no "javascript support".


text:
Q: Openseadragon - tileSource - url: / can i put my local image or normal jpg url? i found this codepen.
https://codepen.io/webconstructor/pen/oMyYBz
I want to use my image which is in local.
Is it possible that i use it?
and why can't i use another image from in any internet site ?
for example, it is working,
var viewer = OpenSeadragon({

      id: "openseadragon1",
      tileSources:{
          url: "https://picsum.photos/2200/2300/?image=100",
          type: 'image',
          crossOriginPolicy: 'Anonymous',
          ajaxWithCredentials: false
      },

but it is not working with this jpg.
url: "https://cdn.pixabay.com/photo/2017/07/22/20/29/life-2529859_960_720.jpg",
so could somebody explain about this, why i can not.
if i can, how ?

A: Try removing the crossOriginPolicy. Sometimes you need it, but sometimes you need it to not be there.
In the case of Pixabay, they don't allow linking directly, so you won't be able to get it to work at all (but if you remove the cross origin policy you'll at least see their "Don't Link Directly" image). Here's an image from a different service you can link directly to:
https://images.unsplash.com/photo-1549284936-c550b7b959ff?w=900
Local images should work just fine. Again you might need to remove the crossOriginPolicy.


text:
Q: asp.net mvc user load testing I need to login in about 100 users each with their own session to test a web application. I need to then have some users do some activity.
Which tool can I use to login many users each with their own session?

A: Definetely use Visual Studio 2010 Ultimate edition if you have it.
Make sure you set the Percentage of New Users property to 100 in the load test properties.

A: Our product, Web Performance Load Tester, does that, as do most load testing tools.


text:
Q: Primefaces CommandButton (Within Datatable) - To Refresh Datatable on a second tab and switch to that tab I am newbie.
I have a Primefaces tab (1. Summary 2. Detail).
I am allowing user to search for the list of items and then in 1st tab, the primefaces datatable shows the results. Along with the table there is an extra column on which user clicks then it should retrieve the corresponding record detail line and also switch to the 2nd tab.
I am able to click on the extra column using Action and log the selected line and it also moves to the second tab. However it is not showing my primefaces datatable on the 2nd tab.
However, when I click on the 2nd tab manually, I can see the datatable and all the correct data.
<p:column width="30">
<p:commandButton id="selectDetailCb"
                     title="View detail"
                     oncomplete="tabViewV.select(2)"
         action="#itunesAnalysisToolMb.retrieveProductDetailRpt(itunesAnalysisToolSummaryV)}"
   icon="ui-icon-search"
                                                     update=":itunesAnalysisToolForm:tabView:itunesAnalysisToolDetailDt">
                                    </p:commandButton>
                                </p:column>

/*
 * Retrieve the iTunes Analysis Tool detail for the selected product and for the selected time frame.
 */
public void retrieveProductDetailRpt(ItunesAnalysisToolSummary selectedProduct){

    log.debug(selectedProduct.getRank());
    log.debug(selectedProduct.getArtist());
    log.debug(selectedProduct.getTitle());
    log.debug(this.startReportDate);
    log.debug(this.endReportDate);
    log.debug(this.itunesProductTypeCode);

    //return "goToDetail";
}

In the background I am getting this message.

Mar 29, 2013 1:02:04 PM com.warnermusic.wis.util.JsfPhaseListener
  beforePhase INFO: RENDER_RESPONSE 6 Mar 29, 2013 1:02:04 PM
  com.sun.faces.context.PartialViewContextImpl$PhaseAwareVisitCallback
  visit SEVERE: java.lang.NullPointerException Mar 29, 2013 1:02:04 PM
  com.warnermusic.wis.util.JsfPhaseListener afterPhase INFO:
  RENDER_RESPONSE 6

but no other errors.
Can you please help me and advise why I am not able to see the dataTable on the 2nd tab while clicking the commandbutton, but I can see when I actually move to the next tab manually.

A: The tabs are usually indexed from 0 to max-1. From the code you have posted seems that you are trying to access to the second tab but you shoud do oncomplete="tabViewV.select(1)".
If there is no more tabs, this exception is usually thrown.


text:
Q: Extract a mixin from a common function in Python Consider two classes that each have an existing shared function, but separate inheritance paths:
class ClazzA(SuperClazzX):
    def foo(self):
        return goo(super(SuperClazzX, self).foo())

class ClazzB(SuperClazzY):
    def foo(self):
        return goo(super(SuperClazzY, self).foo())

foo is clearly a common function which can be extracted to a mixin, what is the right way to do so, such that the functionality remains even though a different super foo is to be called?
Edit: I removed the other mixin, it was confusing and irrelevant.

A: EDIT: simpler code
Mixin has access to other bases of (future) child class, here C::Mixin::foo has access to the other base of C, namely C::Base::foo. Authoritative explanation here.
class Base(object):  # must be new-style class in py 2.x
    def foo(self):
        print "base foo called"

class Mixin(object):
    def foo(self):
        rv = super(Mixin, self).foo()  # call actual implementation
        # use rv

class C(Mixin, Base):
    pass

C().foo()
base foo called

What this does:

*

*self is instance of C, it's __mro__ is (Mixin, Base)

*when Mixin calls super(Mixin, self), the resulting object retains bases (Base,)

*when .foo attribute is resolved, this object finds it in Base

*thus Base.foo is invoked with original self
If you want custom control over implementation, you have access to your own bases, e.g.:
class Foo(...):
    def foo(self):
        print self.__class__.__bases__

Your mixin could look something like this, super-manual approach:
class Mixin(object):
    def foo(self):
        assert self.__class__ is not Mixin  # no point calling directly
        # find the other base
        other = [b for b in self.__class__.__bases__ if b is not Mixin]
        # what to do if there's more than 1 real base?
        # pick base explicitly
        base = other[1]
        # call it,
        return something(base.foo(self, some_args))


text:
Q: Orchard Cms Multiple Media picker fileds on custom type I have created a custom type Project, which has 4 Images, I wish to used 4 fileds of type media picker, which I have added link so ...
public int Create()
            {
                // Define the project type
                ContentDefinitionManager.AlterTypeDefinition("Project", cfg => cfg
                    .WithSetting("Stereotype", "Content")
                    .CommomPart()
                    .AutoroutePart("our-work")
                    .BodyPart()
                    .WithPart("TitlePart")
                    .WithPart("PublishLaterPart")
                    .WithPart("MenuPart", builder => builder
                        .WithSetting("MenuPart.OnMenu", "true")
                        .WithSetting("MenuPart.CurrentMenu", "Project Menu"))
                    .WithPart("Project")
                    .Creatable()
                    .Draftable());

                return 1;

            }

            public int UpdateFrom1()
            {
                // Define project part - having a part with the same name will create fields in the project type
                ContentDefinitionManager.AlterPartDefinition("Project", builder => builder
                   .MediaPickerField("MainImage")
                   .MediaPickerField("MediumImage")
                   .MediaPickerField("SmallImage")
                   .MediaPickerField("Logo")
                   .TextField("ShortDescription", Flavour.TextArea)
                   .TextField("Features", Flavour.Markdown)
                   .TextField("ClientTitle", Flavour.DefaultFlavour)
                   .TextField("ClientName", Flavour.DefaultFlavour)
                   .TextField("ClientQuote", Flavour.Textarea)
                   .BooleanField("MainProjectOnHomePage", false)
                   .Attachable());

                return 2;
            }

Extension methods used to make it a bit less verbose
public static ContentPartDefinitionBuilder MediaPickerField(this ContentPartDefinitionBuilder builder,
                                                                string name, bool required = true, string hint = "")
    {
        var displayName = SplitCamel(name);

        // default implementation of Media picker field - create overloads for more options
        return  builder.WithField(name, fieldBuilder => fieldBuilder
                    .OfType("MediaPickerField")
                    .WithDisplayName(displayName)
                    .WithSetting("MediaPickerFieldSettings.Required", required.ToString(CultureInfo.InvariantCulture))
                    .WithSetting("MediaPickerFieldSettings.AllowedExtensions", "jpg png gif")
                    .WithSetting("MediaPickerFieldSettings.Hint", hint));

    }

    public static ContentPartDefinitionBuilder TextField(this ContentPartDefinitionBuilder builder,
                                                         string name, Flavour flavor, bool required = true, string hint = "")
    {
        var strFlavor = SplitCamel(flavor.ToString());

        // default implementation of Media picker field - create overloads for more options
        return builder.WithField(name, fieldBuilder => fieldBuilder
                    .OfType("TextField")
                    .WithSetting("TextFieldSettings.Required", required.ToString(CultureInfo.InvariantCulture))
                    .WithSetting("TextFieldSettings.Flavor", strFlavor)
                    .WithSetting("TextFieldSettings.Hint", hint));

    }

I am able to add media to the 4 fields in the dashboard, but  on save only the first media item is saved, I am allowed to save the project, even thought all media fiels are required, but the Media items for 3 fields is missing,
I've also tried adding an extra media picker through the dashboard with a similar result.
Am I doing something wrong?


text:
Q: Recognizing a Mukai flop Let us first review the usual construction of a Mukai flop. Suppose $M$ is a smooth $2m$-dimensional projective variety over $\mathbb C$ containing a closed $m$-dimensional subvariety $W$, and suppose we have a projective birational morphism $\nu:M\to\overline M$ such that $\nu$ is an isomorphism away from $W$, and such that the restriction of $\nu$ to $W$ is a projective bundle $W\cong \mathbb P(\mathcal V)\to Y$, where $\mathcal V$ is a vector bundle on a smooth subvariety $Y\subset \overline M$. Assume further that the normal bundle $N_{W/M}\to W$ restricts to the cotangent bundle on each fibre of this projective bundle.
We can then perform the Mukai flop of $M$ along $W$ as follows: let $\widetilde M\to M$ be the blowup of $M$ along $W$. This has exceptional divisor $E = \mathbb P(N_{W/M})$. By the assumption on the normal bundle made above, using the Euler sequence we have an embedding
$$E\subset \mathbb P(\mathcal V)\times \mathbb P(\mathcal V^*)$$ which is described on each fibre over $y\in Y$ as the incidence variety
$$\{(L,H)\in \mathbb P(\mathcal V_y)\times \mathbb P(\mathcal V_y^*): L\subset H\}.$$ It can then be shown that there exists a variety $M'$ and a birational morphism $\widetilde M\to M'$ which is an isomorphism away from $E$ and whose restriction to $E$ is the projection onto $\mathbb P(\mathcal V^*)$ with image $W'\cong\mathbb P(\mathcal V^*)$, and we have a projective birational morphism $\nu':M'\to \overline M$ which is an isomorphism away from $W'$ and restricts to $\mathbb P(\mathcal V^*)\to Y$ on $W'$. The birational morphism $M\dashrightarrow M'$ is the Mukai flop of $M$ along $W$.
My question is as follows. Suppose we had all the hypotheses in the first paragraph above, and suppose we are given a projective birational map $\nu':M'\to \overline M$ which is an isomorphism away from $Y$ and which restricts to the dual projective bundle $\mathbb P(\mathcal V^*)\to Y$ away from $Y$. Can we then conclude that $M\dashrightarrow M'$ is the Mukai flop along $W$? If not, are there some additional conditions that we can impose on $\nu'$ which make it true?
Thanks kindly.

A: If you consider your flop a $(K+D)$-flip, then you might find the additional condition you need. Any flop is actually a $(K+D)$-flip for a well chosen $D$. (For the definition of a $(K+D)$-flip see 3.33 of Birational Geometry of Algebraic Varieties
 By Kollár-Mori).
In this case, $\det N_{W/M}$ (or rather an associated divisor) seems like a good candidate for $D$. An easy calculation shows that $(\det N_{W/M})^{-1}$ is $\nu$-ample. If you can verify that it's strict transform on the Mukai flop is $\nu'$-ample, then it would work as $D$. In any case, you want to find a divisor $D$ for which $-D$ is $\nu$-ample and its strict transform on the Mukai flop is $\nu'$-ample.
If you have such a $D$, then the condition that its strict transform on $M'$ is $\nu'$-ample implies that $\nu'$ is the flop you you want (in this case the Mukai flop), because with this additional condition the flip is unique by (for example) Lemma 6.2 of the above book by Kollár-Mori.


text:
Q: For $r_n=0.2+0.3r_{n-1}$ defined recursively, how to show the limit of $r_n$ exists? Suppose sequence $r_n$ is recursively defined as $r_n=0.2+0.3r_{n-1}$ for $n>0$ and $r_0=1$. I know that if $\displaystyle \lim_{n \rightarrow\infty}r_n$ exists, then $\displaystyle \lim_{n \rightarrow\infty}r_{n-1}=\displaystyle \lim_{n \rightarrow\infty}r_n$ and let $A=\displaystyle \lim_{n \rightarrow\infty}r_n$ and plug it in we will have $A=0.2+0.3A$ and hence $A=2/7$.
The problem is, how do we show the limit exists? $r_n$ is apparently bounded. But I don't know how to show it is monotone. $r_n-r_{n-1}$ gives $0.2-0.7r_{n-1}$, whose sign is dependent on $r_{n-1}$.
Thank you!

A: A method is the following: Your potential limit $A $ (equal $2/7$) satisfy (1) $A=0.2+0.3A$. Put $v_n=u_n-A$ and substract (1) from the recurrence relation, you get $v_n=0.3v_{n-1}$. An easy induction show that $v_n=(0.3)^n v_0$, and you are done.

A: Hints:

*

*The function $f$ which takes in $r_{n-1}$ and returns the next term in the sequence is a monotone increasing function.

*Notice that $x_1 \gt x_2 \gt  0\implies f(x_1) \gt f(x_2) \gt 0$

*Use Induction to show the sequence $(r_n)$ is monotone.

A: You can try the sequence $\{r_n-A\}_n$ which converges to zero.


text:
Q: Make last paragraph - active pointer I am trying to write my research work in markdown, and it's required by my institution to submit it in Word doc format. I decided to use python-docx package to automate this task.
However, I am struggling with some specific task, like adding data to end of the file?
So here I am now.
def merge(docx, files):
    """ merges other docx files into parent docx document """
    docx._body.clear_content()

    elements = []
    for idx, file in enumerate(files):
        donor = Document(file)
        donor.add_page_break()

        for element in donor.element.body:
            elements.append(element)

    for element in elements:
        docx.element.body.append(element)

# base styles
document = Document("docx/base.docx")

# adding two preformatted files with really fragile formatting.
merge(document, ["docx/Tytulka.docx", "docx/Zavdania.docx"])

document.add_paragraph("hey")
document.save("tmp_result.docx")

So what I have in tmp_result.docx, is hey -> content from 1st file, content from 2nd File.
I checked code and was successfully able to use insert_paragraf_after*, which added a paragraph at the end of the file.
So here is a question - how can I ask/trick document object to use the last paragraph as current element pointer? Its default behavior supposes to work, but I have change structure with my merged documents, and new content added to the first paragraph of the file.
I tried the next trick, but the result was unexpectedly unsatisfying**, after which, I decided to stop playing with the API (both word and python-docx) I don't understand.
# trick I use to move active paragraph to the end.

def merge(docx, files):
    docx._body.clear_content()

    elements = []
    for idx, file in enumerate(files):
        donor = Document(file)
        donor.add_page_break()

        for element in donor.element.body:
            elements.append(element)

    for element in elements:
        # moving last paragraph to the end of file.
        tmp = docx.element.body[-1]
        docx.element.body[-1] = element
        docx.element.body.append(tmp)

# base styles
document = Document("docx/base.docx")

# adding two preformatted files with really fragile formatting.
merge(document, ["docx/Tytulka.docx", "docx/Zavdania.docx"])

document.add_paragraph("hey")
document.save("tmp_result.docx")

I wish I can spend more time digging Word specifications, and python-docx code, but I don't really have it. So here is a question:
How to point python-docx to write after particular (last) paragraph?
ANSWER/SOLUTION credited to scanny

The problem with just appending to the body element is there is a "sentinel" sectPr element at the end of the body and it needs to stay there (like not have paragraphs after it). by @scanny

Having this valuable info, I did next thing.

def merge(docx, files):
    """
    Merge existing docx files into docx.
    """
    docx._body.clear_content()

    elements = []
    for idx, file in enumerate(files):
        donor = Document(file)
        donor.add_page_break()

        # all except donor sentinel sectPr
        for element in donor.element.body[:-1]:
            elements.append(element)

    # moving docx centinel to the end and adding elements from
    # donors
    for element in elements:
        tmp = docx.element.body[-1]
        docx.element.body[-1] = element
        docx.element.body.append(tmp)

if __name__ == "__main__":

    # addyng title page and preformatted docs files.
    document = Document("docx/base.docx")
    merge(document, ["docx/Tytulka.docx", "docx/Zavdania.docx"])

    # document.add_paragraph("hey")

    # open for tests
    # os.system("kill -9 $(ps -e -o pid,args | grep Word.app | awk '{print $1}' | head -1)")
    # this part accepts curent document
    # transform markdown files that fits to pattern by adding them
    # to the docx
    # save and open document.
    Builder(document).build("texts/13*.md").save("tmp_result.docx").open()

As results Content of the 1st file -> Content of the 2nd File -> Markdown generated content
Win!Win!Win!

*

** You wouldn't find method insert_paragraf_after in the package, but it's exactly same as insert_paragraf_before with the only difference that paragraph created and inserted to the next ones (see method add_p_before of CT_P class, you can use addnext of BaseOxmlElement)).

*** result of moving current pointer p was next: content from 1st file -> hey -> content from 2nd File, which doesn't make sense (since I don't really know API's of Word and python-docx).

A: Well, I'm not sure I understand exactly what you're trying to do, but I think what you're asking for is this:
last_p_in_document = document.paragraphs[-1]._p
p.addnext(new_p)
last_p_in_document = new_p
# ---etc.---

The problem with just appending to the body element is there is a "sentinel" sectPr element at the end of the body and it needs to stay there (like not have paragraphs after it). The other approach you could take would be to find that element using sectPr = body[-1] and then use sectPr.addprevious(next_element_to_be_added) which actually seems like the simpler approach. The sectPr will continue to be the last child of body (so you don't have to reset it after every element insertion) and you can add table elements as well as paragraph elements with the same code.


text:
Q: Open hyperlink in the same window, different tab I used the below code options to open a hyperlink in the same window and a different tab, but every time the link will open in a different window.
1)
String selectLinkOpeninNewTab = Keys.chord(Keys.CONTROL,Keys.RETURN);
driver.findElement(By.linkText(linkText)).sendKeys(selectLinkOpeninNewTab);

2)
Actions act = new Actions(driver);
act.moveToElement(element).doubleClick(element))).build().perform();

3)
Actions act = new Actions(driver);
act.contextClick(driver.findElement(By.xpath(element)))
    .sendKeys(Keys.ARROW_DOWN)
    .sendKeys(Keys.ARROW_DOWN)
    .sendKeys(Keys.RETURN)
    .build()
    .perform();

Expecting link should be open in the same window different tab, but every time it is opening in the new window.
Please help.

A: I wouldn't recommend this approach as keyboard manipulation is definitely not something you want as it will be the major constraint violating Parallel Testing Best Practices, to wit you will not be able to run your tests in Selenium Grid
I would suggest going for an alternative approach to wit:

*

*Extract href attribute from the link

*Open a new tab using Window.open() function via driver.executeScript() function

*Switch to the new tab using driver.switchTo().window() function

Example code:
WebElement link = driver.findElement(By.linkText(linkText));
String href = link.getAttribute("href");
driver.executeScript("window.open('" + href + "');");
driver.switchTo().window(driver.getWindowHandles().stream().reduce((f, s) -> s).orElse(null));
System.out.println(driver.getTitle()); // at this point you should see the new page title


text:
Q: MVC security WebSecurity.CreateAccount or Membership.CreateUser
Can anyone let me know the difference between
WebSecurity.CreateAccount or Membership.CreateUser
Which one should i use on creating an user in mvc 4 .net


text:
Q: Create Azure Windows VM using another language version Is it possible to choose another language beside US-EN, during Azure VM creation?

A: I never had to do it myself but here's a link that explain how to install a language pack after the installation.

Open the control panel and select "Add a language". Find the language
  you want to add and add it. Now it is available for selection as input
  locale etc, but the translation files needed to get exception messages
  in the language are not automatically downloaded. That can be done by
  selecting the "options" link. Select "Download and Install Language
  Pack" to continue.


text:
Q: MP4 Atom Parsing - where to configure time...? I've written an MP4 parser that can read atoms in an MP4 just fine, and stitch them back together - the result is a technically valid MP4 file that Quicktime can open and such, but it can't play any audio as I believe the timing/sampling information is all off. I should probably mention I'm only interested in audio.
What I'm doing is trying to take the moov atoms/etc from an existing MP4, and then take only a subset of the mdat atom in the file to create a new, smaller MP4. In doing so I've altered the duration in the mvhd atom, as well as the duration in the mdia header. There are no tkhd atoms in this file that have edits, so I believe I don't need to alter the durations there - what am I missing?
In creating the new MP4 I'm properly sectioning the mdat block with a wide box, and keeping the 'mdat' header/size in their right places - I make sure to update the size with the new content.
Now it's entirely 110% possible I'm missing something crucial about the format, but if this is possible I'd love to get the final piece. Anybody got any input/ideas?
Code can be found at the following link:
https://gist.github.com/ryanmcgrath/958c602cff133bd7fa0b

A: I'm going to take a stab in the dark here and say that you're not updating your stbl offsets properly. At least I didn't (at first glance) see your python doing that anywhere.
STSC
Lets start with the location of data. Packets are written into the file in terms of chunks, and the header tells the decoder where each "block" of these chunks exists.  The stsc table says how many items per chunk exist. The first chunk says where that new chunk starts. It's a little confusing, but look at my example. This is saying that you have 100 samples per chunkk, up to the 8th chunk. At the 8th chunk there are 98 samples.

STCO
That said, you also have to track where the offsets of these chunks are. That's the job of the stco table.  So, where in the file is chunk offset 1, or chunk offset 2, etc.

If you modify any data in mdat you have to maintain these tables. You can't just chop mdat data out, and expect the decoder to know what to do.
As if this wasn't enough, now you have to also maintain the sample time table (stts) the sample size table (stsz) and if this was video, the sync sample table (stss).
STTS
stts says how long a sample should play for in units of the timescale. If you're doing audio the timescale is probably 44100 or 48000 (kHz).

If you've lopped off some data, now everything could potentially be out of sync. If all the values here have the exact same duration though you'd be OK.
STSZ
stsz says what size each sample is in bytes. This is important for the decoder to be able to start at a chunk, and then go through each sample by its size.

Again, if all the sample sizes are exactly the same you'd be OK. Audio tends to be pretty much the same, but video stuff varies a lot (with keyframes and whatnot)
STSS
And last but not least we have the stss table which says which frame's are keyframes. I only have experience with AAC, but every audio frame is considered a keyframe.  In that case you can have one entry that describes all the packets.

In relation to your original question, the time display isn't always honored the same way in each player. The most accurate way is to sum up the durations of all the frames in the header and use that as the total time. Other players use the metadata in the track headers.  I've found it best to just keep all the values the same and then players are happy.
If you're doing all that and I missed it in the script then can you post a sample mp4 and a standalone app and I can try to help you out.


text:
Q: How to prove that the line perpendicular to the radius is the tangent in the calculus sense? Let $P=(p_1,p_2)$ be a point on an semicircle and $r$ be the line perpendicular to the radius $\overline{OP}$, like the picture below.

Euclid showed (Book III, Proposition 16) that $r$ does not intersect the semicircle at any point other than $P$.
I'd like help to show that $r$ satisfies the calculus definition of the tangent line to the semicircle at $P$. For this, we have to show that if $y$ is the function whose graph is the semicircle, then
$$\lim_{x\to p_1}\frac{y(x)-y(p_1)}{x-p_1}$$
exists.
Since the slope of $\overline{OP}$ is $-p_2/p_1$ we know that the value of the limit have to be $\displaystyle \frac{p_1}{p_2}=\frac{p_1}{y(p_1)}$.
This is a part of the John Molokach's proof of the Pythagorean Theorem. So, we can not use the expression $y(x)^2=|\overline{OP}|^2-x^2$.
Thanks.

EDIT. Possible answer to my question: (Is it right?) It is enough to prove that the limits
$$\lim_{x\to p_1^+}\frac{y(x)-y(p_1)}{x-p_1}\tag{1}$$
and
$$\lim_{x\to p_1^-}\frac{y(x)-y(p_1)}{x-p_1}\tag{2}$$
exists and are equal.
Given $x\in(p_1,0)$, consider the lines $s(x)$, $t(x)$ and $u(x)$ as in the picture below.

Notice that
$$\text{slope of }t(x)\leq\text{slope of }s(x)\leq\text{slope of }r=\frac{p_1}{y(p_1)}.$$
So, if we assume $y$ continuous, we conclude that
$$\lim_{x\to p_1^+}[\text{slope of }t(x)]=\lim_{x\to p_1^+}\frac{x}{y(x)}=\frac{p_1}{y(p_1)}.$$
It follows from the squeeze theorem that
$$\lim_{x\to p_1^+}[\text{slope of }s(x)]=\frac{p_1}{y(p_1)}.$$
This shows that the limit $(1)$ exists and is equal to $p_1/y(p_1)$ because
$$\frac{y(x)-y(p_1)}{x-p_1}=\text{slope of }u(x)=\text{slope of }s(x).$$
The limit $(2)$ can be dealt analogously and a similar reasoning works if $p_1>0$.

A: I don't think there is any calculus argument.  There is a classical geometry argument though.
Suppose that the circle $\Gamma$ centered at $O$ with radius $OP$ intersects the line $r$ perpendicular to $OP$ at $P$ in another point $Q \neq P$.  Then, since the sum of all angles in the triangle $OPQ$ is $180^\circ$ and $OPQ$ is nondegenerate, we have $$\angle OQP = 180^\circ-\angle OPQ-\angle POQ =90^\circ-\angle POQ<90^\circ=\angle OPQ\,.$$
Since the greater angle of a triangle is subtended by a greater side, $OP<OQ$.  This contradicts the assumption that $Q$ is on $\Gamma$ (whence $OQ$ must equal $OP$).

A: I don't know how much of the development of Calculus you want to use. If you're willing to accept an answer that doesn't proceed directly from the definition, but uses techniques at some remove from the definition, then try this:
You might as well assume that your circle is the unit circle, $x^2+y^2=1$. Using implicit differentiation, $2x\,dx+2y\,dy=0$, thus $\frac{dy}{dx}=-x/y$. The tangent to the circle at point $(a,b)$ thus has slope $-a/b$, while the slope of the radius is $b/a$. Each of these slopes is the negative reciprocal of the other, so the tangent is perpendicular to the radius.

A: Long after Euclid differential calculus came into being, it included differential generality about all curves and their curvature, not just circles.
Molokach looks at the tangent as
1) Limiting case of the secant of coincident points is tangent ,
when
2) Radius of curvature is constant.
which is a typical view from differential calculus.
Let the slope at $r$ be a calculus definition of the tangent line to any curve at $P$. We have a normal to the tangent, there is no fixed radius or center..
$$ \lim_{x\to p_1}\frac{y(x)-y(p_1)}{x-p_1} = yd(x) $$
Curvature $ 1/\overline{OP}$ at P is ( s is arc length) is its change rate:
$$ \dfrac{d (tan^{-1} yd(x))  }  { ds } = \dfrac  { yd^{'} (x) }{  ( 1 + yd^2(x))^{3/2}}   $$
the circle is a special case when the above is a constant.

A: Here is a short outline of the proof that I think will answer your concern:

*

*Assume via Euclid that the tangent line to the semicircle is perpendicular to the radius drawn to the point of tangency.

*Slope of line containing radius is $\frac{dy}{dx}=\frac{y}{x}$, so slope of tangent line is $\frac{dy}{dx}=-\frac{x}{y}$.

*The general solution to the equation $\frac{dy}{dx}=-\frac{x}{y}$ is $x^2+y^2=C.$  Use the fact that the curve must pass through $(0,c)$ to solve for $C=c^2$ and then notice that the curve will pass through a point $(a,b)$ also so that $a^2+b^2=c^2.$

Essentially I created this argument with the notion that the PT can stem from the circle equation instead of the usual argument that uses the PT to write the equation of the circle.
As far as the exercise for the reader, that phrase was added by the editor of The American Mathematical Monthly as sort of a way to save some space in the page filler.  It would really only take a few lines to explain this...
First, if the point $P$ has coordinates $(x_1,y_1)$, then the equation of the tangent line is
$$y-y_1=\left.-\frac{x}{y}\right|_{(x_1,y_1)}(x-x_1).$$
Based on the previous argument, the line contains $P$ and its slope at $P$ is the same as the first derivative of the curve at $P.$

A: I fully agree with Batominovski that there is no calculus argument. For calculus argument to work one needs the functional relation between $x, y$.
It is easy to prove using Euclid axioms that if $OP$ is radius of a circle with center $O$ so that $P$ lies on the circle and $PT$ is any line through $P$ then line $PT$ intersects the circle at only one point $P$ if and only if $\angle OPT = \pi/2$. Such a line $PT$ is called tangent and based on figure if $P$ is $(x, y)$ then slope of $PT$ comes to be $-x/y = dy/dx$ and this gives $x^{2} + y^{2} = k$ and Pythagoras theorem can be established as mentioned in linked article in the question.
Update: We can further use the definition of tangent as given in calculus. Let $P(x, y)$ be a point on the curve and let $P'(x', y')$ be another nearby point on the curve. If the chord $PP'$ stabilizes in a unique direction as point $P'$ moves towards $P$ then the line through $P$ in that unique direction is said to be tangent to the curve at point $P$.
We add some rigor in the previous definition. If there is a unique line $PT$ passing through $P$ such that for any $\epsilon > 0$ there are points $P' P''$ on the curve with $P' \neq P \neq P''$ and $P$ on arc $P'P''$ such that the both the angles "between lines $PT$ and $PQ'$" and "between $PT$ and $PQ''$" where "$Q'$ is any point on arc $PP'$" and "$Q''$ is any point on arc $PP''$" are less than $\epsilon$ then we say that line $PT$ is a tangent to the curve at $P$.
Using this definition also we can show that tangent to a circle at a point is perpendicular to the radius passing through that point. Note further than this is still one step away from the concept of derivative. Here we are considering the existence of a unique direction in the limiting case when $P'$ moves towards $P$. Thus we are talking of the angle which the tangent makes with the $X$ axis.
In order to show that existence of tangent also leads to existence of derivative we need only need to worry about the special case when point $P$ lies on $X$ axis (i.e. when tangent is parallel to $Y$ axis) because $\tan \theta$ is undefined at $\theta = \pm(\pi/2)$. For other points on the circle $P$ the angle $\theta$ made by tangent at $P$ to the $X$ axis is such that $\tan \theta$ is defined and hence the slope/derivative $\dfrac{dy}{dx} = \tan \theta$ exists.


text:
Q: RabbitMQ dead letter handling guarantees If I use publisher confirms, I can be (reasonably) sure that a message sent to an exchange on the RabbitMQ server, and which received ACK from the RabbitMQ server is not lost even if the RabbitMQ server crashes (power outage for example).
However what happens when a message arrives at a dead letter exchange after a manual rejection in the consumer? (channel.basicReject, I use Spring AMQP.)
Can I still be sure that in the case in which the original message is dequeued from the queue to which the consumer is listening, and the RabbitMQ server subsequently crashes, I will eventually find the message, after the RabbitMQ server is restarted, in the queues which are bound to the dead letter exchange (if normally the message would have arrived there)?
If the answer is negative, is there a way to ensure that this is the case?

A: As @GaryRussell suggested, I posted a similar question on rabbitmq-users Google group.
Here is the answer I got from Daniil Fedotov
"Hi,

There is no delivery guarantees in place. Dead lettering does not check if the message was enqueued or saved to disk.
Dead-lettering does not use publisher confirms or any other confirm mechanisms.

It's not that easy to implement reliable dead-lettering from one queue to another and there are plans to address this issue eventually, but it may take a while.

If you want to safely reject messages from the consumer without a risk of losing them - you can publish them from the consumer application manually to the dead-letter queue, wait for the confirmation and then reject."


text:
Q: Checking a null value in a join query after 2 joins and a where or condition I have a linq query that is checking to see if a value exists, given criteria. It joins Permits, AccessControlTypes, and EntanceEnhancementHistories, all on their Guid FKs. It checks Permits of Type "Full" or "Limited" to see if they have any associated EntranceEnhancementHistories.
bool LimitedorFullEntranceEnhancementValue = (
     from p in context.Permits
     join a in context.AccessControlTypes on p.EntranceAccessControlTypeGUID equals a.GUID
     join e in context.EntranceEnhancementHistories on p.GUID equals e.PermitGUID
     where p.GUID.Equals(PermitGuid)
       && ((a.Description.Equals("Full") || a.Description.Equals("Limited"))
       && (e.GUID == null))
     select e).Any();
return LimitedorFullEntranceEnhancementValue;

This query is failing. It's returning false in the case that is does find description of full or limited, but does not find an entrancehancementvalue (it should be null).
It works properly without the check for a null entranceenhancementvalue, and I'm able to get it working with 2 queries, but I don't think this should be necessary.

A: You're using an "inner join" on p.GUID equals e.PermitGUID, which means you'll only see results where an e.PermitGUID exists. I think you want something more like this:
 (from p in context.Permits
 join a in context.AccessControlTypes on p.EntranceAccessControlTypeGUID equals a.GUID
 where p.GUID.Equals(PermitGuid)
   && ((a.Description.Equals("Full") || a.Description.Equals("Limited"))
   && !context.EntranceEnhancementHistories.Any(e => p.GUID == e.PermitGUID)
 select p).Any();

A: You need to use a LEFT OUTER JOIN if you expect to see rows where the Guid key is null:
(from p in context.Permits
 join a in context.AccessControlTypes on p.EntranceAccessControlTypeGUID equals a.GUID
 join t in context.EntranceEnhancementHistories on p.GUID equals e.PermitGUID into leftJoin
 join e in leftJoin on p.DefaultIfEmpty()
 where p.GUID.Equals(PermitGuid)
   && ((a.Description.Equals("Full") || a.Description.Equals("Limited"))
   && (e.GUID == null))
 select e).Any();

return LimitedorFullEntranceEnhancementValue;


text:
Q: walrus operator in dict comprehension I wanted to avoid double evaluation of a mean in a dict comprehension, and I tried using the walrus operator:
>>> dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]}
>>> q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65}

but this gave me the following error:
Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65}
  File "<pyshell#2>", line 1, in <dictcomp>
    q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if mean > 65}
  NameError: name 'mean' is not defined

This error only happens when I try to use the variable, no problem while defining it:
>>> q = {x: (mean := (sum(dic[x]) // len(dic[x]))) for x in dic if (sum(dic[x]) // len(dic[x])) > 65}
>>> mean
86
>>> q
{'B': 77, 'C': 87, 'D': 86}

Why? Where did I get it wrong?

A: You need to place the assignment expression in the conditional of the comprehension, not the value component of the dictionary:
dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]}
q = {x:mean for x in dic if (mean := (sum(dic[x]) // len(dic[x]))) > 65}

Output:
{'B': 77, 'C': 87, 'D': 86}

A: Your code is roughly equivalent to
q = {}
for x in dic:
    if mean > 65:
        mean := ...
        q[x] = mean

which means you are using mean before assigning it.
You need to move the definition to the if-clause-section of the dict-comprehension.
>>> dic = {"A": [45,58,75], "B": [55,82,80,92], "C": [78,95,90], "D":[98,75]}
>>> q = {x: mean for x in dic if (mean := (sum(dic[x]) // len(dic[x]))) > 65}
>>> q
{'B': 77, 'C': 87, 'D': 86}

This translates to
q = {}
for x in dic:
    if (mean := ...) > 65:
        q[x] = mean


text:
Q: Error when using rfe in caret with a PLS-DA model I'm trying to use rfe function from the caret package in combination with PLS-DA model.
sessionInfo()

R version 3.1.1 (2014-07-10)
Platform: x86_64-apple-darwin10.8.0 (64-bit)

locale:
[1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8

attached base packages:
 [1] splines   grid      parallel  stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
 [1] mclust_4.4            Kendall_2.2           doBy_4.5-13           survival_2.37-7       statmod_1.4.20
 [6] preprocessCore_1.26.1 sva_3.10.0            mgcv_1.8-4            nlme_3.1-119          corpcor_1.6.7
[11] car_2.0-22            reshape2_1.4.1        gplots_2.16.0         DMwR_0.4.1            mi_0.09-19
[16] arm_1.7-07            lme4_1.1-7            Matrix_1.1-5          MASS_7.3-37           randomForest_4.6-10
[21] plyr_1.8.1            pls_2.4-3             caret_6.0-41          ggplot2_1.0.0         lattice_0.20-29
[26] pcaMethods_1.54.0     Rcpp_0.11.4           Biobase_2.24.0        BiocGenerics_0.10.0

loaded via a namespace (and not attached):
 [1] abind_1.4-0         bitops_1.0-6        boot_1.3-14         BradleyTerry2_1.0-5 brglm_0.5-9         caTools_1.17.1
 [7] class_7.3-11        coda_0.16-1         codetools_0.2-10    colorspace_1.2-4    compiler_3.1.1      digest_0.6.8
[13] e1071_1.6-4         foreach_1.4.2       foreign_0.8-62      gdata_2.13.3        gtable_0.1.2        gtools_3.4.1
[19] iterators_1.0.7     KernSmooth_2.23-13  minqa_1.2.4         munsell_0.4.2       nloptr_1.0.4        nnet_7.3-8
[25] proto_0.3-10        quantmod_0.4-3      R2WinBUGS_2.1-19    ROCR_1.0-5          rpart_4.1-8         scales_0.2.4
[31] stringr_0.6.2       tools_3.1.1         TTR_0.22-0          xts_0.9-7           zoo_1.7-11

To practice I ran the following example using the iris data.
data(iris)
subsets <- 2:4
ctrl <- rfeControl(functions = caretFuncs, method = 'cv', number = 5, verbose=TRUE)
trctrl <- trainControl(method='cv', number=5)
mod <- rfe(Species ~., data = iris, sizes = subsets, rfeControl = ctrl, trControl = trctrl, method = 'pls')

All works well.
mod
Recursive feature selection

Outer resampling method: Cross-Validated (5 fold)

Resampling performance over subset size:

 Variables Accuracy Kappa AccuracySD KappaSD Selected
         2   0.6533  0.48    0.02981 0.04472
         3   0.8067  0.71    0.06412 0.09618        *
         4   0.7867  0.68    0.07674 0.11511

The top 3 variables (out of 3):
   Sepal.Width, Petal.Length, Sepal.Length

However, if I try to replicate this on data I have generated I get the following error. I can't work out why! If you have any ideas I'd be really interested in hearing them.
x <- as.data.frame(matrix(0,10,10))
for(i in 1:9) {x[,i] <- rnorm(10,0,1)}
x[,10] <- as.factor(rbinom(10, 1, 0.5))
subsets <- 2:9
ctrl <- rfeControl(functions = caretFuncs, method = 'cv', number = 5, verbose=TRUE)
trctrl <- trainControl(method='cv', number=5)
mod <- rfe(V10 ~., data = x, sizes = subsets, rfeControl = ctrl, trControl = trctrl, method = 'pls')

Error in { : task 1 failed - "undefined columns selected"

In addition: Warning messages:
1: In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  :
  There were missing values in resampled performance measures.

2: In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  :
  There were missing values in resampled performance measures.

3: In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  :
  There were missing values in resampled performance measures.

4: In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  :
  There were missing values in resampled performance measures.

5: In nominalTrainWorkflow(x = x, y = y, wts = weights, info = trainInfo,  :
  There were missing values in resampled performance measures.

A: I have worked out (after a lot of to-ing and fro-ing) that levels of the response factor variable have to be characters to combine PLS-DA with RFE in caret.
For example...
x <- data.frame(matrix(rnorm(1000),100,10))
y <- as.factor(c(rep('Positive',40), rep('Negative',60)))
data <- data.frame(x,y)
subsets <- 2:9
ctrl <- rfeControl(functions = caretFuncs, method = 'cv', number = 5, verbose=TRUE)
trctrl <- trainControl(method='cv', number=5)
mod <- rfe(y ~., data, sizes = subsets, rfeControl = ctrl, trControl = trctrl, method = 'pls')


text:
Q: Can I tell MVC to separate pascal-cased properties in to words automatically? I often have C# code like
    [DisplayName("Number of Questions")]
    public int NumberOfQuestions { get; set; }

Where I use the DisplayName property to  add in spaces when it is displayed. Is there an option to tell MVC to add spaces by default if the DisplayName annotation is not explicitly provided?
Thanks

A: There are two ways.
1.Override LabelFor and creating a custom HTML helper:

*

*Utility class for Custom HTML helper:
public class CustomHTMLHelperUtilities
{
// Method to Get the Property Name
internal static string PropertyName<T, TResult>(Expression<Func<T, TResult>> expression)
 {
    switch (expression.Body.NodeType)
    {
        case ExpressionType.MemberAccess:
            var memberExpression = expression.Body as MemberExpression;
            return memberExpression.Member.Name;
        default:
            return string.Empty;
    }
 }
 // Method to split the camel case
 internal static string SplitCamelCase(string camelCaseString)
 {
    string output = System.Text.RegularExpressions.Regex.Replace(
        camelCaseString,
        "([A-Z])",
        " $1",
        RegexOptions.Compiled).Trim();
    return output;
 }
}

*Custom Helper:
public static class LabelHelpers
{
 public static MvcHtmlString LabelForCamelCase<T, TResult>(this HtmlHelper<T> helper, Expression<Func<T, TResult>> expression, object htmlAttributes = null)
  {
    string propertyName = CustomHTMLHelperUtilities.PropertyName(expression);
    string labelValue = CustomHTMLHelperUtilities.SplitCamelCase(propertyName);

    #region Html attributes creation
    var builder = new TagBuilder("label ");
    builder.Attributes.Add("text", labelValue);
    builder.Attributes.Add("for", propertyName);
    #endregion

    #region additional html attributes
    if (htmlAttributes != null)
    {
        var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
        builder.MergeAttributes(attributes);
    }
    #endregion

    MvcHtmlString retHtml = new MvcHtmlString(builder.ToString(TagRenderMode.SelfClosing));
    return retHtml;

  }
}

*Use in CSHTML:
@Html.LabelForCamelCase(m=>m.YourPropertyName, new { style="color:red"})

Your label will display as 'Your Property Name'
2.Using Resource File:
[Display(Name = "PropertyKeyAsperResourceFile", ResourceType = typeof(ResourceFileName))]
public string myProperty { get; set; }

I will prefer the first solution. Because a resource file is intend to do a separate and reserved role in a project. Additionally the custom HTML helper can be reused once created.


text:
Q: Recommending new products using k-means clusters? I'm trying to figure out the best way to recommend images based on past classifications using k-means clusters. What I have done is mapped the RGB values of a set of images, performed a k-means cluster analysis on those RGB values, and attached a "rating" to each image. This has created Voronoi cells similar to this graph. I've stored the cluster centers and ratings into my "training set".
The next step is to take a new image and make a recommendation based on the training set previous images. I'm not sure how to proceed. Would I want to implement a Collaborative Filtering process? Or do I need to perform more processing on the data?
Not sure if it matters but I'm using Apache Spark for the project. Thanks!
Edit: Collaborative filtering is probably not the best way to proceed, since the features being compared for products uses more than just ratings. I need to compare the similarity. I'm guessing this would involve heavy matrix operations?
Edit2: Some feedback here would be awesome. What I'm thinking is training two datasets (a rating of "yes" images vs. "no" images) and then using Spark's computeCost function to develop a value for variance/bias of an image being compared. The final step would then compare whether the image was more similar to the "yes" dataset or "no" dataset, and then make a final recommendation. I'm new to machine learning, so I could be over-thinking it.

A: Thought I'd answer my own question here with my final solution. I realized that although I could get some partially meaningful data from k-means clustering of RGB values, the problem was that the recommendation was not based on meaningful characteristics of the image. It could potentially be useful in the future for other aspects (such as lighting or "brightness").
The final solution was using EigenFaces for image learning. The article below was the most helpful for me to understand the basics and get going:
https://chimpler.wordpress.com/2013/04/17/generating-eigenfaces-with-mahout-svd-to-recognize-person-faces/


text:
Q: 3-tier architecture without JavaEE Question in short:
Is it possible to gradually convert to 3-tier architecture from 2-tier?
Question as it is:
We have a messy kind-of-2-tier application. Presentation is in php, Data in Oracle, Business Logic partially in PLSQL, partially in JavaSE, partially in Php. It is impossible to kill the current software architect, throw everything away and restart with WildFly, for example (unfortunately).
Is it possible to start making layers gradually?
For example, JavaSE applications with Business Logic will stop putting data back to SQL, but what is the right way for Php to get data from JavaSE?
I've read about SOAP a little, but if website on Php will start getting/sending all data through it, it will be extremely cumbersome (as I see it)

A: Just my opinion:
I will go for rewriting your backend in Java (SE or even EE) completely. You can also have advantages for your data-layer access using ORM's like Hibernate. The best way to work im my opinion is to use RESTful webservices or SOAP. There are many libraries for PHP (including the SOAP extension) so you don't have to worry about using SOAP with PHP.
Give a read to:
http://php.net/manual/en/book.soap.php
Many PHP frameworks support SOAP and will give a big help when refactoring your frontend.
So in few words. Your frontend (php) will call Java backend businnes layer that will make all the businnes logic (you may port your PLSQL logic here) and than finally dialogate with your Data layer.


text:
Q: C# TSQL DDL with many values I have a label that's being populated via a two Dropdowns. However I want to clean up the selection and populating process as currently I think my frontend logic (ddl) is not executing in order. What I need is populate the number of records that exist (in the label). Also for those who want to query the backend first please note that this query works fine in MS SQL Server and I get back 1 record(s). Any suggestions? Thanks to all help.
C#:
        int sType = 0;
        if(ddlType.SelectedIndex == 0)
        {
            //Clinical skills
            sType = 1;
        }
        else if (ddlType.SelectedIndex == 1)
        {
            //Response
            sType = 1;
        }
        else if (ddlType.SelectedIndex == 2)
        {
            //Behaviour
            sType = 1;
        }
        else if (ddlType.SelectedIndex == 3)
        {
            //bravery
            sType = 1;

        }
        else if (ddlType.SelectedIndex == 4)
        {
            //Clinical skills
            sType = 1;
        }
        else if (ddlType.SelectedIndex == 5)
        {
            //Clinical skills
            sType = 1;
        }

    if (ddlDivisionsCompliments.SelectedValue == "East Central")
    {
        string sSql = "SELECT RefNo AS [Records]" +
                       "FROM dbo.tbl_compliments " +
                       "WHERE (Compliment_Clinical = '" + sType + "' " +
                        " OR Compliment_Response = '" + sType + "' " +
                        " OR Compliment_Behaviour = '" + sType + "' " +
                        " OR Compliment_Bravery = '" + sType + "' " +
                        " OR Compliment_Teamwork = '" + sType + "' " +
                        " OR Compliment_Other = '" + sType + "' )" +
                        "AND Compliment_division = 'East Central '" +
                      "AND (ComplimentDate >= '" + sStart + "' " +
                      "AND ComplimentDate <= '" + sEnd + "' )";//+
        //"ORDER BY MIN(ComplimentDate)";
        DataTable dt = new DataTable();
        dt = DBConnect.DataReaderDataTable(sSql);

        if (dt.Rows.Count > 0)
        {
            divResults.Visible = false;
            divSave.Visible = true;
            gv.DataSource = dt;
            gv.DataBind();
            lblCount.Text = "For this selection there are " + dt.Rows.Count.ToString() + " record(s) in the database.";
        }
        else
        {
            divResults.Visible = false;
            gv.DataBind();
            lblCount.Text = "No records!";
            //lblCount.TextCssClass = "Alert";
        }

    }

SOLVED : Nested-ifs solved it. ;-) so the code I used might help someone else and this is below:
if (ddlDivisionsCompliments.SelectedItem.Value == "02")
        {

            if (ddlType.SelectedItem.Value == "01" )
            {

                string sSql = "SELECT RefNo AS [Records] " +
                               "FROM dbo.tbl_complaints " +
                               "WHERE (Compliment_Response = '" + sType + "' )" +
                                "AND Compliment_division = 'East Central' " +
                              "AND ComplimentDate >= '" + sStart + "' " +
                              "AND ComplimentDate <= '" + sEnd + "' ";

A: SOLVED : Nested-ifs solved it. ;-) so the code I used might help someone else and this is below:
if (ddlDivisionsCompliments.SelectedItem.Value == "02")
        {

            if (ddlType.SelectedItem.Value == "01" )
            {

                string sSql = "SELECT RefNo AS [Records] " +
                               "FROM dbo.tbl_complaints " +
                               "WHERE (Compliment_Response = '" + sType + "' )" +
                                "AND Compliment_division = 'East Central' " +
                              "AND ComplimentDate >= '" + sStart + "' " +
                              "AND ComplimentDate <= '" + sEnd + "' ";


text:
Q: Adding Columns to Google Drive Spreadsheet I am using the Php based Google Drive API to create Spreadsheets.
I am able to create the spreadsheets in the drive properly.
I would like to add columns to the created SpreadSheet document so I can start adding content to it later.
I tried a few things, so mentioning them one after the other. Check the "data" str.
Here's my code:
//adding directly
$insertedFile = $dr_service->files->insert($file, array('data' => 'column1,column2,column3', 'mimeType' => 'application/vnd.google-apps.spreadsheet'));

//adding it by passing an array
$insertedFile = $dr_service->files->insert($file, array('data' => array("Column 1" => "data 2" ,"Column 2" => "data 2","Column 3" => "data 3"), 'mimeType' => 'application/vnd.google-apps.spreadsheet'));

As I mentioned in my earlier comments, the document is getting created successfully. Just not able to add column names to it.
Looking forward to hearing some solutions,
Thanks,
Mihir.

A: Add columns
To add a new column name, use CellFeed. CellFeed is part of google-spreadsheet-API.
I assume you are using ListFeed. ListFeed will not let you add columns. List feed is more like SQL. Works a little like SQL style INSERT and SELECT.


text:
Q: How to animate uiimageview when changing device orientation I have a single UIImageView which is used to display a background image for my app so takes up the whole screen, the image is changed between 1 of 4 images depending on the screen size/device (480points or 568points) & the orientation.
I've been searching to find if there is a way to animate the switching of the image between orientations as when the device is rotated currently the switch over is quite 'harsh' & briefly shows the white space behind.
Most of what I have found from google/here is people asking how to animate changing between uiimageviews which is not what I want, i just change the image that is displayed in the single uiimageview in code as in this snippet:
- (void)doLayoutForOrientation:(UIInterfaceOrientation)orientation {
if (IS_WIDESCREEN && UIInterfaceOrientationIsPortrait(orientation)) {
    self.backgroundImage.image = [UIImage imageNamed:@"iPhone5backgroundPortrait.png"];
    _backgroundImage.frame = CGRectMake(0, 0, 320, 568);
} if (IS_NOT_WIDESCREEN && UIInterfaceOrientationIsPortrait(orientation)) {
    self.backgroundImage.image = [UIImage imageNamed:@"iPhone4backgroundPortrait.png"];
    _backgroundImage.frame = CGRectMake(0, 0, 320, 480);
} if (IS_WIDESCREEN && UIInterfaceOrientationIsLandscape(orientation)) {
    self.backgroundImage.image = [UIImage imageNamed:@"iPhone5backgroundLandscape.png"];
    _backgroundImage.frame = CGRectMake(0, 0, 568, 320);
} else if (IS_NOT_WIDESCREEN && UIInterfaceOrientationIsLandscape(orientation)) {
    self.backgroundImage.image = [UIImage imageNamed:@"iPhone4backgroundLandscape.png"];
    _backgroundImage.frame = CGRectMake(0, 0, 480, 320);

I have tried the [animateImageNamed: duration:] method but when the device is rotated the background disappears!
thanks

A: Did you try changing the image in:
- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration

? Also, at some point prefetch the images so they are already in the image cache when the rotation happens - otherwise the first one may have a bit of delay.


text:
Q: Num Pad on Apple Keyboard in Java Application fires two events I use netbeans IDE 7.1.2 for Development on Ubuntu 12.04. When typing numbers with the num pad the digit is displayed and the cursor relocated as if used the num pad with num lock disabled.
In Eclipse the keyboard mapping is fine. All i could find on this topic is this:
http://netbeans.org/bugzilla/show_bug.cgi?id=145417
I also tried using a different JVM (Oracle instead of OpenJDK) with the same results.

A: I finally found keyboard options which give me acceptable results. Under Verschiedene Optionen zur Kompatiblität (Miscellaneous compatibility options) i enabled the settings:

*

*Apple Aluminium Keyboard: PC-Tasten emulieren (Druck, Scroll Lock, Pause, NumLock) (Apple Aluminium Keyboard: emulate PC keys (Print, Scroll Lock, Pause, Num Lock))

*Vorgegebene Nummernblocktasten (Default numeric keypad keys)

This also solved my problem that i couldn't copy and paste out of netbeans into a native application.


text:
Q: Why is my foreach loop returning an extra index position? I am pulling text from a .txt, I explode the line then re-explode it so it can be stored as an array. When I print_r after the 2nd explode it outputs an array with a 4th index position when it should only have 0 1 2 3. Any ideas why?
Any help is appreciated, thank you.
PHP
 list($title, $author, $publisher, $isbn) = explode('*', $line);

    print_r($line); //outputs a string

    $books = explode('*', $line);
    echo "<br>";
    print_r($books); //outputs array with extra index position.

Sample of Output
Array ( [0] => Business 101 [1] => John Smith[2] => 2002-07-18 [3] => 1-444-2589-x [4] => )

Sample of line from .txt file
Business 101*John Smith*2002-07-18*1-444-2589-x*

A: Please, share the content of $line, so I can try to help you.
I imagine just one explanation: $line have more values that you expect.
This is comprehensive if you import the data from a file (for example, a CSV file).
So, check if there's something like this:
BookName*Author*PublishDate*ISBN*

Have you seen the last *? This is the problem.
Explode function read the last * and create another field in the array.
If you want to fix this, you can remove the last *, or just pass a limit to your explode function (3 is the number, try it).
array explode(string $delimiter, string $string, int $limit);

Hope it helps you.
Best regards.