text:
Q: Python Profile Pitfalls I am a beginner just starting to profile my code and was confused why the elapsed time given by cProfile was so off from the time given by using time.time().
# Python 2.7.2

import cProfile

def f(n):
    G = (i for i in xrange(n))
    sum = 0
    for i in G:
        sum += i

num = 10**6

cProfile.run('f(num)')

This gives
    1000004 function calls in 2.648 seconds
Yet with time.time(), I get 0.218000173569 seconds
import time

x = time.time()
f(num)
print time.time() - x

From what I have read, I guess this may be because of the overhead of cProfile. Are there any general tips for when cProfile timing is likely to be very off, or ways to get more accurate timing?

A: The point of profiling is to find out what parts of your program are taking the most time, and thus need the most attention.  If 90% of the time is being used by one function, you should be looking there to see how you can make that function more efficient.  It doesn't matter whether the entire run takes 10 seconds or 1000.
Perhaps the most important piece of information the profiler gives you is how many times something is called.  Why this is useful is that it helps you find places where you are calling things unnecessarily often, especially if you have nested loops, or many functions that call other functions.  The profiler helps you track this stuff down.
The profiling overhead is unavoidable, and large.  But it is much easier to let the profiler do what it does than to insert your own timings and print statements all over the place.

A: Note that cProfile gives you CPU time, but Using time.time() gives you elapsed time (which isn't what you want).
maybe you can try using the unix time program.
➜  sandbox  /usr/bin/time -p python profiler.py

real         0.17
user         0.14
sys          0.01

The CPU time should be user+sys


text:
Q: Constructing a group from any set of groups How can we construct a group from any non-empty set of groups that is not in the original set (i.e. not isomorphic to any of its elements)?

A: Given a a set $X$ of groups take a group $G$ s.t. $|G|>|x|$ for all $x\in X$. Then
$G\not\cong x $ for $x\in X$, because there cannot be any bijection $G\to x$, and an isomorphism of groups must always be a bijection.
Only relevant to the previous versions of your question:
Your question needs clarification (without requiring any relation of the group to be constructed with the groups that are given your question is trivially answered). As it is stated now, I can say the following:
A group structure can be defined on any nonempty set. So given any set (whether the elements are groups or not), you can find a group structure on it: If it is finite, use the structure of $\mathbb Z_n$, if countably infinite, the structure of $\mathbb Z$ will do, and for all other cardinalities an application of the Löwenheim-Skolem theorem will give you the existence of the group structure.
(This was an answer pertaining to a part of the original question that was edited out:) Since you might have a finite set of infinite groups you cannot guarantee that the group you construct is isomorphic to one of the elements of your given set.

A: If the given set of groups is the empty set, it is impossible to find a Group that is (isomorphic to) an element of this set.
With the problematic case of the empty et of Groups excluded, the Axiom of Choice allows us to pick an element of any (non-empty) set of groups.

A: Let $G$ be a set of groups and suppose that it is denumerable with $\mathbb{Z}\in G$. So, we can suppose that $G=\{G_n:n\in\omega\}$. Define $+:G\times G\rightarrow G$ such that $+(G_n,G_m)=G_{n+m}$. It's clear that $\langle G,+\rangle$ is a group and $G\simeq\mathbb{Z}$.

A: Since you have a set of groups, the set of their cardinalities is bounded above. Choose a cardinal that is strictly larger than that bound. Now construct a group $G$ whose underlying set has cardinality at least as large as that chosen cardinal (for example the group of permutations of that cardinal). It follows that $G$ is not isomorphic to any of your original groups.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SWF advertisements through VAST Tag not played in JW player I configure Advertisement through VAST tag using jwplayer like.
$(document).ready(function(){
var playerInstance = jwplayer("player1");
playerInstance.setup({
    file: 'https://d150hyw1dtprld.cloudfront.net/videos/HP_VideoTest_NoPostRoll_v2_720p.mp4',
    width: "100%",
    displaytitle: false,
    controls: false,
    primary: 'flash',
    mute:'false',
    autostart: true,
    advertising: {
          client: "vast",
          tag: 'http://ads.adaptv.advertising.com/a/h/DLhbzlB+8BBfoyyx+Qo7i7Bx_Mpt2nNJbie4rwz4DHkL4tzFA61JtQ==?cb=${cachebreaker}&pageUrl=${embeddingPageUrl}&description=${description}&duration=${duration}&id=${id}&keywords=${keywords}&title=${title}&url=${videourl}&eov=eov&width=${width}&height=${height}&videourl=${videourl}&duration=${duration}&br_i=ad&context=${context.homepage}&adap_uid=7924494155751153126'
        }
});
});

The above SWF advertisement not played. only Primary Video (File) only plays. How can i Fix that??

A: It seems like there is a problem with the VAST file representing the advertisement you linked to in your code snippet—when I paste it into Google's VAST Inspector, I get this error:

(4:29:36 PM) Ad error: AdError 901: An unexpected error occurred within the VPAID creative. Refer to the inner error for more info. Caused by: Error: Error: No ad found in ad tag response

In the advertisement, there is a single <MediaFile> tag:
 <MediaFiles>
 <MediaFile delivery="progressive" width="400" height="300" type="application/x-shockwave-flash" apiFramework="VPAID">
 <![CDATA[
http://redir.adap.tv/redir/client/VPAIDClient.swf?adTagUrl=http%3A%2F%2Fads.adaptv.advertising.com%2Fa%2Fh%2FDLhbzlB%2B8BBfoyyx%2BQo7i7Bx_Mpt2nNJbie4rwz4DHkL4tzFA61JtQ%3D%3D%3Fcb%3D%24%7Bcachebreaker%7D%26pageUrl%3D%24%7BembeddingPageUrl%7D%26description%3D%24%7Bdescription%7D%26duration%3D%24%7Bduration%7D%26id%3D%24%7Bid%7D%26keywords%3D%24%7Bkeywords%7D%26title%3D%24%7Btitle%7D%26url%3D%24%7Bvideourl%7D%26eov%3Deov%26width%3D%24%7Bwidth%7D%26height%3D%24%7Bheight%7D%26videourl%3D%24%7Bvideourl%7D%26duration%3D%24%7Bduration%7D%26br_i%3Dad%26context%3D%24%7Bcontext.homepage%7D%26adap_uid%3D7924494155751153126%26a.cluster%3D0%26a.pvt%3D0&companionId=&cpmPassback=&placementId=266469&orgId=5047&injectCompanionDummy=&pauseOnClick=&d.vw=&d.app=
]]>
</MediaFile>
</MediaFiles>

The query param adTagUrl has this as its value:
http://ads.adaptv.advertising.com/a/h/DLhbzlB+8BBfoyyx+Qo7i7Bx_Mpt2nNJbie4rwz4DHkL4tzFA61JtQ==?cb=${cachebreaker}&pageUrl=${embeddingPageUrl}&description=${description}&duration=${duration}&id=${id}&keywords=${keywords}&title=${title}&url=${videourl}&eov=eov&width=${width}&height=${height}&videourl=${videourl}&duration=${duration}&br_i=ad&context=${context.homepage}&adap_uid=7924494155751153126&a.cluster=0&a.pvt=0&companionId=&cpmPassback=&placementId=266469&orgId=5047&injectCompanionDummy=&pauseOnClick=&d.vw=&d.app=

which seems like it's circling back to the same VAST file as the one you linked to. So it really just seems like you have a bad VAST tag here.


text:
Q: How to make a window always stay on top in .Net? I have a C# winforms app that runs a macro in another program.  The other program will continually pop up windows and generally make things look, for lack of a better word, crazy.  I want to implement a cancel button that will stop the process from running, but I cannot seem to get the window to stay on top.  How do I do this in C#?
Edit:  I have tried TopMost = true; , but the other program keeps popping up its own windows over top.  Is there a way to send my window to the top every n milliseconds?
Edit: The way I solved this was by adding a system tray icon that will cancel the process by double-clicking on it.  The system tray icon does no get covered up.  Thank you to all who responded.  I read the article on why there is not a 'super-on-top' window... it logically does not work.

A: Set the form's .TopMost property to true.
You probably don't want to leave it this way all the time: set it when your external process starts and put it back when it finishes.

A: I was searching to make my WinForms application "Always on Top" but setting "TopMost" did not do anything for me. I knew it was possible because WinAmp does this (along with a host of other applications).
What I did was make a call to "user32.dll." I had no qualms about doing so and it works great. It's an option, anyway.
First, import the following namespace:
using System.Runtime.InteropServices;

Add a few variables to your class declaration:
private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
private const UInt32 SWP_NOSIZE = 0x0001;
private const UInt32 SWP_NOMOVE = 0x0002;
private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;

Add prototype for user32.dll function:
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

Then in your code (I added the call in Form_Load()), add the call:
SetWindowPos(this.Handle, HWND_TOPMOST, 0, 0, 0, 0, TOPMOST_FLAGS);

[Reference][1]
[1]: http://www.c-sharpcorner.com/uploadfile/kirtan007/make-form-stay-always-on-top-of-every-window/

A: The way i solved this was by making a system tray icon that had a cancel option.

A: Why not making your form a dialogue box:
myForm.ShowDialog();

A: The following code makes the window always stay on top as well as make it frameless.
using System;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace StayOnTop
{
    public partial class Form1 : Form
    {
        private static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
        private const UInt32 SWP_NOSIZE = 0x0001;
        private const UInt32 SWP_NOMOVE = 0x0002;
        private const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

        public Form1()
        {
            InitializeComponent();
            FormBorderStyle = FormBorderStyle.None;
            TopMost = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SetWindowPos(this.Handle, HWND_TOPMOST, 100, 100, 300, 300, TOPMOST_FLAGS);
        }

        protected override void WndProc(ref Message m)
        {
            const int RESIZE_HANDLE_SIZE = 10;

            switch (m.Msg)
            {
                case 0x0084/*NCHITTEST*/ :
                    base.WndProc(ref m);

                    if ((int)m.Result == 0x01/*HTCLIENT*/)
                    {
                        Point screenPoint = new Point(m.LParam.ToInt32());
                        Point clientPoint = this.PointToClient(screenPoint);
                        if (clientPoint.Y <= RESIZE_HANDLE_SIZE)
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)13/*HTTOPLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)12/*HTTOP*/ ;
                            else
                                m.Result = (IntPtr)14/*HTTOPRIGHT*/ ;
                        }
                        else if (clientPoint.Y <= (Size.Height - RESIZE_HANDLE_SIZE))
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)10/*HTLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)2/*HTCAPTION*/ ;
                            else
                                m.Result = (IntPtr)11/*HTRIGHT*/ ;
                        }
                        else
                        {
                            if (clientPoint.X <= RESIZE_HANDLE_SIZE)
                                m.Result = (IntPtr)16/*HTBOTTOMLEFT*/ ;
                            else if (clientPoint.X < (Size.Width - RESIZE_HANDLE_SIZE))
                                m.Result = (IntPtr)15/*HTBOTTOM*/ ;
                            else
                                m.Result = (IntPtr)17/*HTBOTTOMRIGHT*/ ;
                        }
                    }
                    return;
            }
            base.WndProc(ref m);
        }

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                cp.Style |= 0x20000; // <--- use 0x20000
                return cp;
            }
        }
    }
}

A: What is the other application you are trying to suppress the visibility of? Have you investigated other ways of achieving your desired effect? Please do so before subjecting your users to such rogue behaviour as you are describing: what you are trying to do sound rather like what certain naughty sites do with browser windows...
At least try to adhere to the rule of Least Surprise. Users expect to be able to determine the z-order of most applications themselves. You don't know what is most important to them, so if you change anything, you should focus on pushing the other application behind everything rather than promoting your own.
This is of course trickier, since Windows doesn't have a particularly sophisticated window manager. Two approaches suggest themselves:

*

*enumerating top-level windows
and checking which process they
belong to, dropping their
z-order if so. (I'm not sure if
there are framework methods for
these WinAPI functions.)

*Fiddling with child process permissions to prevent it from accessing the desktop... but I wouldn't try this until the othe approach failed, as the child process might end up in a zombie state while requiring user interaction.

A: Here is the SetForegroundWindow equivalent:
form.Activate();

I have seen people doing weird things like:
this.TopMost = true;
this.Focus();
this.BringToFront();
this.TopMost = false;

http://blog.jorgearimany.com/2010/10/win32-setforegroundwindow-equivalent-in.html

A: If by "going crazy" you mean that each window keeps stealing focus from the other, TopMost will not solve the problem.
Instead, try:
CalledForm.Owner = CallerForm;
CalledForm.Show();

This will show the 'child' form without it stealing focus. The child form will also stay on top of its parent even if the parent is activated or focused. This code only works easily if you've created an instance of the child form from within the owner form. Otherwise, you might have to set the owner using the API.

A: Form.TopMost will work unless the other program is creating topmost windows.
There is no way to create a window that is not covered by new topmost windows of another process. Raymond Chen explained why.

A: Set Form.TopMost

A: I had a momentary 5 minute lapse and I forgot to specify the form in full like this:
  myformName.ActiveForm.TopMost = true;

But what I really wanted was THIS!
  this.TopMost = true;

A: I know this is old, but I did not see this response.
In the window (xaml) add:
Deactivated="Window_Deactivated"

In the code behind for Window_Deactivated:
private void Window_Deactivated(object sender, EventArgs e)
    {
        Window window = (Window)sender;
        window.Activate();
    }

This will keep your window on top.

A: Based on clamum's answer, and  Kevin Vuilleumier's comment about the other flag responsible for the behavior, I made this toggle that switches between on-top and not on-top with a button press.
private void button1_Click(object sender, EventArgs e)
    {
        if (on)
        {
            button1.Text = "yes on top";
            IntPtr HwndTopmost = new IntPtr(-1);
            SetWindowPos(this.Handle, HwndTopmost, 0, 0, 0, 0, TopmostFlags);
            on = false;
        }
        else
        {
            button1.Text = "not on top";
            IntPtr HwndTopmost = new IntPtr(-2);
            SetWindowPos(this.Handle, HwndTopmost, 0, 0, 0, 0, TopmostFlags);
            on = true;
        }
    }

A: I did something i little bit differnt kinda found it much easier
so first on Form Load
private void Form1_Load(object sender, EventArgs e)
{
   this.Shown += new EventHandler(Form1_Shown);//let your form show up here
}

private void Form1_Shown(Object sender, EventArgs e)
{
  Form1.ActiveForm.TopMost = true //and then do your TopMost logic
}


text:
Q: Does an undefined symbol from a vtable imply an error between interface and implementation? Does this kind of error implicate an error between an interface and its implementation?
Undefined symbols for architecture i386:
  "MyClass::ChangeManager::GetChanges(
       MyClass::ObjectId,
       MyClass::IChangeManager::Changes&,
       bool)"
  , referenced from:
  vtable for MyClass::ChangeManager in libMobileUtils.a(ChangeManager.o)

A: No. That simply means that when the implementation emitted the vtable, it chose to place that function in it. It's just a plain old undefined function.


text:
Q: How to load a text file inside a JSON object within a Javascript function I have an autocomplete function :-
  $(document).ready(function () {
  $('input.autocomplete').autocomplete({

    data: {

The data JSON object will be responsible for giving the associated autocomplete values, the JSON key will be the autocomplete suggestions, and the JSON value will be null.
I don't want to manually enter values inside this JSON data like:-
data:{
    "Chocolate": null,
    "Cake": null,
    "Icecream": null,
    "Pudding": null }

Instead, I want to fetch the JSON values from a text file, which will have these contents, so that I can just load the text file for this data JSON object, instead of having to manually enter it.
So, the list.txt file will have:-
           "Chocolate": null,
            "Cake": null,
            "Icecream": null,
            "Pudding": null,
             "Cream:null

And I want to call this list.txt file inside JSON object data, something like:-
data: {
$.get('list.txt') }

How can I achieve this?

A: Try the below code.
Read data from text file with ajax call and convert it into json object.
It will work, but slight modification is needed with your text file as follows.
{
"Chocolate": "null",
"Cake": "null",
"Icecream": "null",
"Cream":"null"
}

And your code will be as follows.
$(document).ready(function() {
    $.ajax({
        url : "list.txt",
        dataType: "text",
        success : function (data) {
            $(".text").html(data);
            var jsonData = JSON.parse(data);
        }
    });
});

If you don't want to modify the existing text file the below code will work.
$(document).ready(function() {
        $.ajax({
            url : "list.txt",
            dataType: "text",
            success : function (data) {
                $(".text").html(data);
                var jsonData = JSON.parse("{"+data+"}");

                 $('input.autocomplete').autocomplete({
                     data:jsonData
                 });  //to initialize autocomplete
            }
        });
    });


text:
Q: Увеличить объем обрабатываемых файлов на сервере node js цикл на сервере node js, перестает перебирать JSON файл,
server.use(bodyParser.json({ limit: '1024mb', parameterLimit: 10000000,extended: true }))
server.use(bodyParser.urlencoded({ limit: '2048mb',parameterLimit: 10000000, extended: true }))

Пытался сделать через лимиты, но они тоже не помогают, или же лимиты слишком малы, что делать с этим делом??
server.post("/save", (req, res) => {
    const mapsStorage = path.join(publicPath, 'maps');
    const createDirName = req.query.locname;
    const dir = path.join(mapsStorage, createDirName);

    const map = req.body;

    !fs.existsSync(dir) && fs.mkdirSync(dir);
    !fs.existsSync(path.join(dir,"assets")) && fs.mkdirSync(path.join(dir,"assets"));
    fs.writeFileSync(dir+"/map.json", JSON.stringify(map));
    for(let piece in map){
        if(piece !== "locSize"){
            map[piece].map(item=>{
                let imageName = item.texture.match(/([a-z]+\/){3}(.+\.png)/i)[2];
                if(!fs.existsSync(path.join(dir,`assets/${imageName}`))){
                    console.log(path.join(dir,`assets/${imageName}`));
                    fs.copyFileSync(path.join(publicPath,item.texture), path.join(dir,`assets/${imageName}`));
                }
            });
        }
    }
});


text:
Q: what can cause a timeout in Entity Framework I have other queries working with the same connectionstring; the server is returning data on those calls.
some settings:
Connection.ConnectionTimeout = 3600 (in debugger)
DB timeout is set to 0
<add
   name="StuffEntities"
   connectionString="metadata=res://*/DataModel.Stuff.csdl|res://*/DataModel.Stuff.ssdl|res://*/DataModel.Stuff.msl;provider=System.Data.SqlClient;provider connection string="data source=10.0.1.Stuff;initial catalog=Stuff;persist security info=True;user id=Stuff;password=Stuff;multipleactiveresultsets=True;App=EntityFramework;Connect Timeout=3600""
   providerName="System.Data.EntityClient" />

outer Exception

{"An error occurred while executing the command definition. See the
  inner exception for details."}

Inner Exception

{"Timeout expired.  The timeout period elapsed prior to completion of
  the operation or the server is not responding."} error code :
  -2146232060

looks like it happens in 30 seconds.
I have no clue what is overriding my settings.

A: context.CommandTimeout = 3600;

forgot to change that one.
silly me.


text:
Q: Deleting contacts from mac contacts application with no Phone number Is it possible to delete contacts from mac contacts application which have no phone no? Or export only those contacts which have a contact?
Thanks.

A: In Contacts or Address Book, you can make a Smart Group (File --> New Smart Group...) that has the criteria Phone is not set which will collect all the contacts without phone numbers. Then you can view the members of this group and delete those contacts (or do whatever you want with them).


text:
Q: Return List which element belongs to up until the element position I wanna build a predicate that given a List of lists and a Element with coordinates X, checks if X belong to any list inside that main List, and if it belongs to any list, returns the ReturnList as a list with elements up until the position of where the Element X is found.
So for example, given;
?-checklist((3,4),[[(1,3), (1,2), (1,1)],[(1,4), (2,4), (3,4), (4,4)]], ReturnList)

returns
ReturnList = [(1,4), (2,4), (3,4)]

I'm trying to implement this and so far I have
get_list([],_,[]).
get_list([List], Element, ReturnList):-
  member(List, Element),
  get_list(List|Rest, Element, List).

But It's one of my first prolog programs and I'm finding it difficult to grasp the logic

A: My solution (with comments) using Prolog builtins member/2 and append/3:
checklist(Elem, List, ReturnList) :-
    member(SubList, List),          % SubList is contained in List
    member(Elem, SubList),          % Elem is contained in SubList
    append(ReturnList, _, SubList), % ReturnList is a prefix of SubList
    append(_, [Elem], ReturnList).  % Elem is the last element of ReturnList

Test:
?- checklist((3,4),[[(1,3), (1,2), (1,1)],[(1,4), (2,4), (3,4), (4,4)]], ReturnList).
ReturnList = [(1, 4),  (2, 4),  (3, 4)] ;
false.


text:
Q: psql.exe - password authentication failed in windows I'm a noob in PostgreSQL. I installed ver 9.2 on windows7. During installation it asked for password and i entered it.
Now whenever i run d:\tools\PostgreSQL9.2\bin\psql.exe it asks for password. When i enter the password it doesn't accept and
it shows "password authentication failed for user "user1". I have re-installed twice already. Also i tried entering my system
password.
I'm trying to get the below command to work
psql.exe -f db/codedb.sql development

What should i do to get this working ?

A: Try setting the user name when connecting.
psql.exe -U username -d dbname -f somefile.sql

You've probably set up the default "postgres" user during installation. Not sure if you've created any others.
To add other users and databases just connect to as postgres to the postgres database and do something like:
CREATE USER myuser WITH ENCRYPTED PASSWORD 'secret';
CREATE DATABASE mydb OWNER myuser;

If your machine is secure you might also like to set up a password file

A: Here is the simple solution for installation Postgresql without getting errors(cluster errors and authentication errors),i have followed below steps and i got installed postgresql sucessfully

*

*create new user in windows from controlpanel-->user accounts

*After logged into new user(whic u hve created) copy postrgresql(.exe) application into any directory(other than 'C') and click on the application to install(dont forget to change the installation directory to which u have copied the application file above).

*after completion of installaion change below configurations in postgresql.conf and pg_hba.cof
add like below in your postgresql.conf
listen_addresses = '*'

add like below in your pg_hba.cof
# IPv4 local connections:
host     all     all     127.0.0.1/32    trust
# IPv6 local connections:
host     all     all     ::1/128     trust
# Allow replication connections from localhost, by a user with the
# replication privilege.
# host   sameuser    postgres    127.0.0.1/32    trust
#host    replication     postgres        ::1/128                 md5

A: change  "trust" instead of "md5" in the pg_hba.conf to connect to the database  and change your password.
    --------------------configuration in pg_hba.conf---------------
    local   all         all                               trust
    local   all         postgres                          trust
    host    all         all         ::1/128               trust


text:
Q: Apache POI, .getRuns() not returning all Runs I am developing a software, which is reading in a Word document (XWPF), changing the grammar according to the prior configuration of the user, and writing the modified text back into the document.
To achieve this, I am using Apache POI (3.10). In most cases it works like expected, but there are some rare cases, where it doesn't.
To be more specific, the code is going through the whole document, paragraph by paragraph. My code is changing the content of the paragraphs by setting the text of their runs.
To have a better picture of what I am talking about:
    XWPFDocument oldDoc = document;
    Iterator<XWPFParagraph> iterator = document.getParagraphsIterator();
    int length = title.length();
    int counter = 0;

    while(iterator.hasNext())
    {
        XWPFParagraph paragraph = iterator.next();
        List<XWPFRun> runs = paragraph.getRuns();
        for(int i = 0; i < runs.size(); i++)
        {
            String text = runs.get(i).toString();
            if(text.contains(title)) {
                runs.get(i).setText(StringFunctions.fromMultiFemaleToSingleMale(text, title, length), 0);
            }
        }

        document.setParagraph(paragraph, counter);
        counter++;
    }

AS you can see, I take every run of a paragraph, and throw it into my transformation method, and overwrite the text of the run. There is no problem at this point (I think).
My problem is, that there are two or three sentences (or paragraphs), which do not return the whole text in their runs. Below is an example.
paragraph.getText() returns:
Alle Beteiligten weisen daher den Notar gem. § 53 BeurkG an, die Umschreibung gemäß dieser Vollmacht durch Eigenurkunde erst zu veranlassen, nachdem der Verkäufer den Eingang des geschuldeten Betrages originalschriftlich bestätigt haben oder hilfsweise die Käuferinnen die Zahlung des vereinbarten Kaufpreises (jeweils ohne Zinsen) durch Bankbestätigung nachgewiesen hat.
while the concatenation of paragraph.getRuns() returns: Alle Beteiligten weisen daher den Notar gem. § 53 BeurkG an, die Umschreibung gemäß dieser Vollmacht durch Eigenurkunde erst zu veranlassen, nachdem die Verkäufer den Eingang des geschuldeten Betrages originalschriftlich bestätigt haben oder hilfsweise die Käuferinnen die Zahlung des vereinbarten Kaufpreises (jeweils ohne Zinsen) durch
You can see here, that the last three words are missing. Since I am accessing the runs, the last part will just be ignored and never transformed by my method. But in this case I need to transform the last word to make it grammatically correct.
Has anyone experienced something similar?
I tried to find a workaround, but I didn't find one.
One of my coworkers talked with me about that and mentioned that he experienced something similar, and that sometimes there is something like a flaw in that XML-like structure of Word-documents, with which Word can still work with, but POI not so well. This does not sound very unlikely, since the document, which I am using, was once the old Word format (.doc), and was saved as a .docx with Word 2007.

A: Still observable in 3.17.
If my word document I have such misses:
Mr. Fancy Employee
Big Firm Manager
Nice Street 1
1234 Best City
                            McFly Martin
                            301 Clontarf Road
3 - Dublin Irland

Order Confirmation
Dear McFly Martin,
We confirm to having received your order (Vote ID: ${name}) on the 23.08.2014 18:23. Your payment amounts to £300.0.

Best regards,

Fancy Employee
Big Firm Manager

but I have one things missed via wordExtractor.getText()
Mr. Fancy Employee
Big Firm Manager
Nice Street 1
1234 Best City

 -

Order Confirmation
Dear  ,
We confirm to having received your order (Vote ID: ) on the . Your payment amounts to £.

Best regards,

Fancy Employee
Big Firm Manager

and another missed on liting all of getRuns()
Mr. Fancy Employee
Big Firm Manager
Nice Street 1
1234 Best City
null

null
 -

null
null
Order Confirmation
Dear

,
We confirm to having received your order (
Vote
ID:
)
 on the
. Your payment amounts to
 £
.
null
null
null
Best regards,
null
null
Fancy Employee
Big Firm Manager


text:
Q: What other sites are using the Stack Overflow engine?
Possible Duplicate:
What Stack Exchange sites are up?

I just saw Math Overflow. What other sites are based on StackOverflow?

A: See this link, but beware, they're all going away soon, as per this link.
Also, see the bottom of the page for a few more computer related sites.


text:
Q: Gnuplot for loop with continous variables I have a plot with many objects and labels. So I wanted to simplify the srcipt using loops. But I don't know how to adress the variables. I define the variables as followed
V1 = 10
V2 = 20
V3 = 23
...
LABEL1 = a
LABEL2 = b
...

The loop should look something like that
set for [i=1:15] label i at V(i),y_label LABEL(i)

This notation leads to errors compiling the script. Is it possiple at all to define such a loop in gnuplot? If so how can I do it?
Thanks for your help!

A: You can define a function which formats the label-definition as string and use a do loop to evaluate the strings:
y_label = 0
V1 = 10
V2 = 20
V3 = 23
LABEL1 = "a"
LABEL2 = "b"
LABEL3 = "c"

do for [i=1:3] {
   eval(sprintf('set label %d at V%d,y_label LABEL%d', i, i, i))
}

Alternatively, you can use two string with whitespace-separated words for the iteration:
V = "10 20 23"
LABEL = "a b c"
set for [i=1:words(V)] label i at word(V, i),y_label word(LABEL, i)

Note, that gnuplot 5.0 also has some limited support to use quote marks to hold several words together as one item:
V = "10 20 25"
LABEL = "'first label' 'second label' 'third one'"
set for [i=1:words(V)] label i at word(V, i),y_label word(LABEL, i)


text:
Q: How to corrupt a file without changing attributes for integrity testing? I'm trying to create a process for comparing two folders that should contain exactly the same files. Would like to be able to modify a file's content without changing the attributes as if the file was accidentally corrupted. Any way to accomplish this?

A: Use a disk editing tool to find some blocks for the file in question, and change their contents. Google a phrase like "disk hex editor" to find one. Now your file is corrupt, and you did not use the OS API calls which would have also updated the time stamps on the file.

A: Use PowerShell's Get-FileHash function.  It will compute the hash based on the contents of the file, not the time stamps.  Then you just compare the hash of FileA to FileB.  If the contents are the same then they should be the same hash.    This way you don't have to worry about edited the file to be different and comparing time stamp data.
Source:  https://msdn.microsoft.com/en-us/powershell/reference/6/microsoft.powershell.utility/get-filehash

The Get-FileHash cmdlet computes the hash value for a file by using a
  specified hash algorithm. A hash value is a unique value that
  corresponds to the content of the file. Rather than identifying the
  contents of a file by its file name, extension, or other designation,
  a hash assigns a unique value to the contents of a file. File names
  and extensions can be changed without altering the content of the
  file, and without changing the hash value. Similarly, the file's
  content can be changed without changing the name or extension.
  However, changing even a single character in the contents of a file
  changes the hash value of the file.
The purpose of hash values is to provide a cryptographically-secure
  way to verify that the contents of a file have not been changed. While
  some hash algorithms, including MD5 and SHA1, are no longer considered
  secure against attack, the goal of a secure hash algorithm is to
  render it impossible to change the contents of a file-either by
  accident, or by malicious or unauthorized attempt-and maintain the
  same hash value. You can also use hash values to determine if two
  different files have exactly the same content. If the hash values of
  two files are identical, the contents of the files are also identical.
By default, the Get-FileHash cmdlet uses the SHA256 algorithm,
  although any hash algorithm that is supported by the target operating
  system can be used.


text:
Q: Вывод сообщения на консоль в проектах C++/CLI Cоздал CLR проект на C++ В Visual Studio 2017, и есть там какие нибудь функции чтобы выводить на экран сообщение или что то другое?

A: Вывод сообщения на консоль в CLR
Console::WriteLine("text");

Для паузы после окончания можно использовать
Console::ReadLine();

Вообще CLR очень похож на C#


text:
Q: Magento 2 How add to custom attribute placeholder only on create account page? I cannot figure out how I can add placeholder for some custom attribute on create account page.
In this file: view/frontend/templates/customer/form/register.phtml i see some code which output html for my attribute:
    <?php $customerAttributes = $block->getChildBlock('customer_form_user_attributes');?>
    <?php if ($customerAttributes): ?>
        <?php $customerAttributes->setObject($block->getFormData())
            ->setEntityType('customer')
            ->setShowContainer(false);?>
        <?php $block->restoreSessionData($customerAttributes->getMetadataForm());?>
        <?= $customerAttributes->toHtml() ?>
    <?php endif;?>

But how to add the one I need placeholder for my custom attribute I cannot think of and track how this can be done.
Please, help me!

A: Show customer attributes in the customer registration form
For showing customer attributes on the registration page, we need to do the following steps:
First, we will add our phtml files to 'form.additional.info' reference name using

Module/CustomerAttribute/view/frontend/layout/customer_account_create.xml

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     layout="1column"
     xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
   <body>
       <referenceContainer name="form.additional.info">
           <block class="Magento\Framework\View\Element\Template"
                  name="phone_number"
                  template="Magenest_CustomerAttribute::extra_field.phtml"/>
       </referenceContainer>
   </body>
</page>


text:
Q: Guitar effect dry through circuit / wet dry mix? I'm working on a digital guitar effect pedal, but wanted to implement a "dry through" circuit so that I could mix the digitally effected/wet signal with the original unaffected/dry signal at the output. This might be a simply be input buffer and summing amp at output, but I might be totally wrong.
I'm struggling with a search term for that which is giving me any useful results, so thought I'd ask here. I think there might be a lot of input/output impedance issues in replies and that's a dark art to me. I think generally guitar effects pedals try to have a high input impedance and a low output impedance, so that maximum signal voltage is transferred to the following stage.
So I thought as I'm splitting the signal, at the input, that I should use an op amp, (maybe you can use an BJT transistor), to 'buffer' the input signal and give the input impedance which the guitar is expecting. After that buffering Amp I can split the signal into two paths. One (dry) would go directly to a summing amp at the output, whilst the other (wet) signal would go through the digital signal path to the summing amp at the output.
I think I'd need a dual gang potentiometer at the output to effect the mix ratio, but that's about it. I don't want to get into phase issues but I guess that might be inevitable.
So in short buffing amp at the input and a summing amp at the output, with a dual gang pot for mix ratio. All the time naively avoiding figures for impedance and phase issues.
My question is: does that sound about right for a dry through mix circuit or totally wrong?

A: If you have the real estate on the stomp box, I suggest a DPDT phase switch so you can switch between the mix being additive (sum) or subtractive (difference).
You might prefer volume control pots on both sides, that's pretty easy to implement with the op-amps.  Alternately, yeah, one for the mix, but I think maybe a volume pot as well.  For a low-impedence out, a small signal transformer will work wonders even if you hate what it does for the ultrasonics.

A: The most common opamp summing configuration is inverting (with or without some gain).
IF the input buffer also is inverting (with or without some gain),
AND IF the phase shift through the digital section is zero,
THEN the net phase shift through the box is zero for both paths.


text:
Q: Concatenate two cell values if a condition is met I'm trying to see if A1 says black. If it does then in B1 I want to display b followed by the value in C1.
For example, if C1 says 454 and A1 says white, then I would like to display w454 in B1.
Below is my attempt at this:
=IF(A1="black",B1,"b"C1)-IF(A1="white",B1,"w"C1)

A: IF you put this formula in B1, it will display what (I think) you're after:
=IF(A1="black","b","w")&C1

This assumes the value of A1 will only be black or white


text:
Q: Windows SSDP discovery service throttling outgoing SSDP broadcasts I have a Python app that broadcasts SSDP discovery requests. I noticed the devices I'm attempting to discover aren't always responding. Using Wireshark I found that only some of my broadcasts are reaching the wire. After some troubleshooting I isolated the source of the problem to the SSDP Discovery service - if I disable that service then my packet loss goes away. Also, if I use a multicast address other than SSDP (239.255.255.250) the problem also goes away. So it definitely seems SSDP is throttling my outgoing UDP broadcasts. Any idea why this is? Perhaps trying to coalesce broadcasts/limit traffic? I'm using Windows 7. The problem doesn't occur under OSX.
Here is a quick test app demonstrating the packet loss - both instances running on the same system, the sender instance transmits a packet every second and the receive reports any gaps in the test-defined packet number.
def testSend():
    seqNumber = 0
    while True:
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 1)
        sock.sendto(str(seqNumber), ("239.255.255.250", 1900))
        sock.close()
        print("Sent Seq #{:4d}  [{}]".format(seqNumber, time.ctime()))
        seqNumber += 1
        time.sleep(1)

def testReceive():
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sock.bind(("", 1900))
    mreq = struct.pack("4sl", socket.inet_aton("239.255.255.250"), socket.INADDR_ANY)
    sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    expectedSequenceNumber = 0
    while True:
        response = sock.recv(100)
        actualSequenceNumber = int(response)
        if actualSequenceNumber == expectedSequenceNumber:
            print("Good: Received Seq #{:>4s}  [{}]".format(response, time.ctime()))
        else:
            print("Bad: Expected Seq #{}, Got #{} ({} frames dropped) [{}]".format(expectedSequenceNumber, actualSequenceNumber, actualSequenceNumber - expectedSequenceNumber, time.ctime()))
        expectedSequenceNumber = actualSequenceNumber + 1

if sys.argv[1] == 'send':
    testSend()
elif sys.argv[1] == 'receive':
    testReceive()

Output on receiving side:

Good: Received Seq #   0  [Sun Sep 20 11:01:18 2015]
Good: Received Seq #   1  [Sun Sep 20 11:01:19 2015]
Good: Received Seq #   2  [Sun Sep 20 11:01:20 2015]
Good: Received Seq #   3  [Sun Sep 20 11:01:21 2015]
Good: Received Seq #   4  [Sun Sep 20 11:01:22 2015]
Bad: Expected Seq #5, Got #12 (7 frames dropped) [Sun Sep 20 11:01:30 2015]
Good: Received Seq #  13  [Sun Sep 20 11:01:31 2015]
Good: Received Seq #  14  [Sun Sep 20 11:01:32 2015]
Good: Received Seq #  15  [Sun Sep 20 11:01:33 2015]
Good: Received Seq #  16  [Sun Sep 20 11:01:34 2015]
Good: Received Seq #  17  [Sun Sep 20 11:01:35 2015]
Good: Received Seq #  18  [Sun Sep 20 11:01:36 2015]
Good: Received Seq #  19  [Sun Sep 20 11:01:37 2015]
Good: Received Seq #  20  [Sun Sep 20 11:01:38 2015]
Bad: Expected Seq #21, Got #51 (30 frames dropped) [Sun Sep 20 11:02:09 2015]
Good: Received Seq #  52  [Sun Sep 20 11:02:10 2015]
Good: Received Seq #  53  [Sun Sep 20 11:02:11 2015]
Good: Received Seq #  54  [Sun Sep 20 11:02:12 2015]
Good: Received Seq #  55  [Sun Sep 20 11:02:14 2015]
Good: Received Seq #  56  [Sun Sep 20 11:02:15 2015]
Good: Received Seq #  57  [Sun Sep 20 11:02:16 2015]
Good: Received Seq #  58  [Sun Sep 20 11:02:17 2015]
Good: Received Seq #  59  [Sun Sep 20 11:02:18 2015]
Good: Received Seq #  60  [Sun Sep 20 11:02:19 2015]
Bad: Expected Seq #61, Got #71 (10 frames dropped) [Sun Sep 20 11:02:30 2015]
Good: Received Seq #  72  [Sun Sep 20 11:02:31 2015]
Good: Received Seq #  73  [Sun Sep 20 11:02:32 2015]
Good: Received Seq #  74  [Sun Sep 20 11:02:33 2015]
Good: Received Seq #  75  [Sun Sep 20 11:02:34 2015]
Good: Received Seq #  76  [Sun Sep 20 11:02:35 2015]
Good: Received Seq #  77  [Sun Sep 20 11:02:36 2015]
Good: Received Seq #  78  [Sun Sep 20 11:02:37 2015]
Good: Received Seq #  79  [Sun Sep 20 11:02:38 2015]
Good: Received Seq #  80  [Sun Sep 20 11:02:39 2015]
Bad: Expected Seq #81, Got #110 (29 frames dropped) [Sun Sep 20 11:03:09 2015]
Good: Received Seq # 111  [Sun Sep 20 11:03:10 2015]
Good: Received Seq # 112  [Sun Sep 20 11:03:11 2015]
Good: Received Seq # 113  [Sun Sep 20 11:03:12 2015]
Good: Received Seq # 114  [Sun Sep 20 11:03:13 2015]
Good: Received Seq # 115  [Sun Sep 20 11:03:14 2015]
Good: Received Seq # 116  [Sun Sep 20 11:03:15 2015]
Good: Received Seq # 117  [Sun Sep 20 11:03:16 2015]
Good: Received Seq # 118  [Sun Sep 20 11:03:17 2015]
Good: Received Seq # 119  [Sun Sep 20 11:03:18 2015]
Bad: Expected Seq #120, Got #130 (10 frames dropped) [Sun Sep 20 11:03:30 2015]
Good: Received Seq # 131  [Sun Sep 20 11:03:31 2015]
Good: Received Seq # 132  [Sun Sep 20 11:03:32 2015]
Good: Received Seq # 133  [Sun Sep 20 11:03:33 2015]
Good: Received Seq # 134  [Sun Sep 20 11:03:34 2015]
Good: Received Seq # 135  [Sun Sep 20 11:03:35 2015]
Good: Received Seq # 136  [Sun Sep 20 11:03:36 2015]

Edit (10/06/15):
I believe I've root-caused the issue. The Windows SSDP Discovery service appears periodically cycle which interface multicast packets go out on and also which interfaces incoming packets are, even on systems with only one physical network interface configured/online. On my system I have a single wired ethernet network and two virtual VMware network adapters (I'm not running in a VM - these are on the host side and are enabled but not being used). I modified the source ofthe utility above to support configuring which interface my broadcasts go out on via setsockopt(IP_MULTICAST_IF) and also which interface I listen to broadcasts on via setsockopt(IP_ADD_MEMBERSHIP). I then ran four instances of the utility - one sending on INADDR_ANY, one receiving on INADDR_ANY, and two more listening on each of the VMware virtual network adapters (VMnet1 and VMnet8, both preconfigured with their own fabricated/virtual subnets). When the INADDR_ANY receiver instance starts missing packets I see them show up on one of the VMware listeners. This is my proof that the Windows SSDP Discovery service is cycling the default adapter set for multicast transmission. I don't see this occur when the SSDP service is disabled. I assume the discovery service is doing this to catch SSDP messages on all network interfaces, although it's not clear why it has to change the system default multicast to accomplish this rather than just having multiple sockets, one on each interface in the system.
The workaround is to explicitly set which interface I configure for multicasting transmissions and listens, rather than relying on INADDR_ANY, which is the traditional way to handle multicasts that works fine on every other OS platform that is single-homed. Note that you have to explicitly set not just the transmitting interface but also the receiving side as well, because the discovery service's cycling of the default interface applies to both the default transmit interface and also which interface incoming packets are accepted for the IP multicast membership group.


text:
Q: Why Excel VBA can't query tables with the @ symbol? I'm trying to query a table, call it history@integration.
When I query the table, with this type of query:
select * from history@integration where id=5

and get the expected output.
With excel I connect to the database in this way:
cn.Open ( _
"User ID=" & userID & _
";Password=" & password & _
";Data Source=" & datasource & _
";Provider=MSDAORA.1")

but I get a runtime error of data type is not supported. I've verified using the exact same connection I can query the database with other "standard" tables like select * from history. Any thought on how I can get the "correct" type.

A: @ is a reserved character in SQL.  Try surrounding the table name with brackets like: [history@integration].

A: In Oracle (assuming this is what you're using, and it would be helpful to state that in your question) @ is typically used to represent a database link: likely it's not part of the table name, but the table "history" is actually in a different database linked to by a DB link named "integration".
Not all datatypes are selectable over an Oracle DB link (LOB types for example)


text:
Q: Android SSL Handshake Error
*

*I have an Apache HTTP Server which is configured using CA signed SSL Certificate.

*I am using ProxyPass to transfer the traffic from httpserver port 443 to IBM Worklight server http://localhost:9009
The problem is the approach is working perfectly on iOS devices but when it comes to Android devices I am getting ssl handshake problem.
(Thread.java:841)
04-16 05:30:51.950: E/com.worklight.androidgap.plugin.WLNativeXHRPlugin(31051): Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
04-16 05:30:51.950: E/com.worklight.androidgap.plugin.WLNativeXHRPlugin(31051):     at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:282)
04-16 05:30:51.950: E/com.worklight.androidgap.plugin.WLNativeXHRPlugin(31051):     at com.android.org.conscrypt.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:202)
04-16 05:30:51.950: E/com.worklight.androidgap.plugin.WLNativeXHRPlugin(31051):     at com.android.org.conscrypt.OpenSSLSocketImpl.verifyCertificateChain(OpenSSLSocketImpl.java:612)
04-16 05:30:51.950: E/com.worklight.androidgap.plugin.WLNativeXHRPlugin(31051):     at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
04-16 05:30:51.950: E/com.worklight.androidgap.plugin.WLNativeXHRPlugin(31051):     at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:406)
04-16 05:30:51.950: E/com.worklight.androidgap.plugin.WLNativeXHRPlugin(31051):     ... 13 more
04-16 05:30:51.950: E/com.worklight.androidgap.plugin.WLNativeXHRPlugin(31051): Caused by: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.

A: From the comments:

Thanks. The solution is to manually add your certificate in trusted stores Android. – Kunwar Adeel Apr 25 at 2:55


text:
Q: How can I change the font color of a dynamic text field using AS3? How can I change the color of the font inside of a dynamic text field using Actionscript 3 in Flash? I'd like to implement this into an if-statement, kind of like this:
if (randomVar == 0) {
    score.color = #0xFFFFFF;
} else if (randomVar == 1) {
    score.color = #0xFAFAFA;
} else {
    score.color = #0xAAAAAA;
}

A: You have to use a TextFormat.   Here is an example:
//first, get the text format that you've applied in Flash at design time:
var txtFormat:TextFormat = score.defaultTextFormat;

//then later, in your if statement:
txtFormat.color = 0xFF0000; //red

//modifying the text format object doesn't actually trigger any changes to text fields
//you have to apply it to your text field to see the changes
score.setTextFormat(txtFormat);

A: Another way to change the color of a TextField's text is to use the TextField.textColor property :
// the color here is in hexadecimal format, you don't need the "#"
score.textColor = 0xFAFAFA;

Hope that can help.

A: In my experience, the best way to do this is using HTMLText. Like this:
var color:uint = 0xffffff;

if (score > 5)
    color = 0x00ff00;
if (score > 10)
    color = 0xff0000;
if (score > 20)
    color = 0x0000ff;

myText.htmlText = "" + score + "";


text:
Q: parameter not passed to angular controller I'm trying to pass a parameter to an angular controller. It doesn't work. I get this error message:

"Failed to load template: App/Views/CustomerDetail.html".

I'm using MVC and angular routing mechanism.
Here's my project struсture:

And, my route config file:
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Customer",
            url: "Customer/{*catchall}",
            defaults: new { controller = "Home", action = "Customers" });

        routes.MapRoute(
            name: "order",
            url: "order/{*catchall}",
            defaults: new { controller = "Home", action = "Orders" });

        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

My angular config with HTML5 models:
'use strict';

var myApp = angular.module('myApp', ['ngRoute', 'appControllers']);
myApp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
    $routeProvider.when('/Customer', {
        templateUrl: 'App/Views/Customers.html',
        controller: 'customerController'
    }).
    when('/Customer/:customerId', {
        templateUrl: 'App/Views/CustomerDetail.html',
        controller: 'customerDetailController'
    }).
    when('/order', {
        templateUrl: 'App/Views/Orders.html',
        controller: 'orderController'
    }).
    otherwise({
        redirectTo:'/'
    });
    $locationProvider.html5Mode({
        enabled: true,
        requireBase: false
    });
}]);

And, my Home controller:
public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
    public ActionResult Customers()
    {
        return View();
    }
    public ActionResult Orders()
    {
        return View();
    }
}

I am trying URL http://localhost:1458/Customer/1
I think I'm making doing something wrong with the routing mechanism. Can you explain to me, please? Where did I make a mistake?


text:
Q: Почему при запросе Multipart from data не распарсивается массив? @Builder
@Data
@NoArgsConstructor
@AllArgsConstructor
public class AddMovieForm {
    private Set<ActorForm> actors;
}

Вот поле actors инициализируется как пустой массив.

    @PostMapping(value = "/save", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> saveMovie(AddMovieForm addMovieForm) {
        System.out.println(addMovieForm);
        return ResponseEntity.ok().build();
    }

Вот мой контроллер

------WebKitFormBoundaryPRnBmnwUDs52Wh9s
Content-Disposition: form-data; name="actors.0.firstName"
Артур
------WebKitFormBoundaryPRnBmnwUDs52Wh9s
Content-Disposition: form-data; name="actors.0.lastName"
Сwfewf
------WebKitFormBoundaryPRnBmnwUDs52Wh9s
Content-Disposition: form-data; name="actors.0.age"
32
------WebKitFormBoundaryPRnBmnwUDs52Wh9s
Content-Disposition: form-data; name="actors.0.gender"
Мужской
------WebKitFormBoundaryPRnBmnwUDs52Wh9s
Content-Disposition: form-data; name="actors.1.firstName"
Артур
------WebKitFormBoundaryPRnBmnwUDs52Wh9s
Content-Disposition: form-data; name="actors.1.lastName"
wfwef
------WebKitFormBoundaryPRnBmnwUDs52Wh9s
Content-Disposition: form-data; name="actors.1.age"
32
------WebKitFormBoundaryPRnBmnwUDs52Wh9s
Content-Disposition: form-data; name="actors.1.gender"
А вот такой запрос приходит. Вот поле name меня смущает. Может кто знает в чем дело ?


text:
Q: imagemap in Safari I originally did this with images being floated but in IE I was getting this 1px separation between all the images for some reason.  It seemed easier to use 1 image and throw an imagemap over it.  Now I find out that in Safari the imagemap doesn't work.  Only 6% of our traffic but that unfortunately includes or Executive VP's home computer.  D'oh.
I cannot figure out why this wont work despite all my searching.  Please help!
There are 4 images with imagemaps - all have unique IDs.  There's lots of bonus code in there thanks to Sharepoint not caring about what I tell it.
http://www.worldvision.ca/About-Us/financial-information/Pages/2011-annual-report-focus.aspx
<img src="images/footer_focus_development.jpg" alt="" style="margin-left:-100px; margin-top:-5px; position:relative;" usemap="#imgmap2012127151844"  border="0"/>
<map id="imgmap2012127151844">
<area shape="rect" alt="" title="" coords="403,197,482,215" href="http://childview.worldvision.ca/childview/en/?page_id=250p=1183" target="" />
<area shape="rect" alt="" title="" coords="446,431,531,447" href="http://childview.worldvision.ca/childview/en/?p=74" target="" />

A: Sorry to @moontear and thanks for the help.  I managed to fix this but wasn't able to post the answer for 8 hours :(
So, turns out that you need to also specify the NAME attribute for the  and not just an ID.

Silly!


text:
Q: Testing CanCanCan ability definition I'm using CanCanCan with Rolify and I´m trying to test my Ability class authorization.
When testing if a unprivileged user can CRUD other users in the system the test fails
1) Ability a guest user should not be able to manage others
 Failure/Error: expect(subject).to_not be_able_to(:crud, User)
   expected not to be able to :crud User(...)

But I can't find any reason why the check in my Ability class fails:
class Ability
  include CanCan::Ability

  def initialize(user = User.new)
    alias_action :create, :read, :update, :destroy, :destroy_multiple, to: :crud

    # What is wrong?
    can :crud, User, id: user.id

    if user.has_role?(:admin)
      can :manage, User
    end
  end
end

This is my spec:
require 'rails_helper'
require 'cancan/matchers'

RSpec.describe Ability do
  let(:user) { create(:user) }
  subject { Ability.new(user) }

  context "a guest user" do
    it "should be able to manage self" do
      expect(subject).to be_able_to(:crud, user)
    end

    it "should not be able to manage others" do
      expect(subject).to_not be_able_to(:crud, User)
    end
  end
end

A: expect(subject).to_not be_able_to(:crud, User)

You are referencing User model, not instance there. Use User.new or another persisted User instance.


text:
Q: How do I replace the built-in wordpress image editor? I'm trying to replace the built-in wordpress image editor (image-edit.php) by way of a plugin. I can't seem to find the correct hook - if there is one. I thought maybe I would replace the wp_image_editor() function, until I remembered you can't overwrite a function in php. So I'm not sure what to do.
Is there such an action hook? If not, what would be the best course of action?

A: First , WP_image_editor is a class, not a function ( CODEX )
the filter you are looking for is maybe  wp_image_editors
add_filter( 'wp_image_editors', 'image_editors_add_gmagick' );

so you would need something like
function image_editors_add_gmagick( $editors ) {
    if( ! class_exists('WP_Image_Editor_Gmagick') )
        include_once 'editors/gmagick.php';

    if( ! in_array( 'WP_Image_Editor_Gmagick', $editors ) )
        array_unshift( $editors, 'WP_Image_Editor_Gmagick' );

    return $editors;
}
add_filter( 'wp_image_editors', 'image_editors_add_gmagick' );

This is somewhat of a wild guess, never had to do that myself before ..


text:
Q: Plone / Python : zc.async problems with Plone on Ubuntu I have integrated collective.documenviewer on my plone website. This is used for viewing PDF and other office files online.
One of the optional add-on products is plone.app.async which in turn uses zc.async. Now, the installation went well without errors. But when I save a file, an error is generated that I can't figure out: Below is the error:
2012-08-29T12:52:03 ERROR collective.documentviewer Error using plone.app.async with collective.documentviewer. Converting pdf without plone.app.async...
Traceback (most recent call last):
File "/home/frank/apps/myplonesite/plone/eggs/collective.documentviewer-2.2a1-py2.7.egg/collective/documentviewer/async.py", line 143, in queueJob
runner = JobRunner(object)
File "/home/frank/apps/myplonesite/plone/eggs/collective.documentviewer-2.2a1-py2.7.egg/collective/documentviewer/async.py", line 50, in __init__
self.queue = self.async.getQueues()['']
File "/home/frank/apps/myplonesite/plone/eggs/plone.app.async-1.2-py2.7.egg/plone/app/async/service.py", line 100, in getQueues
return self._conn.root()[KEY]
File "/home/frank/apps/myplonesite/plone/../../python27/lib/python2.7/UserDict.py", line 23, in __getitem__
raise KeyError(key)
KeyError: 'zc.async'

These are the versions that I am using:
plone.app.async = 1.2
zc.async = 1.5.4

How do I do away with the KeyError issue ?
UPDATE: Below is my buildout
[buildout]
newest = false
allow-picked-versions = false
index = http://dist.candid.org/candid
extends =
    versions.cfg

parts =
    lxml
    svneggs
    svnproducts
    zeo
    instance
    worker
    paster
    plonesite

versions = versions

find-links =
    http://dist.candid.org/candid

develop =
      ../src/candid.main
      ../src/ploned.ui
      ../src/z3c.traverser
      ../src/repoze.whooze
      ../src/marginalia
      ../src/ore.alchemist
      ../src/alchemist.ui
      ../src/alchemist.catalyst
      ../src/alchemist.traversal
      ../src/alchemist.security
      ../src/portal.auth

eggs =
    Plone
    Products.PloneHelpCenter
    Products.LinguaPlone
    candid
    alchemist.ui
    alchemist.catalyst
    alchemist.traversal
    alchemist.security
    ploned.ui
    candidcms.plonepas
    candidcms.policy
    candidcms.theme
    psycopg2
    Products.Scrawl
    collective.contacts
    collective.tabr
    candidcms.workspaces
    lotr.repository
    archetypes.multifile
    Products.ATVocabularyManager
    collective.dynatree
    collective.portlet.explore
    z3c.json
    collective.js.jqueryui
    python-cjson
    collective.plonetruegallery
    lotr.templates
    portal.auth
    Products.PloneFormGen
    quintagroup.pfg.captcha
    collective.documentviewer
    five.intid
    plone.app.async

zcml =
    candidcms.plonepas
    candidcms.policy
    candidcms.theme
    candid.portal
    candidcms.workspaces
    archetypes.multifile
    lotr.templates
    collective.contacts
    collective.tabr
    collective.portlet.explore

[instance]
recipe = plone.recipe.zope2instance
user = uadmin:uadmin
eggs =
    ${buildout:eggs}
    Products.CMFPlone
    Paste
    PasteScript
    PasteDeploy
    repoze.tm2
    repoze.retry
    repoze.who

zcml =
    ${buildout:zcml}

zcml-additional =
    <include package="plone.app.async" file="single_db_instance.zcml" />
environment-vars =
    ZC_ASYNC_UUID ${buildout:directory}/var/instance-uuid.txt

products =
    ${svnproducts:location}

# !+XAPIAN PATH(mn, apr-2012) hardcoded path to candid xapian installation
# temporary fix because plone uses the 'candid.portal' package which is in the
# candid.main package. Once the candid.portal package is factored out this entry
# should be removed.
extra-paths =
  ../parts/xapian/lib/python

[lxml]
recipe = z3c.recipe.staticlxml
egg = lxml
force = false
build-libxslt = true
build-libxml2 = true
libxslt-url = http://candid-portal.googlecode.com/files/libxslt-1.1.24.tar.gz
libxml2-url = http://candid-portal.googlecode.com/files/libxml2-2.6.32.tar.gz

[svnproducts]
recipe = infrae.subversion
urls =
    http://candid-portal.googlecode.com/svn/plone.products/CandidHelpCenter/branches/plone4 CandidHelpCenter

[svneggs]
recipe = infrae.subversion
as_eggs = true
urls =
    http://candid-portal.googlecode.com/svn/plone.products/candidcms.plonepas/trunk/ candidcms.plonepas
    http://candid-portal.googlecode.com/svn/plone.products/candidcms.policy/trunk/  candidcms.policy
    http://candid-portal.googlecode.com/svn/plone.products/candidcms.theme/trunk/ candidcms.theme
    http://candid-portal.googlecode.com/svn/plone.products/candidcms.workspaces/trunk/ candidcms.workspaces
    http://lotr.googlecode.com/svn/lab/apps/lotr.repository/ lotr.repository
    http://lotr.googlecode.com/svn/trunk/products/lotr.templates/ lotr.templates

[paster]
recipe = zc.recipe.egg
eggs = ${instance:eggs}
# !+XAPIAN PATH(mn, apr-2012) hardcoded path to candid xapian installation
extra-paths =
  ../parts/xapian/lib/python
scripts = paster

[zeo]
recipe = plone.recipe.zeoserver
file-storage = ${buildout:directory}/var/filestorage/Data.fs
blob-storage = ${buildout:directory}/var/blobstorage
eggs = ${instance:eggs}

[worker]
recipe = plone.recipe.zope2instance
user = ${instance:user}
eggs = ${instance:eggs}
zcml = ${instance:zcml}
zserver-threads = 2
debug-mode = on
verbose-security = on
zeo-client = true
blob-storage = ${zeo:blob-storage}
shared-blob = on
eggs = ${instance:eggs}
zcml-additional =
    <include package="plone.app.async" file="single_db_worker.zcml" />
environment-vars =
    ZC_ASYNC_UUID ${buildout:directory}/var/worker-uuid.txt

[plonesite]
recipe = collective.recipe.plonesite
site-id = plone
admin-user = uadmin
instance = instance
profiles-initial =
    Products.CMFPlone:dependencies
    Products.CMFPlone:plone-content
    lotr.repository:default
    candidcms.policy:default
    candidcms.theme:default
    collective.dynatree:default
    candidcms.workspaces:default
    lotr.templates:default
    Products.FacultyStaffDirectory:default
    Products.PlonePopoll:default
    Products.PloneFormGen:default
    quintagroup.pfg.captcha:default
    collective.documentviewer:default
products-initial =
    Products.CMFPlone
    archetypes.multifile
    candidHelpCenter
    LinguaPlone
    collective.plonetruegallery
    collective.tabr
    Products.PloneFormGen
    quintagroup.pfg.captcha

A: This would happen if the queues for plone.app.async have not been set up. plone.app.async & zc.async are (over)complicated and actually do require you reading the README ;)
You should have a look at the instructions provided with plone.app.async at their pypi page, in particular the buildout configuration.
Unless you include the necessary zcml (for your "normal", as well as your "worker" instance) your queues will not be setup.

A: This looks like an issue with collective.documentviewer. I am the author and actually think I fixed this at some point. What version are you running?


text:
Q: How can I get value from IDictionary in VisitMember call? I want to get property from IDictionry
I want to access it in VisitMember call
But when I run it
It seems that dictionary value is not returned
Because when I am trying to get convert as here:
var dictProperty = declProp as IDictionary<string, object>;

It returns null (but it has type IDictionary)
Where is the problem?
 protected override Expression VisitMember(MemberExpression node)
            {

                if ((node.Member as PropertyInfo) != null)
                {
                   //this line returns propety  IDictionary<string,object> of my object which Type
                   //I can get from node.Member.DeclaringType)
                    var declProp = node.Member.DeclaringType.GetProperty(node.Member.Name);
                    ///trying to get to dictionary Item and return value
                    var parameterExpression = Expression.Parameter(typeof(IDictionary<string,
                    object>), "dict");
                    var constant = Expression.Constant("ContentType");
                    var propertyGetter = Expression.Property(parameterExpression, "Item", constant);
                    var expr = Expression.Lambda<Func<IDictionary<string, object>, object>>(propertyGetter, parameterExpression).Compile();
                    //but  dictProperty is null
                    //and it seems there is no value
                    var dictProperty = declProp as IDictionary<string, object>;
                    var value = expr(dictProperty);//trick to get value from dict

                }
                else if ((node.Member as FieldInfo) != null)
                {
                    var fieldInfo = node.Member as FieldInfo;
                    var constantExpression = node.Expression as ConstantExpression;
                    if (fieldInfo != null & constantExpression != null)
                    {
                       var value = fieldInfo.GetValue(constantExpression.Value);
                    }
                }
                else
                {
                    throw new Exception();
                }
                Expression mappedMember;
                if (map.memberMap.TryGetValue(node.Member, out mappedMember))
                    return Visit(mappedMember);
                return Expression.PropertyOrField(expression, node.Member.Name);
            }


text:
Q: "Bip bop, bip bop bop" -- does it mean anything? There's a song by Paul McCartnety, Bip-Bop, the main idea of which is quite vague, but nevertheless, three sentences are understood:

Dig your bottom dollar, put it in your hand.
  Why d'you hide your
  handbag underneath the stairs?
  Put your hair in curlers, gonna see a band.

At least, this is what is heard among the repetitious "Bip bop, bip bop bop" or "Wip wop, wip man wop." What might these mean?

A: Such nonsense syllables are common in English-language folk and popular song.

Then sigh not so, but let them go,
    And be you blithe and bonny,
  Converting all your sounds of woe
    Into hey nonny, nonny. —'Much Ado About Nothing'
Fa-la-la-la-la, la-la-la-la —'Deck the Halls'
Whack fol-de-dah now, dance to your partner —'Finnegan's Wake'
Who put the bomp in the bomp bah bomp bah bomp
  Who put the ram in the rama lama ding dong
  Who put the bop in the bop shoo bop shoo bop
  Who put the dip in the dip da dip da dip —'Who Put the Bomp'
There she was just a-walkin' down the street
  singin' do-wah diddy-diddy down diddy-do —'Do Wah Diddy'

Such phrases often express an exuberance beyond mere linguistic content.

A: They are not meaningful in common English and I highly doubt they are meaningful in some kind of slang. These kinds of nonsense "words" are sometimes employed for musical effect. There is even a genre called doo-wop that's characterized by such usage. From Wikipedia,

Doo-wop is a genre of music that was developed in African-American communities of New York City, Philadelphia, Chicago, Baltimore, Newark, Pittsburgh, Cincinnati, Detroit, Washington, D.C. and Los Angeles in the 1940s, achieving mainstream popularity in the 1950s and early 1960s. [...] Doo-wop features vocal group harmony, nonsense syllables, a simple beat, sometimes little or no instrumentation, and simple music and lyrics.


text:
Q: Binary search optimization in c? I am writing a key record look up where the I have an index between the key and the rec number.  This is sorted on the key.  Is there away to do this better that what I have for speed optimization?
typedef struct
{
    char key[MAX_KEYLEN];
    int  rec;
} KeyRecPair;

typedef struct
{
    KeyRecPair *map;
    int         numRecs;
} KeyRecMap;

int GetRecFromKey(char *key, KeyRecMap *theMap)
{
    int cmpValue, bottom = 0;
    int half = theMap->numRecs / 2;
    int top = theMap->numRecs - 1;

    while (bottom != top)
    {
        cmpValue = strncmp(key, theMap->map[half].key, MAX_KEY_LEN);

        if (cmpValue > 0)
        {
            /*top stays*/
            bottom = half + 1;
            half  = bottom + (top - bottom) / 2;
            continue;
        }
        if (cmpValue < 0)
        {
            /*bottom stays*/
            top = half - 1;
            half  = bottom + (top - bottom) / 2;
            continue;
        }
        return theMap->map[half].rec;
    }

    if (0 == strncmp(key, theMap->map[half].key, MAX_KEY_LEN))
        return theMap->map[half].rec;
    return 0;
}

A: The bsearch library function performs a binary search over an array, given a suitable compare function you implement. Being a library function, it is well-optimised and (hopefully) bug-free.

A: A good chunk of your time will be spent in the strncmp.
I suggest forcing that to be inlined, or rewriting it inline, to avoid the function call over head.
If you are feeling brave it may be possible to unroll the loop once or twice and see a performance gain.
If your string was actually a fixed length of array of char, you could make the length a multiple of 4 and and compare 4 bytes at a time with an unsigned int compare, instead of 1 byte at a time.
If you don't have a profiler, you should get one.   Profilers make it easy to see what the relative costs of various implementations are.
Another option would be to pick a different way to organize your data.  Check out AVL trees for inspiration.  Choosing some sort of Hashing function, like the others mentioned, may be a viable option

A: Instead of using a binary search to locate the item, a hash map might be more suitable because it has O(1) lookup characteristics. However that might be slow with load of collisions with a naive approach. However this paper describes a way to create a hashmap like tree that has O(log(n) / log(32)) access time which generally outperforms normal hashmap implementations. (The fixed aray + linked list implementation).

A: Any chance you could use a key that isn't a string? or at least shortest possible strings? (what is MAX_KEYLEN's value) that strcmp every iteration of the loop likely is one of the slower parts of the search.

A: Is there a reason for wanting to optimize this?  Have you run the program with a profiler and determined that the lookup takes a significant part of the total runtime?  Are you just curious about how fast you can get it?  (Either are, in my opinion, good reasons.)  If you are just randomly optimizing for the heck of it, don't.
Also, remember to benchmark.  It's hard to tell which of two versions of a function are faster on a modern system (it was easier on my Z80).  How many cache misses may or may not be more important than the number of branches wrongly predicted.

A: The only potential optimization that I can think of is to use something similar to golden ratio in calculating half instead of dividing the remaining subset to two halves with equal number of elements, that is
        if (cmpValue > 0)
        {
                /*top stays*/
                bottom = half + 1;
                half = bottom + (top - bottom) * 3 / 5;
                continue;
        }
        if (cmpValue < 0)
        {
                /*bottom stays*/
                top = half - 1;
                half = bottom + (top - bottom) * 2 / 5;
                continue;
        }

A: Instead of dividing by 2 U can make advantage of bit shift operator.
=>  for /2 u can use >> 1

A: Since you're going to have to compute half once per loop, why not just do that once, just before it is used? That would cut two complex-looking (at least, relatively speaking) lines of code.

A: Although I would expect a decent optimizer to do this for you, I'd put theMap->map into a local so that it has half a chance of ending up in a register instead of dereferencing it on each access.  Again, I'd expect the optimizer to do this for you, so you might also want to check the assembly output.
I looked at visual studio 2008's output in release and it does a pretty good job on the code.  For example, the comparison code looks like this:
; 30   :         if (cmpValue > 0)
test    eax, eax
jle SHORT $LN11@GetRecFrom
; 31   :         {
; omitted inner block for > case.
$LN11@GetRecFrom:
; 37   :         if (cmpValue < 0)
jge SHORT $LN2@GetRecFrom

basically, it's a branch to branch without retesting cmpValue.  Nice touch.
There is a slight benefit to putting theMap->map into a local, but it's tiny.  If MAX_KEY_LEN is not a nice multiple of 4 and structs aren't padded, you should definitely put the int first in your struct.


text:
Q: quasi random set and multivariate normal distribution matlab I have a multivariate normal distribution generated using mvnrnd.
I would like to generate this multivariate normal distribution not in a pure random way, but using for example a SOBOL sequence and I don't know how to implement it in Matlab. I know how to create a qrandstream but not how to use it in order to generate a multivariate normal distribution.

A: I think about the answer and this is my proposal:
R = chol(Correlation_Matrix) % I apply the Cholesky decomposition to the correlation matrix
Sobol = sobolset(1) % generate the sobolset with dimension 1
Sobolnumbers = net(Sobol,100) % take the firs 100 numbers of the sequence
Z = norminv(Sobolnumbers,0,1) % take the Z normal standardize values using norminv
X = mu + Z*R % obtain X pseudo random numbers from a multivariate normal distribution

A: A multidimensional Sobol set is required accordingly. Please see this function for implementation


text:
Q: need to concatenate content place holder id with div id for javascript code I am trying to implement show/hide div when certain value is selected from drop down list. But I have to concatenate the content place holder id with the div name. If I do not do so, the code block is not working.
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">

        <asp:DropDownList ID="ddlAnnualTax" runat="server" Height="35px" Font-Size="Medium" Width="15%" Enabled="true" onchange="ShowHideDiv()">
            <asp:ListItem Enabled="true" Text="select..." Value="-1"></asp:ListItem>
            <asp:ListItem Value="1">first year</asp:ListItem>
            <asp:ListItem Value="2">second year</asp:ListItem>
        </asp:DropDownList>

 <input type="text" id="txtPassport" />

</asp:Content>

In the code ContentPlaceHolder1 is content place holder id and the div I need to show/hide is dvPassport. So I have to make ContentPlaceHolder1_dvPassport for the code to work. Why is it so ?

A: Try with this code

replace ContentPlaceHolder1_dvPassport with document.getElementById('<%= dvPassport.ClientID %>'). Hope it will work. But I can not say, what is the reason of adding content place holder id with div tag.


text:
Q: How to change polar lines by different colors with respect to the interval with gnuplot I'd like to change this polar plot by using Gnuplot as following:

*

*changing line color (radial lines and their semi circle edges) by
different colors with respect to the range. For example, A to F
interval as red, G to L as blue, and M to S keeping black

Below, I'm providing my code and I'd appreciate if someone give a hand with that.

`set decimalsign '.'
unset border
set polar
set angles degrees #set gnuplot on degrees instead of radians

set style line 10 lt rgb "black" lw 4.0 #redefine a new line style for the grid

set grid polar 20 #set the grid to be displayed every 20 degrees
set grid ls 10

set rrange [0:0.3]
set rtics 0, 0.05, 0.2 format "%.2f"

set size square

set_label(x, text) = sprintf("set label '%s' at (0.22*cos(%f)), (0.22*sin(%f)) center", text, x, x) #this places a label on the outside

#here all labels are created
eval set_label(0, "A")
eval set_label(20, "B")
eval set_label(40, "C")
eval set_label(60, "D")
eval set_label(80, "E")
eval set_label(100, "F")
eval set_label(120, "G")
eval set_label(140, "H")
eval set_label(160, "I")
eval set_label(180, "J")
eval set_label(200, "K")
eval set_label(220, "L")
eval set_label(240, "M")
eval set_label(260, "N")
eval set_label(280, "O")
eval set_label(300, "P")
eval set_label(320, "Q")
eval set_label(340, "S")

set style line 11 lt rgb "blue" lw 10 pt 6 ps 6

plot "-" u 1:2 w lp ls 11
0    0.1499
020   0.1517
040   0.1474
060   0.1520
080   0.1526
100  0.1501
120  0.1491
140  0.1530
160  0.1515
180  0.1519
200  0.1534
220  0.1509
240  0.1501
260  0.1520
280  0.1481
300  0.1523
320  0.1529
340  0.1505
360    0.1499`

A: Here would be my suggestion. You can shorten the placing of the labels a bit.
I am not aware that you can set individual colors for grid lines, so you have to color them "manually".
Check the example below as a starting point.
I assumed that after Q there is coming R not S.
Code: (edit: colored border added)
### polar graph with colored grid lines
reset session

$Data <<EOD
0    0.1499
020   0.1517
040   0.1474
060   0.1520
080   0.1526
100  0.1501
120  0.1491
140  0.1530
160  0.1515
180  0.1519
200  0.1534
220  0.1509
240  0.1501
260  0.1520
280  0.1481
300  0.1523
320  0.1529
340  0.1505
360    0.1499
EOD

set size square
unset border
set polar
set angles degrees
unset label
unset tics
unset key

set style line 10 lt rgb "black" lw 1
set style line 11 lt rgb "blue" lw 4 pt 6 ps 1

set rrange [0:0.2]
set rtics 0, 0.05, 0.2 format "%.2f"

Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
N=18
set grid polar 360./N ls 10
set for [a=1:N] ttics (Alphabet[a:a] (a-1)*360./N)    # set ttic labels

R=0.2
myColors   = '0xff0000 0x00ffff 0x000000'
myColor(n) = word(myColors,(n-1)/(N/3)+1)   #  !!! integer division

set for [a= 1: N] object a circle at 0,0 size R arc [(a-1)*360./N:a*360./N] fc rgb myColor(a) lw 2 front wedge

plot $Data u 1:2 w lp ls 11
### end of code

Result:


text:
Q: Is it possible to get device phone number by imei number in android I like to know its possible by enter IMEI number can my app detect users current device phone number.

A: May be you can use this code to get the phone number.
Code:
TelephonyManager phneMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String phneNmbr = phneMgr.getLine1Number();

Required Permission
    <uses-permission android:name="android.permission.READ_PHONE_STATE"/>


text:
Q: Converting Data to Tenths and averaging values so I have a table in thousandths of a mile like this:
id |fk |from  |to    |speed|score
1  |123|10.002|10.003|20   |10
2  |123|10.003|10.004|25   |11
3  |123|10.004|10.005|40   |44
4  |123|10.005|10.006|50   |23
5  |123|10.006|10.007|20   |54
6  |123|10.007|10.008|10   |24
7  |123|10.008|10.009|65   |24
8  |123|10.009|10.010|23   |24
9  |123|10.010|10.011|74   |56
10 |123|10.011|10.012|25   |43
11 |123|10.012|10.013|10   |76
12 |123|10.013|10.014|5    |10
...

I need to convert the thousandth mile table to tenths of a mile and take average of speed and score like this:
id |fk |from  |to    |Avgspeed|Avgscore
1  |123|10.002|10.012|35.2    |31.3
10 |123|10.012|...   |...     |...

I came up with this query to get the tenth of a mile:
select CASE WHEN rn=1 then 1
when rn%10=0 then 1
else 0 end chk,x.* from
(
select row_number() over (partition by fk order by fk,from) rn,* from dbo.Thous_Data
)x

This gives me
id |fk |from  |to    |speed|score|chk|rn
1  |123|10.002|10.003|20   |10   |1  |1
2  |123|10.003|10.004|25   |11   |0  |2
3  |123|10.004|10.005|40   |44   |0  |3
4  |123|10.005|10.006|50   |23   |0  |4
5  |123|10.006|10.007|20   |54   |0  |5
6  |123|10.007|10.008|10   |24   |0  |6
7  |123|10.008|10.009|65   |24   |0  |7
8  |123|10.009|10.010|23   |24   |0  |8
9  |123|10.010|10.011|74   |56   |0  |9
10 |123|10.011|10.012|25   |43   |1  |10
11 |123|10.012|10.013|10   |76   |0  |11
12 |123|10.013|10.014|5    |10   |0  |12
...

Not sure how to proceed with getting the averages and setting up the from and to correctly. Any ideas appreciated.

A: Something like this?
SELECT 10 * FLOOR(id / 10)  , AVG(speed), MIN( [from] ) , MAX( [to])
FROM dbo.Thous_Data
GROUP BY 10 * FLOOR(id / 10);

A: The way I was able to do it was by starting the count from 0 so that the brackets would be accurate:
with cte as
(select CASE WHEN rn=0 then 1
when rn%10=0 then 1
else 0 end chk,x.*
from
(
select ROW_NUMBER() over (partition by fk order by fk,from)-1 rn,* from dbo.Thous_Data
)x

)
,cte2 as(
SELECT
      distinct fk,to,from,
       SUM([Chk]) OVER (PARTITION BY  fk ORDER BY  to,from) AS Groups

    FROM cte

)

    Select distinct fk,
        Min(from) over (partition by fk,groups) from_
,Max(to) over (partition by fk,groups) to_
,avg(speed) over (partition by fk,groups) Aspeed
,avg(score) over (partition by fk,groups) Ascore

from
cte2


text:
Q: How to close previous frames and reuse them later in tkinter I have this code below. functions at forget() and remember() are supposed to remove the previous frame and grid in a new one with new label. steps should go something like:
step 1: f1.grid_forget()
step 2: f1.grid()
step 3: Label(f1).grid()

this should allow for the whole previous pane to be forgotten, together with its previous contents and pave way fr the new frame and its contents.
from tkinter import *

root = Tk()
f1=Frame(root)
f1.grid(column=0, row=0)
f2=Frame(root)
f2.grid(column=0, row=1)

def forget():
    f1.grid_forget()
    f1.grid(column=0, row=0)
    lbl2 = Label(f1, text="Yes he's back").grid(column=0, row=0)

def remember():
    f1.grid(column=0, row=0)
    f1.grid(column=0, row=0)
    lbl2 = Label(f1, text="Is he back?").grid(column=0, row=0)

b1 = Button(f2, text="Forget", command=forget).grid(column=0, row=0)
b2 = Button(f2, text="Remember", command=remember).grid(column=1, row=0)

root.mainloop()

A: grid_forget doesn't cause a widget to be destroyed. It only causes it to not be mapped to the screen. Since your forget function creates new labels but never destroys the old labels, your frame will keep expanding with each new label.
If you want a widget to be destroyed, you must call destroy on it or one of its ancestors. In your case I'm guessing you want to first do f1.destroy() rather than f1.grid_forget(), since you want all of its children to be destroyed. It's a little unclear precisely what you want to do, another choice would be to only destroy the children of f1.


text:
Q: Getting an ID from a one-to-many field I am trying to get a ID for a related Model.  I have tried several things but can not figure it out.  below is the code I am using.
def assign_load(request):
form = DispatchForm(request.POST or None)
loads = Load.objects.all().filter(active=True, dispatched=False, picked_up=False, delivered=False,
                                  billed=False, paid=False)
context_dict = {'dispatch' : form, 'load' : loads}
if form.is_valid():
    save_it = form.save()
    save_it.save()
    new_dispatch = Dispatch.objects.all().filter(id=save_it.id)
    print(new_dispatch.model.load_number.pk)
    return HttpResponseRedirect('/dispatch/dispatch/')

return render(request, 'dispatch/dispatch_form.html', context_dict)

new_dispatch is the newly created record that has a one-to-many releation with a model called Loads. I need to get the load_number PK when I try to print just the new_dispatch.model.load_number I get back the following.
<django.db.models.fields.related_descriptors.ForwardManyToOneDescriptor object at 0x0000029016E34710>

but what I need is the ID for that record so that I can updated some fields.
Thank you very much for your help, I am new to the Django world and trying to figure this stuff out.

A: Use  Dispatch.objects.get(id=save_it.id) instead of Dispatch.objects.all().filter(id=save_it.id)


text:
Q: Anchor link keeps jumping, no matter what I do Ok, this is driving me crazy!
I'm working with a "tab like" submenu to show 3 different tables. Each link inside this submenu hides the current content and show another one.
NOTE: for now I'll leave a direct link to the page I'm working on so you may check the problem by yourself.
To avoid the  (anchor) jumps, I'm already trying  (which works fine in another site I have). In my jQuery code I'm also using "e.preventDefault();" that helps avoiding the jump to the top of the page, but even using it the page always jumps to some part of the page above the sublinks.
I really don't know what else I could do to avoid this jumps.
For now this is what I have inside my html:

Sites Estáticos

Sites Dinâmicos

Serviços Extras

And this is my jQuery:
function subSections(){
$('nav.menu li a').click(function(e){
    e.preventDefault(); //this helps, but don't solve the problem
    var active = $(this).parent();
    var currSection = $(this).attr('rel');
    if(active.hasClass('current-menu-item')!=true){
        // Add and remove 'current-menu-item' class
        $('nav.menu .current-menu-item').removeClass('current-menu-item');
        active.addClass('current-menu-item');
        // Hide currentSection and Show the clicked one
        $('.showing').fadeOut('slow', function(){
            $('#'+currSection).fadeIn('slow').addClass('showing');
        }).removeClass('showing');
    }
});

}
Also, maybe there's a better way to do this "show and hide" stuff, but this seems to work fine. Well, I'll be glad if anyone can shed a light on this problem and help me! Thanks in advance!

A: Use .show() and .hide() instead of .fadeIn() and .fadeOut().
If you want to keep the animation, you can try .show('slow') and .hide('slow') but that may trigger the jumping problem also.

A: Also, just to refactor the code a small bit and save a bit of typing (and make the script more dynamic) you don't need to write onclick="return false;"on every html link. Simply place return false at the end of the .click function in jQuery.
function subSections(){
$('nav.menu li a').click(function(e){
    e.preventDefault(); //this helps, but don't solve the problem
    var active = $(this).parent();
    var currSection = $(this).attr('rel');
    if(active.hasClass('current-menu-item')!=true){
        // Add and remove 'current-menu-item' class
        $('nav.menu .current-menu-item').removeClass('current-menu-item');
        active.addClass('current-menu-item');
        // Hide currentSection and Show the clicked one
        $('.showing').fadeOut('slow', function(){
            $('#'+currSection).fadeIn('slow').addClass('showing');
        }).removeClass('showing');

    // Return false for all links in the nav onclick
    return false;

    }
});


text:
Q: Efficiently resolving belongs_to relationship in elixir dataloader? Is it possible to use elixir dataloader to query a belongs_to relationship efficiently? It seems that the load is querying all of the items it needs, but the get is returning the first value of the loaded items regardless of which single item it actually needs. This is the code that I am using now:
field :node, :node_object, resolve: fn parent, _, %{context: %{loader: loader}} ->
  # parent.node_id = 1, but concurrently also another parent.node_id = 5
  loader
  |> Dataloader.load(NodeContext, :node, parent) # loads node_id 5 and 1
  |> on_load(fn loader ->
    loader
    |> Dataloader.get(NodeContext, :node, parent) # always returns the node with id = 5
    |> (&{:ok, &1}).()
  end)
end

My current work around is to use the following code, but it makes the code much uglier and unfriendly with the Ecto schemas since I need to explicitly specify the node schema and node_id field of the parent schema here instead of letting dataloader infer it from the existing ecto schemas:
field :node, :node_object, resolve: fn parent, _, %{context: %{loader: loader}} ->
  loader
  |> Dataloader.load(NodeContext, {:one, NodeSchema}, id: parent.node_id)
  |> on_load(fn loader ->
    loader
    |> Dataloader.get(NodeContext, {:one, NodeSchema}, id: parent.node_id)
    |> (&{:ok, &1}).()
  end)
end

A: I was able to fix this by making the node_id a primary_key of the parent schema like this:
defmodule MyApp.ParentSchema do
  use Ecto.Schema
  alias MyApp.NodeSchema

  @primary_key false

  embedded_schema do
    belongs_to :node, NodeSchema, primary_key: true
  end
end

I'm not sure if this is intended behavior for the dataloader since it seems like the primary_key check should happen on the child object instead of the parent object.


text:
Q: How to change positions of labels using kivy I am currently programming a simple app to display some text after the press of a button. The Layout, however, is on my phone totally different from that on my pc.
Changing the positions of the labels in the .kv didn't work; nothing changed.
To build the app, I'm using an Ubuntu virtual box with buildozer.
Screenshot(Galaxy s9+)

Main.py:
import kivy
import random
import math
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.relativelayout import RelativeLayout
def roundup(x):
    return int(math.ceil(x / 5.0)) * 5

x = random.randint(0,29)

tempo = roundup(random.randint(80,150))
Tonart = ["GDur #","eMoll #","DDur ##","hMoll ##","ADur ###","fisMoll ###","EDur ####","cisMoll ####","HDur ######","gisMoll #####","FisDur ######","disMoll ######","CisDur #######","aisMoll #######","FDur ♭","dMoll ♭","BDur ♭♭","gMoll ♭♭","EsDur ♭♭♭","cMoll ♭♭♭","AsDur ♭♭♭♭","fMoll ♭♭♭♭","DesDur ♭♭♭♭♭","bMoll ♭♭♭♭♭","GesDur ♭♭♭♭♭♭","esMoll ♭♭♭♭♭♭","CesDur ♭♭♭♭♭♭♭","asMoll ♭♭♭♭♭♭♭","CDur","aMoll"]

Kreuze = ["Fis","Cis","Gis","Dis","Ais","Eis","His"]

Bs = ["B","Es","As","Des","Ges","Ces","Fes"]
class Controller(RelativeLayout):
    def __init__(self):
    super(Controller, self).__init__()

    def btn_clk(self):
    self.lbl6.text = str(tempo)
    if x == 0 or x == 1:
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = str(Kreuze[0:1])
    elif x == 2 or x == 3:
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = str(Kreuze[0:2])
    elif x == 4 or x == 5:
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = str(Kreuze[0:3])
    elif x == 6 or x == 7:
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = str(Kreuze[0:4])
    elif x == 8 or x == 9:
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = str(Kreuze[0:5])
    elif x == 10 or x == 11:
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = str(Kreuze[0:6])
    elif x == 12 or x == 13:
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = str(Kreuze[0:7])
    elif x == 14 or x == 15:
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = str(Bs[0:1])
    elif x == 16 or x == 17:
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = str(Bs[0:2])
    elif x == 18 or x == 19:
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = str(Bs[0:3])
    elif x == 20 or x == 21:
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = str(Bs[0:4])
    elif x == 22 or x == 23:
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = str(Bs[0:5])
    elif x == 24 or x == 25:
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = str(Bs[0:6])
    elif x == 26 or x == 27:
        print("Tonart:",Tonart[x],"also:")
        print(Kreuze[0:2])
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = str(Bs[0:7])
    elif x == 28 or x == 29:
        print("Tonart:",Tonart[x],"also:")
        print(Kreuze[0:2])
        self.lbl.text = "Tonart:"
        self.lbl2.text = Tonart[x]
        self.lbl3.text = "also:"
        self.lbl4.text = "KEINE VORZEICHEN DIGGAH"

class ActionApp(App):

    def build(self):
        return Controller()

myApp = ActionApp()

myApp.run()

action.kv:
    <Controller>:
    lbl: label1
    lbl2: label2
    lbl3: label3
    lbl4: label4
    lbl5: label5
    lbl6: label6
    RelativeLayout:

        Button:
            text: 'Key und Bpm generieren'
            on_press: root.btn_clk()
            pos: 0,50
        Label:
            id: label1
            text: 'Tonart:'
            pos: -158, -272
        Label:
            id: label2
            text: "..."
            pos: -45, -272
        Label:
            id: label3
            text: "also:"
            pos: 40, -272
        Label:
            id: label4
            text: "..."
            pos: 200, -272
        Label:
            id: label5
            text: "Bpm:"
            pos: -360, -272
        Label:
            id: label6
            text: "..."
            pos: -325, -272


text:
Q: If $A$ is similar to $-A^T$, is $A$ similar to an antisymmetric matrix? Suppose that $A$ is an $n \times n$-matrix with entries from some field $F$. Assume also that $A$ is similar to $-A^T$, ie. $PAP^{-1} = -A^T$ for some invertible matrix $P$. (Here $A^T$ denotes the transpose of $A$.) Does it follow that $A$ is similar to an antisymmetric matrix?

A: Consider the matrix $A = \begin{pmatrix} 1 & 0 \\ 0 & -1 \end{pmatrix}$.  Since $A$ is diagonal, it is similar to $A^T$ (trivially), and since $A$ and $-A$ have the same eigenvalues, they are similar.  Thus $A$ is similar to $-A^T$.
However the eigenvalues of a real antisymmetric matrix are purely imaginary, so $A$ is not similar to one of these.


text:
Q: How can i create 6  in php and arrange in a div wrapper? I want to create 6
 in php by a loop with size of 200x200 px and arrange these 6 div in 3 rows and 2 columns inside a  div wrapper.
Thanks in advance

  <?php
  $i = 1;
 for ( $i=1 ; $i<=6; $i++){
   div1    div2
   div3    div4
   div5    div6
  }
  ?>

A: The generating of the divs is the easy bit - use the clear property in css and assign it using the nth-child syntax like so:
<?php
    echo "
";
    for( $i=0; $i < 6; $i++ ) echo "
$i
";
    echo "
";
?>

To see the wrapper background colour it needs a height -the 2n+1 ~ this is defined in the css specification so you need only use it like it is. Have a look on css-tricks.com etc for use of nth-child, nth-of-type(odd) etc