text:
Q: How to track previous guesses I am a student in Australia studying Digitronics. My code for a game of Minesweeper works, but there are a few flaws. The one that I can't seem to fix is this:
There is a countdown timer, that works by multiplying the rows and the columns, and then taking the number of mines away. However, the player can cheat the timer by entering in the same 'safe' square over and over again. I can't figure out how to put all the guesses into a list, and then add each guess in one by one, but I get the basic principle.
How do I add them into lists so the countdown timer can't be cheated like this?
# Simple Minesweeper - but not so simple anymore
# Version 3.0
# 20/9/17 - 25/10/17

from random import randint      # so there is a random mine placement
import time     # so I can delay the game
import sys      # so I can quit the game at any time

# Starts the loop for the game
play = True
while play == True:

    ##########################################
    #### Lists and Variables Created Here ####
    ##########################################

    # opens the board for use
    board = []

    # opens the mines list, currently empty so it can be altered later.
    mines = []

    # determines the rows on the board
    board_row = 0

    # determines the adjacent mines
    adj = 0

    # sets a variable to be used later in the check_ans() function
    wrong = 0

    #determines the amount of rows on the board
    while True:
        board_row = int(input("For a square board, how many rows and columns? (5 min, 10 max):"))
        if board_row > 10:
            print("That is too high. Please enter another!")
        elif board_row < 5:
            print("That is too small. Please enter another!")
        else:
            break

    # adds mines for a larger board
    if board_row >= 8:
        for i in range(15):
            mines.append([randint(0,board_row-1), randint(0, board_row-1)])

    # adds smaller mines for a smaller board
    elif board_row >= 5:
        for i in range(10):
            mines.append([randint(0,board_row-1), randint(0, board_row-1)])

    # creates the 'x's to display on the minewsweeper board
    for i in range(board_row):
        board.append(["x"] * board_row)

    ##############################
    #### Functions Start Here ####
    ##############################

    # creates the rows
    def draw_board(board):
        for i in board:
             print(" |".join(i))
             print("-" * (board_row*3-1))

    # check the answers
    def check_ans():
        if row >= board_row or col >= board_row:
            print("That number is too high. The order goes 1 to ", board_row)
            wrong = 1
        else:
            wrong = 0

    # defines the adjacent mines, by checking each of the surrounding squares, one
    # by one
    def adj_mines(r, c, adj):
        adj = 0
        if [r+1, c] in mines:
            adj += 1
        if [r+1, c+1] in mines:
            adj += 1
        if [r+1, c-1] in mines:
            adj += 1
        if [r, c+1] in mines:
            adj += 1
        if [r, c-1] in mines:
            adj += 1
        if [r-1, c+1] in mines:
            adj += 1
        if [r-1, c] in mines:
            adj += 1
        if [r-1, c-1] in mines:
            adj += 1
        return adj

    def Intro_to_game():
        print('Hello. This is a game of Minesweeper.')
        print('On each turn, select the number of the row and column that you wish to ')
        print('uncover, and press enter. If a number appears, ')
        print('it indicates how many bombs are in the ')
        print('surrounding eight tiles (\'x\'s). To let you know how')
        print('many tiles you have left to uncover, there is a ')
        print('countdown before each turn. You cannot flag bombs, only avoid them.')
        print('Enjoy, and good luck!')

    # defines number of moves required to beat the game, as
    # there is no flagging function.

    moves = (((board_row) * (board_row) - int(len(mines))))

    ##################################
    #### Main Program Starts Here ####
    ##################################

    draw_board(board)

    # This uses a function to determine how many cells are left to
    # clear the board, as there is no way to flag. This makes the
    # game significantly harder, as you have to keep track in your
    # head of where the bombs are.
    Intro_to_game()
    while True:
        print('===================================')
        print("Cells to clear: " + str(moves))

        # This part enters in the rows and columns. However, although
        # the lists typically start at 0, the program has to subtract
        # one from the different imputs to put them in the right place

        row = (int(input("Row: ")) - 1)

        # This part doesn't allow the player to enter
        # a number that is higher than the board range
        while row >= board_row:
            print('That is not in the board range')
            row = (int(input("Row: ")) -1)

        col = (int(input("Col: ")) - 1)

        # This part doesn't allow the player to enter
        # a number that is higher than the board range

        while col >= board_row:
            print('That is not in the board range')
            col = (int(input("Col: ")) -1)

        # checks to see if there is a bomb in the called field, if not,
        # then it repeats. If there is a bomb, it shows, "Sorry, but you
        # have blown up." Then it asks if they player would like to play
        # again.
        check_ans()

        if wrong != 1:
            if [row, col] in mines:
                break
            else:
                board[row][col] = str(adj_mines(row,col,0))
                moves = moves - 1
        draw_board(board)
        if moves == 0:
            print("You have won!")
            time.sleep(2)
            sys.exit
    print("Sorry, but you have blown up :(")

    # Although unconventional, this little bit processes the
    # request to play again. If yes, it breaks the loop, and
    # goes back to the start. If no, sys.exit quits the game

    print("Would you like to play again? (Yes or No)")
    play_again = input()
    if play_again == 'Yes':
        continue
    if play_again == 'Y':
        continue
    if play_again == 'yes':
        continue
    if play_again == 'y':
        continue
    else:
        sys.exit()

A: The problem here is that you never check if the position is already revealed. You could do it by checking for the initial 'x':
# ...
    if wrong != 1:
        if [row, col] in mines:
            break
        elif board[row][col] != 'x':
            print('This square is already revealed!! Try again')
        else:
            board[row][col] = str(adj_mines(row,col,0))
            moves = moves - 1
# ...


text:
Q: How to use ffmpeg to extract frames from video and read as a list of images in python in memory without writing files At my application server, I have a stream of Webm chunks coming from browsers that users record live videos. I want to analyze each frame simultaneously. So I used python to create a generator yielding the Webm file binaries to feed into ffmpeg. I use the command python convert.py | ffmpeg -i pipe: -r 1 output%3d.jpg to create a set of frames files. (The convert.py is just the generator to yield binary webm data for ffmpeg).
My question is that how can I make the ffmpeg output to a new pipe that in python I can read as a list of images directly?

A: Try:
python convert.py | ffmpeg -i pipe: -r 1 -c:v mjpeg -f image2pipe pipe: | python example.py

redpajama_set_name: RedPajamaStackExchange


text:
Q: KDE Plasma: Skype messages opens up panel and won't close until clicked I'm using KDE Plasma on ubuntu and I have aproblem with skype. Whenever someone messages me, the panel opens up and won't close until I read the message. Please take a look at these gifs:
In the first gif, you see, how the panels opens up, after I get a message, but the panel does not close.

In the second gif, you see, how I have to click on skype and to read the message, to close the panel.

How can I disable this behaviour? I don't want the panel to show up, everytime someone messages me. And I don't want to read the message, to close the panel.
Any suggestions? Please tell me, if you need more informations.
Plasma version:
$ plasmashell --version
plasmashell 5.8.5

EDIT: New skype version: Problem remains:


text:
Q: Odd Performance benefit of adding union in large table query I have this table with around 5 million rows
CREATE TABLE [dbo].[Zip](
    [Coun_Code] [char](2) NOT NULL,
    [Zip] [varchar](10) NOT NULL,
    [State] [nvarchar](50) NOT NULL,
    [Zip_Name] [nvarchar](50) NOT NULL,
    [Active] [bit] NOT NULL,
 CONSTRAINT [Zip_Pk] PRIMARY KEY CLUSTERED
(
    [Zip] ASC,
    [Coun_Code] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

Can someone please help me understand why the second query only takes two secs, while the first takes around 9? I found out by copy-paste mistake...
Q1: Without Union
DECLARE
    @Filter nvarchar(50),
    @StartIndex int,
    @EndIndex int,
    @OnlyStartsWith bit

SELECT @Filter = 'c1210',
@StartIndex = 0,
@EndIndex = 100,
@OnlyStartsWith = 0

    IF @OnlyStartsWith = 1
        SET @Filter = @Filter + '%';
    ELSE
        SET @Filter = '%' + @Filter + '%';

    DECLARE @ZipFilter varchar(10) = @Filter;

    WITH NumberedZips AS
    (
         SELECT Zip, Zip_Name, Coun_Code, [State], Active, ROW_NUMBER() OVER (ORDER BY ZIP) as rowNum
         FROM
            (
            SELECT Zip, Zip_Name, Coun_Code, [State], Active
            FROM Zip z
            WHERE
                z.Zip LIKE @ZipFilter OR z.Zip_Name LIKE @Filter
            --UNION
            --SELECT Zip, Zip_Name, Coun_Code, [State], Active
            --FROM Zip z
            --WHERE
            --  z.Zip LIKE @ZipFilter OR z.Zip_Name LIKE @Filter
        ) filteredZips
    )
    SELECT
        COUN_CODE,
        ZIP_NAME,
        ZIP,
        Active,
        [State]
    FROM NumberedZips nz
    WHERE
        rowNum BETWEEN @StartIndex AND @EndIndex

Q2: With Union
DECLARE
    @Filter nvarchar(50),
    @StartIndex int,
    @EndIndex int,
    @OnlyStartsWith bit

SELECT @Filter = 'c1210',
@StartIndex = 0,
@EndIndex = 100,
@OnlyStartsWith = 0

    IF @OnlyStartsWith = 1
        SET @Filter = @Filter + '%';
    ELSE
        SET @Filter = '%' + @Filter + '%';

    DECLARE @ZipFilter varchar(10) = @Filter;

    WITH NumberedZips AS
    (
         SELECT Zip, Zip_Name, Coun_Code, [State], Active, ROW_NUMBER() OVER (ORDER BY ZIP) as rowNum
         FROM
            (
            SELECT Zip, Zip_Name, Coun_Code, [State], Active
            FROM Zip z
            WHERE
                z.Zip LIKE @ZipFilter OR z.Zip_Name LIKE @Filter
            UNION
            SELECT Zip, Zip_Name, Coun_Code, [State], Active
            FROM Zip z
            WHERE
                z.Zip LIKE @ZipFilter OR z.Zip_Name LIKE @Filter
        ) filteredZips
    )
    SELECT
        COUN_CODE,
        ZIP_NAME,
        ZIP,
        Active,
        [State]
    FROM NumberedZips nz
    WHERE
        rowNum BETWEEN @StartIndex AND @EndIndex

As far as I can see they are using the same index. It does not help/work to remove either filter on the nested SELECT statements, then it also takes around 9 secs. I also tried adding an index on Zip_Name, but that didn't make a difference either.

A: I have not explanation for why the second would be faster.
Try this:
WITH NumberedZips AS
(
     SELECT Zip, Zip_Name, Coun_Code, [State], Active
          , ROW_NUMBER() OVER (ORDER BY ZIP) as rowNum
     FROM
     (  SELECT Zip, Zip_Name, Coun_Code, [State], Active
          FROM Zip z
         WHERE z.Zip LIKE @ZipFilter
        UNION
        SELECT Zip, Zip_Name, Coun_Code, [State], Active
          FROM Zip z
         WHERE z.Zip_Name LIKE @Filter
    ) filteredZips
)
SELECT COUN_CODE, ZIP_NAME, ZIP, Active, [State]
  FROM NumberedZips nz
 WHERE rowNum BETWEEN @StartIndex AND @EndIndex


text:
Q: Attempting find an embedded string in database with mysql I'm attempting to query our database to find specific types of transactions with unique parameters.
There are multiple formats and I'm looking to get the transactions with the -Q/ parameter.
BCR*DEVSTS
BCR*1150
BCR*1150/28AUG
BCR*DEVSTS-Q/28AUG
BCR*DEV-Q/28AUG

I'm able to find the BCR transactions but due to memory constraints I can only get the first 10k rows and they don't have the -Q/ parameter.  I'm trying to create a query that will only select the required transactions.
I used the following to query for the basis transaction:
select *
from transaction_200827
where reqresponse= 'Q' and message rlike '^BCR.*'

I've reviewed multiple websites but haven't been able to find an example of this scenario.  I've tried variations on the examples provided and haven't been successful:
select * from transaction_200827 where reqresponse= 'Q' and message rlike '^BCR(Q/).*'
select * from transaction_200827 where reqresponse= 'Q' and message rlike '^BCR%Q/%.*'

I'm fairly new to building queries and would appreciate any guidance or direction for generating this type of query.

A: You're mixing regexp and LIKE patterns. Use either
message LIKE 'BCR%-Q/%'

or
message RLIKE '^BCR.*-Q/'

You're also missing the - before Q in your patterns.
There's no need to add .* to the end of the regexp -- RLIKE succeeds when the regexp matches anywhere in the string, it doesn't have to match the entire string (the ^ anchor forces it to match starting from the beginning, but there's no $ anchor extending it to the end).
If the column has an index, I recommend using LIKE -- in my experience, RLIKE doesn't take advantage of indexes. Either way, the index will only be used for matching the BCR at the beginning, the rest requires scanning all the values with that prefix.


text:
Q: GLSA-check for Ubuntu or Debian? glsa-check is a tool to report a server's exposure to known security vulnerabilities. Has anyone written a tool to do a similar thing for apt based systems?

A: http://lzone.de/Automated+Linux+Package+Vulnerability+Scanning

*

*Debian:  debsecan

*CentOS, Fedora, Redhat:  "yum list-security"

*OpenSuSE:    "zypper list-patches"

*SLES:    "rug lu"

*Gentoo:  glsa-check

*FreeBSD: Portaudit

**nixes: lynis

A: Check the Security HOWTO for Debian which refers to vulnerability scanners like Nessus.  While not as Free as it used to be, Nessus is still considered the #1 tool for UNIX vulnerability scanning.
If you have the security repository for Debian or Ubuntu installed, you can apt-get upgrade to that without fear of installing new packages, and safe in the knowledge that (as much as the Debian/Ubuntu maintainers are on the case) you will get patched packages at the version that you chose to install.
Some people choose to automatically 'apt-get update; apt-get upgrade -y' if they are only using security; your mileage may vary.

A: Nessus can do an external scans and will pick up on any problems it knows about with anything it finds listening on a port. However unless you use the Unix compliance (needs a professional nessus feed) module you can't check what is actually installed on the scanned host. By default it's pretty good with RedHat and will give you a list of packages that have had redhat advisories issued. AFAIK it doesn't to the same for Debian based systems, so it would need someone to write and maintain a plugin or nessus audit file that cross references DSA or CVE.

A: GLSA is not a network vulnerability scanner as Geoff rightfully pointed, it's only a little script comparing the versions of emerged ebuilds against a list of vulnerabilites affecting official gentoo ebuilds. See here for details: http://gentoo.devel-net.org/glsa/readme
Nessus on the other way only checks a system from the point of view of the network, not locally and as such cannot find vulnerabilities like local root exploits.
I don't know of an equivalent in Debian but if you feel ok developing your own script have a look here:
Debian Security Bug Tracker, Debian Security main page and the associated feed of vulnerabilities.


text:
Q: How to send multiple variables in jeditable? i'm quite new to jquery and right now, im using jeditable to let the user edit some information on my webpage.
So here's my problem, How do you send multiple variables to the php file using jeditable? i understand that when the user clicks the submit button, the id and value will be POST-ed to the php file.
so let's say i have this code:
var x = 1;
var y = 2;

$('.edit_area').editable('test.php', {
    type      : 'textarea',
    cancel    : 'Cancel',
    event     : "dblclick",
    submit    : 'OK',
    indicator : '<img src="img/loading.gif">',
    tooltip   : 'Click to edit...'
});

how can i send the x and y variables to test.php when the user clicks the OK button in jeditable? thanks

A: This post is very old but I stumbled upon it. Maybe this will help somebody. A short look at the  documentation would have told you this:

"(Mixed) submitdata: Extra parameters when submitting content. Can be either a hash or function returning a hash."

$(".editable").editable("http://www.example.com/save.php";, {
   submitdata : {foo: "bar"};
});

So in your case you would just add the extra parameter "submitdata" like this:
submitdata : {x: x, y: y};

If the user clicks the OK button now, the values of x and y would be posted to the server.


text:
Q: How to set UICollectionView width programmatically I would like to set the width of an UICollectionView programmatically. I have tried to modify collectionView.frame and .bounds without success.
class CenterCellCollectionViewFlowLayout: UICollectionViewFlowLayout {
 override func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
   if let cv = self.collectionView {
     let cvBounds = cv.bounds
     let width = cvBounds.size.width //this is always 600, it should be 320
   }
 }
 return super.targetContentOffsetForProposedContentOffset(proposedContentOffset)
}

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
 @IBOutlet weak var collectionView: UICollectionView!
 override func viewDidLoad() {
   super.viewDidLoad()
   collectionView.frame = CGRectMake(collectionView.frame.origin.x, collectionView.frame.origin.y, self.view.frame.width, collectionView.frame.height)
   collectionView.bounds = CGRectMake(collectionView.bounds.origin.x, collectionView.bounds.origin.y, self.view.frame.width, collectionView.bounds.height)
   let width = collectionView.bounds.width //this is 320
   collectionView.reloadData()
 }
}

Storyboard

A: You should use NSLayoutConstraints:
https://developer.apple.com/library/ios/documentation/AppKit/Reference/NSLayoutConstraint_Class/
The reason you are getting an incorrect width is because you are setting it in viewDidLoad(). self.view has not been laid out at this point in the lifecycle. viewWillLayoutSubviews() is the lifecycle method you want to use, as it is called after self.view has been laid out and allows you to manually adjust any subview's (your UICollectionView) layout.

A: You are using self.view.frame.width when building your Rect, which means you are getting the width of your ViewController's view. This ViewController is probably taking the full screen, which means 320 pixels on an iPhone 4 or iPhone 5.


text:
Q: Google Sheet Advanced Search using Query function I'm trying to use Google Sheets to manage a database. I've figured out how to use the query function to do a simple search, but I'd like to know if an advanced search is possible. Here's what I mean:
Example I made (refer to the second sheet)
Each row has a number of attributes, and the search sheet has a number of fields that can be entered. I'd like to be able to search for one without having to keep the other fields filled in as well, but I'm not sure how to mess around with the query function to get what I need.
Any help would be very much appreciated. Thank you!

A: Where must only appear at the beginning of the filtering, not before every conditional.
This can be done with FILTER and some if statements or keep the query and adjust it similarly like this:
= IFERROR(
    query(
      Database!B3:G13,
      "select B,C,D,E,F,G
       where " &
         IF(LEN($C$4), "lower(C) contains lower('"&$C$4&"')", "1=1") & " and " &
         IF(LEN($E$4), "lower(D) contains lower('"&$E$4&"')", "1=1") & " and " &
         IF(LEN($G$4), "lower(E) contains lower('"&$G$4&"')", "1=1") & " and " &
         IF(LEN($I$4), "lower(F) contains lower('"&$I$4&"')", "1=1") & " and " &
         IF(LEN($K$4), "lower(G) contains lower('"&$K$4&"')", "1=1")),
    "No Results")

It essentially checks if the filter is specified and if not puts 1=1 (TRUE) as a placeholder.


text:
Q: Left-inducing a model structure from categories to relative categories One can left-induce a model structure from $\mathsf{Cat}$ to $\mathsf{RelCat}$ along the "homotopy category" functor. The weak equivalences are the relative functors which induce equivalences of homotopy categories, which is good. The cofibrations are the injective-on-objects relative functors, and the acyclic fibrations are the equivalences which are retracts in $\mathsf{RelCat}$. If I'm not mistaken, the existence of this model structure follows from the main result of Hess, Kedziorek, Riehl, and Shipley.
(In case it's not clear, $\mathsf{Cat}$ is the category of categories, $\mathsf{RelCat}$ is the category of relative categories (the "simplest" model of $\infty$-categories), and we're left-inducing the canonical model structure on $\mathsf{Cat}$ along the adjunction $h: \mathsf{RelCat} \overset{\to}{\leftarrow} \mathsf{Cat}: i$, where $iC$ is the relative category with underlying category $C$ with just the isomorphisms being weak equivalences and $hD$ is the homotopy category of the relative category $D$.)
In some ways, this model structure is charmingly simple, and it has the right weak equivalences, but I can't find mention of it in Barwick and Kan. I also don't know a good generating set of acyclic cofibrations, nor do I really understand fibrations. So a few questions:

*

*Is there a good reason why one shouldn't use this model structure?

*Is this model structure Quillen equivalent to the usual model structure on $\mathsf{RelCat}$, constructed by Barwick and Kan, i.e. to $\infty$-categories?

*Is there a good description of the acyclic cofibrations / fibrations in this model structure? For example, I would guess that an object is fibrant iff its weak equivalences are saturated in the sense that they are precisely the maps inverted upon passage to the homotopy category.


text:
Q: Efficient ways to filter unwanted data from a buffer in c++ Lets assume, data is stored in a character buffer in below format
===========================================================================
|length| message1| length| message2| length| message3|...|length |messagen|
===========================================================================

Length - indicates size of following message
From this character buffer, suppose only message2 is unwanted and rest all are relevant,
How efficiently, message2 can be removed so that rest all data in buffer can be used happily?
I have come accross, in-place algorithm, where we can shift the messages in the buffer itself without any additional copy
But with this also, there is an overhead of shifting (n-2) messages because message2 is irrelevant
Is there any better approach/ solution to it to do in c++?
Let me add more details-
Requirement here is need to remove/filter irrelevant data from the buffer and then pass it as input to another function for further processing
irrelevant data can come at any position in the character buffer. Just for example, referred as message 2

A: You don't say how many bits are in your length field, but assuming you can spare an extra bit to make the length-values signed rather than unsigned, I'd be tempted to adopt a convention that says "if a length-header has a negative value, that indicates that the its message-body is invalid and should be ignored".
Once you've adopted that convention, then flagging message 2 as invalid is just a matter of overwriting its length-header with the negation of its current value.
Of course, the code that is reading the buffer later on has to also follow the convention, so if e.g. if it sees a length-header with value of -57 then it should just skip ahead by 57 bytes without processing them.


text:
Q: How do I disable middle mouse click pasting clipboard? I am running Kubuntu 20.04.
I just noticed that clicking the middle mouse button pastes my clipboard; I don't like that.
I cannot find a way to disable this behaviour. I would like to keep middle mouse button click working, but disable the paste action.

A: Right-click somewhere on the desktop and choose Configure Desktop and Wallpaper... from the context menu. This will open the Desktop Folder Settings window. There you can configure the mouse actions:

A: The following solution globally disables paste on middle click for me while retaining all middle mouse button and clipboard functionality:
Follow the steps described in this answer, that is:

*

*Install xbindkeys xsel xdotool

*Place this in ~/.xbindkeysrc
"echo -n | xsel -n -i; pkill xbindkeys; xdotool click 2; xbindkeys"
b:2 + Release

*Reload xbindkeys -p

In step 2. you may need to remove the  + Release part as described in this post, depending on what works on your machine.
Set up xbindkeys to run on startup.
Then open Klipper, e.g. via the clipboard icon in the system tray > right click > Configure Clipboard. Uncheck the option 'Prevent empty clipboard'. Reboot and the problem should be solved.
The latter idea is thanks to milaq's XMousePasteBlock.

A: Steps for a solution:

*

*Identify the ID/IDs of your device with
xinput list

*Get the button map with
xinput get-button-map <ID>

*Set the button action
xinput set-button-map <ID> 1 <new action>

Repeat the last command for as many IDs as your mouse has. 1 stands for the mapping of left-click, then for middle click, etc.
Use for <new action> number 0 to disable middle-click, number 1 if you want to make it equivalent to left-click, etc.
There are other possible methods.
Related:

*

*Any updates on disabling middle-click paste?

*How do I disable middle mouse button click paste?

*Disable mouse middle button click paste on KDE, keeping that button working

*https://bbs.archlinux.org/viewtopic.php?id=100940

*https://www.reddit.com/r/kde/comments/7a71fa/disable_middleclick_paste_and_just_paste/

*Disabling middle mouse button


text:
Q: How do I run this cmd command in python I have a very specific command that I want to run during my python script:
"C:\Program Files\Some Folder\application.exe" /config:"C:\Program Files\Some Folder\my_config.ini"

Including the quotation marks.
my_config.ini is a a configuration file used to specify parameters for the application on startup.
The command works perfectly when I type it into cmd, but I cant get it work in vscode python ...
import os
# i have tried these
os.system('"C:\Program Files\Some Folder\application.exe" /config:"C:\Program Files\Some Folder\my_config.ini"')
os.system('"C:\Program Files\Some Folder\application.exe"' + ' /config:' + '"C:\Program Files\Some Folder\my_config.ini"')
os.system("C:\Program Files\Some Folder\application.exe /config:C:\Program Files\Some Folder\my_config.ini")

They all give this error:
'C:\Program' is not recognized as an internal or external command, operable program or batch file.

EDIT:
Given this question and answer:
os.system to invoke an exe which lies in a dir whose name contains whitespace
Im trying to use this code:
file = 'C:\\Program Files\\Some Folder\\application.exe'
 subprocess.call([file])

and this works! but I still cant figure out how to add the config file to it...


text:
Q: const formData = new FormData(); FromData is not working image didn't upload it seems undefined When i submit data from Formik.It didn't work  it seems undefined or image didn't upload to server.it Saved without image and other data uploaded
onSubmit={async (values, { resetForm }) => {

            const formData = new FormData();
              formData.append("supplier_name", values.supplier);
              formData.append("file", values.supplierImage[0]);
              formData.append("onboarded_date", moment(values.datepicker).format("YYYY-MM-DD"));
              formData.append("country", values.country);
              formData.append("zip_code", values.zip_code);
              formData.append("address_line_1", values.address_1);
              formData.append("address_line_2", values.address_2);

            console.log("values", values.supplierImage)
            if (!id) {
              await post(API_URL.SUPPLIER, formData)
                .then(res => {
                  if (res.data.status === "success") {
                    dispatch(setToast(res.data));
                    resetForm();
                    setError([]);
                    props.history.push("/supplier");
                  }
                })
                .catch(error => {
                  setError(error.data.detail);
                });
            }
          }}

backend response needed like this.our backend is used python django framework.Other data is saved to database but image didn't go to backend
Supplier{
id  integer
title: ID
readOnly: true
supplier_name*  string
title: Supplier name
maxLength: 255
minLength: 1
supplier_image  string($uri)
title: Supplier image
readOnly: true
x-nullable: true
onboarded_date* string($date)
title: Onboarded date
country*    string
title: Country
maxLength: 60
minLength: 1
zip_code*   string
title: Zip code
maxLength: 60
minLength: 1
address_line_1* string
title: Address line 1
maxLength: 60
minLength: 1
address_line_2* string
title: Address line 2
maxLength: 60
minLength: 1

}


text:
Q: How to compare the given integer with possible roots I could not name the question in the best way... My aim is to write a program that takes integer n from user. Then compare with the third power of two integers a and b.
If a^3 + b^3 is smaller than or equal to the given input, I want to print out every single possible calculation to the user.
My code is as follows:
        System.out.println("Hi. Please insert an integer: ");
        Scanner input = new Scanner(System.in);

        int n = input.nextInt();
        double root = Math.cbrt(n);
        int rootInt = (int) root;

        for (int i = 0; i < rootInt; i++){
            for (int j = 0; j < rootInt; j++){

                if ((Math.pow(i, 3)) + (Math.pow(j, 3)) <= n){

                    double t = (Math.pow(i, 3) + (Math.pow(j, 3)));
                    int totalInt = (int) t;

                    System.out.println(i + "^3" + " + " + j + "^3" + " = " + totalInt );

                } else {

                }
                j++;
            }
            i++;
        }

When I run this and give an input as 30, it prints
0^3 + 0^3 = 0
0^3 + 2^3 = 8
2^3 + 0^3 = 8
2^3 + 2^3 = 16

What am I doing wrong?

A: You increase j and i twice. That's why you test only the even values for i, j.
If you want to correct the code, remove the i++, j++ from the end and use only the increments from the 2 fors.


text:
Q: Как сделать уменьшение шрифта если текст не помещается TextBox WPF Как сделать "сжатие" текста, если он не помещается в поле.
Допустим у меня есть ТекстБокс для ввода ФИО, переносить нельзя, поэтому нужно сделать так, что бы при большом тексте, шрифт уменьшался

A: Чтобы не уродовать сам контрол и менять только размер шрифта в нем, можно написать простой конвертер:
class AdaptiveFontSizeConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        var textBox = (TextBox)values[0];
        var dpiX = 96.0 * VisualTreeHelper.GetDpi(textBox).DpiScaleX; // .NET 4.6.2+
        var formattedText =
            new FormattedText(
                textBox.Text,
                CultureInfo.InvariantCulture,
                textBox.FlowDirection,
                new Typeface(
                    textBox.FontFamily,
                    textBox.FontStyle,
                    textBox.FontWeight,
                    textBox.FontStretch),
                textBox.FontSize,
                textBox.Foreground,
                dpiX);
        var fontSize = textBox.FontSize * textBox.ViewportWidth / formattedText.Width;
        if (parameter == null) return fontSize;
        var maxSize = (double)parameter;
        return Math.Min(fontSize, maxSize);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        => throw new NotSupportedException();
}

Используем:
<Grid Margin="5" xmlns:s="clr-namespace:System;assembly=mscorlib">
    <Grid.Resources>
        <c:AdaptiveFontSizeConverter x:Key="conv"/>
    </Grid.Resources>
    <TextBox VerticalAlignment="Top">
        <TextBox.FontSize>
            <MultiBinding Converter="{StaticResource conv}">
                <MultiBinding.ConverterParameter>
                    <s:Double>12</s:Double>
                </MultiBinding.ConverterParameter>
                <Binding RelativeSource="{RelativeSource Self}"/>
                <Binding Path="Text" RelativeSource="{RelativeSource Self}"/>
            </MultiBinding>
        </TextBox.FontSize>
    </TextBox>
</Grid>

По сути сам конвертер принимает только ссылку на TextBox, но т.к. нам надо реагировать на изменение текста в нем, то делаем мультиконвертер и передаем ссылку на свойство Text вторым объектом (но в коде этот второй объект не используется). Дальше все просто — измеряем ширину текста внутри контрола и вычисляем конечный размер шрифта. Ну и добавил еще параметром возможность указания максимального размера шрифта, чтобы контрол не становился уж очень большим когда в нем мало символов.


text:
Q: Deploy vsix referenced dlls I have a visual studio extension project which uses some external library. More over that library uses another library which must be placed in the same folder with the exe file. (in our case it is Visual Studio folder. Folder where Visual Studio was installed.) So how I can deploy my vsix file? Exists there any ability to copy some external libriries in the Visual Studio folder or not?
First idea is to copy library dll in the first of the extension. But it is not very nice...


text:
Q: I have developed write Chinese in Anki. It is working in Anki but not working in Ankidroid It is working on AnkiDesktop but due to character encoding It is not working in Ankidroid. I have tried many solutions but It is failed to load.
In Anki Desktop character length is correct but in Ankidroid same character length is incorrect.
Ex:- '比如'
In Anki Desktop Length is 2,
In Ankidroid Length is 7
So may be there is error due to character encoding.
GitHub link to code
Image

A: Finally I have implemented it using existing js library HanziWriter.
https://github.com/infinyte7/Anki-xiehanzi


text:
Q: Creating a loading circle/wheel (similar to the one in ProgressDialog, but without the dialog) As you know, when using a ProgressDialog a "popup"/dialog appears in which a circle/wheel shows the progress.
I am interested in drawing this wheel out from the dialog box, and only displaying this wheel, still indicating progress.
Main reason to want this, is the fact that I have some sort of "intro screen" which will show a logo and this progress wheel just below, which indicates that the application is loading various content.
This is (or could be) the wheel in question:

It wouldn't hurt if the wheel could be smaller than it appears in a regular ProgressDialog.
(I'm using AsyncTask to load the content while this wheel is displayed.)
Any suggestions?

A: You can use the pre-defined style Android provides for an indeterminate ProgressBar, like this:
<ProgressBar
    style="?android:attr/progressBarStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
/>

If you want it to be smaller, use the progressBarStyleSmall style instead.
From here you can set the visibility of the ProgressBar to make it appear/disappear whenever you want.

A: Have you considered using a ProgressBar and setting setIndeterminate(true);


text:
Q: Android PackageInstaller not installing APK Hello StackOverflow users,
i have an Android app outside of the Play Store. It updates itself by downloading a new APK and invoking the installer dialog using an Intent. The update functionality does not work anymore on Android 10.
I need to use the PackageInstaller API on Android 10 now, but i can't get it to work. My app is not a device or profile owner, but since i don't want a silent install so i think it should be fine.
My problem is that as soon as i commit the session absolutely nothing happens.
PackageInstaller installer = activity.PackageManager.PackageInstaller;
PackageInstaller.SessionParams sessionParams = new PackageInstaller.SessionParams(PackageInstallMode.FullInstall);
int sessionId = installer.CreateSession(sessionParams);
PackageInstaller.Session session = installer.OpenSession(sessionId);

var input = new FileStream(pfad, FileMode.Open, FileAccess.Read);
var packageInSession = session.OpenWrite("package", 0, -1);
input.CopyTo(packageInSession);
packageInSession.Close();
input.Close();

//That this is necessary could be a Xamarin bug.
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();

Intent intent = new Intent(activity, activity.Class);
intent.SetAction("com.example.android.apis.content.SESSION_API_PACKAGE_INSTALLED");
PendingIntent pendingIntent = PendingIntent.GetActivity(activity, 0, intent, 0);
IntentSender statusReceiver = pendingIntent.IntentSender;

// Commit the session (this will start the installation workflow).
session.Commit(statusReceiver);

I took a look at the DDMS and got nothing relevant out of it. One thing that might be of interest is that when i Dispose() the streams, i get an IOException: write failed (EBADF) bad file descriptor which would indicate a bad APK. But i doubt it's that because i can install the APK using a file manager without a hitch. Googling the error didn't lead me anywhere.
How can i fix this problem?

A: There are a couple of things you need to make sure in order for the apk installation to succeed in Android Q:

*

*Do not use using statements or try to dispose anything inside the AddApkToInstallSession method. The Dispose causes the installation to fail. Use try/finally and close instead:

private static void AddApkToInstallSession(Context context, Android.Net.Uri apkUri, PackageInstaller.Session session)
{
  var packageInSession = session.OpenWrite("package", 0, -1);
  var input = context.ContentResolver.OpenInputStream(apkUri);

  try
  {
      if (input != null)
      {
          input.CopyTo(packageInSession);
      }
      else
      {
          throw new Exception("Inputstream is null");
      }
  }
  finally
  {
      packageInSession.Close();
      input.Close();
  }

  //That this is necessary could be a Xamarin bug.
  GC.Collect();
  GC.WaitForPendingFinalizers();
  GC.Collect();
}

*

*You must override the "OnNewIntent" method because you need an intent to confirm the installation of the APK file:

protected override void OnNewIntent(Intent intent)
{
    Bundle extras = intent.Extras;
    if (PACKAGE_INSTALLED_ACTION.Equals(intent.Action))
    {
        var status = extras.GetInt(PackageInstaller.ExtraStatus);
        var message = extras.GetString(PackageInstaller.ExtraStatusMessage);
        switch (status)
        {
            case (int)PackageInstallStatus.PendingUserAction:
                // Ask user to confirm the installation
                var confirmIntent = (Intent)extras.Get(Intent.ExtraIntent);
                StartActivity(confirmIntent);
                break;
            case (int)PackageInstallStatus.Success:
                //TODO: Handle success
                break;
            case (int)PackageInstallStatus.Failure:
            case (int)PackageInstallStatus.FailureAborted:
            case (int)PackageInstallStatus.FailureBlocked:
            case (int)PackageInstallStatus.FailureConflict:
            case (int)PackageInstallStatus.FailureIncompatible:
            case (int)PackageInstallStatus.FailureInvalid:
            case (int)PackageInstallStatus.FailureStorage:
                //TODO: Handle failures
                break;
        }
    }
}

*

*The Activity where you override the "OnNewIntent" method must have LaunchMode set to LaunchMode.SingleTop

*The user must have given the application from which you try to install the APK file the necessary permissions to install APK's. You can check if this is the case by calling PackageManager.CanRequestPackageInstalls(). If this function returns false, you can open the application options window by using this code:

StartActivity(new Intent(
            Android.Provider.Settings.ActionManageUnknownAppSources,
            Android.Net.Uri.Parse("package:" + Android.App.Application.Context.PackageName)));

so the user can easily set the switch to enable this.

*

*This is my main method to initialize the APK installation:

public void InstallPackageAndroidQAndAbove(Android.Net.Uri apkUri)
{
    var packageInstaller = PackageManager.PackageInstaller;
    var sessionParams = new PackageInstaller.SessionParams(PackageInstallMode.FullInstall);
    int sessionId = packageInstaller.CreateSession(sessionParams);
    var session = packageInstaller.OpenSession(sessionId);

    AddApkToInstallSession(apkUri, session);

    // Create an install status receiver.
    var intent = new Intent(this, this.Class);
    intent.SetAction(PACKAGE_INSTALLED_ACTION);
    var pendingIntent = PendingIntent.GetActivity(this, 0, intent, 0);
    var statusReceiver = pendingIntent.IntentSender;

    // Commit the session (this will start the installation workflow).
    session.Commit(statusReceiver);
}

*

*If you are debugging on a Xiaomi device, you must disable MIUI Optimizations under developer options. Otherwise the installation will fail with permission denied error.


text:
Q: Setting delegate for custom protocol interferes with UIScrollViewDelegate methods I'm using a custom subclass of UIScrollView called ImageScrollView. I need to know when the user taps the scroll view, so I created a protocol. I implement the protocol in my RootViewController and everything looks ok. When I build it, theres a warning

Class 'ImageScrollView' does not implement the 'TapDetectingImageViewDelegate' protocol".

After inspecting the init method in the ImageScrollView class, I see that self.delegate = self; is causing the problem. I declare myself the delegate for the UIScrollView delegate methods, but I also am the delegate for my own protocol (Delegate for my protocol must be RootViewController, not ImageScrollView).
- (id)initWithFrame:(CGRect)frame{
      if ((self = [super initWithFrame:frame])) {
         self.showsVerticalScrollIndicator = NO;
         self.showsHorizontalScrollIndicator = NO;
         self.bouncesZoom = YES;
         self.decelerationRate = UIScrollViewDecelerationRateFast;
         self.delegate = self;
      }
      return self;
 }

Do you guys know how can I solve that? Or a better idea to tell my RootViewController that user has tapped the UIScrollView/UIImage.
Declaration of protocol in ImageScrollView.h
@protocol TapDetectingImageViewDelegate <NSObject>

@optional
- (void)tapDetectingImageView:(ImageScrollView *)view gotSingleTapAtPoint:(CGPoint)tapPoint;

@end

Header file of class that implements it
#import <UIKit/UIKit.h>
#import "ImageScrollView.h"

@interface AppleScrollViewViewController : UIViewController <UIScrollViewDelegate, TapDetectingImageViewDelegate>{

    UIScrollView *pagingScrollView;
}

-(void)configurePage:(ImageScrollView *)page forIndex:(NSUInteger)index;
- (CGRect)frameForPageAtIndex:(NSUInteger)index;
- (CGRect)frameForPagingScrollView;
- (UIImage *)imageAtIndex:(NSUInteger)index;
- (NSString *)imageNameAtIndex:(NSUInteger)index;
- (CGSize)imageSizeAtIndex:(NSUInteger)index;
- (NSArray *)imageData;

@end

Protocol method in .m class that implements it
-(void)tapDetectingImageView:(ImageScrollView *)view gotSingleTapAtPoint:(CGPoint)tapPoint{
    NSLog(@"SingleTap");
}

A: You will be having an declaration of RootViewController delegate in the .h file of ImageScrollView,
Change the name of root delegate to rootDelegate ;
In ImageScrollView.h
  RootViewControllerDelegate* rootDelegate;
  @property(nonatomic,assign) RootViewControllerDelegate* rootDelegate;

in ImageScrollView.m file
@synthesize rootDelegate;
- (id)initWithFrame:(CGRect)frame{
      if ((self = [super initWithFrame:frame])) {
         self.showsVerticalScrollIndicator = NO;
         self.showsHorizontalScrollIndicator = NO;
         self.bouncesZoom = YES;
         self.decelerationRate = UIScrollViewDecelerationRateFast;
         self.delegate = self;
         // Root controller delegate.
         self.rootDelegate = self;
      }
      return self;
 }

A: If you want the view controller to be its delegate, then don't set the delegate within the initializer. When you're creating the ImageScrollView instance, you should set it to the view controller.
ImageScrollView * aScrollView = [[ImageScrollView alloc] initWithFrame:aFrame];
aScrollView.delegate = self;
[..]

If you are creating it this via IB i.e. renaming the class name of a UIScrollView to ImageScrollView, you will have to create an outlet for it and then set the delegate in the viewDidLoad method of the view controller.
However, there is an issue with this approach. If ImageScrollView is the subclass of a UIScrollView as the name suggests, the delegate property of the scroll view is lost. You should take that into consideration as well.


text:
Q: How to tell whether your controller action was given parameters? I am trying to determine whether my controller action was called with parameters or not, without hardcoding which parameters can be added on.
So I want to distinguish between
/my_controller

and
/my_controller?q=1

I know that I could look inside the params hash, and check whether it ONLY contains :controller and :action keys. This seems ugly to me, is there a smarter way of doing this check?

A: There is one direct solution:
request.env["QUERY_STRING"] # => "q=1"

Or with Ruby 1.9.2:
request.env.QUERY_STRING # => "q=1"

A: For GET request you can use request.query_parameters method. There is also request.request_parameters for POST requests.
Results for request.query_parameters.inspect are:

*

*for '/my_controller' => '{}'

*for '/my_controller?q=1' => {"q"=>"1"}


text:
Q: How to change the colour of a "cell" in a grid Apologies for a second post so soon but I am having trouble trying to change the color of a rectangle inside of a nested for loop.
When I click on a "cell" I want the stroke to change to (255,0,0) Inside my mouseClicked function I have already found a way thanks to this community to determine a number based on where I clicked. For example the top left cell is 0 and then it goes up by 1 and continues down the rows 12345678(new row)9 10 11 12 etc.
I have included my grid and my mouse clicked function.
final int COLUMNS = 8;
final int ROWS = 12;

int cellNumber;
int tileSize = 30;
int ellipseSize = 20;
int ellipseSpacing = 10;
int numMoves;
int selectedCell;
int targetX;
int targetY;
int randomTarget;
int gridX;
int gridY;
int score = 0;
int clickX;
int clickY;
int col;
int row;
boolean mouseoverColour = false;

void setup(){
  size (700,500);
  background(0);
  //drawTarget();
}

void draw(){
  drawColourgrid();
}

void drawColourgrid(){
   for(int i = 0; i < COLUMNS*tileSize; i+=tileSize){
     for(int j = 0; j < ROWS*tileSize; j+=tileSize){
       noFill();
       stroke(255);
       rect(i + 100,j + 60,tileSize,tileSize);
     }
   }
//fill(255);
//rect(100,60,240,360);
}

void mouseClicked(){
    if (mouseX >= 100 && mouseX <= 100+COLUMNS*tileSize && mouseY >= 60 && mouseY <= 60+ROWS*tileSize){
        mouseoverColour = true;
        col = (mouseX - 100) / tileSize;
        row = (mouseY - 60) / tileSize;
        cellNumber = row * COLUMNS + col;
        println(cellNumber);
    } else {
        cellNumber = -1;
        println(cellNumber);
    }
}

A: I made 3 changes to your code to implement the "selection mechanic" you described:

*

*initializing cellNumber to -1 (to avoid a false positive at start)

*adding background(0); to the draw() loop to "reset" the grid so the selected cells stops looking like they have are being selected

*drawing the red selected cell in drawColourgrid()
I modified the code the lest I could, so it stays your code. I recently helped one of your classmates, you might want to look into it.
Here's your modified code (with appropriate comments):
final int COLUMNS = 8;
final int ROWS = 12;

//initializing cellNumber to -1 to avoid a false positive at start
int cellNumber = -1;
int tileSize = 30;
int ellipseSize = 20;
int ellipseSpacing = 10;
int numMoves;
int selectedCell;
int targetX;
int targetY;
int randomTarget;
int gridX;
int gridY;
int score = 0;
int clickX;
int clickY;
int col;
int row;
boolean mouseoverColour = false;

void setup(){
  size (700,500);
  background(0);
  //drawTarget();
}

void draw(){
  //background to "erase" old selected cells when they are not selected
  background(0);
  drawColourgrid();
}

void drawColourgrid(){
  int selectedColumn = -1;
  int selectedRow = -1;

  if (cellNumber > -1) {
    selectedColumn = cellNumber % COLUMNS;
    selectedRow = cellNumber / COLUMNS;
  }

   for(int i = 0; i < COLUMNS*tileSize; i+=tileSize){
     for(int j = 0; j < ROWS*tileSize; j+=tileSize){
       noFill();
       stroke(255);
       rect(i + 100,j + 60,tileSize,tileSize);
     }
   }

   //this calculate which cell is selected and fill it with red
   if (selectedColumn > -1) {
     fill(255, 0, 0);
     stroke(255);
     rect((selectedColumn * tileSize) + 100, (selectedRow * tileSize) + 60,tileSize,tileSize);
   }
}

void mouseClicked(){
    if (mouseX >= 100 && mouseX <= 100+COLUMNS*tileSize && mouseY >= 60 && mouseY <= 60+ROWS*tileSize){
        mouseoverColour = true;
        col = (mouseX - 100) / tileSize;
        row = (mouseY - 60) / tileSize;
        cellNumber = row * COLUMNS + col;
        println(cellNumber);
    } else {
        cellNumber = -1;
        println(cellNumber);
    }
}

Have fun!


text:
Q: Noisy loss in distributed training in tensorflow I am working on distributed learning in tensorflow through estimators API, and I always get below training loss graphs in tensorboard when comparing one-machine configuration (one ps and one chief on the same machine) and two-machine configuration (one ps and one chief on machine#1, one worker on machine#2).

Also when I download the graph data, I see that some steps are lost in two-machine distributed training case.
My model is defined in keras and I use the standard estimator functions for distributed training using dataset API in the following format (read_dataset is a custom function with generates training or evaluation dataset):
runConfig = tf.estimator.RunConfig(
        session_config=config,
        model_dir=log_dir,
        save_summary_steps=1,
        save_checkpoints_steps=train_steps
        )
estimator = tf.keras.estimator.model_to_estimator(model, model_dir=log_dir, config=runConfig)
train_spec = tf.estimator.TrainSpec(input_fn=lambda: read_dataset(...), max_steps=...)
eval_spec = tf.estimator.EvalSpec(input_fn=lambda: read_dataset(...), start_delay_secs=1, throttle_secs=1, steps=None)
tf.estimator.train_and_evaluate(estimator, train_spec, eval_spec)

What can be the cause for this noisy behavior and missing logs?
And another question: I assume that the above code implements data parallelism, in which input dataset is splitted between different machines and so each sample is used once during training but possibly by a different machine. Is it true? I am using Tensorflow 1.12 and 1.13.


text:
Q: Access server path of web site from within assembly library If I have an assembly library (dll) that is referenced from within an ASP.NET MVC app, is it possible for the assembly to get to the server path without having to pass it in from the MVC app, or have access to HttpContext?
If I use a relative path, it will return the processes path. In the case of running locally in debug, it is:

C:\Program Files\IIS Express

However, the file lives in the bin output, with this DLL, and the rest of the site's binaries.
Is my only choice to pass the path in from the web app?
UPDATE
For now, I'm just using HttpContext.Current.Server.MapPath(), but I don't like having to use HttpContext, in the event that we consume this API from something other than a web app.

A: To get the IIS server path that holds the web site you need HttpContext.Request.FilePath.
I pass the HttpContext into my library function, when I need to know where the web site is located.
However if you want to know the DLL's installed location, then I have seen it done using Assembly.Location


text:
Q: TFS Installation I setup TFS today on my machine and whenever I try to go to the web access it keeps asking me for a username and password. It also prompts me for one when I try to administer security in the application tier.
I didn't select a username and password when I set this up and I tried my machines username and password but it won't work. To top it off, my machine does not have a password and it keeps telling me i have to enter a password.
Is there a default password or login that I need to know about?

A: TFS only works with accounts that have a password.

A: Also, TFS only works with domain accounts, not machine accounts.

A: I'm having a similar problem in Windows 8. I was unable to get it to work in Chrome (my default browser) but I was able to sign in through IE 10 using the same Live ID credentials used to log into the PC.


text:
Q: First setting a SESSION variable through ajax, and then using it upon visiting page I want to POST a string across domains by using AJAX and CORS after a mouse click, and when the POST is successful use that string as a SESSION variable. When ajax fires the done() event, I then want to open a new tab to the domain we posted to earlier and use the SESSION variable.
What I want to achieve, summarised

*

*a user is on site A

*site A does a POST request to page A on site B where it wants to post a string to

*page A on site B stores the string in a SESSION variable

*upon success the browser opens a new tab to page B on site B

*page B on site B looks for the SESSION variable and uses it if present

Even though I was initially planning on solving this with a SharedWorker support does not seem to be quite right for it. Just using a URL parameter / a GET is not possible either because I fear that the size of the data can get too long.
What I have
php/receive-post.php on domain B
<?php
    $origin = $_SERVER['HTTP_ORIGIN'];

    if ($origin == 'http://site.a.com') {
        header('Access-Control-Allow-Origin: '.$origin);
        header('Access-Control-Allow-Methods: POST');
        header('Access-Control-Max-Age: 1000');
        header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With, Cache-Control');

        if (isset($_POST)) {
          session_start();
          $_SESSION['string'] = $_POST['string'];
          echo json_encode($_SESSION['string']);
          session_write_close();
        }
    }

Relevant code from index.php on domain B
<?php
    $string;
    session_start();
    var_dump($_SESSION);
    if (isset($_SESSION['string'])):
        $string= $_SESSION['string'];
    else:
        $string= 'I like bananas';
    endif;
    session_write_close();
    echo $string;
?>

And the script from domain A (jQuery)
$("a").click(function(e) {
  e.preventDefault();
  var href = $(this).attr('href');
  postString($("textarea").serialize(), href);
});

function postString(myString, href) {
  $.ajax({
    type: 'POST',
    url: 'http://domain.a.com/receive-post.php',
    crossDomain: true,
    data: myString,
    headers: {
      'cache-control':' no-cache'
    }
  }).done(function(data) {
    console.log(data);
  }).fail(function(a, b, c) {
    console.log(a + b + c);
  }).always(function() {
    console.log("always");
    var newTab = window.open(href, '_blank');
    if (newTab) {
      newTab.focus();
    } else {
      alert('Your browser blocked opening a new window.');
    }
  });
}

What happens
What should happen is that after clicking the link on domain A, a new tab is opened and de SESSION variable is used on there. However, this is not what happens.
The POSTing of the data works, as I can verify in console on domain B that the returned value of the SESSION variable is indeed set. The new tab is also opened. However, the SESSION variable is not used/set on that page. A var_dump($_SESSION) returns an empty array, meaning that there are no SESSION variables set.
Why is that? Why isn't the SESSION variable carried from page A to page B on domain B? And how do I make it usable?

A: You need to add withCredentials (see jQuery.ajax docs, xhrFields), otherwise cookies won't be send/accepted for cross-domain requests.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials:

The XMLHttpRequest.withCredentials property is a Boolean that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. […] In addition, this flag is also used to indicate when cookies are to be ignored in the response.

And as you said, Access-Control-Allow-Credentials: true needs to be added to the response from the remote domain, to tell that browser that it is allowed to include credentials in cross-domain requests to this URL.


text:
Q: TypeORM import of Relation fails I am using typeorm in a nodejs project with esm. I need to use the Relation wrapper to avoid circular dependencies.
I get this error when i try to use the relation wrapper:
import { Column, Entity, OneToOne, PrimaryGeneratedColumn, Relation } from 'typeorm';
                                                           ^^^^^^^^
SyntaxError: The requested module 'typeorm' does not provide an export named 'Relation'

The code file:
import { Column, Entity, OneToOne, PrimaryGeneratedColumn, Relation } from 'typeorm';
import { Vehicle } from './vehicle';

@Entity({ name: 'vehicle_default_values' })
export class VehicleDefaultValues {
    @PrimaryGeneratedColumn({ unsigned: true })
    id: number;

    @Column({ type: 'int', unsigned: true, unique: true })
    model: number;

    @Column({ type: 'float', default: 550 })
    maxFuel: number;

    @Column({ type: 'boolean', default: false })
    isElectric: boolean;

    @Column({ type: 'float', default: 0.008 })
    fuelConsumption: number;

    @Column({ type: 'mediumint', unsigned: true, default: 200 })
    maxSpeed: number;

    @Column({ type: 'mediumint', unsigned: true, default: 50 })
    trunkVolume: number;

    @Column({ type: 'text', nullable: true })
    vehicleExtras: string;

    @OneToOne(() => Vehicle, (vehicle) => vehicle.vehicleDefaultValues)
    vehicle: Relation<Vehicle>;
}

Used version of typeorm: 0.3.7


text:
Q: When I try to update the order, it changes the total amout to 0 I have added new custom order status to Woo Commerce by using following function.
Register New Order Statuses
function wpex_wc_register_post_statuses() {
    register_post_status( 'wc-shipping-progress', array(
        'label'                     => _x( 'Shipping In Progress', 'WooCommerce Order status', 'text_domain' ),
        'public'                    => true,
        'exclude_from_search'       => false,
        'show_in_admin_all_list'    => true,
        'show_in_admin_status_list' => true,
        'label_count'               => _n_noop( 'Approved (%s)', 'Approved (%s)', 'text_domain' )
    ) );
}
add_filter( 'init', 'wpex_wc_register_post_statuses' );

Add New Order Statuses to WooCommerce
function wpex_wc_add_order_statuses( $order_statuses ) {
    $order_statuses['wc-shipping-progress'] = _x( 'Shipping In Progress', 'WooCommerce Order status', 'text_domain' );
    return $order_statuses;
}
add_filter( 'wc_order_statuses', 'wpex_wc_add_order_statuses' );

whenever I go to edit order and changed the order status to newly added custom order status and click on Save Order button, and go back to Orders it shows Total "0"...

*

*Can anyone please help me to fix this issue?


text: Q: Proof that $\mathbb{Q} \subseteq \{\frac{3m}{7n}\| m\in\mathbb{Z},n\in \mathbb{N}\}$ It seems to me that the statement is true and I thought about prooving it by showing that if you take any rational number of form $\frac{a}{b}$ you can cross multiply it with $\frac{3m}{7n}$ and get $7an=3bm$ you can always find a solution to the expression and it means that $\mathbb{Q}$ is a subset of the group. However I struggle to formalize my proof.


text:
Q: Sending files to email id? I am trying to send files from a specific folder inside sdcard "VCFFiles". I did all things correctly. It worked once but again when I run this app its showing force close.What I did in my project is I made 5 radiobuttons and text them as the files are listed inside "VCFFiles" folder. Whan anyradiobutton will be clicked, respective vcf file will be sent to the email entered in the edittext on clicking send button.following is my code:
public class SendActivity extends Activity{
    private static final int PICK_IMAGE = 1;
    EditText email;
    TextView add_manage;
    Button send;
    RadioGroup vcfgroup;
    RadioButton vcfButton;
    String filepath="";
    static File filevcf;
    static Context mContext;
    RadioButton vcf1;
    RadioButton vcf2;
    RadioButton vcf3;
    RadioButton vcf4;
    RadioButton vcf5;
    ProgressDialog dialog;
    String success;
    String message;
    String response;
    String data;
    File f;
    String radio;
    ArrayList<String> array;
//  String state = Environment.getExternalStorageState();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.send);

        email = (EditText)findViewById(R.id.emailid);
        send = (Button)findViewById(R.id.send);
        add_manage = (TextView)findViewById(R.id.add_manage);
        vcfgroup = (RadioGroup)findViewById(R.id.vcfgroup);
        vcf1 = (RadioButton)findViewById(R.id.vcf1);
        vcf2 = (RadioButton)findViewById(R.id.vcf2);
        vcf3 = (RadioButton)findViewById(R.id.vcf3);
        vcf4 = (RadioButton)findViewById(R.id.vcf4);
        vcf5 = (RadioButton)findViewById(R.id.vcf5);
        send = (Button)findViewById(R.id.send);
        // get selected radio button from radioGroup

        radio = vcf1.getText().toString();

        //get file names and set it in radio buttons
        if(!isExternalStorageAvailable() || isExternalStorageReadOnly()){

        }else{
        new EventListTask2().execute(this);
        }
        //send vcf files to the server
        send.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                int selectedId = vcfgroup.getCheckedRadioButtonId();

                vcf1 =(RadioButton)findViewById(selectedId);
                try{
                    f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/VCFFiles/"+vcf1.getText().toString());
                    filepath = f.getPath();

                if(email.getText().length()!=0){
                    dialog = ProgressDialog.show(SendActivity.this,
                            "Sending", "Please wait...", true);
                    new EventListTask1().execute();
                }else{
                    Toast.makeText(getApplicationContext(), "You may have not entered emailid or selected wrong file!!", Toast.LENGTH_LONG).show();
                }
                }catch(Exception e){

                }
            }
        });

        add_manage.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                Intent in = new Intent(SendActivity.this,AddContactActivity.class);
                startActivity(in);
            }
        });

    }

    public ArrayList<String> GetFiles() {
        ArrayList<String> MyFiles = new ArrayList<String>();
        File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/VCFFiles");

        f.mkdirs();
        File[] files = f.listFiles();
        if (files.length == 0)
            return null;
        else {
            for (int i=0; i<5; i++)
                if(files[i].getPath().endsWith(".vcf")){
                MyFiles.add(files[i].getName());
                }
        }

        return MyFiles;
    }

inside EventListTask2 class I am fetching files from "VCFFIles" using GetFiles() function and associating the name with each radiobutton's name.The code inside is shown below:
RadioButton radioset[] = {vcf1, vcf2, vcf3, vcf4, vcf5};
                if(GetFiles().size()!=0){
                array=GetFiles();
                for(int i=0;i<array.size();i++){
                    radioset[i].setText(array.get(i));
                }}else{
                    Toast.makeText(getApplicationContext(), "You have no vcf files saved", Toast.LENGTH_LONG).show();
                }

Following is log of the app:
03-18 18:41:17.410: E/AndroidRuntime(1598): FATAL EXCEPTION: main
03-18 18:41:17.410: E/AndroidRuntime(1598): java.lang.NullPointerException
03-18 18:41:17.410: E/AndroidRuntime(1598):     at com.example.mycontactdetails.SendActivity$EventListTask1.onPostExecute(SendActivity.java:321)
03-18 18:41:17.410: E/AndroidRuntime(1598):     at com.example.mycontactdetails.SendActivity$EventListTask1.onPostExecute(SendActivity.java:1)
03-18 18:41:17.410: E/AndroidRuntime(1598):     at android.os.AsyncTask.finish(AsyncTask.java:417)
03-18 18:41:17.410: E/AndroidRuntime(1598):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
03-18 18:41:17.410: E/AndroidRuntime(1598):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
03-18 18:41:17.410: E/AndroidRuntime(1598):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-18 18:41:17.410: E/AndroidRuntime(1598):     at android.os.Looper.loop(Looper.java:123)
03-18 18:41:17.410: E/AndroidRuntime(1598):     at android.app.ActivityThread.main(ActivityThread.java:4627)
03-18 18:41:17.410: E/AndroidRuntime(1598):     at java.lang.reflect.Method.invokeNative(Native Method)
03-18 18:41:17.410: E/AndroidRuntime(1598):     at java.lang.reflect.Method.invoke(Method.java:521)
03-18 18:41:17.410: E/AndroidRuntime(1598):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-18 18:41:17.410: E/AndroidRuntime(1598):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-18 18:41:17.410: E/AndroidRuntime(1598):     at dalvik.system.NativeStart.main(Native Method)
03-18 18:53:12.560: E/IOException(1648): IO error: /mnt/sdcard/VCFFiles/Empty (Permission denied)
03-18 18:53:12.560: E/IOException(1648): java.io.FileNotFoundException: /mnt/sdcard/VCFFiles/Empty (Permission denied)
03-18 18:53:12.560: E/IOException(1648):    at org.apache.harmony.luni.platform.OSFileSystem.openImpl(Native Method)
03-18 18:53:12.560: E/IOException(1648):    at org.apache.harmony.luni.platform.OSFileSystem.open(OSFileSystem.java:152)
03-18 18:53:12.560: E/IOException(1648):    at java.io.FileInputStream.<init>(FileInputStream.java:82)
03-18 18:53:12.560: E/IOException(1648):    at com.example.mycontactdetails.SendActivity$Utils.PostDataToFavoriteUser(SendActivity.java:182)
03-18 18:53:12.560: E/IOException(1648):    at com.example.mycontactdetails.SendActivity$EventListTask1.doInBackground(SendActivity.java:310)
03-18 18:53:12.560: E/IOException(1648):    at com.example.mycontactdetails.SendActivity$EventListTask1.doInBackground(SendActivity.java:1)
03-18 18:53:12.560: E/IOException(1648):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-18 18:53:12.560: E/IOException(1648):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-18 18:53:12.560: E/IOException(1648):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-18 18:53:12.560: E/IOException(1648):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
03-18 18:53:12.560: E/IOException(1648):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
03-18 18:53:12.560: E/IOException(1648):    at java.lang.Thread.run(Thread.java:1096)
03-18 18:53:12.630: E/AndroidRuntime(1648): FATAL EXCEPTION: main
03-18 18:53:12.630: E/AndroidRuntime(1648): java.lang.NullPointerException
03-18 18:53:12.630: E/AndroidRuntime(1648):     at com.example.mycontactdetails.SendActivity$EventListTask1.onPostExecute(SendActivity.java:321)
03-18 18:53:12.630: E/AndroidRuntime(1648):     at com.example.mycontactdetails.SendActivity$EventListTask1.onPostExecute(SendActivity.java:1)
03-18 18:53:12.630: E/AndroidRuntime(1648):     at android.os.AsyncTask.finish(AsyncTask.java:417)
03-18 18:53:12.630: E/AndroidRuntime(1648):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
03-18 18:53:12.630: E/AndroidRuntime(1648):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
03-18 18:53:12.630: E/AndroidRuntime(1648):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-18 18:53:12.630: E/AndroidRuntime(1648):     at android.os.Looper.loop(Looper.java:123)
03-18 18:53:12.630: E/AndroidRuntime(1648):     at android.app.ActivityThread.main(ActivityThread.java:4627)
03-18 18:53:12.630: E/AndroidRuntime(1648):     at java.lang.reflect.Method.invokeNative(Native Method)
03-18 18:53:12.630: E/AndroidRuntime(1648):     at java.lang.reflect.Method.invoke(Method.java:521)
03-18 18:53:12.630: E/AndroidRuntime(1648):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-18 18:53:12.630: E/AndroidRuntime(1648):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-18 18:53:12.630: E/AndroidRuntime(1648):     at dalvik.system.NativeStart.main(Native Method)
03-18 19:00:13.010: E/IOException(1676): IO error: /mnt/sdcard/VCFFiles/Empty (Permission denied)
03-18 19:00:13.010: E/IOException(1676): java.io.FileNotFoundException: /mnt/sdcard/VCFFiles/Empty (Permission denied)
03-18 19:00:13.010: E/IOException(1676):    at org.apache.harmony.luni.platform.OSFileSystem.openImpl(Native Method)
03-18 19:00:13.010: E/IOException(1676):    at org.apache.harmony.luni.platform.OSFileSystem.open(OSFileSystem.java:152)
03-18 19:00:13.010: E/IOException(1676):    at java.io.FileInputStream.<init>(FileInputStream.java:82)
03-18 19:00:13.010: E/IOException(1676):    at com.example.mycontactdetails.SendActivity$Utils.PostDataToFavoriteUser(SendActivity.java:183)
03-18 19:00:13.010: E/IOException(1676):    at com.example.mycontactdetails.SendActivity$EventListTask1.doInBackground(SendActivity.java:311)
03-18 19:00:13.010: E/IOException(1676):    at com.example.mycontactdetails.SendActivity$EventListTask1.doInBackground(SendActivity.java:1)
03-18 19:00:13.010: E/IOException(1676):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
03-18 19:00:13.010: E/IOException(1676):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
03-18 19:00:13.010: E/IOException(1676):    at java.util.concurrent.FutureTask.run(FutureTask.java:137)
03-18 19:00:13.010: E/IOException(1676):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1068)
03-18 19:00:13.010: E/IOException(1676):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:561)
03-18 19:00:13.010: E/IOException(1676):    at java.lang.Thread.run(Thread.java:1096)
03-18 19:00:13.090: E/AndroidRuntime(1676): FATAL EXCEPTION: main
03-18 19:00:13.090: E/AndroidRuntime(1676): java.lang.NullPointerException
03-18 19:00:13.090: E/AndroidRuntime(1676):     at com.example.mycontactdetails.SendActivity$EventListTask1.onPostExecute(SendActivity.java:322)
03-18 19:00:13.090: E/AndroidRuntime(1676):     at com.example.mycontactdetails.SendActivity$EventListTask1.onPostExecute(SendActivity.java:1)
03-18 19:00:13.090: E/AndroidRuntime(1676):     at android.os.AsyncTask.finish(AsyncTask.java:417)
03-18 19:00:13.090: E/AndroidRuntime(1676):     at android.os.AsyncTask.access$300(AsyncTask.java:127)
03-18 19:00:13.090: E/AndroidRuntime(1676):     at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:429)
03-18 19:00:13.090: E/AndroidRuntime(1676):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-18 19:00:13.090: E/AndroidRuntime(1676):     at android.os.Looper.loop(Looper.java:123)
03-18 19:00:13.090: E/AndroidRuntime(1676):     at android.app.ActivityThread.main(ActivityThread.java:4627)
03-18 19:00:13.090: E/AndroidRuntime(1676):     at java.lang.reflect.Method.invokeNative(Native Method)
03-18 19:00:13.090: E/AndroidRuntime(1676):     at java.lang.reflect.Method.invoke(Method.java:521)
03-18 19:00:13.090: E/AndroidRuntime(1676):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-18 19:00:13.090: E/AndroidRuntime(1676):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-18 19:00:13.090: E/AndroidRuntime(1676):     at dalvik.system.NativeStart.main(Native Method)

I am not getting what's going wrong? Any help would be grateful.


text:
Q: Popup menu using ABS Is it possible to have POPUP menu like play store attached to each row of adapter
what i done so far
holder.rl_overflow.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                PopupMenu popup = new PopupMenu(context, holder.rl_overflow);
                popup.getMenuInflater().inflate(R.menu.overflow, popup.getMenu());

                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        Toast.makeText(context,"You Clicked : " + item.getTitle(),Toast.LENGTH_SHORT).show();
                        return false;
                    }
                });
                popup.show();

            }
        });

but constructor for POPUP menu says its available from API 11. I go through the developers.android.com and i found, its can be added using SUPPORT V7 library "https://developer.android.com/reference/android/support/v7/widget/PopupMenu.html" but i'm not able to implement this using ABS, please help someone.

A: If you are using the support library you should discard using the ABS. Instead, import the support library into your workspace which can be found in ~/adt-bundle-linux-x86_64-20130729/sdk/extras/android/support/v7/appcompact and use is in your project. And also don't forget to add the support library which can be brought up right clicking into your project and entering Android Tools -> Add Support Library
Using appcompact you will have to extend your activity class with ActionBarActivity. And also using the appcompact you have to make changes in your styles folder. You could refer to this. Do not also forget to update the values-v11 and values-v14 file. Doing all of this will make your application compatible.
P.S. If any error occurs in your appcompact library. Don't panic look at the error logs and open the file that seems to contain the error. Most probably you will have to refresh the file and after that you just fix project properties, and the error goes away.
Hope this helps :)

A: Use like this PopupMenu in ActionBarSherlock.
Styling of the PopupMenu -
<item name="popupMenuStyle">@style/PopupMenu.MyAppTheme</item>

<style name="PopupMenu.MyAppTheme" parent="@style/Widget.Sherlock.ListPopupWindow">
    <item name="android:popupBackground">@android:color/white</item>
</style>


text:
Q: SearchView does not iconify In my app I am using an android.support.v7.widget.SearchView (from support v7 library) to provide search from action bar.
I setup this view in MainActivity, with the following code:
MainActivity.java
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        this.menu = menu;

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

        SupportMenuItem searchMenuItem = (SupportMenuItem) menu.findItem(R.id.menu_search);

        SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
        searchView.setQueryRefinementEnabled(true);

        searchView.setIconifiedByDefault(true);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            // OnQueryTextListener body
            ...
        });

        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));

        return super.onCreateOptionsMenu(menu);
    }

Then in a Fragment i need to ensure that the SearchView is collapsed:
MyFragment.java
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    MenuItem searchMenuItem = menu.findItem(R.id.menu_search);
    SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem);
    searchView.clearFocus(); // Try to prevent SearchView to steal focus. No luck!
    searchView.setIconified(true);
}

@Override
public void onResume() {
    super.onResume();

    setHasOptionsMenu(true);
    // other stuff
}

The problem is that not only the SearchView does not collapse (I tried also with MenuItemCompat.collapseActionView(searchMenuItem) with no success: it returns always false), but also the SearchView "steals" focus at every fragment transaction (e.g. replace one fragment with another), so when the "new" fragment is displayed, the SearchView has focus, so it shows its suggestions.
I also noticed that if I do not call setHasOptionsMenu then the problem of "stealing focus" does not occur.
Is there something I am doing wrong?


text:
Q: Polynomial scaling for numeric root finding Short version:
Is there a way to scale the coefficients of a polynomial which can range from (close to) double precision (2.22e-16) to around unity? The problem is that the numerical root finding can fail due to the large ratios. Or -- but this would require a 40 page reading, certainly not asking anyone to read, but I won't refuse it, either -- how/where can I add a matrix balancing algorithm in the paper below?
Long version (if I explain banalities, it's for the sake of being said, apologies, and for the length):
I am trying my hand with a numerical root finding algorithm, found on this page (Fortran code and the accompanying paper). I am not a mathematician, the paper looks gorgeous, but it's quite meaningless to me, so I am trying to descipher the Fortran code in there. It compiles, it works, outperforms the Lapack by being about 4~5x faster, but if I pass some polynomials that interest me, it fails.
One of them is the coefficients of a half-band FIR filter, which are calculated as $\frac14\textrm{sinc}{\frac{n}{4}}$, with $n=-\frac{N}{2}..\frac{N}{2}$, $N$ being the order of the filter. For orders that are a power of 2, there are values which are mathematically zero, but numerically they are around the machine precision. For example, an N=8 half-band FIR has these coefficients:
h=[9.74543e-18, 0.0750264, 0.159155, 0.225079, 0.25, 0.225079, 0.159155, 0.0750264, 9.74543e-18]

Since the root finding in the paper is an eigenvalue problem based on the companion matrix, the polynomial needs to be normalized to the first coefficient, which results in extremely large differences between the end coefficients and the rest (shown with Octave's compan()):
  -7.6986e+15  -1.6331e+16  -2.3096e+16  -2.5653e+16  -2.3096e+16  -1.6331e+16  -7.6986e+15  -1.0000e+00
   1.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00
   0.0000e+00   1.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00
   0.0000e+00   0.0000e+00   1.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00
   0.0000e+00   0.0000e+00   0.0000e+00   1.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00
   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   1.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00
   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   1.0000e+00   0.0000e+00   0.0000e+00
   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   1.0000e+00   0.0000e+00

These cause the eigenvalue solver in the paper to fail (Octave, or wxMaxima, have no problem). The roots are around or on the unit circle, plus two, real valued ones that are reciprocal, and, in theory, are at zero and infinity. These two cause problems (first and last):

  -7.6986e+15 + 0.0000e+00i
  -9.2871e-01 + 3.7082e-01i
  -9.2871e-01 - 3.7082e-01i
  -4.2221e-01 + 9.0650e-01i
  -4.2221e-01 - 9.0650e-01i
   2.9025e-01 + 9.5695e-01i
   2.9025e-01 - 9.5695e-01i
  -1.2989e-16 + 0.0000e+00i

A common solution (which, I believe, is bultin into Octave) is to apply a so-called matrix balancing, and the result of applying such balancing to the companion matrix above results in these values. Here is the result of Octave's balance():
  -7.6986e+15  -1.2168e+08  -1.0503e+04  -9.1138e+01  -1.0257e+01  -3.6263e+00  -1.7094e+00  -1.4901e-08
   1.3422e+08   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00
   0.0000e+00   1.6384e+04   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00
   0.0000e+00   0.0000e+00   1.2800e+02   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00
   0.0000e+00   0.0000e+00   0.0000e+00   8.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00
   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   2.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00
   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   1.0000e+00   0.0000e+00   0.0000e+00
   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   0.0000e+00   1.4901e-08   0.0000e+00

The ratios are still large, but now the numbers are more "smoothed out". This helps the numerical solver by reducing the loss of precision.
In the linked paper, at around pages 4~5, it's explained how the A matrix is factored, about the perturbation vectors, but I'm lost beyond that, particularly since I can't correlate the paper with the Fortran code. I was hoping to see where I can squeeze a matrix balancing algorithm in there.
If that fails then maybe, the same way a matrix can be balanced, so can be a polynomial? I couldn't find anything on the Internet except something about Balancing numbers, and matrices.
Initially I calculated the geometric mean between the maximum and the minimum coefficients, then the arithmetic mean between each coefficient and the geometric mean. Practically, it's just dividing by two, except for the ends. A FFT reveals that the resulting magnitude is lower by a factor of two, so the scaling seems to work, but the eigenvalue solver still fails. Verifying in Octave, the problematic roots come out reduced, but the unit circle roots seem to be very close. I don't know how stupid is what I did, but here are the results:
  -48066595.61854 +        0.00000i
          0.29025 +        0.95695i
          0.29025 -        0.95695i
         -0.42221 +        0.90650i
         -0.42221 -        0.90650i
         -0.92871 +        0.37082i
         -0.92871 -        0.37082i
         -0.00000 +        0.00000i

However, a reduction by two for 1e-18 is close to nothing, so the next attempt was for every coefficient below 1, multiply by 10, and for every coeff>1, divide by 10. 1 remains unchanged (practically, all multiplied). This seems to work better, the 10 can be changed to 100, or more, the problematic roots come out greatly reduced, but the unit circle roots seem to lose precision. In this case, mutiplying with 1e6, the eigenvalue solver in the paper works:
1.2768819971590109 + 0.0000000000000000i
0.30092056041271281 + 0.71959670183949653i
0.30092056041271281 - 0.71959670183949653i
-0.25561727535438178 - 0.63813585670316197i
-0.25561727535438178 + 0.63813585670316197i
-0.60478923198725509 - 0.25376112338892087i
-0.60478923198725509 + 0.25376112338892087i
-9.9920072216264089e-16 + 0.0000000000000000i

...but wrong:

The x zeroes are the good ones (without the one at infinity), the o are the calculated ones. Again, since I found nothing about polynomial balancing, this is just my (bad) intuition at work.
Now, in theory, for the original roots, those two extremes could be considered zero, and rebuilding the polynomial from the roots would work by manually readjusting the zeros at the ends, but this implies knowing what you're dealing with. What if this is not a half-band FIR? What if it's a windowed FIR with very small values at the ends? High orders will do that. What if it's minimum phase (asymmetric), or simply a random vlaued polynomial?
So I need some sort of polynomial balancing for a generic way to deal with numerical instabilities, and I need it either for the polynomial itself, or to find a way to squeeze in a matrix balancing algorithm (which I can do) in the original Fortran code for the companion matrix.

A: It seems that scaling the polynomial is not worth it, but balancing the matrix is clearly worth it considering that Octave uses it (and it works), LAPACK can use it (and it works), also Maxima, which uses Jenkins-Traub, but still applies a polynomial scaling (which seems to work for this algorithm).
So, since I haven't managed to determine where to insert the matrix balancing algorithm, I resorted to a bit of a hack, based on observations: it seems that, for the forming companion matrix, if the first element $A_{1,1}$ has a very large value, the first eigenvalue can be approximated to be $A_{1,1}$.
So, if the polynomial has $a_nx^n+a_{n-1}x^{n-1}+...a_0$ and $\frac{a_n}{a_{n-1}}\leq\epsilon$ ($\epsilon$ being some chosen threshold), then set the first root to be $-\frac{a_{n-1}}{a_n}$, then set $n=n-1$.
Similarly, if $\frac{a_0}{a_1}\leq\epsilon$ then set the 2nd root to $-\frac{a_0}{a_1}$, decrement the order, and only then start the algorithm.
This seems to work for my particular cases, where I need the roots for FIR and IIR filters, and analog transfer functions, where the worst cases are Lth-band filters and analog prototype denominators such as Bessel polynomials. For these last ones, because the orders are low (compared to FIRs) and the coefficients are (fairly) smooth-varying, they pose no problems, and I can use mpfr C++ without a speed penalty at these orders. But, who knows, it may work with some other, more generic, but similar ill-formed cases (for example, Wilkinson's polynomial is solved with slightly greater accuracy than Octave, with default double precision).


text:
Q: expected value of sum of square on lack of fit test I am studying the part of lack of fit test on linear regression analysis.
let
$y_{ij}=\mu_j + \epsilon_{ij}$, $i=1,2,...n_j$, $j=1,2,...,k$
be the full model. ($\epsilon_{ij}\sim N(0,\sigma^2)$, i.i.d)
And the reduced model is
$y_{ij}=\beta_0+\beta_1x_j + \epsilon_{ij}$, $i=1,2,...n_j$, $j=1,2,...,k$
that is, there is $n_j$ observation of $y$ for each $x_j$.
On my textbook,
$SS_{Res}=SS_{PE}+SS_{LOF}$ and
$SS_{PE}$ is given by
$ \sum_{j=1}^{k} n_j(\bar y_j - \hat y_j)^2$.
and
$ E(SS_{PE})$=$\sigma^2+\Large\frac{\sum_{j=1}^{k} n_j(\mu_j-\beta_0-\beta_1x_j)^2}{k-2}$.
The question is the assumption when calculating this expected value.
I don't understand where $\beta_0$ and $\beta_1$ came from, because in the full model, there is no $\beta$ in the model, and I think the expected value should only be a function of $y$, $x$, and $\mu$, not $\beta$.
In case of the reduced model,  $\mu_j-\beta_0-\beta_1x_j$ equals to $0$ and the second term is always $0$.
This is very confusing to me, and I wish I can get some help.


text:
Q: TikZ - curly braces end at the same node, but there is a gap I created a timeline with TikZ. The problem is, that there is a little gap between the ends of the braces that end at the same node.

And here is my code:
\begin{tikzpicture}[y=1cm, x=1cm, thick, font=\footnotesize]

% axis
\draw[line width=1.2pt, ->, >=latex'](0,0) -- coordinate (x axis) (10,0);

% time points
\draw (3,-4pt) node(t_k){} --
    (3,4pt) node[anchor=south] {$t_{k}$};
\draw (5,-4pt) node(t_k_opt) {} --
    (5,4pt) node[anchor=south] {};
\draw (7,-4pt) node(t_k_opt_impl) {} --
    (7,4pt) node[anchor=south] {$t_{k}+\triangle^{\text{opt}}+\triangle^{\text{impl}}$};

% curly braces
\draw[decorate,decoration={brace,amplitude=3pt,mirror}]
    (3,-2.5) node(t_k_unten){} --
    (5,-2.5) node(t_k_opt_unten){};
\node at (4,-3){$\triangle^{\text{opt}}$};
\draw[decorate,decoration={brace,amplitude=3pt,mirror}]
    (t_k_opt_unten) --
    (7,-2.5) node(t_k_opt_impl_unten){};
\node at (6,-3){$\triangle^{\text{impl}}$};

% vertical dotted lines
\draw[dotted] (t_k)--(t_k_unten);
\draw[dotted] (t_k_opt)--(t_k_opt_unten);
\draw[dotted] (t_k_opt_impl)--(t_k_opt_impl_unten);

\end{tikzpicture}

I'd be glad, if someone could help!

A: You need to use coordinates instead of nodes to mark coordinates on your path for later use). I added the style draw=green to every node which looks like this:

The dashed line end at the nodes and the right brace also starts at right border of the node. (You could consequently use the .center anchor but coordinates are more comfortable.)
Code
\documentclass[tikz]{standalone}
\usetikzlibrary{arrows,decorations.pathreplacing}
\usepackage{amsmath}
\begin{document}
\begin{tikzpicture}[y=1cm, x=1cm, thick, font=\footnotesize]
% axis
\draw[line width=1.2pt, ->, >=latex'](0,0) -- coordinate (x axis) (10,0);

% time points
\draw (3,-4pt) coordinate (t_k)          -- (3,4pt) node[anchor=south] {$t_{k}$};
\draw (5,-4pt) coordinate (t_k_opt)      -- (5,4pt) node[anchor=south] {};
\draw (7,-4pt) coordinate (t_k_opt_impl) -- (7,4pt) node[anchor=south]
                                {$t_{k}+\triangle^{\text{opt}}+\triangle^{\text{impl}}$};

% curly braces
\draw[decorate,decoration={brace,amplitude=3pt,mirror}]
    (3,-2.5) coordinate (t_k_unten) -- (5,-2.5) coordinate (t_k_opt_unten);
\node at (4,-3){$\triangle^{\text{opt}}$};
\draw[decorate,decoration={brace,amplitude=3pt,mirror}]
    (t_k_opt_unten) -- (7,-2.5) coordinate (t_k_opt_impl_unten);
\node at (6,-3){$\triangle^{\text{impl}}$};

% vertical dotted lines
\draw[dotted] (t_k)          -- (t_k_unten);
\draw[dotted] (t_k_opt)      -- (t_k_opt_unten);
\draw[dotted] (t_k_opt_impl) -- (t_k_opt_impl_unten);
\end{tikzpicture}
\end{document}

Output


text:
Q: Model relationship many to many with attribute on relational entity I am trying something very simple. At this point I have three models:
Player >> PlayerMatch >> Match

class Match < ActiveRecord::Base
  attr_accessible :date, :goals_team_a, :goals_team_b
  has_many :PlayerMatches
  has_many :Players, :through => :PlayerMatches
end

class Player < ActiveRecord::Base
  attr_accessible :name, :password_confirmation, :password, :user
  has_many :PlayerMatches
  has_many :matches, :through => :PlayerMatches
end

class PlayerMatch < ActiveRecord::Base
  attr_accessible :match_id, :player_id, :team
  belongs_to :player
  belongs_to :match
end

The model PlayerMatch is the join entity. In each Match a player plays, he can be on team A or team B, that is why I made that attribute team on PlayerMatch.
How can I set that value team for each match? I want to do something like:
p = Player.new
//set players attributes
m = Match.new
//set match attributes

p.matches << m

Now I just want to set his team on that specific match.
Thanks in advance!

A: Using the models you have set up, you can do something like this:
p = Player.create
m = Match.create
pm = PlayerMatch.create(:player => p, :match => m, :team => 'Team')

If you want the PlayerMatch automatically created as in your example, you can retrieve it afterwards and set the team at that point:
p = Player.create
m = Match.create
p.matches << m

pm = p.matches.where(:match_id => m.id).first
pm.update_attributes(:team => 'Team')

Unless you are saying an individual player can play different matches for different teams though, it seems like you may want a Player to belong_to a Team instead.
This post also has some info related to this question.


text:
Q: не работает функция moveBy() Javascript <!doctype html>

<meta charset="utf-8">
<title>Открытие новых окон и запись содержания</title>

Открыть окно

Передвинуть окно

Закрыть окно

Вопрос: при запуске функции winMove() окно не двигается по монитору. Почему?


text:
Q: Property name of VO class has changed when I transferred data between view and controller I use AngularJs + Bootstrap + SpringMvc in my project. I create a VO class to transform data between page and controller. There is a boolean property named "isDefined" in VO class, But when view get data , it becomes "defined". I changed the name to other things like "isFired" and the view just get "fired". Why could that happen?

A: I think you are using primitive boolean not wrapper Boolean for these properties, so the getter of them will be is{}, if you want to use these names change their type to Boolean