text:
Q: How to solve the Gammu CMS Error 38: "Network out of order"? I initially went smoothly Gammu, with status = 0 (SendingOK) . A few minutes later i was having problems with Gammu i found:
Thu 2016/10/13 15:34:45 gammu-smsd[5508]: gammu: 1 "AT+CMGS=109"
Thu 2016/10/13 15:34:45 gammu-smsd[5508]: gammu: 2 "> 0691261801000011000C818031121006390000FF6CD0323BEC3E9FC36E100C179BC962B0980D969BB140EB70BB0E1297E57537BDEE3E83C86178980EB2A6C9E537680532BEE96F17085917D7DDE7F48B5A66C3DF6ED0BA0C52D56030150E661B81EA6E7A7D0D0AB7C56936685E5E87E561F7D905"
Thu 2016/10/13 15:34:45 gammu-smsd[5508]: gammu: 3 "+CMS ERROR: 38"
Thu 2016/10/13 15:34:45 gammu-smsd[5508]: gammu: Checking line: +CMS ERROR: 38
Thu 2016/10/13 15:34:45 gammu-smsd[5508]: gammu: AT reply state: 5
Thu 2016/10/13 15:34:45 gammu-smsd[5508]: gammu: RECEIVED frametype 0x00/length 0x10B/267
Thu 2016/10/13 15:34:45 gammu-smsd[5508]: gammu: Error 38
Thu 2016/10/13 15:34:45 gammu-smsd[5508]: SMS sent on device: "com11:" status=38, reference=-1
Thu 2016/10/13 15:34:45 gammu-smsd[5508]: gammu: CMS Error 38: "Network out of order"
Thu 2016/10/13 15:34:45 gammu-smsd[5508]: Error getting send status of message: Unknown error. (UNKNOWN[27])

and this my configuration gammu :
[gammu]
port = com6:
connection = at115200
[smsd]
service = sql
logfile = myphone1
debuglevel = 255
phoneid = MyPhone1
commtimeout = 1
sendtimeout = 10
checksecurity = 0
hangupcalls = 1
deliveryreport = sms
user = root
password = admin
pc = localhost
database = smsd_database
driver = native_mysql

I used this device Gsm Gateway Sim Box 16 Ports Q2406B :
Device : com6:
Manufacturer : Wavecom
Model : MULTIBAND 900E 1800 (MULTIBAND 900E 1800)
Firmware : 651b09gg.Q2406B 244 041410 13:45
IMEI : 354397003322627

I know about status 38 :
"Network out of order" This cause indicates that the network is not
functioning correctly and that the condition is likely to last a relatively
long period of time; e.g., immediately reattempting the short message transfer
is not likely to be successful.

When I turn off gammu service, and then I restart status still gammu: CMS Error 38: "Network out of order" How best solution to solve this problem ?
Maybe many members gammu users also have experienced the same problem and could solve it. please share here. regards.
I've been looking for with Google still has not found a solution.
I really appreciate your help

A: This error can occur if the phone number is incorrect. For example, I had this error when I tried to text a phone number using 07********, and changing to +447***** (UK prefix) fixed this in my situation.


text:
Q: Handling revoking In-App purchase with iOS 14 I added the new revocation API provided with iOS 14 but i'm still confused about some aspect of it. I tested revoking my subscription using StoreKit Framework and I do enter in the didRevokeEntitlementsForProductIdentifiers callback.
But I'm wondering if this will cover all the cases where apple actually revoke access to a user because the user asked for a Refund. What happen if the app is closed? Will this method be called upon launching the app the next time?
Here is my code:
extension PurchaseManager: SKPaymentTransactionObserver {
    func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
        /*no-op*/
    }

    @available(iOS 14, *)
    func paymentQueue(_ queue: SKPaymentQueue, didRevokeEntitlementsForProductIdentifiers productIdentifiers: [String]) {
        SubscriptionHandler().validateSubscription()
    }
}

A: Yes, I understand paymentQueue(_:didRevokeEntitlementsForProductIdentifiers:) will be invoked when a refund request is granted, as well as if their access to the product changes. For example, with Family Sharing, they may cancel the subscription or leave the family. Note though that they may still have access to the purchased product so one should examine the receipt to know whether or not to revoke access (local receipt validation or via your server). For more information, see this WWDC 2020 video and the documentation.
If your app is not running, I understand paymentQueue(_:didRevokeEntitlementsForProductIdentifiers:) can be invoked when your app is launched next once you add an observer via SKPaymentQueue.default().add(self), similar to how paymentQueue(_:updatedTransactions:) works.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Wait for an element to be filled of text I use Selenium + Python and I work on a Page that data is filled from JS and is Dynamic every 10 seconds but it's not important because I will run it once a week, I want to wait as long as the td with id='e5' get its value and be filled Or rather until the site is fully loaded, The site address is as follows :
Site Address
But i dont find Suitable Expected Conditions for this job :
    driver = webdriver.Firefox()
    driver.get('http://www.tsetmc.com/Loader.aspx?ParTree=151311&i=2400322364771558')
    WebDriverWait(driver, 10).until(EC.staleness_of((By.ID, 'e5')))
    print(driver.find_element_by_id('e5').text)
    driver.close()

I speak about this tag if you cant find it :

A: Try this code to constantly check elements' text value
import time

pause = 1 # set interval between value checks in seconds

field = driver.find_element_by_id('e5')
value = field.text

while True:
    if field.text != value:
        value = field.text
        print(value)
    time.sleep(pause)

If you want to use WebdriverWait try
field = driver.find_element_by_id('e5')
value = field.text

while True:
    WebDriverWait(driver, float('inf')).until(lambda driver: field.text != value)
    value = field.text
    print(value)

A: There is an Expected Condition for that:
WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, 'e5')))

You don't need to wait for the element to be stale, you need it to be visible on the DOM.


text:
Q: How to deep copy an N-Ary tree in kotlin If you want to create a deep copy of a tree (so that each node in the tree is deep-copied), you have to use a recursive algorithm provided in the answer below.
I have not found such an article on SO, regarding realization of this in Kotlin, let alone the articles on N-Ary trees were too few and sparse. That is why I am leaving the code here for anyone who needs to solve such a problem.

A: Suppose, we have a tree class with type T:
data class Tree<T>(var root: TreeNode<T>) {
}

In that class we have a TreeNode class:
data class TreeNode<T>(var name: String, private var nodeAttributes: MutableList<T> = mutableListOf()) {

    var parent: TreeNode<T>? = null
    val childrenList: MutableList<TreeNode<T>> = mutableListOf()
    var depth = 0
        private set
    var index = 0
        private set
    var childLowestIndex = 0
        private set

    fun addChild(node: TreeNode<T>) {
        node.parent = this
        node.index = this.childLowestIndex
        this.childLowestIndex++
        node.depth = this.depth + 1
        childrenList.add(node)
    }
}

A TreeNode has a String name and nodeAttributes — the latter being a Mutable list of the type T that you Tree was initialized with.
It allows to assign and retrieve an arbitrary-length list of data of a chosen type to/from any TreeNode, upon creation or later via addAttributes() and getAttributes()
The tree structure is built upon nested TreeNodes.
Suppose we have to deep copy this Tree or a specific TreeNode.
In order to do that, to the Tree class we should add such a method
fun clone() = Tree(this.root.clone())

But in order to deep copy the tree that is initialized with a root node, that holds the whole data structure, we have to also deep copy the whole data structure i.e. every TreeNode in the structure.
To do that we can add this method below to the TreeNode class:
    /**
     * Return a new independent instance of this TreeNode (deep copy), uses recursion
     */
    fun clone(): TreeNode<T> {
        val newNode = TreeNode(this.name, this.nodeAttributes.map { it }.toMutableList())
        newNode.depth = this.depth
        this.childrenList.forEach {
            val newChild = it.clone()
            newNode.addChild(newChild)
        }
        return newNode
    }

What this method does on each call is:

*

*Creates a new temporary node newNode from the same initial parameters the node that clone() was called upon had

*Copies depth of the node as well. No need to copy the rest of the parameters.

*For each child of this node a clone() of that child is added as a
child to this node, thus the function is recursive.

*It goes until clone() on the deepest node is called, which has no
children, thus no cloning is executed afterwards and clone() returns
a deep copy of the deepest node.

*The algorithm goes all the way back returning all new deep-copied nodes with their deep-copied children and adding them as children to the nodes higher in hierarchy, until the original node that clone() was called upon is reached
Thus, treeNode.clone() returns a deep copy of any selected treeNode.
And afterwards the deep copy of an original tree is created from the deep-copied original node.
Once again:
fun clone() = Tree(this.root.clone())

I hope, this article was useful, feel free to add any corrections and suggestions in the comments.
Here is the link to the full code.
https://github.com/lifestreamy/TreeBuilder/blob/master/src/main/kotlin/treeBuilder/Tree.kt


text:
Q: Can't load file for bar plot I have the following:
\documentclass{article}

\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{filecontents}

\begin{filecontents}{testdata.csv}
  Probe      Mittelwert Standardabweichung
  well_PS         100.00       0.00
  PL-04-021_3      12.19       2.47
  Dextran         104.63       6.28
\end{filecontents}

\pgfplotstableread[col sep=space]{testdata.csv}\datatable

\begin{document}

  \begin{tikzpicture}
    \begin{axis}
      \addplot table[x=Probe,y=Mittelwert]{\datatable};
    \end{axis}
  \end{tikzpicture}
\end{document}

But I keep getting errors from pgfplotstable like
! Package pgfplots Error: Could not read table file 'testdata.csv'. In case you intended to provide inline data: maybe TeX screwed up your end-of-lines? Try `row sep=crcr' and terminate your lines with `\\' (refer to the pgfplotstable manual for details).

What am I doing wrong? Is there a possibility to get more verbose error output?
Update
I found this link which explains how to read a string column, but I fail to read in my .csv file, although hard coded in the .tex it works.

A: There are two problems here: First, you're trying to use strings (the "Probe" column) as the x-coordinate. By default, PGFPlots doesn't know what to do with that (should the point for well_PS be plotted before or after Dextran?). An elegant workaround for this is to simply use the coordinate indes of each data point for its x-coordinate, and use the text from the "Probe" column just for the tick labels. You can do this by using
\addplot table[x expr=\coordindex,y=Mittelwert]{\datatable};

to plot the data, putting
xtick=data,
xticklabels from table={\datatable}{Probe}

in your axis options to set the labels.
Then we run into the second problem, however: You have underscores in your "Probe" column, which lead to a Missing $ inserted error, because by default underscores are used to start a subscript in maths mode. The easiest way to fix this is to replace the underscores in your datatable with \_:

\documentclass{article}

\usepackage{pgfplots}
\usepackage{pgfplotstable}
\usepackage{filecontents}

\begin{filecontents}{testdata.csv}
  Probe      Mittelwert Standardabweichung
  well\_PS         100.00       0.00
  PL-04-021\_3      12.19       2.47
  Dextran         104.63       6.28
\end{filecontents}

\pgfplotstableread[col sep=space]{testdata.csv}\datatable

\begin{document}
  \begin{tikzpicture}
    \begin{axis}[
            xtick=data,
            xticklabels from table={\datatable}{Probe},
        ]
     \addplot table[x expr=\coordindex,y=Mittelwert]{\datatable};
    \end{axis}
  \end{tikzpicture}
\end{document}

A: As far as I know, your problem is based on linebreaks.
The way linebreaks are induced in Linux and Windows is different. Maybe you have seen the good old \l\n in some other programming language before. Basically, Windows wants you to tell it to move to the row below and to the left, while Linux assumes - you want to go down, than you want to go left as well. It does save a little hard-disk and occasionally leads to problems.
If you define inline data like that, this can be written with the wrong line ending by TeX. I'm not sure if it helps, but maybe changing your file format and/or your \usepackage[T1]{inputenc} can do the trick. Your editor of choice will be of assistance with the file format. Just say save as to see the options.
Sorry, but it is a hard to reproduce problem.
If everything else fails you will really have to add \\ to the end of every line and add the option row sep=crcr to your pgfplotstableread.
Also, usually it is advisable not to include tables this way. Simply plot them with \addplot table [x=Probe,y=Mittelwert,col sep=space] {testdata.csv}. It is easier on TeX's limited memory.
Try to experiment a little and report back.


text:
Q: GIT: accidental inclusion of password..how do I fix it? On a commit I accidentally included a password.  How do I remove this commit from the repository?
The push went to github so It's important that the commit be removed completely from the history.

A: You should do as follow:
git log --oneline -S <COMMIT_SEARCH_PATTERN>

# Copy the commit hash

git rebase - i <COMMIT_HASH>~1

# Change the marker to **drop**
# Exit from the editor

git rebase --continue
git push --force

A: To remove the password for future clones and fetches, I'd point you to git rebase, editing the commit and then doing a git push --force.
Of course - you have to change the password anyways.


text:
Q: if value is entered greater than the last element of list,it skips whole program and quits, by reversing condition of while block it runs properly Program quits completely at
while ((temp->x < new_node->x)&&(temp != NULL))

but it runs when written as
while((temp!=NULL) &&(temp->x < new_node->x))

Here is my code.
Node *insert(Node *head)
{
    Node *new_node = (Node *)malloc(sizeof(Node));
    new_node->next = NULL;
    printf("\nEnter x: ");
    scanf("%d", &new_node->x);
    if (head == NULL)
        return new_node;
    else
    {
        Node *prev = NULL, *temp = head;
        while ((temp->x < new_node->x)&&(temp != NULL))  // but, ((temp!=NULL) &&(temp->x < new_node->x)) runs
        {
            prev = temp;
            temp = temp->next;
        }
        new_node->next = temp;
        if (prev == NULL) // Node needs to insert at beginning to maintain the sorting of Linked List
            return new_node;
        prev->next = new_node;
        return head;
    }
}

A: Conditions in a loop or an if statement with && are evaluated strictly left-to-right, and the RHS is not evaluated unless the LHS evaluates to true.  You have:
while ((temp->x < new_node->x) && (temp != NULL))

The condition temp->x < new_node->x is evaluated before temp != NULL.  But, if temp is null, the first comparison will fail on most systems because accessing via a null pointer is undefined behaviour and normally causes a segmentation fault.
By contrast, when you write:
while ((temp != NULL) && (temp->x < new_node->x))

The code first checks for the null pointer, and if the pointer is null, does not evaluate the RHS condition, so the crash is averted.
The moral is always to check for null pointers before trying to access data through the pointer.  Obviously, if the pointer cannot be null, there is no need to test it before using it.  Sometimes, if the pointer should never be null, it may be beneficial to assert that the pointer is not null:
assert(temp != NULL);


text:
Q: Create Server on VirtualBox visible from outside, host is not behind router I am trying to create a web server on a Virtual Machine. I would be happy even if I could access it with something like http://xxx.xxx.xxx.xxx:[port_no] Everything is installed but the step of facing the outside world presents some problems for me, mainly because I am not behind a router. Here are some details:
Host OS: Ubuntu 12.04
The Host is connected to the world through a static IP (Ethernet), there is no router (it is a PC on a University campus and there is no DHCP). There is no firewall from the University administrators.
Guest VM: Ubuntu 14.04 (no windows environment) on VirtualBox.
When using NAT I can connect to the Internet, but if I understand correctly, a Bridged adapter would mean I need either a new static IP or a to be behind a router. When I enable the Bridged Adapter I get an IP 10.0.2.15, I am guessing on an adhocLAN, and ofcourse it does not work.
Is there any solution for my problem?

A: Sure, this is definitely possible. You just need to do some port-forwarding settings from your Virtualbox interface.
Go to Settings -> Network -> Port Forwarding. Then, add a new rule. In the host port, add some port which you wish to use, say 1212. In the guest port, add port 80 which is the default for apache.
Start your virtual machine and that's it. Your web-server can now be reached from your host machine as: http://localhost:1212, and from the external world as <Public-IP>:1212.
Screenshot:

PS: You don't need to use bridged connection or anything like that. Just keep it at NAT.


text:
Q: python get unicode string size I have a binary file. This file contains an UTF-8 string. Moreover, it is guaranteed that this string is just a single word.
In python, how can I get number of letters in this string?
Let's say, I opened this file and read bytes:
bytes = open("1.dat", "rb").read()

What next have I to do to find out length (in letters, not bytes) of UTF-8 string?

A: unicode_string = bytes.decode("utf-8")
print len(unicode_string)


text:
Q: how to improve performance of select I have written a procedure which takes several input parameters.
I need to validate the input.
If they are valid values they have to be present in the database table - attribute_values.
The problem is attribute_values table contains million records.
I am now supposed to improve the performance of select query.
For validating 1 input parameter I am doing something like this.
SELECT COUNT(1) INTO COUNT_VAR
  FROM ATTRIBUTE_VALUES A
 WHERE A.ATTRIBUTE_VALUE = input_paramater1;
IF COUNT_VAR = 1 THEN
SELECT ATTRIBUTE_VALUE_ID INTO MYVAR1
  FROM ATTRIBUTE_VALUES A
 WHERE A.ATTRIBUTE_VALUE =  input_paramater1;
END IF;

other_procedure(MYVAR1);

Any suggestions for improving performance of selecting from a table which contains a million  records.
Also out of count(*) and count(1) which is better.

A: Rather than doing a SELECT COUNT(*)... followed by a SELECT ID..., both against the same table, I suggest you rework this logic as follows:
BEGIN
  SELECT ATTRIBUTE_VALUE_ID
    INTO MYVAR1
    FROM ATTRIBUTE_VALUES A
    WHERE A.ATTRIBUTE_VALUE = INPUT_PARAMETER1 AND
          ROWNUM = 1;

  COUNT_VAR := 1;
EXCEPTION
  WHEN NO_DATA_FOUND THEN
    COUNT_VAR := 0;
    MYVAR1 := NULL;
END;

OTHER_PROCEDURE(MYVAR1);

This helps two ways. First, in my experience SELECT COUNT... is slow, so I try to avoid it whenever possible. Second, this not only saves a second query but lets you take advantage of the standard exception handling built in to PL/SQL.
Share and enjoy.
EDIT: given OP's revelation (in comments to the question, above) that ATTRIBUTE_VALUES.ATTRIBUTE_VALUE is not unique I've updated the code above so that it will not fail if more than one row would be returned.

A: For these queries, I would suggest an index:
create index attribute_values_attribute_value on attribute_values(attribute_value);

This should suffice for your purposes.

A: 3 STEPS:
1) If possible partition the table.
2) Create Index as follows
CREATE INDEX idx1_attribute_values ON attribute_values(attribute_value, attribute_value_id);

3) Use the following coding style for better results
BEGIN
    SELECT attribute_value_id
      INTO myvar1
      FROM attribute_values a
     WHERE a.attribute_value = input_parameter1;
EXCEPTION
WHEN others THEN
    myvar1 := 0;    -- Handle the error codes accordingly
END;

If it still doesn't work, post the plan of the query.


text:
Q: Deleting a dynamically allocated 2D array So I'm used to memory management in C where free(pointer) will free up all space pointed to by pointer. Now I'm confusing myself when attempting to do something simple in C++.
If I have a 2D array of doubles allocated in a manner similar to this
double** atoms = new double*[1000];
for(int i = 0; i < 1000; i++)
  atoms[i] = new double[4];

what would be the correct method of freeing the memory on the heap allocated by new?
My thoughts were originally this (because my brain was thinking in C):
for(int i = 0; i < 1000; i++)
  delete atoms[i];
delete atoms;

But I had forgotten the existence of the delete[] operator so I believe the correct method is as follows:
for(int i = 0; i < 1000; i++)
  delete[] atoms[i];
delete[] atoms;

Is it important to understand the difference between the delete and delete[] operators? Or can I just assume that whenever I allocate an array with ptr = new x[] I must also deallocate it with delete[] ptr?

A: In reality, an array of pointers pointed to by a pointer is still an array of integral data types or numbers to hold the memory addresses. You should use delete[] for both.
Also, yes, a new[] implies a delete[].
When you create an array of arrays, you're actually creating an array of numbers that happen to hold the memory address for another array of numbers. Regardless, they're both arrays of numbers, so delete both with delete[].
http://coliru.stacked-crooked.com/a/8a625b672b66f6ce
#include <iostream>

int main() {

    //Hey, pointers have a finite size, no matter the indirection level!
    std::cout << "sizeof(int*): " << sizeof(int*) << std::endl;
    std::cout << "sizeof(int**): " << sizeof(int**) << std::endl;
    std::cout << "sizeof(int***): " << sizeof(int***) << std::endl;

    //Create an array of pointers that points to more arrays
    int** matrix = new int*[5];
    for (int i = 0; i < 5; ++i) {
        matrix[i] = new int[5];
        for (int j = 0; j < 5; ++j) {
            matrix[i][j] = i*5 + j;
        }
    }

    //Print out the matrix to verify we have created the matrix
    for (int j = 0; j < 5; ++j) {
        for (int i = 0; i < 5; ++i) {
            std::cout << matrix[j][i] << std::endl;
        }
    }

    //Free each sub-array
    for(int i = 0; i < 5; ++i) {
        delete[] matrix[i];
    }
    //Free the array of pointers
    delete[] matrix;

    return 0;
}


text:
Q: Better saving and deploying site as wsp or programmatically creating lists, content types etc. in event receiver? In Sharepoint 2010 it is possible to save a site as a wsp solution package.
In my latest project a site consists of several subsites, lists, content types, permission groups views and so on. Creating all these things programmatically in a feature receiver is much efford.
Are there any disadvantages of saving and deploying the whole site as a wsp? I.e. will the site be ghosted on the target farm, and could the masterpage be changed later?
Thanks!


text:
Q: Getting mount type information in python on OSX Is there a way in which I can get some information about the mounts I have in the folder /Volumes in OSX?
I want to be able to tell the difference between disk images like dmgs and other types, like hard disks or network mounts.
I tried parsing the output of mount -v and looking if read-only is in the line but I doubt that's a particularly accurate way of telling, and also not a good method either.
Is there any module or method that will give me this information?

A: Have a look at the diskutil(8) and hdiutil(1) tools.


text:
Q: How to maven-publish a Gradle project JAR with provided scope Given a Gradle web project that is to be published as a JAR (so that it can be a dependency of another Gradle web project, which has a different release cycle).
The maven-publish plugin is used:
apply plugin: 'war'
apply plugin: 'maven'
apply plugin: 'maven-publish'

The web project has a providedCompile dependency:
providedCompile 'javax.servlet:javax.servlet-api:3.0.1'

A jar is published using mavenJava:
publishing {
    publications {
        // mavenJava publishes a jar file
        mavenJava(MavenPublication) {
            from components.java
        }
    }
    repositories {
        mavenLocal()
    }
}

The problem is that javax.servlet-api has a runtime scope in the resulting Maven POM:
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.0.1</version>
  <scope>runtime</scope>
</dependency>

Runtime scope makes no sense for the servlet-api, it is even harmful. How can the scope be set to provided in the pom.xml?

A: With the help of pom.withXml (see this Gradle sample) it's possible to transform Gradle's providedCompile into provided scope for Maven's POM:
publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java

            // providedCompile -> provided scope
            pom.withXml {
                asNode().dependencies.'*'.findAll() {
                    it.scope.text() == 'runtime'  && project.configurations.providedCompile.allDependencies.find { dep ->
                        dep.name == it.artifactId.text()
                    }
                }.each() {
                    it.scope*.value = 'provided'
                }
            }
        }
    }
    repositories {
        mavenLocal()
    }
}

What the pom.withXml section does is going through all dependencies of type providedCompile within the Gradle project configuration and changing the scope to be written into the Maven pom.xml from runtime to provided.
The generated pom.xml now has the provided scope set for the javax.servlet-api:
<project xmlns="http://maven.apache.org/POM/4.0.0" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <modelVersion>4.0.0</modelVersion>
    [...]
    <dependencies>
        [...]
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>


text:
Q: Incorrect audits Today, I failed an (unfair and incorrect) audit, the first one in a while, and I'm now banned from reviewing for two days. I naturally find this unfair and stupid, and I would really like to get the edit priviledge back.
I'm repeatedly failing these audits it seems, last time I brought it up in the chat with @Shog9, and recently I have not come across a single one that has been fair or even useful as an audit at all in my eyes. The most recent one, and the one that banned me, was this. In my opinion, this is a legitimate answer, other than the fact that the user chose to say that he encountered the problem as well, but it does provide an answer. Might be a good one, might be a bad one, but that's irrelevant in my opinion, an answer is an answer, no matter how correct.
Audits are incredibly annoying, and I know I'm a good reviewer, but I still fail at some. Please consider doing something about it, as it is really annoying to get this feedback when reviewing something that's actually correct, and on top of it all resulting in being banned from contributing through reviewing for two days, which happened to me. It isn't exactly motivating me to keep caring about reviewing.
Edit: It doesn't seem like anything has happened about this, I have complained again, and asked for clarification on how the audit system really works. Since this post, I have been quarantined/banned from reviewing 2-3 more times, once having it lifted (thanks Shog9), the rest waiting it out. As previously mentioned, it isn't exactly motivating me to continue reviewing.

A: Failing an audit is no shame. But you need to learn from the experience.
My review process is continuously changing. Based on the change of the systems, the discussions on meta and an occasional failed audit. The later was a sign that my system was flawed and needed an update.
Right now, I only use the review screen if I'm completely sure. If in doubt, I check the post link to get additional information.

A: I disagree. If you don't know if it's a good answer or not, you should click "Skip". By clicking "No Action Needed", you get that review out of the review queue, and thus are not allowing other people who could know if it's a good answer or not to review it.
Of course, this only applies to this audit. Perhaps other audits are incorrect, but I think this one is fair.

A: I'm the reason that answer was presented to you, because I'm the mod that processed the flags that collected on it indicating that it's not really an answer to the question.
I actually spent a bit of time on it, and almost edited it, but every edit I could think up left me with something that looked, at least to me like a comment at best. I did agree with the flags, but I generally favor improving terse answers that don't really meet our quality guidelines over just deleting them, if they can be saved.
So, when I elected to just delete it after a few minutes, it was because I felt like it was much more of a 'me too' comment left as an answer than an actual answer.
We have become rather strict with quality related flags for this very reason. When we validate them by taking a destructive action, we know there's a very good chance that they'll be used as a review audit. They need to be cut and dry, or at least darn close to it.
So, in this case, I think I probably made a mistake. I could have validated the flags (I did fully agree with them) and left the answer after at least a minor edit to improve it a bit, which would have kept it out of the audit. The fact that I deliberated for a few minutes means that it wasn't really cut and dry after all, and I will keep this experience in mind going forward (and, well, this is a good example of why we need to be extremely accurate). I'm a seasoned moderator with two years under my belt, if I had a hard time making heads or tails of it, I should have definitely made sure it didn't become an audit.
However, we are human, and we do make mistakes occasionally.

A: Once upon a time people complained a lot how crappy the new review system is with users abusing it by randomly voting/flagging/approving without paying attention. Thousands of letters have been written in Meta and many days passed.
Then came the review audits. Trivial, simple and easy to detect. The robo reviewers have been finally defeated, and many people were happy again.
Now I can't speak officially and don't have stats at my disposal but common sense tells me that those trivial audits were not enough. Many bad reviews still take place, by users who honestly think they are doing the right thing. So it's time for the audit system to grow up.
From system meant to filter out those who just review blindly and/or randomly just to gain some badges, it grew up to a system that educates the reviewers, teaching them what is a good review and what is a bad review.
In my opinion, it's a blessed and required change if we want the review process to be effective.
Last but not least, regrading the specific audit you linked to: personally I'm not familiar enough with the relevant area of expertise so would have skipped it, but either that answer was wrong (experts in that area should know) thus deserved a downvote or the answer better fit as comment, especially if it repeated something pretty obvious without giving any real help.
The new audits are not unfair, they are harder to detect as audits and look more like the real reviews that's all. Fine by me!

A: I have to agree to an extent as it seems like some of the audits I have failed just appeared to be the result of the person not being able to speak proper English (which there is plenty of that on these sites). I wish the substance of the audit would be more easily detectable (really obvious vandalizing) vs the way it is now where sometimes I am wondering if the edits are bad simply because of the language barrier.


text:
Q: node.js ejs include partials, and in the main, can't find the variable defined in the partial file this is my code to be included in the main ejs file.
<%

const IDP_URL = "http://idp.com:8082";
const SP_ID = "testing";
const SP_SECRET = "XRRpYIoMtaJC8hFLfUN7Bw==";
const TOKEN_VERIFY_FAIL_URL ="/exsignon/sso/token_verify_fail.ejs";
const LOGINUSER_REDIRECT_URL = "/exsignon/sso/sso_loginuser.jsp";
const ANONYMOUS_REDIRECT_URL = "/exsignon/sample/main.jsp";

%>

and in my main ejs file I'm trying to call sp_ID, and won't recognize and throws an error that sp_id is not defined, I've used many types of includes(<% include filename %>, <%- include filename %>, <%- include (filename) %>) and etc
any ideas would be appreciated

A: You have to wrap all your javascript code in <% %> tags
<% const IDP_URL = "http://idp.com:8082"; %>
<% const SP_ID = "testing"; %>
<% const SP_SECRET = "XRRpYIoMtaJC8hFLfUN7Bw=="; %>
<% const TOKEN_VERIFY_FAIL_URL ="/exsignon/sso/token_verify_fail.ejs"; %>
<% const LOGINUSER_REDIRECT_URL = "/exsignon/sso/sso_loginuser.jsp"; %>
<% const ANONYMOUS_REDIRECT_URL = "/exsignon/sample/main.jsp"; %>


text:
Q: iOS : Cropping Image from Rotated ImageView How to crop a rectangle(red square in screen shot) of UIImage which is rotated as well as zoomed using UIScrollView.
The edges of UIImageView are hidden because of rotation(UIImageView Transformation). Please help.

A: Well, you can do all the complicated core graphics things or do a simple UIView screenshot. I vote for the easy solution: What you have to do is create a new view with the frame same as where that small rect lies. Then add the whole image view to that small view converting its frame so it looks the same. Then take the screenshot of the small view. After you are done simply put the image view back the way it was and remove the small view.
As this is still easier said then done here is some code to chew on (I did NOT test this so please correct the bugs if any after you succeed).
- (UIImage *)getScreenshotInRect:(CGRect)frame {
    UIImageView *theImageView; //your original image view

    UIView *backupSuperView = theImageView.superview; //backup original superview
    CGRect backupFrame = theImageView.frame; //backup original frame

    UIView *frameView = [[UIView alloc] initWithFrame:frame]; //create new view where the image should be taken at
    frameView.clipsToBounds = YES; //not really necessery but can be usefull for cases like using corner radius
    [self addSubview:frameView];

    theImageView.frame = [theImageView.superview convertRect:theImageView.frame toView:frameView]; //set the new frame for the image view
    [frameView addSubview:theImageView];

    UIImage *toReturn = [self imageFromView:frameView]; //get the screenshot

    theImageView.frame = backupFrame; //reset the image view frame
    [backupSuperView addSubview:theImageView]; //reset the image view's superview

    [frameView removeFromSuperview];
    frameView = nil;

    return toReturn;
}
- (UIImage *)imageFromView:(UIView *)view {
    UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.opaque, .0f);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

I do hope this doesn't break because you have rotations. If that is the case I suggest you create another view on which the rotated image view lies and add this view to the small view.


text:
Q: What is the correct way to use escape_value() in XML::Simple Can anyone please guide me how to use this escape_value().
I want to escape this characters:  because it gives reference to invalid character number error.
this is my code
my $xs = XML::Simple->new( KeepRoot => 1, KeyAttr => 1, ForceArray => 1 );
$xs->XMLout($filename, escape_value(`'`')); // but this is not working
my $data = $xs->XMLin($filename);

thanks in advance

A: Looking at the code, it appears that the escape_value method  takes a string and returns returns that string with the following substitutions:

*

*> to >

*< to <

*& to &

*" to "
It doesn't even manipulate the structure of the object. If you call it directly, you simply would do this:
my $string = '"Remove quotes" & <entities> quotes';
my $encoded_string = $self->escape_value( "$string" );
say $encoded_string;  #"Remove quotes" & and <entities> quotes

Heck, why even bother with object orientation?
my $string = '"Remove quotes" & <entities> quotes';
my $encoded_string = XML::Simple::escape_value( "$string" );
say $encoded_string;  #"Remove quotes" & and <entities> quote

What it looks like is that this subroutine is called by XMLOut itself whenever the option NoEscape is either not set or set to 0.
In line 636 of the code, the XMLOut method is calling the value_to_xml method. This takes the data structure passed into XMLOut and creates an XML text. The value_to_xml method then calls the escape_string method in line 1431.

A: U+000C is not allowed in XML.

Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]

Not even escaped.

Characters referred to using character references MUST match the production for Char.


text:
Q: new ArrayList() failing in Java I have the following code:
List<int> intList = new ArrayList<int>();
for (int index = 0; index < ints.length; index++)
{
    intList.add(ints[index]);
}

It gives me an error...
Syntax error on token "int", Dimensions expected after this token

The error occurs on the line starting with List. Can someone explain why I am getting the error?

A: Generics in Java are not applicable to primitive types as in int. You should probably use wrapper types such as Integer:
List<Integer> ints = ...

And, to access a List, you need to use ints.get(index).

A: you should use Integer instead of int because lists requires object not primitive types. but u can still add element of type int to your Integer list

A: You can only use an Object type within the <> section, whereas you're trying to use a primitive type. Try this...
List<Integer> intList = new ArrayList<Integer>();

You then need to access the values using intList.get(index) and intList.set(index,value) (and also intList.add(value) as you are trying to do)

A: You can use primitive collections available in Eclipse Collections. Eclipse Collections has List, Set, Bag and Map for all primitives. The elements in the primitive collections are maintained as primitives and no boxing takes place.
You can initialize a IntList like this:
MutableIntList intList = IntLists.mutable.empty();

Note: I am a contributor to Eclipse Collections.


text:
Q: what is the intention and real purpose of writer in this context? what is the intention of writer in this context?
"does it say that assertions of that woman and mental position of those who heard them can destroy a serious and crucial investigation?"

It is a curious psychological study, and equally curious is the mental
  attitude of the people who could imagine that the assertions of an
  unbalanced woman, acting not only from motives of hatred but also
  from—as she herself stated—the hope of pecuniary reward, could upset
  the critical investigation of a generation of observers.

from http://gutenberg.net.au/ebooks03/0301051h.html

A: The writer is considering the mental attitude of the people who are capable of believing that "the assertions of an unbalanced woman, [...] could upset the critical investigation of a generation of observers." It could, perhaps, be rewritten thus:

It is a curious psychological study. It is also curious that people
  could imagine that the assertions of Mrs Fox-Kane could upset the
  critical investigation of a generation of observers. She was an
  unbalanced woman, who was acting not only from motives of hatred but
  the hope of pecuniary reward, as she herself stated.


text:
Q: Physics of the trikke tricycle I love my trikke, but I still do not understand what propels it forwards.
It is very clear that the energy comes from my legs and not from my arms (I only have to touch the handle bar ever so lightly), but I do not see how my shifting weight from side to side can result in a forward pointing force.
How is the side to side movement converted into a forward moving force?
(And just to be clear: My trikke is not electric).

A: First off, you might as well ask, what makes any vehicle go forward? When you're riding a bike, you're just pushing pedals up and down, so how does that end up making the bike go forward? When you're driving a car, how does the engine make the car go forward? After all, the pistons in the engine just oscillate back and forth.
The answer in all cases is that the forward force ultimately comes from friction with the ground. If a bike, trikke, or car were on perfectly frictionless ice, they all wouldn't be able to go forward. Of course, this doesn't mean that the ground itself is suppling the energy. For bikes or cars, you (or the engine) supply the energy, but the friction force is necessary to convert it into useful forward motion; without friction, the energy just makes the wheels spin in place.
Now specifically, the trikke works just like ice skates and rollerskates work. In the first half of a step on the trikke, you let your body fall down a bit, slightly forward and to the left. If you were on a frictionless surface, this would make your upper body move forward and your lower body move backward, generating no net motion. But because there is friction with the ground, your entire body and the trikke are overall accelerated forward and to the left. In the second half of the step, you move your body back up; that's the part that requires energy input from the legs. Then this is repeated in a step where you fall down forward and to the right, giving a net forward motion.

A: The front wheel provides a friction force perpendicular to the direction it is pointing. Since the wheel turns the trikke one way, the reactive force of the road on the wheel pushes the other way. Since this is perpendicular to the wheel, there is a component of forward force on the bike (or backwards as the case may be).
As with swinging on a swing, your body (or the part of the brain responsible for controlling it) works out what to do. Not so easy to bring that knowledge to the level of conscious thought. You have to lean in to the turn of the trikke or you would fall off (like riding a bicycle).
You turn the handlebar with your arms, but the force is transmitted through the frame of the trikke. Your legs supply the energy through shifting your weight.

A: See the technical studies at http://www.lastufka.net/trikke/. The main physical principle is angular torque via angular momentum transfer from the body to the Trikke. The generation of motion is very much like cross country skiing according to skiers. Both legs and arms can contribute to the angular momentum transfer. The motion is more like a washing machine agitator - side-to-side motion cannot physically contribute as all forces perpendicular to the wheels get canceled by friction and only those parallel (via torque) produce motion. "Leaning" (technically cambering the front wheel via the steering column) helps the rider generate torque, but is not necessary.


text:
Q: CodeIgniter: OS Command Injection Is there a way in CodeIgniter to prevent OS command injection automatically? I am aware of all the other protection CI has, but cannot find any material about OS Command Injection.
EDIT after comments received:
We are developing a web app that we are developing, will be hosted inside a large internal network where they have strict security policies that we will need to adhere to. One of them is OS Command Injection protection. They are afraid that users will run OS Commands through input fields. Is this possible, and how do I prevent this?

A: CodeIgniter doesn't run shell commands, which is a pretty easy way to prevent command injection. If you are adding shell command execution to the web app you are creating you will need to take care of preventing command injection yourself.

A: CodeIgniter has features for preventing SQL Injection but not Command Injections. There are 3 ways to prevent attack from url:

*

*Set limited user permission to runs web application. Make sure he won't be able to write or execute out of control.

*Disable php functions in disable_functions in php.ini.

*Install Suhosin 수호신 which is a PHP security extension and stop eval(). Because eval() is a construct not a function, you cannot disable with disable_functions in php.ini.
Check my command injection attack in Check And Solve If Your QNAP NAS Has been Injected a CPUMiner Program. It contains not only shell_exec() but also eval().


text:
Q: Insert And Update in One Batch I've scoured the internet for a precise answer without much success. Here is my scenario.
In the JDBC universe, it's standard practice to add several "inserts" OR several "updates" into one statement and execute them as a batch. These are homogenous queries, and it makes perfect sense to batch them. Great!
Now let's consider this case. One transaction constitutes of one "insert" and subsequent other "inserts" to be considered successful. An example would be you have an object Parent_A, that has a list of children [Child_M, Child_N, Child_O,...]. Saving Parent_A requires that you also save the children successfully.
Another slightly different example would be, you have a User U and a child Account A. User U can exist without Account A. But on inserting a new Account A, that is for user U, it is required that you also update User U with the Account info (that would be a transaction).
Given the above two scenarios, is it possible to:
1) Given a list of Parents, can you be able to batch all the queries under one transaction?
2) Given a list of Users, can you be able to insert and update each user with an account in a batch execution, and all under a single transaction?
I hope this is not so verbose!!

A: You can do this by using the addBatch(String) method on Statement.
However, since that requires you to actually build the entire sql string yourself (no use of PreparedStatements/bind variables), it would probably be easier to just do 1 batch execution for each table (i.e. Parent, Child) and only commit if all succeed.


text:
Q: Adobe Acrobat Date Picker/Field Returns an Error Every Time on One Specific Form But Works on All Other Forms The date picker/field on one specific form returns an error every time but works on all other forms. Even when I manually try to enter it using the correct formatting, it still returns an error. Below is the code attached to the field. The first piece of code is attached to the exit event and contains the error message returned while the second piece of code is attached to the change event. Is this caused by a bug with my version of Adobe or is my code causing this issue? I know there were issues with the date picker in previous versions of Adobe. Please let me know if you need any other information.
Current Version:
2021.007.20102
Exit Event:
if((!this.isNull) && (!this.execValidate()))
{
    xfa.host.messageBox("You have entered an invalid date. Please select a date from the date picker.");
    this.rawValue = null;
})

Change Event:
if (xfa.event.newText.match(/[^0-9\/]/))
{
    xfa.event.change = "";
}


text:
Q: Second Ajax call already populated with success results I have an Ajax call being made from a button press which returns me some data then goes off and creates a grid. The first time the function is called the Ajax call is made, data is returned and the grid is displayed. Happy Days.
However any subsequent call to the function, where none of the data parameters are changed, result in the Ajax call not being made to the server and the function skips straight to 'success' with the results from the successful call already populated.
Changing any of the 'postParameters' results in a successful Ajax call and the data is refreshed.
function btnClick(){
    //blah blah
    getGridData();
}

function getGridData() {
    var postParameters =
    {
        SiteID: "@Model.SiteID",
        DateFilterFrom: $("#datepickerFrom").val(),
        DateFilterTo: $("#datepickerTo").val(),
        CustomerFilter: $("#customers").val()
    };
    $.ajax({
        url: "@Url.Action("SalesForecast_Read", "Planning")",
        type: "GET",
        contentType: "application/json; charset=utf-8",
        data: postParameters,
        dataType: "json",
        success: function (results) {
            createHighlights(results.Highlights);
            createGrid(results.Entries);
        },
        error: function (e) {
            alert(e.responseText);
        }
    });
};

I know there must be an important Javascript concept I am missing but I just cant seem to be able to nail it.
Can anyone help put me in the right direction?

A: Have you tried to disable the cache with:
$.ajax({
    url: "@Url.Action("SalesForecast_Read", "Planning")",
    type: "GET",
    cache: false,
    contentType: "application/json; charset=utf-8",
    data: postParameters,
    dataType: "json",
    success: function (results) {
        createHighlights(results.Highlights);
        createGrid(results.Entries);
    },
    error: function (e) {
        alert(e.responseText);
    }
});

Explanations
The cache basically tries to save a call to the server by saving the return value of the calls.
It saves them using a hash of your query as a key, so if you make a second query that is identical, it will directly return the value from the cache, which is the value that was returned the first time.
If you disable it, it will ask the server for every query.

A: try to add this in ur ajax call:
$.ajax({
  cache: false,
  //other options...
});

This will force the recall of the ajax each time.
For more information please check the following link :
api.jquery.com/jquery.ajax

A: You can add cache: false to your ajax request.
$.ajax({
    url: "@Url.Action("SalesForecast_Read", "Planning")",
    type: "GET",
    contentType: "application/json; charset=utf-8",
    data: postParameters,
    dataType: "json",
    cache:false,
    success: function (results) {
        createHighlights(results.Highlights);
        createGrid(results.Entries);
    },
    error: function (e) {
        alert(e.responseText);
    }
});

IE might not listen to you though. For that you can add a field to the POST Parameters, where you add the current time in miliseconds, so even IE does not cache.


text:
Q: Add JavaScript to all WooCommerce Products Does anyone know how to add JavaScript to all WooCommerce products?
From what I've read, I might need to upload the code on my server as a .js and then point to it via a function?

A: If you need to do this on the single product page use this condition then enqueue the JavaScript files.
function enqueue_single_product_javascript()
{
    if(is_product())
    {
       // Use wp_enqueue_script()
    }
}
add_action('wp_enqueue_scripts', 'enqueue_single_product_javascript');

https://developer.wordpress.org/reference/functions/wp_enqueue_script/
https://docs.woocommerce.com/document/conditional-tags/


text:
Q: Product of two random Gaussian matrices - orthant probability In my studies of random matrices, I recently came across this challenge:
Let $X \in \mathbb{R}^{m \times n}$ and $Y \in \mathbb{R}^{n \times k} $ be two independent Gaussian random matrices, i.e., with entries independently sampled from $\mathcal{N}(0,1)$ (a normal distribution with zero mean and unit variance). We define the positive orthant probability $$p_+(m,n,k) \triangleq P(\forall i,j: (XY)_{ij} >0).$$
Question: How does $\log_2 p_+(m,n,k)$ behave asymptotically, to leading order, in the limit $ n \rightarrow \infty$ and $\alpha m = \beta k = n $, for some positive constants $\alpha$ and $\beta$?
Note that if $n\rightarrow \infty$ but $m$ and $k$ remain fixed, then from the central limit theorem $\frac{1}{\sqrt{n}}XY$ becomes a Gaussian matrix with independent entries, and then we get $\log_2 p_+(m,n,k) = -mk$. However, I wish to know if this asymptotic behavior persists when $m$ and $k$ are of similar magnitude as $n$. In other words, for what positive constants $a, b$ and $c$, do we have
$$\lim_{\underset{\alpha m = \beta k = n}{n\rightarrow\infty}} \frac{1}{m ^{a }k^{b}} \log_2 p_+(m,n,k) = -c \,.$$
Is it $a=b=c=1$, like in the case of fixed $m$ and $k$, or something else? I guess the answer should depend on $\alpha$ and $\beta$.
If no exact answer will be given to my question, I'll award the answer to whoever supplies the tightest upper bound (non-trivial, in which $a+b>1$).
Thanks in advance!


text:
Q: How to detect Databricks environment programmatically I'm writing a spark job that needs to be runnable locally as well as on Databricks.
The code has to be slightly different in each environment (file paths) so I'm trying to find a way to detect if the job is running in Databricks. The best way I have found so far was to look for a "dbfs" directory in the root dir and if it's there then assume it's running on Databricks. This doesn't feel like the right solution. Does anyone have a better idea?

A: How about this:
Python:
def isLocal():
    setting = spark.conf.get("spark.master")
    return ("local" in setting)

Scala:
def isLocal(): Boolean = {
    val setting = spark.conf.get("spark.master")
    return ("local" contains setting)
}

A: You can simply check for the existence of an environment variable e.g.:
def isRunningInDatabricks(): Boolean =
  sys.env.contains("DATABRICKS_RUNTIME_VERSION")

A: You can look for spark configuration environment variable such as   "spark.home" and value as /databricks/spark
python:
sc._conf.get("spark.home")
result:
'/databricks/spark'

A: This is simple. Databricks notebooks are not files.
# If it is a file...
try:
    __file__
    print("It is a file")
except NameError:
    print("It is a Databricks notebook")


text:
Q: json yql data retrieval via php I'm struggle extracting necessary data from this json stored inside php variable.
Not yet expert in this kind of data structure yet...
Wondering anyone know how to make it work.
I need to loop through results, then read each contact to get
1. the value where type=email
2. value->givenName where type=name (whenever element exist)
the json decoded value is as below
$aNative   = json_decode($retval);

echo "lang: " . $aNative->query->lang . "
"; (works)

(when go deeper, fail to retrieve any value...)

echo "created: " .  $aNative->results->contact[0]->created . "
";

foreach($aNative->$query->results as $contact)
{
    echo $contact->id;
    echo $contact->fields[0]->type;

    if($contact->fields[0]->type=="email")
    {
        echo $contact->fields[0]->value;
    }

}

full json:
{
   "query":{
      "count":10,
      "created":"2012-06-13T09:13:45Z",
      "lang":"en-US",
      "results":{

         "contact":[

            {
               "created":"2006-10-29T04:32:07Z",
               "updated":"2006-10-29T04:32:07Z",
               "uri":"http://social.yahooapis.com/v1/user/BNQJOMYDQYLY2FZSMROV4QDA6MI/contact/14",
               "isConnection":"false",
               "id":"14",
               "fields":{
                  "created":"2006-10-29T04:32:07Z",
                  "updated":"2006-10-29T04:32:07Z",
                  "uri":"http://social.yahooapis.com/v1/user/BNQJOMYDQYLY2FZSMROV4QDA6MI/contact/14/email/11",
                  "id":"11",
                  "type":"email",
                  "value":"angBB@gmail.com",
                  "editedBy":"OWNER"
               }
            },

            {
               "created":"2006-10-29T04:32:07Z",
               "updated":"2006-10-29T04:32:07Z",
               "uri":"http://social.yahooapis.com/v1/user/MNQJOMYDQYLY2FZSMROV4QDA6MI/contact/12",
               "isConnection":"false",
               "id":"12",
               "fields":[
                  {
                     "created":"2006-10-29T04:32:07Z",
                     "updated":"2006-10-29T04:32:07Z",
                     "uri":"http://social.yahooapis.com/v1/user/MNQJOMYDQYLY2FZSMROV4QDA6MI/contact/12/email/6",
                     "id":"6",
                     "type":"email",
                     "value":"jaq@lifemastr.com",
                     "editedBy":"OWNER"
                  },
                  {
                     "created":"2006-10-29T04:32:07Z",
                     "updated":"2006-10-29T04:32:07Z",
                     "uri":"http://social.yahooapis.com/v1/user/MNQJOMYDQYLY2FZSMROV4QDA6MI/contact/12/name/5",
                     "id":"5",
                     "type":"name",
                     "value":{
                        "givenName":"'Jaq'",
                        "middleName":null,
                        "familyName":null,
                        "prefix":null,
                        "suffix":null,
                        "givenNameSound":null,
                        "familyNameSound":null
                     },
                     "editedBy":"OWNER"
                  }
               ]
            }

         ]
      }
   }
}

A: You have forgotten about query. You have to access to results for example in this way:
$aNative->query->results->contact[0]->created

And review whole your code you are trying to access to wrong properties many times. For example in foreach you shall use $aNative->query->results->contact instead of $aNative->results because results it is an object and not array.


text:
Q: IP Redirect using DNS Server For my current project I have an ADDS set up. The ADDS also has a DNS Server installed as a role. The name of my ADDS is corp.nikali.lan. I have to use the DNS Server role to redirect.
The IP address of outlook.com should be reachable by typing email.corp.nikali.lan.
At the moment all I have is the basic set-up after downloading the DNS feature. No added records or anything else.

A: CNAME record - records refer to an alias or redirect for a specific site or subdomain.
Two CNAME fields:

*

*Name

*Destination

Common CNAME entries:
Name: www
Destination: @
(or "yourwebsite.com")
Best example :
www.facebook.com and fb.com , some people are using a shortcut word like fb.com , you need to configure in your (NS) Name server , like the example above CNAME entries.


text:
Q: Node.js Mongodb - Kerberos module not found Im trying to npm install mongodb.
It works and tells me that modules are installed, kerberos is in this list.
But when im trying to run my app i keep getting this:
Error: Cannot find module '../build/Release/kerberos' from '/Users/snorre edwin/Code/raspberry-node-         server/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib'
Error: Cannot find module '../../../build/Release/kerberos' from '/Users/snorre edwin/Code/raspberry-node-server/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers'
Error: Cannot find module '../../../build/Release/kerberos' from '/Users/snorre edwin/Code/raspberry-node-server/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers'
Error: Cannot find module '../../../build/Release/kerberos' from '/Users/snorre edwin/Code/raspberry-node-server/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers'
Error: Cannot find module '../../../build/Release/kerberos' from '/Users/snorre edwin/Code/raspberry-node-server/node_modules/mongodb/node_modules/mongodb-core/node_modules/kerberos/lib/win32/wrappers'

It doesnt make sense, since this is a module which comes with the mongodb package.
Anyone else experienced this?

A: A quick Google found this discussion thread: https://nodejstools.codeplex.com/workitem/532. Although it is in context of Microsoft VS.
Different, possible solutions include:

*

*Instal mongoose (not mongo) globally using npm install mongoose -g.

So I fixed this issue by installing mongoose globally via NPM, then I copied the build folder in the mongoose/node_modules/mongodb/kerberos to my local mongoose folder in my VS project.

*If you're using mongoose, the thread additionally suggests you'll need python installed.

*Add kerberos to the package.json file itself. Also try to install globally.

*Ignore it:


text:
Q: How to convert result of mcapply to dataframe? Rbind gives errors Running do.call(rbind, result) to the resulting list from running 'mcapply' gives an error. This happens when running the markdown file automatically using make.
I do not get the same error when I am running the code block by block in the R console.
library(parallel)
filenames <- list.files(full.names=TRUE)

ALL <- mclapply(filenames, function(i){read.csv(i, header=FALSE)}, mc.cores=4)

combined <- do.call("rbind", ALL)
colnames(combined) <- c("Trip.Distance","Trip.Duration")

Hope somebody can help me, thanks!

A: Thank you @Vitali Avagyan, I realised that my makefile and Rmd file are also on the same directory as the .csv files, hence the error.
I created a new directory containing only the .csv files and it solved the issue.


text:
Q: Como crear un ciclo de widgets en PySide6 estoy creando un proyecto en pyside sobre punto de venta y quiero crear grupo de widgets en donde puedan estar vinculados con las compras que realice el cliente la interfaz gráfica crea de manera que el vendedor cada vez que introduzca un producto nuevo al inventario se cree un grupo de widgets label con los detalles del producto una imagen y un QPushButton, pero no tengo ni idea de como empezarlo alguien me puede ayudar???.

A: def CrearProduc(self):
    contadorY=0
    contadorX=0
    self.ListaDeWidgets=[None,]
    for i in range(1,13):#rango de productos que pueden entrar
        self.ListaDeWidgets.insert(i,QWidget(self.PrinWin.pageCliente))
        self.ListaDeWidgets[i].setGeometry(QRect((315*contadorX)+40,contadorY+25,300,200))
        if (i % 4)==0:
            contadorY += 215
            contadorX = 0
        else:
            contadorX += 1
            pass
        print(contadorY)
        self.ListaDeWidgets[i].setStyleSheet(u"background-color:rgb(0,0,0);")
    pass
    print(self.ListaDeWidgets)

Este es mi ejemplo de como solucione mi problema si algo de mi codigo puedo mejorar por favor háganme lo saber.


text:
Q: sudo: unable to change directory to /root: No such file or directory I have a problem, because I installed nvm and then I tried to uninstall but I made some mess...
When I run "sudo -i" I get this:

sudo: unable to change directory to /root: No such file or directory
sudo: unable to execute /bin/bash: No such file or directory

Someone could help me? Thank you!!


text:
Q: Logstash in reading files/ documents I would like to know if there are any ways that a logstash configuration file can read through different documents, i.e. docx, pdf, excels, and store them into elasticsearch.
Great thanks in advance.

A: Logstash cannot read .docx, .xls or .pdf files, because these sort of files are not text files, they are binary globs, only appearing to be simple after being interpreted by an application designed to parse them.
Logstash is designed to handle files that are plain-text, a good test to determine if a file could be easily read by Logstash is if you could open up the file in a text editor such as sublime, notepad or atom and read the contents, then so could Logstash.
Try opening a .docx file in notepad, that should make this clear.


text:
Q: NSString Converting @ to %40 on Request Currently I'm using Resty (http://projects.lukeredpath.co.uk/resty/) to build my own API wrapper for Objective-C.
I digress however, in the request itself, I am able to determine what is actually being sent and it seems that the NSString *email (I scan for an @ to make sure it is a legitimate email before storing in another NSString) is actually changed.
An example, joe@example.com has been scanned for the @, and then sent to the NSString *email for the request. However, when I send the actual GET request, the NSString is changed to joe%40example.com.
Is this due to the Resty request, or do I have to encode/decode the NSString before the request?

A: Yes, you should URL decode and then perform any validation tasks.
Here is what their documentation has:

NSData or any other data-encodable
  payloads set the request body as-is;
  encodable payloads will be encoded
  using UTF8

http://projects.lukeredpath.co.uk/resty/documentation.html


text:
Q: sentiment analysis in python I am extracting reviews from various website and storing them in a file and then classifying each sentence as positive or negative with the help of senti-wordnet ( which gives certain scores).I am using python 2.7. I don't know how it works for reviews stored in a file. Do anybody know the code in python for this ?
f1=open("foodP.txt","r")
word_features =[]
words = []

for line in f1:
    word_features.append(line)
    s=str(word_features)
    tokens=nltk.word_tokenize(s)

for i,j in nltk.pos_tag(tokens):
    if j in ['VBN','VBP','VB','JJ', 'JJR', 'JJS', 'RB', 'RBR', 'RBS']:
        words.append(i)
print words

this code will give only adjective , adverbs and verbs i need. i want to classify these words as either positive or negative .

A: You don't need POS for sentiment analysis, at least it's not required. Prepare feature by using bag_of_words in X and "neg"/"pos" as Y. Then split into train/test sets and apply classification algorithm - NaiveBayes, MaxEnt, RandomForest, SVM.


text:
Q: Apache HTTP Components gzip request I'm trying to send a gzipped multipart entity from a simple java application (code to be used later in Android) to a service built by RESTEasy. I've tried a few things, but basically it comes down to this:
GZip POST request with HTTPClient in Java
I always get an exception saying the content is not in GZIP format. I tried removing the gzip content-encoding header and ungzipping the content myself (not leaving it to RESTEasy), and I get the same exception.
The content I am sending is in JSON format. I am using multipart entities because there is a lot of it, and the multipart entities are being buffered to disk while uploaded.
I can use anything else. Is there any proven way for this to work with Jetty Client for example?
Edit:
Stacktrace

org.jboss.resteasy.spi.ReaderException: java.util.zip.ZipException: Not in GZIP format
      at org.jboss.resteasy.core.MessageBodyParameterInjector.inject(MessageBodyParameterInjector.java:183)
      at org.jboss.resteasy.core.MethodInjectorImpl.injectArguments(MethodInjectorImpl.java:88)
      at org.jboss.resteasy.core.MethodInjectorImpl.invoke(MethodInjectorImpl.java:111)
      at org.jboss.resteasy.core.ResourceMethodInvoker.invokeOnTarget(ResourceMethodInvoker.java:280)
      at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:234)
      at org.jboss.resteasy.core.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:221)
      at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:356)
      at org.jboss.resteasy.core.SynchronousDispatcher.invoke(SynchronousDispatcher.java:179)
      at org.jboss.resteasy.plugins.server.servlet.ServletContainerDispatcher.service(ServletContainerDispatcher.java:220)
      at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:56)
      at org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher.service(HttpServletDispatcher.java:51)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
      at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
      at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:936)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
      at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1004)
      at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
      at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
      at java.lang.Thread.run(Thread.java:724)


text:
Q: Custom date range for report of upcoming changes Relatively new to javascript, most self learning done through trial and error and internet searches.  Have an issue with code where I could use some expert guidance.
I need to show all changes with a planned start date occurring within our change week, which begins Friday at 00:00:01 and ends the following Thursday at 23:59:59.  The report would show all changes with a planned start date within that time period.
I was able to find the following script includes, modified slightly for my specific requirements.  When the script is called in reporting, I do not receive any results even though there is data that meets my criteria.
I believe my issue is with the array or loop, but am unable to resolve.
I have included only a portion of the script where I believe the issue resides, but can provide full code if helpful.
//Partial Code
    var ChangesPlannedCustom = Class.create();
    ChangesPlannedCustom.prototype = {
    initialize: function() {
    },

    testChangeWeek:function(){
    //Gets all current dates within current week and push into 'result'
    var current = new Date();
    var gdt1 = new GlideDateTime(current);
    var dateToday = gdt1.getLocalDate();
    var sunday = new Date(current.setDate(current.getDate() - current.getDay()));
    var b = gdt1.getLocalDate();
    var result = [b];

    while (sunday.setDate(sunday.getDate() + 1) && sunday.getDay() !== 0) {

    var curr = new Date(sunday);
    var gdt = new GlideDateTime(curr);
    var c = gdt.getLocalDate();
    result.push(c);
}
    //Assigns dates with numbers.  Days contain respective dates.
    //SundayN = 0, MondayN = 1, TuesdayN = 2, WednesdayN = 3, ThursdayN = 4, FridayN = 5, SaturdayN = 6
var sunday1, monday, tuesday, wednesday, thursday, friday, saturday; //sunday1 because sunday is already used above
var sundayN, mondayN, tuesdayN, wednesdayN, thursdayN, fridayN, saturdayN;
var today = dateToday;

var i = [];
for (i = 0; i < result.length; i++) {
    switch (i) {
        case 0:
            sunday1 = result[i];
            sundayN = i;
            break;

        case 1:
            monday = result[i];
            mondayN = i;
            break;

        case 2:
            tuesday = result[i];
            tuesday = i;
            break;

        case 3:
            wednesday = result[i];
            wednesday = i;
            break;

        case 4:
            thursday = result[i];
            thursday = i;
            break;

        case 5:
            friday = result[i];
            friday = i;
            break;

        case 6:
            saturday = result[i];
            saturday = i;
            break;
        default: statement(s);
            break;
            }
}
var todayN = '';
    var q;
for (q = 0; q < result.length; q++) {
    if (result[q].toString() == today.toString()) {
        todayN = q;

    }
}

//code continues - not shown
I expect to receive a list of change numbers that have a planned start date within my specific date range.  Currently, when executing the code in reporting, I receive no results.
Appreciate any assistance provided.


text:
Q: Are empty interfaces code smell? I have a function that returns same kind of objects (query results) but with no properties or methods in common. In order to have a common type I resorted using an empty interface as a return type and "implemented" that on both.
That doesn't sound right of course. I can only console myself by clinging to hope that someday those classes will have something in common and I will move that common logic to my empty interface. Yet I'm not satisfied and thinking about whether I should have two different methods and conditionally call next. Would that be a better approach?
I've been also told that .NET Framework uses empty interfaces for tagging purposes.
My question is: is an empty interface a strong sign of a design problem or is it widely used?
EDIT: For those interested, I later found out that discriminated unions in functional languages are the perfect solution for what I was trying to achieve. C# doesn't seem friendly to that concept yet.
EDIT: I wrote a longer piece about this issue, explaining the issue and the solution in detail.

A: You state that your function "returns entirely different objects based on certain cases" - but just how different are they? Could one be a stream writer, another a UI class, another a data object? No ... I doubt it!
Your objects might not have any common methods or properties, however, they are probably alike in their role or usage. In that case, a marker interface seems entirely appropriate.

A: If not used as a marker interface, I would say that yes, this is a code smell.
An interface defines a contract that the implementer adheres to - if you have empty interfaces that you don't use reflection over (as one does with marker interfaces), then you might as well use Object as the (already existing) base type.

A: You answered your own question... "I have a function that returns entirely different objects based on certain cases."... Why would you want to have the same function that returns completely different objects? I can't see a reason for this to be useful, maybe you have a good one, in which case, please share.
EDIT: Considering your clarification, you should indeed use a marker interface. "completely different" is quite different than "are the same kind". If they were completely different (not just that they don't have shared members), that would be a code smell.

A: Although it seems there exists a design pattern (a lot have mentioned "marker interface" now) for that use case, i believe that the usage of such a practice is an indication of a code smell (most of the time at least).
As @V4Vendetta posted, there is a static analysis rule that targets this:
http://msdn.microsoft.com/en-us/library/ms182128(v=VS.100).aspx

If your design includes empty interfaces that types are expected to implement, you are probably using an interface as a marker or a way to identify a group of types. If this identification will occur at run time, the correct way to accomplish this is to use a custom attribute. Use the presence or absence of the attribute, or the properties of the attribute, to identify the target types. If the identification must occur at compile time, then it is acceptable to use an empty interface.

This is the quoted MSDN recommendation:

Remove the interface or add members to it. If the empty interface is being used to label a set of types, replace the interface with a custom attribute.

This also reflects the Critique section of the already posted wikipedia link.

A major problem with marker interfaces is that an interface defines a contract for implementing classes, and that contract is inherited by all subclasses. This means that you cannot "unimplement" a marker. In the example given, if you create a subclass that you do not want to serialize (perhaps because it depends on transient state), you must resort to explicitly throwing NotSerializableException (per ObjectOutputStream docs).

A: As many have probably already said, an empty interface does have valid use as a "marker interface".
Probably the best use I can think of is to denote an object as belonging to a particular subset of the domain, handled by a corresponding Repository. Say you have different databases from which you retrieve data, and you have a Repository implementation for each. A particular Repository can only handle one subset, and should not be given an instance of an object from any other subset. Your domain model might look like this:
//Every object in the domain has an identity-sourced Id field
public interface IDomainObject
{
   long Id{get;}
}

//No additional useful information other than this is an object from the user security DB
public interface ISecurityDomainObject:IDomainObject {}

//No additional useful information other than this is an object from the Northwind DB
public interface INorthwindDomainObject:IDomainObject {}

//No additional useful information other than this is an object from the Southwind DB
public interface ISouthwindDomainObject:IDomainObject {}

Your repositories can then be made generic to ISecurityDomainObject, INorthwindDomainObject, and ISouthwindDomainObject, and you then have a compile-time check that your code isn't trying to pass a Security object to the Northwind DB (or any other permutation). In situations like this, the interface provides valuable information regarding the nature of the class even if it does not provide any implementation contract.


text:
Q: Add UILabels programmatically to a Collection Cell, swift I am trying to add UILabels in the subView of my Collection Cell.
But when I scroll to the other cell and come back all the UIlabels appear on both cells and some are written under the other..
I tried with collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell , but when I used it none UIlabel was displayed ( I tried with breaking points, it doesn't go after the if statement)
How can I fix it??
Thanks!!!
  class CollectionView: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

        var collection = [PFObject]()

        @IBOutlet weak var collectionView: UICollectionView!

        let sidePadding:CGFloat = 10

        var checkLocation: Bool = false

        override func viewDidLoad()
        {
            super.viewDidLoad();
            self.collectionView!.delegate = self
            self.collectionView!.dataSource = self

        }

        func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
            return 1
        }

        func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return self.collection.count
        }

        func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

            let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! CollectionViewCell

            cell.layer.borderColor = UIColor.lightGrayColor().CGColor
            cell.layer.borderWidth = 0.5
            cell.layer.cornerRadius = 3

            let collectionViewWidth = self.collectionView.bounds.size.width - self.sidePadding * 2
            cell.frame.size.width = collectionViewWidth
            let collectionViewHeight = self.collectionView.bounds.size.height/4.5
            cell.frame.size.height = collectionViewHeight

            // Display the country name
            if let value = self.collection[indexPath.row]["Name"] as? String {
                cell.cellTitle.text = String(Int(indexPath.row)) + "." + value

            }

            let width = (cell.bounds.width - 94 - 4*3 - 60 - 20)/4
            let cellheight = CGFloat(6)
            let cellheight1 = CGFloat(6 + 12 + 2)

            var array = [String]()

            if let MWl = collection[indexPath.row]["MW"] as? Int
            {
                if MWl == 1 {

                    array.append("M")

                } else if MWl == 2 {

                    array.append("M")
                    array.append("W")

                }

            }

            if let JAl = collection[indexPath.row]["JA"] as? Int
            {
                if JAl == 1 {

                    array.append("Jy")

                } else if JAl == 2 {

                    array.append("Jy")
                    array.append("Ac")

                }

            }

            if let HK = collection[indexPath.row]["HK"] as? Int
            {
                if HK == 1 {

                    array.append("HB")

                } else if HK == 2 {

                    array.append("HB")
                    array.append("Ks")

                }
            }

            if let SSl = collection[indexPath.row]["SSl"] as? Int
            {
                if SSl == 1 {

                    array.append("AB")

                } else if SSl == 2 {

                    array.append("AB")
                    array.append("CD")

            }

            //I tried here too
            //  if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell

            if array.count <= 4 {
                for i in 0..<array.count {

                    let taille = CGFloat(i)
                    var si = CGFloat((1+i)*3 + 94 + 30)
                    let label = UILabel() as UILabel
                    label.frame = CGRectMake((si + width*taille), cellheight, width, 12)
                    label.textColor = UIColor(red: 0/255, green: 125/255, blue: 255/255, alpha: 1.0)
                    label.backgroundColor = UIColor.clearColor()
                    label.layer.borderWidth = 0.7
                    label.layer.borderColor = UIColor.lightGrayColor().CGColor
                    label.font = UIFont(name: "Futura-Medium", size: 9)
                    label.textAlignment = NSTextAlignment.Center
                    label.numberOfLines = 1
                    label.text = array[i]
                    label.layer.masksToBounds = true
                    label.layer.cornerRadius = 3.5
                    if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
                        myCell.contentView.addSubview(label)
                    }
                }

            } else {

                for i in 0...3 {

                    let taille = CGFloat(i)
                    var si = CGFloat((1+i)*3 + 94 + 30)
                    let label = UILabel() as UILabel
                    label.frame = CGRectMake((si + width*taille), cellheight, width, 12)
                    label.textColor = UIColor(red: 0/255, green: 125/255, blue: 255/255, alpha: 1.0)
                    label.backgroundColor = UIColor.clearColor()
                    label.layer.borderWidth = 0.7
                    label.layer.borderColor = UIColor.lightGrayColor().CGColor
                    label.font = UIFont(name: "Futura-Medium", size: 9)
                    label.textAlignment = NSTextAlignment.Center
                    label.numberOfLines = 1
                    label.text = array[i]
                    label.layer.masksToBounds = true
                    label.layer.cornerRadius = 3.5
                    if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
                        myCell.contentView.addSubview(label)
                    }
                }

                var j = 0 as Int
                for i in 4..<array.count {

                    let taille = CGFloat(j)
                    let si = CGFloat((1+j)*3 + 94 + 30)
                    let label = UILabel() as UILabel
                    label.frame = CGRectMake((si + width*taille), cellheight1, width, 12)
                    label.textColor = UIColor(red: 0/255, green: 125/255, blue: 255/255, alpha: 1.0)
                    label.backgroundColor = UIColor.clearColor()
                    label.layer.borderWidth = 0.7
                    label.layer.borderColor = UIColor.lightGrayColor().CGColor
                    label.font = UIFont(name: "Futura-Medium", size: 9)
                    label.textAlignment = NSTextAlignment.Center
                    label.numberOfLines = 1
                    label.text = array[i]
                    label.layer.masksToBounds = true
                    label.layer.cornerRadius = 3.5
                    if let myCell = collectionView.cellForItemAtIndexPath(indexPath) as? CollectionViewCell {
                        myCell.contentView.addSubview(label)
                    }
                    j = j + 1
                }

            }

            return cell
        }

    }

EDIT
I tried to create the UILabel programmatically. But in that way I used the elements designed with the StoryBoard and the elements created programmatically. And actually I can't because of this :
     collectionView!.registerClass(RDCell.self, forCellWithReuseIdentifier: "Cell")

I create all the content of the cell programmatically ( the collectionView is created with the storyboard) and it works perfectly.

A: The cell is being reused, therefore you are always adding new labels each time cellForItemAtIndexPath is called. Just tag your labels like label.tag = 1 and when you dequeue the cell remove every subview with this tag, like
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! CollectionViewCell
for view in cell.subviews {
   if view.tag == 1 {
      view.removeFromSuperview()
   }
}

You will be always recreating the labels though, which is bad design. I suggest designing those labels on storyboard or if you insist on doing it in code keep optional references to the label in the cell to not recreate them each time cellForItemAtIndexPath is called.

A: not recommended but you can do is,
Add tag to each label like 1000 or something and find sub views of cell if any of subview tag matches with label tag remove that view
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell
{
     let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionCell", forIndexPath: indexPath) as! CollectionViewCell

     for let labelIs in cell.subviews
        {
            if labelIs.tag == 1000
            {
                labelIs.removeFromSuperview()
            }
        }
      //some whare
      var label = UILabel()
      label.tag = 1000
      return cell
}


text:
Q: How do I find the projection matrix that is equivalent to an orthographic matrix but gives perspective when not in xy-plane? I am messing around in a program that performs all rendering using a matrix set by gluOrtho2D(). What I would like to do is to rotate a specific texture around the y-axis (0,1,0) so that it looks like the original matrix was provided by gluPerspective() instead. I realize that this is not possible with an orthographic projection matrix and that I will have to set up a new perspective projection matrix. I want the textures I draw to look exactly the same as when drawn with the orthographic matrix, except sometimes when I have rotated them around the y-axis.
So to summarize:
How do I find a perspective projection matrix that is equivalent to a given orthographic matrix when shapes are drawn in the xy-plane, but gives me perspective when not in the xy-plane?

A: Basically what I understand is: You want to have a perspective matrix that yields the same image as the orthographic projection, when the object lies in the XY-Plane.
So lets begin:
You want to draw your plane in the XY-plane and you had gluOrtho2D(-w, w, -h, h); (asymmetric orthographic projection is a bit harder, if you need it, then say so).
What you need to do now is:
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(2 * atan(h / 2)  * 180.0 / PI, w / h, 1, 3);

glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0, 0, -2);

What I have done here is matching the center of the projective view frustum on the section of the XY-plane that was visible in the orthographic projection.
Take the graphs of the projection frustums and some math and you can do this yourself :)

Just as a reminder I will leave my answer to the old question here.
Either you have ortho or perspective projection. You have to decide for one.
You will not gain perspective by rotating on any axis.
Why would you have to change a whole program just to change the projection mode?
One possible solution:
I assume the old GL with different matrix modes and so on:
glMatrixMode(GL_PROJECTION); //switch to projection matrix mode
glPushMatrix(); //push the old matrix
glLoadIdentity();
//apply the perspective projection
//do your rendering
glPopMatrix(); //pop the old matrix

With the newer GL scheme you will have to do most of this on your own but it should be easy though.

A:
Is this possible in some easy way without having to convert all of the program to using gluPerspective()?

I'm already getting tired of telling this, but:
The projection is not something defined one time and then enforced on the whole rendering process. You can switchi it anytime you like, and for any anvanced rendering scheme will do this multiple times throughout a single frame.
I think most newbies are confused by this:
reshape(width, height):
    glViewport(0,0,width,height)
    glMatrixMode(GL_PROJECTION)
    glLoadIdentity()
    projection_setup()

They see the projection done in the reshape function and think it's the only place to do it.
Please speak with me:
The projection matrix is just some state used for drawing as anything else. It can be changed as easily as the current color or texture.
Just set the projection you need for a certain sequence of drawing commands as you need it, right before you do the drawing.

A: It is possible to have perspective effect, i.e. rotate around x or y axis, even though your projection matrix is orthographic, the trick is to multiple your view matrix by this magic matrix before/after any other view transformation:
// The matrix is
// -z,  0,  x,  0
//  0, -z,  y,  0
//  0,  0,  1,  0
//  0,  0,  1, -z

where :

*

*x is half viewport width,

*y is half viewport height,

*z might be any negative number except -0.

Several notes:

*

*if u r calling glRotate*, this matrix goes first as these built-in calls are right hand multiplication. if u r tracking ur own view matrix using left hand multiplication as suggested on text-books, this matrix goes last. In either way, this matrix will actually be multiplied by your orthographic project matrix, so u can pre-calculate as well

*z is actually the simulated z depths, so bigger it is in magnitude, further the objects are, as a consequence, rotation looks more like orthographic. Z cannot be positive because this will make w in NDC negative, OpenGL does not allow that, it will get clipped so nothing will draw

*In the end, there is no magic, this matrix is just a compensate, after u do:
M(ortho) X M(magic), u get a perspective matrix

*This trick is crucial if 99% of your code is for orthographic but only one place or two need perspective effect, then u don't need to switch between two modes, if u r using fixed-pipeline, GL_PROJECTION_MATRIX will be left unchanged

*this matrix is taken from Android Open Source Project so hopefully this will give u much confidence


text:
Q: Creating legend for data-defined colors in table using QGIS I am using QGIS 3.10.6.
I have imported satellite imagery and geological maps from government servers. The polygon tables have a column with a code for colors. Such that I can color code my map with the exact same colors using the embedded color code. I do it through assigning a string to the simple fill for the polygon in the "single symbol" category. Since I am using a single symbol, it seems that I cannot create a legend for all the different units (color codes).
Is there a way to create a legend for polygon tables with data-defined colors using the "single symbol" symbology?


text:
Q: AttributeError: 'float' object has no attribute 'GCPPixel' I'm new in coding and trying to translate SEVIRI native images to tif format using gdal library and qgis python console.
The problem is when I want to add GCPs I get an error and I don't know how to solve this problem I know I add GCP in the wrong way but I don't know what is the proper method!
I searched alot but didn't find anything about adding GCPs in qgis python console while using gdaltranslate. Any suggestions will help.
Here is my code in qgis python console :
import gdal
src='E:/data/MSG1-SEVI-MSG15-0100-NA-20190331061240.466000000Z-20190331061258-1408742.nat'

dst='E:/data/trans.tif'

ds=gdal.Open(src)

gdal.Translate(dst,ds,format='GTiff',outputType=gdal.GDT_UInt16,GCPs=(3227050.38610344,1303713.87878049,50.2665350843959,29.244462081302))

error is

Traceback (most recent call last):
  File "C:\PROGRA~1\QGIS3~1.14\apps\Python37\lib\code.py", line 90, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "<string>", line 6, in <module>
  File "C:\PROGRA~1\QGIS3~1.14\apps\Python37\lib\site-packages\osgeo\gdal.py", line 422, in Translate
    (opts, callback, callback_data) = TranslateOptions(**kwargs)
  File "C:\PROGRA~1\QGIS3~1.14\apps\Python37\lib\site-packages\osgeo\gdal.py", line 376, in TranslateOptions
    new_options += ['-gcp', _strHighPrec(gcp.GCPPixel), _strHighPrec(gcp.GCPLine), _strHighPrec(gcp.GCPX), str(gcp.GCPY), _strHighPrec(gcp.GCPZ)]
AttributeError: 'float' object has no attribute 'GCPPixel'

A: Your problem is what you're passing as the GCPs parameter to the gDal.Translate function. You're passing a list (tuple) of floating point values, when what that parameter expects is a list of gdal.GCP() objects.
Because the library thinks it has gdal.GCP() objects, it is trying to call the GCPPixel method on one of them, which would work if that's what it was.  But it's a float, and of course, floating point numbers don't have a GCPPixel method, hence the error you're getting.


text:
Q: filling combobox from database using remote object i'm just new in flex and want fill my combobox from database, this is the code, i think all is right but it doesn't work !!!
can you help be to find what i miss !!
so first this is the code of my class, it selects a column (Intitule Chapitre) from database
public class RapportDao {

    public Connection conectar(){
        Connection cn = null;
        String connectionUrl = "jdbc:sqlserver://localhost\\SQLEXPRESS;databaseName=mabase;user=sa;password=sa;";

        try
        {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
            cn = DriverManager.getConnection(connectionUrl);

        }
        catch(Exception ex)
        {
            System.out.println("Error : " + ex.getMessage());
        }
        return cn;
    }
public ArrayList<Rapport> Selection() {

             Connection conn = conectar();
             ArrayList<Rapport> list = null;

             if (conn!=null){

                 try{
                     Rapport pr = null;
                     String a;
                     list = new ArrayList<Rapport>();
                     String sql = "select IntituleChap from Rapport";
                     Statement st = conn.createStatement();
                     ResultSet rs=st.executeQuery(sql);
                     while (rs.next())
                     {
                         a=rs.getString("IntituleChap");
                         pr  = new Rapport();
                         pr.setIntituleChap(a);
                         list.add(pr);
                     }

             }
                 catch(SQLException e ) {

                     // System.out.print(e.getMessage());
                     System.out.println("Error = " + e.getMessage());
                    }

             }else
             {

             }
             return list;
    }
}

and this is my actionscript code for combobox
  <fx:Script>
            <![CDATA[

    import spark.components.ComboBox;
    private function getTypeprojetResult(event : ResultEvent):void
                {
                    //Alert.show(""+event.result);
                }
    ]]>

    <fx:Declarations>
            <s:RemoteObject id="RemoteRapportDao"
                            destination="RapportDaoDest"
                            fault="onFault(event)">
                <s:method name="Selection" result="getTypeprojetResult(event);"/>
            </s:RemoteObject>
        </fx:Declarations>

<s:ComboBox id="cmbchap" x="130" y="223" width="172" height="19" dataProvider="{RemoteRapportDao.Selection.lastResult}"/>

*

*RemoteRapportDao : is the id RemoteObject

*Selection() : my method on the service

i don't get any things on the combobox !!!
thank you !

A: your code is correct but the thing you missing is calling the function from your service in before fill it.
to do that you need a listener in application complete handler
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
           xmlns:s="library://ns.adobe.com/flex/spark"
           xmlns:mx="library://ns.adobe.com/flex/mx"
           xmlns:esri="http://www.esri.com/2008/ags"
           minWidth="1000" minHeight="700" applicationComplete="application1_applicationCompleteHandler(event)">

this methode is called when your application is completely started.
this how you do that.
protected function application1_applicationCompleteHandler(event:FlexEvent):void
{
    RemoteRapportDao.Selection()
}