text:
Q: Can a duress code(s) be designed for the moderators to indicate type of coercion? Can a system of duress codes be designed for the remaining moderators to signal if, when, and where from any directives are being forced on them?
The post that prompted this was from StackOverflow's meta.  Specifically, this one: I'm resigning as a Stack Overflow Community Elected Moderator
The entire question and its subsequent discussion is powerful reading.  I've lurked here for a few years and have come to appreciate George Stocker's presence more recognizably than most.  This departure announcement has led me to break my silence.
By all appearances, the remaining mods are greatly restricted in what they're allowed to say.  Given SO's willingness to go to the press with what seem to be misdirections and half-truths (AND letting those go unretracted for 2+ weeks and counting), I would not be surprised to learn of the existence of significant dirty leverage.  Has more doxxing been threatened?  Are there lawsuits being waved around?
All trust I've ever had for SO has been shattered and scattered to the wind.  As someone who controls the budget for my IT Department, I can safely say that there is no possibility of my ever adopting Teams now.  It's a non-starter unless I see a massive turnaround in behavior from SO here - not just saying "we'll do better next time" but actually fixing the damage from their speaking with The Register.
Barring that, I would like to see if we can get an inkling of the nature for the perceived threats over the existing mods.  It seems like we should be able to do something of this nature - https://tvtropes.org/pmwiki/pmwiki.php/Main/CovertDistressCode?from=Main.DuressCode

A: No need.
We don't work for SE. We'd quit and/or complain loudly. Sometimes both.
Some of the most vocal advocates against the way the company is doing many things are former employees. Monumental blunders were made from the perspectives of many, and this is a mess that makes many people unhappy.
The only thing remotely resembling leverage is the fact that we care deeply for the communities we are part of.
(PS - If anyone has my dirty laundry please return it laundered and folded. Thank you)
.. / -- . .- -. --..-- / .-- .... .- - / -.. --- / -.-- --- ..- / .-- .- -. - / ..- ... / - --- / -.. --- --..-- / .--. --- ... - / .. -. / -- --- .-. ... . / -.-. --- -.. . ..--..

A: Your premise that moderators are being threatened somehow is just wrong. There are several hundred of us network-wide and as a group are some of the most active and outspoken users of the network. Moderators aren't paid so have nothing to lose directly. Surely some, especially the resigning ones, would just speak out?
Moderators are privy to some private information which we are rightly expected to be careful with, but in reality all the significant stuff about the recent events is public anyway. If you think moderators are being muted in their opinions, it may be because they don't want to inflame the situation further, or are having their say privately.


text:
Q: Is it possible to create a Map that has ArrayList properties with log(n) complexity? I am trying to build a generic data structure that needs to hold keys and values and in the same time keep track on the index's in which key's and values were put in like arraylist do just in a complexity of O(log n) or less.
I tryed to work around a solution to this problem and created various TreeMaps that has Integer - index's and valuse and vise-versa, and the same with keys.
Just to make it more clear, the Index's symbolize the insertion order from the user. so if I had 3 elements then their index's are 0 1 2 and if element 0 was deleted then I need to push 1 to 0 and 2 to 1 and a new element would be added with index 2.
My problem is when I remove a key and its value, if I want to insert the next key and value in the right index I have to make sure all the old ones were set back by 1. I don't know how to do it and not to fall into O(n) complexity.
My goal is to use existing data structure's and mixing them to get this result, please take a look at the methods I implemented as I need those.
I am adding my code for reference, any help would be much appreciated.
Thank you
Tom
import java.util.Collection;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Map;

public class SuperStruct<K,V>
{
    private Map<K,V> mInternalKeyToValueMap;//all the keys and their values
    private Map<Integer,V> mIndexToValueMap;//index's for values according to the entrance order to
    private Map<V,Integer> mValueToIndexMap;//values and their index's
    private Map<Integer,K> mIndexToKeyMap;//index's and their keys according to entrance order
    private Map<K,Integer> mKeyToIndexMap;//keys and their index's
    private int mNextIndex;//index for the data structure according to the order data was received by user

    public SuperStruct(){
        mInternalKeyToValueMap = new TreeMap<K,V>();
        mIndexToValueMap = new TreeMap<Integer,V>();
        mValueToIndexMap = new TreeMap <V,Integer>();
        mIndexToKeyMap = new TreeMap <Integer, K>();
        mKeyToIndexMap = new TreeMap <K,Integer>();
    }
    public boolean containsKey(Object key) {
        boolean containable = mInternalKeyToValueMap.containsKey(key);
        return containable;
    }

    public boolean containsValue(Object value) {
        boolean containable = mValueToIndexMap.containsKey(value);
        return containable;
    }

    public V get(Object key) {
        if(mInternalKeyToValueMap.containsKey(key)){
            V value = mInternalKeyToValueMap.get(key);
            return value;
        }
        return null;
    }

    public Collection<K> keySet() {

        return mInternalKeyToValueMap.keySet();
    }
    /**
     * This method is putting the key and the value in the main TreeMap "mInternalKeyToValueMap", while on the mean time updating 4 other TreeMaps
     * with data regarding to the index in which data was received from the user.
     * all in all this method runs in complexity of 6*(O(log n)) that sums down to O(log n) cause constants don't calculate over the whole
     * Complexity calculation
     * In case that a key already had a mapping to it and we overwrite the value we will run in complexity of 11*(O(log n)) which still sums down to O(log n)
     * cause constants don't calculate over the whole
     */

    public V put(K key, V value) {
        if(mValueToIndexMap.containsKey(value))//preventing duplications of value
            return value;
            if(mInternalKeyToValueMap.containsKey(key)){//when a key already exist in system and we want to overwrite its value
                int indexToDelete = mKeyToIndexMap.get(key);//we get the index of the value we over-write
                V value1 = mIndexToValueMap.get(indexToDelete);//using this index we get the value
                mValueToIndexMap.remove(value1);//we remove the value and its index
                mIndexToValueMap.remove(indexToDelete);//we remove the index and its value
            }
            mInternalKeyToValueMap.put(key, value);//putting the new value for the key in the main TreeMap
            mValueToIndexMap.put(value, mNextIndex);//populating the TreeMap of values and their index's - the order we received them from the user
            mIndexToValueMap.put(mNextIndex, value);//This TreeMap holds the index's for each value according to the order of insertion by user
            mIndexToKeyMap.put(mNextIndex, key);//This TreeMap holds the index's for each key according to the order of insertion by user
            mKeyToIndexMap.put(key,mNextIndex);//populating the TreeMap of keys and their index's - the order we received them from the user
            ++mNextIndex;//advancing the index which mark the insertion order of arguments to structure
            return null;

    }

    public V remove(Object key) {
        if(mInternalKeyToValueMap.containsKey(key)==true && (mInternalKeyToValueMap.get(key)!=null))
        {
            V value = mInternalKeyToValueMap.get(key);
            mInternalKeyToValueMap.remove(key);//removing map for the value
            int mIndexToRemoveValue = mValueToIndexMap.get(value);//getting the right index to remove the value
            mIndexToValueMap.remove(mIndexToRemoveValue);//vacating the value for this index
            mIndexToKeyMap.remove(mIndexToRemoveValue);//vacating the key for this index
            mKeyToIndexMap.remove(key);//removing a key and index in the keyToIndex Map
            mValueToIndexMap.remove(value);//removing a key and index in the ValueToIndex Map
            return value;

        }
        return null;
    }

    public Collection<V> values() {
        return mInternalKeyToValueMap.values();
    }

    public Collection<V> getStrcutureSorted(){
        return mValueToIndexMap.keySet();
    }

    public V getValueByIndex(int index){//return the index in which the value sits in, if not present null
        V value = mIndexToValueMap.get(index);
            return value;
    }

    public Integer getIndexByKey(K key){
        Integer returnable = mKeyToIndexMap.get(key);
        if(returnable == null)
            return -1;
        return returnable;

    }
    public K getKeyByIndex(int index){
        return mIndexToKeyMap.get(index);
    }
    }

A: This is an interesting conundrum. It feels like it should be possible, but the details are elusive. The problem is in the index update operation after a delete. If the indexes are stored in a tree node, for example, then on average n/2 indexes will have to be altered after a delete operation, which ruins the O(log n) property you are striving for.
If you store objects simultaneously in a tree and in an ArrayList, you still have the issue of locating an object in the ArrayList, which I can't get to work in a straightforward fashion in time less than O(n). Possibly there's some variation on an ArrayList, perhaps a custom construction, but that seems like a lot of work.
Instead, I suggest you consider a red-black tree or similar balanced tree with the modification noted at Red-black tree access by ordinal index: for each node of the tree, store also the count of nodes in the subtree with the given node as root. During insert and delete operations, you will have to update the count of all nodes affected by a rotation operation. That can still be done in O(log n) time, but it is complicated.
Then binary searches for the kth smallest (or largest) element will also run in O(log n) time, as usual, by the usual recursive algorithm.
Here are a few more references for the technique: http://www.cs.usfca.edu/~galles/cs673/lecture/lecture8.pdf, http://fdatamining.blogspot.ca/2011/09/functional-red-black-tree-with-dynamic.html, http://en.wikipedia.org/wiki/Order_statistic_tree. That should get you started.
Update: implementation details
What you will have to do is to create two trees. One could be an ordinary balanced tree (like a red-black tree) to hold references to your objects with key/value pairs. You could search on the key and get the corresponding value in O(log n); insertion and deletion would also be O(log n). In addition, nodes in this first tree would hold references to nodes in the second tree (below).
The second tree would also hold references to nodes in the first tree, but it would be an order statistic tree as in the discussion above. Insertions would always place new items at the right end of the tree.
An insert operation into this data structure would be an ordinary insert into the first tree by key, an insert into the right side of the order statistic tree, and the references in each inserted node would be updated to point to the appropriate location in the other tree.
A search operation could be done on the first tree for a given key in O(log n), which would return the appropriate value, and following a reference to the other tree, could be used to find the "order statistic" of the node in the second tree in O(log n) time by traversing up the tree to the root and performing a simple calculation.
A search operation could be done on the second tree in O(log n) time for the kth position in the queue, returning a reference to the second tree, which could be dereferenced to obtain the associated key/value pair.
Deletion in either tree would be preceded by deferencing the reference to the other tree, then deletion of the node in the first tree, followed by deletion of the corresponding node in the other tree, both O(log n) operations.
I think that's it. Everything can be done in O(log n) time. There is a minor cost in space for the second tree, but it just contains references; space is still O(n).
Does that work?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Restricting the constructor-access to certain classes Let's say I want to restrict the access to the constructor of a public class, so that only certain classes may create an instance of it, but all classes are able to use the instance.
In Java, I know two ways to archive this:

*

*Make a public static inner class with a private constructor and instantiate it in the outer class.

*Make the classes constructor package-private (restricts access to all classes in the same package).

In PHP however, there are no inner classes and the namespaces (which are close to packages) have no own access-modifier (ergo no package-private).
So, how can I protect the access to the classes constructor?


text:
Q: JMS and IBM WebSphere not generating COD I am creating an application that consumes messages from a MQ using JMS. My MQ manager is IBM WebSphere MQ and I am using the IBM jms implementation to consume the messages.
The messasges are coming and going fine. I receive the messages from the other part and I can send messages to them. The problem is that they are not receiving the COD after I consume the message from the queue. They receive the COA, but no COD.
Here is my receive message code:
public byte[] readMsgFromClient() throws JMSException {
        byte[] message = null;
        QueueReceiver reader = null;
        try {
            connection = getQueueConnection();
            connection.start();
            session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

            Queue queue = session.createQueue(config.getQueueRsp());

            ((MQQueue) queue).setTargetClient(JMSC.MQJMS_CLIENT_NONJMS_MQ);

            reader = session.createReceiver(queue);

            JMSBytesMessage byteMessage = (JMSBytesMessage) reader.receive(3000);

            if (byteMessage != null) {
                message = new byte[(int) byteMessage.getBodyLength()];
                byteMessage.readBytes(message);
            }
        } finally {
            if (reader != null) {
                reader.close();
            }

            if (session != null) {
                session.close();
            }

            if (connection != null) {
                connection.close();
            }
        }

        return message;
    }

Do I have to manually send the COD? DO I have to configure my WebSphere to automatically send the COD? Do I have to notify the WebSphere that my application has consumed the message?

A: The COD messages are probably ending up the the dead letter queue (DLQ) with an RC (Reason Code) of 2035 (not authorized).
Here is another of those things you learn the hard way:

*

*COA messages are generated under the queue manager's UserId

*COD messages are generated under the UserId of the sender's message.

If the sending application's UserId is appl001 then the COD will be generated using the UserId of appl001.  If that UserId does not have permission to write to the particular queue then the message will end up in the DLQ.
Generally, the permission issue happens when the sender application is connected to 1 queue manager and the receiver application is connected to another queue manager.  i.e. messages are hoping between queue managers.
Hence, the sender's UserId does not have permission to put a message on the remote queue manager.

A: As stated by @Roger, the permissions to put the COD are based on the UserId in the MQMD of the message that is sent.
If you do not want to add the remote user to your local system you can use the itsoME exit provided in the IBM Redbook "Secure Messaging Scenarios with WebSphere MQ".  The latest version is found under the "Additional Material" link.
With this exit you need to have a MCAUSER set on your RCVR or RQSTR channel and configure that channel with the following attributes:
MSGEXIT('itsoME(MsgExit)')
MSGDATA('MCA/')

The result is that UserIdentifier field of the MQMD will be changed to the value of the MCAUSER that is configured on the channel.  You would then give that MCAUSER +put and +passid to the XMITQ that returns to the remote queue manager.
The exit can be used for other things such as removing the reporting options if you do not want to allow COA/COD.


text:
Q: Unable to programmatically expand TreeNode that is assigned to a TreeView I am working with C++ and .NET 1.1. I have an issue with programmatically expanding TreeNode objects once they are assigned to a TreeView. When running the following code in debug mode:
TreeView* myTreeView = new TreeView();
TreeNode* myTreeNode = new TreeNode();
myTreeNode->Expand();
myTreeView->Nodes->Add(myTreeNode);
myTreeNode->Expand();

I can see that the IsExpanded property of myTreeNode is set to true when doing the first Expand(), but when the node is added to myTreeView IsExpanded is set to false, and the second Expand() has no effect at all.
Can anyone explain this behavior? I'm thinking there is a setting for the TreeView or something similar, but I haven't been able to find anything like that, and from the example code MS provides this should work just fine, so I'm probably missing something pretty obvious...

A: I suggest adding a myTreeNode->Collapse() before calling the expand. It could be that the node thinks it is expanded when it is not and so calling expand will just be ignored because the node thinks it is already expanded anyway...
  TreeView* myTreeView = new TreeView();
  TreeNode* myTreeNode = new TreeNode();
  myTreeNode->Expand();
  myTreeView->Nodes->Add(myTreeNode);
  myTreeNode->Collapse();
  myTreeNode->Expand();

A: Have you tried listening for the TreeView.AfterCollapse event to see if someone else is collapsing the TreeNode after you add it to the TreeView?


text:
Q: web3React and solana/web3.js in one lib working together with MetaMask and Phantom wallets is there any library out there that integrates web3React and solana/web3.js so that they can co-exist and do all the operations when the user switches chains from EVM chains to Solana and the other way back, as well as support for chainId and account?
If not, how would you approach the following:

*

*User connects to Phantom wallet via solanaProvider.connect() on a button click. Now the user has access to a list of chains [1, 56, 137, 'Solana'] that they can choose from to switch to another network. The user connected to chain 'Solana' and we now have access to PublicKey. But now the user wants to switch to EVM chains ([1, 56, 137]). How do you handle this action in the app. There is no RPCs method to switch from Solana to EVM since Solana has not been build in cross-chain way so we do not have methods that would allow to switch like we do with
evmProvider.request({ method: 'wallet_switchEthereumChain', params: [{ chainId: '0x${chainId.toString(16)}' }], })
So you can easily switch from EVM to EVM chain using the RPC methods and web3React lib will emit the events properly and update chainId and account. But how do you handle the EVM to non-EVM chain switch so that the front-end knows that user now wants to be on chain 1 and evmAccount or other way round.
So far I have been using web3React lib and augmented it to my own hook, let's call it useMyWeb3ReactHook with some extra changes. There I also packed in a custom-built useMySolanaWeb3Hook that returns provider, pubKey and chainID.
The app so far is using useMyWeb3ReactHook in different places and I would like to keep just one hook from which the app reads provider, (pubKey || account) and chainID.
I also have at least 3 places where I request the chain switch just by passing chainID to wallet_switchEthereumChain method. I was thinking of creating a redux state, let's call it nonEvmState that would also get updated if requested chainID === 'Solana' and then pass that nonEvmState to useMyWeb3ReactHook where I would say if nonEvmState then chainID is 'Solana'. If user wants to switch back to EVM -> Reset the nonEvmState and hopefully switch back to evm chain.
How others are doing it that support EVM and Solana? Would be curious to learn.
Thanks for your suggestions


text:
Q: Object property and object prototype EDITED
What is the difference in doing:
var a = function(){};
a.myProperty = function(){};

Versus:
var a = function(){};
a.prototype.myProperty = function(){};

I realise this might be a silly or vague question but what do I need to understand to know the difference between the two and when to use one over the other?

A: There is no difference. Your setting a property on an object.
Note that your second example fails because you havn't set a.prototype to a value.
Of course if you made a a function then it gets a prototype property by default.
And that .prototype property has a special property. If you invoke new someFunction then the [[Prototype]] of the return value is someFunction.prototype.
This only applies if .prototype is a property of a function. Since new only works on functions.

A: Note that the question has been heavily edited since it was first posed, which is why the existing comment and answer make no sense.
All functions have prototypes. The methods attached to these prototypes are available to instances of objects created by calling the function as a constructor. So in the second example, if you write var o = new a(); then you will be able to invoke o.myProperty();.
Additionally all functions are objects, so you can set arbitrary properties directly on the function itself, as per the first example. You can also access the function from the object using o.constructor (or this.constructor from a member function). This could be used to implement the equivalent of C++ static class variables.


text:
Q: How to push commit without adding the merge commit when there are updates in remote mainline Say I pull the mainline of a repo, make some changes, added one commit my_commit. At the same time, someone else pushed someone_commit to remote mainline. Now if I want to push, if I do git pull, there will be conflicts and I have to add a merge commit. Is there a way I could achieve something like previous_commits->someone_commit->my_commit instead of `
previous_commits->someone_commit -> merge commits of ...
                ->my_commit      ->

A: Yes, this is the purpose of git rebase.
Something like:
git rebase origin/mainline

This will reset your branch to mainline (with previous_commits at the tip), then replay your commits on top.
You will be prompted to resolve conflicts if there are any.

The following doesn't sound relevant to your current situation, but note that this will change the history of your local branch. If you have already pushed your local commits to a development branch, you will need to use a force push to rewrite the history on the remote development branch. But if, as you say, you and a colleague are working on the same branch, then this isn't likely to be a problem (and a force push on a shared branch can cause major issues)


text:
Q: Why do I receive "This value should be of type string" when using a DateTime constraint on Symfony 5? I have the following entity (only attached the relevant parts):
use ApiPlatform\Core\Annotation\ApiResource;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ApiResource(mercure=true)
 * @ORM\Entity(repositoryClass="App\Repository\EventRepository")
 */
class Event {
    /**
     * @ORM\Column(type="datetime")
     * @Assert\DateTime
     * @Assert\NotNull
     */
    private $createdAt;

    public function __construct() {
        $this->createdAt = new \DateTime();
    }

    public function getCreatedAt(): ?\DateTimeInterface {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTimeInterface $createdAt): self {
        $this->createdAt = $createdAt;
        return $this;
    }
}

Its repository:
class EventRepository extends ServiceEntityRepository {
    public function __construct(ManagerRegistry $registry) {
        parent::__construct($registry, Event::class);
    }
}

When creating a POST request to the event endpoint (via Postman or the Swagger UI), it fails with the following exception:

A: You are using the wrong of assertion.
Date expects a string or an object that can be cast into a string. And a DateTimeInterface is neither.
You should be using a Type constraint.
/**
 * @Assert\Type("\DateTimeInterface")
 */
 private $createdAt;

The ability to use Assert\Date to validate DateTime objects was deprecated on Symfony 4.2, and on Symfony 5.0 it was removed altogether.


text:
Q: Function doesn't return anything (async?) I'm trying to add XPATH evaluation into my form. When user fills XPATH, it's evaluated on a server using AJAX and then return true or false.
The problem is that this function seems to return undefined allways. I suppose it's because of asynchronious behaviour of JS so I used $.when but it didn't helped.
function evalXpath(xpath) {
    var test = $.post('/api/test-xpath/', {'xpath': xpath});
    test.done(function (data) {
        console.log('BEFORE RETURN '+Boolean(data['success']));
        return Boolean(data['success']);
    })
}

$(document).ready(function () {
    $('#id_xpath').on('change', function () {
        var xpath = $("#id_xpath").val();
        $.when(evalXpath(xpath)).done(function (evaluated) {
            console.log('RETURNED '+evaluated);
            $('#xpath-valid').text(evaluated ? 'VALID' : 'INVALID');
        });

    });

});

The console output (as you can see, it's still asynchronious):

Do you have any ideas?

A: You're really close. A couple of things:

*

*You forgot to return the promise out of evalXpath.

*To get proper promise value chaining (e.g., in order for your value from the callback inside evalXpath to then become the resolution value of the promise it returns), use then, not done.

*Then when using evalXpath, there's no need for $.when.
So:
function evalXpath(xpath) {
    var test = $.post('/api/test-xpath/', {'xpath': xpath});
    return test.then(function (data) {
//  ^^^^^^      ^^^^
        console.log('BEFORE RETURN '+Boolean(data['success']));
        return Boolean(data['success']);
    })
}

// ...
evalXpath(xpath).then(function (evaluated) {
//               ^^^^ (this one could be `done`, but let's be consistent)


text:
Q: Picasa for Linux: doesn't it support video files? I'm just switching from Windows to Linux. I'm glad to see that Picasa is also available (v3.0 beta), but doesn't Picasa on Linux support video files? This official help page doesn't mention Linux...
I've just imported some files from my camera, but Picasa skipped all the videos.

A: Due to licensing issues, Picasa on Linux does not support videos at all.
From the FAQ:

Q: Hey! I have a bunch of movie files
  that Picasa skipped.
Picasa for Linux does not support
  movie files. The program will not
  attempt to find or play movies. (Note:
  under Options > File Types, the Movies
  checkbox is visible but not
  functional.)

A: Se here http://ubuntuforums.org/showthread.php?t=1385837   for a solution. I've followed this, and works well. :)


text:
Q: функция не выводит числа в excel файл есть формула (K=A*(1-exp(-LT))^n). при запуске функции она должна выводить(записывать) в excel -файл значения K, A, L, n, T, но при запуске она просто зависает. (по сути это обычная подборка чисел для решения уравнения)
def Calc():
    global path
    workbook = openpyxl.load_workbook(path)
    print(workbook.get_sheet_names())
    sheet = workbook.active
    for A in range (1, 6):
       for L in range (1, 6):
           for n in range (1, 6):
               for T in np.arange (0.01, 1.00, 0.01):
                   K=A*pow((1-math.exp(-L*T)), n)
                   for i in range (0, 3):
                       c1 = sheet.cell(row = i+10, column = 1)
                       c1.value=K
                       c2 = sheet.cell(row = i+10, column = 2)
                       c2.value=A
                       c3 = sheet.cell(row = i+10, column = 3)
                       c3.value=L
                       c4 = sheet.cell(row = i+10, column = 4)
                       c4.value=n
                       c5 = sheet.cell(row = i+10, column = 5)
                       c5.value=T
                   workbook.save(path)

A:     for A in range (1, 6):
       for L in range (1, 6):
           for n in range (1, 6):
               for T in np.arange (0.01, 1.00, 0.01):
                   K=A*pow((1-math.exp(-L*T)), n)
                   for i in range (0, 3):
                      ...
                   workbook.save(path)

У вас запись файла находится внутри четырёх вложенных циклов, если посчитать, вы перезаписываете файл 100 * 5**3 = 12500 раз, поэтому так тормозит. Записывайте файл один раз в самом конце:
    for A in range (1, 6):
       for L in range (1, 6):
           for n in range (1, 6):
               for T in np.arange (0.01, 1.00, 0.01):
                   K=A*pow((1-math.exp(-L*T)), n)
                   for i in range (0, 3):
                      ...
    workbook.save(path) # <- запись после выполнения всех циклов


text:
Q: Tossing a coin until you have more heads than tails I toss a coin a many times, each time noting down the result of the toss. If at any time I have tossed more heads than tails I stop.
I.e. if I get heads on the first toss I stop.
Or if toss T-T-H-H-T-H-H I will stop.
If I decide to only toss the coin at most 2n+1 times, what is the probability that I will get more heads than tails before I have to give up?

A: Let $C_n$ be the $n$-th Catalan number, defined by $\frac{1}{n+1}\binom{2n}{n}$. Let's also say that you keep tossing even after you had more heads than tails, for good measure. Then there are $2^{2n + 1}$ different sequences of tosses you could've made. How many of them will at some point have more heads than tails?
We will divide this by cases in the following way: Any sequence that does at some point have more heads than tails are grouped together according to the number of tosses it took to get more heads for the first time. That means, for instance, that half of all the sequences (the ones starting with head) are in group $0$. The ones that took $3$ coin tosses are in group $1$ and so on. The ones that made it to the more-heads-than-tails-side only on the last coin flip are in group $n$.
How many sequences are in each group? Say we have the group labelled $i$. That means that for any sequence in this group, after $2i$ throws they have exactly as many heads as tails, and at no point before have they had more heads. There are $C_i\cdot 2^{2n-2i}$ tossing sequences like that. $C_i$ because that's how many ways you can reach the spot, and $2^{2n-2i}$ because that's how many ways it can go on after this, provided that the $(2i + 1)$th throw is a heads (which it is; that was the definition of group $i$).
So we're left with calculating the following sum:
$$
\sum_{i = 0}^n 2^{2n-2i}C_i = \sum_{i = 0}^n \frac{2^{2n-2i}}{i+1}\binom{2i}{i}
$$
and then divide it by $2^{2n + 1}$, and you have your probability.
PS. I don't know how to calculate the sum, but WolframAlpha says it's equal to
$$
2^{2 n+1}-\frac{1}{2} \binom{2(n+1)}{n+1}
$$
which suggests there are $\frac{1}{2}\binom{2(n+1)}{n+1}$ sequences of coin tosses that are $2n + 1$ long and that never have more heads than tails in any initial segment.

A: There is no harm in imagining that we toss the coin $2n+1$ times and simply look to see whether at some point we got a success (meaning more heads than tails at that point).
Say that a finite string of H's and T's is balanced if it contains an equal number of H's and T's, and that it is completely unbalanced if it has no balanced initial segment. Let $U$ be the set of completely unbalanced strings of length $2n+2$; the lemma in this proof and the remarks preceding it show that $|U|=\binom{2n+2}{n+1}$.
Let $U_T$ be the set of completely unbalanced strings of length $2n+2$ that start with T; these are the ones that have an excess of T's over H's in every non-empty initial segment. There is clearly a bijection between $U_T$ and $U_H$, the set of $\sigma\in U$ that start with H, and $U_T\cap U_H=\varnothing$, so $|U_T|=\frac12\binom{2n+2}{n+1}$.
Let $\sigma\in U_T$. If you delete the initial T from $\sigma$, you get a string of length $2n+1$ whose non-empty initial segments all have at least as many T's as H's, i.e., strings that are not successes. Conversely, prepending a T to any unsuccessful string of length $2n+1$ produces a string in $U_T$. Thus, exactly $\frac12\binom{2n+2}{n+1}$ of the $2^{n+1}$ strings of length $2n+1$ are failures, and there must therefore be
$$2^{n+1}-\frac12\binom{2n+2}{n+1}$$
successes.

A: I will expand my comment.
Set $N=2 n+1$ and $S_k= \sum_{i=1}^k X_i $, where the $X_i$ are i.i.d.r.v. assuming values $+1, -1$ with equal probability ($S_0=0$ a.s.). This is the simple random walk. The idea is that we associate to head a +1 and to tail a -1.
What you are looking for is the probability of the event $A=\max_{1 \leq k \leq N} S_k \geq 1$; that is before $N$ the random walk passed 1 which means you had 1 more head than tails.
For $l$ positive integer define $T_l$ as the first time the random walk hits the level $l$ (the event $A$ corresponds to $T_1 \leq N$); the reflection principle implies $P(T_l \leq r) = 2 P(S_r \geq l) - P(S_r = l)$. I think you can find a proof of that on the internet, if you need it I will write it.
Coming back to you case you have:
$$
P(T_1 \leq N) = 2 P(S_N \geq 1 ) - P(S_N=1)=
$$
$$
=1- \binom {2n+1}{n+1} \ 2^{-(2n+1)} .
$$
EDIT.
One version of the reflection principle says that
$$
P(T_l \leq r \cap S_r < l ) = P(T_l \leq r \cap S_r > l ).
$$
Note that  $(S_r>l) \subset (T_l \leq r)$, so the R.H.S is equal to $P(S_r >l)$.
Note also that $(T_l = r \cap S_r < l) = (T_l = r \cap S_r > l) = \emptyset$.
Then:
$$
P(T_l < r \cap S_r <l) = \sum_{k=1}^{r-1} P(T_l=k \cap S_r<l) = \sum_{k=1}^{r-1} P(T_l=k \cap S_r-S_k<0)
$$
The last step is because $T_l=k$ implies $S_k=l$.
The event $(T_l=k) \in \sigma\{X_1,...,X_k\}$, while $S_r-S_k <0 \in \sigma \{X_{k+1},...,X_r\}$ and those sigma-algebras are independent.
So
$$
P(T_l=k \cap S_r-S_k<0) = P(T_l=k)P(S_r-S_k<0)=P(T_l=k)P(S_r-S_k>0)
$$
where last equality follow from the symmetry of $S_r-S_k$.
Proceeding backwards, the result follows.
This implies:
$$
P(T_l \leq r) = P(T_l \leq r \cap S_r \geq l) + P(T_l \leq r \cap S_r < l)=
$$
$$
=P(S_r \geq l) + P(S_r > l )=2 P(S_r \geq l) - P(S_r = l ).
$$

A: As in some previous answers, assume that you continue tossing the coin even if you get more heads than tails at some point, so you have a total of $2n+1$ tosses and $2^{2n+1}$ possible outcomes of the tosses.
To count the number of sequences of tosses in which we never get more heads than tails, we can use Andre's reflection principle:
The number of tails t must be larger than the number of heads h, so $n+1\le t\le 2n+1$, and the number of tosses in which tails never falls behind heads is
given by
$\displaystyle\sum_{t=n+1}^{2n+1} \bigg[\binom{2n+1}{t}-\binom{2n+1}{t+1}\bigg]=$
$\big[\binom{2n+1}{n+1}-\binom{2n+1}{n+2}\big]+\big[\binom{2n+1}{n+2}-\binom{2n+1}{n+3}\big]+\big[\binom{2n+1}{n+3}-\binom{2n+1}{n+4}\big]+\cdots+\big[\binom{2n+1}{2n+1}-\binom{2n+1}{n+2}\big]$
$=\binom{2n+1}{n+1}$, so the probability of getting more heads than tails at some point in the tosses is equal to
$1-\binom{2n+1}{n+1}/2^{2n+1}$.


text:
Q: Datastructure ambiguity I can't figure this interview question.
You have an array of integers. You need to provide another Data structure that will have these functions:
int get(int index)
void set (int index, int value)
void setall(int value)

They all do what you guess they're suppose to do.
The limitation is that every function is in O(1).
How can you design it so that setAll will be O(1).
I thought about adding another field to each  integer, that will point to an integer that will be changed every time setAll is called. the problem comes when someone call setAll and then set then get.
Edit: I changed the names of the variables so it would be clearer. Also, since you asked, get is suppose to return array[i], set(index, value) suppose to put the value value in array[index].
After setall(index, value) you should get (get(i) == get(j) == value) for every i,j in the array.

A: How about storing a "version number" with each variable, i.e.
 int globalValue, globalVersion;
 int nextVersion;
 int[] localValue, localVersion;

 int get(int i) {
     if (localVersion[i] > globalVersion)
         return localValue[i];
     else
         return globalValue;
 }

 void set(int i, int value) {
     localValue[i] = value;
     localVersion[i] = nextVersion++;
 }

 void setAll(int value) {
     globalValue = value;
     globalVersion = nextVersion++;
 }

A: Keep a DateTime field ( or simply a counter ) with each element in the array, a setAllValue variable and setAllDateTime variable. With each set, update the DateTime/counter of the element. With SetAll, update the value and DateTime of setAllDateTime.
In get, compare the DateTime of SetAll with DateTime of the element, whichever is newer, return that.


text:
Q: Showing properties of unit tangents I'm working my way through the book Vector Calculus by Marden and Tromba and I've run into a bit of trouble on one of the problems (more like I'm clearly misunderstanding them but I'm not sure how). The question is as follows:
For $c:[a,b] \rightarrow \mathbb{R}^{3}$ we say $T(t) = c'(t)/||c'(t)||$ is the unit tangent to c. Show that $T'(t) \cdot T(t)=0$. What is $T'(t)$ in terms of c?

A: I think this formula will help you: $(a\cdot b)'= a'\cdot b+ a\cdot b'$.
And we know $T\cdot T=1$, a constant. What can we say about it?


text:
Q: Brms Causing R Session Aborted (R Encountered Fatal Error)
I keep getting this error when running brm function from brms package for building bayesian model.
I couldnt find what causes this error
Anyone have any suggestions on how to solve this? Thanks a lot for help!


text:
Q: Object Exporter + VS community 2013 =? Do you guys know if  Object Exporter (https://visualstudiogallery.msdn.microsoft.com/c6a21c68-f815-4895-999f-cd0885d8774f) can be used for Visual Studio Community 2013?
Thanks!

A: It works perfectly to install it in VS community 2013


text:
Q: How to find examples of periodic points of the (complex) exponential-function $z \to \exp(z)$? Background: By considering the question  which asks whether a certain summation-method $\mathfrak M$ for the (extremely divergent!) sum $\mathfrak M: S(z)=z + e^z + e^{e^z}+e^{e^{e^z}} + ...$ might be valid, I had the idea, that a good test for the validity of the summation-method would be to compare one result with cases, where the sum can be given on some standard way.
For instance, if $z$ is a fixpoint $p$  of $\exp(z)$  having  $\exp(p)=p$ then $S(p) = p + p+ p+ p+...$ which could possibly been evaluated using the $\zeta(0)$ - definition.
But this is possibly no good test, a better one were, if for instance $p$ were a $2$- periodic point where the sign changes, (let's denote a fixpoint $p_1$ and a $2$-periodic point $p_2$) such that $\exp(p_2)=-p_2$ and the series becomes $S(p_2)=p_2 - p_2 + p_2 - ... + ...$ which can then be assumed to be the Cesarosum of the alternating series of a constant.
First steps of my own approach: This led to the idea to find such $2-periodic$ points to have example cases.
What I've done so far was to screen segments of the complex plane , say a square around some $z_0$ of size $2x2$ in steps of $1/10$ and find local minima. Then take each local minima of the error ($|z_0 - e^{e^z}|$  as new center of a new square with $0.2 x 0.2$ size, and iterate this two or three times until the error is small enough and then use Newton-iteration to finally find a point $p_2$ (hopefully meeting the requirements for Cesaro-summability!).
This gave by tedious manual screening an initial set of $2$-periodic points. But all so far found $2$-periodic points were on the real-positive halfplane and so not suited for Cesaro-summation of $S(p_2)=p_2-p_2+p_2-...$ with alternating signs.
Here is a picture which included  a couple more points which I found by extrapolating linear trends in subsets of the found ones. See my initial answer here

Question 1:
So my first question is now for ideas,
 - 1) how could I improve the search-routine? (Perhaps avoiding that manual screening at all)
The extrapolation-idea is very useful and allows to find infinitely many more $2$-periodic points completely automatically, but it still needs an initial manual screening to get at least $3$ points as germ for the extrapolation.
Question 2:
The picture contain no pairs of $2$-periodic points having alternating signs on the real part.
I've tried to find analytically better solutions, of to even prove there are no such points, but arrived nowhere definite so far.
 - 2) Are there really no $2$-periodic points with negative real part?
Question 3 & 4:
If there are indeed no such cases, what about $3$-periodic points or in general $n$-periodic points?
 - 3) Are there $n$-periodic points with negative real part?
 - 4) Is there any analytical method known how to find $n$-periodic points without manual screening? (For the finding of $1$-periodic (or "fix"-) points we have the Lambert W-function. For generalizing the Lambert W I had found a scheme giving power series, but which have extremely small range of convergence and I think are thus useless here)

A: The structure of the periodic points of the exponential map is well-understood. Observe that the real axis is invariant and contains no periodic points; its preimages contain the horizontal lines at imaginary parts that are integer multiplies of $\pi$.
Consider the strips
$$ S_k := \{ a + ib\colon (2k-1)\pi < b < (2k+1)\pi\}.$$
Every periodic point $z$ has an "itinerary" $(k_n)_{n=0}^{\infty}$, defined by
$$ f^n(z) \in S_{k_n}.$$
(Here $f$ is the exponential map and $f^n$ its $n$-th iterate.)
Clearly the itinerary is a periodic sequence whose period divides the period of $z$.
It is known that every periodic sequence is realised by a periodic point. When $(k_n)_{n=0}^{\infty}$ is not the sequence $k_n \equiv 0$ for all $n$, this periodic point is unique and, in particular, has the same period as $(k_n)$.
For the sequence defined by $k_n\equiv 0$, there are two fixed points, one in the upper half-plane and one in the lower half-plane, which are complex conjugates of each other.
The periodic point for a given itinerary can be obtained by backwards iteration, as you mention. That is, let $L_k\colon \mathbb{C}\setminus (-\infty,0]\to S_k$ denote the inverse of the map $f|_{S_k}$. If $z\notin\mathbb{R}$, then define
$$ z_m := L_{k_0}(L_{k_1}(\dots(L_{k_m})\dots)).$$
Then the sequence $z_m$ will converge to a periodic point with the desired itinerary, and this point is unique, except for the exceptional case $k_n\equiv 0$, where it depends on whether $\operatorname{Im} z$ is positive or negative.
It is also known that every periodic point as above, except for the case $k_n\equiv 0$ has a periodic curve to $\infty$ attached to it, periodic of the same period. This curve is called a "Devaney hair" or "external ray", and all points except the periodic endpoint converge to infinity under iteration.
I think that all of this can already be found in the paper by Devaney and Krych (Dynamics of $\exp(z)$, ETDS, 1984). They use a somewhat different convention for itineraries, but the results are equivalent.

A: As you may remember, you need to solve in general the $p$-th auxilliary exponential equation to find the fixed points first. The first auxilliary is $f(z)=z$, with $f=exp$. This is solved by using Lambert's $W$ function as $z_k=-W_k(-1)$, $k\in\mathbb{Z}$. None of these is stable as $|f'(z_k)|>1$. The second auxilliary is $f^{(2)}(z)=z$ or $e^{e^z}=z$. This cannot be solved in terms of elementary functions, so you need to use Newton's method. Once you find a solution $z_0$, the fixed points will be $z_0$ and $f(z_0)$. You can test then for the period, by using the modulus of the derivative of the multiplier, as given by Shell, as $|(f^{(2)})'(z_0)|$. If that's less than one, then it will be a 2-cycle, with limits $z_0$ and $f(z_0)$.
In general you'll have to solve the $p$-th auxiliary $f^{(p)}(z)=z$, for which you can still use Newton's method, but as the composition becomes more and more entangled, it will progressively be slower and may even fail. If you get a point $z_0$, then all $\{z_0,f(z_0),f^{(2)}(z_0),\ldots,f^{(p-1)}(z_0)\}$ will be fixed points, which you can check using again the modulus of the multipler $|(f^{(p)})'(z_0)|$.
With that said, it's unknown really whether there are points of period $p$ for arbitrary $p$ in both tetration of the exponential and/or regular tetration. You can only check individual values. In one of my papers I extract the fixed points using functions which generalize $W$, but the check is still the same. They all have to go through Shell's multiplier to check for the modulus. You can get a rough idea on where to look, by graphing the iterates of the exponential like this.

A: update: an update on the Pari/GP routine, few textual improvements
I've got a sudden enlightenment which seems to solve the problem completely.
The key here is, that on one hand the fixed- and periodic points of $\exp(z)$ are all repelling (this was also mentioned/proved in an article of Shen/Rempe-Gillen, pg 1, see reference below), and on the other hand the one single fixed point of $\log(z)$ is nicely attracting, but it is only a singular occurence.
$1$-periodic points/fixed points
Well, further fixed points can be found by using branches of the $\log()$, say
$$ \text{lb}(z,k) = \log(z) + k \cdot C \qquad \text{where } C = i 2 \pi$$
We may then have for some $p_1 = p_1' + C $ the equality
$$ \exp(p_1) = p_1 = p_1' + C = \exp (p_1'+ C) $$
and on the other hand the inverse relation
$$ \text{lb} (p_1,1) = p_1'+ C = \text{lb}(p_1'+C,1)$$
Noticing this we can exploit the attractive property of the (iterated) logarithmizing to converge from some initial value to the desired fixpoint, say from $z=1+I$ to some $p_1$ .
Example:
z = 1+I     | %681 = 1 + I
z=lb(z,1)   | %682 = 0.34657359 + 7.0685835*I
z=lb(z,1)   | %683 = 1.9568606 + 7.8049907*I
z=lb(z,1)   | %684 = 2.0852451 + 7.6083262*I
z=lb(z,1)   | %685 = 2.0654578 + 7.5864764*I

From where we can now use the Newton-iteration to get even quadratic convergence rate and then find the arbitrary well approximated value of the desired fixed point $\exp(z)=z$
z=newton(z) | %686 = 2.0622777 + 7.5886312*I
exp(z)-z    | %687 = 6.6538205 E-211 - 1.9010916 E-211*I

Using the $k$'th multiple of the constant $C=i2\pi$ we can now find (and index) the (infinitely many) complex fixed points ($1$-periodic):
 $$ p_1 = \text{lb}(p_1,k) \to \exp(p_1)=p_1$$
Another example:
p_1 = 1+I         | %688 = 1 + I
p_1=lb(p_1,3)     | %689 = 0.34657359 + 19.634954*I
p_1=lb(p_1,3)     | %690 = 2.9774671 + 20.402703*I
p_1=lb(p_1,3)     | %691 = 3.0262041 + 20.275440*I
p_1= newton(p_1)  | %692 = 3.0202397 + 20.272458*I
exp(p_1)-p_1      | %693 = 1.6045424 E-219 + 0.E-220*I  \\ error is machine- epsilon

2-periodic points
That procedere for finding $1$-periodic points is of course well known. For the finding of $1$-periodic (or: fixed-) points we have also the LambertW-function and their branching behaviour for even an immediate solution. But none such function is known for the $n$-periodic points for $n\ge 2$. Thus we have to find our own procedure now...
For that search of $2$-periodic fixpoints I'll not go to explain the formulae in detail (it is trivial but too tedious for this answer-box), but I simply state that for the search for a solution to
$$ \exp(\exp(p_2) ) = p_2 \ne \exp(p_2) $$
it suffices to use -instead of the iterated exponential-function- the iterated branched logarithm-function, where the branch-index is allowed/required to change between the two steps of iteration:
$$ p_2 =  \text{lb}( \text{lb}(p_2,k_0),k_1) $$
Initialize arbitrarily, iterate and, if desired, refine using the Newton-iteration on the $\exp(\exp())$ function.
Example:
p_2 = 1+I                | %694 = 1 + I
p_2=lb(lb(p_2,-1),0)     | %695 = 1.7063287 - 1.5078409*I
p_2=lb(lb(p_2,-1),0)     | %696 = 1.9537456 - 1.4538908*I
p_2=lb(lb(p_2,-1),0)     | %697 = 1.9430376 - 1.4429267*I
p_2= newton(p_2)         | %698 = 1.9428329 - 1.4437804*I
exp(exp(p_2))-p_2        | %699 = 6.1238446 E-202 - 1.6330252 E-201*I
exp(p_2)-p_2             | %700 = -1.0588348 - 5.4784957*I

We have now:
 p_2            | %701 = 1.9428329 - 1.4437804*I
 exp(p_2)       | %702 = 0.88399815 - 6.9222761*I
 exp(exp(p_2))  | %703 = 1.9428329 - 1.4437804*I

which is indeed a $2$-periodic point.
It is meaningful now, to simplify the notation for finding $2$-periodic points. Just let us use a vectorial notation for the two branch-indexes and write
$$ p_2 = \text{Find}([k_1,k_2])  $$
implemented as Pari/GP-function (Pseudocode)
  Find(K) = my(z=1+I,k_1=K[1],k_2=K[2]);    \\ K is the vector [k_1,k_2]
     for(t=1,5,       \\ 5 or even only 3 iterations suffice to start Newton
           z=lb(z,k_1);
           z=lb(z,k_2);
         );
     return(Newton(z)) ;

Update A better routine, which also employs the Newton-iteration on the branched iterated logarithm (instead on iterated exponentiation):
 \\Pari/GP
 default(realprecision,200) \\ my usual numerical precision
 pi2i=2*Pi*I                \\ constant
 {Find(K,maxerr=1e-100,maxit=25,z0=1+I)=my(err,L,z,l_prod,n=#K);
    L=vector(n); \\ shall contain the sequence of logarithms/periodic points

    \\ the following preconditioning is likely not needed at all
    L[1]=z0; for(it=1,3,for(i=1,n,L[(i % n) + 1]=lb(L[i],K[i])));
    z0=L[1];

    \\ Newton-iteration on branched iterated logarithm,initial value z0
    for(it=1,maxit,
      z=z0;
      L[1] = l_prod = z;
      for(i=1,n,  L[(i % n)+1]=z=log(z)+K[i]*pi2i;  if(i<n,l_prod*=z) );
      err = (z-z0)/(1/l_prod-1); \\ denominator contains derivative
      z0 -= err;
      if(abs(err) < maxerr,break());
      );
    return(L);}

end update
Using $Find([k_1,k_2])$ for $k_1=-3..3$ and $k_2=0..12$ I get the following chart of $1$- and $2$-periodic points (they are $1$-periodic when $k_1=k_2$) where the first parameter $k_1$ controls the color:

To see the $2$-periodicities, below is the same picture whith the pairs of periodic points connected by straight lines:

It is worth to note, that $2$-periodic points of the form $\text{Find}([k,-k])$ give pairs of complex conjugate numbers (big red diamonds), while $\text{Find}([k,k]) (=\text{Find}([k]))$ give $1$-periodic points (big brown circles). Note moreover that the $1$-periodic and the conjugate $2$-periodic points lay asymptotically on an (exponential) curve which can be seen, when the scale of the imaginary axis is taken as logarithmic (or even better transformed to $\sinh^{-1}()$ to see also the numbers with negative imaginary component ).
3-,4-,5-,... n-periodic points
If we extend the $\text{Find}([...])$ function to $3,4,5,...n$ entries $\in \mathbb Z$ in the vector-argument we find easily any $n$-periodic point which we like. $\text{Find}([0,0,1])$,$\text{Find}([0,0,-1])$,$\text{Find}([0,0,2])$,...$\text{Find}([0,1,1])$ ...
Finally $\text{Find}([k_1,k_2,k_3])$ with $k_1,k_2,k_3 \in \mathbb Z$ give all $3$-periodic points, and in case $k_1=k_2=k_3$ the $1$-periodic fixed points and in case $k_1=k_2=k_3=0$ the primary fixed point of the $\log()$-function. Unfortunately, as Y. Galidakis pointed out in his answer, the Newton-iteration for higher iterates of the $\exp()$ gets more&more involved; numerical checks up to $n=63$ and $20$ iterations in the $\text{Find}([...])$-function however looked very promising but are still under consideration.
See here some picture for examples for $n=3$,$n=5$,$n=11$,$n=31$ - periodic points.

*

*$3$-periodic examples

Here the coloring is chosen to make the exemplars of one shape-family better discernible where one shape-family is meant as having chosen $k_1,k_2$ constant and only $k_3$ varying.

*

*$5$-periodic examples

*

*$13$-periodic examples

I have shown only one exemplar because the overlay of more exemplars of the shape-family makes the picture too chaotic

*

*$31$ - periodic example

Here I show 4 exemplars of a very special shape-family by keeping all but one of the vectorial arguments to zero:
$$\text{Find}([0,0,...,0,k_{31}])$$
which produces the natural iteration-map for the $\log()$ for $30$ steps and then in one step adds $k_{31} \cdot C$ .
Of course, this typical shape-family exists analoguously for all $n$-periodic points.

Remark
This scheme, if it is really exhausting (what seems obvious to me), gives nice intuition in more general statements about the nature of the set-of-periodic points of the exponential function.

*

*The number of $2$-periodic fixpoints is then that of $\mathbb Z^2$. All of them can be indexed like the rational numbers by a pair of 2 integer indexes.

*The number of $n$-periodic fixpoints is then that of $\mathbb Z^n$. Indexing as before, but with $n$-tuple of integer indexes.

*If I understand the topological concept of "dense subset" correctly it is immediately obvious, that the set of $n$-periodic points is "dense" (Shen/Rempe-Gillen give a reference to a proof)

*Because there is so far no reason to assume that some class of $n$-periodic points might be missing/impossible, this answers one doubt in Galidakis' answer, by here claiming that $n$-periodic point for all $n$ exist and there are $\mathbb Z^n$ of them.(See also Shen/Rempe-Gillen, Theorem 1.1)

*I don't know yet, whether it shall be possible to find, for instance for the $2$-periodic points, a simpler analytical description than this of the iterated branched logarithms, for instance by a parametrical definition of the curves on which that points lay, for instance to prove the exhaustiveness of my method for the set of 2-periodic orbits/points.
Shen, Zhaiming; Rempe-Gillen, Lasse, The exponential map is chaotic: an invitation to transcendental dynamics, Am. Math. Mon. 122, No. 10, 919-940 (2015). ZBL1361.37002.
Update: an article which deals with the question of $p_1$ (fixed-) points on the braches of the $\log()$-function is by Stanislav Sykora (2016) at his web-space here . Don't know really whether the exposition can be used at least as proof for the questions whether the set of fixed points $p_1$ found by this method here is really exhaustive, though.

A: At question 2 and 3:
I didn't find any 2-periodic points where (at least) one has negative sign on the real part.
It seems that the few cases with negative real parts are not helpful/powerful enough to base a Cesaro-summation of the infinite series on the n-periods of the periodic points.

The following are periods found by random-generating vectors of $K$ (values $-10...10$, periods as documented. For each period length 2000 tries. Nothing systematic so far!
 period:5
 [0, 0, -5, 6, 0]
 3.59082749599 + 1.47618971232*I
 1.35645844221 + 0.390038693480*I
 0.344597110913 + 0.279988561156*I
 -0.811918635625 - 30.7336040230*I
 3.42570548172 + 36.1019037153*I

 period:5
 [0, -3, 7, 0, 0]
 1.39589550907 + 0.381166300943*I
 0.369493169111 + 0.266563764150*I
 -0.786115761464 - 18.2245911795*I
 2.90370129081 + 42.3683926548*I
 3.74874562619 + 1.50236871704*I

6
 period:6
 [0, 0, 5, 0, -2, 0]
 2.50151898932 - 1.46197427832*I
 1.06381612289 - 0.528895733527*I
 0.172303614637 - 0.461379744497*I
 -0.708253491774 + 30.2025438493*I
 3.40820103291 + 1.59424215683*I
 1.32512022296 - 12.1288407143*I

 period:6
 [-10, -2, 0, 0, 0, 0]
 -0.865726055159 - 1.16777496158*I
 0.374096952332 - 65.0405893212*I
 4.17502806712 - 14.1314152585*I
 2.69024296013 - 1.28352546925*I
 1.09217349774 - 0.445163548252*I
 0.165016321238 - 0.387035882053*I

 period:6
 [6, 0, 0, 0, 1, -5]
 1.94758289292 - 29.7291698287*I
 3.39426995654 + 36.1937328801*I
 3.59326415488 + 1.47728921312*I
 1.35714636151 + 0.390061973605*I
 0.345069979151 + 0.279869780194*I
 -0.811260602392 + 6.96462918257*I

7
 period:7
 [-3, -4, 9, 0, 0, 0, -1]
 -0.750444308081 - 5.74329299488*I
 1.75649728498 - 20.5502806192*I
 3.02651414772 - 26.6182716405*I
 3.28802037436 + 55.0910858620*I
 4.01076580829 + 1.51118369513*I
 1.45535723212 + 0.360331909844*I
 0.404999059491 + 0.242709153027*I

 period:7
 [-8, 5, -7, 1, 0, 0, 6]
 -0.170370792911 + 38.2832303265*I
 3.64502185218 - 48.6902358879*I
 3.88827281086 + 29.9198522843*I
 3.40689602021 - 42.5407328375*I
 3.75365864051 + 4.79230392555*I
 1.80621689648 + 0.906341375286*I
 0.703523044147 + 0.465078494459*I

8
 period:8
 [9, 2, 6, -10, 1, 0, 0, 4]
 -0.183435398095 + 25.6847041258*I
 3.24592114662 + 58.1266057847*I
 4.06418024304 + 14.0813826162*I
 2.68486042576 + 38.9889234027*I
 3.66564298323 - 61.3298103386*I
 4.11804903195 + 4.77208731106*I
 1.84106769616 + 0.858834846465*I
 0.708790828907 + 0.436479925461*I

 period:8
 [0, 6, 2, 8, 3, -2, 0, 0]
 1.02121461182 - 0.489741421848*I
 0.124493728473 - 0.447168470622*I
 -0.767493877253 + 36.3998441297*I
 3.59478673353 + 14.1582489042*I
 2.68153380067 + 51.5876324277*I
 3.94463110922 + 20.3684188203*I
 3.03239537454 - 11.1868702610*I
 2.45019248787 - 1.30608992453*I

 period:8
 [7, 4, 4, -4, 1, 0, 0, 2]
 -0.139550493338 + 13.1980686114*I
 2.58012639847 + 45.5636666372*I
 3.82071134899 + 26.6469711272*I
 3.29285053446 + 26.5611256149*I
 3.28707484580 - 23.6852881281*I
 3.17439265913 + 4.85028944014*I
 1.75729393145 + 0.991281741545*I
 0.701910122418 + 0.513600707428*I

10
 period:10
 [13, 11, 0, 0, 0, -1, -2, 7, -8, -6]
 3.88980667763 - 39.1931011362*I
 3.67340164853 + 80.2095359456*I
 4.38569002022 + 70.6400691168*I
 4.25952110464 + 1.50879089393*I
 1.50825667185 + 0.340425849316*I
 0.435798949967 + 0.221988383926*I
 -0.715228532737 - 5.81205985617*I
 1.76745009101 - 14.2596107258*I
 2.66505425965 + 42.5348198592*I
 3.75228206472 - 48.7572601585*I

 period:10     range for entries of K is -20 to +20
 [13, 0, 0, 0, 9, -14, -4, 7, -2, -5]
 2.45890496064 - 32.6598313838*I
 3.48897209063 + 80.1857592496*I
 4.38529164743 + 1.52731263559*I
 1.53550026359 + 0.335142367490*I
 0.452125566132 + 0.214892564673*I
 -0.691955916993 + 56.9923559438*I
 4.04299085160 - 86.3816573645*I
 4.45986945473 - 26.6567678748*I
 3.29684662012 + 42.5772726672*I
 3.75430951723 - 11.0728521642*I

31
 period:31    range for entries of K is -50 to +50
 [18, 41, 5, 3, -43, -44, 35, 7, -2, 46, 32, -39, 22, 0, -49, 7, 44, 19, 17, -36, 0, 0, 0, -10, -6, 32, 12, 33, -43, 14, -43]
 4.46123659082 - 268.670811286*I
 5.59362472174 + 111.543142519*I
 4.71566725871 + 259.131288260*I
 5.55750039366 + 32.9685268863*I
 3.50956315667 + 20.2533523759*I
 3.02311284853 - 268.777751156*I
 5.59394808482 - 278.019702686*I
 5.62789436426 + 218.360807399*I
 5.38648079756 + 45.5273258094*I
 3.82526317868 - 11.1133399676*I
 2.46413008062 + 287.787230418*I
 5.66225807926 + 202.624164033*I
 5.31174315327 - 243.501368016*I
 5.49536042974 + 136.681090990*I
 4.91845800632 + 1.53061225907*I
 1.63921352217 - 307.574382164*I
 5.72873115272 + 42.4168302595*I
 3.75658336920 + 277.896704179*I
 5.62734083557 + 120.937800074*I
 4.79635775505 + 108.338449219*I
 4.68623916110 - 224.668117822*I
 5.41484177250 - 1.54994085447*I
 1.72851827511 - 0.278785039562*I
 0.560104777428 - 0.159908482226*I
 -0.540452863018 - 63.1099522429*I
 4.14491514575 - 39.2784716315*I
 3.67621370882 + 199.596270778*I
 5.29646626740 + 76.9506038467*I
 4.34552685950 + 208.847190418*I
 5.34181926132 - 268.626976088*I
 5.59352139149 + 86.4136809929*I

The values for the elements of the periods can be approximated to arbitrary precision, when Newton-iteration on the iterated branched logarithm is applied.


text:
Q: Connecting pygalmesh with PyQt5 for 3D rendering? I have some pygalmesh-generated meshes with code like:
import pygalmesh
s = pygalmesh.Ball([0, 0, 0], 1.0)
mesh = pygalmesh.generate_mesh(s, cell_size=0.2)

I would like to render them in a pyqt5 3D viewer window/widget, and navigate in the resulting 3D scene. How can I achieve this?
Is there some simple sample code out there?


text:
Q: webDavUrl missing from item response, why? webDavUrl property is not present in the list children request response.
using: GET /groups/{group-id}/drive/items/{item-id}/children
Any idea as to why that is?

A: The webDavUrl property must be explicity requested. Unfortunately it looks like the documentation does not mention this, so we'll need to get that rectified.
GET …?select=*,webDavUrl


text:
Q: SSRS - link to a survey works, but if I change it to another survey I get rsItemsNotFound I'm looking at a VS project which stores report records in a database table (here it holds things like the report url, name, etc.). We have a link that when you click it, it opens a report as a PDF. This one works fine.
I duplicated this report, made appropriate changes for a new report, and also copied the exact same format when adding a new row for it in the database (just with its own name and different url, etc.).
When I change the link in the code to grab the new report (nothing in the code has changed aside from which report ID it grabs from the database), it gives me 'folder/reportname' cannot be found (rsitemsnotfound).
Both reports are under the same folder location, and in the code it definitely grabs all the information from the database, and it uses the same data source credentials for the reports. No spelling errors either. Both reports work in the survey designer preview btw.
It seems like there is an issue with connecting to the data source for the new report, but again all the credentials and everything are the same so I am a bit stumped as to why this error is happening.
I am using Visual Studio 2019, I am not sure if it matters but the previous reports likely were made using earlier versions

A: Figured out the issue, very silly of me to not realize. In the DB I saved the report name in the path as something different than the name of the rdl


text:
Q: Find all matrix $A$ that satisfy $A^n = I$ (identity matrix). I've just began to learn mathematics at university, and I have met this problem which make me stuck at finding a way to solve, that is:

Find all matrix $A$ with size $m$ that product of ($n$) matrices
  $\underbrace
{A \times A \times \cdot \cdot \cdot \times A}
_{{n-\text{times}}} = I_m$.
  ($I_m$ is the identity matrix with size $m$)

Can you help me solve this?


text:
Q: How to maintain multiple concurrent connections using nodemailer? I'm creating a email verification system for my website and I'm using nodemailer to send the emails
However I'm concerned that the email won't be sent when multiple users ask for email verification
So to check for this, I created a simulation code which looks like this:
const express = require('express');
const app=express();

app.use(express.json());

const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({
  host: "smtp-mail.outlook.com",
  secureConnection: false,
  port: 587,
  pool:true,
  maxConnections:2,
  tls: {
     ciphers:'SSLv3',
     rejectUnauthorized: false
  },
  auth: {
      user: 'generic-email@outlook.com',
      pass: 'generic password'
  }
  });

app.get('/',async (req,res)=>{

for(var i=0;i<10;i++)
{
  transporter.sendMail({
    from: 'generic-email@outlook.com', // sender address
    to: `generic-client@gmail.com`, // list of receivers
    subject: "testing", // Subject line
    text: "testing?", // plain text body
    html: "<b>TESTING</b>", // html body
  },(err,info)=>{
    if(err)
     console.log('ERROR=>',err);
    else
     console.log('INFO=>',info);
  });
}
return res.send('Emails sent')
});

app.listen(3000,()=>{
    console.log('Listening at Port 3000...');
 });

as far as my knowledge goes the above code is stacking up 10 emails (due to the pool:true) and sending 2 concurrently (due to the maxConnections:2 ) at a time and theoretically it should work
as according to Microsoft outlook docs 3 concurrent connections are allowed

The service has various limits to prevent abuse and to ensure fair
use. An additional limit is being added. Under the new limit, up to
three concurrent connections are allowed to send email messages at the
same time. If an application tries to send more than three messages at
the same time by using multiple connections, each connection will
receive the following error message:

but on running the code I randomly get this error for some of the sent emails:
Error: Message failed: 432 4.3.2 Concurrent connections limit exceeded. Visit https://aka.ms/concurrent_sending for more information. [Hostname=SG2PR01MB2186.apcprd01.prod.exchangelabs.com]
    at SMTPConnection._formatError (C:\Users\name\node_modules\nodemailer\lib\smtp-connection\index.js:774:19)
    at SMTPConnection._actionSMTPStream (C:\Users\name\node_modules\nodemailer\lib\smtp-connection\index.js:1651:34)
    at SMTPConnection.<anonymous> (C:\Users\name\node_modules\nodemailer\lib\smtp-connection\index.js:1136:22)
    at SMTPConnection._processResponse (C:\Users\name\node_modules\nodemailer\lib\smtp-connection\index.js:932:20)
    at SMTPConnection._onData (C:\Users\name\node_modules\nodemailer\lib\smtp-connection\index.js:739:14)
    at TLSSocket.SMTPConnection._onSocketData (C:\Users\name\node_modules\nodemailer\lib\smtp-connection\index.js:189:44)
    at TLSSocket.emit (events.js:376:20)
    at addChunk (internal/streams/readable.js:309:12)
    at readableAddChunk (internal/streams/readable.js:284:9)
    at TLSSocket.Readable.push (internal/streams/readable.js:223:10) {
  code: 'EMESSAGE',
  response: '432 4.3.2 Concurrent connections limit exceeded. Visit https://aka.ms/concurrent_sending for more information. [Hostname=SG2PR01MB2186.apcprd01.prod.exchangelabs.com]',
  responseCode: 432,
  command: 'DATA'
}

so what am I doing wrong here? and how do I make sure I can handle multiple email requests efficiently without nodemailer breaking down?


text:
Q: Show which git tag you are on? I'm having trouble finding out which tag is currently checked out.
When I do:
git checkout tag1
git branch

I can't seem to find out which tag I'm on. It only logs:
* (no branch)
master

Is it possible to find out which tags are checked out? In the above example, this would be tag1.

A: Show all tags on current HEAD (or commit)
git tag --points-at HEAD

A: Edit
Jakub Narębski has more git-fu. The following much simpler command works perfectly:
git describe --tags

(Or without the --tags if you have checked out an annotated tag. My tag is lightweight, so I need the --tags.)
Original answer
git describe --exact-match --tags $(git log -n1 --pretty='%h')

Someone with more git-fu may have a more elegant solution...
This leverages the fact that git-log reports the log starting from what you've checked out. %h prints the abbreviated hash. Then git describe --exact-match --tags finds the tag (lightweight or annotated) that exactly matches that commit.
The $() syntax above assumes you're using bash or similar.

A: git describe is a porcelain command, which you should avoid:
http://git-blame.blogspot.com/2013/06/checking-current-branch-programatically.html
Instead, I used:
git name-rev --tags --name-only $(git rev-parse HEAD)

A: When you check out a tag, you have what's called a "detached head". Normally, Git's HEAD commit is a pointer to the branch that you currently have checked out. However, if you check out something other than a local branch (a tag or a remote branch, for example) you have a "detached head" -- you're not really on any branch. You should not make any commits while on a detached head.
It's okay to check out a tag if you don't want to make any edits. If you're just examining the contents of files, or you want to build your project from a tag, it's okay to git checkout my_tag and work with the files, as long as you don't make any commits. If you want to start modifying files, you should create a branch based on the tag:
$ git checkout -b my_tag_branch my_tag

will create a new branch called my_tag_branch starting from my_tag. It's safe to commit changes on this branch.

A: Here's a fun one for a certain set of use cases. If your repository has versions such as v1.0.0, v1.1.0, v1.1.1 etc, and also shorthand versions such as v1 that point to whatever is the latest v1.x.x, the following will give you a reference to the currently-checked-out commit in relation to the most recent fully versioned tag, with fallbacks if that doesn't work:
git describe --tags --exact-match --match "v*.*.*" \
  || git describe --match "v*.*.*" --tags \
  || git describe --tags \
  || git rev-parse HEAD

So let's say you have the following commits:
* 4444444 (main, origin/main, tag: v2.0.0, tag: v2.0, tag: v2)
* 3333333
* 2222222 (tag: v1.1.0, tag: v1.1, tag: v1)
* 1111111 (tag: v1.0.0, tag: v1.0)
* 0000000

Output of the above command for a few example HEADs:

*

*git checkout main -> v2.0.0

*git checkout 3333333 -> v1.1.0-1-g3333333

*git checkout 2222222 -> v1.1.0

*git checkout v1 -> v1.1.0

*git checkout 0000000 -> 0000000 (full ref)

A: git log --decorate
This will tell you what refs are pointing to the currently checked out commit.

A: This worked for me git describe --tags --abbrev=0
Edit 2020: As mentioned by some of the comments below, this might, or might not work for you, so be careful!


text:
Q: Disable all controls of a table column using jQuery I am looking to disable all the elements (controls) of specified table columns (td's) using jQuery.
My table looks like the following :

The table is generated dynamically, but this is how it is rendered as. Now each of my  has multiple controls like select, checkbox, buttons, but not fixed for every row and column. I am looking to disable all controls of a specified  by using it's Id.
I used the following jQuery, but it doesn't seemt to do the job :
$('#' + td_id).select('*').each(function(element){element.disabled=true});
I have also tried the following, still it doesn't seem to work :
$('#' + td_id).attr('disabled', 'false');
Am I doing something wrong? Please help.
Thanks!

A: try this
$('#' + td_id).find(':input').prop("disabled", true);

:input select all the input elements

A: if you need to disable all controls in a column (multilpe rows) I think the best way is to assign a class to each td in that column.
For examle if you want to disable controls in the second column, you may do something similar:

Than, using JQuery you can do this:
$(".col-2 :input').prop("disabled", true);

It should work...

A: I think this should work :

    <input type="text" />
    <input type="radio" />
    <input type="checkbox" />
    <select>
        <option>1233</option>
    </select>

    <input type="text" />
    <input type="radio" />
    <input type="checkbox" />
    <select>
        <option>second</option>
    </select>

Now to disable only first "td" you should use:
$('tr').children().eq(0).find(':input').prop("disabled", true);

If you are using JQuery1.6 or above use prop() else use attr().


text:
Q: python packet sniffer using raw socket trying to create packet sniffer using raw socket in python, and want to parse the full TCP header using struct.unpack method, but some fields like HLEN(4bits) and offset, URG,ACK,PST,RST,SYN,FIN in tcp header are on bits not Byte . so my question is how to parse these values from header !

A: You could use:

*

*ctypes which is part of the standard library, or

*Construct which is designed to support network protocols,

*bitarray which isn't,

*bitstring which isn't as well.

Here is an example:
from ctypes import c_int32, c_uint32, Structure, Union

class _bits(Structure):
    _fields_ = [
        ("odd", c_uint32, 1),
        ("half", c_uint32, 31),
    ]

class Int(Union):
    _fields_ = [
        ("bits", _bits),
        ("number", c_uint32),
    ]

a = Int(number=12345)
a.bits.odd, a.bits.half

the result:
>>> a = Int(number=12345)
>>> a.bits.odd, a.bits.half
(1L, 6172L)


text:
Q: Javascript does not work in Django templates with foundation 6 I have these scripts loaded to my template
<script src="{% static 'js/jQuery.min.js' %}"></script>

  <script src="{% static 'js/app.js' %}"></script>
  <script src="{% static 'js/plugins/foundation.core.js' %}"></script>
  <script src="{% static 'js/plugins/foundation.reveal.js' %}"></script>
  <script src="{% static 'js/plugins/foundation.util.touch.js' %}"></script>
  <script src="{% static 'js/plugins/foundation.util.triggers.js' %}"></script>
  <script src="{% static 'js/plugins/foundation.util.mediaQuery.js' %}"></script>
  <script src="{% static 'js/plugins/foundation.util.motion.js' %}"></script>
  <script src="{% static 'js/plugins/foundation.util.box.js' %}"></script>
  <script src="{% static 'js/plugins/foundation.util.keyboard.js' %}"></script>

Anyways, my Foundation modals do not work. When I click the button made for this purpose, it doesn not do anything.
The repo if you want to  test it: https://github.com/RodrigEEz/PersonalBlog


text:
Q: CefSharp GL ERROR :GL_INVALID_OPERATION : glCreateAndConsumeTextureCHROMIUM: invalid mailbox name, I plugged in selenium and CefSharp to work together however I am getting weird errors being logged...

[0217/000149:ERROR:gles2_cmd_decoder.cc(13988)] [.Compositor-000001C8F5CE0570]GL ERROR :GL_INVALID_OPERATION : glCreateAndConsumeTextureCHROMIUM: invalid mailbox name
  [0217/000149:ERROR:gles2_cmd_decoder.cc(7639)] [.Compositor-000001C8F5CE0570]RENDER WARNING: texture bound to texture unit 0 is not renderable. It maybe non-power-of-2 and have incompatible texture filtering.
  [0217/001125:WARNING:dns_config_service_win.cc(673)] Failed to read DnsConfig.
  [0217/003937:WARNING:raw_channel_win.cc(532)] WriteFile: The pipe is being closed. (0xE8)
  [0217/003937:WARNING:proxy_message_pipe_endpoint.cc(50)] Failed to write enqueue message to channel

Code looks following (Atm app is more for debugging than for it's original purpose):
using System;
using System.Linq;
using System.Windows.Forms;
using CefSharp.WinForms;
using OpenQA.Selenium.Chrome;
using System.Threading;
using System.IO;
using OpenQA.Selenium;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        ChromiumWebBrowser _browser;
        private void button1_Click(object sender, EventArgs e)
        {

            _browser = new ChromiumWebBrowser("https://www.google.com/gmail/about/")
            {
                Dock = DockStyle.Fill,
            };

            Thread.Sleep(1000);
            var options = new ChromeOptions { BinaryLocation = Path.Combine(System.IO.Directory.GetCurrentDirectory().Split(new[] { "bin" }, StringSplitOptions.None)[0], @"support\cef_binary_3.2556.1368.g535c4fb_windows64_client\Release\cefclient.exe") };
           // options.AddArgument("no-sandbox");
            var cefDriver = new ChromeDriver(options);
            cefDriver.Navigate().GoToUrl("https://www.google.com/gmail/about/"); //Somewhere here error is raised that then writes a log file and pops up alert that derails whole application
            Thread.Sleep(1000);
            if (isAlertPresent(cefDriver)) {
              //  cefDriver.SwitchTo().Alert().Accept(); //This fails to close opened error dialog
            }
        }

        public bool isAlertPresent(ChromeDriver driver)
        {
            try
            {
                driver.SwitchTo().Alert();
                return true;
            }
            catch (NoAlertPresentException Ex)
            {
                return false;
            }
        }
    }
}

A: I believe it had something to do with blocking on UI thread..
Code below works ok.
using OpenQA.Selenium.Chrome;
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private async void button1_Click(object sender, EventArgs e)
        {

            var username = textBox1.Text;
            var password = textBox2.Text;

            if (new[] { username, password }.Any(o => string.IsNullOrWhiteSpace(o)))
            {
                label3.Text = "One of'em boxes is empty";
                return;
            }

            await PassLogin(username, password);
        }

        async Task PassLogin(string username, string password)
        {
            await Task<ChromeDriver>.Factory.StartNew(() =>
            {
                var options = new ChromeOptions { BinaryLocation = Path.Combine(System.IO.Directory.GetCurrentDirectory().Split(new[] { "bin" }, StringSplitOptions.None)[0], @"support\cef_binary_3.2556.1368.g535c4fb_windows64_client\Release\cefclient.exe") };
                var cefDriver = new ChromeDriver(options);
                return cefDriver;
            }).ContinueWith(async cefDriverTask =>
            {
                var cefDriver = await cefDriverTask;
                cefDriver.Navigate().GoToUrl("https://www.google.com/gmail/about/");
                cefDriver.FindElementByCssSelector(".gmail-nav__nav-link.gmail-nav__nav-link__sign-in").Click();
                var user = cefDriver.FindElementById("Email");
                user.SendKeys(username);
                cefDriver.FindElementById("next").Click();
                Thread.Sleep(100);
                var pass = cefDriver.FindElementById("Passwd");
                user.SendKeys(password);
                cefDriver.FindElementById("signIn").Click();
            });
        }
    }
}


text:
Q: NSTextView replacement for huge files NSTextview was not designed for huge files.
Before I start writing a replacement myself (for simple ascii files) I want to ask if there are already alternatives available to handle these files.
NSTextview is great but if you load a large file > 100 to 200mb it is getting really slow when you scroll down to the end for example.
So, does anyone know of a replacement available?


text:
Q: Understanding this Event Example After reading online tutorials regarding events , I think I almost have an idea of whats going on. I developed the following extremely simple code to trigger an event in case a value is greater than 5.I know the code is pretty useless but I am using it to get my point across. (Instead of a main I just used a button event to trigger the code.)
//declare the delegate
public delegate void MyDelegate(string str);

public class SomeClass
{
    public event MyDelegate MyEventFromDelegate;
    private int i;
    public int I
    {
            get
            { return i; }
            set
            {
                if (value > 5)
                {
                    MyEventFromDelegate("Value Greater than 5");
                    i = 0;
                }
                else
                {
                    i = value;
                }
            }
    }

}

public partial class Form1 : Form
{
    public Form1()
    { InitializeComponent();  }

    public void Method_To_Call(String rx)
    {   MessageBox.Show("This method will be called if greater than 5");}

    private void button1_Click(object sender, EventArgs e)
    {
        SomeClass a = new SomeClass();
        a.MyEventFromDelegate +=new MyDelegate(Method_To_Call);
        a.I = 12;
    }
}

The only concern I have here is when we want to raise an event with the statement
MyEventFromDelegate("Value Greater than 5");

What point is passing a parameters to the event is at this point if later (at button click event) we are actually going to assign it a function to call every time an event is triggered.

A: In your very simple example - there is no point, because SomeClass instance "a" is very short-lived, and because you are not using rx parameter passed to Method_To_Call.
Your form method button1_Click is connected to the button's Click event through a delegate. Button does not know what code will execute when it is clicked. All it has to do is to signal that is has been clicked. That signal is implemented using a delegate.
Your could have defined your delegate as having an integer parameter where the checked value is passed. Then although the event method would be invoked only when value is greater than 5, inside the event method you could do things differently depending on the actual value.
//declare the delegate
public delegate void MyDelegate(int aValue);

public class SomeClass
{
    public event MyDelegate MyEventFromDelegate;
    private int i;
    public int I
    {
            get
            { return i; }
            set
            {
                if (value > 5)
                {
                    MyEventFromDelegate(value);
                    i = 0;
                }
                else
                {
                    i = value;
                }
            }
    }

}

public partial class Form1 : Form
{
    public Form1()
    {
      InitializeComponent();
    }

    public void Method_To_Call(int aValue)
    {
      MessageBox.Show("This method signals that value is greater than 5. Value=" + aValue.ToString());
    }

    private void button1_Click(object sender, EventArgs e)
    {
        SomeClass a = new SomeClass();
        a.MyEventFromDelegate +=new MyDelegate(Method_To_Call);
        a.I = 12;
    }
}


text:
Q: Paginate 20,000 API results without database I access a SOAP webservice which can return results, for example, of 20000 ID's in array form.
I need to then use the same webservice to get more information about each of those 20,000 ID's but making 20,000 API requests is obviously not an option.
The API is limited as you can see. No pagination and no way to get the required additional data in the initial pull.
I also have no database access to store and loop through.
Any other options to paginate this data outside of a massive timeout value that I might have overlooked?

A: No database? Surely you have something.. access the filesystem and serialize the results there.

A: How often does the data change? You might have to do the 20k API calls, but you don't want to do so on every request. Maybe you can setup a cronjob which caches the data on your server, for example every hour or every day, depending on how often the data changes.

A: Jquery paginator plugin can help DAN, http://tablesorter.com/docs/example-pager.html

A: I think you need this http://lotsofcode.com/php/php-array-pagination.htm


text:
Q: Return value for recursive function with two arguments Considering the following code for Integer Partition:
int p (int n, int m)
{
    if (n == m)
        return 1 + p(n, m - 1);
    if (m == 0 || n < 0)
        return 0;
    if (n == 0 || m == 1)
        return 1;

    return p(n, m - 1) + p(n - m, m);

}

If I take an example p(7,3), what happens after function becomes p(7,0) & p(4,3)?

A: If you have Python you can play around with this:
def p(n,m):
    if n == m:
        return 1 + p(n,m-1)
    elif m == 0 or n < 0:
        return 0
    elif n == 0 or m == 1:
        return 1
    else:
        return p(n,m-1) + p(n-m,m)

def tupleFromString(s):
    #converts a string like `(3,7)` to the correspoding int tuple
    s = s.strip()
    arguments = s[1:len(s)-1].split(',')
    return tuple(int(i) for i in arguments)

def toString(t):
    #converts an int-tuple to a string, without the spaces
    return str(t).replace(' ','')

def expandOnce(s):
    s = s.strip()
    if s.startswith('p'):
        n,m = tupleFromString(s[1:])
        if n == m:
            return '1 + p' + toString((n,m-1))
        elif m == 0 or n < 0:
            return '0'
        elif n == 0 or m == 1:
            return '1'
        else:
            return 'p' + toString((n,m-1)) + ' + p' + toString((n-m,m))
    else:
        return s

def expandLine(line):
    return ' + '.join(expandOnce(term) for term in line.split('+'))

def expand(s):
    firstLine = True
    k = len(s)
    prefix = s + ' = '
    while 'p' in s:
        if firstLine:
            firstLine = False
        else:
            prefix = ' '*k + ' = '
        s = expandLine(s)
        print(prefix + s)
    print(prefix + str(sum(int(i) for i in s.split('+'))))

p(m,n) is a direct implementation of the function, and expand displays the steps as strings:
>>> p(4,3)
4
>>> expand('p(4,3)')
p(4,3) = p(4,2) + p(1,3)
       = p(4,1) + p(2,2) + p(1,2) + p(-2,3)
       = 1 + 1 + p(2,1) + p(1,1) + p(-1,2) + 0
       = 1 + 1 + 1 + 1 + p(1,0) + 0 + 0
       = 1 + 1 + 1 + 1 + 0 + 0 + 0
       = 4

The logic of this is as follows. If you want to know what p(4,3) is, you consult the definition. p(4,3) has n = 4 and m = 3, so you need to use that last clause of the definition. This tells you that
p(4,3) = p(4,3-1) + p(4-3,3)
       = p(4,2) + p(1,3)

That doesn't help unless you know what p(4,2) and p(1,3) are so you go back to the definition and find that p(4,2) = p(4,1) + p(2,2) and p(1,3) = p(1,2) + p(-1,2). Combining this with the above, you now know that
p(4,3) = p(4,3-1) + p(4-3,3)
       = p(4,2) + p(1,3)
       = p(4,1) + p(2,2) + p(1,3) + p(1,2)

at each stage, if there is a term which looks like p(m,n) -- you go back to the definition and see what it means. You eventually hit basis cases such as p(4,1) = 1. Once all of the p are evaluated -- just add what is left (just a bunch of ones and zeros).
Similarly,
p(7,3) = p(7,2) + p(4,3)
       = p(7,1) + p(5,2) + p(4,2) + p(1,3)
       = 1 + p(5,1) + p(3,2) + p(4,1) + p(2,2) + p(1,2) + p(-2,3)
       = 1 + 1 + p(3,1) + p(1,2) + 1 + 1 + p(2,1) + p(1,1) + p(-1,2) + 0
       = 1 + 1 + 1 + p(1,1) + p(-1,2) + 1 + 1 + 1 + 1 + p(1,0) + 0 + 0
       = 1 + 1 + 1 + 1 + p(1,0) + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0
       = 1 + 1 + 1 + 1 + 0 + 0 + 1 + 1 + 1 + 1 + 0 + 0 + 0
       = 8


text:
Q: Google API: Url mismatch: flow.redirect_uri is ignored Environment details

*

*OS type and version: Ubuntu 18.10

*Python version: Python 3.8.6

*pip version: pip 9.0.2 from python 3.8

*google-api-python-client version: 1.12.3

Steps to reproduce

*

*Copy the code from People API example

*Use the code below to get credentials

*Deploy your app to Heroku

*Login into Google Console. Register you app. Setup redirect url so that it matches the url of your Heroku application. I added it with https://.... Beside this, I also added http://localhost. Both url were withouth trailing slashes and withouth port numbers

*Run the app. It will produce the error

Code example
def get_creds(SCOPES):
    creds = None
    cred_dir = os.path.join(BASE_DIR, 'credentials.json')
    pickle_dir = os.path.join(BASE_DIR, 'token.pickle')

    # The file token.pickle is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists(pickle_dir):
        with open(pickle_dir, 'rb') as token:
            creds = pickle.load(token)

    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            config = json.loads(os.environ['CRED'])
            flow = InstalledAppFlow.from_client_config(config, SCOPES)
            flow.redirect_uri = os.environ['REDIRECT_URL']
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open(pickle_dir, 'wb') as token:
            pickle.dump(creds, token)
    return creds

Use it like this:
    creds = get_creds(['https://www.googleapis.com/auth/contacts'])

    service = build('people', 'v1', credentials=creds)

REDIRECT_URL is set to Heroku application url, starting with https://, withouth trailing slash. I also tested it in Python console:
>>> import os
>>> os.environ['REDIRECT_URL']

Stack trace
Browser output (there is no console stack trace):
400: redirect_uri_mismatch
The redirect URI in the request, http://localhost:33779/, does not match the ones authorized for the OAuth client. To update the authorized redirect URIs, visit: https://console.developers.google.com/apis/credentials/oauthclient/${your_client_id}?project=${your_project_number}

I think that the line:

flow.redirect_uri = os.environ['REDIRECT_URL']

does not actually change
What have I tried:

*

*this, I double checked for correct urls. I also added urls with https and with trailing slashes

A: I find similar problem with an accepted answer form here
In following line:
creds = flow.run_local_server(port=0)
try port 8080 instead of 0 and check the outcome.


text:
Q: How do I match the correct strings while keeping capture groups the same? I began with the regex: ^(S?g?[mfds]|S?G*g[msdf])$ and I converted it to: ^(S?)(G*)(g?)(m|s|d|f|)$
to separate capture groups into (S, G, g, m/f/d/s)
this is the link to what I am supposed to match and what I should not match: https://regex101.com/r/q8b7zJ/1
I tried solving this by having (g?|G*g) in the second capture group to prevent Gm from matching, however, my capture groups end up becoming (S, Gg, '', msdf)
How do I match the correct strings while keeping my capture groups the same (S, G, g, m/s/d/f)

A: To prevent Gm from matching, you might use a negative lookahead (?!G[mfds]) to rule out the matches for G followed by any of m f d d
import re

strings = [
    "m",
    "gf",
    "Ggm",
    "GGgf",
    "Ss",
    "SGgs",
    "mf",
    "Gm",
    "SSm",
    "GSm"
]

pattern = r"^(S?)(?!G[mfds])(G*)(g?)([mfds])$"
for s in strings:
    m = re.match(pattern, s)
    if m:
        print(m.groups())

Output
('', '', '', 'm')
('', '', 'g', 'f')
('', 'G', 'g', 'm')
('', 'GG', 'g', 'f')
('S', '', '', 's')
('S', 'G', 'g', 's')

See a regex demo and a Python demo.


text: Q: including user input in launch.json (VSCode) Is it possible, in VSCode launch.json, to specify user input that is requested by the program after it has started? E.g. if the program asks for "Name?" I'd like to include "Lisa" in launch.json so I don't have to type it every time I want to debug.


text:
Q: NextJS - api submit form data So not sure why but I am trying to submit my form data to /api/new
But when I do I get the following error
./pages/api/new.js
Error:
  x Expected '(', got 'new'
   ,----
 2 | export default function new(req, res) {
   :                         ^^^
   `----

Caused by:
    0: failed to process input file
    1: Syntax Error

Not sure why but seems to only be an issue when I have inputs that are file type.

A: new is a reserved keyword and you cannot use reserved keywords as function, variable, label, or class names. Try naming the handler newRouteHandler or something else.


text:
Q: Uniform continuity of $f(x) = \frac {1} {x^3}$ on $(0,1]$ Not sure about the Uniform continuity of $f(x) = \frac {1} {x^3}$   on $(0,1]$. Unsure where to begin. My textbook showed that $\frac {1}{x^2}$ was not uniformly continuous on $(0,1)$.
Edit: Looking for hints to show that $f$ is not in fact uniformly continuous on this interval using familiar theorems.

A: Not uniformly continuous by contradiction. Suppose that I could extend my function to $f'(x)$ such that $f'(0)=r$ for some $r \in \Bbb R$, then for any sequence $x_n$ converging to 0, we have lim $f(x_n) = \infty$, and cannot therefore equal r, thus $f$ cannot be extended to some $f'$ such that $f'$ is continuous on [0,1] and so $f$ is not uniformly continuous on (0,1). Now how does this relate to showing that $f$ is not uniformly continuous on (0,1]. If a function is not uniformly continuous on a subset $A \subset B$ then f is not uniformly continuous on B?


text:
Q: Installing OpenCV on OSX 10.6 using MacPorts I tried installing OpenCV following the instructions for a MacPorts install on http://opencv.willowgarage.com/wiki/Mac_OS_X_OpenCV_Port, typing
sudo port install opencv

in the terminal.
The install/compilation seemed to go fine, and the files are in /opt/local subdirectories as they should be. As a first test, I then tried including highgui.h in a C++ source file:
#include <highgui.h>

but when compiling with g++ or gcc, I get error: highgui.h: No such file or directory. I'm new to developing on a Mac, so maybe I'm missing something?
I thought I might have to set some path variable and after reading some posts I found when googling, I tried setting DYLD_LIBRARY_PATH=/opt/local/lib, but that was wild guess and it didn't seem to help. What should I do to make the compilers find the library?
Thanks!

A: I couldn't get it to work for quite some time either until I found that there is a pkg-config set.
All you have to do to compile without problems is this:
g++ `pkg-config --libs --cflags opencv` -o helloWorld  helloWorld.cpp

or gcc if you are working with C instead of C++.
I hope that helps!

A: MacPorts installs C/C++ headers in /opt/local/include directory which is not the system default. It means that you have to explicitly tell GCC where to look for headers you are using. You can do that by specifying "-isystem" or "-I" command line options:

-isystem dir
             Search dir for header files, after all directories specified
  by -I but before the standard system
  directories.  Mark it as a system
             directory, so that it gets the same special treatment as is
  applied to the standard system
  directories.  If dir begins with "=",
  then
             the "=" will be replaced by the sysroot prefix; see --sysroot and
  -isysroot.

-Idir
             Add the directory dir to the head of the list of directories to
  be searched for header files.  This
  can be used to override a system
             header file, substituting your own version, since these
  directories are searched before the
  system header file directories.
  However,
             you should not use this option to add directories that contain
  vendor-supplied system header files
  (use -isystem for that).  If you
             use more than one -I option, the directories are scanned in
  left-to-right order; the standard
  system directories come after.
If a standard system include directory, or a directory
  specified with -isystem, is also
  specified with -I, the -I option will
  be
             ignored.  The directory will still be searched but as a system
  directory at its normal position in
  the system include chain.  This is
             to ensure that GCC's procedure to fix buggy system headers
  and the ordering for the include_next
  directive are not inadvertently
             changed.  If you really need to change the search order for
  system directories, use the -nostdinc
  and/or -isystem options.

I recommend using -isystem because it disables some warnings you cannot fix without modifying the code. For example, using std::auto_ptr if you compile your code with -std=c++0x etcetera.
The same goes for libraries. You have to tell GCC where to find them using -L option.

A: Referenced from the OpenCV wiki page:
http://opencv.willowgarage.com/wiki/CompileOpenCVUsingMacOSX
Set the environment variables like this:
export PKG_CONFIG_PATH=/opt/local/lib/pkgconfig
export LD_LIBRARY_PATH=/opt/local/lib
and compile opencv code like this:
g++ -bind_at_load `pkg-config --cflags opencv` morphology.c -o morphology `pkg-config --libs opencv`
and then run the code like this:
./morphology

A: Macports install was working smoothly for me, it is worth to install tbb before installing opencv, massive speedup (and sadly it won't work the other way around).
#include <highgui.h> is not the c++ header.
Use #include<opencv2/highgui/highgui.hpp> and its friends in /opt/local/include and avoid anything in /opt/local/include/opencv.


text:
Q: Should or should not AsyncTask be used for long-running operations? I'm confused by what I read about the AsyncTask. On one hand, the android document states that "AsyncTasks should ideally be used for short operations (a few seconds at the most.)". The document does not give an explanation as to why this is so.
On the other hand, I've read at least one article that explicitly or implicitly suggests that AsyncTasks be used for long-running operations, such as this one.
Could any android guru give a more convincing reason why or why not an AsyncTask should be used for long-running operations? Or point me to the documents that explain this. I haven't been able to find the answer.

Ah, someone else asked a similar question. Let me see if the answers make sense to me.

A: the interface exposed by AsyncTask defines a setup, a background operation, and an "on done" callback that can update the UI. this implies that it's intended use is for operations that have a clearly defined finish that results in feedback to the user.
if you need an ongoing background thread, use an Executor to execute an instance of Runnable that hosts your ongoing operations. use this with care however, since when your app leaves the foreground, the thread will continue to run. carefully craft your Runnable such that it can be aborted (the run() method can be caused to return cleanly).
it's worth it to note that AsyncTask just forces you into a well-defined pattern for performing an asynchronous operation then updating the UI. IMHO it's overly complicated and makes a lot of assumptions, like a single-or limited size thread pool. for example, if one part of your app was blocking in AsyncTasks, would you assume that it would prevent an AsyncTask from running in another part of your app? it will.

A: Definitely not. Async tasks are queued up, and one cannot start until the previous one completes.
Use regular threads for long-running tasks.