text:
Q: I am making a Tic-Tac-Toe game using Python This is my first time posting a question so I apologize if I missed any necessary details from my question.
So here is the code, it is intended to play tic-tac-toe with the machine and everything goes right until the machine plays its turn and it overwrites the player's selected square if the random function chooses that number, I am almost sure that the problem might come from the MakeListOfFreeFields(board) function but can't find anything.
I also called the free fields function to some not efficient spots to see if it worked. It didn't
Any help is appreciated, thanks!
# coding=utf-8
from random import randrange

def DisplayBoard(board):
    print("+","-"*7,"+","-"*7,"+","-"*7,"+",sep="")
    print("|","|","|","|",sep="       ")
    print("|   ",board[0][0],"   |   ",board[0][1],"   |   ",board[0][2],"   |",sep="")
    print("|","|","|","|",sep="       ")
    print("+","-"*7,"+","-"*7,"+","-"*7,"+",sep="")
    print("|","|","|","|",sep="       ")
    print("|   ",board[1][0],"   |   ",board[1][1],"   |   ",board[1][2],"   |",sep="")
    print("|","|","|","|",sep="       ")
    print("+", "-"*7,"+","-"*7,"+","-"*7,"+",sep="")
    print("|","|","|","|",sep="       ")
    print("|   ",board[2][0],"   |   ",board[2][1],"   |   ",board[2][2],"   |",sep="")
    print("|","|","|","|",sep="       ")
    print("+", "-"*7,"+","-"*7,"+","-"*7,"+",sep="")
    return

def EnterMove(board):
    MakeListOfFreeFields(board)
    while True:
        movPlayer = int(input("Insert the box number you wish to select.\n"))
        if movPlayer < 1 and movPlayer > 9:
            print("Pick another number.\n")
            continue
        elif movPlayer not in board[0] and movPlayer not in board[1] and movPlayer not in board[2]:
            print("Spot taken, pick another one!")
            continue

        for row in range(0,3):
            for column in range(0,3):
                if board[row][column] == movPlayer:
                    board[row][column] = "O"
                    return

def MakeListOfFreeFields(board):
    for row in range(0,3):
        for column in range(0,3):
            if board[row][column] == "X" or board[row][column] == "O":
                continue
            else:
                emptySquares.append(([row],[column]))

def VictoryFor(board, sign):
    if board[0][0] == sign and board[0][1] == sign and board[0][2] == sign:
        return True
    elif board[1][0] == sign and board[1][1] == sign and board[1][2] == sign:
        return True
    elif board[2][0] == sign and board[2][1] == sign and board[2][2] == sign:
        return True
    elif board[0][0] == sign and board[1][0] == sign and board[2][0] == sign:
        return True
    elif board[0][1] == sign and board[1][1] == sign and board[2][1] == sign:
        return True
    elif board[0][2] == sign and board[1][2] == sign and board[2][2] == sign:
        return True
    elif board[0][0] == sign and board[1][1] == sign and board[2][2] == sign:
        return True
    elif board[2][0] == sign and board[1][1] == sign and board[0][2] == sign:
        return True
    else:
        return

def DrawMove(board):
    MakeListOfFreeFields(board)
    while True:
        row = randrange(3)
        column = randrange(3)

        if ([row],[column]) not in emptySquares:
            continue
        else:
            board[row][column] = "X"
            return

board = [[1,2,3],[4,"X",6],[7,8,9]]
emptySquares = []
moves = 1
player = "O"
CPU = "X"

print("Welcome to Tic-Tac-Toe!")

while moves < 9:
    moves += 1
    DisplayBoard(board)
    EnterMove(board)
    DisplayBoard(board)
    DrawMove(board)
    DisplayBoard(board)
    VictoryFor(board, player)

    if VictoryFor(board, player) == True:
        print("Congratulations! You've won!")
        break

    VictoryFor(board, CPU)
    if VictoryFor(board, CPU) == True:
        print("Better luck next time! You've lost. :(")
        break

#End of the program.

A: One solution to keep your code is to 'clear' your output.
For example, use : 'IPython.display.clear_output()'
Don't forget to temporize it to keep it readable with a 'time.sleep()'
Here is your code:
# coding=utf-8
import time
from random import randrange
from IPython.display import clear_output

def clear():
    clear_output(wait=True)

def DisplayBoard(board):
    print("+","-"*7,"+","-"*7,"+","-"*7,"+",sep="")
    print("|","|","|","|",sep="       ")
    print("|   ",board[0][0],"   |   ",board[0][1],"   |   ",board[0][2],"   |",sep="")
    print("|","|","|","|",sep="       ")
    print("+","-"*7,"+","-"*7,"+","-"*7,"+",sep="")
    print("|","|","|","|",sep="       ")
    print("|   ",board[1][0],"   |   ",board[1][1],"   |   ",board[1][2],"   |",sep="")
    print("|","|","|","|",sep="       ")
    print("+", "-"*7,"+","-"*7,"+","-"*7,"+",sep="")
    print("|","|","|","|",sep="       ")
    print("|   ",board[2][0],"   |   ",board[2][1],"   |   ",board[2][2],"   |",sep="")
    print("|","|","|","|",sep="       ")
    print("+", "-"*7,"+","-"*7,"+","-"*7,"+",sep="")
    return

def EnterMove(board):
    MakeListOfFreeFields(board)
    while True:
        movPlayer = int(input("Insert the box number you wish to select.\n"))
        if movPlayer < 1 and movPlayer > 9:
            print("Pick another number.\n")
            continue
        elif movPlayer not in board[0] and movPlayer not in board[1] and movPlayer not in board[2]:
            print("Spot taken, pick another one!")
            continue

        for row in range(0,3):
            for column in range(0,3):
                if board[row][column] == movPlayer:
                    board[row][column] = "O"
                    return

def MakeListOfFreeFields(board):
    for row in range(0,3):
        for column in range(0,3):
            if board[row][column] == "X" or board[row][column] == "O":
                continue
            else:
                emptySquares.append(([row],[column]))

def VictoryFor(board, sign):
    if board[0][0] == sign and board[0][1] == sign and board[0][2] == sign:
        return True
    elif board[1][0] == sign and board[1][1] == sign and board[1][2] == sign:
        return True
    elif board[2][0] == sign and board[2][1] == sign and board[2][2] == sign:
        return True
    elif board[0][0] == sign and board[1][0] == sign and board[2][0] == sign:
        return True
    elif board[0][1] == sign and board[1][1] == sign and board[2][1] == sign:
        return True
    elif board[0][2] == sign and board[1][2] == sign and board[2][2] == sign:
        return True
    elif board[0][0] == sign and board[1][1] == sign and board[2][2] == sign:
        return True
    elif board[2][0] == sign and board[1][1] == sign and board[0][2] == sign:
        return True
    else:
        return

def DrawMove(board):
    MakeListOfFreeFields(board)
    while True:
        row = randrange(3)
        column = randrange(3)

        if ([row],[column]) not in emptySquares:
            continue
        else:
            board[row][column] = "X"
            return

board = [[1,2,3],[4,"X",6],[7,8,9]]
emptySquares = []
moves = 1
player = "O"
CPU = "X"

print("Welcome to Tic-Tac-Toe!")

while moves < 9:
    moves += 1
    clear()
    DisplayBoard(board)
    time.sleep(0.3)
    clear()
    EnterMove(board)
    time.sleep(0.3)
    clear()
    DrawMove(board)
    time.sleep(0.3)
    clear()
    DisplayBoard(board)
    time.sleep(0.3)
    clear()
    VictoryFor(board, player)
    time.sleep(.3)

    if VictoryFor(board, player) == True:
        print("Congratulations! You've won!")
        break

    VictoryFor(board, CPU)
    if VictoryFor(board, CPU) == True:
        print("Better luck next time! You've lost. :(")
        break

#End of the program.


text:
Q: extension methods nested within a class i wanted to know as i start to make some dramatic move from using regular helpers to more and more extension methods so they start to pile up ,
say my top main namespace is as follows :
the main namespace name is myname + last digit of year and current month
thats how i keep it organized as a helper namespace
namespace "myname212"
{
    namespace DbRelated
    {
        some clasess & methods
    }

    namespace styling
    {
        same as usual ..
    }

    // .... some more categories and...then

    //the extentions namespace

    namespace CustomExtentions
    {
        // simplest ext class and its first method
        public static class ToNumber
        {
            public static int Toint(this Textbox TbxToConvrt)
            {
                return Convert.ToInt32(TbxToConvrt.Text);
            }
            //some more of same subject
        }
    }
}

but what if i have a more general catefory that has it own sub category logocally
namespace Extentions
{
    public static class MainCategory
    {
         public static class SubCat1
         {
             public static some_method();
         }
         public static class SubCat2
         {
             public static some_method();
         }
    }
}

the a hierarchical stracture above will not work .
so is it true that if i'd like to build more categories i could only do it via
nested namespaces instead of nested classes ?
is this what you do ?

A: You can nest namespaces instead:
namespace My.Nested.Namespace.So.Far
{
    public static class BlaExtensions
    {
    }
}

or even:
namespace My.Nested.Namespace
{
    public static class FooExtensions
    {
    }

    namespace So.Far
    {
        public static class BlaExtensions
        {
        }
    }
}

should work too.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Map each value in a Java array (or similar) like in Ruby It's been a while since I last used Java, so forgive me if the question is stupid. In Ruby, I use .map quite a lot. Is there something similar in Java or do I have to iterate over the Array?
In Ruby, instead of
output = []
input.each do |elem|
  output << SomeClass.new(elem)
end

I can write
output = input.map { |elem| SomeClass.new(elem) }

A: Yes, with Java 8 you can use streams to iterate over collections implicitly. For example:
final List<String> strings = Arrays.asList("Me", "You");
final List<String> reducedStrings = strings.stream().map(s -> s.substring(1)).collect(Collectors.toList()); // [ "e", "ou" ]

Reference:
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toList--

A: Since Java 8 and its support for lambda expressions and its stream API:
List<SomeClass> result = someCollection.stream()
                                       .map(SomeClass::new)
                                       .collect(Collectors.toList());

If you're really using an array and not a collection (you should prefer collections almost always), then you can create a strem over the array using
Arrays.stream(array)


text:
Q: jclouds/amazon s3/rackspace cloudfiles/windows azure storage- appending content to an existing blob I have a scenario in which multiple lines of text are to be appended to an existing text file... Is it possible to do this using Jclouds? (That would be ideal for me as jclouds supports a lot of cloud providers)...
Even if this is not doable using jclouds, does the native API of Amazon S3/Rackspace Cloudfiles/Azure storage support appending content to existing blobs?
If this is doable, then kindly point me to good working examples which show the same...

A: This is not possible in the underlying blob stores I know of.


text:
Q: a tap method in lua isnt working I am new to the site and programming in this language... I have gotten a basic understanding of the language and I am having this error:
assertion failed!
stack back:
[C]: ?
[C]: in function 'assert'
?: in function 'getOrCreateTable'
?: in function 'addEventListener'

and there are more lines, but you get the picure.
this is my code that is located in the area that it said to go:
title:addEventListener("tap",title)
how:addEventListener("tap",how_fun)

function how_fun:tap( event )
    local how_img = display.newImage("how.png",0,0)
    how_img:addEventListener("tap" ,home_switch)
end

local function home_switch( event )
    local title = display.newImage(mainGroup, "title.png",0,0)
    local how = display.newImage(mainGroup, "how_button.png",0,0)
end

I have no idea of what went wrong... this code is there so if I click on said image it will do what I want...
but I am getting an error in the how_img:addEvent.. area!
if any Q's I will be happy to answer them!
here is the whole code:
 -- Hide status bar
 display.setStatusBar(display.HiddenStatusBar)

 -- main game group
 mainGroup = display.newGroup()

 local title = display.newImage(mainGroup, "title.png",0,0)
 local how = display.newImage(mainGroup, "how_button.png",70,200)

 function title:tap()
-- sets settings for cats
local cat_health = 10
local cat_hunger = 10
local cat_voice = 10
local cat_hygiene = 10
local your_score = 0

local cat = display.newImage(mainGroup, "bg.png",0,0)

local food = display.newImage(mainGroup, "food.png",0,0)

local bath = display.newImage(mainGroup, "bath.png",200,0)

local hunger = display.newText(mainGroup,"Hunger "..cat_hunger.."/10",display.contentWidth/2+15,display.contentHeight-40, native.systemFont, 18)
hunger:setTextColor(255,255,255)

local Score = display.newText(mainGroup,"Your Score: "..your_score,20,display.contentHeight-40, native.systemFont, 18)
Score:setTextColor(255,255,255)

local health = display.newText(mainGroup,"Health "..cat_health.."/10",display.contentWidth/2+15,display.contentHeight-65, native.systemFont, 18)
health:setTextColor(255,255,255)

local hygiene = display.newText(mainGroup,"hygiene "..cat_hygiene.."/10",20,display.contentHeight-65, native.systemFont, 18)
hygiene:setTextColor(255,255,255)

function food:tap( event )
    if (cat_hunger<10) then
        cat_hunger = cat_hunger+1
        hunger.text = "Hunger "..cat_hunger.."/10"
    end
    return true
end

local function trigger()
    if (cat_hunger>0) then
        cat_hunger = cat_hunger-1
    end
    if (cat_hygiene>0) then
        cat_hygiene = cat_hygiene-1
    end
    hunger.text = "Hunger "..cat_hunger.."/10"
    hygiene.text = "Hygiene "..cat_hygiene.."/10"
    return true
end

local function your_score_func()
    your_score = your_score+1
    Score.text = "Your Score: "..your_score
end

local function health_func( event )
    if (cat_hunger==2) then
        cat_health = cat_health-1
        health.text = "Health: "..cat_health.."/10"
    end
    if (cat_hunger==1) then
        cat_health = cat_health-2
        health.text = "Health: "..cat_health.."/10"
    end
    if (cat_hunger==0) then
        cat_health = cat_health-3
        health.text = "Health: "..cat_health.."/10"
    end
    if (cat_hygiene==2) then
        cat_health = cat_health-1
        health.text = "Health: "..cat_health.."/10"
    end
    if (cat_hygiene==1) then
        cat_health = cat_health-2
        health.text = "Health: "..cat_health.."/10"
    end
    if (cat_hygiene==0) then
        cat_health = cat_health-3
        health.text = "Health: "..cat_health.."/10"
    end
    if (cat_health<1) then
        local bkgd = display.newImage("over_bg.png",0,0)
    end
    return false
end

function bath:tap( event )
    if (cat_hygiene<10) then
        cat_hygiene = cat_hygiene+1
        hygiene = "hygiene "..cat_hygiene.."/10"
    end
    return true
end

timer.performWithDelay(4000, trigger,0)
timer.performWithDelay(2000, your_score_func,0)
timer.performWithDelay(3000, health_func,0)
bath:addEventListener("tap",bath)
food:addEventListener("tap",food)
timer.performWithDelay(1000, music_loop)

local function music_loop( event )
audio.play(main_mus)
timer.performWithDelay(1000, music_loop,0)
end
 end

 title:addEventListener("tap",title)
 how:addEventListener("tap",how_fun)

function how_fun:tap( event )
local how_img = display.newImage("how.png",0,0)
how_img:addEventListener("tap" ,home_switch)
 end

 local function home_switch( event )
local title = display.newImage(mainGroup, "title.png",0,0)
local how = display.newImage(mainGroup, "how_button.png",0,0)
 end

A: There is no Object called how_fun.
You should change:
function how_fun:tap( event )
    local how_img = display.newImage("how.png",0,0)
    how_img:addEventListener("tap" ,home_switch)
end

to
function how:tap( event )
    local how_img = display.newImage("how.png",0,0)
    how_img:addEventListener("tap" ,home_switch)
end


text:
Q: How to get domain controller IP Address How do you get the Domain Controller IP address programmatically using C#?

A: Here's how I would do it.
You'll need to use System.Net and System.DirectoryServices.
// get root of the directory data tree on a directory server
DirectoryEntry dirEntry = new DirectoryEntry("LDAP://rootDSE");
// get the hostname of the directory server of your root (I'm assuming that's what you want)
string dnsHostname = dirEntry.Properties["dnsHostname"].Value.ToString();
IPAddress[] ipAddresses = Dns.GetHostAddresses(dnsHostname);

A: Thanks All,
I done it as in this code
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Net;
    using System.Net.Sockets;
    using System.DirectoryServices.AccountManagement;
    using System.DirectoryServices.ActiveDirectory;
public doIt()
        {
            DirectoryContext mycontext = new DirectoryContext(DirectoryContextType.Domain,"project.local");
            DomainController dc = DomainController.FindOne(mycontext);
            IPAddress DCIPAdress = IPAddress.Parse(dc.IPAddress);
        }

Thanks again

A: Well here is the general workflow of how to get it as described at the MS site:
http://support.microsoft.com/kb/247811
Here is the link from PInvoke.net to call the referenced DsGetDcName function:
http://pinvoke.net/default.aspx/netapi32/DsGetDcName.html
You could go down and dirty and do a raw DNS A Record query as described in the first link, but I think the PInvoke call should do the trick.
Hope that helps,
Mike


text:
Q: Programmatically wire event handler of a control in a datatemplate I have clickable image/rectangle controls throughout my application and prefer to wire them in code:
clickableimagecontrol.MouseUp += MouseUp_Handler

I am struggling to understand how to do the same with datatemplates. I basically need to find the spot where the template is applied to each item, so I can insert my hooks.
I know WPF recommends using Commands of some type, but that requires more boiler-plate code, not to mention that image/rectangles don't support commands so I'd have to redo the whole thing with styled button controls instead.
Is this possible?

A: Please see workable solution:
    private void ElementKeyUp(object source, KeyEventArgs args)
    {
        throw new NotImplementedException();
    }

    private DataTemplate GetDataTemplate()
    {
        var result = new DataTemplate();

        var factory = new FrameworkElementFactory(typeof(ListViewItem));

        var handler = new KeyEventHandler(ElementKeyUp);

        factory.AddHandler(KeyUpEvent, handler);

        result.VisualTree = factory;

        return result;
    }


text:
Q: Continue after "throw new Exception" When I throw an exception, my program breaks.
I want to continue my program after throw new MatchException.
My program checks the characters. When I put a wrong character, I get the exception and my program breaks.
My code:
public AbstractToken Peek()
{
    // Loop through all tokens and check if they match the input string
    foreach (KeyValuePair<Type, string> pair in _dictionary)
    {
        var match = Regex.Match(_input.Substring(_counter), pair.Value);
        if (match.Success)
        {
            if (pair.Key.IsSubclassOf(typeof(AbstractToken)))
            {
                // Create new instance of the specified type with the found value as parameter
                var token = (AbstractToken)Activator.CreateInstance(pair.Key, new object[] { match.Value, _counter }, null);
                return token;
            }
        }
    }
    throw new MatchException(_input[_counter].ToString(CultureInfo.InvariantCulture), _counter);
}

A: Catch the exception with a try catch and handle it.

A: Use try and catch to handle the exception. What you are doing now is throwing an Exception, which will result in a program crash.
More info here
So what it should be:
public AbstractToken Peek()
    {
        // Loop through all tokens and check if they match the input string
        try
        {
            foreach (KeyValuePair<Type, string> pair in _dictionary)
            {
            var test = _input.Length;
            // TODO: See if substring does not impose a to harsh performance drop
            Match match = Regex.Match(_input.Substring(_counter), pair.Value);

            if (match.Success)
            {
                if (pair.Key.IsSubclassOf(typeof(AbstractToken)))
                {
                    // Create new instance of the specified type with the found value as parameter
                    AbstractToken token = (AbstractToken)Activator.CreateInstance(pair.Key, new object[] { match.Value, _counter }, null);

                    return token;

                }
            }
        }
        }
        catch(Exception e)
        {
            //Do whatever u want
        }

    }

OR:
public AbstractToken Peek()
    {
        // Loop through all tokens and check if they match the input string
        foreach (KeyValuePair<Type, string> pair in _dictionary)
        {
            var test = _input.Length;
            // TODO: See if substring does not impose a to harsh performance drop
            Match match = Regex.Match(_input.Substring(_counter), pair.Value);

            if (match.Success)
            {
                if (pair.Key.IsSubclassOf(typeof(AbstractToken)))
                {
                    // Create new instance of the specified type with the found value as parameter
                    AbstractToken token = (AbstractToken)Activator.CreateInstance(pair.Key, new object[] { match.Value, _counter }, null);

                    return token;

                }
            }
        }
    }

Both codes won't fire any Exception

A: When you raise an Exception the software looks for a try-catch block in your stack to handle it. If this block isn't found, the program will crash.
The stack of calls save all functions that you called, in the bottom the first function and in the top the current function.

A: Use try and catch blocks and leave the catch block as empty.
try
{
       foreach (KeyValuePair<Type, string> pair in _dictionary)
        {
            var test = _input.Length;
            // TODO: See if substring does not impose a to harsh performance drop
            Match match = Regex.Match(_input.Substring(_counter), pair.Value);

            if (match.Success)
            {
                if (pair.Key.IsSubclassOf(typeof(AbstractToken)))
                {
                    // Create new instance of the specified type with the found value as parameter
                    AbstractToken token = (AbstractToken)Activator.CreateInstance(pair.Key, new object[] { match.Value, _counter }, null);

                    return token;

                }
            }
        }
}
catch{ }


text:
Q: Google sheets get first occurrence from duplicate column headers I need to get the first occurrence from duplicate column headers as follows:

A workaround was to group all the same columns and use an IF blank then get next column formula. However, it seems not efficient if a column was added in between or the columns were re-arranged in some way. So the quickest way I could think of is to just get the first occurrence from a range that's equal to the column header.

A: first column:
=INDEX(FILTER(A1:E5, A1:E1="name"),,1)

first non empty:
=INDEX(IFERROR(SPLIT(TRIM(FLATTEN(QUERY(TRANSPOSE(
 FILTER(A1:E5, A1:E1="name")),,9^9))), " ")),,1)

whole table:
={INDEX(IFERROR(SPLIT(TRIM(FLATTEN(QUERY(TRANSPOSE(FILTER(A1:E5, A1:E1="name")),,9^9))), " ")),,1), B1:B5,
  INDEX(IFERROR(SPLIT(TRIM(FLATTEN(QUERY(TRANSPOSE(FILTER(A1:E5, A1:E1="email")),,9^9))), " ")),,1)}

update:
=INDEX(LAMBDA(a, h, x, {
 INDEX(IFERROR(SPLIT(TRIM(FLATTEN(QUERY(TRANSPOSE(FILTER(a, h="name")),,9^9))), " ")),,1), x,
 INDEX(IFERROR(SPLIT(TRIM(FLATTEN(QUERY(TRANSPOSE(FILTER(a, h="email")),,9^9))), " ")),,1)})
 (SUBSTITUTE(A1:E10, " ", CHAR(9)), A1:E1, B1:B10))

A: I see you already accepted an answer, but just in case you or anyone needs this with more columns, you could use this formula:
=query({A1:Z},"Select Col"&JOIN(", Col",byrow(filter(unique(transpose(A1:1)),unique(transpose(A1:1))<>""),lambda(each,match(each,A1:1,0)))),true)

This will find first appearance of all unique headers and make the query ;)


text:
Q: Finding average by grouping row values pandas dataframe data=df.groupby('Term')['Subject'].apply(tuple)

I wrote this line in python but I didn't achieved desired output. Can anyone help me out.
I tried many grouping methods but I never came up with the output.

A: If you are looking at the average of the Subject column grouped by Term, you were actually quite close:
df.groupby('Term')['Subject'].mean()


text:
Q: I am trying to sort a list on a page that is contained in an iFrame in another page that my parent page opens on click (same domain) using Javascript I am working on  site that has a lot of cross-referencing. What I would like to do is from Page 1 is to enter a search term and click a search button, and have that open a new page (Page 2), that contains an iFrame (Page 3), that has the searchable list.
I have a working code to search the list, and I have a working code that can execute that search from Page 2 to Page 3 (The page that has the embedded iFrame and the page in the iFrame), and I have a working code to accurately send the search term from Page 1 to Page 2, but I can't get it to actually then execute the search on page 3.
What I have so far is Page1:
//html
Search  <input type="text" id="filterList" placeholder="Search">
//js
 const searchlist = document.querySelector("#search");
   searchlist.addEventListener ("click", openAndSearchL, false);
   const listfilter = document.querySelector("#filterList");
   var lIndex;

   function openAndSearchL(){
     openTargetL();
     timeSearchL();

   }

   function openTargetL() {
     var domain = "https://awebsite.com";
     lIndex = window.open (domain +'/page2.html');
   }

   function timeSearchL(){
     setTimeout(sendSearchL,247);
   }

   function sendSearchL(){
     let x = listfilter.value;
     lIndex.postMessage(x,"https://awebsite.com/page2.html");
     lIndex.focus();
     console.log(x);
   }

(I have the timeout as that is how I rigged it for Page 2 to get the message after loading - by all means if anyone has a better method let me know)
Page 2:
//html
Search  <input type="text" id="filterList" placeholder="Search">

//javascript
//message listener - moves the search term from page 1 to page 2
window.addEventListener("message", (event) => {
    let txt=document.querySelector('#filterList');
     txt.value=`${event.data}` ;
 });

//send search term to page 3 and execute search

   const searchlist = document.querySelector("#search");
   searchlist.addEventListener ("click", sortList, false);
   const listfilter = document.querySelector("#filterList");

   function sortList(){
   sendSearch();
   doSearch();
   }

   function sendSearch(){
   let x = listfilter.value;
   frames['mainframe'].document.getElementById("filterList").value = x;
   }

   function doSearch(){
   frames['mainframe'].document.getElementById("search").click();
   }

and page 3:
//html
 Search <input type="text" id="filterList" placeholder="Search"> /* note these will actually be hidden - they are just here to act as a place to store the search term and to trigger the search*/

12345

6789

content

10111213

other content

compelling content

//javascript
   /*search by text*/

   const search = document.querySelector("#search");
   search.addEventListener ("click", sortList, false);

function sortList() {
var input, filter, ul, li, a, i, txtValue;
    input = document.getElementById("filterList");
    filter = input.value.toUpperCase();
    ul = document.getElementById("articleList");
    li = ul.getElementsByTagName("li");
    for (i = 0; i
 -1) {
            li[i].style.display = "";
        } else {
            li[i].style.display = "none";
        }
    }
}

So everything works except I cannot for the life of me figure out how to get the sen search function on page 2 that executes the search on page 3 to execute from Page1. I assume it would be something like adding an additional function to the "message" event listener.. but everything I have tried so far has failed.
I am 100% teaching myself and I am only a few weeks in so any help would be greatly appreciated.


text:
Q: Why is chrome.action.onClicked.addListener not working? Why does clicking the action icon in chrome not return a result?
I'm developing in chrome and want to console.log when the action icon is clicked. Looking at the console, the first script in my background.js file works (tracking the current URL), however, nothing is returned when the icon is clicked. Any idea what I'm doing wrong? Thanks!
manifest.json
{
  "manifest_version": 3,
  "name": "Chrome Extension with React & Webpack",
  "options_page": "options.html",
  "background": { "service_worker": "background.bundle.js" },
  "action": {
    "default_title": "Click to show an alert"
  },
  "permissions": ["activeTab", "scripting", "tabs"],
  "chrome_url_overrides": {
    "newtab": "newtab.html"
  },
  "icons": {
    "128": "icon-128.png"
  },
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*", "<all_urls>"],
      "js": ["contentScript.bundle.js"],
      "css": ["content.styles.css"]
    }
  ],
  "devtools_page": "devtools.html",
  "web_accessible_resources": [
    {
      "resources": ["popup.html", "content.styles.css", "icon-128.png", "icon-34.png"],
      "matches": [],
       "extension_ids": []
    }
  ]
}

Background.js
//This works
chrome.tabs.onUpdated.addListener(function () {
  console.log("TAB UPDATED")
  getTab().then(url => {
      console.log(url);
  })
})

async function getTab() {
  let queryOptions = { active: true, currentWindow: true };
  let tabs = await chrome.tabs.query(queryOptions);
  return tabs[0].url;
}

//Nothing is console logged
chrome.action.onClicked.addListener(tab => { console.log('test')});


text:
Q: Test fixed effects for joint significance in R Just as in this post I'm looking to test for the joint significance of the fixed effects in a model. Unlike the post I referred to, I'm looking to test each fixed effect individually. I have used a sample dataset which is publicly available and I already ran an F test on the fixed effects. I would like to know if you think this is the right way to test for joint significance.:
library(foreign)
Panel <- read.dta("http://dss.princeton.edu/training/Panel101.dta")
Panel$RandomFactor <- sample(LETTERS[1:6],nrow(Panel),replace=T)
fit <- lm(y~factor(RandomFactor)+factor(country)+factor(year)+x1 + x2 -1,data=Panel)
summary(fit)
library(aod)
wald.test(b=coef(fit),Sigma=vcov(fit),Terms= 1:6,) # F test on Random Factor

#Wald test:
#----------
#
#Chi-squared test:
#X2 = 5.9, df = 6, P(> X2) = 0.43

wald.test(b=coef(fit),Sigma=vcov(fit),Terms= 7:12,) # F test on Country

#Wald test:
#----------
#
#Chi-squared test:
#X2 = 20.5, df = 6, P(> X2) = 0.0022
wald.test(b=coef(fit),Sigma=vcov(fit),Terms= 13:21,) #F test on year
#Wald test:
#----------
#
#Chi-squared test:
#X2 = 12.1, df = 9, P(> X2) = 0.21

Is this the right way to test for joint significance in a fixed effects model? The results look plausible to me, country is significant but year and RandomFactor(as expected) not.
Since I use many fixed effects in my real dataset, I would really like to test each individual fixed effect for significance (as I did here) and mix different combinations.
Any help is much appreciated. Many thanks,
Tim


text:
Q: Visual Studio TFS doesn't deploy web project I am using Visual Studio team services (visual studio online). I have a visual studio solution with 12 projects including a Web project (front end), which I set up. I had setup a build and deploy pipeline and successfully deployed the project to IIS but on checking the deployed files I found that the Web project wasn't deployed, just the class libraries. Navigating to the website url gives and "unauthorised response".

A: Refer to these steps to deploy web app:

*

*NuGet Restore task to restore packages

*Visual Studio Build task (Solution: ***.sln; MSBuild Arguments: /p:SkipInvalidConfigurations=true /p:DeployOnBuild=true  /p:WebPublishMethod=Package /p:PackageLocation="$(build.artifactstagingdirectory)\"); Platform:xxx(e.g. $Buildplatform); Configuration: XXX(e.g. $(BuildConfiguration))

*WinRM-IIS Web App Deployment task: (Machines:XXX; Admin Login: XXX; Password: XXX; Web Deploy Package: $(build.artifactstagingdirectory)\XXX.zip; Website Name: XXX

A: Works now, I just changed the Visual Stuio Version (in the build definition) to Visual Studio 2015, because that is where the app was written


text:
Q: Prevent Softkeyboard from hiding when DialogFragment opens in Android In my app, I have list of chat messages. Each message on click shows popup context dialog menu. My problem is that, when user clicks the input window, Soft-keyboard is opened, then he clicks on of the messages. When DialogFragment is opened it closes Soft-keyboard.
How I can prevent closing Soft-keyboard on dialog opening just like Hangouts does in screenshot?
I have these settings in Manifest for this activity:
          android:configChanges="screenSize|orientation|keyboardHidden"
          android:windowSoftInputMode="stateHidden|adjustResize"


text:
Q: Wordpress Custom posts with Taxonomy I saw some themes have different sections like "portfolio", 'Testimonial' etc. These are custom posts, but i need to know how to do them? What is the mechanism? Is it about the Taxonomy? My ideas are not clear, Can any one help? Any link for tutorial will be appreciated

A: Here's a thorough tutorial from Smashing Magazine
http://wp.smashingmagazine.com/2012/11/08/complete-guide-custom-post-types/


text:
Q: GoogleApiClient not calling onConnected method inside service I am trying to update the location from service but when I call googleApiClient to connect it is not calling any of the methods such as onConnected, onConnectionSuspended or onConnectionFailed.
Here's the full code :
public abstract class BASE_LOCAT_SERVICE extends Service  implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener, LocationListener {

    public String TAG="LOC_SERVICE";

    public GoogleApiClient googleApiClient;
    private Location lastLocation;
    private static int UPDATE_INTERVAL = 5000;
    private static int DISPLACEMENT = 10;
    private LocationRequest locationRequest;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG+"_LOC","On create Command");
        buildGoogleApiClient();
    }

    protected synchronized void buildGoogleApiClient() {
        googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API).build();
        Log.i(TAG+"_LOC","googleApiClient Connecting");
    }

    protected void createLocationRequest() {
        locationRequest = new LocationRequest();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(UPDATE_INTERVAL);
        locationRequest.setSmallestDisplacement(DISPLACEMENT);
        Log.i(TAG+"_LOC","createLocationRequest");
    }

    private void initialiseWithLastLocation() {
        try{
            lastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    googleApiClient);
            Log.i(TAG+"_LOC","initialiseWithLastLocation Initialised");
        }catch(SecurityException ex){
            Log.e(TAG+"_LOC", "Unable to get last known location", ex);
        }
    }

    protected void startLocationUpdates() {

        try {
            LocationServices.FusedLocationApi.requestLocationUpdates(
                    googleApiClient, locationRequest, this);
            Log.i(TAG+"_LOC","startLocationUpdates Initialised");
        } catch (SecurityException ex) {
            Log.e(TAG+"_LOC", "Unable to get Last Known location", ex);
        }
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        createLocationRequest();
        initialiseWithLastLocation();
        startLocationUpdates();
        Log.i(TAG+"_LOC","googleApiClient Connected");
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG+"_LOC","googleApiClient onConnectionSuspended");
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Log.i(TAG+"_LOC","googleApiClient onConnectionFailed");
    }

    @Override
    public void onLocationChanged(Location location) {
        lastLocation = location;
        Log.i(TAG+"_LOC"," onLocationChanged");
    }

    public String getLastLocation()
    {
        if(lastLocation!=null)
        {
            String ret="Location : \n";

            ret = ret+"Latitude : "+lastLocation.getLatitude()+"\n";
            ret = ret+"Longitude : "+lastLocation.getLongitude()+"\n";
            ret = ret+"Altitude : "+lastLocation.getAltitude()+"\n";
            ret = ret+"Accuracy : "+lastLocation.getAccuracy()+"\n";
            ret = ret+"Provider : "+lastLocation.getProvider()+"\n";
            ret = ret+"Speed : "+lastLocation.getSpeed()+"\n";
            ret = ret+"MAP Link : https://www.google.com/maps/?q="+lastLocation.getLatitude()+","+lastLocation.getLongitude()+"\n";

            return ret;
        }
        else
            return "Location Not Available";
    }
}

and the logcat shows only this:
LOC_SERVICE_LOC: On create Command
LOC_SERVICE_LOC: googleApiClient Connecting

A: You have to connect using mGoogleApiClient.connect() inside onStartCommand
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (mGoogleApiClient != null) {
        mGoogleApiClient.connect();
    }else{
       Toast.makeText(getApplicationContext(),"mGoogleApiClient is null",Toast.LENGTH_LONG).show();
    }
    return START_STICKY;
}


text:
Q: Rewriting url with Application Request Routing (MVC5 application) I have an MVC5 application with url http://site1.com running in IIS on an integrated application pool. I have another service running on http://site2.com/dir/service.svc.
I am trying to create a rewrite rule for http://site1.com/dir/service.svc to go to http://site2.com/dir/service.svc.
I keep getting 404 NOT FOUND responses. But I have verified that I can browse the service through my web browser.
In IIS, I've used the ARR (Application Request Routing) plugin to create rewrite rules on both the application and the server level.
The following is an example of the rewrite rule from both applicationHosts.config (server level) and web.config (application level):
<rule name="rewrtite test 2" patternSyntax="ExactMatch">
  <match url="http://site1.com/dir/service.svc" />
  <action type="Rewrite" url="http://site2.com/dir/service.svc" />
</rule>

In my MVC application, I have tried to add the following to my RouteConfig.cs:
routes.IgnoreRoute("dir/{*pathInfo}");

I also tried with:
routes.IgnoreRoute("dir/service.svc");

I read that the problem might be because of ExtensionlessUrlHandler so I tried removing it with:
<handlers>
  <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
</handlers>

Some details:

*

*IIS 6.2

*MVC 5

*.NET 4.5.1

I've tried to turn on FailedRequestLogging with the following settings:

*

*All Content (*)

*Status Codes: 200-600

*Providers: ASP, ASP.NET, ISAPI Extension, WWW Server

But I don't get any log files in %SystemDrive%\inetpub\logs\FailedReqLogFiles.
Thanks.


text:
Q: Prove the randomness of elements in list I wrote a function that generates random numbers (but not with libraries) I could use numpy or statistic library in python, But generate them from scratch.
Now I have a list of numbers, But the problem is how can I show that these numbers are actually random? I am familiar with the concept of correlation but don't know how to use it for my problem or is there any other mathematical way or library to prove this?

Thanks in advance


text:
Q: Dplyr Pivot Table RShiny Here's an example RShiny app using the dataset starwars from the dplyr library in R. It produces a pivot table where an end-user would be able to select as many 'dimension(s)', 'measure(s)', and 'aggregate function(s)' they want and it produces a resulting dataset accordingly.
However, I am running into the problem with the 'aggregate function' isn't working properly when testing out the RShiny app. The problem should be where the pivotData dataframe is defined. At the summarize_at dplyr chain, the object funsList is called out from its previous assignment of input$funChoices. However this doesn't work and produces and error.
Code below:
pivotData <- reactive({
    input$runit
    isolate({
      measuresVec <- input$measures
      dimensionsVec <- input$dimensions
      funsList <- input$funChoices

      pivotData <- data %>%
        group_by_at(vars(dimensionsVec)) %>%
        summarize_at(vars(measuresVec), funsList , na.rm = TRUE)
    })

    return(pivotData)

  })

If you substitute funsList to the functions object defined at the very beginning, you will see that the first two inputs (dimensions and measures) work. However, the number of functions is obviously predefined in the RShiny app and will automatically be displayed accordingly without the end-user getting that opportunity.
Ideally, the total number of columns should equal (# of Dimensions) + (# of Measures * # of Functions)
Any help would be greatly appreciated! Thanks so much!
Entire Code snippet below:
library(DT)
library(shiny)
library(shinydashboard)
library(dplyr)
library(dbplyr)
library(tidyverse)
library(DBI)

ui <- function(request) {
  dashboardPage(
    dashboardHeader(title = "SW Pivot"),
    dashboardSidebar(
      actionButton("runit", "RUN QUERY"),
      hr(),

      h4(HTML("&nbsp"), "Select Table Rows"),
      uiOutput('rowSelect'),
      hr(),
      h4(HTML("&nbsp"), "Select Table Columns"),
      uiOutput('colSelect'),
      hr(),
      h4(HTML("&nbsp"), "Select Table Cell Fill"),
      uiOutput('aggSelect'),
      hr()

    ),
    dashboardBody(dataTableOutput("data"))

  )
}

data <- starwars

server<-shinyServer(function(input, output, session) {

  # Identify Measures, Dimensions, and Functions --------------

  dimensions <- colnames(data)[!sapply(data, is.numeric)]
  measures <- colnames(data)[sapply(data, is.numeric)]
  functions <- list( mean = mean,
                     sum = sum,
                     max = max,
                     min = min)

  # functions <- as.vector(unlist(functions))

  output$rowSelect <- renderUI({
    selectizeInput(
      inputId = "dimensions",
      label = NULL,
      multiple = TRUE,
      choices = dimensions,
      selected = c()
    )
  })

  output$colSelect <- renderUI({
    selectizeInput(
      inputId = "measures",
      label = NULL,
      multiple = TRUE,
      choices = measures,
      selected = c()
    )
  })

  output$aggSelect <- renderUI({
    selectizeInput(
      inputId = "funChoices",
      label = NULL,
      multiple = TRUE,
      choices = functions,
      selected = c()
    )
  })

  pivotData <- reactive({
    input$runit
    isolate({
      measuresVec <- input$measures
      dimensionsVec <- input$dimensions
      funsList <- input$funChoices

      pivotData <- data %>%
        group_by_at(vars(dimensionsVec)) %>%
        summarize_at(vars(measuresVec), functions, na.rm = TRUE)
    })

    return(pivotData)

  })

  output$data <- renderDataTable({
      tabledata <- pivotData()
      datatable(tabledata)
  })

})

shinyApp(ui, server)

A: The functions don't get properly stored when you define the function list. It is easier to just choose the string name of the function and later use match.fun to get the actual function.
A few things I've noticed:

*

*I've updated your dplyr code to 1.0.0 with across

*you get a faster UI when you don't use renderUI but use observeEvent/updateXInput when some variables change

library(DT)
library(shiny)
library(shinydashboard)
library(dplyr)

ui <- function(request) {
  dashboardPage(
    dashboardHeader(title = "SW Pivot"),
    dashboardSidebar(
      actionButton("runit", "RUN QUERY"),
      hr(),

      h4(HTML("&nbsp"), "Select Table Rows"),
      uiOutput('rowSelect'),
      hr(),
      h4(HTML("&nbsp"), "Select Table Columns"),
      uiOutput('colSelect'),
      hr(),
      h4(HTML("&nbsp"), "Select Table Cell Fill"),
      uiOutput('aggSelect'),
      hr()

    ),
    dashboardBody(dataTableOutput("data"))

  )
}

data <- starwars

server<-shinyServer(function(input, output, session) {

  # Identify Measures, Dimensions, and Functions --------------

  dimensions <- colnames(data)[!sapply(data, is.numeric)]
  measures <- colnames(data)[sapply(data, is.numeric)]
  functions_string <- c("mean", "sum", "max", "min")

  # functions <- as.vector(unlist(functions))

  output$rowSelect <- renderUI({
    selectizeInput(
      inputId = "dimensions",
      label = NULL,
      multiple = TRUE,
      choices = dimensions,
      selected = c()
    )
  })

  output$colSelect <- renderUI({
    selectizeInput(
      inputId = "measures",
      label = NULL,
      multiple = TRUE,
      choices = measures,
      selected = c()
    )
  })

  output$aggSelect <- renderUI({
    selectizeInput(
      inputId = "funChoices",
      label = NULL,
      multiple = TRUE,
      choices = functions_string,
      selected = c()
    )
  })

  pivotData <- eventReactive(input$runit, {
    measuresVec <- input$measures
    dimensionsVec <- input$dimensions

    fun_list <- lapply(input$funChoices, match.fun)
    names(fun_list) <- input$funChoices
    pivotData <- data %>%
      group_by(across(all_of(dimensionsVec))) %>%
      summarize(across(all_of(measuresVec), fun_list, na.rm = TRUE))

    return(pivotData)

  })

  output$data <- renderDataTable({
    tabledata <- pivotData()
    datatable(tabledata)
  })

})

shinyApp(ui, server)


text:
Q: How to map terminal shortcut from CTRL-M to another combination I read in another post that you can type CtrlJ or CtrlM instead of the Return key in the terminal, which is great. But what I want to be able to do, is change that to another combination, for example: Ctrlspacebar. I've tried remapping the F1 key, to no avail.
Is this possible?

A: Depends what exactly you want to do.
terminals have two major modes both of which can be fine tuned with extra settings:

*

*cooked/canonical mode. In that mode, the terminal comes with an internal line editor where the ^H (or ^?), ^W, ^U (or @), ^V (or \) characters can be used to edit the line. Nothing is sent to the application reading from the terminal device until the ^J character is received.

*raw mode. Where every character is available for reading to the application reading the terminal device as soon as it is typed, or after a delay or after so many have been entered depending on the time and min parameters, but in anycase, not with that internal line editor.

In both cases, the ^M (CR) character can be automatically translated to ^J (LF) (or ignored for those terminals that send both CR and LF upon pressing Enter).
The first mode is the default mode of the terminal. The second mode is used by applications like zsh, bash or vi that want to take control of the line editing.
In the first mode, you cannot change what character is used to accept the line.
But you may be able to tell your terminal to send the ^J character upon pressing this or that key. For instance, with xterm, you can use the translations X11 resource to change the key mapping and tell it to send whatever you want upon a given key press. If your terminal doesn't support remapping the keyboard, you can still use GNU screen to do the translation for you. For instance, if your terminal sends the ^[OP character sequence upon pressing F1, you can add
bindkey \033OP "\012"

to your ~/screenrc to tell it to send LF when you press F1
For the second case, that is where applications take control of the input, you can still use the same approach as above, but you could also configure each individual application to do this and that when you press F1
For instance, with zsh, the LF character is bound to the accept-line zsh widget. You could do:
bindkey "^[OA" accept-line

to have F1 bind to that same widget.
Note that Ctrl+Space usually sends the NUL character which you can refer to as \0 or ^@.


text:
Q: Fault-tolerant KVM hosts I'm going to create a simple virtual hosts infrastructure using QEMU+KVM. It is expected to be very simple, without clouds or any other cool things. Right now the only requirement is the fault-tolerance for data (hosts' disk images online backup). Live migration welcomed, but is not obligatory. What way do you suggest? Right now I'm thinking about DRBD.

A: If the only thing you require from such a setup is having a replica on a second host, then DRBD is probably your best (and cheapest) bet.
Layers above depend mainly on what kind of setup you expect.
If manual failover is good enough for you, then setup drbd in master/slave mode and lvm, or pretty much any modern filesystem to store the images.
If you want some kind of automatic failover, or having some guests up on both machines (ie. for loadbalancing), you need some kind of clustered setup. Either cLVM, or clustered filesystem (such as GFS, or OCFS).
Another option, though I cannot recommend it yet, is using CEPH. It has not yet been declared production ready, and i don't expect it to be, until there is a recovery procedure for btrfs.


text:
Q: How I start my winforms app via telnet? I have a windows forms application on a client machine.  I am trying to log in via telnet, shut it down, update some files, and restart it.
Using cmd on the client machine and typing in MyApp.exe works great to start it.  But if I do this in the telnet window something odd happens: The application starts in as far as it is now in the process list but none of its forms ever open nor any log4net logging is done.
What's going on and how do I fix this?
Edit:  This seems to be the case with all form-based windows apps. Try it out yourself: telnet localhost => notepad.  It pops up int he user interface but not the ui!
Also, I have RAdmin installed on all these machines?  From what I've seen its got non-existent automation facilities but maybe there's something about it that can help me out?

A: Edit: In my original answer, I misunderstood your question, I thought you said you restarted the machine.
With that said, I'd still probably try to take a different approach. Can you set some type of auto update service into MyApp.exe. An easy way would be to set up a webservice which MyApp.exe can poll to see when new versions are available. Then you'll need to lauch an updater application to do the updating work.

A: I think what's going on is that your app is starting up on a private desktop, and then quiting as soon as you close your telnet session.  I don't know how to make it start up on the "current/active" desktop window, but to keep it running after you log out of telnet try running with the "start" command.

A: Instead of using telnet, you could try using VNCRobot. I believe VNCRobot runs as the user and should share the same desktop.
Disclaimer: I've never used VNCRobot, I just thought it would be worth mentioning.

A: On Windows XP, I found a way around this limitation by using Windows task scheduler. For Windows 7, telnet is not installed by default.
I first had to change the Network Access: Sharing and security model for local accounts to "Classic – local users authenticate as themselves" by merging the following registry settings:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa]
"forceguest"=dword:00000000
I placed it in a file on a remote FTP server and used the FTP command to get it.
Merge it with regedit /s file.reg
Then I created a task that ran once:
SchTasks /Create /SC ONCE /RU "user" /RP pass /TN "StartApp" /TR "\"C:\Windows\NotePad.exe\"" /ST 00:00:00
Manually started the schedule:
Schtasks /run /tn "StartApp"
Deleted the schedule:
schtasks /delete /F /tn "StartAPP"
And that worked. Crazy right! What a pain!

A: If you can run PowerShell on these machines you could use it to find the running process and kill it. the..
Get-Process

..Cmdlet will show you the running processes, you can write the logic to foreach through this list and match your application with regex directly in powershell,  I don't know Ruby but theoretically you could use it to do the same invoking the powershell commands with:
powershell.exe -command Get-Process

To kill a process its:
Stop-Process <processId>
Stop-Process -processname <processName>

Not quite sure how to start the GUI process through telnet, I don't have telnet setup on my equipment.
perhaps you can do something similar to this: http://www.peterprovost.org/blog/post/Powershell-Sudo-(sort-of)-for-Vista-UAC.aspx
Setting the verb to "runas" like in the example at that address will invoke UAC, doing this I was unable to kill the new process, however I am to kill it if I set:
$psi.Verb = "open"

Additionally you can set these attributes as well:
Verb                    : open
Arguments               :
CreateNoWindow          : False
EnvironmentVariables    : {processor_revision, processor_level, logonserver, systemroot...}
RedirectStandardInput   : False
RedirectStandardOutput  : False
RedirectStandardError   : False
StandardErrorEncoding   :
StandardOutputEncoding  :
UseShellExecute         : True
Verbs                   : {open, runas, runasuser}
UserName                :
Password                :
Domain                  :
LoadUserProfile         : False
FileName                : notepad.exe
WorkingDirectory        :
ErrorDialog             : False
ErrorDialogParentHandle : 0
WindowStyle             : Normal


text:
Q: Matlab optimization, failure in initial objective function evaluation I want to solve an optimization problem by Matlab fmincon function. I defined my objective function as:
function f = objfun(x,p1,p2)
x1=x(1:24);
y1=x(25:48);
z1=x(48:end);

f=-mean(x1*(p1)'+y1*(p2)')+mean(z1*(p1)')
end

p1,p2 are 1x24 vectors which are calculated in the main file. I need to find the optimum values for x1, y1 and z1 which are 1x24 vectors (total 72 variables).
When I run the main code I get an error message about the objective function and then for fmincon caused by failure in initial objective function evaluation.
Would you please advise how can I solve the problem?

A: Considering that x is a 1x72 vector, I think there is a typo on the line 4 of your code.
z1=x(48:end);

This will give you a 1x25 vector and the latter multiplication z1*(p1)' will not work since p1 is 1x24.
I suppose you mean:
z1=x(49:end);

This way you have the 24 last elements of x, and the multiplication z1*(p1)' is possible.


text:
Q: Error while installing lamp-server or any other server on my ubuntu 16.04LTS When i try to install lamp-server by entering command :
sudo apt-get install lamp-server^

I get the following output on my terminal :
Reading package lists... Done
Building dependency tree
Reading state information... Done
Note, selecting 'libhttp-message-perl' for task 'lamp-server'
Note, selecting 'libencode-locale-perl' for task 'lamp-server'
Note, selecting 'php7.0-cli' for task 'lamp-server'
Note, selecting 'mysql-client-5.7' for task 'lamp-server'
Note, selecting 'libapache2-mod-php' for task 'lamp-server'
Note, selecting 'rename' for task 'lamp-server'
Note, selecting 'mysql-server-5.7' for task 'lamp-server'
Note, selecting 'php-common' for task 'lamp-server'
Note, selecting 'libaprutil1' for task 'lamp-server'
Note, selecting 'mysql-server' for task 'lamp-server'
Note, selecting 'php7.0-opcache' for task 'lamp-server'
Note, selecting 'libcgi-fast-perl' for task 'lamp-server'
Note, selecting 'libwrap0' for task 'lamp-server'
Note, selecting 'libhttp-date-perl' for task 'lamp-server'
Note, selecting 'perl-modules-5.22' for task 'lamp-server'
Note, selecting 'liblwp-mediatypes-perl' for task 'lamp-server'
Note, selecting 'libfcgi-perl' for task 'lamp-server'
Note, selecting 'libcgi-pm-perl' for task 'lamp-server'
Note, selecting 'libaprutil1-dbd-sqlite3' for task 'lamp-server'
Note, selecting 'php7.0-common' for task 'lamp-server'
Note, selecting 'libaio1' for task 'lamp-server'
Note, selecting 'libio-html-perl' for task 'lamp-server'
Note, selecting 'ssl-cert' for task 'lamp-server'
Note, selecting 'apache2-data' for task 'lamp-server'
Note, selecting 'libperl5.22' for task 'lamp-server'
Note, selecting 'libapr1' for task 'lamp-server'
Note, selecting 'libaprutil1-ldap' for task 'lamp-server'
Note, selecting 'libhtml-tagset-perl' for task 'lamp-server'
Note, selecting 'mysql-client-core-5.7' for task 'lamp-server'
Note, selecting 'php7.0-json' for task 'lamp-server'
Note, selecting 'php7.0-readline' for task 'lamp-server'
Note, selecting 'tcpd' for task 'lamp-server'
Note, selecting 'liblua5.1-0' for task 'lamp-server'
Note, selecting 'mysql-common' for task 'lamp-server'
Note, selecting 'libhtml-template-perl' for task 'lamp-server'
Note, selecting 'libtimedate-perl' for task 'lamp-server'
Note, selecting 'apache2-bin' for task 'lamp-server'
Note, selecting 'perl' for task 'lamp-server'
Note, selecting 'apache2' for task 'lamp-server'
Note, selecting 'php-mysql' for task 'lamp-server'
Note, selecting 'apache2-utils' for task 'lamp-server'
Note, selecting 'libhtml-parser-perl' for task 'lamp-server'
Note, selecting 'libapache2-mod-php7.0' for task 'lamp-server'
Note, selecting 'liburi-perl' for task 'lamp-server'
Note, selecting 'mysql-server-core-5.7' for task 'lamp-server'
Note, selecting 'php7.0-mysql' for task 'lamp-server'
libaio1 is already the newest version (0.3.110-2).
libapr1 is already the newest version (1.5.2-3).
libaprutil1 is already the newest version (1.5.4-1build1).
libaprutil1-dbd-sqlite3 is already the newest version (1.5.4-1build1).
libaprutil1-ldap is already the newest version (1.5.4-1build1).
libcgi-fast-perl is already the newest version (1:2.10-1).
libcgi-pm-perl is already the newest version (4.26-1).
libencode-locale-perl is already the newest version (1.05-1).
libfcgi-perl is already the newest version (0.77-1build1).
libhtml-parser-perl is already the newest version (3.72-1).
libhtml-tagset-perl is already the newest version (3.20-2).
libhtml-template-perl is already the newest version (2.95-2).
libhttp-date-perl is already the newest version (6.02-1).
libhttp-message-perl is already the newest version (6.11-1).
libio-html-perl is already the newest version (1.001-1).
liblua5.1-0 is already the newest version (5.1.5-8ubuntu1).
liblwp-mediatypes-perl is already the newest version (6.02-1).
libtimedate-perl is already the newest version (2.3000-2).
liburi-perl is already the newest version (1.71-1).
libwrap0 is already the newest version (7.6.q-25).
rename is already the newest version (0.20-4).
ssl-cert is already the newest version (1.0.37).
tcpd is already the newest version (7.6.q-25).
apache2 is already the newest version (2.4.18-2ubuntu3.5).
apache2-bin is already the newest version (2.4.18-2ubuntu3.5).
apache2-data is already the newest version (2.4.18-2ubuntu3.5).
apache2-utils is already the newest version (2.4.18-2ubuntu3.5).
libapache2-mod-php is already the newest version (1:7.0+35ubuntu6.1).
libapache2-mod-php7.0 is already the newest version (7.0.28-0ubuntu0.16.04.1).
libperl5.22 is already the newest version (5.22.1-9ubuntu0.2).
mysql-client-5.7 is already the newest version (5.7.21-0ubuntu0.16.04.1).
mysql-client-core-5.7 is already the newest version (5.7.21-0ubuntu0.16.04.1).
mysql-common is already the newest version (5.7.21-0ubuntu0.16.04.1).
mysql-server is already the newest version (5.7.21-0ubuntu0.16.04.1).
mysql-server-core-5.7 is already the newest version (5.7.21-0ubuntu0.16.04.1).
perl is already the newest version (5.22.1-9ubuntu0.2).
perl-modules-5.22 is already the newest version (5.22.1-9ubuntu0.2).
php-common is already the newest version (1:35ubuntu6.1).
php-mysql is already the newest version (1:7.0+35ubuntu6.1).
php7.0-cli is already the newest version (7.0.28-0ubuntu0.16.04.1).
php7.0-common is already the newest version (7.0.28-0ubuntu0.16.04.1).
php7.0-json is already the newest version (7.0.28-0ubuntu0.16.04.1).
php7.0-mysql is already the newest version (7.0.28-0ubuntu0.16.04.1).
php7.0-opcache is already the newest version (7.0.28-0ubuntu0.16.04.1).
php7.0-readline is already the newest version (7.0.28-0ubuntu0.16.04.1).
The following packages were automatically installed and are no longer required:
  libappindicator1 libdbd-mysql-perl libdbi-perl libindicator7
  libmysqlclient20 libreadline5 libterm-readkey-perl mariadb-common
  python-appindicator python-gconf python-gobject python-pexpect
  python-ptyprocess
Use 'sudo apt autoremove' to remove them.
Suggested packages:
  mailx tinyca
The following NEW packages will be installed:
  mysql-server-5.7
0 upgraded, 1 newly installed, 0 to remove and 7 not upgraded.
7 not fully installed or removed.
Need to get 0 B/2,724 kB of archives.
After this operation, 48.4 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Preconfiguring packages ...
(Reading database ... 289162 files and directories currently installed.)
Preparing to unpack .../mysql-server-5.7_5.7.21-0ubuntu0.16.04.1_amd64.deb ...
Aborting downgrade from (at least) 10.0 to 5.7.
    If are sure you want to downgrade to 5.7, remove the file
/var/lib/mysql/debian-*.flag and try installing again.
dpkg: error processing archive /var/cache/apt/archives/mysql-server-5.7_5.7.21-0ubuntu0.16.04.1_amd64.deb (--unpack):
 subprocess new pre-installation script returned error exit status 1
Errors were encountered while processing:
 /var/cache/apt/archives/mysql-server-5.7_5.7.21-0ubuntu0.16.04.1_amd64.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

When I run apt-get update :
Fetched 306 kB in 13s (22.6 kB/s)
Reading package lists... Done
W: The repository 'http://ppa.launchpad.net/pinta-maintainers/pinta-stable/ubuntu xenial Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://ppa.launchpad.net/pinta-maintainers/pinta-stable/ubuntu/dists/xenial/main/binary-amd64/Packages  404  Not Found
E: Some index files failed to download. They have been ignored, or old ones used instead.
Fetched 306 kB in 13s (22.6 kB/s)
Reading package lists... Done
W: The repository 'http://ppa.launchpad.net/pinta-maintainers/pinta-stable/ubuntu xenial Release' does not have a Release file.
N: Data from such a repository can't be authenticated and is therefore potentially dangerous to use.
N: See apt-secure(8) manpage for repository creation and user configuration details.
E: Failed to fetch http://ppa.launchpad.net/pinta-maintainers/pinta-stable/ubuntu/dists/xenial/main/binary-amd64/Packages  404  Not Found
E: Some index files failed to download. They have been ignored, or old ones used instead.

This is maybe because the "http://ppa.launchpad.net/pinta-maintainers/pinta-stable/ubuntu/dists/xenial/main/binary-amd64/Packages" is not online, i guess. But how to solve this error, please help me out here.
Previously, I had a similar error with qbittorrent, and what i did was i opened software-properties-gtk and unticked its repository in the "other softwares" tab. But i have been told it is a bad practice to do so, so do i tick that option again, and how to change those websites?


text:
Q: Shannon's Entropy interesting problem I found Here is the problem:

A student is worried that the metro system might not operate properly
  when he goes home on a given day. There are two reasons for his
  worries: it is really Cold outside, and they may be working on the
  construction of metro Extension. He estimates that the risk of
  failure due to the cold weather is 20%. Independently, they may shut
  down traffic due to the metro Extension plans with a probability of
  50%.
How unpredictable is it that the student may not be able to take the
  subway home, i.e. that the trains are cancelled, either because of the
  cold weather or due to the construction work (or both)? Answer in
  terms of entropy, measured in bits.

The answer:
$$
P(W \lor C) = 1 − P(\neg W)P(\neg C) = 1 − 0.40 = 0.60 \\
ent = −0.6 \log_2(0.6) − 0.4 \log_2(0.4) \approx 0.971
$$
I can understand lets say that 0.6 where it came from and why, but that 0.4 I cannot really what it represents for the student at all.
My approach (which is wrong apparently) is: $ ent = −0.2 \log_2(0.2) − 0.5 \log_2(0.5) −0.1 \log_2(0.1) ≈ 1.28 $, where 0.1 is $0.5 \times 0.2 $ since events are independent.` To my understanding, my expression reads: probability it's cold, or probability there are contractions, or both. What does the correct answer expression read in layman terms?

A: The definition of entropy is
$$-\sum_{i = 1}^n\left[P(x_i) log(P(x_i))\right]$$
where $x_1, ..., x_n$ are mutually-exclusive events (or symbols, in other interpretations).
In this case, there are two mutually exclusive outcomes: success with probability $P(x_{\mbox{success}}) = 0.4$, and failure with probability $P(x_{\mbox{success}}) = 0.6 = 1 - 0.4$.
Your three-term formula might make sense if there were three mutually-exclusive outcomes: success, failure due to cold but no extension, failure due to extension but not cold, and failure due to both cold and extension. There are a number of problems here:

*

*Fundamentally, there is no reason to think that the knowledge of success/failure contains the same amount of information as the knowledge of  both success/failure and the exact cause for failure. The entropy of success/failure + reason for failure is greater (in this case) than the entropy of just success/failure.

*As you can see, for the events to be mutually exclusive, you'd need 4, not 3, events.

*Your formula has a problem in the "probabilities" not summing to 1. This is just not a valid distribution.


text:
Q: Pandas dataframe not updating during iteration (itertuples), but works independently outside of function Earlier I create a dataframe for every balance reading that contains a 0 on a particular day. But when it comes time to run the while loop, the if statement   does not ever find a nonzero balance reading, even when it does exist.
I independently ran the code for one particular account and it passed through all my code and found the previous balance and replaced it, but I had to do it sequentially, not all in one function. My guess is that itertuples is the source of this problem.
# df looks like this with amount_y being the balance (ignore amount_x for now, it represents transaction amount/day/account):

# accrual_date | financial_account_id | amount_x | amount_y

def updateBalance(df):
    index = 0
    for row in df.itertuples():
        old_balance = 0
        index_when_condition_met = 0

        if df.loc[index,'amount_y'] == 0:
            financial_account_id_search = df.loc[index,'financial_account_id']
            accrual_date_search = df.loc[index,'accrual_date']
            ordered = df[df['financial_account_id'].str.match(financial_account_id_search)].sort_values(by='accrual_date').reset_index(drop=True)

            for row2 in ordered.itertuples():

                index_when_condition_met = ordered[(ordered['accrual_date'].str.match(accrual_date_search)) & (ordered['amount_y'] == 0)].index.values[0] #takes first balance reading if more than one balance reading of 0 took place on same day

                while index_when_condition_met > 0:

                    if ordered.loc[index_when_condition_met - 1,'amount_y'] != 0: # previous balance is not 0,

                        old_balance = ordered.loc[index_when_condition_met - 1,'amount_y']
                        break
                    else: # previous balance is 0, need to check earlier entries
                        index_when_condition_met = index_when_condition_met - 1

                if index_when_condition_met == 0:
                    old_balance = 0
                    df.at[index,"amount_y"] = old_balance # might be redundant

                else:
                    df.at[index,"amount_y"] = old_balance

        index = index + 1
    return df
updateBalance(df)

The new resulting dataframe for e should have replaced all 0 values with a nonzero previous balance (if it exists).


text:
Q: XSD unique contraint based on multiple elements including an optional element I have defined a unique constraint on multiple elements : define unique constraint based on multiple elements
Now unique constraint looks like this:

<xs:unique name="specieSizeGroupLengthAssortment">
    <xs:selector xpath="DataRow"/>
    <xs:field xpath="Specie"/>
    <xs:field xpath="Group"/>
    <xs:field xpath="Length"/>
    <xs:field xpath="Type"/>
</xs:unique>

Now imagine the element "Type" is optional. So far my search and my testing confirmed, that this unique constraint only works on elements which have all the subelements defined in the unique constraint.
For example:
This should be invalid due to unique constraint:
<DataRow>
   <Specie>A</Specie>
   <Length>100</Length>
   <Group>A</Group>
</DataRow>

<DataRow>
   <Specie>A</Spacie>
   <Length>100</Length>
   <Group>A</Group>
</DataRow>

This should be valid :
<DataRow>
   <Specie>A</Specie>
   <Length>100</Length>
   <Group>A</Group>
</DataRow>

<DataRow>
   <Specie>A</Spacie>
   <Length>100</Length>
   <Group>A</Group>
   <Type>D</Type>
</DataRow>

This should be invalid :
<DataRow>
   <Specie>A</Specie>
   <Length>100</Length>
   <Group>A</Group>
   <Type>D</Type>
</DataRow>

<DataRow>
   <Specie>A</Spacie>
   <Length>100</Length>
   <Group>A</Group>
   <Type>D</Type>
</DataRow>

Is it possible to create an XSD schema that will do this kind of validation?

A: The specification states that each field in a unique constraint

must identify a single node (element or attribute) whose content or value, which must be of a simple type, is used in the constraint.

XML Schema part 1: Structures, §3.11.1, my bold.
So it appears that you can't use optional elements in a uniqueness constraint.  This is backed up by the step-by-step rules for validating these constraints (§3.11.4):

3 For each node in the ·target node set· all of the {fields}, with that node as the context node, evaluate to either an empty node-set or a node-set with exactly one member, which must have a simple type. [Definition:]  Call the sequence of the type-determined values (as defined in [XML Schemas: Datatypes]) of the [schema normalized value] of the element and/or attribute information items in those node-sets in order the key-sequence of the node.
  4 [Definition:]  Call the subset of the ·target node set· for which all the {fields} evaluate to a node-set with exactly one member which is an element or attribute node with a simple type the qualified node set. The appropriate case among the following must be true:
  4.1 If the {identity-constraint category} is unique, then no two members of the ·qualified node set· have ·key-sequences· whose members are pairwise equal, as defined by Equal in [XML Schemas: Datatypes].
  [...]

This explicitly defines the uniqueness check as applying only to the "qualified node set", i.e. those nodes matching the selector which have values for all their fields

A: I think I got it the wrong way around. Unique constraints allow absent fields; Key constraints do not.
The language is very obscure, but is easier to understand in the XSD 1.1 version because some notes have been added. I don't think there is any (intentional) change in functionality between the two versions.

*

*The {selector}, with the element information item as the context node, evaluates to a node-set (as defined in [XPath]). [Definition:]  Call this the target node set.

*Call the subset of the ·target node set· for which all the {fields} evaluate to a node-set with exactly one member which is an element or attribute node with a simple type the qualified node set.
So if some selected node has a missing value for one of its fields, then this node is not part of the qualified node-set.

*

*If the {identity-constraint category} is unique, then no two members of the ·qualified node set· [may] have ·key-sequences· whose members are pairwise equal, as defined by Equal in [XML Schemas: Datatypes].

This means that for "unique", selected nodes for which a field is absent are simply ignored.

*

*If the {identity-constraint category} is key, then all of the following must be true:
4.2.1 The ·target node set· and the ·qualified node set· are equal, that is, every member of the ·target node set· is also a member of the ·qualified node set· and vice versa.

This means that for "key", the data is invalid if one of the fields is missing.
I'm left concluding that the original schema as posted almost does what is required, except that the first example is not invalid: for both selected nodes there is a field missing, therefore neither selected node is included in the qualified node-set, therefore the unique constraint has no effect. To make this invalid, you will need a second "unique" constraint that only lists the first three fields. But then you will get a validity error if these three fields are the same, even if the fourth field is present.
In XSD 1.1 of course you can solve the problem with an assertion, along the lines
test="count(DataRow) = count(distinct-values(DataRow/concat(
                         Specie, '|', Length, '|', Group, '|', Type)))


text:
Q: Joda DateTime array sort array by date time I have an arraylist of Joda DateTimes like this:
List <DateTime> nextRemindersArray = new ArrayList<DateTime>();
nextRemindersArray.add(reminderOneDateTime);
nextRemindersArray.add(reminderTwoDateTime);
nextRemindersArray.add(reminderThreeDateTime);

I am trying to sort the dates in ascending order but I am having trouble:
I googled it and found this page:
https://cmsoftwaretech.wordpress.com/2015/07/19/sort-date-with-timezone-format-using-joda-time/
I tried it like this:
nextRemindersArray.sort(nextRemindersArray);

But it gives me the error:
Error:(1496, 37) error: incompatible types: List<DateTime> cannot be converted to Comparator<? super DateTime>

I then tried like this:
DateTimeComparator dateTimeComparator = DateTimeComparator.getInstance();
nextRemindersArray.sort(nextRemindersArray, dateTimeComparator);

and also like this:
nextRemindersArray.sort(nextRemindersArray, new DateTimeComparator());

but all have errors.
I tried the Joda time manual and that wasn't much help. How do I sort the array?
Thanks in advance for your help

A: What you are looking for is:
nextRemindersArray.sort(DateTimeComparator.getInstance());

But because DateTime already implements Comparable, you don't really need a comparator and you can simply use:
nextRemindersArray.sort(null); //uses natural sorting
//or probably more readable
Collections.sort(nextRemindersArray);

Note that a quick look at the documentation of List::sort would have shown you that the method expects only one argument and it has to be a Comparator (and not two arguments like in your question).

A: Lets say we have SomeClass with this method getCreatedDate() which returns a DateTime joda object.
For a List you can have a simple comparator:
private Comparator<Listing> byCreatedDate = Comparator.comparing(SomeClass::getCreatedDate);

Then in your code you can call:
 ...
 listings.sort(byCreatedDate);
 return listings;
 ...

Haven't tested it but ... the idea should be ok.
In Kotlin you would call listing.sortedBy { it.createdDate }


text:
Q: bpftrace execsnoop not catch "echo" command I'm trying to figure out what execsnoop can catch or not. \
ENV
Distributor ID: Ubuntu
Description:    Ubuntu 22.04.1 LTS
Release:    22.04
Codename:   jammy
5.15.0-48-generic
bpftrace v0.16.0

Terminal 1
execsnoop.bt

Terminal 2
ls
/usr/bin/echo
/usr/bin/echo a
strace echo a
echo a          # Not showed in Terminal 1
echo            # Not showed in Terminal 1

*

*The docs say it catches which event call exec() https://github.com/iovisor/bpftrace/blob/master/tools/execsnoop_example.txt. But command strace echo a actualy call it. https://github.com/iovisor/bpftrace/pull/1490/files \

>strace echo a
execve("/usr/bin/echo", ["echo", "a"], 0x7fff01460c38 /* 30 vars */) = 0
brk(NULL)                               = 0x55d40d778000
arch_prctl(0x3001 /* ARCH_??? */, 0x7fff0f437c90) = -1 EINVAL (Invalid argument)
mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7f93860f4000

A: My guess is that strace echo a forces the use of /usr/bin/echo, a binary which your shell exec() into, whereas just running plain echo in the terminal uses a built-in from your shell, and as such does not trigger an exec().
This is why /usr/bin/echo a works as expected as well.
info echo from bash mentions the built-in:
   Due to shell aliases and built-in 'echo' functions, using an
unadorned 'echo' interactively or in a script may get you different
functionality than that described here.  Invoke it via 'env' (i.e., 'env
echo ...') to avoid interference from the shell.

You will also likely get different outputs from echo --help and /usr/bin/echo --help.


text:
Q: Outlook REST API. How to start new thread on forward message? First i want to ask how the Outlook client decides if a message that the user wrote should be in the same thread(conversation) or in a new one on forward of a message.
From my observations it checks the subject, but does it check also something else.
I'm using the Outlook rest api v2 and beta versions.
To force the api to create the message in new thread i tried setting the subject in the following patern:
Fwd: { subject of the message i forward} or
Fwr: { subject of the message i forward}
The only successful approach was to add some character to the end of the subject text, but i'm afraid that this might be considered as a bug from some users.
So is there some way to create the message in a new thread when calling /messages/{message_id}/createforward endpoint?
Looking forward for an answer to this.

A: I used a different approach when it came to Forward/Reply messages, because I had some issues with Attachments. It seems that my approach could be useful in your case as well.
When I want to forward a message, I retrieve all the attachments of the message and I add 'FW:' at the beginning of the subject, and then I use https://outlook.office365.com/api/v2.0/me/sendmail as If I am sending a new email! That will start a new thread! I hope it works for you.


text:
Q: Reload Webpage when timeout Mechanize Hi guys my code is basically used to check a number of links i've gave to find certain tags in the webpage. Once found it will then give me back the links that i've gave. However, sometimes mechanize will get stuck forever trying to open/read the page unless i've set a timeout. Are they any ways to reload/retry the webpage upon time out?
import mechanize
from mechanize import Browser
from bs4 import BeautifulSoup
import urllib2
import time
import os
from tqdm import tqdm
import socket

br = Browser()

with open("url.txt", 'r+') as f:
lines = f.read().splitlines()

br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]

no_stock = []
for i in tqdm(lines):
    r = br.open(i, timeout=200)
    r = r.read()
    done = False
    tries = 3
    while tries and not done:
        try:
            soup = BeautifulSoup(r,'html.parser')
            done = True # exit the loop
        except:
            tries -= 1 # to exit when tries == 0
    if not done:
        print('Failed for {}'.format(i))
        continue # skip this and continue with the next
    table = soup.find_all('div', {'class' : "empty_result"})
    results = soup.find_all('strong', style = 'color: red;')
    if table or results:
        no_stock.append(i)

Updated error:
  File "/usr/local/lib/python2.7/dist-packages/mechanize/_response.py", line 190, in read
    self.__cache.write(self.wrapped.read())
  File "/usr/lib/python2.7/socket.py", line 355, in read
    data = self._sock.recv(rbufsize)
  File "/usr/lib/python2.7/httplib.py", line 587, in read
    return self._read_chunked(amt)
  File "/usr/lib/python2.7/httplib.py", line 656, in _read_chunked
    value.append(self._safe_read(chunk_left))
  File "/usr/lib/python2.7/httplib.py", line 702, in _safe_read
    chunk = self.fp.read(min(amt, MAXAMOUNT))
  File "/usr/lib/python2.7/socket.py", line 384, in read
    data = self._sock.recv(left)
socket.timeout: timed out

Any help is appreciated!

A: catch the socket.timeout exception and retry there:
try:
    # first try
    soup = BeautifulSoup(r,'html.parser')
except socket.timeout:
    # try a second time
    soup = BeautifulSoup(r,'html.parser')

You can even try many times, and if a line fails, continue with the next:
for i in tqdm(lines):
    r = br.open(i, timeout=200)
    r = r.read()
    done = False
    tries = 3
    while tries and not done:
        try:
            soup = BeautifulSoup(r,'html.parser')
            done = True # exit the loop
        except: # just catch any error
            tries -= 1 # to exit when tries == 0
    if not done:
        print('Failed for {}'.format(i))
        continue # skip this and continue with the next
    table = soup.find_all('div', {'class' : "empty_result"})
    results = soup.find_all('strong', style = 'color: red;')
    if table or results:
        no_stock.append(i)


text:
Q: Add two voltage signal and Convert output to current signal I generated two different Signals using DDS and now I want to add them and convert output signal to current signal without any distortion in it? what is the best and accurate part I can use ?

A: You can use opamp summer circuit for adding two signals.See the link below for detailed explanation.
https://www.electronics-tutorials.ws/opamp/opamp_4.html
Then again use opamp at the ouput stage to convert V(voltage) to I(current).(V to I converter) .see the link below
https://wiki.analog.com/university/courses/electronics/text/chapter-4
Ask if you have any doubt regarding this explanation


text:
Q: Are these functions equivalent in TensorFlow? I'm a newbie wit TensorFlow and I've studying it for the last few days.
I want to understand if the following two functions are equivalent or not:
1.
softmax = tf.add(tf.matmul(x, weights), biases, name=scope.name)

2.
softmax = tf.nn.softmax(tf.matmul(x, weights) + biases, name=scope.name)

If they are in fact different, what is the main difference?

A: softmax1 = tf.add(tf.matmul(x, weights), biases, name=scope.name)

is not equal to
softmax2 = tf.nn.softmax(tf.matmul(x, weights) + biases, name=scope.name)

since softmax1 has no softmax calculation at all while softmax2 does. See the Tensorflow API for tf.nn.softmax. The general idea of a softmax is that it normalizes the input by rescaling the whole data sequence ensuring their entries are in the interval (0, 1) and the sum is 1.
The only thing that is equal between the two statements is the basic calculation. + does the same thing tf.add does so tf.add(tf.matmul(x, weights), biases) is equal to tf.matmul(x, weights) + biases.

EDIT: To add some clarification (I think you do not know really know what softmax is doing?):
tf.matmul(x, W) + bias

Calculates a matrix multiplication between x (your input vector) and W the weights for the current layer. Afterwards the bias is added.
This calculation models the activation of one layer. Additionally you have an activation function, like the sigmoid function which transforms your activation. So for one layer you normally do something like this:
h1 = tf.sigmoid(tf.matmul(x, W) + bias)

Here h1 would be the activation of this layer.
The softmax operation simply rescales your input. E.g., if you got this activation on your output layer:
output = [[1.0, 2.0, 3.0, 5.0, 0.5, 0.2]]

The softmax rescales this input for fitting the values in the interval (0, 1) and being the sum equal to 1:
tf.nn.softmax(output)
> [[ 0.01497873,  0.0407164 ,  0.11067866,  0.81781083,  0.00908506,
     0.00673038]]

tf.reduce_sum(tf.nn.softmax(output))
> 1.0


text:
Q: Find all compilation errors in a Delphi project I am doing some refactoring of my Delphi project. I want to be able to make a change, then see all the places in the project that break due to that change. Similar to how Eclipse lists all the compile errors for a project (in Java).
In Delphi, I can make a change, then recompile my project, but the compiler stops when it finds the first Unit that does not compile. I have to fix that Unit, compile again, which will then show me the next error, etc etc.
I want to be able to see all the compile errors in the project at once. Then I can decide if the change is worth doing or not. For example, if the change will require hand fixing of 50 separate source files, it's not worth doing. But if it only breaks 2 files then that's an easy change to make.
Is there any way to do this in Delphi? Can I tell the compiler to keep going even after finding a Unit that does not compile?
I am using Delphi 2010

A: There's no way to do that with the Delphi compiler, but if you're considering making a breaking change to some part of a unit's public interface, you can use the refactoring tools that come with the IDE to find all references to whatever it is you're about to change before you change it, which will give you the information you're looking for.

A: Delphi units, as a modularity feature, are conceptually at a similar level to Java jars or .NET assemblies; they compile to individual files. In neither Java nor .NET can you compile dependent modules when you have compile errors in a referenced module.
The reason they are more granular than .NET assemblies etc. owes to their history. They were designed in part around the segmented x86 architecture; the data associated with any one unit could not be any larger than 64KB. Similarly, units served as a natural division between near code and far code. If you're familiar with 16-bit x86, you'll know that pointers to far data required a value for the segment as well as the offset, while near data only needed an offset. Calling near code was also faster than calling far code. Programs were also smaller and less complex back then; the unit was a reasonable granularity of module for an entire subsystem's worth of behaviour. This is much less the case today.

A: The Delphi compiler already tries to compile as much as it can.
Unfortunately, very often, an error is critical enough to prevent the compiler to move past the error as it cannot make an assumption as to what the code should be it if were compilable.
Moreover, very often, the errors a compiler can give after the 1st error has been encountered are not reliable and may even disappear after the 1st error has been fixed. (witnessed by all the red squiggly lines appearing and disappearing when you type)
What the compiler does however is to provide all the hints and warnings (which are called errors for some other compilers).

A: You can use Ctrl-Shift-Enter to see all occurances of the variable, property, method or wahtever is currently under the cursor. With that information you can decide to do your changes or not.
Alas, with the current version this feature doesn't work as reliable as it should.


text:
Q: Storing blocks in a c-style array I am trying to dynamically instantiate a c array of blocks, load it and then run them and could use some help.
// Definitions ===========================================
typedef void (^MorphC)(ScratchC* scratch);

@property (nonatomic) MorphC __strong * morphCs;

// Building up the Morph Registry ========================
static NSMutableDictionary* morphs_;
+ (void) initialize {
    morphs_ = [[NSMutableDictionary alloc] init];
    [MathC hydrate];
}
+ (void) hydrate {
    [MathC registerMorph:@"sin" execute:^(ScratchC* scratch) {
        AEScratchPush(scratch, sin(AEScratchPop(scratch)));
    }];
}
+ (void) registerMorph:(NSString*)name execute:(MorphC)execute {
    [morphs_ setObject:execute forKey:name];
}
+ (MorphC) morphFromKey:(NSString*)key {
    return [morphs_ objectForKey:key];
}

// Loading up a temporary NSMutableArray* _compiling =====
- (void) applyTag:(NSString*)tag stack:(Stack*)stack {
    [_compiling addObject:[MathC morphFromKey:tag]];
}

// Initializing C Array and loading from NSMutableArray ==
- (void) build {
    _morphCs = (MorphC __strong *)malloc(_compiling.count*sizeof(MorphC));
    i = 0;
    for (MorphC morph in _compiling)
        _morphCs[i++] = morph;              // Currently, getting a bad ACCESS here
}

// Executing the Morphs ==================================
- (CGFloat) evaluateFloat:(VarsC*)vars {
    if (![_morphs count]) return NAN;
    AEScratchLoadVariables(_scratch, vars);

    for (int i=0;i<[_morphs count];i++)
        _morphCs[i](_scratch);

    return AEScratchPop(_scratch);
}

I'm currently getting a EXC_BAD_ACCESS while building up the C Array, but I suspect I have a number of issues.  I don't totally understand the need for the __strong at the morphCs definition, but the compiler complains with out.  Should the property have a strong indicator also?
Do I need to be doing [morph copy] in one or more places?
Is there anything else I'm messing up?

A: You can't malloc an array of strong pointers.
Think about the semantics of a strong pointer: When it is declared, it's value is initialized to nil. When the variable goes out of scope, it releases its existing value. Therefore, the compiler must be able to keep track of strong pointers to be able to carry this out. If you have an array of strong pointers of unknown length, when it goes out of scope for example, how can the compiler know how many pointers to release? It can't.
In C++ terminology, strong references are "non-POD" types - they have nontrivial constructors and destructors. Therefore, they cannot be allocated with malloc.
It is mentioned here in the ARC specification:

It is undefined behavior if a managed operation is performed on a
  __strong or __weak object without a guarantee that it contains a primitive zero bit-pattern, or if the storage for such an object is
  freed or reused without the object being first assigned a null
  pointer.

In other words, the only way you can use malloc and free is if you guarantee that every time after you call malloc you zero the memory of all the pointers you allocated, before using them. And every time before free you guarantee to first assign nil to each strong pointer in the array.
However, in Objective-C++, you can use new[] and delete[] to dynamically allocate arrays of strong pointers.

These requirements are followed automatically in Objective-C++ when
  creating objects of retainable object owner type with new or new[] and
  destroying them with delete, delete[], or a pseudo-destructor
  expression.


text:
Q: Cannot query Active Directory using ServerBind on non-domain computer in Windows PE I have a need to write a .NET application which will query Active Directory while running in Windows PE on a computer which is not yet a member of the domain.
We are running this during a Microsoft Deployment Toolkit task sequence (note that MDT 2012 has been configured to load support for .NET into the WinPE environment - the .NET application is starting without any problems).
I am using the code below to bind to the domain:
DirectoryEntry entry = new DirectoryEntry(
  path,
  username,
  password,
  AuthenticationTypes.ServerBind | AuthenticationTypes.Secure);

I have tried a path both of the form:
LDAP://domainServer/dc=domain,dc=name
And also without a domain controller name as
LDAP://dc=domain,dc=name
I have also tried using a username both of the form domain\username and also just username.
The DirectoryEntry object seems to be constructed okay, but when I try to execute Console.Writeline(entry.Name) to confirm a valid connection has been made, I get the following exception:

System.Runtime.InteropServices.COMException (0x80005000): Unknown
  error (0x80005000)    at
  System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
  at System.DirectoryServices.DirectoryEntry.Bind()    at
  System.DirectoryServices.DirectoryEntry.get_Name()

I have tried other variations on this code, trying to execute LDAP queries with various filters, trying to rewrite it in VBScript, etc... but the code posted above is the simplest example I could come up with which reproduces the problem.
From what I have read, in a scenario like this you would always need to use AuthenticationTypes.ServerBind and that is why I am trying to specify the code within the ADSI LDAP path. But what is wrong with the code above? To me, it looks like it is passing all needed information in the parameters to the DirectoryEntry constructor.

A: There is a way to get it work, but it's not supported by Microsoft. This post helped me a lot. It works, tested and approved for a deployment of new computers :)
Get the ADSIxXX.inf from the zip file to C:\ADSI
Copy the following files from a Windows/System32 to C:\ADSI. Carefull of Architecture
 x86 x64 -
   adsldp.dll
   adsmsext.dll
   adsnt.dll
   mscoree.dll
   mscorier.dll
   mscories.dll

Mount the bootimage.wim
No need to load Package (Your WinPE is already configured to load .NET API), juste add ADSI driver:
Dism /Image:C:\Mount /Add-Driver /Driver:C:\ADSI\ADSIxXX.inf /forceunsigned

No need to load his script
Unmount the bootimage.wim
Then it's done, if your .NET application is well implement ;)
I'm not sur the PIPE | is supported as an argument too, just set to AuthenticationTypes.Secure -
DirectoryEntry entry = new DirectoryEntry(
  path,
  username,
  password,
  AuthenticationTypes.ServerBind | AuthenticationTypes.Secure);

Link: http://www.deploymentresearch.com/Research/tabid/62/EntryId/74/ADSI-plugin-for-WinPE-4-0.aspx#AddComment


text:
Q: Understanding of Oracle Statement-Level Read Consistency between Oracle 10g and 10g+ I'm new to Oracle and I just want to confirm my understanding of Statement-Level Read Consistency for Oracle 10g and 10g+.
The Oracle 10g document states:

Oracle always enforces statement-level read consistency. This guarantees that all the data returned by a single query comes from a single point in time—the time that the query began. Therefore, a query never sees dirty data or any of the changes made by transactions that commit during query execution. As query execution proceeds, only data committed before the query began is visible to the query. The query does not see changes committed after statement execution begins.

Oracle 11g document states:

Oracle Database always enforces statement-level read consistency, which guarantees that data returned by a single query is committed and consistent with respect to a single point in time. The point in time to which a single SQL statement is consistent depends on the transaction isolation level and the nature of the query:

*

*In the read committed isolation level, this point is the time at which the statement was opened. For example, if a SELECT statement opens at SCN 1000, then this statement is consistent to SCN 1000.

*In a serializable or read-only transaction this point is the time the transaction began. For example, if a transaction begins at SCN 1000, and if multiple SELECT statements occur in this transaction, then each statement is consistent to SCN 1000.

*In a Flashback Query operation (SELECT ... AS OF), the SELECT statement explicitly specifies the point in time. For example, you can query a table as it appeared last Thursday at 2 p.m.

See the bold text. If I understand correctly, Oracle changed its behavior between 10g and 10g+. In 10g, Statement-Level Read Consistency is always based on the view when the statement starts. In 10g+, Statement-Level Read Consistency is based on a view that depends on the isolation level and the query itself. Is my understanding correct? Thank you.

A: The behaviour did not change. It has been the same since Oracle 7 at least (probably before, but that was before my time) and still is today with Oracle 19. The documentation was just expanded to include the behaviour at isolation levels other than the default READ COMMITTED, or when using the Flashback Query mechanism.
(You should really be looking at the latest documentation: https://docs.oracle.com/en/database/oracle/oracle-database/index.html - 11g is very old)
The important point is that the default isolation used by Oracle (statement-level consistency) implies that repeating the same statement may not deliver the same result since other transactions may have updated the data during the first execution of the statement. Oracle uses multi-version consistency to provide concurrent access such that readers don't block writers and writers don't block readers.


text:
Q: How to install this github ruby(gem) project on my ubuntu system? I am new to Ruby and this project is a ruby gem.
Link to the project https://github.com/cheerfulstoic/music.
I can't find any steps to setup this project.

A: That's a Ruby gem.
Just install it manually:
gem install music

or add the following to your Gemfile, when your project uses Bundler:
gem 'music'