text:
Q: databinding dictionary  to a dependency property I need some help!
I have build a custom control and added to it a DependencyProperty of type:
Dictionary<string,int>

and from the XAML where the control is held I do a data binding to bind to the Dictionary outside the control.
here are some code snippets:
View model of the control who hold the custom control
private Dictionary<string, int> _wordsList;

public Dictionary<string, int> WordsList
{
    get
    {
        return _wordsList;
    }
    set
    {
        _wordsList = value;
        RaisePropertyChanged("WordsList");
    }
}

public WordsViewModel()
{
    //CalculateWordsDictionary returns a dictionary<string,int>
    WordsList = CalculateWordsDictionary(texts);
}

XAML:
<local:MyControl WordsList="{Binding Path=WordsList}" />

Code behind of the custom control:
public Dictionary<string, int> WordsList
{
    get { return (Dictionary<string, int>)GetValue(WordsListProperty); }
    set { SetValue(WordsListProperty, value); }
}

// Using a DependencyProperty as the backing store for WordsList.  This enables animation, styling, binding, etc...
public static readonly DependencyProperty WordsListProperty =
    DependencyProperty.Register("WordsList", typeof(Dictionary<string, int>), typeof(MyControl), new PropertyMetadata(new Dictionary<string, int>()));

I've set a break point on the set of the DependencyProperty and it never reaches this point.
I just can't figure out why this isn't working... or maybe there is some other way to pass the dictionary to the control?
btw
I am using MVVM Light

A: the important stuff you did not post:) whats your binding within your usercontrol? you have to use some kind of "local binding" so that your MyControl binds to it dependency property. you can use ElementName binding like this:
EDIT: here is the code for the UserControl called MyControl (just a snippet)
 <MyControl x:Name=uc>
   <ContentControl Content="{Binding ElementName=uc, Path=WordsList}"/>

A: Fixed!!!!!
All the comments together was the question
I there was a DataContext defined, I removed it completely. Also I registered the property changed callback
worked as charm!
Thanks to all


text:
Q: Sum three text fields whose values are controlled by jqueryui sliders I have three jqueryui sliders that output numbers (stored in arrays) to three text fields (that have css class .add). I need the three text fields to be summed and the total to be shown in a text field (with id #amount) automatically whenever the sliders are changed. I have tried this:

But it only sums the three text fields if I manually type numbers into them. I also need the flexibility to change the default starting amount (var = sum 10;) whenever needed and have it display in the #amount field on page load (it does not display on page load atm).

A: For the UI slider, you need to use the slider change event and value method to get the value

jQuery(function($) {
  $('.add').slider({
    min: 0,
    max: 10
  })
});

var calcPrice = jQuery.noConflict();
var basePrice = 10;
calcPrice('#amount').val(basePrice);
calcPrice('.add').on('slidechange', function() {
  var sum = basePrice;
  calcPrice('.add').each(function() {
    sum += Number(calcPrice(this).slider('value')) || 0;
  });
  calcPrice('#amount').val(sum);

});
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.css" rel="stylesheet" />

<input id="amount" />

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I read Bytes from a File in Ruby 1.9? In Ruby 1.9 the File and IO libraries were changed -- they now seem to always interpret the data as encoded strings (e.g. UTF-8), and the returned values seem to be always strings.
I need to read a file in Ruby 1.9 byte by byte, without any modification or interpretation of the data.
I want to read byte sequences, not encoded strings.
Any tips on how to best do this?

A: I had a similar problem in a gem I wrote. Here's the relevant code:
(you don't need the require statements)
# ==============================================================================
# Loading Libraries and Stuff needed for Ruby 1.9 vs 1.8 Compatibility
# ==============================================================================
# the idea here is to define a couple of go-between methods for different classes
# which are differently defined depending on which Ruby version it is -- thereby
# abstracting from the particular Ruby version's API of those classes

if RUBY_VERSION >= "1.9.0"
  require "digest/md5"
  require "digest/sha1"
  include Digest

  require 'fileutils'        # replaces ftools
  include FileUtils::Verbose

  class File
    def read_bytes(n)  # returns a string containing bytes
          self.bytes.take(n)
    end
    def write_bytes(bytes)
      self.syswrite(bytes)
    end
    def get_byte
      self.getbyte     # returns a number 0..255
    end
  end

  ZEROBYTE = "\x00".force_encoding(Encoding::BINARY) unless defined? ZEROBYTE

else # older Ruby versions:
  require 'rubygems'

  require "md5"
  require "sha1"

  require 'ftools'
  def move(a,b)
    File.move(a,b)
  end

  class String
    def getbyte(x)   # when accessing a string and selecting x-th byte to do calculations , as defined in Ruby 1.9
      self[x]  # returns an integer
    end
  end

  class File
    def read_bytes(n)
      self.read(n)   # should use sysread here as well?
    end
    def write_bytes(bytes)
      self.write(bytes)   # should use syswrite here as well?
    end
    def get_byte     # in older Ruby versions <1.9 getc returned a byte, e.g. a number 0..255
      self.getc   # returns a number 0..255
    end
  end

  ZEROBYTE = "\0" unless defined? ZEROBYTE
end

A: IO has the binmode method (calling it is setting it), which disables newline and encoding conversion. The File class inherits this method.


text:
Q: Merging multiple CSV files using unique ID with Python I have a lot of different CSV files from two different locations, and I need to merge them using a unique id and another header name then write the data into another CSV file. Only the unique Id and each of the file headers.
So I have two files in different locations like that with a lot of different headers however I need only the name header to be written into another csv file.

unique id
name

1
a

2
b

At the end I want to get this:
| unique id| Name from file one || Name from file two |
| -------- | ------------------ ||--------------------|
| 1        | a                  || a                  |
| 2        | b                  || b                  |

I need to merge these field into another CSV file with unique id.


text:
Q: Live Preview in Mediawiki The MediaWiki manual states the following:

Enabling live preview
Live preview is on or off depending on
  the $wgLivePreview variable of
  LocalSettings.php. To activate it you
  must also enable it on a per-user
  basis in the "editing" tab of you user
  preferences page.

However, when I go to the article describing the variable $wgLivePreview, it says that this variable was deprecated in 1.15.x.
Is there any alternative and relatively similar way of enabling Live Preview in the current version (1.16.5) of Mediawiki?

A: It appears the variable (along with live preview itself) was removed in r59446; the feature was then restored in r62173 and turned completely always-on in r65390.
It looks like 1.16 was branched from around r62818, so you can set $wgLivePreview to make the option visible in the user preferences. Or apply r65390 to your local installation, or install the 1.17 beta release instead of 1.16.


text:
Q: Is there a way to have the hunchentoot:*dispatch-table* update automatically on function redefinition? I have set up the dispatch-table in the following-manner:
(setq hunchentoot:*dispatch-table*
        (mapcar #'(lambda (regex-and-handler)
                    (hunchentoot:create-regex-dispatcher (first regex-and-handler)
                                                         (second regex-and-handler)))
                (list (list "^/one$" #'page-one)
                      (list "^/two$" #'page-two))))

Now, if I redefine the function page-one, the *dispatch-table* still uses the old definition, and uses the new definition only when the (setq ...) form is re-evaluated. Is there a way to get it to pick up the new function definition?

A: Use the function's names, as a symbol, instead of resolving the symbol to a function object with function (reader syntax #') when evaluating the list. In other words:
....
(list (list "^/one$" 'page-one)
      (list "^/two$" 'page-two))))


text:
Q: Wireframe and Shadows I'm working my way through the good intro Packt book "Learning Threee.js..." by Jos Dirksen.
On page39 he discusses the chapter-02/01-basicscene.html file and shows rendering a series of cubes with shadows. The example works fine solid objects but I when I make the cubes wireframe;
var cubeMaterial = new THREE.MeshLambertMaterial({color:  Math.random() * 0xffffff, wireframe: true });
I still see solid shadows on the plane.
Is this a known problem or is there a way of seeing just the wireframe shadows?
Thanks
Graham

A: It's a feature. :-)
When casting shadows, objects are treated as solid from the point of view of the light.
See this related post: Shadowmap texture alpha.
three.js r.66


text:
Q: OrbitControls not working with Loading file So I have this code which basically shows a 3D file (obj, stl, 3mf) inputted by the user using three js OBJLoader, STLLoader, and 3MFLoader. All works fine but I tried some (inside this code) to add OrbitControls to this so that the user can zoom in, zoom out, rotate, etc. with the file but it does not seem to work. The console has no errors at all but rotating, zooming in and out, etc. doesn't work as well with the render.
<input type="file" name="file" id="file" onchange="loadFile(event)" />

Can anyone check the code out and tell me why it is not working and how to fix it?

A: OrbitControls is not directly exported as part of the Three.js library; instead it's exported as part of the examples.
If you're using a bundler (such as WebPack) you can import it like this:
// Typical Three.js import
import * as THREE from "three"

// Additional OrbitControls import
import {OrbitControls} from "three/examples/jsm/controls/OrbitControls";

Or if you're using a script import, you can use this:

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

canvas {
  display: block;
}

Then you can use it like this:
const controls = new OrbitControls( camera, renderer.domElement, scene );

A: From docs:

controls.mouseButtons = {
        LEFT: THREE.MOUSE.ROTATE,
        MIDDLE: THREE.MOUSE.DOLLY,
        RIGHT: THREE.MOUSE.PAN
    }


text:
Q: Google Places / Business API - how to get special hours of any business? I would like to get opening hours for places in Google Maps into the future, these are defined in the Google My Business as "special hours" (christmas, etc)
In the Google Places API https://developers.google.com/places/web-service/details, it returns opening hours for this week only, no special hours. You can get special hours from the Google My Business API, but from what I gather it's only for businesses you administer, not for any business out there like you can get for Places. https://developers.google.com/my-business/reference/rest/v4/accounts.locations
There's a 3 year old request to add special hours to the Places API, but yeah, 3 years old. https://code.google.com/p/gmaps-api-issues/issues/detail?id=10145
Does anyone know of any method to get special hours for any Place ID out of Google?


text:
Q: CAShapeLayer strokeColor from image pattern UIColor to CGColor upside down I'm using CABasicAnimation to draw all UIBezierPaths i have in an Array using CAShapeLayer
CAShapeLayer *shapeLayer = [CAShapeLayer layer];
shapeLayer.path = [path CGPath];
shapeLayer.strokeColor = path.color.CGColor;

My path.color is a UIColor from image pattern. When it is converted to CGColor the image pattern is upside down. I know that is because iOS and core graphics use different starting points for drawing.
I have tried
shapeLayer.transform = CATransform3DMakeRotation(M_PI, 0.0, 0.0, 1.0);

and
shapeLayer.geometryFlipped = YES;

But none of them worked.
How do I flip the strokeColor image pattern 180 degree to match with the origin UIColor?

A: As you have correctly suspected, the coordinate system differs. In this case, the origin is at the bottom left at (0, 0).
So what you could do to compensate that is to either flip the image yourself using an image editor or do it in code like so:
UIImage *flippedPatternImage = [UIImage imageWithCGImage:patternImage.CGImage scale:1.0f orientation:UIImageOrientationLeftMirrored];

UIColor *colorWithImagePattern = [UIColor colorWithPatternImage:flippedPatternImage];

And finally assign it to the strokeColor:
shapeLayer.strokeColor = path.color.CGColor;


text:
Q: Regex to remove track number from song name? I have a ListView that display song names and artists. Sometimes, the song names contain the track number and a separator with some in this format
13 - J. Cole - Best Friend

and others like this
13 - Beautiful People

After some digging around I found that the best way to go about this is to define a regex pattern that will remove any unnecessary characters in the string. Cool. I've looked at other SO questions on a similar topic here and a couple blog posts but still no luck.
This my first time dealing with regular expressions and I find it quite useful, just trying to wrap my head around coming up with efficient/useful patterns.
Here's what I need to remove from the string if it is a match
The track number
The "-" or whatever separator character that follows it
The artist name and the "-" that follows that(Each artist name is listed below the   song, so it would be redundant)

Any help on this would be greatly appreciated as usual guys, thanks!
Edit: The same output that  I would like is something like this, with just the song names. No track numbers, and if applicable; no artist names following the "-"
Beautiful People
Angel of Mine
Human Nature

A: Here's a possible regex you could use:
name.replaceFirst("^\\d+\\.?\\s*-(?:.*?-)?\\s*", "")

This takes out:

*

*digits at the front

*optionally followed by a dot

*optionally spaces

*a hyphen

*if a further hyphen is found, then everything up to that

*optionally spaces

A: A piece of code will be better to give you a hint:
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {

    public static void main(String[] args) {

        String[] songNames = {
            "1 - my awesome artist - go beyond",
            "2 - such is life",
            "My awesome song"
        };

        Pattern trackNumberPattern = Pattern.compile("^ *\\d+ *- *");
        Pattern artistPattern = Pattern.compile(" *- *[^-]+ *- *");

        Matcher matcher;

        for(String song: songNames) {

            matcher = trackNumberPattern.matcher(song);
            if(matcher.find()) {
                song = matcher.replaceFirst("");
            }

            matcher = artistPattern.matcher(song);
            if(matcher.find()) {
                song = matcher.replaceFirst("");
            }

            System.out.println(">>> " + song);

        }
    }

}

You can find the doc to write regex in java here: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
DISCLAIMER: This won't work properly if some of the song names or artist names contain dashes (-), etc...

A: You can use this regex (a little bit radical):
^\\d*+\\W*+\\b(?>[^-]++-\\s++(?=\w))?

and replace it by nothing.
this will destroy all digits followed by non-word characters at the begining, and the interpret name if it is present


text:
Q: Visual Studio 2013 does not delete the copy constructor when a user-defined move constructor is provided I appreciate the C++11 standard dictates:

If the class definition does not explicitly declare a copy
  constructor, one is declared implicitly. If the class definition
  declares a move constructor or move assignment operator, the
  implicitly declared copy constructor is defined as deleted; otherwise,
  it is defined as defaulted.

(actually copied from here)
The following code:
#include <iostream>

struct C
{
    int x = 1;

    C()
    {
    }

    C(C&&)
    {
    }
};

int main()
{
    const C c;
    C c2(c);

    std::cout << c.x << " " << c2.x << std::endl;

    return 0;
}

does not compile on gcc 4.9.0, but compiles just fine on Visual Studio 2013 (Compiler Version 18.00.21005.1 for x86). Is this yet another Visual Studio violation of the standard, or am I doing something wrong this time? If this is a violation of the standard, is there a tracking bug or any source where this behaviour is documented?

A: You're not doing anything wrong, and your interpretation of the standard is correct. Visual C++ 2013 indeed does not implement these rules properly.
A relevant bug report is here:
Default copy constructor is generated even when a custom move constructor is defined [c++11]
It's marked as Won't Fix and the comment from the development team is:

Visual Studio 2013 indeed does not fully implement the C++11 rules
  governing special member functions and move operations. We will
  include a fix for this bug in the next major release of Visual Studio.

The good news is that things seem to be working properly in Visual C++ 2015 RC. I've just verified that your code triggers both compiler and IntelliSense errors. The compiler diagnostic is:
error C2280: 'C::C(const C &)': attempting to reference a deleted function

(From what I've tested during the past few months, MSVC14 is shaping up as a pretty good C++ compiler - lots of standard compliance issues have been fixed.)


text:
Q: Use page Title in Gutenberg custom banner block I have created a custom banner image block for Gutenberg, which works great, but
I want to know if it is possible to use the page title as the current banner text
placeholder until it has been edited?

My Edit function is
 return [
            el('div', {className:'header-banner'},
                el(
                    element.Fragment,
                    null,
                    controls,
                    el( "div",{
                        className: 'banner-image',
                        style: { backgroundImage: 'url('+attributes.mediaURL+')' }
                    },
                    attributes.title || isSelected ?  el(RichText, {
                            key: 'editable',
                            tagName: "h1",
                            className: "banner-title",
                            //Can i add the page title in here if it is avaiable??
                            //placeholder: i18n.__('Write title…'),
                            value: attributes.title,
                            onChange: function onChange(value) {
                                return props.setAttributes({ title: value });
                            },
                            inlineToolbar: true
                        }) : null

                    )
                )
            )//header-banner
        ];

Thanks :)

A: Gutenberg stores the current editor state using wp.data, which is an abstraction over Redux. To get the title (or 100+ other values), we need to query the core/editor data store. Gutenberg makes it simple to retrieve post attributes with getEditedPostAttribute.
Once we know where to look, getting the title is simple:
const { select } = wp.data;
const title = select("core/editor").getEditedPostAttribute( 'title' );

That works, but it's not responsive. When the post title changes, title won't reflect the new value. That's kind of a let down.
To reflect changes to the editor title, we need to listen for changes to the core/editor data store. There are a few ways to do this.
One solution is to define a simple change handler function and subscribe it to data store updates:
const { select } = wp.data;

function logTitle() {
  const title = select("core/editor").getEditedPostAttribute( 'title' );
  console.log("Editor Title:", title);
}
subscribe(logTitle);

That will fire when any wp.data store value is updated -- which happens a lot.
What seems to be the Gutenberg-sanctioned way of including data-store values is to use a higher-order component to include the value directly:
const GetTitle = props =>
{props.title}
;

const selectTitle = withSelect(select => ({
  title: select("core/editor").getEditedPostAttribute( 'title' )
}));
const PostTitle = selectTitle(GetTitle);

Then in the block's output, include a <PostTitle /> jsx tag. That's a lot cleaner than nested callbacks or another change handler.
Higher-order components can be difficult to follow. The short explanation is that they wrap a existing component, generate some data, then return a copy of the component with the new data passed as props. This separates logic from presentation and helps with maintainability.
GetTitle is simple enough, it's just a small component that takes in a props object with a title key and spits out some html.
withSelect is a function constructor or decorator. It accepts a function argument, and returns a new function which expects a component. Normally the returned function is invoked immediately (sort of an IIFE) but I stored it in the selectTitle variable for clarity. The new function generates an object containing the title, this object will be passed as props to any components passed to withSelect. Through some magic this will be called whenever the data store is updated.
In the end, PostTitle contains the function result of selectTitle which is a component pre-populated with the the generated props. This component can then be placed into our markup using a <PostTitle /> tag. Whenever the editor data-store is updated, the higher-level component will reflect the new data.

A: @joemaller thanks for the helpful response.
Here's an example that demonstrates using withSelect() to wrap a component defined via the edit property of the block configuration object passed to registerBlockType().
The component is passed the title via props.
If the user edits the post/page title, the component is re-rendered with the new title because its props will have changed. This enables it to update in "real time".
import { withSelect } from '@wordpress/data'

...
edit: withSelect(
  ( select ) => {
    return {
      title: select( 'core/editor' ).getEditedPostAttribute( 'title' ),
    }
  } )( props => {
    return (

{ props.title }

    )
} ),


text:
Q: Add metadata to JavaScript objects Is it possible to add metadata to JavaScript objects (including strings, numbers and functions)? That is,
double = function(a){ return a*2; };
addMetadata(double,{desc:"Returns the double of a number."});
getMetadata(double).desc;

How could addMetadata and getMetadata be implemented?

A: For objects, including functions, the best way to implement get/setMetadata is not to implement it at all.
double = function(a){ return a*2; };
double.desc = "Returns the double of a number."
alert(double.desc);

For "primitive" strings/numbers you can use a dictionary approach like suggested in another answer:
metaStorage = {}

setMetaData = function(obj, data) {
    if(typeof obj == "object")
        obj._metaData = data;
    else
        metaStorage[obj] = data;
}

getMetaData = function(obj) {
    if(typeof obj == "object")
        return obj._metaData;
    else
        return metaStorage[obj];
}

setMetaData(1, "this is one");
console.log(getMetaData(1))

setMetaData(window, "my window");
console.log(getMetaData(window))

However, I can't imagine how it could be useful to attach metadata to string/number literals.

A: You could do this :
var metaDataStorer = {};
function addMetadata(object, meta) {
    metaDataStorer[object] = meta;
}
function getMetadata(object) {
    return metaDataStorer[object];
}


text:
Q: Error 400: Bad Request Aggregate Exception when using Parse Query I am trying to check if a Parse Object exists on Parse so that I can then either upload a new object for the user if one doesn't exist, or modify the data if one does exist.
The code I am using for this is:
if(!FB.IsLoggedIn)
    yield break;
Debug.Log ("NPCF: FB Is Logged In");
ParseQuery<ParseObject> query = ParseObject.GetQuery ("User"+FB.UserId);
Debug.Log ("NPCF: Called GetQuery on User" + FB.UserId);

var queryTaskContinueWith = query.FindAsync().ContinueWith( t =>
{
    if(t.IsFaulted)
    {
        using (IEnumerator<System.Exception> enumerator = t.Exception.InnerExceptions.GetEnumerator())
        {
            if (enumerator.MoveNext())
            {
                ParseException error = (ParseException) enumerator.Current;
                Debug.Log ("Error Message: " + error.Message);
                Debug.Log ("Error Code: " + error.Code);
            }
        }
    }
    // NOT REACHING HERE
    Debug.Log ("NPCF: t.Result count: " + t.Result.Count());
    var result = t.Result;

    if(result.Count() == 0)
    {
        //Upload New Data
    }
    else
    {
        //Modify/Sync Data
    }
}

I know I've had this working in the past, because I have had  the functionality working completely. Is it actually possible to query an object if the object doesn't exist? Or am I just being stupid right now and missing a step out/forgetting how to properly perform this action?


text:
Q: Element tag needs to include in particular occurence using XSLT I want to include the  tag inside the quotes using XSLT,
My Input XML is:
<text>
  <top>

Glucose builds up in your blood and your cells become starved for energy and can't function properly.

  </top>
  <bottom>

And, for some people, this may be all that is needed to successfully maintain target blood glucose levels.

It doesn't come in a pill form because it would get destroyed in the stomach during digestion.

  </bottom>
</text>

XSL I used as:
<xsl:stylesheet version="3.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    xmlns:json="http://json.org/" xmlns:mf="http://example.com/mf"
    exclude-result-prefixes="#all">

  <xsl:param name="length" as="xs:integer" select="80"/>
  <xsl:param name="pattern" as="xs:string" select="concat('((.{1,', $length, '})( |$))')"/>
  <xsl:param name="sep" as="xs:string" select="' +
 '"/>

  <xsl:function name="mf:break" as="xs:string">
    <xsl:param name="input" as="xs:string"/>
    <xsl:variable name="result">
      <xsl:analyze-string select="$input" regex="{$pattern}">
        <xsl:matching-substring>
          <xsl:value-of select="concat('"', regex-group(2), '"')"/>
          <xsl:if test="position() ne last()">
            <xsl:value-of select="$sep"/>
          </xsl:if>
        </xsl:matching-substring>
      </xsl:analyze-string>
    </xsl:variable>
    <xsl:sequence select="$result"/>
  </xsl:function>

  <xsl:param name="ser-params" as="element()">
    <output:serialization-parameters xmlns:output="http://www.w3.org/2010/xslt-xquery-serialization">
      <output:method value="xml"/>
      <output:version value="1.0"/>
      <output:indent value="yes"/>
      <output:omit-xml-declaration value="yes"/>
    </output:serialization-parameters>
  </xsl:param>

  <xsl:template match="top">
    "top": <xsl:apply-templates/>,
  </xsl:template>

  <xsl:template match="bottom">
    "bottom": <xsl:apply-templates/>,
  </xsl:template>

  <xsl:template match="p">
    <xsl:sequence select="mf:break(normalize-space(string-join(text()/serialize(., $ser-params), '')))"/>
  </xsl:template>

</xsl:stylesheet>

I got the output as:
"top": "Glucose builds up in your blood and your cells become" +
"starved for energy and can't function properly.",

"bottom": "And, for some people, this may be all that is needed" +
"to successfully maintain target blood glucose levels."

"It doesn't come in a pill form because it would get destroyed in" +
"the stomach during digestion.",

But i need output as:
"top": "Glucose builds up in your blood and your cells become" +
"starved for energy and can't function properly.",

"bottom": "And, for some people, this may be all that is needed" +
"to successfully maintain target blood glucose levels."

"It doesn't come in a pill form because it would get destroyed in" +
"the stomach during digestion.",

I want the  tag coming inside the quotes, Please help me on this. Thanks in advance

A: Well, you have posted various variations on that topic already and you have received a lot of answers, do you understand any of them at all or why are you not able to adapt the solutions posted so far to further needs?
If you want to have serialized markup then you have already been shown how to use the serialize function to create that and if you first want to transform p elements to span elements then you simply need to do that which is a basic step in XSLT 2.0. So change
  <xsl:template match="p">
    <xsl:sequence select="mf:break(normalize-space(string-join(text()/serialize(., $ser-params), '')))"/>
  </xsl:template>

to
<xsl:template match="p">
    <xsl:variable name="span">

            <xsl:apply-templates/>

    </xsl:variable>
    <xsl:sequence select="mf:break(normalize-space(serialize($span, $ser-params)))"/>
</xsl:template>

and of course use <xsl:output method="text"/> as already suggested several times and the output should be along the requested format, e.g.
        "top":
        "Glucose builds up in your blood and your cells become starved for energy" +
 "and can't function properly."
    ,

        "bottom":
        "And, for some people, this may be all that is needed to successfully" +
 "maintain target blood glucose levels."
        "It doesn't come in a pill form because it would get destroyed in the" +
 "stomach during digestion."
    ,

(although I don't understand what that format is supposed to represent or achieve, it is certainly not JSON and would also not parse as Javascript).


text:
Q: How do I write rows and columns with drawString in Java public void drawboard(Graphics g){
    g.setColor(Color.yellow);
    for (int row = 0; row < board.length; row++){
        for (int col = 0; col < board[row].length; col++){
                g.drawString("X", col, row);
            }
    }

All I get is a yellow square that is 35x30 (variables for row and col in another part of the program).  I can't see any "X" at all.  I have tried to space it out in case it was all mashed together with col+10, row+10, but it doesn't affect it.  I switched col and row with the same affect.
Thank you.

A: The drawString second and third argument are in pixels.  You're just printing lots of X's on themselves, offset by 1 pixel and again and again, so of course all you get is a big blob.
What you want is to multiply by the width/height of your rows and cols like this:
g.drawString("X", col * columnWidth, row * rowHeight);

A: There is nothing wrong with this code. For this piece of code, of course you see yellow rectangle, as Xs are spaced only 1 pixel apart.
If you provide drawString with sufficient coordinates, you should see your X at that coordinates. So, if you space col and row variables in your loop like you have explained, you should see several Xs in several rows/columns. (But don't forget to change the board array in that case, as it is possible the loop will not execute at all, if you space them too far apart).
Maybe you can tell us where do you call that code from? Is it executed in paintComponent method or do you call it manually from some other thread?


text:
Q: Action Script 3 Redirect to url Variable I have made a flv file that plays a movie. Swf is loaded automatically before the site loads. When the movie ends i want to redirect back to a website url. Problem is that the website that I redirect back is not static.
But I know the url of the site from the url bar. Example:
The url is loaded here: http://myad.com
Current url adress: http://myad.com/reloader.html?ADURL=http://www.website.com/test.asp&
So I want at the last frame of the swf, to be redirected back to www.website.com
Any ideas what action script 3 code I need to use;
Thank you
edit: corrected adurl


text:
Q: How can I iterate over ManyToManyField? A simple question and yet I can't find an answer for it.
I have a model with a ManyToMany field:
class Stuff(models.Model):
  things = models.ManyToManyField(Thing)

then in a different function I want to do this:
myStuff = Stuff.objects.get(id=1)
for t in myStuff.things.all:
  # ...

But that is giving me:
TypeError: 'instancemethod' object is not iterable

How can I iterate over a manyToManyField ?

A: Like Abid A already answered, you are missing brackets ()
for t in myStuff.things.all():
    print t.myStuffs.all()

A: Try adding the () after all: myStuff.things.all()

A: ManyToManyField seems to have a different kind of Manager than your basic Django class.  Looking at the source here, https://github.com/django/django/blob/master/django/db/models/fields/related_descriptors.py#L821, it seems you are looking for the related_val field which appears to contain the tuple of related objects references.


text:
Q: How can I access a function in another class? I am developing an app for android that has to access another class, but i don't know why it doesn't work.
When run the App in android 2.3.3 it force closes, and I don't understand why. I think that the method is correct.
Log in the force close the phone android:
> app_vercode:1
device_model:u8800
build_version:111180
condition:1
processName:beta.tester
pid:13277
uid:10088
tag:null
shortMsg:java.lang.NullPointerException
longMsg:java.lang.NullPointerException: Unable to start activity ComponentInfo{beta.tester/beta.tester.BetaTesterActivity}: java.lang.NullPointerException
stackTrace:java.lang.RuntimeException: Unable to start activity ComponentInfo{beta.tester/beta.tester.BetaTesterActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1664)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1680)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3703)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at beta.tester.BetaTesterActivity.onCreate(BetaTesterActivity.java:23)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1628)
... 11 more

       Detail logs:

EDIT: This code already is correctly.
The code:
class BetaTesterActivity:
   package beta.tester;

   import android.app.Activity;
   import android.os.Bundle;
   import android.widget.TextView;

   public class BetaTesterActivity extends Activity {

 public TextView text1;
 private teste cmd;

     /** Called when the activity is first created. */
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main);

         text1 = (TextView) findViewById(R.id.text1);
         //Start the function
         cmd = new teste();
         cmd.start(this);

    }
  }

class teste:
package beta.tester;

public class teste {

//Function that I will start
    public void start(BetaTesterActivity zav){

        zav.text1.setText("Hello");

   }
 //
}

A: In class teste, you are creating a new BetaTesterActivity, which is useless. You need to use the instance created by the framework. Change your class teste to this:
public class teste {

    //Function that I will start
    public void start(BetaTesterActivity zav){

        zav.text1.setText("Hello");

    }

}

Then in the onCreate method of your activity class, you need to initialize cmd and then call start like this:
cmd.start(this);


text:
Q: how to keep tab indent even after uncomment in visual studio 2017? I am very new to VS 2017.
I used VS 2013 for ages, and I am very used to it.
But several days ago, I upgraded to 2017 and I found a serious problem of IDE.
My C# Text Editor's indenting option looks like below.
Block, tab 4 size, indent 4 size, keep tabs.

When I comment any lines, it keeps my indent.
But when I uncomment, it goes like it ignores the indent.
Like below.

When normal, it keeps my indent as tab.

When commented, it still keeps my indent as tab.

When uncommented, the indent disappears and turns into a space.
Anyone knows what I have to check the other options?


text:
Q: Is it possible to add individual labels to Chart.JS bars? I have a fully functional Chart.JS Barchart which loads as intended, however I would like to add the username to each bar which is associated to them so administrators (who can see all entries) can distinguish between them.
function BarChart(data) {
                var barChartData = {
                    labels: data.Month,
                    datasets: [
                        {
                            label: 'Weight (kg)',
                            fillColor: "rgba(220,220,220,0.5)",
                            backgroundColor: "rgba(46, 44, 211, 0.7)",
                            highlightFill: "rgba(220,220,220,0.75)",
                            highlightStroke: "rgba(220,220,220,1)",
                            data: data.Weight
                        },
                        {
                            label: 'Steps',
                            fillColor: "rgba(0,0,0,0.5)",
                            backgroundColor: "rgba(215, 44, 44, 0.7)",
                            highlightFill: "rgba(0,0,0,0.5)",
                            highlightStroke: "rgba(0,0,0,0.5)",
                            data: data.Steps
                        }
                    ]

                }
                var ctx = document.getElementById("barchart").getContext("2d");
                window.myBar =new Chart(ctx, {
                    type: 'bar',
                    data: barChartData,
                    options: { responsive: true }
                });

I have successfully passed through the Usernames and they can be called by using data.User, however when I append this to the Steps or Weight label, I end up with "Steps for: admin,admin,admin" (since I have three entries, all from admin).
Is it possible to have it so each bar has the username it belongs to?

A: Maybe not quite what you asked for, but you could add it to the tooltip.
options: {
  tooltips:{
    callbacks: {
       afterLabel: function(e){return "added By:" +data.User[e.datasetIndex][e.index]}
    }
  }
}

https://jsfiddle.net/r71no58a/7/


text:
Q: First Baseline and Last Baseline Properties in UIStackView What effect do the First Baseline and Last Baseline properties have on the subviews of a UIStackView?
Generally, can someone please illustrate the implementation of these values?

A: Suppose you have a two-line text view (or field or label or button) and a three-line text view, and you add them to a horizontal stack view. Do you want to align their first lines, or their last lines? That's the difference.
.FirstBaseline:

.LastBaseline:

Note: I increased the vertical content hugging and compression resistance priorities to 1000 (required) to get this to work properly.

A: var firstBaselineAnchor: NSLayoutYAxisAnchor

Represents the baseline for the topmost line of text in the view.
var lastBaselineAnchor: NSLayoutYAxisAnchor

Represents the baseline for the bottommost line of text in the view.


text:
Q: Tomcat redirect 'stderr' content to 'stdout' I have just migrated web application from Tomcat6 to Tomcat7.
But after this errors that appeared in application are logged to 'stderr.log' file.
When I have used Tomcat6 errors and output were logged to 'stdout.log' file. So I was able to see every information I need in one(stdout.log) file.
How to 'tell' Tomcat7 to log errors and output to 'stdout.log' file as it was in Tomcat6?

A: Have a look at the logging.properties file in the conf/ directory of your Tomcat Installation. This is the point where the general logging is configured.
It is in the java.util.logging format.


text:
Q: Count current users on the page I'm trying to count current viewers on the particular page. I need this count to be stored in the DB. The main trouble is to clean up after user leaves the page.
Users are anonymous. Every active user sends AJAX-request every 5 seconds.
What's the best algorithm to do that? Any suggestions?
UPD: I'm trying to reduce amount of queries to the DB, so, I think, I don't really need to store that count in the DB while I can access it other way from the code.

A: Don't even think about storing this in database, your app will be incredibly slowed down.
So use Cache for this kind of operation.
To count the number of people, I'd say:

*

*assign a random ID to each anonymous user and store it in his session

*send the ID within your ajax call

*store an Array of Hashes in cache with [{ :user_id, :latest_ping }, {} ] (create a cache var for each page)

*delete the elements of the array which appear to be too old

*you've your solution: number of users = nb of elements in the array

A: If you store the users in the database somehow, you could store a last_seen_at field in the users table, and update that with Time.now for every AJAX request that user sends.
To display how many users you currently have, you can just perform a query such as:
@user_count = User.where("last_seen_at < ?", 5.seconds.ago).count

If you want to clean up old users, I suggest that you run some kind of cron job, or use the whenever gem, or something like that, to periodically delete all users that haven't been seen for some time.

A: I would suggest you create a model that contains a unique key (cookie-id or something) that you save or update with every AJAX heartbeat request.
You then have a session controller that could look like this:
def create
  ActiveUser.where(:cookie => params[:id]) || ActiveUser.new
  ActiveUser.cookie = prams[:id]
  ActiveUser.timestamp = Time.now
  ActiveUser.save
end

Your number of active users is then simply a SELECT COUNT(*) FROM ActiveUsers WHERE timestamp > NOW() - 5 or something like that.

A: Martin Frost is on the right track. There's the #touch method to update last_seen_at: user.touch(:last_seen_at)
But it would be even more efficient to just update the user without having to fetch the model from the database:
> User.update_all({:last_seen_at => Time.now}, {:id => params[:user_id})
SQL (3.1ms)  UPDATE "users" SET "last_seen_at" = '2011-11-17 12:37:46.863660' WHERE "users"."id" = 27
=> 1


text:
Q: How to easily indent output to ofstream? Is there an easy way to indent the output going to an ofstream object?  I have a C++ character array that is null terminate and includes newlines.  I'd like to output this to the stream but indent each line with two spaces.  Is there an easy way to do this with the stream manipulators like you can change the base for integer output with special directives to the stream or do I have to manually process the array and insert the extra spaces manually at each line break detected?
Seems like the string::right() manipulator is close:
http://www.cplusplus.com/reference/iostream/manipulators/right/
Thanks.
-William

A: This is the perfect situation to use a facet.
A custom version of the codecvt facet can be imbued onto a stream.
So your usage would look like this:
int main()
{
    /* Imbue std::cout before it is used */
    std::ios::sync_with_stdio(false);
    std::cout.imbue(std::locale(std::locale::classic(), new IndentFacet()));

    std::cout << "Line 1\nLine 2\nLine 3\n";

    /* You must imbue a file stream before it is opened. */
    std::ofstream       data;
    data.imbue(indentLocale);
    data.open("PLOP");

    data << "Loki\nUses Locale\nTo do something silly\n";
}

The definition of the facet is slightly complex.
But the whole point is that somebody using the facet does not need to know anything about the formatting. The formatting is applied independent of how the stream is being used.
#include <locale>
#include <algorithm>
#include <iostream>
#include <fstream>

class IndentFacet: public std::codecvt<char,char,std::mbstate_t>
{
  public:
   explicit IndentFacet(size_t ref = 0): std::codecvt<char,char,std::mbstate_t>(ref)    {}

    typedef std::codecvt_base::result               result;
    typedef std::codecvt<char,char,std::mbstate_t>  parent;
    typedef parent::intern_type                     intern_type;
    typedef parent::extern_type                     extern_type;
    typedef parent::state_type                      state_type;

    int&    state(state_type& s) const          {return *reinterpret_cast<int*>(&s);}
  protected:
    virtual result do_out(state_type& tabNeeded,
                         const intern_type* rStart, const intern_type*  rEnd, const intern_type*&   rNewStart,
                         extern_type*       wStart, extern_type*        wEnd, extern_type*&         wNewStart) const
    {
        result  res = std::codecvt_base::noconv;

        for(;(rStart < rEnd) && (wStart < wEnd);++rStart,++wStart)
        {
            // 0 indicates that the last character seen was a newline.
            // thus we will print a tab before it. Ignore it the next
            // character is also a newline
            if ((state(tabNeeded) == 0) && (*rStart != '\n'))
            {
                res                 = std::codecvt_base::ok;
                state(tabNeeded)    = 1;
                *wStart             = '\t';
                ++wStart;
                if (wStart == wEnd)
                {
                    res     = std::codecvt_base::partial;
                    break;
                }
            }
            // Copy the next character.
            *wStart         = *rStart;

            // If the character copied was a '\n' mark that state
            if (*rStart == '\n')
            {
                state(tabNeeded)    = 0;
            }
        }

        if (rStart != rEnd)
        {
            res = std::codecvt_base::partial;
        }
        rNewStart   = rStart;
        wNewStart   = wStart;

        return res;
    }

    // Override so the do_out() virtual function is called.
    virtual bool do_always_noconv() const throw()
    {
        return false;   // Sometime we add extra tabs
    }

};

See: Tom's notes below

A: Well this is not the answer I'm looking for, but in case there is no such answer, here is a way to do this manually:
void
indentedOutput(ostream &outStream, const char *message, bool &newline)
{
  while (char cur = *message) {
    if (newline) {
      outStream << "  ";
      newline = false;
    }
    outStream << cur;
    if (cur == '\n') {
      newline = true;
    }
    ++message;
  }
}

A: A way to add such feature would be to write a filtering streambuf (i.e. a streambuf which forwards the IO operation to another streambuf but manipulate the data transfered) which add the indentation as part of its filter operation.  I gave an example of writing a streambuf here and boost provides a library to help in that.
If your case, the overflow() member would simply test for '\n' and then add the indent just after if needed (exactly what you have done in your indentedOuput function, excepted that newline would be a member of the streambuf).  You could probably have a setting to increase or decrease the indent size (perhaps accessible via a manipulator, the manipulator would have to do a dynamic_cast to ensure that the streambuf associated to the stream is of the correct type; there is a mechanism to add user data to stream -- basic_ios::xalloc, iword and pword -- but here we want to act on the streambuf).

A: I've had good success with Martin's codecvt facet based suggestion, but I had problems using it on std::cout on OSX, since by default this stream uses a basic_streambuf based streambuf which ignores the imbued facet. The following line switches std::cout and friends to use a basic_filebuf based streambuf, which will use the imbued facet.
std::ios::sync_with_stdio(false);

With the associated side effect that the iostream standard stream objects may operate independently of the standard C streams.
Another note is since this facet does not have a static std::locale::id, which meant that calling std::has_facet<IndentFacet> on the locale always returned true. Adding a std::local::id meant that the facet was not used, since basic_filebuf looks for the base class template.

A: There is no simple way, but a lot has been written about the complex
ways to achieve this. Read this article for a good explanation of
the topic. Here is another article, unfortunately in German. But
its source code should help you.
For example you could write a function which logs a recursive structure. For each level of recursion the indentation is increased:
std::ostream& operator<<(std::ostream& stream, Parameter* rp)
{
    stream << "Parameter: " << std::endl;

    // Get current indent
    int w = format::get_indent(stream);

    stream << "Name: "  << rp->getName();
    // ... log other attributes as well

    if ( rp->hasParameters() )
    {
        stream << "subparameter (" << rp->getNumParameters() << "):\n";

        // Change indent for sub-levels in the hierarchy
        stream << format::indent(w+4);

        // write sub parameters
        stream << rp->getParameters();
    }

    // Now reset indent
    stream << format::indent(w);

    return stream;

}

A: I have generalized Loki Astarti's solution to work with arbitrary indentation levels.  The solution has a nice, easy to use interface, but the actual implementation is a little fishy.  It can be found on github:https://github.com/spacemoose/ostream_indenter
There's a more involved demo in the github repo, but given:
#include "indent_facet.hpp"

/// This probably has to be called once for every program:
// http://stackoverflow.com/questions/26387054/how-can-i-use-stdimbue-to-set-the-locale-for-stdwcout
std::ios_base::sync_with_stdio(false);

// This is the demo code:
std::cout << "I want to push indentation levels:\n" << indent_manip::push
          << "To arbitrary depths\n" << indent_manip::push
          << "and pop them\n" << indent_manip::pop
          << "back down\n" << indent_manip::pop
          << "like this.\n" << indent_manip::pop;

}
It produces the following output:
I want to push indentation levels:
    To arbitrary depths
        and pop them
    back down
like this.

I would appreciate any feedback as to the utility of the code.

A: Simple whitespace manipulator
struct Whitespace
{
    Whitespace(int n)
        : n(n)
    {
    }
    int n;
};

std::ostream& operator<<(std::ostream& stream, const Whitespace &ws)
{
    for(int i = 0; i < ws.n; i++)
    {
        stream << " ";
    }
    return stream;
}


text:
Q: Error Code: 1318. Incorrect number of arguments for PROCEDURE 2.procedurainot111; expected 3, got 1 DELIMITER //
CREATE PROCEDURE `procedurainot111` (out kol_sotr INT, out sumpokaz INT, IN number_otd int)
BEGIN
SELECT COUNT(номер_отдела), sum(показатели) INTO kol_sotr, sumpokaz
FROM сотрудники WHERE номер_отдела=number_otd;
END //
DELIMITER ;
call procedurainot111('1')


text:
Q: Convert JSON to Associative array I want to convert a JSON response to associative array but looks like I was not able to make it right.
Here is my JSON sample response:
{
   "response":[
  {
     "id":100,
     "certificate":{
        "id":1,
        "title":"Lorem ipsum dolor sit amet, consectetur adipiscing elit."

     },
     "created_at":"2013-12-02T15:20:08.233Z"

  },
  {
     "id":101,
     "certificate":{
        "id":2,
        "title":"Aenean facilisis, nisl vitae pulvinar varius."
     },
     "created_at":"2013-12-02T15:20:08.240Z"

  }
 ],
"count":2
}

This is what I have tried so far:
    var len = obj.response.length;
    var rData = [];
    var gcData = [];

    for(var i = 0; i < len; i++){

        rData[i] = $.map(obj.response[i], function(value, index) {

            if(typeof value=="object"){
                gcData = $.map(value, function(value1, index) {
                    return [value1];
                });

                return gcData;

            }else{
                return [value];
            }
        });

    }

My expected output:
rData = [
    100 : [
           id: ["100"],
           certificate: [
              id: ["1"],
              title: ["Lorem ipsum dolor sit amet, consectetur adipiscing elit."]
           ],
           created_at: ["2013-12-02T15:20:08.240Z"]

         ]
    101 : [
           id: ["101"],
           certificate: [
              id: ["2"],
              title: ["Aenean facilisis, nisl vitae pulvinar varius."]
           ],
           created_at: ["2013-12-02T15:20:08.240Z"]

         ]

]

Please help. Thanks.

A:
I just want to group it by keys something like I have in expected output

It seems you want to create an id -> object map. To do that you just have to iterate over the array, take the id attribute of each object as property name and assign the object (the element of the array) to that property of the map.
Example:
var map = {};
var response = obj.response;

for (var i = 0, l = response.length; i < l; i++) {
    map[response[i].id] = response[i];
}

console.log(map);

Each object inside the array is already in the structure you want it to be. The output is
{
    "100": {
        "id": 100,
        "certificate": {
            "id": 1,
            "title": "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
        },
        "created_at": "2013-12-02T15:20:08.233Z"
    },
    "101": {
        "id": 101,
        "certificate": {
            "id": 2,
            "title": "Aenean facilisis, nisl vitae pulvinar varius."
        },
        "created_at": "2013-12-02T15:20:08.240Z"
    }
}

A: your desired JSON is incorrect.
It isn't clear if you want to create an array of arrays or an object of arrays or what. To help decide which option fits your need, try this code
var a=[];
var o={};

for (var i=0, l=response.length; i<l; i++) {
  var e = response[i];
  a[e.id] = e.certificate;
  o[e.id] = e.certificate;
}

console.log(JSON.stringify(a));
console.log(JSON.stringify(o));


text:
Q: MySQL - Duplicate table I need to duplicate a table in MySQL, making the new table empty. That is, I need to copy only the structure of an existing table to a new one.

A: Try the create table LIKE syntax.
create table users2 like users;

This should give you an empty table (users2) with the same structure as the original (users).

A: There is also another way to create a empty table as existing table and you can use the following command also
create table a select * from users2 limit 0, 0;


text:
Q: Identify a book about an underground psi research facility This is a book I remember reading when I was a teen, so late 70's or early 80's.
Children and young adults are press-ganged (I remember it was involuntary, anyway) into an underground research facility where research into psi powers is going on.  Eventually one of the research subjects becomes meta-powered and breaks out.
What stands out in my mind is the memory of a test.  Imagine a bell jar, with a pedestal in it, with a ball standing on it.  A powered individual is supposed to be able to knock the ball off the post, then put it back onto the post.  There is a scene where some official-in-charge who isn't supposed to be powered actually accomplishes the test, levitating the gently glowing ball back onto its perch.

A: The ball on the pedestal inside a bell jar is an exact description of a scene near the end of Pstalemate (Lester del Rey, 1971) in which the protagonist discovers telepathic powers in himself and takes massive doses of hallucinogens, trying to induce "bad trips" to harden himself against the otherwise inevitable madness that he sees via reading his own future mind.


text:
Q: Big-O notation, prove the following: $\sum\limits_{k=3}^n(k^2 - 2k)$ is $O(n^3)$. Use the definition of Big-O notation to prove the following:
$\sum\limits_{k=3}^n(k^2 - 2k)$  is $O(n^3)$.
Can someone please give me some hints on how to expand $\sum\limits_{k=3}^n(k^2 - 2k)$?

A: You don't actually have to work very hard at all:
$$\sum_{k=3}^n\left(k^2-2k\right)\le\sum_{k=3}^nk^2\le\sum_{k=3}^nn^2=(n-2)n^2\le n^3\;.$$
In other words, don't expand the sum: bound it instead. As you can see, even a pretty crude bound works fine here.

A: The easiest way to conclude that it is $\mathcal{O}(n^3)$ is to note that
$$k^2 - 2k < k^2 \leq n^2, \,\,\,\,\, \forall k \in \{3,4,\ldots,n\}$$
You could in fact evaluate the sum exactly and then prove that it is $\mathcal{\Omega}(n^3)$. Make use of the fact that
$$\sum_{k=1}^n k^2 = \dfrac{n(n+1)(2n+1)}6 \text{ and } \sum_{k=1}^n k = \dfrac{n(n+1)}2$$
Move your mouse over the gray area below for the complete solution.

Note that$$\sum_{k=3}^n (k^2-2k) = \sum_{k=3}^n k^2 - 2\sum_{k=3}^nk = \dfrac{n(n+1)(2n+1)}6-1^2-2^2 - 2 \left(\dfrac{n(n+1)}2-1-2\right)$$The above simplifies to$$\dfrac{(n-2)(n-1)(2n+3)}6$$


text:
Q: (GPUMemory Crashes ) Application is crashing when applying effects to array of images
-(void)imageToVideoConversion:(NSMutableArray *)arrayOfImages
{

    NSLog(@"(((((((((((((((((((())))))))))))))))))))) no of images:%lu",(unsigned long)[arrayOfImages count]);

    NSArray *paths = nil;
    NSString *documentsDirectory = nil;

    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    documentsDirectory = [paths objectAtIndex:0];

    NSString *videoOutputPath =  [documentsDirectory stringByAppendingPathComponent:
                        [NSString stringWithFormat:@"ImageVideo-%d.mov",arc4random() % 1000]];

    NSError *error = nil;
    NSUInteger fps = 30;

    imageSize = CGSizeMake(640, 640);

    NSLog(@"Start building video from defined frames.");

    videoWriter = [[AVAssetWriter alloc] initWithURL:
                   [NSURL fileURLWithPath:videoOutputPath] fileType:AVFileTypeQuickTimeMovie
                                               error:&error];
    NSParameterAssert(videoWriter);

    NSDictionary *videoSettings = [NSDictionary dictionaryWithObjectsAndKeys:
                                   AVVideoCodecH264, AVVideoCodecKey,
                                   [NSNumber numberWithInt:imageSize.width], AVVideoWidthKey,
                                   [NSNumber numberWithInt:imageSize.height], AVVideoHeightKey,
                                   nil];

    AVAssetWriterInput* videoWriterInput = [AVAssetWriterInput
                                            assetWriterInputWithMediaType:AVMediaTypeVideo
                                            outputSettings:videoSettings];

    AVAssetWriterInputPixelBufferAdaptor *adaptor = [AVAssetWriterInputPixelBufferAdaptor
                                                     assetWriterInputPixelBufferAdaptorWithAssetWriterInput:videoWriterInput
                                                     sourcePixelBufferAttributes:nil];

    NSParameterAssert(videoWriterInput);
    NSParameterAssert([videoWriter canAddInput:videoWriterInput]);
    videoWriterInput.expectsMediaDataInRealTime = YES;
    [videoWriter addInput:videoWriterInput];

    //Start a session:
    [videoWriter startWriting];
    [videoWriter startSessionAtSourceTime:kCMTimeZero];

    int frameCount = 0;
    double numberOfSecondsPerFrame =  1.0 * 3.0;

    NSLog(@"Frame per seconds:%f", numberOfSecondsPerFrame);

    double frameDuration = fps * numberOfSecondsPerFrame;

    for(int i = 0; i<=[arrayOfImages count]; i++)
    {

        UIImage *originalImage = nil;
        NSString *nameImage = nil;
        UILabel *title = nil;
        UIColor *cur_color;

        if (i == 0)
        {
            nameImage = [NSString stringWithFormat:@"TitleImage_%lu.png",[[SingletonClass sharedManager] titleValue]+1];
            cur_color = [UIColor colorWithRed:(rgbValues[[[SingletonClass sharedManager] titleValue]].redValue/255) green:(rgbValues[[[SingletonClass sharedManager] titleValue]].greenValue/255) blue:(rgbValues[[[SingletonClass sharedManager] titleValue]].bluevalue/255) alpha:1.0];

            UIImageView *snapshotView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 640.0, 640.0)];
            snapshotView.image = [UIImage imageNamed:nameImage];

            title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 640.0, 100.0)];
            title.center = CGPointMake(snapshotView.frame.size.width/2, snapshotView.frame.size.height/2);
            title.text = self.titleText.text;
            title.textColor = cur_color;
            title.textAlignment = NSTextAlignmentCenter;
            title.font = [UIFont fontWithName:[NSString stringWithFormat:@"%@",(font_styles)[[[SingletonClass sharedManager] titleValue]].fontStyle] size:75];
            title.backgroundColor = [UIColor clearColor];
            [snapshotView addSubview:title];

            UIGraphicsBeginImageContext(snapshotView.frame.size);
            [snapshotView.layer renderInContext:UIGraphicsGetCurrentContext()];
            originalImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();

        }

        else
        {
            /***************** Add Border ***************/

            NSData *n_dat = UIImageJPEGRepresentation([arrayOfImages objectAtIndex:i-1], 0.8);
            originalImage = [UIImage imageWithData:n_dat];

            NSString *imageString = [NSString stringWithFormat:@"border.png"];

            UIImage *borderImage = [UIImage imageNamed:imageString];
            CGSize size1 = CGSizeMake(640.0,640.0);
            UIGraphicsBeginImageContext(size1);

            [originalImage drawInRect:CGRectMake(0,0,640.0,640.0)];
            [borderImage drawInRect:CGRectMake(0,0,640.0,640.0)];

            originalImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();

            /********************************************/
        }

        UIImage *imageToAddBuffer = nil;

        if (isEffectSelected == YES)
        {

            NSLog(@"Priningintg the current effect number:%d",currentEffectNumber);

            imageToAddBuffer = [self add_EffectOnImage:originalImage effectNumber:currentEffectNumber];

            NSData* imgData = UIImagePNGRepresentation(imageToAddBuffer);
            imageToAddBuffer = [UIImage imageWithData:imgData];
        }
        else
        {
            imageToAddBuffer = originalImage;
        }

        CVPixelBufferRef buffer = nil;

        buffer = [self pixelBufferFromCGImage:[imageToAddBuffer CGImage]];
     //   [imageToAddBuffer release];
        imageToAddBuffer =nil;

        BOOL append_ok = NO;
        int j = 0;
        while (!append_ok && j < 30) {
            if (adaptor.assetWriterInput.readyForMoreMediaData)
            {

                CMTime frameTime = CMTimeMake(frameCount*frameDuration,(int32_t) fps);

                NSLog(@"Count of the array(((((((((((((()))))))))) %d",i);

                append_ok = [adaptor appendPixelBuffer:buffer withPresentationTime:frameTime];
                if (buffer!= NULL) {
                    CVPixelBufferRelease(buffer);
                }

                //[pool  release];

                if(!append_ok){
                    NSError *error = videoWriter.error;
                    if(error!=nil) {
                        NSLog(@"Unresolved error %@,%@.", error, [error userInfo]);
                    }
                }

            }
            else {
                printf("adaptor not ready %d, %d\n", frameCount, j);
                [NSThread sleepForTimeInterval:0.1];
            }
            j++;
        }
        if (!append_ok) {
            printf("error appending image %d times %d\n, with error.", frameCount, j);
        }
        frameCount++;

    }

    //Finish the session:
    [videoWriterInput markAsFinished];

    [videoWriter finishWritingWithCompletionHandler:^(){

        NSLog(@"Came here----------");

        [self MergeAndSave:videoOutputPath];

    }];

    videoOutputPath = nil;

}

Here without applying any effects(changing colors to images) when i generate video it is working properly ,but when i apply effects and generate video after 5 images app is crashing.(if i select only 4 images to generate video with effects it is generating video)without any crash.
when i run instruments leaks it is showing red lines in gpuimagepicturs.m and gpuimageoutput.m files,any one knows please help me thanks in advance.


text:
Q: how to avoid to fire form control valueChanges when undefined vs null I am using Angular 8 And I have a form object and I have subscribed valuechanges in the following way:

        this.myFormSubscription = this.myForm.get(this.parentGroupName).valueChanges
            .pipe(
                startWith(null as string),
                pairwise(),
                debounceTime(100),
                distinctUntilChanged((a, b) => lodash.isEqual(a, b))
            )
            .subscribe(([prev, next]: [any, any]) => {
                //...do something
            });

The problem is that it fires when previous value is null and next value is undefined which for me the result of this comparison should be true and I don't need tracing these kind of changes.
And I also have to say I put the valuechanges on hole of the controllers in my form so the value of 'prev' and 'next' which subscribe method returns are always objects that are not just one level too!
for example like this:
prev = {a: 1, b: 2, c: {d: 3, e: null} };
next = {a: 1, b: 2, c: {d: 3, e: undefined} };

In this case the valuechanges event fires which I really need to stop that, Is there any way?
Or maybe I have to compare the previous and next value manually, right? Would be a good solution? Although that seems difficult and tricky to because the objects are two-level...
So what really I should do?!
Actually I am new at this, so any help would be appreciated.

A: Try to keep it simple and add as you go. In the most basic form does it work like this:
this.myFormSubscription = this.myForm.get(this.parentGroupName).valueChanges
            .subscribe((value) => {
                if (value) { <= If value is null or undefined, it will not continue.
                //...do something
               }
            });

UPDATE:
If your FormGroup looks like this (where c is the sub-group of myForm)
this.myForm = this.fb.group({
 a: [null],
 b: [null],
 c: this.fb.group({
   d: [null],
   e: [null],
 })
});

If you need to get the valueChanges of e. It would be like this
const cGroup = this.myForm.get('c') as FormGroup;
cGroup.get('e').valueChanges.subscribe(value => {
 // Now you only have the value and changes of e in the formgroup of c
 if (value) {

 }
});


text:
Q: Running Example App using Flutter in Android Emulator I'm trying to run a Flutter example in an Android Emulator.
The project that I'm running is: https://github.com/iampawan/Flutter-UI-Kit
When I run it I get the following error:
A problem occurred evaluating project ':app'.
> /Users/R/dev/flutter-projects/learn/Flutter-UI-Kit/android/key.properties (No such file or directory)
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
BUILD FAILED in 0s
  Command: /Users/R/dev/flutter-projects/learn/Flutter-UI-Kit/android/gradlew app:properties
Please review your Gradle project setup in the android/ folder.

My flutter doctor -v output:
[✓] Flutter (Channel master, v1.4.8-pre.24, on Mac OS X 10.14.4 18E226, locale ----)
    • Flutter version 1.4.8-pre.24 at /Users/R/dev/flutter-installation/sdk-git/flutter
    • Framework revision 976223533d (hace 2 días), 2019-03-31 07:38:41 -0400
    • Engine revision f3ec767458
    • Dart version 2.2.1 (build 2.2.1-dev.2.1 None)

[✓] Android toolchain - develop for Android devices (Android SDK version 28.0.3)
    • Android SDK at /Users/R/Library/Android/sdk
    • Android NDK location not configured (optional; useful for native profiling support)
    • Platform android-28, build-tools 28.0.3
    • ANDROID_HOME = /Users/R/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)
    • All Android licenses accepted.

[✓] iOS toolchain - develop for iOS devices (Xcode 10.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 10.2, Build version 10E125
    • ios-deploy 1.9.4
    • CocoaPods version 1.6.0

[✓] Android Studio (version 3.3)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin version 33.0.1
    • Dart plugin version 182.5215
    • Java version OpenJDK Runtime Environment (build 1.8.0_152-release-1248-b01)

[✓] IntelliJ IDEA Ultimate Edition (version 2018.2.7)
    • IntelliJ at /Applications/IntelliJ IDEA.app
    • Flutter plugin version 33.0.1
    • Dart plugin version 182.5215

[✓] VS Code (version 1.32.3)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 2.25.0

[✓] Connected device (1 available)
    • Android SDK built for x86 • emulator-5554 • android-x86 • Android 9 (API 28) (emulator)

• No issues found!

Any help would be appreciated!
I already followed this solution: https://github.com/flutter/flutter/issues/18983


text:
Q: Match multiple exact routes I am creating a function that checks if the current url matchs exactly the format I want.
I want to "check in bulk" if the current URL is part of an acceptable list of URLs.
I managed to do it with REGEX:
  const validateOpinionPath = (currentUrl: string): boolean => {

    const regexPatter = /opinion\/[0-9a-z-]*\/(large|medium|small)$/g
    const matchResult = currentUrl.match(regexPatter)
    return !!matchResult
  }

HOWEVER I would like to know how can I do the same by using matchPath (or any other function provided by react-router-dom).
I tried the following but it matches only the first URL:
  const validateOpinionPath = (currentUrl: string): boolean => {
    const match = matchPath(currentUrl, {
      path:
        '/option/:opinionId/large' ||
        '/option/:opinionId/medium' ||
        '/opinion/:opinionId/small',
      exact: true,
      strict: false
    })

    return !!match
  }

I want to match exactly these routes:
 '/option/:opinionId/large',
 '/option/:opinionId/medium',
 '/opinion/:opinionId/small'

'/option/:opinionId/large/something' should return false

A: Reason why multiple strings separated by || operator doesn't works is because second string will only be selected as the value of the path property if first string is a falsy value, for example an empty string.
Since, in your case, first string is not a falsy value, value of the path property is always the first string, i.e. '/option/:opinionId/large'.
Solution
You can pass an array of strings as a value of path property in options object passed to matchPath(). This way each path will be checked instead of just the first one.
const match = matchPath(currentUrl, {
  path: [
     '/option/:opinionId/large',
     '/option/:opinionId/medium',
     '/opinion/:opinionId/small'
  ],
  exact: true,
  strict: false
})

A: I hope this will work!
    const validateOpinionPath = (currentUrl: string): boolean => {
      const match = matchPath(currentUrl, {
        path: '/option/:opinionId/*'
        exact: true,
        strict: false
      })
      return !!match
    }

A: React router dom uses path-to-regexp.
Your path can be:
/option/:optionId/(small|medium|large)


text:
Q: tool to inspect mercurial's internal files Git has the cat-file command to inspect internal files, e.g. git cat-file blob 557db03 will show the contents of the object whose hash starts with 557db03.
Are there similar tools for mercurial that allow me to look at all the different data files that merfcurial uses internally?

A: Try hg --debug help and you can see the list of all the debug commands:
 debugancestor:
      find the ancestor revision of two revisions in a given index
 debugbuilddag:
      builds a repo with a given DAG from scratch in the current empty repo
 debugbundle:
      lists the contents of a bundle
 debugcheckstate:
      validate the correctness of the current dirstate
 debugcommands:
      list all available commands and options
 debugcomplete:
      returns the completion list associated with the given command
 debugdag:
      format the changelog or an index DAG as a concise textual description
 debugdata:
      dump the contents of a data file revision
 debugdate:
      parse and display a date
 debugdiscovery:
      runs the changeset discovery protocol in isolation
 debugfileset:
      parse and apply a fileset specification
 debugfsinfo:
      show information detected about current filesystem
 debuggetbundle:
      retrieves a bundle from a repo
 debugignore:
      display the combined ignore pattern
 debugindex:
      dump the contents of an index file
 debugindexdot:
      dump an index DAG as a graphviz dot file
 debuginstall:
      test Mercurial installation
 debugknown:
      test whether node ids are known to a repo
 debugpushkey:
      access the pushkey key/value protocol
 debugrebuildstate:
      rebuild the dirstate as it would look like for the given revision
 debugrename:
      dump rename information
 debugrevlog:
      show data and statistics about a revlog
 debugrevspec:
      parse and apply a revision specification
 debugsetparents:
      manually set the parents of the current working directory
 debugstate:
      show the contents of the current dirstate
 debugsub:
      (no help text available)
 debugwalk:
      show how files match on given patterns
 debugwireargs:
      (no help text available)

There are a lot of them, and they pretty much expose everything.

A: The closest commands would be:
hg cat -r rev aFile

hg cat: Print the specified files as they were at the given revision

This is not completely the same than git cat-file though, as the latter can also list SHA1, type, and size for a list of objects.
In that second case, hg manifest might be more appropriate.


text:
Q: The difference between the volume of a set and the measure of a set? For a set $S$, we can evaluate its volume $\operatorname{Vol}(S)$ or its measure $\mu(S)$ based on a measure $\mu$.
My question is: In what condition can $\operatorname{Vol}(S)$ and $\mu(S)$ have the same meaning? I'm writing a paper (in computer science) and want to substitute $c \operatorname{Vol}(S)$ for $\int_{r \in S} c \mu(dr)$, where $c$ is a constant and $\mu$ is any one measure. Is the substituting right? or rigorous?

A: It completely depends on your definition of $\mathrm{Vol}$, since there is no standard definition. Most people would define it as $\int_Sd\mu$, so it's probably fine. If you want to be absolutely rigorous, though, just go ahead and include this definition of $\mathrm{Vol}$ at the beginning of your paper.


text:
Q: Codeigniter ajax request not working I send one request to controller ,And When I alert(tele) to controller it is display values,But in controller it shows empty,,
But Other date1 and date2 are working..
<script type="text/javascript">
$(document).ready(function(){
$('#buttonsearch').click(function(){
var date1=$("#date1").val();
var date2=$("#date2").val();vartele=$("#tele").val();
 alert(tele);
 $.ajax(
 {
 type: "POST",
 url: '<?php echo site_url('totalorders/orderajax'); ?>',
 data: 'date1=' + date1 + '&date2='+ date2 +'& tele ='+ tele,
 success: function(data)
 {
 alert(data);
 $("#customers2").html(data);
 }}); });});
</script>

controller code..
 public function orderajax()
    {

         $this->load->database();
        $this->load->library('session');
        $date1=$this->input->post('date1');
        $date2=$this->input->post('date2');
        $tele=$this->input->post('tele');
        $data['tele']=$tele;
        if(($date1 != '') && ($date2 != '') && ($tele == ''))
        {

            $data['orders'] = $this->orderdetails->get_ajaxsearchorders($date1,$date2,$tele);
        }
        else
        {
            $sss=$tele;
            $data['orders'] = $this->orderdetails->get_ajaxsearchorders1($sss);
        }
        $this->load->view('orderviewajax',$data);
    }

can you guys help me where i was wrong..
Note : only 'tele' value is not working date1,date2 are working..

A: Give the space between the key word var and the variable name tele. Check the following line.
var tele = $("#tele").val();

A: add space in variable declaration. and while posting data dont give a space.
For Eg:
             type:"POST",
             url:"<?php echo base_url(); ?>staff_activity/date_report",
             data:'year='+nep_year+'&month='+nep_month,

A: Your root problem is the space you've embedded within the query string in this part:
... +'& tele ='+ tele

Remove the space between & and tele...
... +'&tele ='+ tele

HOWEVER, you don't need to collect each value and manually construct a query string.
Simply use jQuery .serialize(), which collects the form's values and constructs the query string automatically.
data:  $('form').serialize(),


text:
Q: How to Download table data as excel sheet using php..? Guys i'm generating a set of data in a table after som set of calculation.. as soon as user clicks save button excel file with that data must be generated for downloading..
What is the php code for that ..
guys the data is not retrieved from database...its being displayed after a set of calculation as been performed.
Since i dont have any idea ive not posted any related code...sry for that..
below is how my table looks like
https://ibb.co/mUMOrQ
below is my table code

CUF Table

        TimeStamp
        CUF

                    <button id="change-chart"  class="btn btn-primary">Save</button>

Below is jquery that ive included to download the file
     $("#BUTTON").click(function(){
     $("#TABLE").table2excel({
     // exclude CSS class
    exclude: ".noExl",
    name: "Data",
    filename: "Data" //do not include extension
   });
   });

A: You can use one of the following
https://stackoverflow.com/a/38761185/5350773
http://www.jqueryscript.net/table/Export-Html-Table-To-Excel-Spreadsheet-using-jQuery-table2excel.html


text:
Q: PDFs generated using itextsharp giving error at the time of first print command I am getting below for the first time giving print command.
"An error exists on this page. Acrobat may not display the page correctly. please
contact the person who created the pdf document to correct the problem".
Print out is comming very fine. and Second time print out command not giving any error.
Please help me why this error is comming for the first time print.
This is part of my code to create PDF
PdfContentByte cb = writer.DirectContent;
cb.BeginText();
Font NormalFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, Color.BLACK);
// Add an image to a fixed position
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(Server.MapPath("~/images/images/banner.tiff"));
img.SetAbsolutePosition(35, 760);
img.ScalePercent(50);
cb.AddImage(img);
// Draw a line by setting the line width and position
cb.SetLineWidth(2);
cb.MoveTo(20, 740);
cb.LineTo(570, 740);
cb.Stroke();
//Header Details
cb.BeginText();
writeText(cb, drHead["EmpName"].ToString(), 25, 745, f_cb, 14);
writeText(cb, "Employee ID:", 450, 745, f_cn, 12);
writeText(cb, drHead["EmployeeID"].ToString(), 515, 745, f_cb, 12);
cb.EndText();
cb.BeginText();
writeText(cb, "XXXX:", 25, 725, f_cb, 8);
cb.EndText();
cb.SetLineWidth(2);
cb.MoveTo(20, 675);
cb.LineTo(570, 675);
cb.Stroke();
cb.EndText();
// Acknowledgement section
cb.BeginText();
writeText(cb, "XXXXXXXXXXXXXXXX", 20, 140, f_cb, 12);
cb.EndText();
cb.EndText();

Please help me to know what is the issue.

A: You have nested text blocks. That's illegal PDF syntax. I think recent versions of iTextSharp warn you about this, so I guess you're using an old version.
This is wrong:
cb.BeginText();
...
cb.BeginText();
...
cb.EndText();
...
cb.EndText();

This is right:
cb.BeginText();
...
cb.EndText();
...
cb.BeginText();
...
cb.EndText();

Moreover: ISO-32000-1 tells you that some operations are forbidden inside a text block.
This is wrong:
cb.BeginText();
...
cb.AddImage(img);
...
cb.EndText();

This is right:
cb.BeginText();
...
cb.EndText();
...
cb.AddImage(img);

Finally, some operators are mandatory when creating a text block. For instance: you always need setFontAndSize() (I don't know what you're doing in writeText(), but I assume you're setting the font correctly).
In any case: you have chosen to use iTextSharp at the lowest level, writing PDF syntax almost manually. This assumes that you know ISO-32000-1 inside-out. If you don't, you should use some of the high-level objects, such as ColumnText to position content at absolute positions.


text:
Q: Is there a way to set multiple artists for one song? I have an album that contains many songs, some of which are performed by several artists.
I do want all the songs to appear under one album in the albums, and when I am browsing by artists, so under each artist I should see this album and the songs he participated.

*

*How do I set more than one artist on a song?

*How do I make it appear in the library the way I described above.

A: There is no easy way to do this, you only have one artist field per track.
What you could do is listing the name of all artists in the artist field and then create smart playlists with rules for "Artist contains".

A: To add other artists, use ; separator or / between artists. (Artist1; Artist2; Artist3; Artist4 or Artist1/Artist2/Artist3/Artist4)
 I tried this in my iPod (Shuffle 3rd)
Example:
 I have "On The Floor" song. This song have 2 artists. It is Jennifer Lopez and Pitbull.
 On the artist field, type Jennifer Lopez; Pitbull. Then if you want to add a smart playlist contain Pitbull, use 'Artist contains' and fill the box with 'Pitbull'. Then it will show songs with Pitbull artist.
This is the example:

on the image above, on the floor is listed with my other Pitbull songs but still shows the other artist (Jennifer Lopez)

A: You need to set "Album Artist" to whatever artist you want to use.  Then it'll group like you want it.  You get to "Album Artist" from GetInfo -> Info

A: instead of using (artist; artist) or (artist/artist) you can also simply use (artist & artist) but it still doesn't fully do what you want it to do.


text:
Q: Choice model from aggregated dataframe in R I would like to fit a choice model to an aggregated dataframe of sales data. I was thinking of using R and the mlogit package to fit a logit model, however that can only be done with data on an individual level.
Is it possible to get to an individual data level in R using an aggregated dataframe?
I would like some guidance onhow to think about this problem...
Am I on the right track?
Below is a reproducible example:
library(mlogit)
library(dplyr)
data(Car)
#make a an aggregated dataframe
car2 <- group_by(Car,type1,fuel1,range1) %>% summarise(sales=n())

head(car2)
Source: local data frame [6 x 4]
Groups: type1, fuel1 [2]

   type1    fuel1 range1 sales
  <fctr>   <fctr>  <dbl> <int>
1 regcar methanol     50   110
2 regcar methanol     75   180
3 regcar methanol    125  1138
4 regcar methanol    200   945
5 regcar      cng     75   307

Also, I have found some articles of Bayesian methods for estimating
disaggregate choice models using aggregate data.
Would be very greatful if someone have some tutorials in R or some code examples to get me started.
Thankful for tips and guidance


text:
Q: How to keep my variable state as it is? Ok, So I have been making a Fibonacci Series program e.g(0 1 1 2 3 5 8 13 21..). My logics are good but there is variable state problem when I come outside from the for() loop.
How to keep my "firstNumber" state as it is ?
And I dont know why it is printing value till 19 though I am giving input value 10
public class Fibonacci {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        System.out.println("Enter the number: ");
        int input = scan.nextInt();
        FibonacciFunction(input);

    }
    public static int FibonacciFunction(int x) {
        int firstNumber = 0;
        int i;
        for(i =1; i <= x; i++) {
            int numbers = firstNumber + i;
            System.out.println(numbers);
            firstNumber = i; //Keep this state as it is so that when loop run for the second time "firstNumber" should be 1 not 0 again

        }

        return firstNumber;
    }

}

Output
Enter the number:
10
1
3
5
7
9
11
13
15
17
19

A: Your logic is not correct: you are adding the iterator value i of the for loop to the last number, but you need to add the second-to-last number to the last number in the Fibonacci sequence. Thus, your firstNumber variable is not supposed to stay on the "state" of 1 or 0 but should grow with the Fibonacci sequence as the loop goes on.
public static int FibonacciFunction(int x) {
    if(x <= 0) return 0;
    int firstNumber = 0, secondNumber = 1;
    for(int i = 0; i < x; i++) {
        int numbers = firstNumber + secondNumber;
        firstNumber = secondNumber;
        secondNumber = numbers;
        System.out.println(numbers);
    }

    return firstNumber;
}

It's printing values up till 19 because the argument for the function is the number of Fibonacci values you want it to print, not the maximum Fibonacci number.

A: To solve your error, you are saying that you want firstNumber to not be 0 when it comes out of the for loop.  It is impossible for firstNumber to be 0 at the end of the for loop unless the for loop didn't happen.  When you say it is coming back 0 that means the forloop is not going, in which case it returns the original value of firstNumber which is 0.  This means the value x is incorrect, or the way you read it in is incorrect.
Trying putting  in a S.O.P statement after  the firstNumber =i; to see what the value actually is:
   public static int FibonacciFunction(int x) {
        int firstNumber = 0;
        int i;
        for(i =1; i <= x; i++) {
            int numbers = firstNumber + i;
            System.out.println(numbers);
            firstNumber = i;
            System.out.print(" First Number Value: "+ firstNumber);

        }

        return firstNumber;
    }


text:
Q: How to set scroller speed limit in UITableView cell in IOS ? I am building an application in IOS. I have use UITableView Cell in my class and I want to set scroller speed limit.
Is there any way to set scroller speed limit. PLease help me I am new in IOS.

A: You can use tableView.decelerationRate property for this purpose.

A: You should use the tableView.decelerationRate property.  It determines the speed after a user lifts their finger from the screen.  For the constants, use UIScrollViewDecelerationRateNormal or UIScrollViewDecelerationRateFast.  For more advanced speeds, you will need to set the decelerationRate property yourself with a floating-point value.
Edit:
-(void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    self.scrollView.decelerationRate = UIScrollViewDecelerationRateFast;
}


text:
Q: Background image not showing in jsp dynamic web project Hi I am trying to use a background image in home.jsp page.when i run the project image is not loading a red cross mark is showing instead of the image
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
       <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<link rel="stylesheet" href="ac-styles.css" type="text/css" media="screen" />

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home Page</title>

 Hello This Is The Home Page For your J2ee Spring Application

I had placed the image under

when i run the application the result is

please help..
Thanks in advance..

A: The JSP file is not in the same folder as of image file root folder is present. So either you have to move your .jsp file in web-content folder or you should use backspace commands like:

This should work.
Conversely the best method would be to migrate your image file in web-inf/views folder.That would be easy but not recommended for big projects.

note that I included "../" two times. In your directory structure it
  is needed. For more information read the refering manual for HTML
  src's.


text:
Q: How can I avoid JS and use only CSS? After several test, I haven't been able to do what I want to do with a pure css. How can I obtain the same result like the example below without using a javascript.
Is it possible to do that with a pure css?
Thanks.
jsfiddle Demo

var main = document.getElementsByClassName('container');
for(var i = 0; i < main.length; i++) {
 var height = main[i].childNodes[3].offsetHeight;
 main[i].style.height = height+"px";
}
.container {
  width: 100%;
  background: yellow;
  position: relative;
  margin-bottom: 10px;
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.right-child {
  width: 60%;
  height: 180px;
  background: blue;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 40%;
}

A: Like this?
I added height to the .container because since the children are positioned absolutely, they are out of the document's flow, meaning it's like .container doesn't have a child at all.
As for the height:100% for the .right-child, well it is so that it takes the height of the nearest relatively positioned element,which is the .container

.container {
  width: 100%;
  height: 200px;
  background: yellow;
  position: relative;
  margin-bottom: 10px;
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

.right-child {
  width: 60%;
  height: 100%;
  background: blue;
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  left: 40%;
}

A: You can use flexbox to do that, just add display: flex;align-items: center; to .container
and remove the position: absolute and transform translate stuff and you get a clean CSS

.container {
  background: yellow;
  margin-bottom: 10px;
  display: flex;             /* added property */
  align-items: center;       /* added property */
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
}

.right-child {
  width: 60%;
  height: 180px;
  background: blue;
}

A: Another way:
.container {
  width: 100%;
  background: yellow;
  overflow:hidden;
  margin-bottom: 10px;
}
.left-child {
  margin-top:30px;
  width: 40%;
  height: 120px;
  background: red;
  float:left;
}
.right-child {
  width: 60%;
  height: 180px;
  background: blue;
  float:right;
}

https://jsfiddle.net/ghdzy57w/14/

A: A solution without position : relative or position : absolute

.container {
  width: 100%;
  background: yellow;
  margin-bottom: 10px;
  display: inline-block;
}
.left-child {
  width: 40%;
  height: 120px;
  background: red;
  margin-top: 30px;
  display:inline-block;
}

.right-child {
  width: 60%;
  height: 180px;
  background: blue;
  display:inline-block;
  float: right;
}


text:
Q: AsyncTask not executing download Like I wrote in my former question, the subclass of AsyncTask I wrote doesn't download file as intended.
public class Upit extends DialogFragment {

    public ProgressDialog dl;

    private class DownloadFile extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... sUrl) {
            try {
                URL url = new URL(sUrl[0]);
                URLConnection urlc = url.openConnection();
                urlc.connect();
                int fileLength = urlc.getContentLength();
                InputStream is = new BufferedInputStream(url.openStream());
                OutputStream os = new FileOutputStream(
                        Environment.getDataDirectory().getAbsolutePath()
                                .concat("data/com.markosoft.maturko/databases/proba.mp3"));
                byte Data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = is.read(Data)) != -1) {
                    total += count;
                    publishProgress((int) total * 100 / fileLength);
                    os.write(Data, 0, count);
                }
                os.flush();
                os.close();
                is.close();
            } catch (Exception e) {
                Log.e("ERROR_TAG", e.getMessage());
                return "Podaci neuspešno preuzeti";
            }
            return "Podaci uspešno preuzeti";
        }

        @Override
        protected void onProgressUpdate(Integer... progress) {
            super.onProgressUpdate(progress);
            dl.setProgress(progress[0]);
        }

        @Override
        protected void onPostExecute(String result) {
            Toast.makeText(dl.getContext(), result, Toast.LENGTH_SHORT).show();
            dl.dismiss();
        }
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanteState) {
        AlertDialog.Builder b = new AlertDialog.Builder(getActivity());
        b.setMessage(R.string.upit_poruka)
                .setPositiveButton(R.string.upit_da, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        if (Provera()) {
                            upd(getActivity());
                        }
                        Izadji();
                    }
                })
                .setNegativeButton(R.string.upit_ne, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        Izadji();
                    }
                });
        return b.create();
    }

    protected void Izadji() {
        this.dismiss();
    }

    protected boolean Provera() {
        return true;
    }

    public void upd(Context context) {
        dl = new ProgressDialog(context);
        dl.setMessage("Preuzimanje najnovijih podataka...");
        dl.setIndeterminate(false);
        dl.setMax(100);
        dl.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dl.setCancelable(true);
        dl.show();
        DownloadFile dlf = new DownloadFile();
        dlf.execute("http://podcasts.aolcdn.com/massively/podcasts/03-19-13-massively-E241.mp3");
    }

    @Override
    public void onStop() {
        super.onStop();
    }
}

The problem is most likely in the path of the file. BTW, I've asked for permission in AndroidManifest.xml


text:
Q: Forming a recursive equation from a function I've been asked to form a recurrence equation from a recursive function and solve it for T(n). This function  divides an array of  elements into two halves; find the highest value of each half, then returns the highest of the two. However I am having some trouble understanding how to form a recurrence equation from this function.
I've looked at some similar questions here and elsewhere on the internet, and from what I think I've understood, this function does two recursive calls and splits the data into 2 each time, and size should be = n, however I am unsure regarding the other elements in the function and how to write them correctly.
ℎ([], , )
{
  ( == 1)
  A[];

  1 = ℎMax([], , ⌊/2⌋);
  2 = ℎMax([],  + ⌊/2⌋,  − ⌊/2⌋);

  if (1 ≥ 2)
   1;

   2;
}

A: T(n) = 2T(n/2) + c
Time complexity - O(n)
The function makes 2 recursive calls on sub arrays of size n/2 and a constant work


text:
Q: Set WinForm Show Date from MySQL C#/MySQL - Set WinForm Access Date MySQL
So I created a MySQL Database which my form is able to access & login to. My goal for it is to be able to pull information from the MySQL Database into the form as a label (I know easy right?).
Example:

The hardest problem for me was figuring out how to store lets say a "Subscription" start/end date and be able to tell me on a label, how many days I had left on my subscription. All this using information for the database.
(Yes this database is for test purposes only no where near final.)

*

*Created a table called edata.
Created fields the program would use
(Account Status/StartSub/EndSub)

My Question: How would I go about taking the dates entered and creating a value that I could use to show in the "Days Left Here" label?

A: I will create the table like this:
CREATE TABLE `test`.`New Table` (
  `ID` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `FirstName` VARCHAR(45),
  `LastName` VARCHAR(45),
  `Username` VARCHAR(45),
  `Password` VARCHAR(45),
  `Account` INTEGER UNSIGNED,
  `StartSub` DATETIME,
  `EndSub` DATETIME,
  PRIMARY KEY (`ID`)
)
ENGINE = InnoDB;

Then query like this:
using (MySqlConnection conn = new MySqlConnection(constring))
{
    using (MySqlCommand cmd = new MySqlCommand())
    {
        cmd.Connection = conn;
        conn.Open();

        cmd.CommandText = "select * from edata where id = 1;";
        MySqlDataAdapter da = new MySqlDataAdapter(cmd);
        DataTable dt = new DataTable();
        da.Fill(dt);

        conn.Close();

        DateTime dateStart = Convert.ToDateTime(dt.Rows[0]["StartSub"]);
        DateTime dateEnd = Convert.ToDateTime(dt.Rows[0]["EndSub"]);

        if (DateTime.Now >= dateStart && DateTime.Now <= dateEnd)
        {
            TimeSpan ts = dateEnd - DateTime.Now;
            label1.Text = "Active";
            label2.Text = ts.TotalDays + " day(s) left";
        }
        else
        {
            label1.Text = "Expired";
            label2.Text = "0 day left";
        }
    }
}

A: If you can parse the values out it is pretty simple, for example:
string end_date_string = "2014-09-24";
string start_date_string = "2014-09-18";

DateTime end_date = DateTime.Parse(end_date_string);         // parse end date
DateTime start_date = DateTime.Parse(start_date_string);     // parse start date
TimeSpan dur = end_date.Subtract(start_date);                // total duration
TimeSpan timeleft = end_date.Subtract(DateTime.Now);         // how much time left until we hit the end_date

Label l;
l.Text = timeleft.Days.ToString();
// l.Text = timeLeft.Hours.ToString();
// l.Text = timeleft.Minutes.ToString();