Combining recursive iterator results: children with parents

Question: I'm trying to iterate over a directory which contains loads of PHP files, and detect what classes are defined in each file.
Consider the following:
$php_files_and_content = new PhpFileAndContentIterator($dir);
foreach($php_files_and_content as $filepath => $sourceCode) {
    // echo $filepath, $sourceCode
}

The above $php_files_and_content variable represents an iterator where the key is the filepath, and the content is the source code of the file (as if that wasn't obvious from the example).
This is then supplied into another iterator which will match all the defined classes in the source code, ala:
class DefinedClassDetector extends FilterIterator implements RecursiveIterator {
    public function accept() {
        return $this->hasChildren();
    }

    public function hasChildren() {
        $classes = getDefinedClasses($this->current());
        return !empty($classes);
    }

    public function getChildren() {
        return new RecursiveArrayIterator(getDefinedClasses($this->current()));
    }
}

$defined_classes = new RecursiveIteratorIterator(new DefinedClassDetector($php_files_and_content));

foreach($defined_classes as $index => $class) {
    // print "$index => $class"; outputs:
    // 0 => Class A
    // 1 => Class B
    // 0 => Class C
}

The reason the $index isn't sequential numerically is because 'Class C' was defined in the second source code file, and thus the array returned starts from index 0 again. This is preserved in the RecursiveIteratorIterator because each set of results represents a separate Iterator (and thus key/value pairs).
Anyway, what I am trying to do now is find the best way to combine these, such that when I iterate over the new iterator, I can get the key is the class name (from the $defined_classes iterator) and the value is the original file path, ala:
foreach($classes_and_paths as $filepath => $class) {
    // print "$class => $filepath"; outputs
    // Class A => file1.php
    // Class B => file1.php
    // Class C => file2.php
}

And that's where I'm stuck thus far.
At the moment, the only solution that is coming to mind is to create a new RecursiveIterator, that overrides the current() method to return the outer iterator key() (which would be the original filepath), and key() method to return the current iterator() value. But I'm not favouring this solution because:

It sounds complex (which means the code will look hideous and it won't be intuitive
The business rules are hard-coded inside the class, whereas I would like to define some generic Iterators and be able to combine them in such a way to produce the required result.

Any ideas or suggestions gratefully recieved.
I also realise there are far faster, more efficient ways of doing this, but this is also an exercise in using Iterators for myselfm and also an exercise in promoting code reuse, so any new Iterators that have to be written should be as minimal as possible and try to leverage existing functionality.
Thanks
Comment: +1 for upping the bar and using OOP in PHP
Answer: OK, I think I finally got my head around this. Here's roughly what I did in pseudo-code:
Step 1
We need to list the directory contents, thus we can perform the following:
// Reads through the $dir directory
// traversing children, and returns all contents
$dirIterator = new RecursiveDirectoryIterator($dir);

// Flattens the recursive iterator into a single
// dimension, so it doesn't need recursive loops
$dirContents = new RecursiveIteratorIterator($dirIterator);

Step 2
We need to consider only the PHP files
class PhpFileIteratorFilter {
    public function accept() {
        $current = $this->current();
        return    $current instanceof SplFileInfo
               && $current->isFile()
               && end(explode('.', $current->getBasename())) == 'php';
    }
}

// Extends FilterIterator, and accepts only .php files
$php_files = new PhpFileIteratorFilter($dirContents);

The PhpFileIteratorFilter isn't a great use of re-usable code. A better method would have been to be able to supply a file extension as part of the construction and get the filter to match on that. Although that said, I am trying to move away from construction arguments where they are not required and rely more on composition, because that makes better use of the Strategy pattern. The PhpFileIteratorFilter could simply have used the generic FileExtensionIteratorFilter and set itself up interally.
Step 3
We must now read in the file contents
class SplFileInfoReader extends FilterIterator {

    public function accept() {
        // make sure we use parent, this one returns the contents
        $current = parent::current();
        return    $current instanceof SplFileInfo
               && $current->isFile()
               && $current->isReadable();
    }

    public function key() {
        return parent::current()->getRealpath();
    }

    public function current() {
        return file_get_contents($this->key());
    }
}

// Reads the file contents of the .php files
// the key is the file path, the value is the file contents
$files_and_content = new SplFileInfoReader($php_files);

Step 4
Now we want to apply our callback to each item (the file contents) and somehow retain the results. Again, trying to make use of the strategy pattern, I've done away unneccessary contructor arguments, e.g. $preserveKeys or similar
/**
 * Applies $callback to each element, and only accepts values that have children
 */
class ArrayCallbackFilterIterator extends FilterIterator implements RecursiveIterator {

    public function __construct(Iterator $it, $callback) {
        if (!is_callable($callback)) {
            throw new InvalidArgumentException('$callback is not callable');
        }

        $this->callback = $callback;
        parent::__construct($it);
    }

    public function accept() {
        return $this->hasChildren();
    }

    public function hasChildren() {
        $this->results = call_user_func($this->callback, $this->current());
        return is_array($this->results) && !empty($this->results);
    }

    public function getChildren() {
        return new RecursiveArrayIterator($this->results);
    }
}

/**
 * Overrides ArrayCallbackFilterIterator to allow a fixed $key to be returned
 */
class FixedKeyArrayCallbackFilterIterator extends ArrayCallbackFilterIterator {
    public function getChildren() {
        return new RecursiveFixedKeyArrayIterator($this->key(), $this->results);
    }
}

/**
 * Extends RecursiveArrayIterator to allow a fixed $key to be set
 */
class RecursiveFixedKeyArrayIterator extends RecursiveArrayIterator {

    public function __construct($key, $array) {
        $this->key = $key;
        parent::__construct($array);
    }

    public function key() {
        return $this->key;
    }
}

So, here I have my basic iterator which will return the results of the $callback I supplied through, but I've also extended it to create a version that will preserve the keys too, rather than using a constructor argument for it.
And thus we have this:
// Returns a RecursiveIterator
// key: file path
// value: class name
$class_filter = new FixedKeyArrayCallbackFilterIterator($files_and_content, 'getDefinedClasses');

Step 5
Now we need to format it into a suitable manner. I desire the file paths to be the value, and the keys to be the class name (i.e. to provide a direct mapping for a class to the file in which it can be found for the auto loader)
// Reduce the multi-dimensional iterator into a single dimension
$files_and_classes = new RecursiveIteratorIterator($class_filter);

// Flip it around, so the class names are keys
$classes_and_files = new FlipIterator($files_and_classes);

And voila, I can now iterate over $classes_and_files and get a list of all defined classes under $dir, along with the file they're defined in. And pretty much all of the code used to do this is re-usable in other contexts as well. I haven't hard-coded anything in the defined Iterator to achieve this task, nor have I done any extra processing outside the iterators
Answer: I think what you want to do, is more or less to reverse the keys and values returned from PhpFileAndContent. Said class returns a list of filepath => source, and you want to first reverse the mapping so it is source => filepath and then expand source for each class defined in source, so it will be class1 => filepath, class2 => filepath.
It should be easy as in your getChildren() you can simply access $this->key() to get the current file path for the source you are running getDefinedClasses() on. You can write getDefinedClasses as getDefinedClasses($path, $source) and instead of returning an indexed array of all the classes, it will return a dictionary where each value from the current indexed array is a key in the dictionary and the value is the filepath where that class was defined.
Then it will come out just as you want.
The other option is to drop your use of RecursiveArrayIterator and instead write your own iterator that is initialized (in getChildren) as
return new FilePathMapperIterator($this->key,getDefinedClasses($this->current()));

and then FilePathMapperIterator will convert the class array from getDefinedClasses to the class => filepath mapping I described by simply iterating over the array and returning the current class in key() and always returning the specified filepath in current().
I think the latter is more cool, but definitely more code so its unlikely that I would have gone that way if I can adapt getDefinedClasses() for my needs.


Host http:// and https:// for same domain on separate IIS servers

Question: Is it possible to host http://example.com and https://example.com on two separate IIS servers?
Answer: Any decent router could do this as well, route 433 to serv1 and 80 to serv2.
Answer: Well, one IP address has to be authoritative for the DNS name. However, that device could be an Apache machine with ProxyPass and ProxyPassReverse that could send the requests to the right server. Also, I think IIS 7.0 has pretty good redirection now too, so you could host both on (for example) the server that serves HTTP, but just make it proxy or redirect to another server for HTTPS.
Comment: It would be better to redirect it at the network level with some firewall rules.
Comment: That works too.


Restricted nodes don't show up in search results

Question: On this Belgium version of the side users has to have the right permission to view specific nodes. I did this with Content Access module.
But now when you as anonymous user search any content the restricted nodes don't show up?
How do i manage the teasers show up always? But when you want to see full content it's restricted?
Answer: The default Drupal search respects the Drupal permission system, so if the user performing a search doesn't have permission to see a node, it won't appear in search results at all. To get around this, you'll need something that circumvents the permission system, either by altering the search function, or replacing it entirely.
You could take a look at the Custom Search module. It modifies Drupal's search, and gives you control over the default search options. However, I can't recall if it includes an option to show content you wouldn't otherwise have permission to see.
The other way you could do it is to create a custom view, add a filter for the field you want to search on, then under advanced, select "query options", and tick the "disable query rewriting" option. This will prevent the permissions from being applied to the view, so will allow users to see nodes they don't have access to. However, I'm not aware of any way of making a view search multiple fields from a single exposed filter, making it less than ideal for an alternative search box.


IONIC apk Generate Issue

Question: I have getting this error when I run ionic cordova build --release android
but yesterday it was running perfectly im not change anything about configuration only build distribution I think it is version issue but I unable to find how to resolve it please help
here is console log
FAILURE: Build failed with an exception.

* What went wrong:
Could not resolve all files for configuration ':app:releaseCompileClasspath'.
> Could not find any version that matches com.google.firebase:firebase-measurement-connector:[10.2.1,12.1.0[.
  Versions that do not match:
      17.0.0

      16.0.0
      15.0.0

  Required by:
      project :app > com.google.firebase:firebase-messaging:17.0.0

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or
--debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED
 in 41s
11 actionable tasks: 11 executed
(node:15826) UnhandledPromiseRejectionWarning: Error: /home/chamikara/Projects/freelance/ionic/beachlines/notifications/platforms/android/gradlew: Command failed with exit code 1 Error output:
FAILURE: Build failed with an exception.

* What went wrong:
Could not resolve all files for configuration ':app:releaseCompileClasspath'.
> Could not find any version that matches com.google.firebase:firebase-measurement-connector:[10.2.1,12.1.0[.
  Versions that do not match:
      17.0.0
      16.0.0
      15.0.0
  Required by:
      project :app > com.google.firebase:firebase-messaging:17.0.0

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

* Get more help at https://help.gradle.org

BUILD FAILED in 41s
    at ChildProcess.whenDone (/home/chamikara/Projects/freelance/ionic/beachlines/notifications/platforms/android/cordova/node_modules/cordova-common/src/superspawn.js:169:23)
    at emitTwo (events.js:126:13)
    at ChildProcess.emit (events.js:214:7)
    at maybeClose (internal/child_process.js:925:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:209:5)
(node:15826) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:15826) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

Comment: Possible duplicate of [ionic build getting error after installing OneSingle plugin](https://stackoverflow.com/questions/51743969/ionic-build-getting-error-after-installing-onesingle-plugin)
Answer: Related to this answer : https://stackoverflow.com/a/51779975/279326 I fixed by going back to email@example.com npm i -g email@example.com

IONIC apk Generate Issue


How to prove math discrete expression in right way?

Question: I have such expression
$$ \{A\} \subseteq P(B) \to P(A) \subseteq P(B) $$
As far as I understand I have to convert expression left part to make it fit right one.
But I don't see any associations with these two parts...
Comment: You know that $A$ is in $P(B)$ from the left side of the conditional.  What other sets *must* be in $P(B)$?  What other sets are in $P(A)$?  Do you see now that the right side of the conditional must also be true?
Answer: Since $\{A\} \subseteq P(B)$ then $A \in P(B)$ so $A \subseteq B$
Thus every subset of $A$ is a subset of $B$ which tells us that $P(A) \subseteq P(B)$
Answer: $\{A\} \subseteq \mathcal P(B)$ implies $A \in \mathcal P(B)$. Therefore $A$ is a subset of $B$. Therefore any subset of $A$ is a subset of $B$ which is the conclusion where are looking for.


Get part-Of class from OWL Ontology

Question: I have an ontology made with protègè, I defined an ObjectProperty named part-Of.

I'm parsing an OWLClass trying to find out whether or not the subclasses are part-Of the parsed class. In this case, I am parsing At_Home when the subclasses, ANA and PHE, have the following subclass of signature as in this picture

I've already tried with:
OWLDataFactory df = manager.getOWLDataFactory();
    OWLObjectProperty partOf = df.getOWLObjectProperty("part-Of");
    OWLClassExpression c = df.getOWLObjectSomeValuesFrom(partOf, target);
    NodeSet<OWLClass> subClasses = hermit.getSubClasses(c, true);
    if(subClasses.isEmpty()) {
        //System.out.println("\tQuesta classe non ha parti");
        res[0] = null;
    }
    else {
        for(Node<OWLClass> parte : subClasses) {
            risultato.add(parte.getRepresentativeElement().getIRI().getFragment());
        }
        res[0] = risultato;
    }

where target is the At_Home OWLClass, but the method continues to return an empty NodeSet, so it means that At_Home has no parts even if ANA and PHE are its parts.
The wanted result should be a NodeSet with the OWLClass "ANA" and "PHE"
Answer:
df.getOWLObjectProperty("part-Of");

This is the problem. You need to use the full IRI of your property, not just the fragment; this won't match the property as stated in your ontology.
Comment: so adding the full IRI "semanticweb.org/diego/ontologies/2019/2/…" should do the trick, but how can I get it from ontology that I didn't create myself? I mean, in the IRI there is "diego" and parts like "2019/2" which are variable, how can I find the right ObjectProperty with only the fragment name? is there a way? @Ignazio
Comment: I don't really understand the question. In any ontology, whether created by you or imported from some other site, the properties are identified by absolute IRIs, not relative ones. In which scenario do you only have the fragment name?

Get part-Of class from OWL Ontology


Images in iOS push notification

Question: I am trying to send images in push notifications
I have made the notifications registrations in app delegate and apns device token is generating properly.
ALso I have coded in service ext as follows:
import UserNotifications

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

// Get the custom data from the notification payload
if let notificationData = request.content.userInfo["data"] as? [String: String] {
    // Grab the attachment
    if let urlString = notificationData["attachment-url"], let fileUrl = URL(string: urlString) {
        // Download the attachment
        URLSession.shared.downloadTask(with: fileUrl) { (location, response, error) in
            if let location = location {
                // Move temporary file to remove .tmp extension
                let tmpDirectory = NSTemporaryDirectory()
                let tmpFile = "file://".appending(tmpDirectory).appending(fileUrl.lastPathComponent)
                let tmpUrl = URL(string: tmpFile)!
                try! FileManager.default.moveItem(at: location, to: tmpUrl)

                // Add the attachment to the notification content
                if let attachment = try? UNNotificationAttachment(identifier: "", url: tmpUrl) {
                    self.bestAttemptContent?.attachments = [attachment]
                }
            }
            // Serve the notification content
            self.contentHandler!(self.bestAttemptContent!)
            }.resume()
    }
}
}
}

.
And the payload in json is as follows
{
    "aps":
            {"sound":"default","alert":
                                        {"title":"iOS","body":"Hello Dude...."},
            "mutable-content": 1},
    "CustomData":
                    {"mType":"alert","m":"Hello Dude...."},
    "Attachement-url":"https://pusher.com/static_logos/320x320.png"
}

I am receiving the title and message but image is not coming.
Please guide how to get image in push notifications
Comment: Please match your payload key with code. Check `Attachement-url` in code.
Comment: Checkout this answer https://stackoverflow.com/a/50523908/5084797 .
Comment: Can u please guide me with swift code and all the process need to be done for having images in push notifications
Answer: For Swift, If you want you can try with this framework
Also Add "content-available":1 in your aps
OR you can try downloading like this,
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

            self.contentHandler = contentHandler
            bestAttemptContent = (request.content.mutableCopy() as?UNMutableNotificationContent)

            bestAttemptContent?.title = request.content.title
            bestAttemptContent?.body = request.content.body

            guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else {
                return failEarly()
            }

            guard let payload = content.userInfo["CustomData"] as? [String: Any] else {
                return failEarly()
            }

            guard let attachmentURL = payload["Attachement-url"] as? String else {
                return failEarly()
            }

            let identifierName = getIdentifierName(fileURL: attachmentURL)
            let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString

            guard let imageData = NSData(contentsOf:NSURL(string: attachmentURL)! as URL) else { return failEarly() }

            guard let attachment = UNNotificationAttachment.create(imageFileIdentifier: identifierName, data: imageData, options: nil, tmpSubFolderName: tmpSubFolderName) else { return failEarly() }

            content.attachments = [attachment]
            contentHandler(content.copy() as! UNNotificationContent)
        }

    }

    func getIdentifierName(fileURL : String) -> String {
        var identifierName : String = "image.jpg"

        if !fileURL.isEmpty() {
            identifierName = "file.\((fileURL as NSString).lastPathComponent)"
        }

        return identifierName
    }

    func failEarly() {

        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }

    extension UNNotificationAttachment {
        static func create(imageFileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?, tmpSubFolderName : String) -> UNNotificationAttachment? {

            let fileManager = FileManager.default
            let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
            let fileURLPath      = NSURL(fileURLWithPath: NSTemporaryDirectory())
            let tmpSubFolderURL  = fileURLPath.appendingPathComponent(tmpSubFolderName, isDirectory: true)

            do {
                try fileManager.createDirectory(at: tmpSubFolderURL!, withIntermediateDirectories: true, attributes: nil)
                let fileURL = tmpSubFolderURL?.appendingPathComponent(imageFileIdentifier)
                try data.write(to: fileURL!, options: [])
                let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, url: fileURL!, options: options)
                return imageAttachment
            } catch let error {
                print("error \(error)")
            }

            return nil
        }
    }

Comment: Can u please help me with a live example in swift for rich notifications
Comment: You mean like a Demo project?? Try steps from here https://github.com/manishsharma93/BasicUtilityKit/ and see how it goes.
Answer: This line:
if let urlString = notificationData["attachment-url"], let fileUrl = URL(string: urlString) {
Is looking for an attachment-url value as a child of a data object in the userInfo dictionary.
It is looking for this:
{
    "aps" : {
        ...
    },
    "data" : {
        "attachment-url" : "some url"
    }
}

But the payload in your question is this:
{
    "aps":{
        "sound":"default",
        "alert": {
                    "title":"iOS",
                    "body":"Hello Dude...."
                },
        "mutable-content": 1
    },
    "CustomData": {
        "mType":"alert",
        "m":"Hello Dude...."
    },
    "Attachement-url":"https://pusher.com/static_logos/320x320.png"
}

The "data" section does not exist, and the attachment-url key does not exist.
Change your Swift code to match what is in the payload and you should be able to get the image URL and download it.
You will have a big problem if you receive a notification that does not have the attachment URL key or the attachment URL is not a properly formed URL. In those cases your if let will not be entered and the contentHandler will not be called! This will not just cause the service extension to lock up, but it will prevent any notification that does not have the attachment URL from being delivered! Add an else that calls the contentHandler to fix this.
Once you have it downloaded though there is another problem. iOS will need to know what kind of data you are putting in the attachment. The attachment options dictionary allows you to include type information about the attachment. Get the MIME Type of the downloaded file and create a Uniform Type Identifier from that. The Uniform Type Identifier string can then be used in the options dictionary.
I cover all of this in depth in the iOS Notifications book. The sample chapter available now deals with adding images to notifications.

Images in iOS push notification


Can't connect to SQL Server using an Alias

Question: I have a SQL Server 2000 install on a server that I am having weird connection issues with.
Using SSMS I can't connect to it using an Alias I have setup on Configuration Manager.  The Alias is set to use TCPIP which is the first protocol in the order below shared memory.  If I use the exact same server name I put into the Alias then I can connect just fine.
I see the exact same behavior in my ASP.NET application, using the alias I get a connection failure, using the name it connects just fine.  The ASP.NET connection string is not specifying a protocol.
Answer: Using the server name will use the default connection protocol for the client.
This may be named pipes or tcp/ip (MDAC version, upgrade vs install etc).

The Alias is set to use TCPIP which is
  the first protocol in the order below
  shared memory

I assume that if the client alias is set to use tcp, then the server is only configured to listen on named pipes so it only works with server name. The client will eventually find named pipes in it's list of protocols to use.
To test, replace servername with np:servername and tcp:servername to change the protocol without using the alias.
Or check what the server is listening on and fix that...
The other option is a non-standard TCP port (server, not 1433) or firewall preventing access to port 1433/1434.
SQL 2000 Books
Answer: Does the alias specify a protocol?  Is that protocol accepted by the server?  Is that the protocol being used when you are connecting by name?  (i.e. what is the order of client protocols)


Equivalent of \\tsclient for VMWare vSphere Console

Question: What is the \\tsclient equivalent to access the host hard drive for VMWare vSphere consoles?
That is, a network drive shortcut from the vm to the connecting machine.
The option to connect a USB drive is useful, but not as useful as the rdp tsclient shortcut is.
Comment: What data are you trying to access - do you mean from the client you're connecting from, or from the host?  And you're looking to access this data from a VM, correct?  Please clarify what data you need, where it is, and where you need to get it.  There's no "equivalent", but there are certainly options.
Comment: Trying to connect from the VM to the connecting machine.
Comment: Hopefully this is not a production vmware vsphere deploy of any value.  Because if it is it will be screwed up shortlyl.
Comment: Nah, development environments. So screwing it is more of an inevitability.
Comment: The only reason a direct network share is not an option is because the domain trust relationship is bollo...
Comment: so the vcenter is a member of domain A but the guests are members of domain B but you want to access the local drives on the vcenter server, is that correct?
Comment: vccenter is hosted on domain 'DEV' and guests are members of 'PROD', wanted to access local drives of guest from domain 'DEV'.
Comment: Mostly I was wanting to know if there was a generic shortcut for any given guest rather than having to know your own IP address. It's not particularly onerous, but it did surprise me that no shortcut was coded into the VMWare client.
Answer: As far as I know, there isn't.  You need to create a regular file share.


Como achar uma string baseando-se em um grupo de expressões regulares

Question: Estou a tentar criar um Template Engine em PHP por questões de estudo.
Suponhamos que eu tenha o seguinte array:
$regexList = [
  'varPattern' => '/{{\s*\$(.*?)\s*}}/',
  'loopPattern' => '/@for\((.*?)\)\s*{{((?:[^{}]|(?R))*)}}/',
  'statementPattern' => '/@if\((.*?)\)\s*{{((?:[^{}]|(?R))*)}}/'
]

e as seguites funções:
getVar($nomeDaVariavel);
loop($nomeDoArray);
getStatementResult($expressãoBooleana);

e a seguinte string:
$string = '

{{ $nomeCompleto }}

@for($nomes as $nome)
{{
  @if($nome == 'Eleandro)
  {{

{{ $nome }}

  }}
}} ';

A ideia é ler a string de cima para baixo e baseando-se na lista de expressões regulares achar o resultado e entregá-lo a função correcta.
Por exemplo: A primeira coisa a ser achada tem de ser a {{ $string }}, então passamos o nome da variável a função getVar($nomeDaVariávelEncontrada).
A seguir será o loop, então chamamos o loop($comoNomeDoArrayEncontrado); e dentro do loop será encontrado o if, então pegamos o conteúdo do if e entregamo-lo a função getStatementResult($expressãoBooleanaEncontrada) com o valor encontrado.
Como eu posso fazer isso na ordem certa (de cima para baixo)?
Comment: Nesse caso, seria interessante utilizar o padrão interpreter, pois, é evidente que seu problema gera uma estrutura composite. No momento, estou sem tempo para formular uma solução.
Comment: Não estou entendendo sua pergunta, o RegexList tem 3 RegEx's dentro dele, porque não chamar somente um deles quando existe a necessidade e atribuir na variavel, usando-a na hora que precisar? Não existe um método que faça o código "ler" de cima para baixo, ele já faz isso naturalmente, basta você estruturar corretamente.
Comment: @Paz Estou usando o preg_replace_callback para substituir os resultados das _patterns_ que estão no **$regexList**. Como pode ver [aqui](http://php.net/manual/en/function.preg-replace-callback.php), essa _função_ recebe também um _array_ com _patterns__ (no caso o **$regexList**. O problema é que essa _função_ pega a ocorrência da primeira _pattern_ no $regexList, em vez de pegar a primeira ocorrência na $string que tenha uma _pattern_ no **$regexList**, entende?
Comment: Eu não sei o que posso encontrar primeiro na **$string**, pode ser um **@if**, um **@for** ou um **{{$var}}**, mas sei que eu devo substituir as ocorrências que aparecerem primeiro na **$string**, no caso, a primeira ocorrência seria **{{$var}}, então eu substituiria **{{$var}}** com alguma coisa, a segunda seria **@for**, então eu executaria o loop, e por aí fora... É isto que não estou a conseguir.
Answer:
Estou usando o preg_replace_callback para substituir os resultados das patterns que estão no $regexList.
  [...] O problema é que essa função pega a ocorrência da primeira pattern no $regexList, em vez de pegar a primeira ocorrência na $string que tenha uma pattern no $regexList.

Use apenas um regex.
Nesse caso, não use um array. Em vez disto:
$regexList = [
                 '/regex1/',
                 '/regex2/',
                 '/regex3/',
             ];

Use isto:
$regex = '/regex1|regex2|regex3/';

Na função:
$resultado = preg_replace_callback(
                 $regex,
                 function ($matches) {
                     // ...
                     return 'substituído';
                 },
                 $texto
             );

Mas como sabe qual regex foi encontrado?
Pode usar grupos para identificá-los.
$regex = '/(regex1)|(regex2)|(regex3)/';

Então:
$resultado = preg_replace_callback(
                 $regex,
                 function ($matches) {
                     if ($matches[1]) {
                         return 'regex1 substituído';
                     } else if ($matches[2]) {
                         return 'regex2 substituído';
                     } else if ($matches[3]) {
                         return 'regex3 substituído';
                     }
                 },
                 $texto
             );

Mas você tem outros grupos nos padrões, e contar o número certo do grupo pode ser complicado. Podemos usar grupos nomeados para facilitar as coisas.
$regex = '/(?P<padrao1>regex1)|(?P<padrao2>regex2)|(?P<padrao3>regex3)/';

$resultado = preg_replace_callback(
                 $regex,
                 function ($matches) {
                     if ($matches['padrao1']) {
                         return 'regex1 substituído';

                     } else if ($matches['padrao2']) {
                         return 'regex2 substituído';

                     } else if ($matches['padrao3']) {
                         return 'regex3 substituído';
                     }
                 },
                 $texto
             );

Código
Para responder sua pergunta, com um pouco de recursão:
function analisar( $string ) {
    $regex = '/
                    (?P<var>       {{\s*\$(.*?)\s*}}                      )
                |
                    (?P<loop>      @for\((.*?)\)\s*{{((?:[^{}]|(?R))*)}}  )
                |
                    (?P<statement> @if\((.*?)\)\s*{{((?:[^{}]|(?R))*)}}   )
              /x';

    $resultado = preg_replace_callback(
                     $regex,
                     function ($matches) {
                         /*
                             //debug
                             echo "\n\nSubst: $matches[0]\n\$matches = ";
                             var_export($matches);
                         */
                         if ($matches['var']) {
                             return getVar($matches[2]);

                         } else if ($matches['loop']) {
                             return loop($matches[4], $matches[5]);

                         } else if ($matches['statement']) {
                             return getStatementResult($matches[7], $matches[8]);
                         }
                     },
                     $string
                 );

    return $resultado;
}

function getVar($nomeDaVariavel){
    return 'VAR('
        . analisar($nomeDaVariavel)
        . ')';
}
function loop($nomeDoArray, $codigo){
    return "LOOP\nLOOP-COND("
        . analisar($nomeDoArray)
        . ")\nLOOP-CODIGO("
        . analisar($codigo)
        . ')';
}
function getStatementResult($expressãoBooleana, $codigo){
    return "IF\nIF-COND("
        . analisar($expressãoBooleana)
        . ")\nIF-CODIGO("
        . analisar($codigo)
        . ')';
}

Teste:
$string = '
{{ $nomeCompleto }}

@for($nomes as $nome)
{{
  @if($nome == \'Eleandro\')
  {{

{{ $nome }}

  }}
}}
';

echo analisar($string);

Resultado:
VAR(nomeCompleto)

LOOP
LOOP-COND($nomes as $nome)
LOOP-CODIGO(
  IF
IF-COND($nome == 'Eleandro')
IF-CODIGO(

VAR(nome)

  )
)

Demo: https://ideone.com/pBfQBP
Comment: Obrigadasso mano. Mais vale tarde do que nunca.


receber json_encode ( (array) $objj) no jquery

Question: Tenho o seguinte retorno do PHP por JSON através de AJAX:
[
  "ok",
  [
    [
      {
        "\u0000CelulasReunioes\u0000idCelula":"17",
        "\u0000CelulasReunioes\u0000data":"2019-01-30",
        "\u0000CelulasReunioes\u0000presentes":"0",
        "\u0000CelulasReunioes\u0000visitas":"0",
        "\u0000CelulasReunioes\u0000criancas":"0",
        "\u0000CelulasReunioes\u0000decisoes":"0",
        "\u0000CelulasReunioes\u0000discipulados":"0",
        "\u0000CelulasReunioes\u0000jejum":"s",
        "\u0000CelulasReunioes\u0000evangelismo":"s",
        "\u0000CelulasReunioes\u0000supervisao":"s",
        "\u0000CelulasReunioes\u0000oferta":"30"
      },
      {
        "\u0000CelulasReunioes\u0000idCelula":"17",
        "\u0000CelulasReunioes\u0000data":"2019-02-01",
        "\u0000CelulasReunioes\u0000presentes":"10",
        "\u0000CelulasReunioes\u0000visitas":"2",
        "\u0000CelulasReunioes\u0000criancas":"2",
        "\u0000CelulasReunioes\u0000decisoes":"6",
        "\u0000CelulasReunioes\u0000discipulados":"1",
        "\u0000CelulasReunioes\u0000jejum":"n",
        "\u0000CelulasReunioes\u0000evangelismo":"n",
        "\u0000CelulasReunioes\u0000supervisao":"n",
        "\u0000CelulasReunioes\u0000oferta":"0"
      }
   ]
 ]
]

Basicamente fiz um (array) $objeto no PHP para poder usar json_encode () pois são retornos de objetos PHP
Agora, pretendo usar esse array de 2 posições`
retorno [ 0 ] = "ok";
retorno [ 1 ] = array PHP de objetos convertidos por (array) com vários índices;

Pegar a posição [ 1 ] do array e fazer um foreach.
resultado.forEach(function(reuniao, index){

    html  = '
' + reuniao.idCelula + '
';
    html += '
';
    html += '
Data : ' + reuniao.data + '
';
    html += '
';

});

Obs.:
O meu propósito aqui é transformar o retorno:
"\u0000CelulasReunioes\u0000idCelula"

em
"CelulasReunioesidCelula"

e, de preferência assim caso seja possível:
"idCelula"

Alguém pode me ajudar?
Comment: Vc já conseguiu fazer a parte do ajax? Onde, aqui na pergunta, está algum método do jQuery, como vc cita no título? Não entendi bem "onde vc está com dificuldade"...
Comment: sim: a parte que está assim: "\u0000CelulasReunioes\u0000idCelula":"17", já é o retorno do ajax. Aqui está normal. Agora preciso transformar esse retorno que no console sai assim : CelulasReunioes idCelula, em apenas assim: idCelula, isso no jQuery. Perceba que  \u0000 significa um espaço em branco
Comment: `CelulasReunioes` é o nome da sua classe no PHP? Se sim, como vc formou esse JSON? Pelo que entendi, o seu problema está na formação do JSON. É melhor vc corrigir isso no PHP, não acha? O que acha de [edit] a pergunta e postar o seu código PHP, se for o caso?
Comment: (array) $objeto.  Assim formei o array PHP, Mas ele entrega algo assim "\u0000CelulasReunioes\u0000idCelula":"17". para os índeces. Ele coloca um espaço antes e outro depois do nome da Classe
Comment: Te serve uma resposta que "corrija" o seu PHP? Quando digo corrigir, significa fazer de uma outra forma a qual acho mais adequado. Aí vc julga se é melhor pra sua aplicação...
Comment: sim, mas seria convertendo o objeto em em array atributo por atributo ou existe uma função mais direta como o que faz a (array) $objeto°
Comment: A minha resposta já explica e exemplifica. Confesso que ainda estou curioso! Como você conseguiu chegar a um JSON com o nome da classe em cada atributo? Tentei imitar seu JSON, mas não consegui! @_@
Comment: é como expliquei, converti objetos em array com a função (array) $objeto.
Comment: Vamos [continuar esta discussão no chat](https://chat.stackexchange.com/rooms/89169/discussion-between-lipespry-de-folga-and-carlos-rocha).
Answer: Como proposto nos comentários, vou reformular seu PHP (que não foi postado, mas, digamos que, desenvolvi essa parte do zero).
<?php
class CelulasReunioes
{
    public $idCelula, $data, $presentes, $visitas,
        $criancas, $decisoes, $discipulados, $jejum,
        $evangelismo, $supervisao, $oferta;

    public function __construct($dados)
    {
        $this->idCelula = $dados[0];
        $this->data = $dados[1];
        $this->presentes = $dados[2];
        $this->visitas = $dados[3];
        $this->criancas = $dados[4];
        $this->decisoes = $dados[5];
        $this->discipulados = $dados[6];
        $this->jejum = $dados[7];
        $this->evangelismo = $dados[8];
        $this->supervisao = $dados[9];
        $this->oferta = $dados[10];
    }

}

$obj1 = new CelulasReunioes(
    array(
        '17', '2019-01-30', '0', '0', '0', '0', '0', 's', 's', 's', '30'
    )
);
$obj2 = new CelulasReunioes(
    array(
        '17', '2019-02-01', '10', '2', '2', '6', '1', 'n', 'n', 'n', '0'
    )
);

header('Content-Type: application/json');

$retorno = array('ok', array($obj1, $obj2));

echo json_encode($retorno, true);

É uma classe simples, só para simularmos a formação do JSON... Ignore a minha classe, apenas crie seu JSON como no meu exemplo.
Nomeado json.php, este arquivo me retorna o JSON da seguinte forma (formatado via JSONLint.com):
["ok", [{
    "idCelula": "17",
    "data": "2019-01-30",
    "presentes": "0",
    "visitas": "0",
    "criancas": "0",
    "decisoes": "0",
    "discipulados": "0",
    "jejum": "s",
    "evangelismo": "s",
    "supervisao": "s",
    "oferta": "30"
}, {
    "idCelula": "17",
    "data": "2019-02-01",
    "presentes": "10",
    "visitas": "2",
    "criancas": "2",
    "decisoes": "6",
    "discipulados": "1",
    "jejum": "n",
    "evangelismo": "n",
    "supervisao": "n",
    "oferta": "0"
}]]

Agora, no cliente (HTML/JavaScript):
$.ajax({
    url: 'http://localhost/json.php',
    dataType: 'json'
})
.done(function(resultado){
    resultado[1].forEach(function(reuniao, index){
        let html  = '
' + reuniao.idCelula + '
';
        html += '
';
        html += '
Data : ' + reuniao.data + '
';
        html += '
';
        // Aqui o html já está pronto para o uso! Aplique-o onde quiser.
        console.log(html);
    });
});

Basicamente, adicionei o índice 1 no forEach a fim de fazer a repetição apenas no array que contém os objetos: resultado[1].forEach(...);.
No final da repetição, joguei um console.log(html) a fim de testes. Basta você substituir essa parte do código conforme sua necessidade.
Se quiser ver tudo funcionando, pode baixar no meu GitHub/LipESprY e simular no seu ambiente.
PS: Fiz a requisição do Ajax utilizando a biblioteca do jQuery versão 3.3.1;
Comment: pois é. dessa forma eu já tinha feito. Mas o que NÃO queria era exatamente isso. Percorrer o objeto atributo a atributo. Gostaria de sabe se existe uma outra função nativa do PHP que, assim como o (array) converta para array sem precisar percorrer os atributos
Comment: Colega, o `json_encode` já vai fazer todo esse serviço. Eu não percorri atributo por atributo. Apenas instanciei a classe 2 vezes pra ficar igual a sua! Parece que não estou entendendo seu objetivo... xD


how the natural policy gradient simplifies?

Question: in David Silver RL course page 37 for "natural policy gradient"  Using compatible function approximation we have:

So the natural policy gradient simplifies:

my question is how the above equation further simplified to the:
Answer: compatible function approximation of advantage function has the following form:
$A^{\pi_\theta} (s, a) = \nabla_\theta\log \pi_{\theta}(s,a)^T w$
this form makes sure that we can use it instead of true advantage function and still get a proper direction of the gradient. You simply plug this expression in the equation and get the result.


Como estabelecer uma conexão P2P?

Question: Em uma conexão normal, é preciso que quem vai receber a conexão esteja com uma porta aberta no roteador (transmitindo para um computador da rede interna). Mas em uma conexão P2P isso não acontece.
Como programas P2P funcionam independente dessa porta aberta? Como por exemplo, programas como torrent ou Gnutella fazem varias conexões com nós da rede, no caso do torrent tem o tracker que pode de alguma forma trabalhar como mediador e criar uma conexão entre as maquinas, mas no caso do Gnutella não existe algo centralizando, existe apenas uma lista de nós para se conectar.
Como posso implementar essa conexão inicial? Partindo do pressuposto que não é uma conexão local e que não há nenhuma porta aberta no roteador (como normalmente ocorre) (Não precisa necessariamente do código, só o conceito é suficiente)
Comment: Dê uma olhada nesse projeto https://pypi.org/project/pyp2p/
Answer: Primeiro, Você pode usar qualquer método de Python para criar a comunicação da rede P2P, pode usar socket se quiser programar em mais baixo nível, ou pode usar flask como servidor e request como clientes, ou qualquer biblioteca que permita a criação de um cliente e um servidor, você pode usar threading para programar em paralelo e manter varias conexões ao mesmo tempo.
Segundo, o Tracker do Torrent é um servidor intermediário que guarda as informações dos peers, o que facilita para eles encontrarem os outros na internet, quando não existe um servidor desse tipo, é necessário um tipo de método de procura nos próprios peers o que é bem mais difícil de se implementar, mas existem maneiras como IRC ou sites na internet que fornecem essas informações.
Terceiro, tem um milhão de técnicas para criar uma conexão P2P, pode usar Port-Forward para redirecionar os pacotes recebidos pelo IP publico para um IP privado na sua rede, ou pode usar servidores ICE(Interactive Connectivity Establishment) que usa Turn e Stun, entre outras é só pesquisar.

Como estabelecer uma conexão P2P?


How to define class methods in Python C API?

Question: I was trying to create a Python class definition in C++ code and access it in Python. However, the function is called but the parameters are not received correctly. Please help me in doing this properly.
#include <iostream>
#include <Python.h>

using namespace std;

#include <Python.h>

static PyObject* MyClass__Init(PyObject *self, PyObject *args)
{
    cout << "MyClass__Init Called" << endl;
    Py_INCREF(Py_None);
    return Py_None;
};

static PyObject* MyModule__Start(PyObject *self, PyObject *args)
{
    const char* zBuff;

    if (PyArg_ParseTuple(args, "s", &zBuff))
        cout << "MyModule Start Called with parameter " << zBuff << endl;
    else
        cout << "MyModule Start ERROR" << endl;

    Py_INCREF(Py_None);
    return Py_None;
};

static PyObject* MyClass__Start(PyObject *self, PyObject *args)
{
    const char* zBuff;

    if (PyArg_ParseTuple(args, "s", &zBuff))
        cout << "MyClass Start Called with parameter" << zBuff << endl;
    else
        cout << "MyClass Start ERROR" << endl;

    Py_INCREF(Py_None);
    return Py_None;
};

static PyMethodDef pModuleMethods[] =
{
    {"Start", MyModule__Start, METH_VARARGS, ""},
    {NULL, NULL, 0, NULL}
};

static PyMethodDef pClassMethods[] =
{
    {"__init__", MyClass__Init, METH_VARARGS, ""},
    {"Start", MyClass__Start, METH_VARARGS, ""},
    {NULL, NULL, 0, NULL}
};

void Start()
{
    Py_Initialize();

    /* create a new module and class */
    PyObject *pClassDic = PyDict_New();
    PyObject *pClassName = PyString_FromString("MyClass");
    PyObject *pClass = PyClass_New(NULL, pClassDic, pClassName);

    PyObject *pModule = Py_InitModule("MyModule", pModuleMethods);
    PyObject *pModuleDic = PyModule_GetDict(pModule);

    /* add methods to class */
    for (PyMethodDef* pDef = pClassMethods; pDef->ml_name != NULL; pDef++)
    {
        PyObject *pFunc = PyCFunction_New(pDef, NULL);
        PyObject *pMethod = PyMethod_New(pFunc, NULL, pClass);
        PyDict_SetItemString(pClassDic, pDef->ml_name, pMethod);
    }

    PyDict_SetItemString(pModuleDic, "MyClass", pClass);

    PyRun_SimpleString("import MyModule\n"
        "MyModule.Start('Hello Module')\n"
        "myObj = MyModule.MyClass()\n"
        "myObj.Start('Hello Class')\n");

    Py_Finalize();
};

int main()
{
    Start();
};

Output is,
MyModule Start Called with parameter Hello Module
MyClass__Init Called
MyClass Start ERROR

The Module function is called without any issue, but the class method is called without the proper input variable.
Answer: It appears that the parameter to self is always NULL and instead - for class methods - the reference to self is passed within the argument list.
So, to parse the arguments of a class method you need to parse the reference to self, too.
Since Python 2.6 you can provide a list of format specifiers to PyArg_ParseTuple. The number of format specifiers has to fit the number of arguments that are passed to the function (see https://docs.python.org/2/c-api/arg.html under (items) (tuple) [matching-items]).
By modifying your MyClass__Start function to parse an additional parameter, you are able to parse and print both arguments to inspect them.
For me, the following code
static PyObject* MyClass__Start(PyObject *self, PyObject *args)
{
    PyObject* argListSelf;
    const char* zBuff;

    if (PyArg_ParseTuple(args, "Os", &argListSelf, &zBuff)) {
        cout << "MyClass Start Called with parameters " <<
        cout << PyString_AsString(PyObject_Str(argListSelf)) <<
        cout << " and " << zBuff << endl;

        cout << "self " << PyString_AsString(PyObject_Str(self)) << endl;
    }
    else {
        if(PyErr_Occurred())
            PyErr_Print();

        cout << "MyClass Start ERROR" << endl;
    }

    Py_INCREF(Py_None);
    return Py_None;
};

results in
MyModule Start Called with parameter Hello Module
MyClass__Init Called
MyClass Start Called with parameters \
    0x602428<?.MyClass instance at 0x7f484a333200>0x602428 and HelloClass
self <NULL>

Note that I printed the pointer value of self, which is NULL.
I also added
if(PyErr_Occurred())
    PyErr_Print();

which I would always add for debugging purposes.
Comment: "It appears that the parameter to self is always NULL" is this a bug? Anyway issue resolved. Thanks bbastu.
Comment: I tried to figure out if it is a bug. All documentations and examples on the web that I found explicitly state, that self will be a pointer to the class instance. but none of them shows and example which uses the pointer. Is there anyone for whom self is not NULL?


For $2x+2y-3z\geq0$ and similar prove that $\sum\limits_{cyc}(7z-3x-3y)(x-y)^2\geq0$

Question:
Let $x$, $y$ and $z$ be non-negative numbers such that
  $2x+2y-3z\geq0$, $2x+2z-3y\geq0$ and $2y+2z-3x\geq0$. Prove that:
  $$(7z-3x-3y)(x-y)^2+(7y-3x-3z)(x-z)^2+(7x-3y-3z)(y-z)^2\geq0$$

I have a proof for the following weaker inequality.
Let $x$, $y$ and $z$ be non-negative numbers such that
$2x+2y-3z\geq0$, $2x+2z-3y\geq0$ and $2y+2z-3x\geq0$. Prove that:
$$(11z-4x-4y)(x-y)^2+(11y-4x-4z)(x-z)^2+(11x-4y-4z)(y-z)^2\geq0.$$
For the proof we can use the following lemma.
Let $a$, $b$, $c$, $x$, $y$ and $z$ be real numbers such that
$x+y+z\geq0$ and $xy+xz+yz\geq0$. Prove that:
$$(a-b)^2z+(a-c)^2y+(b-c)^2x\geq0.$$
Proof.
Since $x+y+z\geq0$, we see that $x+y$ or $x+z$ or $y+z$ is non-negative because if
$x+y<0$, $x+z<0$ and $y+z<0$ so $x+y+z<0$, which is contradiction.
Let $x+y\geq0$.
If $x+y=0$ so $xy+xz+yz=-x^2\geq0$, which gives $x=y=0$ and since $x+y+z\geq0$,
we obtain $z\geq0$, which gives $(a-b)^2z+(a-c)^2y+(b-c)^2x\geq0.$
Id est, we can assume $x+y\geq0$.
Now, $$(a-b)^2z+(a-c)^2y+(b-c)^2x=(a-b)^2z+(a-b+b-c)^2y+(b-c)^2x=$$
$$=(x+y)(b-c)^2+2(a-b)(b-c)y+(y+z)(a-b)^2$$
and since $x+y>0$, it's enough to prove that
$$y^2-(x+y)(y+z)\leq0,$$
which is
$xy+xz+yz\geq0,$
which ends a proof of the lemma.
Now we can prove a weaker problem.
From the condition we have:
$$\sum_{cyc}(2x+2y-3z)(2x+2z-3y)=\sum_{cyc}(9xy-8x^2)\geq0$$
and we see that $\sum\limits_{cyc}(11z-3x-3y)=5(x+y+z)\geq0$ and
$\sum\limits_{cyc}(11z-3x-3y)(11y-3x-3z)=9\sum\limits_{cyc}(9xy-8x^2)\geq0$
and by the lemma we are done!
This way does not help for the starting inequality.
Any hint please. Thank you!
Comment: Isn't the question obvious?
Comment: @user35508 Why it's obvious?
Comment: Let me post an answer..Then tell me your views..
Comment: Sorry..I missed a point
Answer: Proof:
Because both the conditions and the conclusion are homogeneous, we may assume that $x+y+z=1$.
Geometrically,
 $$\Delta=\{(x,y,z)\in \mathbb{R}^3 |\ 2x+2y−3z≥0,  2x+2z−3y≥0, \\
2y+2z−3x≥0, x+y+z=1\}$$
 is a triangle . By solveing three linear equations
$$2x+2y−3z=0,\  2x+2z−3y=0,\ x+y+z=1;$$
$$2x+2z−3y=0,\ 2y+2z−3x=0,\ x+y+z=1;$$
$$2x+2y−3z=0,\  2y+2z−3x=0,\ x+y+z=1;$$
we get three vertices of the triangle $\Delta$. They are $(\frac{1}{5}, \frac{2}{5}, \frac{2}{5})$, $(\frac{2}{5}, \frac{1}{5}, \frac{2}{5})$ and $(\frac{2}{5}, \frac{2}{5}, \frac{1}{5})$.
Then $\Delta=u(\frac{1}{5}, \frac{2}{5}, \frac{2}{5})+v(\frac{2}{5}, \frac{1}{5}, \frac{2}{5})+w(\frac{2}{5}, \frac{2}{5}, \frac{1}{5}),\ u+v+w=1, u\geq 0,v\geq 0,w\geq 0$.
Let $x=\frac{1}{5}u+\frac{2}{5}v+\frac{2}{5}w,\ y=\frac{2}{5}u+\frac{1}{5}v+\frac{2}{5}w,
\ z=\frac{2}{5}u+\frac{2}{5}v+\frac{1}{5}w$. We may write the inequality
$$(7z−3x−3y)(x−y)^2 +(7y−3x−3z)(x−z)^2 +(7x−3y−3z)(y−z)^2\geq 0$$
as
$$\dfrac{1}{25}[(u+v-w)(u-v)^2+(v+w-u)(w-v)^2+(u+w-v)(u-w)^2]\geq 0.$$
Obvioursly, it is schur's inequality. Equality holds for $(x,y,z)=(1,1,1)$, and for
$(x,y,z)=(4,3,3)$ or any cyclic permutation.
Comment: Thank you very much! Now, it seems very easy!
Answer: We can use the substitutions $2x+2y - 3z = u, \ 2y+2z - 3x = v$ and $2z+2x - 3y = w$ for $u, v, w \ge 0$.
By solving the system of equations above, we get
$x = \frac{2u+v+2w}{5}, \ y = \frac{2u+2v+w}{5}$ and $z = \frac{u+2v+2w}{5}$.
The rest is the same as @yao4015's solution.


Configure NLB for IIS Websites

Question: We have two IIS Servers SERVER A and Server B, where my website (port80) is hosted. I have configured a NLB CLuster for this website using fortinet firewall. and all the links which are pointed to cluster IP.
Health monitor for NLB is configured as
1. Check port 80 is up or not
Problem is:
Suppose my website is running in Server A. when i stopped the IIS in Server A, the website is not failovering to sever B, because port 80 is still open.
But if i disable the network connection in server A, failover will work and the website is accessible though server B.
I need to configure the NLB as, whenever my IIS goes down, failover should happen. Can any one should guide me which port/Service that i need to check in the NLB health monitoring. Appreciate any response
Answer: Look if you have "Default web site" up and running on port 80 in your IIS. If so, either stop/delete it or reconfigure your health check.

Configure NLB for IIS Websites


Binomial distribution problem / biased coin toss

Question: I've got a text where the following statement appears:
You have a biased coin that has a 51% chance of coming up heads and 49% chance of coming up tails. Tossing it 1,000 times, you will generally obtain more or less 510 heads and 490 tails, majority of heads. If you do the math, you will find that the probability of obtaining a majority of heads after 1,000 tosses is close to 75%. The more you toss the coin, the higher the probability (e.g., with 10,000 tosses, the probability climbs over 97%).
This is a Bernoulli experiment executed 1000 times so we are dealing with a binomial distribution.
So doing the math (with python)
from scipy.stats import binom

n = 1000  # tosses
p = 0.51 # probability of head (coin is biased)
x = 501  # to get majority of heads out of 1000 tosses I need just 501
binom.pmf(x, n, p)  # scipy library

0.021451693818843456

And for 10000 tosses
n = 10000  # tosses
p = 0.51 # probability of head (coin is biased)
x = 5001  # to get majority of heads out of 10000 tosses I need just 5001
binom.pmf(x, n, p)  # scipy library

0.0011231912772331355

Assuming I'm wrong, where is my error?
Thanks
Comment: You got the probability of exactly 501/1000 heads and then exactly 5001/10000 heads rather than at least that many.
Comment: Thanks Ian, but to this you need to add probability of 502/100, 503/100, ... 1000/1000 (which is highly improbable), which is equivalent to what Henry said in his answer: 1 - binom.cdf(x-1, n, p)
Comment: ...Yes, that is what I meant. I described what you got, which was clearly not what you wanted.
Comment: Oh, now I understand ... thanks!!
Answer: You are using the probability mass function when you should be using the cumulative distribution function or its complement
1 - binom.cdf(x-1, n, p) might give you what you are looking for.  Or you could take a sum
Comment: Thanks Henry, you are right


How can I avoid making unpleasant facial expressions when playing difficult chords?

Question: When I'm playing (learning) difficult chords on guitar (ex: F,B7) my facial muscles (basically lips) form a weird action (I felt it and I saw it in the mirror).
I feel I'll get used to it as I go and I have seen some good players also do that (may be they can't help it).
You may also have faced this experience in learning stage and got over it. How did you overcome this?
Comment: http://slugsolos.tumblr.com/
Comment: My good friend plays the piano with his mouth wide open. I almost frown when playing the piano, and I close my eyes when playing the guitar. Et cetera. It's no big deal IMHO :D
Comment: Julian Bream was also famous for his mid coitus facial expression. All part of rock'n'roll baby.
Comment: If you Google "guitar face" and click images, I bet you won't worry so much about making faces. In fact, you might realize it's practically required. :)
Answer: At first this happens because you are concentrating so much on your hands that the rest of your body can move in sympathetic ways - not just gurning faces, but you find some guitarists twist their bodies, arching their backs - not always deliberately :-)
Once you have learned the 'muscle memory' to a level that playing is automatic, the gurning reduces and you become much more relaxed. If you are pushing the limits of your capabilities it may happen.
Personally, I wouldn't worry about it - once you can play well, you'll be forgiven a lot of things.
Comment: "once you can play well, you'll be forgiven a lot of things" ofcourse
Comment: A pretty famous trombone player makes many facial expressions, especially with his eyebrows, while playing. The way he has said it, it's because he's concentrating so much on the tiny variations in his embouchure and the aperture in his lips. As Dr. Mayhem said, you'll be forgiven a lot of things once you can play well, and he's one of the best in the world.
Comment: @JoshFields Alessi eyebrows? Also, that's nothing compared to [Bartoli faces](http://www.youtube.com/watch?v=rISjBGOtHhs).
Comment: @NReilingh, Yes, Alessi eyebrows. Completely worth it with his playing though… As with her faces… I've seen videos of her before, but the singing is worth it!
Answer: The jazz nod and the blues grimace are things that many players practice for hours in front of a mirror to ACHIEVE...and you want to practice to ELIMINATE them?
heh
Try singing along.  You can't make weird shapes with your lips if you're using them at the same time as you're playing.
Answer: Circuits in your brain controlling your hands while playing, those circuits in some people are right adjacent to the circuits that control facial muscles. There can be a little bleed through, like faintly hearing the wrong phone call on your land line.
If you force yourself to smile while you play it may help.
Answer: Only eliminate a guitar face if it makes you look ugly.  Consult the opposite sex on this.
If it concerns you, practice playing in front of a mirror.  Also practice in front of a mirror moving from your guitar face to a relaxed face.  You will learn how it feels when you make the face and have the muscle memory to return your face to a relaxed position.
Answer: While playing the violin, I tend to make all sorts of strange faces. Like, faces that involve muscles I didn't even know I had (although now I have this strange ability for bizarre faces, which comes in handy when you're doing childcare ;-)).
For me, it manifests itself in the form of strange eyebrow movements and rapidly blinking eyes. I'll see videos of myself playing while my eyes are batting, and no, it's not particularly attractive.
I've started to curb this habit though. I received some advice in a different question, and have started thinking about it more. It is suggested that people who's facial muscles twitch a bit may be nervous or, in my opinion, straining to much. You should be totally - totally - relaxed while playing. If you are stressed, it will show in your body language.
Try recording yourself again and again, and focus on staying calm and collected... cool as a cucumber. If you get comments from non-musicians about your facial expressions, invite them to try. ;-)
Answer: I chew on my tongue when playing guitar. I am playing guitar for 30 years. But because I hardly ever perform I am not aware of my facial expression. It looks as if I am chewing a gum bit then I stop and you can see that I am not chewing any gum. It looks weird. A musician friend suggested I actually should chew a gum to prevent that becasue it is too late to eliminate that habit. So instead of hiding your mimic  you expose it.


Chef::DataBag and RSpec-mocks -- undefined method `recieve'

Question: i am trying to create a list method stub for Chef::DataBag class as follows:
$ cat spec/spec_helper.rb
require "rspec"

RSpec.configure { |config|
  config.mock_framework = :rspec
  config.mock_with :rspec
}

$ cat spec/test_spec.rb
require "spec_helper"
require "chef"

RSpec.describe "test" do
  describe "simple test" do
    it "mocks chef databag" do
      allow(Chef::DataBag).to recieve(:list).and_return {}
    end
  end
end

$ grep "rspec \|chef " Gemfile.lock | head -n 2
  gem "chef", "11.16.4"
  gem "rspec", "3.1.0"

when executing rspec i get the following error.
$ bundle exec rspec spec/test_spec.rb
F

Failures:

  1) test simple test mocks chef databag
     Failure/Error: allow(Chef::DataBag).to recieve(:list).and_return {}
     NoMethodError:
       undefined method `recieve' for #<RSpec::ExampleGroups::Test::SimpleTest:0x000000049964f8>
     # ./spec/test_spec.rb:7:in `block (3 levels) in <top (required)>'

Finished in 0.00048 seconds (files took 0.53998 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./spec/test_spec.rb:6 # test simple test mocks chef databag

that is how i verified that Chef::DataBag has the list method:
$ bundle exec ruby -e "require 'chef'; puts Chef::DataBag.methods" | grep list
list

can you please point out what is wrong?
Comment: Are you using ChefSpec?
Comment: @sethvargo, no. i don't. i exposed whatever i am using.
Answer: You misspelled "receive." Try this:
allow(Chef::DataBag).to receive(:list).and_return {}

Comment: grrrr. `d4m|\|` typo. i did not notice it. worth mentioning that the hash `{}` should be surrounded with `()`. i "love" interpreters. thanks.


What is the probability that a randomly chosen point lies inside a given parabola?

Question: A parabola (say $y^2=4ax$) divides the coordinate plane into two regions: one considered to be "inside" the parabola and the other "outside". However, both these regions are infinitely large. What is the probability that a randomly chosen point on this plane lies inside the parabola?
Of course, had the curve been one with finite area, one could argue that the probability is zero (i.e. it is an almost impossible event), but this seems to be much tricker.
More generally, how would one go about finding such a probability for any curve that encloses an infinitely large area?
Comment: Any time one speaks of a "randomly chosen point on a plane" it is necessary do describe how that point is chosen, because there is no one natural map from a pair of uniform randoms on $(0,1)$ to a range consisting of the whole plane.
Comment: No, there are ways to choose a random point.  For example, choose two independent uniforms $(u_1,u_2)$ on $(0,1)$ and let $r = -\ln u_1$ and $\theta = 2\pi u_2$.  Then the point described in polar coordinates by $(r,\theta)$ is randomly distributed over the plane.  But it is not uniformly distributed; there is no way to choose a uniformly distributed point over the plane.
Comment: Does that mean that there is no way of choosing such a random point at all?
Answer: An example that shows the probability need not be zero:
Choose two independent uniforms $(u_1,u_2)$ on $(0,1)$ and let $r=−\ln u_1$ and $\theta=2\pi u_2$. Then the point described in polar coordinates by $(r,\theta)$  is randomly distributed over the plane. The distribution is not uniform; the distance from the origin is exponentially distributed, thus concentrated near the origin.
Then for any given $\theta$ with $0 < \theta \leq \pi/2$, the value of $u_1$ that causes the point to lie just on the parabola is
$$u_1 = e^{-\frac{\cos\theta \cot \theta}{4a}}$$
When $\pi/2 < \theta < \pi$, that quadrant (by symmetry) has the same probability of $(r,\theta)$ lying inside the parabola as in the first quadrant; when $\pi \leq \theta < 2\pi$ the point of course cannot lie inside the parabola.
So the overall probability of $(r,\theta)$ lying inside the parabola will be given by
$$
\frac12 \frac2{\pi} \int_0^{\frac{\pi}{2}}e^{-\frac{\cos\theta \cot \theta}{4a}}\,d\theta
$$
That integral is not zero. For example, when $a=1$ the probability of lying inside the parabola is about $0.3617$.
(Here, I did this for the upward-facing parabola $y=4ax^2$ but for your example it will work along the same general lines.)
Answer: Let's talk about doing this for a general funtion f(x). As you hinted at this depends on how you approach the infinite plane. If we take a large square at the origin then we could calculate the integral for the area under the quadratic that intersects the square. Then calculate what proportion of the squares area that is. Then take the limit as the squares side length tends to infinity. This might give you an answer.
However my choice of a square was completely arbitrary so you may get a different answer if you used a different shape like a circle say. For your graph it seems to me that any regular shape would give you 0 when you take the limit because the gradients approach flat. But why must we use a regular shape.
This hasn't answered your question but I think sadly the question is not well defined. There may be concepts in measure theory about this that somebody else can tell you about however.


stack in listview flutter infinite height

Question: i want to put a card between an image and the rest of the page
so i used stack in listview builder but it doesn't give the expected result
what i want

what i get => https://i.stack.imgur.com/Oxy41.jpg
ListView.builder(
      itemCount: 1,
      itemBuilder: (context, i) {
        return Stack(
          children: <Widget>[
            first(_listviewurl, _listViewData[0], _listviewwe9t),
            Container(
              padding: EdgeInsets.all(40),
              child: Text(
                "News",
                style: TextStyle(
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                    fontSize: 32),
              ),
            ),
        Positioned(
        width: MediaQuery.of(context).size.width / 2.5,
        height: MediaQuery.of(context).size.height / 5,
        left: MediaQuery.of(context).size.width / 9,
        top: MediaQuery.of(context).size.height / 1.9,
        child: Card(
          semanticContainer: true,
          clipBehavior: Clip.antiAliasWithSaveLayer,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(20),
          ),
          child: Image.asset(
            "images/img1.jpg",
            fit: BoxFit.fill,
          ),
        ),
      ),
          ],
        );
      },
    ),

Answer: Because your card is in your listview and your listview's height is the same with your first Widget, you can add Container as parent widget of your Stack widget and set height for it:
Container(
  child: Stack(...)
)

Comment: well thank you man .. the first time i post a question and get an answer


Django TastyPie ForeignKey full = true not working

Question: I have two model Product and CartItem :
#product models.py
class Product(models.Model):
   objects = ProductManger()
   name = models.CharField(max_length=200)
   brand_name = models.CharField(max_length=100)
   description = models.TextField()

#CartItem models.py
class CartItem(models.Model):
   objects = CartItemManager()
   cart = models.ForeignKey(Cart)
   product = models.ForeignKey(Product)
   quantity = models.PositiveSmallIntegerField(blank=True, null=True, default=1)

I want to get all cartitems for a cart, for that in api.py (tastypie) i have the following:
class CartItemRelatedResource(ModelResource):

    class Meta:
       queryset = Product.objects.all()
       resource_name = 'item_product'
       allowed_methods = ['get']
       include_resource_uri = False
       authentication = SessionAuthentication()

class CartItemResource(ModelResource):
     product = fields.ForeignKey(CartItemRelatedResource, 'product', full=True)

    class Meta:
       queryset = CartItem.objects.all()
       resource_name = 'cart_item'
       excludes = ['modification_date']
       allowed_methods = ['post', 'get', 'delete']
       authentication = SessionAuthentication()

    def get_cart_items(self, request, **kwargs):
       self.method_check(request, allowed=['get'])
       self.is_authenticated(request)
       cart_id = request.GET.get('id', '')
       items = CartItem.objects.filter(cart__exact = cart_id)
       data = serializers.serialize('json', items)
       return HttpResponse(data, mimetype='application/json')

But when i get_cart_items, the response has the pk of the product, it doesn't have the product name or description. I want to get the product name too in the response. From what i have read full=true is the best solution(with minimum requests because a cart can have multiple cart items).
Answer: Your version of get_cart_items() is not using the Tastypie code to fetch, that's why full=True is not working.
full=True will work if you use the Tastypie default handlers to get the data.  You don't need to write your own get_cart_items().
Comment: thanks fro your reply. Should i be using `def obj_get_list(self, bundle, **kwargs):   cart_id= request.GET.get('cart_id') ... `
Comment: I don't full understand what you're trying to do, but in the general case you don't need to write any code at all, just use the default tastypie url.
Comment: I would like to have the url like /api/cart_item/cart/?id=1 opposed to /api/cart_item/cart/?cart__id=id. I will try with the later one and if it works will accepted your answer. Thanks for your help. I am new to django-tastypie :)
Comment: Oh, I get it now.  It would have helped if you added that in your answer.  It's probably best to over-ride the check_filters() and build_filters() functions to allow your filter.


Uncaught TypeError: Cannot read property 'validaDocumento' of undefined

Question: Estou tentando criar uma função de validação dentro do ValidationEngine, porém estou recebendo este erro:
Uncaught TypeError: Cannot read property 'validaDocumento' of undefined
E Não consigo identificar qual o problema. Tenho outro site utilizando a mesma função, e não consigo ver onde estou errando.
Meu código:
<!DOCTYPE html>

        <title>Teste</title>

        <form method="POST" class="validar formConsulta">
            CPF/CNPJ:
            <input type="text" class="validate[funcCall[validaDocumento]]" data-errormessage="Documento invalido!" />
            <input type="submit" value="Consultar">
        </form>

Link para acessar o código: https://codepen.io/maykelesser/pen/zEgovq
Já tentei mudar a ordem do Javascript (colocar em cima, no head, abaixo de tudo, inverter as funções) e sempre dá o mesmo erro.
O que posso fazer para sanar o problema?
Answer: O problema encontra-se aqui
$(function(){
    $(".validar").validationEngine("attach");
        function validaDocumento(field, rules, i, options){ return true; }
            $(this).submit(function(e){ e.preventDefault(); });
    });
});

O código acima só ira ser executado após a página ser carregada, você está importando os Scripts, a página esta sendo renderizada, consequentemente validate[funcCall[validaDocumento]] está sendo executado após a importação e antes $(function(){, pois o script só sera executado quando a página estiver carregada.
Você deve colocar o método validaDocumento fora.
$(function(){
    $(this).submit(function(e){ e.preventDefault(); });
    $(".validar").validationEngine("attach");
});
function validaDocumento(field, rules, i, options){ return true; }

Veja funcionando:

<form method="POST" class="validar formConsulta">
    CPF/CNPJ:
    <input type="text" class="validate[funcCall[validaDocumento]]" data-errormessage="Documento invalido!" />
    <input type="submit" value="Consultar">
</form>
Comment: Perfeito! Muitíssimo obrigado! Vou aplicar ao código real agora ;-)


How to prove this property of condition expectation?

Question: I'm trying to prove the following property of conditional expectation
$$E[f(X)Y+g(X)|X]=f(X)E(Y|X)+g(X)$$
I know that
$$E[f(X)Y+g(X)|X]=E[f(X)Y|X]+g(X)$$
But I can't see why
$$E[f(X)Y|X]=f(X)E(Y|X)$$
What am I missing out? Thanks very much in advance.
Comment: fiy I edited in above the missing conditionals  $E[f(X)Y|X]$ in $E[f(X)Y]$. I'm assuming their absence was a typo - ok?
Comment: @peterag Thanks. It wasn't really a typo though. In fact, I was thinking of $X$ as conditioning only the second term in $E[f(X)Y+g(X)]$. Just knowing that the two terms are being conditioned on it makes it all much clearer already, lol
Answer: Given $X=x$, $f(X)$ is equal to $f(x)$ and can be treated as a constant while evaluating the conditional expectation:
$$E[f(X)Y|X=x]=E[f(x)Y|X=x]=f(x)E[Y|X=x]$$
or in terms of random variables
$$E[f(X)Y|X]=f(X)E[Y|X]$$


Deploying Django + Next JS

Question: I have built Django + Next JS website and now I want to deploy. I don't know which one to prefer hosting server or VPS. Website is simple, static and kind of catalogue. Next JS default homepage is pages/index.js. I mean it is not index.html, it is index.js

Is it possible on hosting server? I'm asking because next js is also need to run node js server on development.
On VPS plan does anyone know about how to dockerize exactly this things?
Hosting or VPS?
Which hosting server do you prefer?
Answer: It all depends on you preferences and how you plan on developing the app further and maintaining it.
Some providers do give an option to configure your instances as you wish, others don't.
You could consider using
https://nextjs.org/docs/advanced-features/static-html-export
if your app has only client part and if you don't use server side render
Personally I would recommend to consider either Heroku, Digital Ocean or AWS for your deployments but it highly depends on your cost expectations etc.
All of these give you an option to configure you're server instances as you wish.
Heroku might need a bit less configuration, but probably is less flexible at the same time.
Digital Ocean or AWS will give you full control over the instances but will take a bit more effort for setting up the deployment etc.

Deploying Django + Next JS


JavaScript - nubie, window.onlaod and IIFE

Question: I have a plunker here - https://plnkr.co/edit/RZTF9uda8Cw2YQx8Gs1Y?p=preview
Its a simple event on a button
With window.onload it works but not with the IIFE.
I thought the IIFE would run once its created so is that not like once the window has loaded?
<code>    // (function(){

    //   var btn = document.getElementById('btn1');

    //   btn.addEventListener('click', function(){
    //     alert('Hi');
    //   })

    // })();

    window.onload = function(){

      var btn = document.getElementById('btn2');

      btn.addEventListener('click', function(){
        alert('Hi');
      })

    };
</code>
Answer:
I thought the IIFE would run once its created

Yes, of course. (It's kinda in the name already …)

so is that not like once the window has loaded?

And that is the problem.
Your script resource is embedded in the head, meaning at the time it is executed, the HTML element you are trying to select by its id does not exist yet.
So you either need to execute this after the element exists (window load, DOMContentReady), or embed the external script resource after the relevant HTML elements. (Placing scripts at the end of body is a general performance recommendation anyway.)
Comment: "would run once its created" — For a value of "it" equal to *the function* and not *the element*.
Comment: @Quentin yes, of course; I assumed that's what OP meant as well.


How can I filter users within a user-configurable range in Views?

Question: For example, consider a dating website.  Each user has an Age stored in their profile.  They also have a Max age and Min age, which are the maximum and minimum ages of people they hope to receive interest from (in other words, users with ages outside the range Min age - Max age should not be allowed to contact that user).
How can I build a page in Views that filters the results for the current user to show other users that both meet the current user's age range and for which the current user meets their age ranges?
In other words, I need to somehow filter the results like this:

Only show users that have ages within the range of the current user's Max age and Min age (example: current user is 20 and wants to see users from 18-25; filter to show users from 18-25)
Only show users for which the current user has an age that falls within the range of their Max age and Min age (example: current user is 20 and wants to see users from 18-25; filter to show users who want to receive messages from someone age 20)

Is this something I can somehow do with contextual filters, or do I need to write my own custom filter?
Comment: How about using [Views Contextual Range Filter](https://www.drupal.org/project/contextual_range_filter) for the view contextual filter, then constructing the links to this page dynamically by loading current user and appending min/max onto link, or overriding a views hook and adding parameters there.
Comment: @J.Reynolds That's a great module and a good start, but I realized there are two separate filters here.  Please see the updated question.
Answer: Install sandbox project Views arguments in filters
Add four contextual filters to your user view:

User:Uid, hide view when filter not available, Exclude (you will send in the user's own uid and exclude him from the result as you do not want him to be matched against himself)

Global:Null, hide view when filter not available, and give it an administrative title of 'current age'. (You will send it the current user's age as a param).

Global:Null, hide view when filter not available, and give it an administrative title of 'min age'. (You will send it the current user's min age preference as a param).

Global:Null, hide view when filter not available, and give it an administrative title of 'max age'. (You will send it the current user's max age preference as a param).

Then add normal filters as follows:

That should take care of the view, and you now just have to construct a link to add the parameters manually, or override a view hook to do so. Possible candidate would be hook_views_pre_view where you have direct access to args param, but on other hooks it should be available on the $view object.
Something like this code will work, and you can just add your own defensive programming and substitute where appropriate.
<code>function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == "compatible" &&  $display_id == "page" && user_is_logged_in() && count($args) != 4) {
    global $user;
    $account  = user_load($user->uid);
    $age = field_get_items("user", $account, "field_age");
    $min_age = field_get_items("user", $account, "field_min_age");
    $max_age = field_get_items("user", $account, "field_max_age");
    $args = array(
      $account->uid,
      $age[0]['value'],
      $min_age[0]['value'],
      $max_age[0]['value']
    );
  }
}
</code>


expression Encoder gives an error when try to capture screen

Question: currently i am developing an error reporting system using c#, in my case i am try to provide user to capture his or her screen when they recreating the problem, in my case i use expression encoder to capture my screen but when i try to run i get the following error

and this is the full code i used.. please help me to overcome this what is the wrong? when i try the same code @ my office which machines are using windows 7 enterprise edition it's work fine, but when i try to run the same code using my own laptop it gives this error  in my laptop am having windows 7 home premium , and also i try the same code with my friend's laptop which use windows 7 professional.. am i missing any configuration or any reference?
please help
this is the code
<code>namespace CAp
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void CaptureMoni()
    {

        try
        {

            Rectangle _screenRectangle = Screen.PrimaryScreen.Bounds;
            _screenCaptureJob = new ScreenCaptureJob();
            _screenCaptureJob.CaptureRectangle = _screenRectangle;
            _screenCaptureJob.ShowFlashingBoundary = true;
            _screenCaptureJob.ScreenCaptureVideoProfile.FrameRate = 20;
            _screenCaptureJob.CaptureMouseCursor = true;

            _screenCaptureJob.OutputScreenCaptureFileName = string.Format(@"C:\test.wmv");
            if (File.Exists(_screenCaptureJob.OutputScreenCaptureFileName))
            {
                File.Delete(_screenCaptureJob.OutputScreenCaptureFileName);
            }
            _screenCaptureJob.Start();
        }
        catch (Exception e) {
            MessageBox.Show(e.ToString());
        }
    }

    public ScreenCaptureJob _screenCaptureJob { get; set; }

    private void button1_Click(object sender, EventArgs e)
    {
        CaptureMoni();
    }
}
</code>
}
Comment: BTW: You can click **Ctrl+C** to copy text from an error dialog box to your clipboard. Usually better than posting a screenshot here.
Comment: yes bro, i know it but i did this for better readability since now am in very critical stage since i need to add this feature to my research project, thank you bro!
Answer: Finally I got the answer yesterday..., It's a matter of my laptops Resolution, since I am using the whole screen capture and expression encoder only support resolutions that can be divided by 4. After changing the resolution to a value that is divisible by 4 as a example (1280X1024), it finally works fine!


No module named .. while running Django tests with PyCharm

Question: I have the following error when running Django's tests with PyCharm 4.5 ImportError: No module named date_utils.
Here is a short overview the project tree:
.
├── manage.py
├── settings.py
├── app1
│   ├── models.py
│   ├── __init__.py            #Empty
├── utils
│   ├── __init__.py            #Empty
│   ├── date_utils.py

In app1.models.py, I do
from utils.date_utils import my_wonderful_function
I import both apps in my settings.py
INSTALLED_APPS = (
    'grappelli',
    '...',
    'djcelery',
    'utils',
    'app1',
)

Please note that it is working well when using manage.py test.
Can you please help understanding why this is happening with PyCharm but not with manage.py ? Thanks !
Answer: Ok, I found the problem. Problem was that PyCharm also have module named utils, and so the import was not using my module, but the PyCharm's one.
Comment: There is a patch on the JetBrains issues tracker. They say it will be resolved in version 4.5.3. But I am running that version and it is not resolve. I installed the patch and things seem to be working. Here is the URL: https://youtrack.jetbrains.com/issue/PY-16054#comment=27-1016339


Why does "sticky noise" defy averaging attack?

Question: I have read an interesting paper (pdf) describing how a privacy preserving technique might be breached, but I am having trouble understanding the following paragraph describing one of several layers of noise added to an observation.

Let C be a condition, e.g. "age = 34". The static noise associated with C is a random number drawn from a normal distribution N(0,1). The value is generated by a pseudo-random generator, whose seed is a salted hash of the string literal C:
static_seedC = XOR(hash(C), salt)
This ensures that the static noise associated with C is always the same independently from the query where C appears. The noise is "sticky" thereby preventing an attacker from sending the query many times and averaging the results to obtain a precise estimate of the private value ("averaging attack").

So if I understand correctly, the seed always generates the same number, let's say 0.4, so that C always becomes 34.4 instead of 34. If however C would sometimes be 33.9, 34.1, 34.2 and so forth, given enough trials the attacker would be able to draw a histogram which would be centered around 34 and infer that the age was 34?
If this is correct, can anyone please explain the equation above generating the noise (in this case the number 0.4)? I am not so familiar with the terms.
Comment: From what you posted, it's not entirely clear to me how they're using the "static noise". It would be good to include a citation and link to the original paper.
Comment: Regarding how they generate the static noise: The paragraph says they take the literal string "age=34" and run it through a [hash function](https://en.wikipedia.org/wiki/Cryptographic_hash_function). They combine the hash output with salt using the bitwise [exclusive or](https://en.wikipedia.org/wiki/Exclusive_or) function. [Salt](https://en.wikipedia.org/wiki/Salt_(cryptography)) is a fixed, random sequence of bits. The xor output is used as the seed for a [pseudorandom number generator](https://en.wikipedia.org/wiki/Pseudorandom_number_generator), which is used to generate the noise.
Comment: Hi, I've added an answer to your question. Let me know if anything is not clear :)
Answer: Full disclosure: I am one of the authors of the linked paper.
Your understanding is partially correct. I will explain more in detail how Diffix generates static noise.
Suppose that Diffix receives a query $Q$:
$$Q \equiv \quad \operatorname{count}(\ \textsf{age = 34} \quad \wedge \quad \textsf{gender = M}\ ).$$
$Q$ counts how many users (i.e. rows) in the database $D$ have age 34 and are male. We denote this number by $Q(D)$. Of course, $Q(D)$ is not necessarily 34 (this is the source of your misunderstanding).
In order to protect privacy, Diffix doesn't output $Q(D)$, but rather $Q(D) + \textit{noise}$. The $\textit{noise}$ is made of different noise layers: for each condition in $Q$, Diffix adds a static noise layer and a dynamic noise layer. $Q$ has two conditions, so the $\textsf{noise}$ will be made of $2 \times 2 = 4$ layers (i.e. noise values). Specifically, the output will be
$\newcommand{\static}{\textsf{static}}
\newcommand{\dynamic}{\textsf{dynamic}}$
\begin{align*}
\widetilde{Q}(D) = Q(D)
&+ \static[\textsf{age=34}] + \dynamic_Q[\textsf{age=34}] \\
&+ \static[\textsf{gender=male}] + \dynamic_Q[\textsf{gender=male}].
\end{align*}
To generate the noise value $\static[\textsf{age=34}]$, Diffix draws a number from a normal distribution $N(0,1)$. But Diffix makes sure that the value of $\static[\textsf{age=34}]$ is always the same (this is needed to protect privacy, see the paper for more details). In order to do this, Diffix uses a pseudo-random number generator, seeded essentially with a salted hash of the string $\texttt{'age=24'}$. You can read more about hashes, salts and PRNG on Wikipedia. But apart from technical details, the only thing you need to understand is that $\static[\textsf{age=34}]$ is immutable, meaning that its value stays the same for any query that contains the condition $\textsf{age=34}$. It would be absolutely equivalent to simply use a cache to store every noise value and reuse them every time the same condition is processed by Diffix.
The process to generate $\dynamic_Q[\textsf{age=34}]$ is similar, but here the seed depends also on the query set of $Q$. For details, please refer to the paper.
You can read a simplified version of the paper in our blog post.
Comment: Great! I've also added the link to our blog post where we give a simplified explanation of the attack.


LandXML to Topography.ByPoints doesn´t work as expected

Question: I´m new here, so I hope this thread doesn´t exist already.
I exported a LandXML file from Civil3D. In this file are 3 surfaces listed. Now my aim is to import it in revit and convert it to a topography. It was no problem to extract all the points and faces and generate a mesh. But with the Topography.ByPoint node I get a topography which doesn´t look right.
[mesh and topography][1]
I've already tried a lot. But now I have no idea what goes wrong. Does somebody has an idea?
Answer: I implemented and documented a Revit add-in to import a LandXML surface to Revit back in 2010; maybe that will help?
http://thebuildingcoder.typepad.com/blog/2010/01/import-landxml-surface.html
Comment: Thank you for your answer! I have used your LandXML-file in my dynamo project. And it seems to work. So I think my exported LandXML file seems to be incorrect. Can you tell me how or with which program do you have created the file?
Comment: that sample file was provided by a developer, so i do not know its source. you could check here: http://landxml.org/... however, also note that wikipedia says: LandXML: a non-proprietary standard for data exchange among the land development, civil engineering and surveying communities. The Open Geospatial Consortium (OGC) Land and Infrastructure Standards Working Group (LandInfraSWG) developed a UML as-is conceptual model of LandXML-1.2 that revealed problems with LandXML and broad disparity with the OGC standards baseline... https://en.wikipedia.org/wiki/List_of_XML_markup_languages#L


Accessibility Checks - TextInputEditText has contradictory exceptions

Question: All, we're using the Espresso Accessibility Checking and are getting the following errors for the same view. What's the best way to fix this? Removing the content description fixes the second error but the first still remains. Is there a way to satisfy the Accessibility Checker for TextInputEditText?
https://developer.android.com/training/testing/espresso/accessibility-checking
AccessibilityViewCheckException: There were 2 accessibility errors:
TextInputEditText{id=2131362592, res-name=reason}: View is missing speakable text needed for a screen reader
TextInputEditText{id=2131362592, res-name=reason}: Editable TextView should not have a contentDescription.

Answer: I noticed that this error will go away if you set the hint in the TextInputEditText and remove the labelFor in TextInputLayout.
According to Google documentation, setting the hint is the way to tell Accessibility about your view for EditTexts.

When labeling editable elements, such as EditText objects, use the android:hint XML attribute for static elements and the setHint() method for dynamic elements to indicate each element's purpose. (Source)

Also, in Google's example of TextInputLayout, it does not specify that you need to have the labelFor field. (Source)
Code Example:
<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TextInputEditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/edit_text_hint"/>

</android.support.design.widget.TextInputLayout>

I am aware that this post is in direct contradiction to this post:
Accessibility Check fail when using TextInputLayout. However, doing the things mentioned in that post did not work for me on the latest version of Android.
Comment: I had a similar problem because I was using `labelFor` in the `TextView` referencing an `EditText`. Removing `labelFor` and using `hint` in the `EditText` did the trick


What to do from stopping the program from exiting in Python before if command

Question: I used the following code for building a simple Python program which gets input from user.
Name = raw_input('Enter your name: ')
Age = raw_input('Enter you age:')
Qualifications = raw_input('Enter you Qualification(s):')
A = raw_input()

print "Hello" +'.'+ "Your Name is " + Name + ". " + "Your Age is " + Age + ". " + "Your Qualification(s) is/are:" + Qualifications + "."
print "If the above data is correct, type yes. If not, type no. Typing no will restart he program and make you write the form again." + A
if A in ['y', 'Y', 'yes', 'Yes', 'YES']:
    print 'Thanks for your submission'
if A in ['No' , 'no' , 'NO' ,'n' , 'N']:
    reload()

The program finishes before the if command.
Comment: Have you considered that if `A` is anything but one of the variations of Yes or No, your program will finish?
Comment: you might want to move `A = raw_input()` below the two lines starting with `print`. currently the user has to confirm before he sees the instructions
Comment: There is absolutely no reason for the code to finish before the `if` command
Answer: If you give anything but ['y', 'Y', 'yes', 'Yes', 'YES'] or ['No' , 'no' , 'NO' ,'n' , 'N'], your program will finish and not execute any of the statements in their respective if-clauses.
The reload() function will not do what you expect. It's used to reload a module and should be used inside the interpreter. It also requires a previously imported module as it's argument, calling it without will raise a TypeError.
So in order to actually ask the questions again, you'll need a loop. For example:
while True:
    name = raw_input('Enter your name: ')
    age = raw_input('Enter your age: ')
    qualifications = raw_input('Enter your Qualification(s): ')

    print "Hello. Your name is {}. Your age is {}. Your qualifications are: {}".format(name, age, qualifications)
    quit = raw_input("Is the above data correct [yY]? ").lower() # notice the lower()
    if quit in ("y", "yes"):
        break
    else:
        # If the input was anything but y, yes or any variation of those.
        # for example no, foo, bar, asdf..
        print "Rewrite the form below"

If you now input anything else than a y, Y or any variation of yes, the program will ask the questions again.
Comment: I want the program to ask input again if the user types anything other than yes or no. If the user inputs no, the program must print 'Rewrite the form below' before asking the questions again.
Comment: @VishalSubramanyam That is what the program does, until infinity. I updated the answer to include that print. If you realllly want to check for the `no` case, just add a similar check as in the `yes` case.
Answer: Move your A raw_input line after you print the "Your name is..." and stuff. Like this:
I also made the script keep asking to restart until the input is valid.
Name = raw_input('Enter your name: ')
Age = raw_input('Enter you age:')
Qualifications = raw_input('Enter you Qualification(s):')

print "Hello" +'.'+ "Your Name is " + Name + ". " + "Your Age is " + Age + ". " + "Your Qualification(s) is/are:" + Qualifications + "."
print "If the above data is correct, type yes. If not, type no. Typing no will restart he program and make you write the form again."

yes = ['y', 'Y', 'yes', 'Yes', 'YES']
no = ['No' , 'no' , 'NO' ,'n' , 'N']

A = ''

while A not in (yes+no):   # keep asking until the answer is a valid yes/no
    A = raw_input("Again?: ")

if A in yes:
    print 'Thanks for your submission'
if A in no:
    reload()