scala mailbox size limit

Question: Can I set maximum size for an actor's mailbox in Scala?
Take the Producer-Consumer problem. With threads I can block the producers when the buffer fills up. I saw a couple of producer-consumer examples written in Scala and they all use actors with mailboxes used as a "buffer". Can I set mailbox size to cause producers to wait until a consumer is ready? Any other elegant solution to avoid uncontrollable growth of mailboxes?
Answer: You can create an actor that acts as a buffer between the producer and consumer. The buffer checks out its mailbox to its loop data. It sends back an "overload" message to the producer when the number of buffered products is too high; and sends a "clear" message once everything is back in order. In case of too many messages it simply drops incoming ones (or oldest ones).
The consumer actively requests for products from the buffer, which in turn sends back one product. If the buffer is empty, the consumer keeps waiting for the input.
The producer sends products to the buffer actor. If it receives an "overload" message it can stop production, or it can continue producing, knowing the fact that the products might get dropped.
Of course this logic could directly be implemented into the producer or consumer itself, but a separate buffer will allow you to introduce multiple producers and/or consumers more easily.
Answer: The Actor.mailboxSize method returns the number of pending messages in the Actor's mailbox.
This can be used for throttling the producer in various ways.
For example, one possibility could be,
The producer checks if the consumer's mailboxSize is greater than some threshold. If it is, then it sends a SpecialMessage to the consumer, and blocks on a semaphore. When the consumer receives this SpecialMessage it releases the semaphore. The producer can now merrily continue it's business.
This avoids polling as well as any dropped messages.
Comment: Polling seems more appropriate to me than making the consumer's mailbox a "shared state" between two actors.
Comment: Polling is often better from a purely programming perspective, but semaphores are often better from a hardware utilization perspective.  Depends on your exact situation as to which should be selected.
Comment: @Zed The consumer's mailbox IS shared state! Otherwise the producer wouldn't be able to send any messages to it :)

scala mailbox size limit


Lambda Search VS Linear Search

Question: When I was debugging a lambda-based search, I noticed that it simply went through the list linearly, so it made we wonder if there was any advantage to doing a lambda search on a list in C# versus coding your own type-checking linear search on the same list.
Comment: What is lambda search?
Comment: Please add the code you're talking about. Lambdas don't affect the complexity of the search method you're using.
Comment: I don't have code. This is more of a conceptual question.
Answer: Lambda  method performs a linear search; therefore, the method is an O(n) operation, where n is Count.
For more detailed on Lambda read these link
Lambda Search

Lambda Search VS Linear Search


Issue with a position relative on Chrome and Android native browser

Question:
First post here, after a long time using your advices !
So, here is my problem : I try to center an element horizontally. I've defined 'top:50%' in CSS and ask jQuery to find 'margin-top:-XXpx'.
It works on load, but when I refresh the page with Chrome or Android native browser, the element moves below.
This doesn't happen with Firefox (i haven't tried with other browsers).

you can see it here : http://www.porteguillau.me/2/

Does someone have any idea ?
Comment: Relative code would immensely help. I doubt you need jquery to solve this issue as well.
Answer: You should probably use absolute positioning in stead of relative.
Also, Are you trying to centre the div vertically? If you know the height (which you should if the icons are fixed sizes), set the top margin to negative half the height of the div (In your example -150px or so).
Comment: BTW you can do all of what I just said with just CSS. As a general rule, avoid using jquery for layout unless you have to.
Comment: Thanks, it's safer like this, but i'd like my icons to have a size  equal to x% of the body. The parent element of the icons is set here to center them horizontally. But i suppose that it is not possible to define the size of an element based on his "grand"-parent (body->element->icons)


HTML Select Always have Blue Background Regardless of Focus

Question: I am using this example of HTML select multiple Attribute: https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_select_multiple. The code is below:
<!DOCTYPE html>

The select multiple attribute

The multiple attribute specifies that multiple options can be selected at once:

<form action="/action_page.php">
  Choose a car:
  <select name="cars" id="cars" multiple>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
  </select>

  <input type="submit" value="Submit">
</form>

Hold down the Ctrl (windows) or Command (Mac) button to select multiple options.

When I select the Volvo option, it has a blue background:

When I click somewhere else on the screen (to remove the focus), the background for Volvo becomes grey:

My question: How do I make the background on my selection (in this case, Volvo) always blue, regardless of focus?
Answer: As far as I know, the color and background-color cannot be changed with the  :checked pseudo-element, but it can be mimic with the help of a linear-gradient.

option:checked {
  background: linear-gradient(lightblue, lightblue);
}
<form action="/action_page.php">
  Choose a car:
  <select name="cars" id="cars" multiple>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
  </select>

  <input type="submit" value="Submit">
</form>
Answer: Best you can do is use a linear gradient.

select option:checked{
  background: #1E90FF -webkit-linear-gradient(bottom, #1E90FF 0%, #1E90FF 100%);
}

Choose a car:
  <select name="cars" id="cars" multiple>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="opel">Opel</option>
    <option value="audi">Audi</option>
  </select>


Installing Shorewall on Debian stable

Question: I'm going to install Shorewall on a Debian stable Linux box. The shorewall version in the stable repositories is 220.127.116.11-2.
Shorewall website suggests to pin apt preferences and force the download of the new Shorewall version from testing repos.
Package: shorewall
Pin: release o=Debian,a=testing
Pin-Priority: 700

Have you ever done something like that and do you think it is safe?
Answer: Yes, it's a common way if one is running Debian stable, but needs a more recent version of a specific software. The backports mechanism is the way to go, but there are no backports provided for shorewall. So, go ahead and guck luck; I'm quite sure it will work flawlessly.

Installing Shorewall on Debian stable


Access is Denied for PowerShell access site via URL in localhost

Question: What IP I need o put in the IP Address and Domain Restriction in order to allow Windows PowerShell to be able to run Invoke-WebRequest to a URL for a site that is hosted on the same machine.
I am doing it for testing scheduled tasks. As for now, my IIS is configured to allow access only to my IP. I tried adding 127.0.0.1, the local machine IPv4 address and the Default Gateway, but I still get Forbidden: Access is Denied response.
What IP I need to use in the IP Address and Domain Restrictions in order to give PowerShell access to loading my site which is hosted on the same machine.
Answer: Sorry I cannot add comments yet. Are you able to browse to the URL normally without requiring credentials? If authentication is enabled on your site, you might want to modify your web.conf file and exclude the URL you are trying to access.


Cannot open TUN/TAP dev /dev/as0t0: No such file or directory (errno=2)

Question: I just attempted to install OpenVPN Access Server on my Debian VPS that uses OpenVZ. It installed fine, however when I try to start it from the administration panel, I get these errors:
<code>process started and then immediately exited: ['Sat Sep 22 19:14:33 2012 Cannot open TUN/TAP dev /dev/as0t0: No such file or directory (errno=2)']
service failed to start or returned error status
process started and then immediately exited: ['Sat Sep 22 19:14:33 2012 Cannot open TUN/TAP dev /dev/as0t1: No such file or directory (errno=2)']
service failed to start or returned error status
process started and then immediately exited: ['Sat Sep 22 19:14:33 2012 Cannot open TUN/TAP dev /dev/as0t2: No such file or directory (errno=2)']
service failed to start or returned error status
process started and then immediately exited: ['Sat Sep 22 19:14:33 2012 Cannot open TUN/TAP dev /dev/as0t3: No such file or directory (errno=2)']
service failed to start or returned error status
process started and then immediately exited: ['Sat Sep 22 19:14:33 2012 Cannot open TUN/TAP dev /dev/as0t4: No such file or directory (errno=2)']
service failed to start or returned error status
process started and then immediately exited: ['Sat Sep 22 19:14:33 2012 Cannot open TUN/TAP dev /dev/as0t5: No such file or directory (errno=2)']
service failed to start or returned error status
process started and then immediately exited: ['Sat Sep 22 19:14:33 2012 Cannot open TUN/TAP dev /dev/as0t6: No such file or directory (errno=2)']
service failed to start or returned error status
process started and then immediately exited: ['Sat Sep 22 19:14:33 2012 Cannot open TUN/TAP dev /dev/as0t7: No such file or directory (errno=2)']
service failed to start or returned error status
</code>
Is there a solution for this?
Answer: I had similar problem when trying to install OpenVPN on OpenVZ. You have good information at: http://wiki.openvz.org/VPN_via_the_TUN/TAP_device
Your problem could be:

tun module is not loaded on HW-node. If you rent a VPS ask your VPS-provider for tun-device. Otherwise follow instruction how to install tun-module at HW-node.
CT has not rights for TUN/TAP device. Follow instruction in above doc.

I can also recommend OpenVPN page about OpenVPN/OpenVZ


Create new row with identifier and NA on outcome if missing

Question: I have a data frame such as the one below:
   id day  time trial outcome
1   1   1 15:10     2   FALSE
2   1   2 15:01     2    TRUE
3   1   2 20:10     3   FALSE
4   1   3 11:10     1   FALSE
5   1   4 15:10     2   FALSE
6   1   5 20:13     3   FALSE
7   1   6 11:10     1   FALSE
8   1   6 15:10     2   FALSE
9   1   7 11:10     1   FALSE
10  1   7 15:09     2    TRUE
11  1   7 20:00     3    TRUE
12  1   8 11:10     1   FALSE
13  1   8 15:01     2    TRUE
14  1   9 15:00     2    TRUE
15  1   9 20:06     3    TRUE
16  1  10 11:10     1   FALSE
17  1  11 11:10     1   FALSE
18  1  11 15:00     2    TRUE
19  1  12 20:00     3    TRUE
20  1  13 15:02     2    TRUE

Each day participants received 3 trials. The outcome is whether they looked at the trial. If they did not look, no data row was recorded. What I wish to do is create rows for those missing trials.
So in the above example, on day 1: trial 1 and 3 would need to be added; where id=1, day=1, and trial=1 and 3, but time and outcome have a NA. On day 2, only trial 1 would have to be added; where id=1, day=2, and trial=1, but again time and outcome are NA.
I have been playing around, but have not been able to find a reliable solution.
Reproducible dataset:
structure(list(id = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35",
"36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46",
"47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57",
"58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68",
"69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79",
"80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90",
"91", "92", "93", "94", "95", "96"), class = "factor"), day = c(1,
2, 2, 3, 4, 5, 6, 6, 7, 7, 7, 8, 8, 9, 9, 10, 11, 11, 12, 13),
    time = c("15:10", "15:01", "20:10", "11:10", "15:10", "20:13",
    "11:10", "15:10", "11:10", "15:09", "20:00", "11:10", "15:01",
    "15:00", "20:06", "11:10", "11:10", "15:00", "20:00", "15:02"
    ), trial = c(2, 2, 3, 1, 2, 3, 1, 2, 1, 2, 3, 1, 2, 2, 3,
    1, 1, 2, 3, 2), outcome = structure(c(1L, 2L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L
    ), .Label = c("FALSE", "TRUE"), class = "factor")), .Names = c("id",
"day", "time", "trial", "outcome"), row.names = c(NA, 20L), class = "data.frame")

Answer: Here is a solution in base R using merge.
# Skeleton dataframe as template
df2 <- cbind.data.frame(
    day = rep(1:max(df$day), each = max(df$trial)),
    trial = rep(1:max(df$trial), max(df$day)));

#
df <- merge(df, df2, by = c("day", "trial"), all = TRUE)
df;
#   day trial   id  time outcome
#1    1     1 <NA>  <NA>    <NA>
#2    1     2    1 15:10   FALSE
#3    1     3 <NA>  <NA>    <NA>
#4    2     1 <NA>  <NA>    <NA>
#5    2     2    1 15:01    TRUE
#6    2     3    1 20:10   FALSE
#7    3     1    1 11:10   FALSE
#8    3     2 <NA>  <NA>    <NA>
#9    3     3 <NA>  <NA>    <NA>
#10   4     1 <NA>  <NA>    <NA>
#11   4     2    1 15:10   FALSE
#12   4     3 <NA>  <NA>    <NA>
#13   5     1 <NA>  <NA>    <NA>
#14   5     2 <NA>  <NA>    <NA>
#15   5     3    1 20:13   FALSE
#16   6     1    1 11:10   FALSE
#17   6     2    1 15:10   FALSE
#18   6     3 <NA>  <NA>    <NA>
#19   7     1    1 11:10   FALSE
#20   7     2    1 15:09    TRUE
#21   7     3    1 20:00    TRUE
#22   8     1    1 11:10   FALSE
#23   8     2    1 15:01    TRUE
#24   8     3 <NA>  <NA>    <NA>
#25   9     1 <NA>  <NA>    <NA>
#26   9     2    1 15:00    TRUE
#27   9     3    1 20:06    TRUE
#28  10     1    1 11:10   FALSE
#29  10     2 <NA>  <NA>    <NA>
#30  10     3 <NA>  <NA>    <NA>
#31  11     1    1 11:10   FALSE
#32  11     2    1 15:00    TRUE
#33  11     3 <NA>  <NA>    <NA>
#34  12     1 <NA>  <NA>    <NA>
#35  12     2 <NA>  <NA>    <NA>
#36  12     3    1 20:00    TRUE
#37  13     1 <NA>  <NA>    <NA>
#38  13     2    1 15:02    TRUE
#39  13     3 <NA>  <NA>    <NA>

Explanation: Construct a skeleton (template) dataframe based on the maximum number of days and trials. Then merge the skeleton with the original dataframe with merge(..., by = c("day", "trial"), all = TRUE), to flag missing entries with NA.

Sample data
df <- structure(list(id = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24",
"25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35",
"36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46",
"47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57",
"58", "59", "60", "61", "62", "63", "64", "65", "66", "67", "68",
"69", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79",
"80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "90",
"91", "92", "93", "94", "95", "96"), class = "factor"), day = c(1,
2, 2, 3, 4, 5, 6, 6, 7, 7, 7, 8, 8, 9, 9, 10, 11, 11, 12, 13),
    time = c("15:10", "15:01", "20:10", "11:10", "15:10", "20:13",
    "11:10", "15:10", "11:10", "15:09", "20:00", "11:10", "15:01",
    "15:00", "20:06", "11:10", "11:10", "15:00", "20:00", "15:02"
    ), trial = c(2, 2, 3, 1, 2, 3, 1, 2, 1, 2, 3, 1, 2, 2, 3,
    1, 1, 2, 3, 2), outcome = structure(c(1L, 2L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L
    ), .Label = c("FALSE", "TRUE"), class = "factor")), .Names = c("id",
"day", "time", "trial", "outcome"), row.names = c(NA, 20L), class = "data.frame")

Answer: This is a job for complete from tidyr,
library(tidyr)

complete(df, trial, nesting(id, day))

Answer: You can use a combination of expand.grid() to get all the possible combinations and then merge them with the original data.frame.
dat <- data.frame(id = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
                         "14", "15", "16", "17", "18", "19", "20"),
                  day = c(1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 7, 8, 8, 9, 9, 10, 11, 11, 12, 13),
                  time = c("15:10", "15:01", "20:10", "11:10", "15:10", "20:13",
                           "11:10", "15:10", "11:10", "15:09", "20:00", "11:10", "15:01",
                           "15:00", "20:06", "11:10", "11:10", "15:00", "20:00", "15:02"),
                  trial = c(2, 2, 3, 1, 2, 3, 1, 2, 1, 2, 3, 1, 2, 2, 3, 1, 1, 2, 3, 2),
                  outcome = structure(c(1L, 2L, 1L, 1L, 1L,  1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 2L, 1L, 1L, 2L, 2L, 2L),
                                      .Label = c("FALSE", "TRUE"), class = "factor"))

vals <- expand.grid(id = unique(dat$id),
                    day = unique(dat$day),
                    trial = unique(dat$trial))
vals$time <- NA
vals$outcome <- NA

dat2 <- merge(vals, dat, all = TRUE)


android wear duplicate sensorEventListener

Question: I'm developing an Android Wear App which register Heart Rate from start until the moment the user stop it touching a button, so i don´t unregister the listener on function onStop or onDestroy.
The problem is when i return to the Wear Menu and open the app again. In that moment the app register the listeners again and get all measures duplicated. I tried to unregister the listeners on function onStart and onRestart but it didn´t work.
Here is my code:
    ...

public class MainActivity extends Activity implements SensorEventListener {
    Sensor mHeartRateSensor;
    SensorManager mSensorManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Sensor and sensor manager
        mSensorManager = ((SensorManager)getSystemService(SENSOR_SERVICE));
        mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mSensorManager.registerListener(this, mHeartRateSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        mSensorManager.registerListener(this, mHeartRateSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }
    /*
    I need the listeners are active, so i can't unregister it
    @Override
    protected void onDestroy() {
        this.mSensorManager.unregisterListeners(this);
        super.onDestroy();
    }*/

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
        //Get heart rate and accuracy
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {
        //
    }

    /*on click listeners*/
    ...
}

Thanks in advance.
Answer: You can add a boolean variable named mIsRegistered,set its default value to false.and when you want to register,firstly check the value,if false ,do register,if true,dont't register again.


Exporting a binary based file with Python

Question: I'm am currently working on a export script for Blender, however I feel my question is more based around Python in general so I've posted it here.
A friend created a conversion program in java for .obj files , which turns them into a custom binary file format. However, I want to skip that process and export the binary file directly from Blender.
The file contains text, integers and floats, using utf-8, utf-16 and utf-32 formats.
So far I have all the data exporting as a standard text file, so I just need to output it in the appropriate encoding/format. Here is the code he is using in Java for writing the data to the file in different encodings:
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class StreamConverter {

//---------------------------------------------------

public static void buffer_write_string(DataOutputStream out,String text) throws IOException{
    byte[] bytes = text.getBytes();
    for(int i =0;i<text.length();i++){
        buffer_write_u8(out,bytes[i]);
    }
}

public static void buffer_write_u32(DataOutputStream out,int i) throws IOException{
    ByteBuffer b = ByteBuffer.allocate(4);
    b.order(ByteOrder.LITTLE_ENDIAN);
    b.putInt(i);
    out.write(b.array());
}

public static void buffer_write_u16(DataOutputStream out,int i) throws IOException{
    out.write((byte) i);
    out.write((byte) (i >> 8));
}

public static void buffer_write_s16(DataOutputStream out,int i) throws IOException{
    out.write((byte) i);
    out.write((byte) (i >> 8));
}

public static void buffer_write_s32(DataOutputStream out,int i) throws IOException{
    ByteBuffer b = ByteBuffer.allocate(4);
    b.order(ByteOrder.LITTLE_ENDIAN);
    b.putInt(i);
    out.write(b.array());
}

public static void buffer_write_u8(DataOutputStream out,int i) throws IOException{
    out.writeByte((byte) i);
}

public static void buffer_write_s8(DataOutputStream out,int i) throws IOException{
    out.writeByte((byte) i);
}

public static void buffer_write_f64(DataOutputStream out,double i) throws IOException{
    ByteBuffer b = ByteBuffer.allocate(8);
    b.order(ByteOrder.LITTLE_ENDIAN);
    b.putDouble(i);
    out.write(b.array());

}

public static void buffer_write_f32(DataOutputStream out,float i) throws IOException{
    ByteBuffer b = ByteBuffer.allocate(4);
    b.order(ByteOrder.LITTLE_ENDIAN);
    b.putFloat(i);
    out.write(b.array());
}

}

I'm not sure how to do this is Python, I'm trying this to see if I can at least get integers to output correctly but no luck.
def write_u8(file, num):
    enum = num.encode('utf-8')
    file.write(enum)

def write_u16(file, num):
    enum = num.encode('utf-16')
    file.write(enum)

def write_u32(file, num):
    enum = num.encode('utf-32')
    file.write(enum)

example usage:
write_u32(file, u'%i' % (vertex_count))

also tried this:
counts = bytes([vertex_count,tex_count,normal_count])
file.write(counts)

I'm a bit lost with this whole binary/encoding thing, I've read through the Python documentation, but it hasn't helped.
Any links to tutorials or examples would be great!
Answer: From what I understand, what you would like to do is serialize your object and deserialize it back. In Python, Pickle is the package you are looking for. You can look at its documentation right here.


Wso2 ESB Integration with SFDC

Question: I am integrating WSO2 ESB 4.8.1 with SFDC.
Using SFDC connector 1.0
In WSO2 i have written the code <salesforce.logout/>, according to WSO2 Documentation they say that it closes the current connection.
<salesforce.logout/> produces below soap message which i identified in WSO2 ESB log
TID: [0] [ESB] [2016-08-30 07:55:39,442] DEBUG {org.apache.synapse.transport.http.wire} -  << "<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:urn="urn:partner.soap.sforce.com"><soapenv:Header><urn:SessionHeader><urn:sessionId>00D17000000BPGr!AQcAQDIggW.ikXtsb0Ckm8c8pKKDlF_8QN42jL31WUa6hDLOdEeNIjrYsevKW0FeZLDzlrjcDLwMni_7gYaZgNfdN4zv9Cgj</urn:sessionId></urn:SessionHeader></soapenv:Header><soapenv:Body><urn:logout></urn:logout></soapenv:Body></soapenv:Envelope>[\r][\n]" {org.apache.synapse.transport.http.wire}

But few times i am getting below error (INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal Session. Session not found, missing session hash:) when <salesforce.logout/> is executed
TID: [0] [ESB] [2016-08-30 07:55:39,529] DEBUG {org.apache.synapse.transport.http.wire} -  >> "<?xml version="1.0" encoding="UTF-8"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sf="urn:fault.partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><soapenv:Body><soapenv:Fault><faultcode>sf:INVALID_SESSION_ID</faultcode><faultstring>INVALID_SESSION_ID: Invalid Session ID found in SessionHeader: Illegal Session. Session not found, missing session hash: je59etMAEPM+m9VdYJb0AW==[\n]" {org.apache.synapse.transport.http.wire}
TID: [0] [ESB] [2016-08-30 07:55:39,529] DEBUG {org.apache.synapse.transport.http.wire} -  >> "This is expected, it can happen if the session has expired and swept away, or if the user logs out, or if its just someone trying to hack in. </faultstring><detail><sf:UnexpectedErrorFault xsi:type="sf:UnexpectedErrorFault"><sf:exceptionCode>INVALID_SESSION_ID</sf:exceptionCode><sf:exceptionMessage>Invalid Session ID found in SessionHeader: Illegal Session. Session not found, missing session hash: je59etMAEPM+m9VdYJb0AW==[\n]" {org.apache.synapse.transport.http.wire}
TID: [0] [ESB] [2016-08-30 07:55:39,529] DEBUG {org.apache.synapse.transport.http.wire} -  >> "This is expected, it can happen if the session has expired and swept away, or if the user logs out, or if its just someone trying to hack in. </sf:exceptionMessage></sf:UnexpectedErrorFault></detail></soapenv:Fault></soapenv:Body></soapenv:Envelope>[\r][\n]" {org.apache.synapse.transport.http.wire}

Is it SFDC issue/WSO2 SFDC connector issue/WSO2 ESB configuration issue.?
For upsert operation we are using configkey attribute in entire project, below is the code
<salesforce.upsert configKey="sfdc_connection_dtls">
          <allOrNone>0</allOrNone>
          <allowFieldTruncate>0</allowFieldTruncate>
          <sobjects xmlns:sfdc="sfdc">{//sfdc:sObjects}</sobjects>
        </salesforce.upsert>

So when i use <salesforce.logout/> in the respective sequence, does it closes only the current connection which is available in sequence.? or it closes all connection which are existing.?
Where ever i am using salesforce.upsert(below is the skeleton code) can i use <salesforce.logout/> after salesforce.upsert call.?
<salesforce.upsert configKey="sfdc_connection_dtls">

</salesforce.upsert>

Looking forward for your help
Thanks,
Tejas
Answer: In WSO2 SFDC connector, there's a single SF connection created per flow per init configuration. Therefore, if you issue a logout, your subsequent requests will fail. It is not necessary to issue logout since the connection is anyway terminated at the end of the flow.

Wso2 ESB Integration with SFDC


Getting views contextual filter from url for display suite block

Question: I have a URL for an event content type that concatenates two other content types, namely "name-of-venue" and "name-of-performer" with "date-of-event", so the url is "name-of-venue/name-of-performer/dateofevent".
I wish to place a block on the event content type that shows only the events for that venue.
I have tried to configure the contextual filter as shown on the screen shot,

using the PHP code:

$np = explode('/', drupal_get_normal_path($argument)); if
  (!empty($np[3])) {   $handler->argument = $np[3];   return TRUE; }
  else {   return FALSE; }

However this does not return just those events for that specific venue, but for all venues.
Consequently I fear that I am not actually exploding the url and so failing to obtain the NID for "name-of-venue" that I need for the contextual filter.
Any suggestions would be very much appreciated.
Thank you.
Comment: Do you want to display the View Block on the Event Content Type? Or on the Venue Content Type? I am a bit confused by the "...I wish to place a block on the event content type that shows only the events for that venue...". I would expect sth like "...I wish to place a block on the Venue content type that shows only the events for that venue...". Cheers!
Comment: Apologies @StefanosPetrakis, I want to display the view block on the event content type that shows only the events for that venue.
Comment: So, you want a view that will display events related to the current event. The relation being "same venue". I hope I got this right this time. If I did, then the next question would be, why you would need code for validation? You could grab the NID from the internal node path (node/%nid) and use that further in your view to get all related events. I could give you an example of that, if I am on the right track. Cheers again!
Comment: @StefanosPetrakis. Correct! I think I've tried what you're suggesting, but obviously I must be doing something wrong. Any example would be very much appreciated. Many thanks for all your help.
Comment: Okey! And you are using Entiry Reference for the linkage between Events and Venues, right?
Comment: @StefanosPetrakis. Correct!
Comment: @StefanosPetrakis. I should have added that the Event Content Type has two entity reference fields. One for the name-of-venue that is set using Rules when the Event Content Type is saved, and the other for name-of-performer that is set by the user (the venue) when entering the event details on the Event Content Type. Don't know if that's relevant?
Comment: Hey @Richard, thanks for the update, I don't think this changes sth, no.
Comment: Nope, sorry, have to rewrite this, my answer is wrong. Ignore it for the time.
Comment: @StefanosPetrakis. No worries. Really appreciate your help. Thank you.
Comment: Second attempt below :-)
Answer: Here is a kind-of-complex sketch for your problem, using only Views:

Create a block view displaying Content of type Event
Add a "Content: Nid" contextual filter, using the default settings. You may need to set the default value to "Content ID from URL" for the case "When the filter value is NOT available"
In your View configuration, under "Relationships", create a "Entity Reference: Referenced entity" relationship for your reference field (e.g. field_venue) and click on "Require this relationship": This relationship will retrieve the venue of the Event that is defined from the contextual filter.
Create a second relationship, one of type "Entity Reference: Referencing entity", again for your reference field (e.g. field_venue) and click on "Require this relationship". Important: Use the first relationship (step 3) for this one: This second relationship will retrieve the events that reference the venue we got from the first relationship.
Set your Views format to use fields (either by using a Table or by ticking the "Force using fields" option).
Add the fields you want to display and select the second relationship you created for them.

At this point your block should list all events for the venue of your current event. The problem that still remains is excluding the current event from that list. Follow steps take care of that:

Add two "Content: Nid" fields, set one of them to use the second relationship and exlude them from display.
Set a "Global: Fields comparison" filter and set it to filter out rows when the two excluded fields from above are equal: This will take care of excluding the actual event from showing in the block.

Once you place this block inside an event node page, it should display a list of Events from the same venue excluding the current event.
Cheers and let me know how this goes.

Appendix A:

Appendix B:
Comment: Gonna add some screenshots as well.
Comment: Hi @StefanosPetrakis, and thank you. Unfortunately, although I've tied steps 1 to 6 as you've suggested (hopefully correctly) the block is displaying the no results found message "No future events at name-of-venue/name-of-performer/300416 have yet been entered". In other words it's displaying the URL (venue/performer/date), rather than details (selected fields from the Event Content Type) of the event itself. If this isn't going to work, I do have an integer field, "current-user:field-user-page-nid", that stores the NID of the venue – is there any way we could use that instead?
Comment: Could you export your view in a pastebin? I would like to have a look. And I don't really understand the "In other words it's displaying the URL "(venue/performer/date)" part. But, let me first have a look at the View export and then we can look into alternatives. This issue will be solved eventually, it's not such a rarity  :-)
Comment: Hi, @StefanosPetrakis hopefully this is the link you require http://pastebin.com/NamE4uzj. Very many thanks.
Comment: Hi @Richard, I just tried with the view you exported and it seems to work, you can have a look at Appendix B, in my answer (edited). I had to remove the date filter and adjust the "Views Displays" (admin/structure/ds/vd/manage/establishment_events_entry-block-fields/display), but the view configuration itself worked for me as expected. The nid you see in the screenshot of Appendix B, 209, is the nid of an event. Can you have another check at your view/block without the date filter? Best regards and you are welcome!
Comment: Hi @StefanosPetrakis – we're almost there! The block is now displaying "name-of-performer" correctly, but not the event category or the other data  taken from 'content entity referenced from field_establishment_reference' and combined for display in the block in the "Global: Custom Text" field, and I've no idea why this is? I'm really sorry to be taking up so much of your time, but your help is really appreciated.
Comment: Hey @Richard, make sure the global text field comes after the fields that are combined. Let me know if that solves it! If necessary, place it last in line.
Comment: Hi @StefanosPetrakis – it is indeed the last in line, and I'm afraid it always has been. So unfortunately that's not the answer :(
Comment: Hey @Richard, we'll make this work, no worries. I think you need to check the relationships you use in the fields of the view, you should use "Content referencing Content from field_establishment_reference" and not "Content entity referenced from field_establishment_reference", the latter delivers the fields of the venue, and not of the venue's events. Could you try to update this and check if that solves it?
Comment: You were absolutely right @StefanosPetrakis! That does solve it. And, even better, it also works with the event date filter you suggested we remove while we were trying to get it to work. I can only say thank you, thank you. Your help and hard work is genuinely very much appreciated. Again, thank you.
Comment: Dear @Richard, this is really good news and a huge feeling of satisfaction to hear you got it solved. It was not at all trivial site building, what was needed to solve it, I learned lots. As a reminder, if this worked for you, you should accept my answer. See you around!


Two identically configured sendmails, one of them is not delivering mail

Question: I have two identically configured OpenBSD machines that use sendmail for mail delivery. I basically made no changes to the sendmail install other than setting up an alias root: email@example.com on each one. They're both on the same subnet(s) and both can access the mail server mail.example.com. However, one of them cannot deliver mail. I'm not terribly familiar with sendmail, so hopefully someone can explain this behaviour. I've posted the /var/log/maillog/ from each machine below:
The machine which delivers successfully:
Dec  7 11:57:35 gw003 sendmail[9640]: nB7JvZmS009640: from=kamil, size=60, class=0, nrcpts=1, msgid=<200912071957.nB7JvZmS009640@gw00
3.backbone.example.com>, relay=root@localhost
Dec  7 11:57:35 gw003 sm-mta[30258]: nB7JvZlR030258: from=<firstname.lastname@example.com>, size=401, class=0, nrcpts=1, msgid=<2
email@example.com>, proto=ESMTP, daemon=MTA, firstname.lastname@example.com [127.
0.0.1]
Dec  7 11:57:35 gw003 sendmail[9640]: nB7JvZmS009640: firstname.lastname@example.com, ctladdr=kamil (1031/1031), delay=00:00:00, xdelay=00:
00:00, mailer=relay, pri=30060, relay=[127.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (nB7JvZlR030258 Message accepted for delivery)
Dec  7 11:57:35 gw003 sm-mta[29848]: STARTTLS=client, relay=mail.example.com., version=TLSv1/SSLv3, verify=FAIL, cipher=AES256-SHA,
 bits=256/256
Dec  7 11:57:35 gw003 sm-mta[29848]: nB7JvZlR030258: to=<email@example.com>, ctladdr=<firstname.lastname@example.com> (1031/1
031), delay=00:00:00, xdelay=00:00:00, mailer=esmtp, pri=30401, relay=mail.example.com. [10.2.32.11], dsn=2.0.0, stat=Sent (4b1d5e2
f-0000528c Message accepted for delivery)

The machine which is failing to deliver:
Dec  7 12:00:35 gw004 sendmail[12957]: nB7K0ZdA012957: from=kamil, size=60, class=0, nrcpts=1, msgid=<200912072000.nB7K0ZdA012957@gw0
04.backbone.example.com>, relay=root@localhost
Dec  7 12:00:35 gw004 sm-mta[25655]: nB7K0Z7U025655: <firstname.lastname@example.com>... User unknown
Dec  7 12:00:35 gw004 sendmail[12957]: nB7K0ZdA012957: firstname.lastname@example.com, ctladdr=kamil (1031/1031), delay=00:00:00, xdelay=00
:00:00, mailer=relay, pri=30060, relay=[127.0.0.1] [127.0.0.1], dsn=5.1.1, stat=User unknown
Dec  7 12:00:35 gw004 sm-mta[25655]: nB7K0Z7U025655: from=<firstname.lastname@example.com>, size=60, class=0, nrcpts=0, proto=ESM
TP, daemon=MTA, firstname.lastname@example.com [127.0.0.1]
Dec  7 12:00:35 gw004 sendmail[12957]: nB7K0ZdA012957: nB7K0ZdB012957: DSN: User unknown
Dec  7 12:00:36 gw004 sm-mta[25655]: nB7K0Z7W025655: from=<>, size=2203, class=0, nrcpts=1, msgid=<200912072000.nB7K0ZdB012957@gw004.
backbone.example.com>, proto=ESMTP, daemon=MTA, firstname.lastname@example.com [127.0.0.1]
Dec  7 12:00:36 gw004 sendmail[12957]: nB7K0ZdB012957: to=kamil, delay=00:00:01, xdelay=00:00:01, mailer=relay, pri=31084, relay=[127
.0.0.1] [127.0.0.1], dsn=2.0.0, stat=Sent (nB7K0Z7W025655 Message accepted for delivery)
Dec  7 12:00:36 gw004 sm-mta[9947]: nB7K0Z7W025655: to=<firstname.lastname@example.com>, delay=00:00:01, xdelay=00:00:00, mailer=
local, pri=32465, dsn=2.0.0, stat=Sent

Comment: "Identically configured"... they've got different hostnames, for a start...
Comment: Sure, apart from the hostname and individual IP addresses. They are a mirror image of each other built with the same configuration managed steps.
Answer: I suspect a name resolution problem on the "bad" system. Check /etc/hosts for non-symmetric entries. Check DNS resolution on both machines.
ifconfig -a            # note various IP adresses of this system
dig -x 18.104.22.168       # query FQDN for my own ip, are results symmetric?
dig -x 184.108.40.206         # same on another interface
dig -x 220.127.116.11         # and another one

and
dig my.fully.qualified.domain.name.
dig another.fully.qualified.domain.name.

and
hostname   # is it symmetric on both systems? or short on one and fully-qualified on another?

Comment: I've checked the relevant IP addresses (the primary management interface IP, the interface for the VLAN with the mail server, and the primary external interface) and the forward and reverse queries seem to match. hostname shows the FQDN for both systems, and it is set correctly in /etc/hosts
Answer:
email@example.com [127.0.0.1]

You are not relaying through your mail server mail.example.com
This is certainly a configuration problem related to relay domain or the server domain.
(on the second machine it delivers mails on localhost, meaning it believes that the final destination is itself. check domain/hostname/relays)
Comment: The successful one also has the same relay line. Also, why would only the second machine think it is the final destination for the domain while the first does not? It seems gw004 decides right away that firstname.lastname@example.com is an unknown user where as gw003 correctly relays the mail to the mail server.
Answer: Check the contents of /etc/mail/local-host-names and /etc/mail/relay-domains and maybe /etc/mail/mailertable -- your second box needs to know either it is example.com, or how to get there.
Comment: I checked these and they're empty on both boxes. I thought that by virtue of mail.example.com being the MX record for example.com, they should both be able to figure out that email@example.com should send there. Indeed it seems like gw003 does. Or am I wrong in this assumption?
Comment: Hmmm.  Look in /etc/mail/access to make sure it is permitted to send to itself, first.


How do I efficiently bin values into overlapping bins using Pandas?

Question: I would like to bin all the values from a column of type float into bins that are overlapping. The resulting column could be a series of 1-D vectors with bools - one vector for each value from the original column. The resulting vectors contain True for each bin a value falls into and False for the other bins.
For example, if I have four bins [(0, 10), (7, 20), (15, 30), (30, 60)], and the original value is 9.5, the resulting vector should be [True, True, False, False].
I know how to iterate through all the ranges with a custom function using 'apply', but is there a way to perform this binning more efficiently and concisely?
Answer: Would a simple list comprehension meet your needs?
Bins = [(0, 10), (7, 20), (15, 30), (30, 60)]
Result = [((9.5>=y[0])&(9.5<=y[1])) for y in Bins]

If your data is stored in column data of a pandas DataFrame (df) then you can define the function:
def in_ranges(x,bins):
    return [((x>=y[0])&(x<=y[1])) for y in bins]

and apply it to the column:
df[data].apply(lambda x: pd.Series(in_ranges(x,Bins),Bins))


Good Explanation of Epsilon-Delta Definition of a Limit?

Question: I'm really doing my best but completely failing to understand the epsilon-delta definition of a limit. I vaguely understand it like this: Given a bound on the difference between the input and desired input, there also exists a bound on the difference between the value of our function and the value of the function at the limit. However, my I have no understanding of where this formal definition came from and what it means at a deeper level, so I feel like it's just been arbitrarily thrown at me by my textbook. Can someone elaborate on its meaning and what this relationship between $$ and $$ signifies? I would appreciate as simple of an explanation as possible.
Comment: It is not directly answering the question but this little discussion https://math.stackexchange.com/q/3435671/399263 can be a good complement in trying to understand some subtleties about limits.
Comment: I can provide you with an excellent resource. Which addresses exactly what you are looking for. Link: https://youtu.be/Prwx4vr2l2M
Comment: As a further reading, you can use Introduction to metric and topological space by Wilson Sutherland. Second edition, page no. 25.
Comment: You can think about $\varepsilon-\delta$ as control; I want to control my function and push its outputs together, not merely *close* together but *as close as I wish*, usually stated as "arbitrarily close". If I can't have this control, then I can always stand my ground and say: "No, that is not the limit, we cannot get so close". If we do have this control, then no matter how defiant I am, if I challenge someone to find a value within, say $0.000000001$, then someone can beat me and say "Yes! Such a $\delta$ does exist". Then we have a limit, because I always lose :)
Comment: Sorry ! this is the correct link to another question about $\epsilon-\delta$ definition. https://math.stackexchange.com/questions/1489702/how-to-make-sense-out-of-the-epsilon-delta-definition-of-a-limit/1489710#1489710
Answer: Other answers have talked about the epsilon-delta definition as a game. Maybe it would be helpful to play a couple of rounds of that game to solidify what we are talking about.
Let's play the game with the function $f(x) = x^2 - 2x + 1$. We (team $\delta$) think that the limit of $f(x)$ as $x$ tends to $3$ is $4$. The good news is that we are correct. But our evil opponents (team $\epsilon$) are trying to trip us up by throwing strange values of $\epsilon$ at us.
Maybe their opening gambit is to say: "What about $\epsilon = 10$?". To win the round, we must provide an interval of the form $[3 - \delta, 3 + \delta]$ such that if $x$ is in that interval then $f(x)$ is in the interval $[4 - \epsilon, 4 + \epsilon] = [4 - 10, 4 + 10] = [-6, 14]$.
It is easy for us to repel this first attack. We say: "$\delta = 1$". And sure enough, on the interval $[2, 4]$ the function $f(x)$ takes values in $[1, 9]$. Therefore, the weaker statement that it takes values in $[-6, 14]$ is true and we win that round.
Our opponents get smarter. "Well, what about $\epsilon = 1$?", they ask. Our "$\delta = 1$" response isn't going to cut it this time because we need to find a interval for $x$ where the corresponding $f(x)$ interval is $[4 - 1, 4 + 1] = [3, 5]$. We think a little (but not too much) and suggest "$\delta = 0.1$" because that seems safe. It implies an interval of $[2.9, 3.1]$ for $x$ and $[3.61, 4.41]$ for $f(x)$. So this works fine and we win again.
Now our opponents are angry. "Fine, what about $\epsilon = 0.0000001$?" they smugly demand. We are now getting scared and also a little bored. These guys are going to keep throwing out smaller and smaller values for $\epsilon$ and we are going to need to come up with smaller and smaller values for $\delta$. Can we do it?
That is the general question for delta-epsilon limits. Can we always win the game? If we can, then the limit exists.
The specific details as to how we do this for our $f(x)$ aren't particularly interesting but we might approach it by:

Noting that $|f(x) - 4| < \epsilon \iff -\epsilon < f(x) - 4 < \epsilon$
Noting that near $x = 3$, say in the interval $[2, 4]$, $f(x)$ is increasing. That is if $\delta < 1$ then for all $x$ in $[3 - \delta, 3 + \delta]$ we have $f(3 - \delta) < f(x)$ and $f(x) < f(3 + \delta)$
Finding $\delta$ such that $-\epsilon < f(3 - \delta) - 4$ and $f(3 + \delta) - 4 < \epsilon$ (probably by converting the $<$ signs to $=$, solving the resulting quadratic equations in $\delta$ and maybe nudging $\delta$ a little to ensure that the $<$ holds rather than just $\le$)

Again the specifics for other functions might be very different (and you'll probably go on to prove some theorems to make them easier) but what is important is whether you can produce a winning $\delta$ for any $\epsilon$ thrown at you.
Some final notes:

In the game our opponents value of epsilon and our responding value of delta must always be strictly greater than zero. Saying "$\epsilon = 0$" or "$\delta = 0$" isn't an allowed move in the game
Our opponents aren't going to win by throwing larger values of $\epsilon$ at us because we can just repeat our previous $\delta$ and win that round
We can't just pick a small value of $\delta$ at the start and walk away because our opponent could pull a similar trick to the one we used and produce an $\epsilon$ that breaks our $\delta$. We need to know their $\epsilon$ before producing our $\delta$.
There is a nice Brilliant article that explains this game approach too
Comment: I so liked this!
Answer:
$\lim_{x \rightarrow y}{f(x)} = c $ if and only if for every $ \epsilon > 0 $, there is a $ \delta > 0 $ such that
$ 0 < |x - y| < \delta$ implies $ | f(x) - c | < \epsilon $ for all $x$

Lets see what it means.
It's easiest to read
$ 0 < |x - y| < \delta $ as "the distance between $x$ and $y$ is between $0$ and $\delta$".
If we use this interpretation, the definition becomes:
$\lim_{x \rightarrow y}{f(x)} = c$ if and only if for every $ \epsilon > 0 $, there is a $\delta > 0$ such that if the distance between $x$ and $y$ is between $0$ and $\delta$, the distance between $f(x)$ and $c$ is less than $\epsilon$.
This basically means that $f(x)$ gets arbitrarily close to $c$ without necessarily becoming $c$.
Suppose $f(x)$ does not get arbitrarily close to $c$, i.e., there is some constant $d$ such that $f(x)$ will stay away from $c$ with at least distance $d$.
Then we can show the limit definition does not hold:
take $\epsilon = d$. Now there doesn't exist a $\delta$ such that
$0 < |x - y| < \delta \rightarrow |f(x) - c| < \epsilon $
(because we just assumed that $f(x)$ would never get closer to $c$ than distance $d$, and remember that this happening is equivalent to $|f(x) - c| < \epsilon = d$).
What may be helpful too is a (trivial) proof using the limit definition. Usually in these proofs, you take an $\epsilon$, and return a $\delta$ for which you have proved that $ 0 < |x - y| < \delta \rightarrow | f(x) - c | < \epsilon $ (when dealing with continuous functions you usually just use $|x - y| < \delta$ in your proof).
I prove that
$\lim_{x \rightarrow y} x = y$ (or, equivalently $f(x) = x$ and $c = y$ in the original formulation).
Take $\delta = \epsilon$. Then $ |x - y| < \delta \rightarrow | f(x) - y | = | x - y | < \delta = \epsilon $. So the condition that there exists some $\delta$ for which $ |x - y| < \delta \rightarrow | f(x) - c | < \epsilon $ holds is true, as I've just shown. More advanced proof usually use a similar logic, but the expression for $\delta$ and working out the $| f(x) - c | < \epsilon$ can become quite hard. This is why other theorems are often used (for continuous functions, $ \lim_{x \rightarrow y} f(x) = f(y) $, and compositions, products, sums of continuous functions are again continuous, which can help you out very often).
Also, the definition requires that something must hold for every $\epsilon$. Sometimes, teachers explain this as a game: you can choose $\epsilon$ freely, and you can give a procedure to show that something (there exists a $\delta$ such that...) will hold, then we can say $\lim_{x \rightarrow y} f(x) = c$. So, if you win this game by giving such a procedure, you basically got the recipe for a proof!
If you cannot win, it suffices to give a single $\epsilon$ such that $f(x)$ will never get closer to $c$ then distance $\epsilon$.
The wikipedia page on the ($\epsilon$, $\delta$)-definition is pretty good. Also, the picture from there may be helpful when you try to visualize $\delta$ and $\epsilon$ as distances.
Comment: I would tweak your explanation a bit to explain that to "break" a limit, it's not necessary that the function *never* approach the proposed limit.  It's enough if, no matter how close you get, the function *sometimes* gets "far away" from the proposed limit.  Think $\sin \frac 1x$ as $x \to 0$.
Comment: @RobertShore You're so right. Good example indeed!
Comment: Thank you, I think my issue was with understanding the significance of delta and epsilon as indicators that the function approaches the same limit over any bounds.


private files in drupal 6

Question: I have a sub directory in my files directory which I want to store private images. I display the images with their watermark, via the imagecache modules.
I thought I could make the directory (with the original images) hidden to the public simply by dropping an .htaccess file in the folder, with
deny from all

but the files are still publicly accessible. What am I missing?
Answer: If you want to basically prevent hotlinking images, you can try the following in your .htaccess file
RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http(s)?://(www\.)?yourdomain.com [NC]
RewriteRule \.(jpg|jpeg|png|gif)$ - [NC,F,L]

private files in drupal 6


Does running a HTTPModule prevent IIS Logging?

Question: We are running a site using a custom HTTPModule to do some URL Routing.
The problem is this sites traffic is not being logged by IIS.
Everything appears to be set up correctly, and other sites on the same server are logging. But the log folder for this site remains empty. (not even the W3SVC... folder is being created!)
Is this related to us running a HTTPModule, or is something else causing the problem. I can't find anything that says it would stop logging, or anything that says it won't.
Answer: In a word, no.  You've got something else funny going on.  Are you absolutely sure logging is enabled and you are looking at the correct path?


Abrir cliente de email com ficheiro de anexo

Question: Estou a tentar abrir o meu cliente de email (por exemplo o Outlook) com o seguinte:

Send mail

Agora queria enviar um anexo pelo mailto. Já vi que não é possível com a função mailto, mas existe outra maneira de abrir o meu cliente de email com um ficheiro anexo?
Answer: O protocolo "mailto" não oferece este recurso, principalmente por se tratar de locais e pode variar de dispositivo pra dispositivo. A nível de "Javascript" também não é possível por questões de segurança e incapacidade de comunicar com o sistema operacional para obtenção de arquivos. Uma alternativa seria ao invés de chamar o protocolo "mailto", você disponibilizar na página o upload do arquivo e após a conclusão do envio chamar a função que dispara o e-mail, no caso se for o PHP, a função "mail".
Comment: Sim, mas o objectivo é o anexo passar para o cliente de email. Obrigado
Comment: Isso mesmo @pc_oc, você perguntou uma outra maneira e citei na resposta. A forma que conheço até hoje seria você fazer isso no lado servidor. Via Javascript não há como anexar um arquivo direto chamado o protocolo "mailto".
Comment: Veja se este tópico em inglês pode lhe ajudar: https://stackoverflow.com/questions/1195111/c-sharp-mailto-with-attachment


Tinyproxy Refused CONNECT method

Question: I'm trying to configure tinyproxy and it throws the following error in the log file when I'm checking it via Proxifier checker:
<code>CONNECT   Oct 22 11:39:59 [13230]: Connect (file descriptor 6): 81-*-*-*.utk.ru [81.*.*.*]
CONNECT   Oct 22 11:39:59 [13230]: Request (file descriptor 6): CONNECT www.google.com:80 HTTP/1.1
INFO      Oct 22 11:39:59 [13230]: Refused CONNECT method on port 80
INFO      Oct 22 11:39:59 [13230]: no entity
</code>
Proxifier shows me this error:
<code>[44:38] Error : the proxy server cannot establish connection with www.google.com:80
    The error may indicate that the proxy server doesn't support SSL connections.
    It means that the proxy can be used for web browsing but it cannot work with Proxifier.
    The proxy server reply header is:
        HTTP/1.0 403 Access violation
        Server: tinyproxy/1.8.3
        Content-Type: text/html
        Connection: close
</code>
Here's my tinyproxy config:
<code>##
## tinyproxy.conf -- tinyproxy daemon configuration file
##
## This example tinyproxy.conf file contains example settings
## with explanations in comments. For decriptions of all
## parameters, see the tinproxy.conf(5) manual page.
##

#
# User/Group: This allows you to set the user and group that will be
# used for tinyproxy after the initial binding to the port has been done
# as the root user. Either the user or group name or the UID or GID
# number may be used.
#
User root
Group root

#
# Port: Specify the port which tinyproxy will listen on.  Please note
# that should you choose to run on a port lower than 1024 you will need
# to start tinyproxy using root.
#
Port 3128

#
# Listen: If you have multiple interfaces this allows you to bind to
# only one. If this is commented out, tinyproxy will bind to all
# interfaces present.
#
#Listen 192.168.0.1

#
# Bind: This allows you to specify which interface will be used for
# outgoing connections.  This is useful for multi-home'd machines where
# you want all traffic to appear outgoing from one particular interface.
#
#Bind 192.168.0.1

#
# BindSame: If enabled, tinyproxy will bind the outgoing connection to the
# ip address of the incoming connection.
#
#BindSame yes

#
# Timeout: The maximum number of seconds of inactivity a connection is
# allowed to have before it is closed by tinyproxy.
#
Timeout 600

#
# ErrorFile: Defines the HTML file to send when a given HTTP error
# occurs.  You will probably need to customize the location to your
# particular install.  The usual locations to check are:
#   /usr/local/share/tinyproxy
#   /usr/share/tinyproxy
#   /etc/tinyproxy
#
#ErrorFile 404 "/usr/share/tinyproxy/404.html"
#ErrorFile 400 "/usr/share/tinyproxy/400.html"
#ErrorFile 503 "/usr/share/tinyproxy/503.html"
#ErrorFile 403 "/usr/share/tinyproxy/403.html"
#ErrorFile 408 "/usr/share/tinyproxy/408.html"

#
# DefaultErrorFile: The HTML file that gets sent if there is no
# HTML file defined with an ErrorFile keyword for the HTTP error
# that has occured.
#
DefaultErrorFile "/usr/share/tinyproxy/default.html"

#
# StatHost: This configures the host name or IP address that is treated
# as the stat host: Whenever a request for this host is received,
# Tinyproxy will return an internal statistics page instead of
# forwarding the request to that host.  The default value of StatHost is
# tinyproxy.stats.
#
#StatHost "tinyproxy.stats"
#

#
# StatFile: The HTML file that gets sent when a request is made
# for the stathost.  If this file doesn't exist a basic page is
# hardcoded in tinyproxy.
#
StatFile "/usr/share/tinyproxy/stats.html"

#
# Logfile: Allows you to specify the location where information should
# be logged to.  If you would prefer to log to syslog, then disable this
# and enable the Syslog directive.  These directives are mutually
# exclusive.
#
Logfile "/var/log/tinyproxy/tinyproxy.log"

#
# Syslog: Tell tinyproxy to use syslog instead of a logfile.  This
# option must not be enabled if the Logfile directive is being used.
# These two directives are mutually exclusive.
#
#Syslog On

#
# LogLevel:
#
# Set the logging level. Allowed settings are:
#       Critical        (least verbose)
#       Error
#       Warning
#       Notice
#       Connect         (to log connections without Info's noise)
#       Info            (most verbose)
#
# The LogLevel logs from the set level and above. For example, if the
# LogLevel was set to Warning, then all log messages from Warning to
# Critical would be output, but Notice and below would be suppressed.
#
LogLevel Info

#
# PidFile: Write the PID of the main tinyproxy thread to this file so it
# can be used for signalling purposes.
#
PidFile "/var/run/tinyproxy/tinyproxy.pid"

#
# XTinyproxy: Tell Tinyproxy to include the X-Tinyproxy header, which
# contains the client's IP address.
#
#XTinyproxy Yes

#
# Upstream:
#
# Turns on upstream proxy support.
#
# The upstream rules allow you to selectively route upstream connections
# based on the host/domain of the site being accessed.
#
# For example:
#  # connection to test domain goes through testproxy
#  upstream testproxy:8008 ".test.domain.invalid"
#  upstream testproxy:8008 ".our_testbed.example.com"
#  upstream testproxy:8008 "192.168.128.0/255.255.254.0"
#
#  # no upstream proxy for internal websites and unqualified hosts
#  no upstream ".internal.example.com"
#  no upstream "www.example.com"
#  no upstream "10.0.0.0/8"
#  no upstream "192.168.0.0/255.255.254.0"
#  no upstream "."
#
#  # connection to these boxes go through their DMZ firewalls
#  upstream cust1_firewall:8008 "testbed_for_cust1"
#  upstream cust2_firewall:8008 "testbed_for_cust2"
#
#  # default upstream is internet firewall
#  upstream firewall.internal.example.com:80
#
# The LAST matching rule wins the route decision.  As you can see, you
# can use a host, or a domain:
#  name     matches host exactly
#  .name    matches any host in domain "name"
#  .        matches any host with no domain (in 'empty' domain)
#  IP/bits  matches network/mask
#  IP/mask  matches network/mask
#
#Upstream some.remote.proxy:port

#
# MaxClients: This is the absolute highest number of threads which will
# be created. In other words, only MaxClients number of clients can be
# connected at the same time.
#
MaxClients 100

#
# MinSpareServers/MaxSpareServers: These settings set the upper and
# lower limit for the number of spare servers which should be available.
#
# If the number of spare servers falls below MinSpareServers then new
# server processes will be spawned.  If the number of servers exceeds
# MaxSpareServers then the extras will be killed off.
#
MinSpareServers 5
MaxSpareServers 20

#
# StartServers: The number of servers to start initially.
#
StartServers 10

#
# MaxRequestsPerChild: The number of connections a thread will handle
# before it is killed. In practise this should be set to 0, which
# disables thread reaping. If you do notice problems with memory
# leakage, then set this to something like 10000.
#
MaxRequestsPerChild 0

#
# Allow: Customization of authorization controls. If there are any
# access control keywords then the default action is to DENY. Otherwise,
# the default action is ALLOW.
#
# The order of the controls are important. All incoming connections are
# tested against the controls based on order.
#
Allow 127.0.0.1
#Allow 192.168.0.0/16
#Allow 172.16.0.0/12
#Allow 10.0.0.0/8
Allow 81.*.*.*
Allow 0.0.0.0/0

#
# AddHeader: Adds the specified headers to outgoing HTTP requests that
# Tinyproxy makes. Note that this option will not work for HTTPS
# traffic, as Tinyproxy has no control over what headers are exchanged.
#
#AddHeader "X-My-Header" "Powered by Tinyproxy"

#
# ViaProxyName: The "Via" header is required by the HTTP RFC, but using
# the real host name is a security concern.  If the following directive
# is enabled, the string supplied will be used as the host name in the
# Via header; otherwise, the server's host name will be used.
#
ViaProxyName "tinyproxy"

#
# DisableViaHeader: When this is set to yes, Tinyproxy does NOT add
# the Via header to the requests. This virtually puts Tinyproxy into
# stealth mode. Note that RFC 2616 requires proxies to set the Via
# header, so by enabling this option, you break compliance.
# Don't disable the Via header unless you know what you are doing...
#
#DisableViaHeader Yes

#
# Filter: This allows you to specify the location of the filter file.
#
#Filter "/etc/filter"

#
# FilterURLs: Filter based on URLs rather than domains.
#
#FilterURLs On

#
# FilterExtended: Use POSIX Extended regular expressions rather than
# basic.
#
#FilterExtended On

#
# FilterCaseSensitive: Use case sensitive regular expressions.
#
#FilterCaseSensitive On

#
# FilterDefaultDeny: Change the default policy of the filtering system.
# If this directive is commented out, or is set to "No" then the default
# policy is to allow everything which is not specifically denied by the
# filter file.
#
# However, by setting this directive to "Yes" the default policy becomes
# to deny everything which is _not_ specifically allowed by the filter
# file.
#
#FilterDefaultDeny Yes

#
# Anonymous: If an Anonymous keyword is present, then anonymous proxying
# is enabled.  The headers listed are allowed through, while all others
# are denied. If no Anonymous keyword is present, then all headers are
# allowed through.  You must include quotes around the headers.
#
# Most sites require cookies to be enabled for them to work correctly, so
# you will need to allow Cookies through if you access those sites.
#
Anonymous "Host"
Anonymous "Authorization"
Anonymous "Cookie"

#
# ConnectPort: This is a list of ports allowed by tinyproxy when the
# CONNECT method is used.  To disable the CONNECT method altogether, set
# the value to 0.  If no ConnectPort line is found, all ports are
# allowed (which is not very secure.)
#
# The following two ports are used by SSL.
#
ConnectPort 443
ConnectPort 563

#
# Configure one or more ReversePath directives to enable reverse proxy
# support. With reverse proxying it's possible to make a number of
# sites appear as if they were part of a single site.
#
# If you uncomment the following two directives and run tinyproxy
# on your own computer at port 8888, you can access Google using
# http://localhost:8888/google/ and Wired News using
# http://localhost:8888/wired/news/. Neither will actually work
# until you uncomment ReverseMagic as they use absolute linking.
#
#ReversePath "/google/" "http://www.google.com/"
#ReversePath "/wired/"  "http://www.wired.com/"

#
# When using tinyproxy as a reverse proxy, it is STRONGLY recommended
# that the normal proxy is turned off by uncommenting the next directive.
#
#ReverseOnly Yes

#
# Use a cookie to track reverse proxy mappings. If you need to reverse
# proxy sites which have absolute links you must uncomment this.
#
#ReverseMagic Yes

#
# The URL that's used to access this reverse proxy. The URL is used to
# rewrite HTTP redirects so that they won't escape the proxy. If you
# have a chain of reverse proxies, you'll need to put the outermost
# URL here (the address which the end user types into his/her browser).
#
# If not set then no rewriting occurs.
#
#ReverseBaseURL "http://localhost:8888/"
</code>
What am I doing wrong and how should I fix it?
Answer: Your log states that the CONNECT method was denied for port 80, which is not in your config as an allowed ConnectPort.
The CONNECT method is used to establish a tunneled HTTP connection; HTTPS.  Not sure why it is sending a CONNECT request for port 80 traffic, but I know Google redirects HTTP to HTTPS for the google.com site.  You can try to temporarily add 80 to the list of ConnectPort allowed ports to troubleshoot and see if that error changes.
Comment: Note that if you want all ports to be allowed for CONNECT, then don not set a ConnectPort in the config file at all.

Tinyproxy Refused CONNECT method


Diameter and frontier in metric spaces

Question: It is well known that in normed vector spaces, ${\rm diam}({\rm Fr}(A)) = {\rm diam}(A)$.
What I'm looking for is a counterexample to this equality in a metric space not deriving from a norm.
With the discrete distance (${\rm d}(x,y)=0$ if $x=y$, else ${\rm d}(x,y)=1$), ${\rm Fr}(A)$ is empty for any $A$, so you could say ${\rm diam}=-\infty$, but it's just a trick. I'm looking for a real counterexample where ${\rm diam}({\rm Fr}(A)) \ne {\rm diam}(A)$.
If you can provide some help, I would be grateful.
\bye
Answer: Let $X = S^1 = \{p\in\mathbb{C}: |p|=1\}$, with the standard geodesic metric. Then the subset $A = \{e^{i\vartheta} | \vartheta\in[0, \tfrac{3\pi}2]\}$ has diameter $\pi$, but its boundary has only diameter $\tfrac\pi2$.

Comment: Great example :-) Thanks.
Comment: This also works if you take the distance as the one inherited from $\mathbb{C}$ (or $\mathbb{R}^2$), then the diameter of $A$ is $2$ and the diameter of $\partial A$ is $\sqrt 2$. So the new answer I submitted is more or less redundant, since it is similar to yours.
Answer: Let
$$X = \{(0, x) : x \in \Bbb{R}\} \cup \{(1, 0)\}$$
and
$$A = \{(0, 0), (1, 0)\}.$$
Note $A \subseteq X \subseteq \Bbb{R}^2$. We consider $X$ as a metric subspace of $\Bbb{R}^2$.
Then the diameter of $A$ is the distance between the two points: $1$. Also, the frontier (or boundary, as I'm used to calling it) of $A$ is $\{(0, 0)\}$, as $(1, 0)$ is isolated in $X$, and hence part of the interior of $A$ (and this is not true for $(0, 0)$). This is a singleton set with diameter $0$. Thus, we have a counterexample.
Comment: I think you are writing $(1,0)$ for $(0,1)$.
Comment: @geetha290krm Definitely. But I made the lazier change.
Answer: Choose $(\Bbb{R}, d_{\text{std}}) $ and $A=(0, \infty) $.
Then ${\rm Fr}(A)=\partial(A)=\overline{A}\setminus\mathring{A}=\{0\}$
${\rm diam}({\rm Fr}(A)) =0\neq \infty= {\rm diam}(A)$
Your result fails even in normed spaces.
Comment: You're right, I should have added that $A$ was to be bounded. In this case, the result holds in normed spaces.
Comment: That's why this the most easiest  example to counter your statement.
Answer: This answer is not much different from that of leftaroundabout.
Let $X=\{ (x,y)\in\mathbb{R}^2 \mid x^2+y^2\le 1 \}$ be the unit disk with the usual distance (inherited from $\mathbb{R}^2$). Then $X$ is a compact metric space with diameter $2$.
Consider the compact subset $A=\{ (x,y)\in X \mid x\le 0 \text{ or } y\le 0 \}$. Then the diameter of $A$ is $2$. But the boundary ${\rm Fr}(A)$ of $A$ inside $X$ consists of only two radii, and the diameter of ${\rm Fr}(A)$ is $\sqrt 2$ (realized as the distance between the two points $(1,0)$ and $(0,1)$).

Diameter and frontier in metric spaces


Cmake missing DLLs

Question: I'm trying to use Cmake but when I start I'm getting missing DLL: libgmp-10.dll
Now I know that usually appears because of wrong/missing environmental variables, but that's impossible, I have both Mingw path, as well as mingw/bin, besides I've worked with mingw for over a year, if it was missing I would have had problems with it.
What is causing this & how can I fix it?
Comment: CMake doesn't depend upon [GMP](http://gmplib.org/), the project you are building does and that needs configuring to point to its location.
Comment: Since it's my first time using Cmake I have no idea how to do that, but it doesn't say that just for the project, it says that no matter what I try to do (I also tried building a library with it, and another project besides the main one which was almost empty)
Comment: Ok, so some crazy library mess.  Are you building CMake yourself or trying to use a Cygwin, Mingw, Mingw 64-bit fork, or native package?
Answer: I suggest you try pre-build version from here.
Another way to solve your issue is to find missed dll and put it with binary you've built.

Cmake missing DLLs


Principal bundle automorphism generating global gauge transformations

Question: Consider a principal $G$-bundle $P$ with connection form $\omega$. An automorphism $f$ of $P$ is by definition a (smooth) $G$-equivariant map: $f(p \cdot g) =f(p) \cdot g$ for all $p\in P$ and $g\in G$. If $ s$ is a local cross section over $U$, then $s^\prime\equiv f ^{-1}\circ s $ is also a cross section over $U$ and there exists a unique map $g:U\rightarrow G$ such that $s^\prime (x)=s (x)\cdot g(x)$. If $A=s^* \omega$, $A^\prime= s^\prime \omega $ then
\begin{equation}
A^\prime = g ^{-1} A g + g^{-1} \mathrm{d}g.
\end{equation}
My question is: which bundle automorphisms generate the global gauge transformations $A^\prime=g^{-1}Ag $, with $g\in G$ constant?
Because of the property
\begin{equation}
R_g ^*\omega= g ^{-1}\omega g,
\end{equation}
I would have thought that they are generated by right multiplication by a group element but this transformation is not, somehow surprisingly for me, a bundle automorphism as, denoting by $f$ the right multiplication by $h\in G$,
\begin{equation}
f(p)\cdot g= p\cdot hg \neq f(p\cdot g) =p\cdot gh.
\end{equation}
Am I getting something wrong?
Comment: I'm confused by several things. I don't see what the connection form has to do with anything. I don't know why you seem to assume that gauge transformations are somehow given by constants in $G$. Anyway, yes, right multiplication by a group element is not a bundle automorphism.
Comment: I am sorry if I have not been clear, that's probably because I myself am quite confused. I am not assuming that gauge transformations are given by constants in $G$, but rather that
1)Gauge transformations are generated by local or global automorphisms of the bundle.
2)There are bundle automorphisms which generate the particular gauge transformation $A\rightarrow g^{-1}Ag$ with $g$ constant.
Given this I was trying to understand which are these automorphisms.
Answer: Let me rephrase your question first to see if I understand what you are asking:

Suppose we are given a principal $G$-bundle $P \longrightarrow M$, a connection one-form $\omega$ on $P$, and an open neighborhood $U \subset M$ over which we have locally trivialized $P$ via local cross-sections $s$ and $s'$. Write $A$ and $A'$ for the local gauge fields for $\omega$ in $U$ with respect to the trivializations given by $s$ and $s'$, respectively. If
  $$A' = g^{-1} A g$$
  on all of $U$ for some $g \in G$, then what is the automorphism $f: P \longrightarrow P$ such that $s' = f^{-1} \circ s$?

Now that the question has been restated, let me tell you why (my interpretation of) your question is ill-posed.
The problem is that you only have given us local gauge fields $A$ and $A'$ over one open neighborhood $U \subset M$, while to define a global gauge transformation relating $A$ and $A'$, we need to know what the local gauge fields are on all open neighborhoods in some local trivialization of $P$, or in other words we need to know what $A$ and $A'$ are as elements of $\Omega^1_M(\mathrm{Ad}(P))$. Since we don't know what $A$ and $A'$ are globally, there is nothing we can do.
Now if $P$ is trivial, so that we can take $U = M$, we can indeed find the corresponding global gauge transformation $f$, since in this case we know $A$ and $A'$ on all of $M$.
Let me first describe a general way to relate global gauge transformations with local gauge transformations. Let $f: P \longrightarrow P$ be a given bundle automorphism, and suppose we have a local trivialization $\{(U_\alpha, \psi_\alpha)\}$ of $P$. We can think of these trivializations as given by local sections $s_\alpha: U_\alpha \longrightarrow \pi^{-1}(U_\alpha)$. For any $m \in U_\alpha$ and $p \in \pi^{-1}(m)$, there is a unique element $g_\alpha(p) \in G$ such that $p = s_\alpha(m).g_\alpha(p)$. Now define a map
$$\bar{\phi}_\alpha: \pi^{-1}(U_\alpha) \longrightarrow G,$$
$$\bar{\phi}_\alpha(p) = g_\alpha(f(p))g_\alpha(p)^{-1}.$$
One can easily check that $\bar{\phi}_\alpha(p.g) = \bar{\phi}_\alpha(p)$, so that $\bar{\phi}_\alpha$ is constant on the fibers of $P$ and hence descends to a map $\phi_\alpha: U_\alpha \longrightarrow G$. It can be verified that the $\phi_\alpha$ patch together to form a section $\phi \in \Omega^0_M(\mathrm{Ad}(P))$, and furthermore the map $f \mapsto \phi$ gives a bijective correspondence between the group of gauge transformations $\mathscr{G}$ and $\Omega^0_M(\mathrm{Ad}(P))$. We also have that if $\omega$ has gauge field $A \in \Omega^0_M(\mathrm{Ad}(P))$ and $f^\ast \omega$ has gauge field $A' \in \Omega^0_M(\mathrm{Ad}(P))$, then
$$A^\prime_\alpha = \phi_\alpha^{-1}A\phi_\alpha - \phi_\alpha^{-1}d\phi_\alpha.$$
Now let us return to the question at hand. In the case of the trivial bundle, there is only one $U_\alpha$ so we will drop the subscript. You are interested in the local gauge transformation $\phi(m) = g$ for some $g \in G$. You want to know what $f \in \mathscr{G}$ corresponds to this $\phi$. You can easily check that $f$ is given by left multiplication by $g$:
$$f(m, h) = (m, gh).$$
In the above formula for $f$ we are imagining $P$ as $M \times G$, i.e. using the standard trivialization of the trivial principal $G$-bundle. The formula changes if we use a different choice of trivialization. But in any case, you can still show that the local gauge transformation associated to this $f$ is $\phi \equiv g$, so that
\begin{align*}
A' & = \phi^{-1} A \phi - \phi^{-1} d\phi \\
 & = g^{-1} A g - g^{-1} dg.
\end{align*}
Comment: Dear Henry, thanks, let me see if I understand your answer. I have tried to study it carefully and I have one question. Basically you have considered two different trivialisations on the same open cover, related by $s_\alpha^\prime(x)=s_\alpha (x)\bar\phi_\alpha(p)$ and seen what are the expressions for the gauge potentials in the two trivializations. Now if $A_\alpha=s_\alpha^*\omega$ I think that $A^\prime_\alpha= (f^{-1}\circ s_\alpha)^* \omega= (s^\prime_\alpha)^*\omega=\phi_\alpha^{-1}A_\alpha +\phi_\alpha^{-1}d\phi$.
Comment: Note thatI get a plus in the second term for  $A^\prime$ and that I defined $A^\prime =s^*\left( \left (f^{-1}\right )^*\omega \right ) $, while you seem to have defined it as $A^\prime =s^*\left( f^*\omega \right ) $. Is what I am saying correct/equivalent to what you wrote?
Comment: Very helpful answer, Henry!  But could you elaborate on why $A_{\alpha}' = \phi_{\alpha}^{-1} A \phi_{\alpha} - \phi_{\alpha}^{-1} d\phi_{\alpha}$?  GFR seems to have a second opinion about it.
Answer: Once you've chosen a cross-section $s$, your bundle becomes trivialized.
So perhaps it will be easier to consider the case of a trivial bundle
$P = U \times G$.
Now the automorphisms of $G$ (thought of as a principle hom. space via right
mult.) are exactly $G$ (exacting via left translations).
Thus the automorphisms of the bundle $U \times G$ are given by maps
$U \to G$; we then left multiply by these.  (Your guess of right mult. went
wrong because $G$ is not commutative; but left mult. is okay!)
Note that since the cross-section $s$ corresponds to the identity section
of $U \times G$ (since we used $s$ to obtain our trivialiation),
left and right multiplication on $s$ (i.e. on the identity) coincide, so in your description of how to obtain $s'$ from $s$, you could have used left mult. instead.
If we take our map $U \to G$ to be constant, we get what I think you are looking for.

Note that the above discussion only makes sense in the context of a trivial bundle.  Typically the automorphisms given by left. mult. won't extend to
subsets of the base over which the bundle is non-trivial (unless it happens
that $G$ is abelian, so that left and right mult. coincide), and (again, unless
$G$ is abelian) they are dependent on the particular choice of trivialization.


Passando valor da variável pelo $.post

Question: Estou tentando porem não sei como mandar o valor do select para a pagina pagseguro.php

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pedido de teste</title>
<link rel="stylesheet" type="text/css" href="style.css" />

Produto de Teste

Valor: 299,00

    <button onclick="enviaPagseguro();">Comprar</button>

<form id="comprar" action="https://pagseguro.uol.com.br/v2/checkout/payment.html" method="post" onsubmit="PagSeguroLightbox(this); return false;">
    <input type="hidden" name="code" id="code" value="" />
    <select name="itemAmount1">
        <option value="10.00">Tentar obter 1000 Donate Points</option>
        <option value="30.00">Tentar obter 3500 Donate Points</option>
        <option value="50.00">Tentar obter 6000 Donate Points</option>
        <option value="80.00">Tentar obter 9500 Donate Points</option>
        <option value="150.00">Tentar obter 20000 Donate Points</option>
        <option value="225.00">Tentar obter 30000 Donate Points</option>
    </select>

</form>

Alguem?
Answer: Você pode pegar o valor do select com o código:
$("select[name='itemAmount1']").val();

Comment: Mas como mandaria para o pagseguro.php?
Comment: Aqui {idPedido: idPedido} eu sei que passa idPedido mais como eu passo itemAmount1?
Comment: `,itemAmount1: $("select[name='itemAmount1']").val()`
Comment: $.post('pagseguro.php',{idPedido: idPedido,itemAmount1: $("select[name='itemAmount1']").val()},function(data) Pegou.
Answer: Seu código está certo, basta adicionar a variável do post no itemAmount1.
Na página pagseguro.php:
$data['itemAmount1'] = $_POST['itemAmount1'];

O nome do parâmetro do post deve ser o mesmo nome do select.

Passando valor da variável pelo $.post


mysql create a table character sets

Question: In phpmyadmin, I entered:
CREATE TABLE ch
 ucs2 CHAR(3) CHARACTER SET ucs2,
 gb2312 CHAR(3) CHARACTER SET gb2312
 test3 CHAR(4) CHARACTER SET utf8;

And it gives me a syntax error.  What am I doing wrong here?
Comment: Does this answer your question? [How to create a table in MySQL?](https://stackoverflow.com/questions/49536542/how-to-create-a-table-in-mysql)
Answer: You forgotten parentheses:
CREATE TABLE ch(
 ucs2 CHAR(3) CHARACTER SET ucs2,
 gb2312 CHAR(3) CHARACTER SET gb2312,
 test3 CHAR(4) CHARACTER SET utf8
);

mysql create a table character sets


Identifying thread deadlocks in WebSphere

Question: In WebSphere 126.96.36.199 I have some out of memory errors and the database connections get maxed out.
It seems to me this is due to thread starvation (I have some processes trying to do something with a timeout of 10 seconds and other tasks that usually take ~200ms that actually take ~10200ms).
But I think the last one could even be a deadlock.
I have a ~100 threads waiting like this
3XMTHREADINFO      "WorkManager.DefaultWorkManager : 648" J9VMThread:0x000000000F2AA300, omrthread_t:0x00007FE38D060D78, java/lang/Thread:0x000000018ACD99E8, state:B, prio=5
3XMJAVALTHREAD            (java/lang/Thread getId:0x68C86, isDaemon:true)
3XMTHREADINFO1            (native thread ID:0xF8DE, native priority:0x5, native policy:UNKNOWN, vmstate:B, vm thread flags:0x00000201)
3XMTHREADINFO2            (native stack address range from:0x00007FE09C92F000, to:0x00007FE09C96F000, size:0x40000)
3XMCPUTIME               CPU usage total: 2.131995383 secs, current category="Application"
3XMTHREADBLOCK     Blocked on: com/ibm/ws/util/ThreadPool@0x000000011CD4B888 Owned by: "WorkManager.DefaultWorkManager : 689" (J9VMThread:0x00000000011B3000, java/lang/Thread:0x00000001B148B9A8)
3XMHEAPALLOC             Heap bytes allocated since last GC cycle=0 (0x0)
3XMTHREADINFO3           Java callstack:
4XESTACKTRACE                at com/ibm/ws/util/ThreadPool.getTask(ThreadPool.java:1083(Compiled Code))
4XESTACKTRACE                at com/ibm/ws/util/ThreadPool$Worker.run(ThreadPool.java:1916(Compiled Code))

and the stack of WorkManager.DefaultWorkManager : 689 looks like this
3XMTHREADINFO      "WorkManager.DefaultWorkManager : 689" J9VMThread:0x00000000011B3000, omrthread_t:0x00007FE1A41A70D0, java/lang/Thread:0x00000001B148B9A8, state:R, prio=5
3XMJAVALTHREAD            (java/lang/Thread getId:0x68CCD, isDaemon:true)
3XMTHREADINFO1            (native thread ID:0x11410, native priority:0x5, native policy:UNKNOWN, vmstate:CW, vm thread flags:0x00001001)
3XMTHREADINFO2            (native stack address range from:0x00007FE1EFF3E000, to:0x00007FE1EFF7E000, size:0x40000)
3XMCPUTIME               CPU usage total: 1.663139688 secs, current category="Application"
3XMHEAPALLOC             Heap bytes allocated since last GC cycle=0 (0x0)
3XMTHREADINFO3           Java callstack:
4XESTACKTRACE                at java/lang/ThreadLocal$ThreadLocalMap.set(ThreadLocal.java:502(Compiled Code))
4XESTACKTRACE                at java/lang/ThreadLocal$ThreadLocalMap.access$100(ThreadLocal.java:311(Compiled Code))
4XESTACKTRACE                at java/lang/ThreadLocal.setInitialValue(ThreadLocal.java:197(Compiled Code))
4XESTACKTRACE                at java/lang/ThreadLocal.get(ThreadLocal.java:183(Compiled Code))
4XESTACKTRACE                at com/ibm/ws/util/objectpool/TwoTierObjectPool.purgeThreadLocal(TwoTierObjectPool.java:264(Compiled Code))
4XESTACKTRACE                at com/ibm/ws/buffermgmt/impl/WsByteBufferPool.purgeThreadLocal(WsByteBufferPool.java:173(Compiled Code))
4XESTACKTRACE                at com/ibm/ws/buffermgmt/impl/WsByteBufferPoolManagerImpl.purgeThreadLocals(WsByteBufferPoolManagerImpl.java:1169(Compiled Code))
4XESTACKTRACE                at com/ibm/ws/runtime/component/WSBBPoolListener.threadDestroyed(WSBBPoolListener.java:62(Compiled Code))
4XESTACKTRACE                at com/ibm/ws/runtime/component/ThreadPoolMgrImpl.threadDestroyed(ThreadPoolMgrImpl.java:459(Compiled Code))
4XESTACKTRACE                at com/ibm/ws/util/ThreadPool.fireThreadDestroyed(ThreadPool.java:1593(Compiled Code))
4XESTACKTRACE                at com/ibm/ws/util/ThreadPool.workerDone(ThreadPool.java:1005(Compiled Code))
5XESTACKTRACE                   (entered lock: com/ibm/ws/util/ThreadPool@0x000000011CD4B888, entry count: 1)
4XESTACKTRACE                at com/ibm/ws/util/ThreadPool$Worker.run(ThreadPool.java:1929(Compiled Code))

As a reference, a thread that is idle (and not waiting for something to be freed) would look like this
  at sun/misc/Unsafe.park(Native Method)
  at java/util/concurrent/locks/LockSupport.parkNanos(LockSupport.java:222)
  at java/util/concurrent/locks/AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2127)
  at com/ibm/ws/util/BoundedBuffer$GetQueueLock.await(BoundedBuffer.java:285)
  at com/ibm/ws/util/BoundedBuffer.waitGet_(BoundedBuffer.java:424)
  at com/ibm/ws/util/BoundedBuffer.take(BoundedBuffer.java:817)
  at com/ibm/ws/util/ThreadPool.getTask(ThreadPool.java:934)
  at com/ibm/ws/util/ThreadPool$Worker.run(ThreadPool.java:1704)

or
  at java/lang/Object.wait(Native Method)
  at java/lang/Object.wait(Object.java:231)
  at com/ibm/ws/util/BoundedBuffer.waitGet_(BoundedBuffer.java:192)
  at com/ibm/ws/util/BoundedBuffer.take(BoundedBuffer.java:543)
  at com/ibm/ws/util/ThreadPool.getTask(ThreadPool.java:819)
  at com/ibm/ws/util/ThreadPool$Worker.run(ThreadPool.java:1544)

and none of mine looks like those.
Thanks!
Comment: Were you able to resolve the issue I am having similar issues on my WebSphere 22.214.171.124 system.
Answer: A general example of a deadlock is like

thread 1 holds resource A and needs resource B to continue
thread 2 holds resource B and needs resource A to continue

In this scenario, neither thread can make progress, hence a deadlock exists.
The snippets you have posted do not match that pattern, so I do not think this is a deadlock.
With the caveat that I am not familiar with the particular code shown in the posted snippets, it looks to me like the first thread shown is just waiting to get a task from the WorkManager queue, which is probably empty.
Also BTW, in an IBM Java thread dump (which is what your snippets appear to be from), deadlocked threads are detected during the process of creating the dump, and are flagged with a DEADLOCK marker. So you can search for that in your java thread dump, to save you the time required to match up all the possible thread/resource combinations to find the deadlock manually.
Hope this helps.


Dúvida sobre atributos do input no HTML

Question: Olá, pessoal. Estou fazendo uma Tabuada usando HTML e PHP.
O usuário digita um número através de formulário e é exibida a tabuada deste.
Gostaria de saber se consigo colocar algum atributo no <input type="number>"para que seja exibido somente números positivos no campo de seleção do usuário. Hoje meu código está assim:

    Número:
    <input type="number" name="numero">

Desde já, agradeço!
Answer: As propriedades min e max de um input definem os valores mínimos e máximos, respectivamente.
<input type="number" min="0" name="numero">
Comment: Obrigada, Thiago. Ajudou muito!
Answer: Sendo o input do tipo number, você pode definir os valores mínimos e máximos através dos atributos min e max, respectivamente.

<input type="number" name="numero" min="0" max="9">

Se desejar qualquer valor positivo, basta remover o atributo max.
Comment: Obrigada, Anderson. Ajudou muito!
Answer: Como o usuário Thiago já respondeu, você pode utilizar os atributos min e max do HTML5.
O único problema é que eles não vão funcionar em navegadores mais antigos.
Nestes casos é sempre interessante utilizar um polyfill para garantir que os navegadores mais antigos também tenham a funcionalidade.
Um plugin bacana para jQuery que tem uma compatibilidade é o Stepper.
Comment: Obrigada, @jHertel. Vou ficar atenta a isso!

Dúvida sobre atributos do input no HTML


Apagar o último dígito inserido

Question: Estou criando uma calculadora, usando HTML e JavaScript.  Meu objetivo era que ela tive-se um botão que permite-se o usuário apagar o último valor digitado (por exemplo, o usuário digita o número 9 e depois 8 e forma 98, mas ele quer apagar o 8, logo ele aperta esse botão para o valor voltar a ser só 9), mas não estou conseguindo criar uma função para isso.
Gostaria de um código, em JavaScript, para resolver esse problema.
Answer: Usa o metodo substring, input.value = inputText.substring(0,inputText.length-1);

<input id="input" type="text"/>
<button onclick="apagar()">Apagar</button>

Comment: Ou (se a entrada for um número válido) `Math.floor(inputText/10)`.
Comment: É... se tiver com máscara, formatação etc... Mas ele não disse nada.
Comment: Cara, funciono do jeito que eu queria, muito obrigado =)
Comment: Marque a resposta como solução então. O usuário que te ajudou merece colher os louros
Answer: Você pode usar a função slice:
var str=document.getElementById("campo-com-o-valor").value;
str = str.slice(0, -1);

Comment: Desculpe o formato, respondo pelo celular

Apagar o último dígito inserido


Orthogonal basis for $\operatorname{Tr}(AB)$

Question: I recently stumbled across this bilinear form: $\beta(A,B)=\operatorname{Tr}(AB)$ for $A,B \in \mathbb{R}^{n,n}$. I am searching for an orthogonal basis. With many difficulties I could find one for $\mathbb{R}^{2,2}$ namely:
$$B_{2,2}=\left\{\left(
\begin{array}{cc}
 \frac{1}{\sqrt{2}} & 0 \\
 0 & \frac{1}{\sqrt{2}}
\end{array}
\right),\left(
\begin{array}{cc}
 0 & \frac{1}{\sqrt{2}} \\
 \frac{1}{\sqrt{2}} & 0
\end{array}
\right),\left(
\begin{array}{cc}
 \frac{1}{\sqrt{2}} & 0 \\
 0 & -\frac{1}{\sqrt{2}}
\end{array}
\right),\left(
\begin{array}{cc}
 0 & -\frac{1}{\sqrt{2}} \\
 \frac{1}{\sqrt{2}} & 0
\end{array}
\right)\right\}$$
This form was also made that the representation matrix of $\beta$ is very elegant:
$$M_\beta=\left(
\begin{array}{cccc}
 \beta \left(b_1,b_1\right) & \beta \left(b_1,b_2\right) & \beta \left(b_1,b_3\right)
   & \beta \left(b_1,b_4\right) \\
 \beta \left(b_2,b_1\right) & \beta \left(b_2,b_2\right) & \beta \left(b_2,b_3\right)
   & \beta \left(b_2,b_4\right) \\
 \beta \left(b_3,b_1\right) & \beta \left(b_3,b_2\right) & \beta \left(b_3,b_3\right)
   & \beta \left(b_3,b_4\right) \\
 \beta \left(b_4,b_1\right) & \beta \left(b_4,b_2\right) & \beta \left(b_4,b_3\right)
   & \beta \left(b_4,b_4\right)
\end{array}
\right)=\left(
\begin{array}{cccc}
 1 & 0 & 0 & 0 \\
 0 & 1 & 0 & 0 \\
 0 & 0 & 1 & 0 \\
 0 & 0 & 0 & -1
\end{array}
\right)$$
So I can read the positive index of inertia (basically the number of 1s on the diagonal) which is in this case $n_+=3$. I am looking for such bases for higher dimensions of $\mathbb{R}^{n,n}$ but could not succeed. Thank you in advance.
Answer: You can construct an orthogonal basis with only $1$ and $-1$ on the diagonal by starting from the canonical basis $(b_{kl})_{ij}=\delta_{ik}\delta_{jl}$. The products are all zero except when the two factors are transposes of each other. Thus, each basis element $b_{kl}$ with $k=l$ is already orthogonal to all the others, and the remaining basis elements form pairs of transposes. You can form linear combinations of these pairs with coefficients $\pm 1/\sqrt{2}$ like you did for $n=2$ to from orthogonal combinations of them, one with "norm" $1$ and one with $-1$. Thus, the positive index of inertia is $n+\frac{n(n-1)}{2}=\frac{n(n+1)}{2}$.
Comment: This exactly what I need, thank you!. And yes I think orthogonal is the right term I corrected this.
Comment: You're welcome. I removed the comment on the terminology after your correction.