Q:

CKEditor : how to ensure consistency for inputs

I'm using CKeditor in my site to get user inputs. I'm using CKEditor as I want user to be able to do some kind of formatting say making text bold, italics, ability to copy-paste content etc.
The input that I get are also used to make some reports.
Now I'm facing the issue that some users are different fonts [some use Arial, some Calibiri, etc] and also use the font size of their preference.
When making reports I want to ensure consistency with respect to at least two things for text entered through site - Font and font size [say I want it to be restricted to Arial and size 10].
I was thinking to disable CKEditor features for selecting font and font size. But if the user is copy-pasting the content then I'll still have the issue of font and size. I'm looking for options that I can try .
One option that came to my mind is - after pasting the content, if I can run the CKEditor with some option to replace the content as per my specification of font & size. If so, how can I do this?
Another option that I'm thinking is - to have another field in the form, that will take the input from the field entered by user and set the value using CKEditor as per my specification.
In both cases, I need to know when the user has completed his action on the field for me to update either the same or different field.
Any suggestions?
thanks
pradeep

A:

The first way to do this is simply to call selectAll and removeFormat commands on getData event:
CKEDITOR.replace( 'editor1', {
    on: {
        getData: function() {
            // Save the old selection
            var ranges = this.getSelection().getRanges();

            this.execCommand( 'selectAll' );
            this.execCommand( 'removeFormat' );

            // Restore the selection
            this.getSelection().selectRanges( ranges );
        }
    }
});

You can also do this on paste event if you like. Please note that removeFormat can destroy your selection and editor won't be able to restore it.
This is a dirty way but you can easily change tags and attributes you want to remove. You can also use this one: config.forcePasteAsPlainText = true; to "dehtmllize" pasted content.
However, to do this gently, you should read a little bit about the data processor.

The gentle approach is:
CKEDITOR.replace( 'editor1', {
    on: {
        instanceReady: function() {
            this.dataProcessor.htmlFilter.addRules({
                attributes: {
                    style: function( attribute ) {
                        return false;
                    },
                    width: function( attribute ) {
                        return false;
                    },
                    height: function( attribute ) {
                        return false;
                    },
                    // ...
                    // You can modify (remove) any attribute you want
                }
            });
        }
    }
});

Eventually you can even filter the style attribute with regex and remove some bits that you don't like.


Q:

Updating data with jQuery Mobile

I have a simple form that contains the jquery UI date picker and basically when the date changes I want to refresh my data (go and get all records based on date).
However i have no idea how to do refresh the data?
So looking for advice and simple example if you could help please.
@model ViewModels.ScheduleMobileDisplay
@{
    ViewBag.Title = "Test";
    Layout = "~/Views/Shared/_AppHomeLayout.Iphone.cshtml";

}

@using (Html.BeginForm())
{
{

        <link href="~/Content/CSS/jquery-ui-1.10.1.Redmond/jquery-ui-1.10.1.custom.min.css" rel="stylesheet" />

            <input type="text" id="datepicker"  placeholder="Select Date" />

                    @Model.AppointmentDate

                @foreach (var item in Model.Appointments)
                {

                            @item.StartTime @item.Name

                }

}

A:

You'd want to make an ajax call to a webservice to get the data, then update your page in the ajax call's success callback.
$.ajax('www.mywebsite.com/myserviceurl', {
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: messageData,
    type: 'POST',
    timeout: 20000,
    success: function(data) {
        /* update page here */
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.log(errorThrown);
    }
});


Q:

When I reopen the program is everything fades in txt file

I have a code like that,
database = open(r"C:\Users\PC\Desktop\database.txt", "w")

print("Please type 1 if add a film")

enter = input("Enter: ")

if enter == "1":
    film=input("Please write a film name: ")
    database.write(film)
    database.close()

When I reopen the program is everything fades in txt file.How I do before writing what I write is saved under :)

A:

Use the a mode.
database = open(r"C:\Users\PC\Desktop\database.txt", "a")

The w mode will truncate the file when you open it (rewriting the file), while this will append to the end of the file.
To append into a new line, simply:
if enter == "1":
    film=input("Please write a film name: ")
    database.write(film + "\n") #\n is the newline character
    database.close()


Q:

disable-output-escaping=yes is not working in the below case

I have below sample xml  `
<?xml version="1.0" encoding="utf-8"?>
<TDX>
<AddressData>
    <AddressDetail>
<Address FieldName="ReceiverAddress1" FieldValue="CNR TOORONG & TOORAK RD"/>
    </AddressDetail>
</AddressData>
</TDX>

And the XSLT that transforms this xml into desired format. I have taken a single node here

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="xml"/>
  <xsl:template match="/">
    <ConNotes>
      <ConNote>
        <ReceiverAddress1>
          <xsl:value-of  disable-output-escaping="yes" select="TDX/AddressData/AddressDetail/Address[@FieldName='ReceiverAddress1']/@FieldValue"/>
        </ReceiverAddress1>
      </ConNote>
    </ConNotes>
  </xsl:template>
</xsl:stylesheet>

Whenever I try to transform the XML using xslt I get the error "Whitespace is not allowed at this location". I have figured it out that this error is due to the special character & present in the FieldValue attribute of address node.
I have tried disable-output-escpaing="yes" but it's not working as expected.
I have used "output method="xml"" in the XSLT file.
Please help me with this. I am using XML notepad for applying the transformation.
I am expecting the output xml like this:

<?xml version="1.0" encoding="utf-8" ?>
- <ConNotes>
- <ConNote>
  <ReceiverAddress1>CNR TOORONG & TOORAK RD</ReceiverAddress1>
  </ConNote>
  </ConNotes>

A:

When you use disable-output-escaping="yes" then the ampersand & in the output is not escaped as entity &. The output is then not a well-formed XML document. When you open the result XML in IE you will get the "Whitespace..." error.
The fix is trivial: Just remove the disable-output-escaping="yes" and
the output will be well-formed:
<ConNotes>
<ConNote>
<ReceiverAddress1>CNR TOORONG & TOORAK RD</ReceiverAddress1>
</ConNote>
</ConNotes>


Q:

XTS-AES Mode in C#

Is it possible to use AES in XTC mode in C# (.net 3.5)? It doesn't seem to be in the CipherMode enumeration. I cannot seem to find any implementations of it on the web.
EDIT: Since I couldn't find a .net implementation,  I wrote one: https://bitbucket.org/garethl/xtssharp

A:

I have since written a C# implementation of XTS mode (using the built in AES cipher in .net), and released it under a BSD license. You can find it here: https://bitbucket.org/garethl/xtssharp


Q:

Differences in iterating over Linked Lists

I know that iterating through a LinkedList using
for(int i = 0; i < list.size(); i++){
  Item item = list.get(i);
}

to get the single objects has bad performance as each call of .get(i) iterates from the beginning of the list up to i.
The correct way would be using an Iterator. So far so good.
But what about this style:
for(Item item : list){
  // item is already here
}

Does this have the same performance like using Iterators? How does this work internally?

A:

Does this have the same performance like using Iterators?

Yes. Both variants generate the same bytecode. The following byte code was generated from a for-each-loop, but when using an iterator in the loop it looks exactly the same:
for(Object o : list) {
}

  44: aload_1
  45: invokevirtual #30                 // Method java/util/LinkedList.iterator:()Ljava/util/Iterator;
  48: astore_3
  49: goto          59
  52: aload_3
  53: invokeinterface #34,  1           // InterfaceMethod java/util/Iterator.next:()Ljava/lang/Object;
  58: astore_2
  59: aload_3
  60: invokeinterface #40,  1           // InterfaceMethod java/util/Iterator.hasNext:()Z
  65: ifne          52

How does this work internally?

In case of non-arrays, the for-each-loop uses Iterators internally. See the byte code above - all the methods are invoked which would also be invoked when using an Iterator.
See also The For-Each Loop and How does the Java 'for each' loop work? for some additional information.


Q:

MonthCalendar in .NET - expanding a month

I have a WinForm app with a MonthCalendar control on it. The MaxSelectionCount property is set to 1 day.
There is a certain behavior that I would like to change. If the view is such that the control displays 12 months and the user clicks on a month, it will expand that month and the selected date becomes the last day of that month. I would like to change that to the first day of that month. How can I do this?
Also, what event is raised when I expand a month in this manner? Does it have a specific event?
Thanks.

A:

This is technically possible, since Vista the native control sends a notification (MCM_VIEWCHANGE) when the view changes.  You can capture this notification and turn it into an event.  Add a new class to your project and paste the code shown below.  I pre-cooked the code that selects the first day.  Compile.  Drop the new control from the top of the toolbox onto your form.  Tested on Windows 8, you'll need to check if it works okay on Vista and Win7.
using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class MonthCalendarEx : MonthCalendar {
    public enum View { Month, Year, Decade, Century };
    public class ViewEventArgs : EventArgs {
        public ViewEventArgs(View newv, View oldv) { NewView = newv; OldView = oldv; }
        public View NewView { get; private set; }
        public View OldView { get; private set; }
    }
    public event EventHandler<ViewEventArgs> ViewChange;

    protected virtual void OnViewChange(ViewEventArgs e) {
        if (ViewChange == null) return;
        // NOTE: I saw painting problems if this is done when MCM_VIEWCHANGE fires, delay it
        this.BeginInvoke(new Action(() => {
            // Select first day when switching to Month view:
            if (e.NewView == View.Month) {
                this.SetDate(this.GetDisplayRange(true).Start);
            }
            ViewChange(this, e);
        }));
    }

    protected override void WndProc(ref Message m) {
        if (m.Msg == 0x204e) {         // Trap WMREFLECT + WM_NOTIFY
            var hdr = (NMHDR)Marshal.PtrToStructure(m.LParam, typeof(NMHDR));
            if (hdr.code == -750) {    // Trap MCM_VIEWCHANGE
                var vc = (NMVIEWCHANGE)Marshal.PtrToStructure(m.LParam, typeof(NMVIEWCHANGE));
                OnViewChange(new ViewEventArgs(vc.dwNewView, vc.dwOldView));
            }
        }
        base.WndProc(ref m);
    }
    private struct NMHDR {
        public IntPtr hwndFrom;
        public IntPtr idFrom;
        public int code;
    }
    private struct NMVIEWCHANGE {
        public NMHDR hdr;
        public View dwOldView;
        public View dwNewView;
    }
}


Q:

Html and css Trying to put image

I am trying to put image to above of my video but it won't show up, only little mark top of the left side ? I know this is maybe simple but I don't get it.Maybe add something to css and change that images code place ?
<!DOCTYPE html>

<TITLE>    </TITLE>

<LINK href="to.css" rel="stylesheet" type="text/css">

HOME

 dropdown #1

dropdown #1 item #1

dropdown #1 item #2

dropdown #1 item #3

 dropdown #2

dropdown #2 item #1

dropdown #2 item #2

dropdown #2 item #3

Hello and Welcome --------------

<video width="900" height="550" controls >
<source src="fifa.mp4" type="video/mp4">
<source src="fifa.ogg" type="video/ogg">
<source src="fifa.webm" type="video/webm">
<object data="fifa.mp4" width="320" height="240">
<embed src="fifa.swf" width="320" height="240">
</object>
</video>

CSS:

body {
margin:0;
padding:0;
min-width:525px;
font-family: Arial;
font-size: 17px;
background-image:url('fifa2.jpg');
}

#header {
float: left;
width: 100%;
height: 100px;
position: absolute;
}

#footer {
float: left;
width: 100%;
background-color: #000000;
font-size: 14pt;
font-weight: bold;
text-align: center;
position: absolute;
height: 40px;
left: 0px;
bottom: 0px;
}

#wrapper {
padding-left: 200px;
padding-right: 125px;
overflow: hidden;
}

#left_side {
position: relative;
float: left;
width: 200px;
right: 200px;
margin-left: -100%;
padding-bottom: 2000px;
margin-bottom: -2000px;
}

#right_side {
position: relative;
float: left;
width: 125px;
background-color: #66CCCC;
margin-right: -125px;
padding-bottom: 2000px;
margin-bottom: -2000px;
}

#content_area {
position: relative;
float: left;
width: 100%;
padding-bottom: 2000px;
margin-bottom: -2000px;
}

#nav {
background-color: #222;
}
#nav_wrapper {
width: 335px;
margin: 0 auto;
text-align: left;
}
#nav ul {
list-style-type: none;
padding: 0;
margin: 0;
position: relative;
min-width: 200px;
}
#nav ul li {
display: inline-block;
}
#nav ul li:hover {
background-color: #333;
}
#nav ul li a, visited {
color: #CCC;
display: block;
padding: 15px;
text-decoration: none;
}
#nav ul li:hover ul {
display: block;
}
#nav ul ul {
display: none;
position: absolute;
background-color: #333;
border: 5px solid #222;
border-top: 0;
margin-left: -5px;
}
#nav ul ul li {
display: block;
}
#nav ul ul li a:hover {
color: #699;
}

video {
margin-top: 250px;
}

![My page][1]

Link to image: [1]: http://i.stack.imgur.com/AARLw.jpg

A:

Set css position form image and video elements as:
img{
   position:absolute;
}

video{
   position:relative;
}


Q:

Give Website Minimum Browser Size

I use a lot of absolute elements in my website design so that it will mold to whatever browser dimensions are being used, but there is a minimum size that I want to use. In other words, I want my website to become compact as the browser is being resized smaller but at a certain point I want the overflow:auto attribute to kick in and force the user to see the whole page using scrolling instead of compacting the page further.
Any ideas? I tried putting in an empty table with specific dimensions into an element with overflow:auto, but that didn't work. I am not a terribly experienced web-designer.

A:

CSS
html, body {
    min-width: 980px;
}


Q:

Windows Phone 7 resolution - Is my emulator lying to me?

All the talk on WP7 resolution = 800x480. I can create more than 480 and it shows up in the emulator - I just don't know if this means I do have more screen space than is promulgated or if my emulator is lying to me.
Putting a Silverlight app in Landscape only mode (SupportedOrientations="Landscape" Orientation="Landscape" in <phone:PhoneApplicationPage />). I'll have a width of 800 and height of 480 (d:DesignWidth="800" d:DesignHeight="480").
I change d:DesignHeight to d:DesignHeight="496" and then add as the only XAML inside the <phone:PhoneApplicationPage /> tag:
<Grid x:Name="LayoutRoot" Background="Blue">
    <TextBlock Text="bottom" VerticalAlignment="Bottom"></TextBlock>
</Grid>

See there? My "Bottom" text is still showing on the screen. Anything thoughts?

A:

Your "design" sizes will be overridden at runtime. Your emulator isn't lying but your designer is (now) misleading.
You can data-bind some labels to ActualWidth and Actualheight to verify what's happening.


Q:

Adding a variable into a string

I added this line of Code:
tweet_string = 'Starting activity for insta'
os.system("python3 tweet.py tweet_string")

As you can see the tweet script uses the first argument as tweet context. Unfortunately I don't know how to use the variable correct... Can you assist me here?

A:

Of course, don't pass your variable name in the literal string...
Just adding out of quotes doesn't cut it because of the spaces. You have to protect with quotes.
it should be:
os.system('python3 tweet.py "{}"'.format(tweet_string))

(better, but if there's a quote in tweet_string you'll have an issue again)
Anyway: don't use os.system it's deprecated. This is better and handles quoting automatically:
import subprocess
subprocess.check_call(["python3","tweet.py",tweet_string])

(Python 3.5 added a unified subprocess.run method which can check return code or not, redirect output in a variable or not, which is the recommended approach to run a subprocess if you don't need to be compatible with previous versions)
Of course, always ask yourself the question when running a python subprocess inside a python module: wouldn't it be easier to import the module and call a function?


Q:

Using Breakpoint in Eclipse with counterclockwise debugger

While everything is configured properly, clojure working fine with Eclipse, I am unable to add breakpoint to code. On right clicking in Text Editor's window there is no option as "toggle breakpoint" for debugging.

A:

http://code.google.com/p/counterclockwise/issues/detail?id=288&start=100
I posted an issue to CCW bugtracker.
It seems, latest version of the CCW plugin somehow forget about debugging.


Q:

Cannot start Docker in Azure Shell

When in Azure Shell I type the following
PS Azure:\> systemctl start docker.service

I get the following error message

Error getting authority: Error initializing authority: Could not
  connect: No such file or directory (g-io-error-quark, 1) Failed to
  connect to bus: No such file or directory

How can I resolve it?
Thank you in advance

A:

Azure Cloud Shell offers a browser-accessible, pre-configured shell experience for managing Azure resources without the overhead of installing, versioning, and maintaining a machine yourself. You could read the supported features and tools here.
Moreover, you could not run the docker daemon in the Azure cloud shell since Cloud Shell utilizes a container to host your shell environment, as a result running the daemon is disallowed. You could Utilize docker-machine to manage Docker containers from a remote Docker host.


Q:

jSpinner time picker model editing

I have jSpinner using for time picking.
Problem 1: User can edited hour minutes and second seperator ":" and can write extra digits like "123"
Problem 2: model get always current time. I want "00:00:00" When i write this in code instead "hh:mm:ss" user can't edit the values.
My Code is;
spinner1 = new javax.swing.JSpinner();
SpinnerDateModel spinnermodel = new SpinnerDateModel();
spinnermodel.setCalendarField(Calendar.MINUTE);
spinner1 .setModel(spinnermodel);
spinner1 .setEditor(new JSpinner.DateEditor(spinner1 , "hh:mm:ss"));

Any help appreciated. Thanks.

A:

Problem 1: User can edited hour minutes and second seperator ":" and
  can write extra digits like "123"

You can use the editor's formatter to accomplish this through getTextField() method:
JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner, "HH:mm:ss");
DateFormatter formatter = (DateFormatter)editor.getTextField().getFormatter();
formatter.setAllowsInvalid(false); // this makes what you want
formatter.setOverwriteMode(true);

The text field is in fact a JFormattedTextField with a DateFormatter as formatter. Take a look to How to Use Formatted Text Fields for a better understanding on how to work with this component.
Note the pattern used when the editor is created. It's "HH:mm:ss" because of your 2nd requirement.

Problem 2: model get always current time. I want "00:00:00"

You need to provide to your spinner with an initial date at 12 PM (24 hours) which will be translated in "00:00:00":
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 24);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);

SpinnerDateModel model = new SpinnerDateModel();
model.setValue(calendar.getTime());

JSpinner spinner = new JSpinner(model);

Example
Here is a quite simple example to test what I've said. Hope it be helpful.
import java.util.Calendar;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SwingUtilities;
import javax.swing.text.DateFormatter;

public class Demo {

    private void createAndShowGUI() {

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 24); // 24 == 12 PM == 00:00:00
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);

        SpinnerDateModel model = new SpinnerDateModel();
        model.setValue(calendar.getTime());

        JSpinner spinner = new JSpinner(model);

        JSpinner.DateEditor editor = new JSpinner.DateEditor(spinner, "HH:mm:ss");
        DateFormatter formatter = (DateFormatter)editor.getTextField().getFormatter();
        formatter.setAllowsInvalid(false); // this makes what you want
        formatter.setOverwriteMode(true);

        spinner.setEditor(editor);

        JPanel content = new JPanel();
        content.add(spinner);

        JFrame frame = new JFrame("Demo");
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.getContentPane().add(content);
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Demo().createAndShowGUI();
            }
        });
    }
}

Edit

When user try manually write hours or minutes (not using arrows) some
  logical problem ocures i think. Example i write 12 but spinner shows
  21.

First off sorry I didn't note that before. This creepy behaviour happens because formatter's overwrite mode property is set to false somewhere during JSpinner.DateEditor's initialization (but couldn't find where). This property is true by default according to javadoc. To solve this you only need to add this line (I've also edited my code above):
formatter.setOverwriteMode(true);


Q:

Red Circle Around Custom Android Button Image

I have created a floating action button, and made my own image (at each of dpi sizes), but there is a red circle around it (image below).  Here is my xml defining the button
<android.support.design.widget.FloatingActionButton
android:id="@+id/addplant"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end|bottom"
android:layout_margin="@dimen/fab_margin"
android:src="@mipmap/add_plant"/>

Here is my source image (@192x192), and a screenshot of what i'm seeing in android studio.

A:

You can try the below -
   <android.support.design.widget.FloatingActionButton
    ...
    ...
    android:src="@drawable/icon" // change backgroung icon
    app:backgroundTint="@android:color/transparent" // change background color
    />

setting tint to transparent will override that primary color pink you have given in styles.

A:

EDIT 2
No need to use app:backgroundTint juse USE android:scaleType="center" in your FloatingActionButton it will work
<android.support.design.widget.FloatingActionButton
    android:id="@+id/addplant"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    android:scaleType="center"
    android:src="@mipmap/add_plant" />

OUTPUT

Try this
<android.support.design.widget.FloatingActionButton
    android:id="@+id/addplant"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="@dimen/fab_margin"
    android:src="@drawable/add_plant"/>

android:src="@drawable/add_plant"

<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:fillColor="#FFFFFF"
        android:pathData="M19,13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"/>
</vector>

OUTPUT

EDIT
To support vector drawablea add this in  your build.gradle file
defaultConfig {
        vectorDrawables.useSupportLibrary = true
 }


Q:

Conflict between JQuery and TinyMCE

I got a .ctp web page with the following lines of code:

    <form name="addpost" id="addpost" method="post" action="/Site1/addtopic">

            <textarea rows="12" cols="48" name="data[Test][content]" id="data[Test][content]"></textarea>

        <input type="submit" value="Send">

No matter how many characters I have entered into the textarea, the alert box will pop up saying "must be ten characters".
Could you help me please?

A:

If I remember it correct, .val() doesn't work correctly to get value of a tinyMCE textarea.
Try this to get the value instead:
tinyMCE.activeEditor.getContent();


Q:

Where can I download best raw files

I am new to photoshop  and need images to practice. I  searched in google for raw files, but with little success .Most of the images are having less resolutions.  I have got very few best images from adobe.  Where can I download the raw files, images which are unedited with good resolution

A:

The best way to do this is to take your own pictures or ask a friend for some. Most digital SLR cameras shoot raw pictures. Some P/S cameras do that as well. Any answer to this question is going to be based on a personal opinion.


Q:

Is it possible to import XML or JSON data from a table within a Word online document into Apps Script website as an HTML table?

I am building a web app using Apps Script.
In this web app I have a table that needs to be populated from a table in a Word doc in OneDrive.
This document is updated regularly, so I would prefer to programmatically update the content of the html table in Apps Script.
Is this possible?
If so, can anyone give me guidance as to how to accomplish this?
I've started looking into importing xml from a url, but I'm not sure that I'm on the right track.

A:

You need to incorporate the following steps

Read your data into a Google Apps function, e.g. with OneDriveApp as recommended by Cooper
Use google.script.run to call the Apps Script function from you html file
Incorporate a Web Polling function that updates your html table with fresh contents in desired intervals

Sample:

code.gs

function doGet(){
  return HtmlService.createHtmlOutputFromFile('index');
}
function getFreshData(){
  //read here your Word Doc data, e.g. with One DriveApp and store it e.g. in an array
  ...
  return myDataArray;
}

index.html

...
<body onload="polling()">
...
  <script>
    function polling(){
      setInterval(myFunction,2000);  //chose how often you want your table
     }
    function myFunction(){
      google.script.run.withSuccessHandler(onSuccess).getFreshData();
    }
    function onSuccess(myDataArray){
      // Create a html table with the freshly obtained myDataArray from the Word Doc
     ...
    }
  </script>
...


Q:

Do Cython files break the Community Edition (Free) PyCharm?

So, the free edition of PyCharm does not support Cython (unlike the paid version). What does this mean? Will it break if I have any *pyx files in my project directory, or refuse to work with those files in any way, or ...?

A:

From the docs:

Cython support includes:
Coding assistance:
Error and syntax highlighting.
Code completion for keywords, fields of structs, and attributes of extension types.
Code formatting and folding.
Ability to create line comments (⌘/).
Cython syntax for typed memoryviews.
Code inspections. Almost all Python code inspections work for Cython.
Refactorings.
Numerous ways to navigate through the source code, among them:
Navigating with Structure View.
Navigate | Declaration (⌘B).
Navigate | Implementation (⌥⌘B) from overridden method / subclassed class.
Advanced facilities to search through the source code, in particular, finding usages.
Compiling Cython modules:
Compilation is done using external tools. The preferred build systems (Makefile, setup.py, etc.) should be configured as external tools.
C compiler should be downloaded and installed on your computer.

The free version just gives you a text editor view of your .pyx, .pxi, and .pxd files, just like any other file it doesn't know what to do with.


Q:

Need help understanding Big-O

I'm in a Data Structures class now, and we're covering Big-O as a means of algorithm analysis. Unfortunately after many hours of study, I'm still somewhat confused. I understand what Big-O is, and several good code examples I found online make sense. However I have a homework question I don't understand. Any explanation of the following would be greatly appreciated.

Determine how many times the output statement is executed in each of
  the following fragments (give a number in terms of n). Then indicate
  whether the algorithm is O(n) or O(n2):
    for (int i = 0; i < n; i++)
        for (int j = 0; j < i; j++)
            if (j % i == 0)
                System.out.println(i + ” ” + j);

A:

Suppose n = 5. Then, the values of i would be 0, 1, 2, 3, and 4. This means that means that the inner loop will iterate 1, 2, 3, 4, and 5 times, respectively. Because of this, the total number of times that the if comparison will execute is 1+2+3+4+5. A mathematical formula for the sum of integers from 1 to n is n*(n+1)/2. Expanded, this gives us n^2 / 2 + n / 2.
Therefore, the algorithm itself is O(n^2).
For the number of times that something is printed, we need to look at the times that j%i=0. When j < i, the only time that this can be true is when j = 0, so this is the number of times that j = 0 and i is not 0. This means that it is only true once in each iteration of the outer loop, except the first iteration (when i = 0).
Therefore, System.out.println is called n-1 times.


Q:

Copy a Guava Optional

Is there a "nice" way to create a copy of an Optional object?
For example, say I have a method
Optional<Obj> doSomeStuff(Optional<Obj> input){
   if(something){
     return Optional.copyOf(input); // does this exist in some Guava library or something?
   }
   // ...
}

Basically, I want to have immutability so that I don't pass the same Optional around, and if something gets triggered then I want to make sure that I create a brand new Optional with same contents of the input Optional (whether it be empty or not).
Is there any clean way to do it? The Optional.copyOf method does not exist.

A:

The Optional class is immutable,  so you do not need copy,. You can just do return input.

A:

Guava Optional is already immutable.
You don't need to make a copy of it.
Here is the beginning of the javadoc:

An immutable object that may contain a non-null reference to another object. Each instance of this type either contains a non-null reference, or contains nothing (in which case we say that the reference is "absent"); it is never said to "contain null".


Q:

Conflicting JS with Popup contact Form

I am trying to implement a popup contact form on a HTML site, and I'm running into a js conflict. I'm stuck with how to get everything on the site to work, because removing some of the js calls causes certain functionality to stop working. I'm sure for this community of experts, my error is probably evident and simple; nonetheless I could really use some help figuring it out. I've included my code below.
Thanks in advance!
<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

    <title>iMAR Affiliate</title>
    <meta content="DSA79" name="author" />
    <meta content="responsive, html5 template, one page, landing, startup, business, company, corporate, creative" name="keywords" />
    <meta content="iMAR Affiliate" name="description" />
    <meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport" />
    <link href="css/bootstrap.css" rel="stylesheet" />
    <link href="css/font-awesome.min.css" rel="stylesheet" />
    <link href="css/flexslider.css" rel="stylesheet" />
    <link href="css/owl.carousel.css" rel="stylesheet" />
    <link href="css/animate.css" rel="stylesheet" />
    <link href="css/style.css" rel="stylesheet" />
    <link href="css/responsive.css" rel="stylesheet" />
    <link href="js-image-slider.css" rel="stylesheet" type="text/css" />
    <link href="http://fonts.googleapis.com/css?family=Lato:400,900italic,900,700italic,400italic,300italic,300,100italic,100" rel="stylesheet" type="text/css" />

<link type="text/css" rel="stylesheet" href="html5ModalContact.css">

<button class="navbar-toggle" data-target="#navigation-menu" data-toggle="collapse" id="nav-toggle" type="button">Toggle navigation</button>

Home

About

Brochure

Benefits

FAQ

Clients

Contact Us

Contact

Help

Privacy

Terms

© iMAR Entertainment Inc. 2007-2014

<

<form action="newsletter.php" class="subscribe-form pull-right" id="subscribe-form" method="post"><input class="subscribe-input" name="email" placeholder="Enter your e-mail address..." type="email" /><button class="subscribe-submit" type="submit">Subscribe</button></form>

Join our newsletter subscription, be always informed

A:

You are probably loading a jQuery extension before you are loading jQuery.
Change the order of your script tags to

Then the Can't find variable jQuery & TypeError: undefined is not a function (evaluating '$().html5ModalContact') error should be gone.


Q:

MSTest: How to assert positive if one of 3 asserts are valid?

I have an IntegrationTest where I want to test the result of a linq query.
The linq query goes something like this
where myObject.fieldA.StartsWith(aString)
   || myObject.fieldB.StartsWith(aString)
   || myObject.fieldC.StartsWith(aString)

Now I want write the test like so:
foreach(var result in results)
{
   StringAssert.StartsWith(result.fieldA, aString);
   StringAssert.StartsWith(result.fieldB, aString);
   StringAssert.StartsWith(result.fieldC, aString);
}

but of course that is not correct, because it should assert valid when one of the 3 above is valid.
Any idea how to do that using MSTest ?

A:

You can work around it by using
Assert.IsTrue(
    result.fieldA.StartsWith(astring) ||
    result.fieldB.StartsWith(astring) ||
    result.fieldC.StartsWith(astring)
);


Q:

What strategy should I use when I run across a word not found in Duden?

Here is a sentence from Donna Leon's Acqua Alta, Chapter 20:

Als sie Brunetti hinter sich herplatschen hörte, ging sie noch zwei Stufen höher und drehte sich zu ihm um.

The word "herplatsch(en)" is not to be found in Duden Online. Of course, neither is it to be found in Reverso, Pons or Leo. What is the best strategy for someone who is reading to learn German and who encounters such a situation, to understand the meaning?

A:

The word herplatschen consists root of the platschen and the prefix her-.
Platschen can be found in Duden.
I think you should learn about prefixes. Or at least keep a list of them.
When you have a word you can't find, check if it has a prefix and search for the root.

A:

In this case Google Translate gives the translation "splash around", which I suppose could be derived from the components, but Google uses it's own database of translations. The larger question though is what strategy to use if the usual references come up dry. First, add dict.cc and DWDS (as mentioned in the comments) to your list of go to references. DWDS has both a dictionary and a usage database, which are both useful depending on the situation. (The first dictionary I go to is Wiktionary, which doesn't cover some of the more unusual words, but it's easy to read and covers most of what you might find out there in the wild.) Also try Google Translate and DeepL; we all know their AI isn't perfect but it can give you a starting point. For technical or specialized words try the German Wikipedia, the trick I often use is to find the article there, then look on the left side of the page for versions of the article in other languages and click on English. You might also try doing a regular Google search on the word. I tried this in this case and it turned up a few old dictionaries, example link. Then of course don't underestimate the power of context. If all that fails then do a search here and ask if nothing relevant comes up. With the internet there are many resources available that didn't exist in the past, so you don't have to just rely on dictionaries nowadays.


Q:

Is passing data between directives, controllers, and services using $emit and $broadcast bad practice?

Hi I'm a beginning Angular developer and I was wondering if the way I've passed data between controllers is bad practice or not.
I'm creating a seatmap widget whereby you click on a seat and it will display data in another part of the App using a different controller.
1) I have a directive that incorporates dynamic templating. Based on the model being passed (from an ng-repeat), it will create an event listener like so:
if(scope.seat.isAvailable) {
  element.bind('click', function() {
    scope.$emit('clickedSeat', scope.seat);
  }
  element.append(seatAvailableTemplate);
}

2) In my controller, I have the following listening for the click:
$scope.$on('clickedSeat', function(event, seat) {
  seatSelectionService.broadcastSeatData(seat);
}

3) I have a service where I've passed in $rootScope which allows me to broadcast the data to a different controller:
var seatSelectionService = {};
seatSelectionService.broadcastSeatData = function(clickedSeat) {
  seatSelectionService.seatData = clickedSeat;
  $rootScope.$broadcast('seatSelected');
}
return seatSelectionService;

4) In the other controller, I have a listener which sets the $scope attribute, which renders {{selectedSeat}} in the view:
$scope.$on('seatSelected', function() {
  $scope.selectedSeat = seatSelectionService.seatData;
  $scope.apply();
}

Of course I have had to pass in seatSelectionService into both controllers for it to work.
Is there a better way to do this? Or is this way of passing data valid practice?

A:

$broadcast and $emit themselves aren't bad practice, but it does look like you've over complicated your app.
You can add services directly to directives - they can have controllers built into them that depend on the services.
So in your directive, add a controller that uses the seatSelectionService, something like:
seatSelectionService.setSeat( scope.seat )

Which cuts out one of the steps at least - your setSeat method would still want to do a $broadcast when it's done down to anything listening.
Directives can be really simple or really complex - they can simply be a quick way of outputting a repeated template, or a dynamic template with a controller and access to multiple services.
Something else you might want to look at is promises - I used to use $broadcast and $emit a lot more than I needed to, until I learnt how to use promises and defer properly


Q:

Firefox/Chrome Web Extension - Security Error When Trying To Inject IFrame Through Content Script

I have the following really simple code in a content script that runs whenever a button in my "popup.html" file is pressed:
Section of code inside "inject.js"
browser.runtime.onMessage.addListener((message) => {
    console.log("Trying to inject iFrame");
    var iframe = document.createElement("iframe");
    iframe.src = browser.extension.getURL("inject.html");
    document.body.appendChild(iframe);
});

The content of "inject.html" is:
<!DOCTYPE html>
<html>

<head>
</head>

<body>
    <p>
        Hello. This is a Test.
    </p>
</body>

</html>

However, when this code runs I get the following output in the console (Using "example.com: as an example URL):

Trying to inject iFrame
  Security Error: Content at http://example.com/ may not load or link to moz-extension://218287b3-46eb-4cf6-a27f-45b9369c0cd9/inject.html.

Here is my "manifest.json"
{
"manifest_version": 2,
"name": "Summarizer",
"version": "1.0",

"description": "Summarizes webpages",

"permissions": [
    "activeTab",
    "tabs",
    "storage",
    "downloads",
    "*://*.smmry.com/*"
],

"icons":
{
    "48": "icons/border-48.png"
},

"browser_action":
{
    "browser_style": true,
    "default_popup": "popup/choose_length_page.html",
    "default_icon":
    {
        "16": "icons/summarizer-icon-16.png",
        "32": "icons/summarizer-icon-32.png"
    }
}

"web_accessible_resources": [
    "inject.html"
]
}

And, lastly, here is the top level file structure of my extension:

How can I fix this security error?
This is not a duplicate of this: Security error in Firefox WebExtension when trying getUrl image because I provided the full path in my manifest.json

A:

I was missing a comma. Here is the relevant portion of the manifest.json with the comma in place:
"browser_action":
{
    "browser_style": true,
    "default_popup": "popup/choose_length_page.html",
    "default_icon":
    {
        "16": "icons/summarizer-icon-16.png",
        "32": "icons/summarizer-icon-32.png"
    }
},

"web_accessible_resources": [
    "inject.html"
]


Q:

Edited post used for audit

I was recently temporarily banned from audit following the following bad review:
https://stackoverflow.com/review/low-quality-posts/24433630 in case you cannot fully access the review, here is a screenshot

To me, the messages, comments and the fact this message was edited (I was unable to access the edit history) strongly suggests the first version of the answer contained spam and/or offensive language, but this has been edited out.
At the end, the answer I was asked to review looked acceptable to me (e.g. I leave it up to the community to upvote/downvote/accept this answer based on its technical accuracy).
I will patient a few more hours before reviewing (not a big issue), but I wanted to take this opportunity to report what could be a bug in the audit system: the audit system picked an answer, and the test was based on the first version of that answer, instead of the current (and edited) version of this answer.
FWIW, there are similarities with Failed review audit for a post, but it looks alright? except I am making a suggestion on how to fall into this again.

A:

If a post wasn't spam at time of flagging, the spam flags should not have been validated otherwise we get incorrect review audits like these.
Similar to the issue you linked (Failed review audit for a post, but it looks alright?), I've cleared the spam flags and re-deleted the answer.


Q:

Give a unit vector perpendicular to vector $v=2i+3j$.

Solution is "multiples of $3i-2j$". How is this answer reached?

A:

Hint: $u = xi +yj \perp yi -xj$. You can take $v = \dfrac{yi-xj}{\sqrt{x^2+y^2}}$, and use $x = 2$, and $y = 3$. Then: $u \perp v$, and $||v|| = 1$


Q:

How can I toggle the margin of an element using JavaScript?

I am trying to move a div to the side, and back, with a transition, by changing the margin. I have one button that I want to toggle it's margin. The div moves to the right,but when I click again, it doesn't move back to it's original position. This is what I have:
HTML

Click Me!

CSS
#movingdiv {
overflow: hidden;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: gray;
-webkit-transition-duration: 0.3s;
-moz-transition-duration: 0.3s;
-o-transition-duration: 0.3s;
transition-duration: 0.3s;
}

JavaScript
function toggle () {

var el = document.getElementById("movingdiv");
if ( el.style.marginLeft="250px" ) {

    el.style.marginLeft="250px";

}

else {

    el.style.marginLeft="0px";

}

}

Here it is in action:
http://codepen.io/dakoder/pen/nfimJ

A:

You're making an assignment, instead of checking equality. In addition, you have your else condition and if condition mixed. Change it to the following:
if ( el.style.marginLeft==="250px" ) {
    el.style.marginLeft="0px";
} else {
    el.style.marginLeft="250px";
}


Q:

multiplication of Nx1 column vector with Nx3 matrix

I have a column vector Nx1 and a matrix Nx3 and I want to multiply the first element of the Nx1 with all the elements of the first row of the Nx3 matrix and the second element with all the elements of the second row of the Nx3 and so on.
Using for loop it is possible to do it.
Is there any other way to do it.
Thanks

A:

Suppose A is n-by-3 and x is n-by-1 vector.
It's so much fun with bsxfun:
>> myLongExpectedResult = bsxfun( @times, A, x );

A:

I think the faster solution is the following:
C = A.*[B,B,B];

where A is the Nx3 matrix and B the Nx1 matrix


Q:

Missing 'libaudiopolicyservice_intermediates" when trying to compile AOSP 7.1.1 release 6?

ninja: error: 'out/target/product/victara/obj/SHARED_LIBRARIES/libaudiopolicymanager_intermediates/export_includes', needed by 'out/target/product/victara/obj/SHARED_LIBRARIES/libaudiopolicyservice_intermediates/import_includes', missing and no known rule to make it
build/core/ninja.mk:148: recipe for target 'ninja_wrapper' failed
make: *** [ninja_wrapper] Error 1

#### make failed to build some targets (04:02 (mm:ss)) ####

I got this error when compiling AOSP for victara (Moto X 2nd generation)... Anyone know how to fix ?
I'm using this local manifest: https://github.com/renanmarcs/local_manifests/blob/master/local.xml
And this is how I started to compile:
cd ~/aosp
repo sync
source build/envsetup.sh
lunch aosp_victara-userdebug
make -j2

A:

SOLVED: I've changed "USE_CUSTOM_AUDIO_POLICY" in "BoardConfig.mk" to "0" for disable this option.


Q:

How to achieve inset shadow effect in WPF

I have designed an interface in HTML and wish to translate this into WPF but am having troubles with inset shadow.
box-shadow: inset 0 2px 7px 0 rgba(0, 0, 0, 0.5);

The effect im looking for is here in this jsFiddle, how can I translate this into WPF exactly?
Update
What I currently have based on Richards answer is below, its still not showing a shadow though?
<Border Grid.Row="1" CornerRadius="3" Grid.Column="0"  Margin="13,0,12,0" BorderThickness="0"  BorderBrush="#d2d2d2" ClipToBounds="True" Background="#fff0f0f0" >
    <Border Background="Transparent" BorderBrush="Black"  CornerRadius="3" BorderThickness="0" Margin="0">
        <Border.Effect>
            <DropShadowEffect ShadowDepth="2" BlurRadius="7" Color="Black" Direction="270" Opacity="0.5"/>
        </Border.Effect>
    </Border>
</Border>

A:

You could try something like this, tweaking the thicknesses accordingly:
<Border Background="LightGray" BorderBrush="DarkGray"
           BorderThickness="1" ClipToBounds="True">
  <Border Background="Transparent" BorderBrush="Black"
              BorderThickness="0 2 7 0" Margin="-2">
    <Border.Effect>
      <DropShadowEffect ShadowDepth="0" BlurRadius="10"/>
    </Border.Effect>
  </Border>
</Border>


Q:

how would I go about copying the contents of a 2-dimensional list to the clipboard, formatted for Excel?

I have a 2d list in a Python utility that writes to a table using PyQt.  I also want to copy all of the data from that list to the clipboard, with the caveat that it must be formatted for insertion into an excel document or a table in Word (as excel-formatted data generally is).
The question, then, is two-fold:
1) How do I go about formatting the data, stringwise, to match Excel's standards, and 2) how do I copy that to the clipboard?
From what I understand, Excel-formatted data, when viewed directly as plaintext, is XML-formatted in some way, but I don't know how to find out exactly what that XML looks like.  I have not found a text editor that copies the formatting information upon pasting; they all just drop the formatting and paste the cell contents as plaintext.  Copying to the clipboard once I have that should be pretty straightforward, I think.

A:

The easiest way is probably to use TAB seperated values, for example:
15.117  0.681   39.871      533.47
14.771  0.755   47.559      652.65
11.849  0.682   47.561      660.76
10.92   0.63    46.908      658.26
10.087  0.613   47.649      676.23

This pastes well in Word and Excel (however, tabs are replaced with spaces in the example above - choose 'edit' to copy tha sample data).
For a real table in Word, you could format your data as a html table.
It is also possible to put multiple formats on the clipboard, but I'm not sure how this would be done in Python.

Mark Ransom's answer uses the Windows API to copy to the clipboard. This allows you to set the clipboard format.
See this for the standard formats.
For the html format you'll need to add some header data.


Q:

How to hide products in Shopify search results based on a vendor name

I'm in a situation where hiding a certain vendors products in the control panel isn't an options due to an outside POS.  For a test in search.liquid, I used search.terms like below.  This code works but not everyone will type thevendor exactly the same way and will see the products if they don't type thevendor.
{% for item in search.results %}
{% if search.terms == 'thevendor' %}
{% else %}
{% include 'search-result' %}
{% endif %}
{% endfor %}

I tried to figure out how to write the code to hide these products in a better way.  I tried product.vendor like below but when I search for those products individually they are not hidden.  The code:
{% for item in search.results %}
{% if product.vendor == 'thevendor' %}
{% else %}
{% include 'search-result' %}
{% endif %}
{% endfor %}

Can someone tell me what I'm missing here?  It seems it doesn't know what product.vendor is but when I print out who the vendor is, it displays the vendor.  I don't understand why it's not hiding the products that are associated with this vendor.

A:

{% for item in search.results %}
{% if item.product.vendor == 'thevendor' %}
{% else %}
{% include 'search-result' %}
{% endif %}
{% endfor %}

This should work.


Q:

In a text based adventure game, how do I prevent long confusing conditional code?

I am creating a text-based, choose your own adventure game in C++.
In this game, there will be lots of possibilities on where you choose to go, what you choose to do etc.
My question is, how do I prevent this from becoming extremely confusing.
Example:
Lets say at one point in the game you can be asked whether to go to the forest or the desert. If you choose desert, thats a COMPLETELY different story line from the forest.
So how would I prevent from my code looking like this.
if (player goes to the desert)advice? {
    /*Whole story line of the desert*/
else if (player goes to the forest) {
    /*Whole story line of the forest */

Inside of these story lines there would be more conditionals like that, and more elaborate story lines, so is there any way that I can write the code for one story line in a separate file, then just run that file for that conditional? Anyways I can do that separately instead of writing everything out inside of the conditionals? If I did that the code would quickly become long and confusing to look at/edit.
I was thinking about doing headers and making functions inside of the headers that write out the story line, so I would just have to type out the function, but if I did that, then I couldnt access the global variables in the game such as playerName or playerRace etc.
Any and all suggestions are appreciated. I'm new to C++ so please forgive me if I've missed something painstakingly obvious.

A:

Probably a class based solution. The question is quote broad, so not quite sure which design patterns would fit. However, a sample class may be CrossroadsDesicision that'll export options ["Go to desert", "Go to city", ...] and have a method apply that should receive an options from the array and return the relevant decision class for the next step
Edit:
The base class should contain:

possibleDecisions - an array of possible decisions (You could use an option class here, composed of a name (string or enum - you should use templating here) and a description)
apply - a function receiving a decision, acting on it, and returning the next decision


Q:

Login with Facebook API

I have successfully created login with Facebook API, when user logins auth token is returned. But how can I get user details from Facebook API? What kind of query I have to make to Facebook API to get logged in users name etc. details ?

A:

Simply use 'me' to denote the logged in user and use the access_token to access all permitted resources like:
https://graph.facebook.com/me?access_token=...

Also you can access all permitted fields using below:
Friends: https://graph.facebook.com/me/friends?access_token=...
News feed: https://graph.facebook.com/me/home?access_token=...
Profile feed (Wall): https://graph.facebook.com/me/feed?access_token=...
Likes: https://graph.facebook.com/me/likes?access_token=...
Movies: https://graph.facebook.com/me/movies?access_token=...
Music: https://graph.facebook.com/me/music?access_token=...
Books: https://graph.facebook.com/me/books?access_token=...
Notes: https://graph.facebook.com/me/notes?access_token=...
Permissions: https://graph.facebook.com/me/permissions?access_token=...
Photo Tags: https://graph.facebook.com/me/photos?access_token=...
Photo Albums: https://graph.facebook.com/me/albums?access_token=...
Video Tags: https://graph.facebook.com/me/videos?access_token=...
Video Uploads: https://graph.facebook.com/me/videos/uploaded?access_token=...
Events: https://graph.facebook.com/me/events?access_token=...
Groups: https://graph.facebook.com/me/groups?access_token=...
Checkins: https://graph.facebook.com/me/checkins?access_token=...

Full information is here: http://developers.facebook.com/docs/reference/api/


Q:

Using John Papa's AngularJS style guide, what is the proper way to declare data objects?

Let's say that I have an AngularJS data service that makes a call to the server and returns an object that can be extended with additional methods.  For example, assume the following function is part of an AngularJS service for something like NerdDinner.
function getDinner(dinnerId) {
   return $http.get('api/dinner/' + dinnerId)
      .then(loadDinnerComplete)
      .catch(loadDinnerFailed);

   function loadDinnerComplete(response) {
      return new Dinner(response.data);
   }
}

What's the best practice for a place to define the Dinner class?  Is that a factory in a separate file?  Do I define that in the NerdDinner service?  Or do I define that in the GetDinner class (assuming that's the only method that can create dinners)?
I did not find any specific reference to creating objects in the style guide, so forgive me if it's covered and I just missed it.
Edit
I ultimately decided to accept Jeroen's answer because it most matched my needs for a rather simple use case.  However, Daniel's answer is pure gold, and should not be overlooked.  If I chose to extend the functionality of my DTO with simple CRUD or additional server based operations, a $resource is a great approach.

A:

Where to place business entities (like Dinner) is not explicitly mentioned in John Papa's style guide (afaik).
If you want to go this route (using business entities and placing logic there), I should give each entity its own factory:
(function() {
  'use strict';

  angular
    .module('myDinner')
    .factory('Dinner', DinnerFactory);

  function DinnerFactory() {

    Dinner.prototype.eat = eat;
    Dinner.prototype.cancel = cancel;

    return Dinner;

    // Constructor

    function Dinner (data) {
        // this is just an example:
        this.time = data.time;
        this.location = data.location;
    }

    // Methods

    function eat() {
      // ...
    }

    function cancel() {
      // ...
    }

  }

})();

Then you can inject them into your controller or maybe other service objects, just using Dinner, and create a new Dinner object using new Dinner(data).
You could also use a service, but John Papa discourages services, because they are too similar to factories.

A:

IMO what you are doing has already been done in $resource and restacular. You are talking about "defining data objects" (or, models in typical parlance). That said, defining each "data object" as its own factory is the way to do it, as per John Papa's advice regarding single concerns.
John Papa talks about this in the factories section.
If you want to work this out by hand, IMO you could define your models and append methods on each which would represent various crud operations. This is the pattern $resource and restangular (sort of) take.
//Dinner model as angular factory, each of these methods returns a promise

function Dinner($http) {
    return {
        create: function(route, body) { /** http.post */ },
        get: function(route) { /** http.get */ },
        update: function(route, body) { /** http.put */ },
        destroy: function(route) { /** http.delete */ }
    };
}

now your Dinner model has convenient crud methods built in so you could do
var dinner = new Dinner;
dinner.get("/api/dinner/1").then() //get dinner with id of 1
dinner.update("/api/dinner/1", {name: "burger"}).then() //update dinner with id of 1

Edit:
So if you want to create an object that isn't concerned with retrieving data, IMO you should create another factory that requires your model. This decouples your data retrieval from your data manipulation. In OPs original example, the data retrieval and manipulation are  tightly coupled.
function Meal(dinner) {
    //this.meal is the specified dinner
    this.meal = new Dinner().get("/api/dinner" + dinner);

    //some random build-in data manipulation methods
    return {
        getCalories: function() { return this.meal * 400; },
        getPrice: function() { return (this.meal * 100) + "$"; }
    };
}

Now that you've separated your data-manipulation into a separate object you can do something like this (this is a synchronous example though)
var mcdonalds = new Meal(/** specify which dinner */)
mcdonalds.getPrice() //$4.56
mcdonalds.getCalores() //9999


Q:

Outputting Shiny (non-ggplot) plot to PDF

Is there a method to output (UI end) Shiny plots to PDF for the app user to download?  I've tried various methods similar to those involving ggplot, but it seems downloadHandler can't operate in this way.  For example the following just produces broken PDF's that don't open.
library(shiny)
runApp(list(
  ui = fluidPage(downloadButton('foo')),
  server = function(input, output) {
    plotInput = reactive({
      plot(1:10)
    })
    output$foo = downloadHandler(
      filename = 'test.pdf',
      content = function(file) {
        plotInput()
        dev.copy2pdf(file = file, width=12, height=8, out.type="pdf")
      })
  }
))

Very grateful for assistance.

A:

Solved.  The plot should be saved locally with pdf(), not the screen device (as with dev.copy2pdf).  Here's a working example: shiny::runGist('d8d4a14542c0b9d32786').  For a nice basic model try:
server.R
library(shiny)
shinyServer(
    function(input, output) {

        plotInput <- reactive({
            if(input$returnpdf){
                pdf("plot.pdf", width=as.numeric(input$w), height=as.numeric(input$h))
                plot(rnorm(sample(100:1000,1)))
                dev.off()
            }
            plot(rnorm(sample(100:1000,1)))
        })

        output$myplot <- renderPlot({ plotInput() })
        output$pdflink <- downloadHandler(
            filename <- "myplot.pdf",
            content <- function(file) {
                file.copy("plot.pdf", file)
            }
        )
    }
)

ui.R
require(shiny)
pageWithSidebar(
    headerPanel("Output to PDF"),
    sidebarPanel(
        checkboxInput('returnpdf', 'output pdf?', FALSE),
        conditionalPanel(
            condition = "input.returnpdf == true",
            strong("PDF size (inches):"),
            sliderInput(inputId="w", label = "width:", min=3, max=20, value=8, width=100, ticks=F),
            sliderInput(inputId="h", label = "height:", min=3, max=20, value=6, width=100, ticks=F),
            br(),
            downloadLink('pdflink')
        )
    ),
    mainPanel({ mainPanel(plotOutput("myplot")) })
)

A:

(Hello), just use pdf :
library(shiny)
runApp(list(
  ui = fluidPage(downloadButton('foo')),
  server = function(input, output) {
    plotInput = reactive({
      plot(1:10)
    })
    output$foo = downloadHandler(
      filename = 'test.pdf',
      content = function(file) {
        pdf(file = file, width=12, height=8)
        plotInput()
        dev.off()
      })
  }
))

EDIT : I don't know... It's weird. A workaround is to use dev.copy2pdf like you did in the first place but in the reactive function instead downloadHandler :
## server.R
library(shiny)
shinyServer(
  function(input, output) {
    plotInput <- reactive({plot(rnorm(1000))
                           dev.copy2pdf(file = "plot.pdf")
                           })
    output$myplot <- renderPlot({ plotInput() })
    output$foo <- downloadHandler(
      filename <- "plot.pdf",
      content <- function(file) {
        file.copy("plot.pdf", file)
      })
  }
)


Q:

Efficiently reformat column entries in large data set in R

I have a large (6 million row) table of values that I believe needs to be reformatted before it can be used for comparison to my data set. The table has 3 columns that I care about.
The first column contains nucleotide base changes, in the form of C>G, A>C, A>G, etc. I'd like to split these into two separate columns.
The second column has the chromosome and base position, formatted as 10:130448, 2:40483, 5:30821291, etc. I would also like to split this into two columns.
The third column has the allelic fraction in a number of sample populations, formatted like .02/.03/.20. I'd like to extract the third fraction into a new column.
The problem is that the code I have written is currently extremely slow. It looks like it will take about a day and a half just to run. Is there something I'm missing here? Any suggestions would be appreciated.
My current code does the following: pos, change, and fraction each receive a vector of the above values split use strsplit. I then loop through the entire database, getting the ith value from those three vectors, and creating new columns with the values I want.
Once the database has been formatted, I should be able to easily check a large number of samples by chromosome number, base, reference allele, alternate allele, etc.
pos <- strsplit(total.esp$NCBI.Base, ":")
change <- strsplit(total.esp$Alleles, ">")
fraction <- strsplit(total.esp$'MAFinPercent(EA/AA/All)', "/")
for (i in 1:length(pos)){
    current <- pos[[i]]
    mutation <- change[[i]]
    af <- fraction[[i]]
    total.esp$chrom[i] <- current[1]
    total.esp$base[i] <- current [2]
    total.esp$ref[i] <- mutation[1]
    total.esp$alt[i] <- mutation[2]
    total.esp$af[i] <- af[3]

}

Thanks!

A:

You can use tidyr, dplyr and separate:
library(tidyr)
library(dplyr)

total.esp %>% separate(Alleles, c("ref", "alt"), sep=">") %>%
              separate(NCBI.Base, c("chrom", "base"), sep=":") %>%
              separate(MAFinPercent.EA.AA.All., c("af1", "af2", "af3"), sep="/") %>%
              select(-af1, -af2, af = af3)

You'll need to be careful about that last MAFinPercent.EA.AA.All. - you have a horrible column name so may have to rename it/quote it depending on how exactly r has it (this is also a good reason to include at least some data in your question, such as the output of dput(head(total.esp))).
data used to check:
total.esp <- data.frame(Alleles= rep("C>G", 50), NCBI.Base = rep("10:130448", 50), 'MAFinPercent(EA/AA/All)'= rep(".02/.03/.20", 50))

Because we now have a tidyr/dplyr solution, a data.table solution and a base solution, let's benchmark them. First, data from @akrun, 300,000 rows in total:
df1 <- data.frame(Alleles =rep(c('C>G', 'A>C', 'A>G'), 100000),
                  NCBI.Base=rep(c('10:130448', '2:40483', '5:30821291'),  100000),
                  MAFinPercent= rep(c('.02/.03/.20', '.05/.03/.04', '.02/.04/.03'),  100000),
                  stringsAsFactors=FALSE)

Now, the benchmark:
microbenchmark::microbenchmark(
  tidyr = {df1 %>% separate(Alleles, c("ref", "alt"), sep=">") %>%
                   separate(NCBI.Base, c("chrom", "base"), sep=":") %>%
                   separate(MAFinPercent, c("af1", "af2", "af3"), sep="/") %>%
                   select(-af1, -af2, af = af3)},
  data.table = {setDT(df1)[, unlist(lapply(.SD, tstrsplit,
                                           split='[>:/]', type.convert=TRUE), recursive=FALSE)]},
  base = {pos <- strsplit(df1$NCBI.Base, ":");
          change <- strsplit(df1$Alleles, ">");
          fraction <- strsplit(df1$MAFinPercent, "/");
          data.frame( chrom =sapply( pos, "[", 1),
                      base = sapply( pos, "[", 2),
                      ref  = sapply( change, "[", 1),
                      alt = sapply(change, "[", 2),
                      af  = sapply( fraction,  "[", 3)
          )}
)
Unit: seconds
       expr      min       lq     mean   median       uq      max neval
      tidyr 1.295970 1.398792 1.514862 1.470185 1.629978 1.889703   100
 data.table 2.140007 2.209656 2.315608 2.249883 2.481336 2.666345   100
       base 2.718375 3.079861 3.183766 3.154202 3.221133 3.791544   100

tidyr is the winner

A:

Here is a data.table solution.  We convert the 'data.frame' to 'data.table' (setDT(df1)), loop over the Subset of Data.table (.SD) with lapply, use tstrsplit and split the columns by specifying the split character, unlist the output with recursive=FALSE.
library(data.table)#v1.9.6+
setDT(df1)[, unlist(lapply(.SD, tstrsplit,
        split='[>:/]', type.convert=TRUE), recursive=FALSE)]
#   Alleles1 Alleles2 NCBI.Base1 NCBI.Base2 MAFinPercent1 MAFinPercent2
#1:        C        G         10     130448          0.02          0.03
#2:        A        C          2      40483          0.05          0.03
#3:        A        G          5   30821291          0.02          0.04
#   MAFinPercent3
#1:          0.20
#2:          0.04
#3:          0.03

NOTE: I assumed that there are only 3 columns in the dataset.  If there are more columns, and want to do the split only for the 3 columns, we can specify the .SDcols= 1:3 i.e. column index or the actual column names, assign (:=) the output to new columns and subset the columns that are only needed in the output.
data
df1 <- data.frame(Alleles =c('C>G', 'A>C', 'A>G'),
   NCBI.Base=c('10:130448', '2:40483', '5:30821291'),
   MAFinPercent= c('.02/.03/.20', '.05/.03/.04', '.02/.04/.03'),
   stringsAsFactors=FALSE)

A:

Try this (after retaining your first three lines of code):
 total.esp   <- data.frame( chrom =sapply( pos, "[", 1),
                            base = sapply( pos, "[", 2),
                            ref  = sapply( change, "[", 1),
                            alt = sapply(change, "[", 2),
                            af  = sapply( af,  "[", 3)
                           )

I cannot imagine this taking more than a couple of minutes. (I do work with R objects of similar size.)


Q:

tikz plots alignment

I'm trying to produce a figure using
\begin{figure}
\centering
\makebox[\columnwidth]{\input{try1.tikz}}
\makebox[\columnwidth]{\input{try2.tikz}}
\end{figure}

The files try1.tikz and try2.tikz are given below. The only difference between them is that in the former xmin=-2, in the latter xmin=-4.
I get

How do I align the panels vertically?
try1.tikz is:
\begin{tikzpicture}[font=\footnotesize\sffamily]

\begin{axis}[%
view={0}{90},
width=4cm,
height=4cm,
scale only axis,
xmin=-2, xmax=1,
ymin=0, ymax=1.7,
name=plot2,
unbounded coords=jump]
\end{axis}

\begin{axis}[
view={0}{90},
width=4cm,
height=4cm,
scale only axis,
xmin=-2, xmax=1,
ymin=0, ymax=1.7,
at=(plot2.left of south west), anchor=right of south east,
unbounded coords=jump]
\end{axis}

\begin{axis}[
view={0}{90},
width=4cm,
height=4cm,
scale only axis,
xmin=-2, xmax=1,
ymin=0, ymax=1.7,
at=(plot2.right of south east), anchor=left of south west,
legend style={nodes=right,font=\tiny},
legend pos= north west,
unbounded coords=jump]

\end{axis}
\end{tikzpicture}

and try2.tikz is:
\begin{tikzpicture}[font=\footnotesize\sffamily]

\begin{axis}[
view={0}{90},
width=4cm,
height=4cm,
scale only axis,
xmin=-4, xmax=1,
ymin=0, ymax=1.7,
name=plot2,
unbounded coords=jump]
\end{axis}

\begin{axis}[
view={0}{90},
width=4cm,
height=4cm,
scale only axis,
xmin=-4, xmax=1,
ymin=0, ymax=1.7,
at=(plot2.left of south west), anchor=right of south east,
unbounded coords=jump]
\end{axis}

\begin{axis}[
view={0}{90},
width=4cm,
height=4cm,
scale only axis,
xmin=-4, xmax=1,
ymin=0, ymax=1.7,
at=(plot2.right of south east), anchor=left of south west,
legend style={nodes=right,font=\tiny},
legend pos= north west,
unbounded coords=jump]
\end{axis}
\end{tikzpicture}

A:

You can use the groupplots library:
\documentclass{article}
\usepackage{pgfplots}
\usetikzlibrary[pgfplots.groupplots]

\begin{document}
  \begin{figure}
    \begin{tikzpicture}[font=\footnotesize\sffamily]
      \begin{groupplot}[
          group style={group size=3 by 2},
          view={0}{90},
          width=4cm,
          height=4cm,
          scale only axis,
          xmin=-2, xmax=1,
          ymin=0, ymax=1.7,
          name=plot2,
          unbounded coords=jump]
        ]
        \nextgroupplot          \addplot [domain=-2:1, thick, cyan] {rnd};
        \nextgroupplot          \addplot [domain=-2:1, thick, cyan] {rnd};
        \nextgroupplot          \addplot [domain=-2:1, thick, cyan] {rnd};
        \nextgroupplot[xmin=-4] \addplot [domain=-4:1, thick, cyan] {rnd};
        \nextgroupplot[xmin=-4] \addplot [domain=-4:1, thick, cyan] {rnd};
        \nextgroupplot[xmin=-4] \addplot [domain=-4:1, thick, cyan] {rnd};
      \end{groupplot}
    \end{tikzpicture}
  \end{figure}
\end{document}

Which produces

Any option that is common for all plots can go as the optional arguments to the \begin{groupplot} command, and any that are specific to each plot can be passed to the \nextgroupplot command.
To make the difference between the top and the bottom plots, the best way would probably be by defining a style for all of them, as in zeroth's answer. So I modified my answer to show how options can be passed individually to each \nextgroupplot.

A:

This brings immediate attention to the groupplots library of pgfplots.
Your plot can be realized through:
% \usepgfplotslibrary{groupplots}
\begin{tikzpicture}
  \begin{groupplot}[group style={rows=2,columns=3},
    view={0}{90},
    width=4cm,height=4cm,
    scale only axis,
    xmin=-2, xmax=1,
    bottom plots/.style={xmin=-4},
    ymin=0, ymax=1.7,unbounded coords=jump]
    \nextgroupplot
    \nextgroupplot
    \nextgroupplot
    \nextgroupplot[bottom plots]
    \nextgroupplot[bottom plots]
    \nextgroupplot[bottom plots]
  \end{groupplot}
\end{tikzpicture}

which will yield the following image:

The groupplot environment does the following:

Determines the number of plots by rows and columns in the style group style. (one can also use group size=<cols> by <rows>)
Grab each \nextgroupplot and places it in column-wise order
Each \nextgroupplot is equivalent to \begin{axis} ... \end{axis}
Every option specified in the groupplot (and not in the group style style) environment will be added
to each \nextgroupplot macro, thereby each axis environment.

If you need to adjust the spacing between the plots you have the following styles (which should be placed inside the group style key:

horizontal sep=<dim>
vertical sep=<dim>

Thus you can do:
 group style={vertical sep=0cm}

to make them touch each other in the vertical direction. The pgfplots manual has a whole section of this which I highly suggest you read (it is placed under Related Libraries).


Q:

Fastest wireless solution for home with the best range

I am looking for the fastest wireless (WiFi) solution with the best range for home. What would be the best solution? I have challenging situation with two thick floors.

A:

Fastest wireless solution for home
  with the best range

For speed you may consider a 5GHz wireless network which offers a higher throughput than 2.4 GHz networks, for better range you should install directional antennae rather than range extenders as they will have a negative impact on the speed.
And here's a handy utility to do a site survey and discover 'weak spots'.

Ekahau HeatMapper is a free software tool for quick and easy
  coverage mapping of Wi-Fi (802.11)
  networks. It's the only free,
  easy-to-use tool that shows, on a map,
  the wireless network coverage in your
  home or small office. HeatMapper also
  locates all access points.

A:

Go for Wireless-N Certified devices. I cannot recommend any devices as it changes based on country, but try to look for big (network) brands - Cisco/Linksys, Netgear, Dlink etc.
However, I have had problems with houses that have thick floors, you may want to look at either running ethernet across the house or putting more than one router in your house and enabling it as a repeater / range extender.


Q:

Group Schemes and rational points

Suppose $0\to F \to G \to H \to 0$ is a short exact sequence of group schemes over a field $k$. Then $0 \to F(k) \to G(k) \to H(k) \to 0$ is not exact ($G(k) \to H(k)$ is not surjective). However, is it true if we look at the $k^{sep}$-points or the $k^{alg}$-points instead of the $k$-points ($k^{sep}$ resp. $k^{alg}$ a separable resp. algebraic closure of $k$)? Is there a reference for this fact?

A:

Let us assume that
a) You define a short exact sequence of group schemes to mean that the corresponding sequence of fppf group sheaves is exact
and
b) Your group schemes are of finite type over $k$.
Then one has that
$$0\to F(\overline{k})\to G(\overline{k})\to H(\overline{k})\to 0$$
is exact, and
$$0\to F(k^\mathrm{sep})\to G(k^\mathrm{sep})\to H(k^\mathrm{sep})\to 0$$
is exact if $F$ is smooth over $k$.
The point is that one has an exact sequence
$$0\to F(L)\to G(L)\to H(L)\to H^1_\text{fppf}(\mathrm{Spec}(L),F)$$
for any extension $L$ of $k$.
Now, if $L$ is algebraically closed then $H^1_\text{fppf}(\mathrm{Spec}(L),F)$ is trivial. Indeed, note that $F$ is separated (e.g. see [1, Proposition 1.22]) and thus any $F$-torsor $X$ is representable (e.g. see [2, Theorem 6.5.10(ii)]). But, since $X$ is of finite type over $L$, and $L$ is algebraically closed, we know that $X(L)\ne \varnothing$ and so $X$ is trivial (e.g. see [2, Proposition 6.5.3]).
If, in addition, $F$ is smooth, we need to show that $H^1_\text{fppf}(\mathrm{Spec}(L),F)$ is trivial when $L$ is separably closed. But, by the same argument as above any $F$-torsor $X$ is representable. But, since $F$ is smooth we know that $X$ is also smooth, and thus $X(L)\ne \varnothing$ (e.g. see [2, Proposition 3.5.70]) and thus $X$ is trivial once again.
[1] Milne, J.S., 2017. Algebraic groups: The theory of group schemes of finite type over a field (Vol. 170). Cambridge University Press.
[2] Poonen, B., 2017. Rational points on varieties (Vol. 186). American Mathematical Soc..


Q:

To understand a C code about endianness

I am studying big and little-endianness.
1. What is the purpose of | \ in the following code?
...

#elif defined(LITTLE_ENDIAN) && !defined(BIG_ENDIAN)

  #define htons(A) ((((uint16_t)(A) & 0xff00) >> 8) | \
                    (((uint16_t)(A) & 0x00ff) << 8))
...

2. What is the purpose of (A) in the code?

A:

The '|' is the bitwise OR operator.  It basically combines the values.  The 'A' is the parameter from the #define htons.  It is enclosed in parentheses so that expressions will not confuse the programmer or compiler.  The '\' continues the macro onto the next line.  (A macro usually ends at the end of the line.)
This macro takes the 16-bit value in A and masks out the top 8 bits. It then takes that value and shifts it right 8 bits.  That means the top 8 bits are now on the bottom of the 16-bit value.  It next masks out the top 8 bits of the original value in A and shifts those left 8 bits.  That means the bottom 8 bits are now on the top.  Finally, it recombines the two values back into one value.
The end result is that the top and bottom bytes have had their places swapped.

A:

This code is nothing more than standard C-preprocessor Macros.
The | is the bitwise OR operator. The \ escapes the newline so that the #define can continue to the next line. The (A) is a parameter for the macro.

A:

| performs a bitwise "OR" on two integers
\ is an escape character that allows a #define to cotninue onto the next line


Q:

Подключение FarseerPhysics

Возникла необходимость в подключении физического движка, выбрал Farseer Physics
Делаю по видео
При сборке появляется ошибка:
Ошибка CS0006  Не удалось найти файл метаданных "D:\Andrew\Programs\Farseer Physics Engine 3.5 Samples\Farseer Physics Engine 3.5\bin\WindowsGL\Debug\FarseerPhysics MonoGame.dll
Проверил папку, там и правда нет FarseerPhysics MonoGame.dll
Никто не сталкивался? Не знаю как исправить ошибку, ибо без понятия где брать этот файл
P.S.: Скачивал Farseer Physics с официального сайта

A:

Попробуй так
http://alangamedev.com/farseer-physics-on-visual-studio-2015-monogame/
Чтобы исправить это, разверните все «Ссылки» из всех проектов и удалите MonoGame.Framework (щелкните правой кнопкой мыши и выберите «Удалить»)
Теперь добавьте их, указав на правильный ресурс, сделайте это, щелкните правой кнопкой мыши по «Ссылки» и выберите «Добавить ссылку», затем в появившемся диалоговом окне просмотрите правильную сборку MonoGame, в моем случае она находится в каталоге установки по умолчанию (C:\Program Files (x86)\MonoGame\v3.0\Assemblies\Windows)
Если вы попытаетесь запустить его сейчас, вы получите ошибки в отношении используемой версии .NET Framework, чтобы исправить это, щелкнуть правой кнопкой мыши по всем проектам, выбрать «Свойства» и на появившейся вкладке настроек выбрать Новой .NET Framework (я выбрал 4.5).
Теперь, если вы попытаетесь запустить его, он будет жаловаться на SDL, этот легко исправить, щелкните правой кнопкой мыши на SDL.dll и удалите его тоже:


Q:

How to get only one column-set of array-data (vuejs2 getters)

My efWezlow array:
[{"adres":"Something","w17_18":60,"w16_17":61,"w15_16":62,"w14_15":48,"w13_14":null},
...{}]

I have getters:
export default {
   fil_adres: state => {
     return state.efWezlow.filter(efWezel => efWezel.adres)
   }
}

and in mounted:
get data by
this.$store.getters.fil_adres
My array getters via Vuex
fil_adres: Array[9]
0: Object
   adres: "Something"
   w17_18: 62
   w16_17: 72
   w15_16: 65
1: Object
...
8: Object

And big question how can I get only column 'adres' from array:
[{adres, w17_18, w16_17, w15_16},...{}]
Is it possible?
Filter on getters don't  cut off rest of 'columns' so I get whole array despite want one column.

A:

If you want to do it in getters, and I'm assuming you don't want a list of objects, instead, an array that only contains values of adres, a map suffices:
export default {
  fil_adres: state => state.efWezlow.map(item => item.adres)
}


Q:

Swagger2feature CXF xml configuration

I am trying to configure CXF nonSpring with Swagger to see the json documentation generated, but I can not see where the url that was generated from Swagger is.
Here is my code:
pom.xml
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-rs-service-description-swagger</artifactId>
            <version>3.1.11</version>
        </dependency>

web.xml
<?xml version="1.0"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<display-name>Archetype Created Web Application</display-name>
<servlet>
    <servlet-name>CXFServlet</servlet-name>
    <display-name>CXFServlet</display-name>
    <servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value> com.bank.AdminApplication </param-value>
    </init-param>
    <init-param>
        <param-name>jaxrs.application.address.ignore</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>jaxrs.features</param-name>
        <param-value>
                    org.apache.cxf.jaxrs.swagger.Swagger2Feature
                    (basePath=/swagger/apidocs)
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>CXFServlet</servlet-name>
    <url-pattern>/rest/*</url-pattern>
  </servlet-mapping>
</web-app>

main interface with definitions and annotations:
@Path("/")
@Api(value="/swagger/apidocs")
public interface ApiClient {

    @GET
    @Path("endpoint/consult")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @ApiOperation(value = "Consult test Endpoint", response = Response.class)
    public Response consultEndpoint() throws ServiceException;

}

I go to: http://localhost:8080/webapp/swagger/apidocs
but nothing appears
Any recommendation?

A:

Well, finally I found how to integrate CXF non spring with swagger; here is the code:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>coop.bancocredicoop.test</groupId>
<artifactId>test-api-cxfnonspring-swagger</artifactId>
<version>1.0.0</version>
<name>test-api-cxfnonspring-swagger</name>
<description>Servicios test api rest</description>
<packaging>war</packaging>
<dependencies>
   <dependency>
        <groupId>org.webjars</groupId>
        <artifactId>swagger-ui</artifactId>
        <version>3.6.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-transports-http-jetty</artifactId>
        <version>3.2.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-frontend-jaxrs</artifactId>
        <version>3.2.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-rs-service-description-swagger</artifactId>
        <version>3.2.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>2.9.3</version>
    </dependency>
</dependencies>
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
        </plugin>
        <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
    </plugins>
</build>

web.xml
<?xml version="1.0"?><!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"><web-app><servlet>
  <servlet-name>CXFServlet</servlet-name>
    <servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
    <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.AdminApplication</param-value>
    </init-param>
    <init-param>
        <param-name>jaxrs.address</param-name>
        <param-value>/</param-value>
    </init-param>
</servlet>
<servlet-mapping>
    <servlet-name>CXFServlet</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping></web-app>

AdminAplication.java
import java.util.HashSet;
import java.util.Set;
import javax.ws.rs.core.Application;
import org.apache.cxf.jaxrs.swagger.Swagger2Feature;
import com.fasterxml.jackson.databind.AnnotationIntrospector;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
public class AdminApplication extends Application {
HashSet<Object> singletons = new HashSet<Object>();
public AdminApplication() {
    singletons.add(new PersonService());
}
@Override
public Set<Class<?>> getClasses() {
    HashSet<Class<?>> set = new HashSet<Class<?>>();
    return set;
}
@Override
public Set<Object> getSingletons() {
    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
    AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
    mapper.setAnnotationIntrospectors(primary, secondary);
    JacksonJsonProvider jaxbProvider = new JacksonJsonProvider();
    jaxbProvider.setMapper(mapper);
    singletons.add(jaxbProvider);
    Swagger2Feature feature = new Swagger2Feature();
    feature.setContact("Pablo Garcia");
    feature.setDescription("api Description");
    feature.setPrettyPrint(true);
    feature.setTitle("api title");
    singletons.add(feature);
    return singletons;
  }
}

PersonService.java
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

@Path("/people")
@Produces(MediaType.APPLICATION_JSON)
@Api(value = "/people")
public class PersonService {

  @GET
  @Produces(MediaType.APPLICATION_JSON)
  @Path("/person/{id}/")
  @ApiOperation(
      value = "api value",
      notes = "api notes "
  )
  public Response getPerson(@PathParam("id") String personId) throws Exception {
      PersonResponse p = new PersonResponse();
      return Response.ok(p).build();
  }
}

And finally, a simple POJO PersonResponse:
public class PersonResponse {
    private String name;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}


Q:

md-input-container value can be changed by scrollng when it has value and focused

<md-input-container ng-if="vm.sellerActive" class="less-margin-input-container">
            price
            <input id="Price"
                   name="Price"
                   type="number"
                   ng-model="vm.price"
                   ng-pattern="vm.patternNegative"
                   required>

                    required

                    negative

        </md-input-container>

enter image description here
how can i delete those arrows because of those arrows, row can be scrollable when focus on it?

normally it is like this

When i click the row, arrows come. When i click wheel of mouse, the value is increasing or decreasing

A:

What you are experiencing is default behavior of number input. The number value will increase / decrease depending on the scroll position.
Update
I've created a directive for disabling mouse scroll and arrow keys(up/down) on input type number.
Usage:
<input type="number" disable-it mousewheel="true" arrowkeys="true">

disable-it : directive
mousewheel : disable scroll
arrowkeys  : disable up/down arrows

(function() {
  'use strict';
  angular
    .module('myApp', []);

  angular
    .module('myApp')
    .controller('MyController', MyController)
    .directive('disableIt', disableIt);

  MyController.$inject = [];

  function MyController() {

  }

  disableIt.$inject = [];

  function disableIt() {
    var DDO = {
      restrict: 'A',
      link: function(scope, element, attrs) {
        // Firefox: DOMMouseScroll
        // IE9, Chrome, Safari, Opera: mousewheel
        if (attrs.mousewheel && attrs.arrowkeys) {
          handleEvent('DOMMouseScroll mousewheel keydown');
        } else if (attrs.mousewheel && !attrs.arrowkeys) {
          handleEvent('DOMMouseScroll mousewheel');
          handleEvent('keydown');
        } else {
          throw new Error("Please give the boolean values to  mousewheel, arrowkeys properties");
        }

        function handleEvent(ev) {
          var code = null;
          element.on('focus', function(event) {
            element.on(ev, function(e) {
              if (e.type==='keydown') {
                code = (e.keyCode ? e.keyCode : e.which);
                if (code === 38 || code === 40) {
                  e.preventDefault();
                }
              } else {
                e.preventDefault();
              }

            });
          }).on('blur', function(e) {
            element.off(ev);
          });
        }

      }
    };

    return DDO;
  }
}());
input[type=number] {
  -moz-appearance: textfield;
}

input[type=number]::-webkit-inner-spin-button,
input[type=number]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

    <input id="Price" name="Price" type="number" disable-it mousewheel="true" ng-model="MC.num" arrowkeys="true">{{MC.num}}

If you want to just hide the arrow icons in <input type="number"> you can use the below CSS style sheets:
input[type='number'] {
    -moz-appearance:textfield;
}

input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
    -webkit-appearance: none;
}

You can't disable the scrolling behavior, however since you are using ng-pattern you can use plain <input type="text"> along with your default validations.


Q:

What happens to electrons when they are detected?

I know photons are absorbed and annihilated when they are detected but
a) when electrons are detected, are they absorbed and annihilated? and
b) if electrons are ever absorbed, what happens when they are? Are photons omitted?

A:

You have to distinguish the behavior of fermions and bosons. They have different spin quantum numbers, half integer for fermions, integer for bosons.
There is no conservation law for bosons, whereas fermion number is conserved.

Besides this spin characteristic fermions have another specific property: they possess conserved baryon or lepton quantum numbers. Therefore what is usually referred as the spin-statistics relation is in fact a spin-statistics-quantum number relation.2
In contrast to bosons, as a consequence of the Pauli principle only one fermion can occupy a particular quantum state at any given time. If multiple fermions have the same spatial probability distribution, then at least one property of each fermion, such as its spin, must be different. Fermions are usually associated with matter, whereas bosons are generally force carrier particles; although in the current state of particle physics the distinction between the two concepts is unclear.

The electrons are fermions and cannot just disappear the way the photon, a boson, does just balancing energy and momentum. The other quantum numbers have to be balanced also. Thus depending on the interaction under observation, an electron will scatter off the field of molecules and atoms and other free electrons, radiating photons, until its energy is low enough to be bound in a molecular or atomic state, even increasing the molecule's charge. If it is unlucky enough to meet a positron, maybe in the electron positron cloud at the center of our galaxy, it will annihilate to two photons, because the quantum numbers will be balanced.
In vacuum it will just stick around if it has close to zero kinetic energy and is away from molecular surfaces.
Detection, "here is an electron" happens in a detector where a signal is given that an electron has been captured , as a dot on a screen for example, or by the ionizing radiation it leaves in a chamber until its energy degrades enough to be captured by a molecular level.


Q:

Can GetTypeInfo ever return null?

I am rewriting some code (targeting .NET 4.5.2. currently) that uses reflection to compile for .NET Standard 1.4. I therefore need to use GetTypeInfo() on a Type at many places.
In order to handle the edge cases correctly, my question is, can GetTypeInfo() ever return null? The documentation (https://msdn.microsoft.com/en-us/library/system.reflection.introspectionextensions.gettypeinfo(v=vs.110).aspx) is silent about this.
When I open a source of GetTypeInfo() from a standard .NET 4.5.2 project, I get:
public static class IntrospectionExtensions
{
    public static TypeInfo GetTypeInfo(this Type type){
        if(type == null){
            throw new ArgumentNullException("type");
        }
        var rcType=(IReflectableType)type;
        if(rcType==null){
            return null;
        }else{
            return rcType.GetTypeInfo();
        }
    }
}

That is still confusing. There is a code branch that returns null when '(IReflectableType)type' is null, but why? - the 'type' itself is checked against null before, and an exception is thrown when it is null, therefore I cannot see how 'rcType' can ever be null (mind you, this is not an 'as' operator, it is a straight typecast).
In a good tradition, the documentation on IReflectableType.GetTypeInfo (, https://msdn.microsoft.com/en-us/library/system.reflection.ireflectabletype.gettypeinfo(v=vs.110).aspx ) is also silent about the possibility of a null outcome.
A code that uses reflection needs to use GetTypeInfo at many places, and if a null results is allowed, it would therefore require to have a null check and a corresponding action at every such place. I have checked other people's code (including Microsoft's own example at https://msdn.microsoft.com/en-us/library/system.reflection.typeinfo%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396 ) and developers seem to be treating it as a null result was not possible. Is that correct?

A:

GetTypeInfo() is never supposed to return null.
See the new code in .NET Core and the comment that Microsoft people who ported this code left.


Q:

HTML5 canvas getPixel

I was create one scribbling application in HTML5(using canvas).I want save current work and retrieve that(like a file) also do modification later.How can i do that.
Any help would be appreciable.

A:

Take a look at Canvas2Image, it seems to support PNG, JPEG and BMP.


Q:

Example of a fictional story without any characters (the story being 1000+ words)

Guessing that there is no such example, but if there is, I'm very interested in knowing about it.
Just as a short example, just to make it clear it's possible; the example is not intended to be a work of art, but a proof of concept: "The sun set in the sky, but just beneath the ocean's surface, a volcano was slowly working it's way to the light of the next day. In the morning, waves crashed against the rising lava flows."
UPDATE:
Thanks to all who have commented, to clarify the intent of the question, it's an attempt to understand the nature of characters by removing them. My hope is that in doing so, my understanding of characters and their function will grow in some way.

A:

It is possible to have a story without character - that is living beings that have thought processes and some amount of intelligence. This would include people, animals, aliens, robots, etc. There are two types of characters - flat and round. Flat characters are generally those that are background characters that don't evolve or change throughout the piece. Round characters will evolve and develop at the story goes on.
It is not, however, possible to have a story without a subject. There are no characters in your example, but there are subjects - the sun, the volcano, the waves. A story's subject can be a character, but it doesn't have to be. The subject can be an inanimate object such as a house or a planet.

A:

Unfortunately, I can't think of any stories that follow your strict requirement on excluding anything that "is able to reproduce".
The closest I could come is Ray Bradbury's short story, "There Will Come Soft Rains" (note: link goes to a PDF file). Unfortunately, there are some animals in it, and humans are referred to. Also, as Lynn noted regarding the sun, you could argue that the house is a character.
The question does arise, however: with absolutely no characters, or reference to living things, what story is there to tell? There would be no room for character development, and I can't imagine much conflict arising from such a story, either.

A:

There's certainly a fair number of science-fiction and fantasy stories that describe a world, a society, or some other concept, without relying on individual characters. Talking about a people, but not about anyone in particular.
Similarly, a lot of Jorge Luis Borges stories are about describing a fantastical concept -  "The Library of Babel" and "The Babylon Lottery" spring to mind immediately. I think "Library" might possibly have a narrator, but it might as well not have.
I'd say this type of story has no characters, because it has no actors, nobody individual we're focusing on. But there is a nebulous "they" - "the people," "it was decided," etc., - that moves the story forward; you can't point to any particular character, but there are people somewhere in the picture.


Q:

Animate layout on different activities on android 4.4(kitkat) and higher

Now this specific page does describe a way to animate between layouts of different activities, but the problem is that the API is only supported for android 5.0 and higher, so I'd like to know what are the ways in which animation(like transition or any other type of fade/slide in etc.) could be done for layouts in two different activities.

A:

You can't set transitions on your theme prior to Lollipop version but you can still use animations programmatically.
Here’s an example with animations that slide the new activity in when first created, and the opposite movement when you press the back button.
left_in.xml
<set>

    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="-100%"
               android:toXDelta="0"
               android:interpolator="@android:anim/decelerate_interpolator"
               android:duration="500"/> //in milliseconds
</set>

right_in.xml
<set>

    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="100%"
               android:toXDelta="0"
               android:interpolator="@android:anim/decelerate_interpolator"
               android:duration="500"/>
</set>

left_out.xml
<set>

    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="0"
               android:toXDelta="-100%"
               android:interpolator="@android:anim/decelerate_interpolator"
               android:duration="500"/>
</set>

right_out.xml
<set>

    <translate xmlns:android="http://schemas.android.com/apk/res/android"
               android:fromXDelta="0"
               android:toXDelta="100%"
               android:interpolator="@android:anim/decelerate_interpolator"
               android:duration="500"/>
</set>

On your activities you can call the animations as follows:
On start: overridePendingTransition(R.anim.right_in, R.anim.left_out);
On Back Pressed: overridePendingTransition(R.anim.left_in, R.anim.right_out);
Or any combination of the above.
Note that the first animation on overridePendingTransition is for the incoming activity and the second for the outgoing activity.