text:
Q: How to say that something is the same regarding each pair in a group of different pairs of things? They are two scenarios that I am comparing. Each scenario has 2 variation that slightly differ from one another. The first variation of the first scenario parallels the first variation of the second scenario, and the second variation of the first scenario parallels the second variation of the second scenario. The number of people involved in each variation in each scenario is the same as the number of people involved in its counterpart in the other scenario.
Now I want to say the content of the last sentence differently as something as

The number of involved people are the same in each of the paralleling variations.

or

The number of involved people are the same in each pair of the
  paralleling variations.

Which way of saying the strong part is correct/preferred? Or maybe both are problematic?

A: So I might understand this in one reading, I would state the situation:
There are 2 scenarios, 1 and 2. Each scenario has 2 variations, 1.1 and 1.2 for scenario 1, and, 2.1 and 2.2 for scenario 2. Variations 1.1 and 1.2 complement scenario 1, respectively the same as variations 2.1 and 2.2 complement scenario 2.
So

The number of people involved in the two sets of complementary variations are the same, respectively.

I understand there can be other solutions. This one sets well with me, so I offer  it in hope it will help.


text:
Q: On page refresh on click mute button is not working for audio I have a simple section with video-tag, I have added audio as background to this section, I want on click muted button the sound should play on the background
The problem:
I mean the audio plays only when user clicks muted-btn, at first everything works fine but when I refresh the page and click muted-btn the video plays but the audio on the background is not playing, but when I hit ctrl + shift + r and click the muted-btn button the audio is playing, the problem is when u normal refresh the page and click the muted-btn audio is not playing.
Note: the video sound is playing but not the audio on the background (music beat)
Here is HTML
 <audio id="audioplayer" playsinline controls muted loop autoplay hidden>
            <source src="audio/muzyka_meed_loop.mp3" type="audio/mpeg">
            Your browser does not support the audio element.
   </audio>

Here is button for mute and unmute the audio on click
   mutedbtn.on("click", function () {
        if ($("#audioplayer")[0].muted == true) {
            $("#muted-btn").removeClass("muted");
            $("#audioplayer")[0].muted = false;
        } else {
            $("#muted-btn").addClass("muted");
            $("#audioplayer")[0].muted = true;
        }
    });

Here is live demo : live demo
What am I doing wrong in my code?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Serial communication read line C++ I want to read a line from serial with Symbian C++ but to do that I have to continue reading into a buffer until I reach "/n". I have no idea how to do this though. This is actually a Python project but I am trying to create a C++ library with with the neccesary functions ported from PySerial. Al I still have to port is "readline though.
Here is the original Python code for it:
def readline(self, size=None, eol=LF):
     """read a line which is terminated with end-of-line (eol) character
     ('\n' by default) or until timeout."""
     leneol = len(eol)
     line = bytearray()

     while True:
         c = self.read(1)
         if c:
             line += c
             if line[-leneol:] == eol:
                 break
             if size is not None and len(line) >= size:
                 break
         else:
             break
     return bytes(line)

My library is based on PyS60USB which has already implemented the following to read at least one byte:
TUint8* buf = 0;
TPtr8 tmp(buf, 0);
TInt err;
TBool alloc_ok = EFalse;

Py_BEGIN_ALLOW_THREADS;
TRAP(err,
   buf = (TUint8*) User::AllocLC(1);
   tmp.Set(buf, 0, 1);
   alloc_ok = ETrue;
   self->iConnManager->RecvL(tmp, timeout);
   CleanupStack::Pop(buf);
   );
Py_END_ALLOW_THREADS;

My question though is now, how can I translate the afore mentioned Python code to Symbian C++ code that can add all the read bytes to a buffer and continously check the buffer for eol?
Thanks, all help will be greatly appreciated.


text:
Q: Jquery Get Text of Nested Selector not child How To Access keyword-text e.g java On click keyword-remove class.
First Of all it's outside keyword-remove scope can not use $(this).
I want to access nested selector span text.

  java

$(document).on("click",".keyword-remove", function(){

});

A: As the click event is on the span, it cannot be empty. If it is empty you cannot click it. After entering some data in the span select the sibling span using the siblings function and print the textContent. Alternatively .next can be used instead of siblings

$(document).on("click",".keyword-remove", function(){
   console.log($(this).siblings('span')[0].textContent)
   });

First span java

A: use next() to select the next sibling of the element you clicked.

$(document).on("click",".keyword-remove", function(){
  console.log($(this).next('.keyword-text').text())
});

  REMOVE
  java

A: You can use the following code block -
$(document).on("click",".keyword-remove", function(){
  console.log($(this).next().find('.keyword-text').text())
});

Working Example -
https://jsfiddle.net/0wmnxdrp/1/

A: Personally I would use closest() paired with a following find().  The reason being, this removes the positional logic from the equation, and you only rely on the parent child relationship.

$(document).on("click",".keyword-remove", function(){
  console.log($(this).closest('.keyword').find('.keyword-text').text());
});

  X
  java


text:
Q: Regex - Capture multiple multiline text blocks with only a starting pattern I have a very large text file with several entries like this:
    -------------------------------------

       LOTS OF
        MULTILINE
       TEXT

    *************************************
              MORE
       MULTILINE
         TEXT

    *************************************

       EVEN-MORE-TEXT-SOMETIMES-WITH-DASHES

    *************************************

    -------------------------------------

       2ND LOT OF
        MULTILINE
       TEXT

    *************************************
      MORE
       MULTILINE
         TEXT FOR 2ND LOT

    *************************************

       EVEN-MORE-TEXT-FOR-2ND

    *************************************

Note that these are only two entries, I don't care about the asterisks, but the text that follows the dashed line.
I want to get a capture group with all the text in each entry so that I can analyze it later line by line.
I can capture the first entry with an expression like this:
/-{37}\s*([\s\S]+)-{37}/gm
But I'm having trouble running the capture group several times because I don't have a clear terminator for the groups (since the *{37} appears several times)
Here's a regex 101 example:
https://regex101.com/r/XZQ5h6/1
How can I capture the text after the dashed line but before the next dashed line or the end of the file?
Edit:
So to make my question clearer, the capture group I would expect for the first entry would be.
   LOTS OF
    MULTILINE
   TEXT

*************************************
          MORE
   MULTILINE
     TEXT

*************************************

   EVEN-MORE-TEXT-SOMETIMES-WITH-DASHES

*************************************

I also happen to have some dashes in the text, so I have edited the example. Ideally, I want an array of capture groups with just the content in the entries.

A: You can use this regex:
-{37}\R+((?:.+\R)+)

RegEx Demo
RegEx Detail;

*

*-{37}: Match hyphen of 37 in length

*\R+: Match 1+ of line breaks

*(: Start capture group

*

*(?:.+\R)+: Match a line of 1+ character followed by a line break. Repeat this group 1+ times to match multiple of these lines

*): End capture group

A: This regex will match both entries:
/-{37}[^-]+/gm

Try it out in regex101.

A: If you want to capture the 2 parts in the example data in a capture group:
^-{37}\s*^((?:(?!--).*(?:\r?\n|$))+)

In parts, the pattern matches:

*

*^ Start of string

*-{37} Match 37 times a - char

*\s*^ Match optional whitespace chars, and assert start of string (note to use the multiline flag due to the anchors)

*( Capture group 1

*

*(?: Non capture group

*

*(?!--) Negative lookahead, assert not -- at the start of the string (or make it more specific like (?!-{37}\r?\n))

*.*(?:\r?\n|$) Match the whole line followed by a newline or assert the end of the string

*)+ Close non capture group 1+ times

*) Close group 1

Regex demo
Or a bit shorter, but then it would include the leading whitespace chars in the match:
^-{37}((?:\r?\n(?!--).*)*)

Regex demo


text:
Q: How to zoom a selected area on screen recording I am using camtasia studio for screen record. for small portion of my screen I want to zoom camera/recording area.
How can I zoom area when recording?

A: I just had the same need. I wanted to zoom in on an increasing counter in a callout window. I wanted the zoomed in "callout" to be perfectly synchronized with the actual video that was running.
I clipped the video I wanted zoomed in and put it in exactly the same location on an additional track above. Then, I copied the clip to a new project. Using the pan and zoom tools, I created a smaller video of just what I wanted by selecting the video size and positioning the pan window after setting my zoom.
It was easy to produce the video to a new WMV file and import that back into my original project. I used the copied clip as a guide of where to place the zoomed in video on the timeline. Finally, I removed the copied clip from the timeline because I no longer needed it.
For my needs, all I did was add a drop shadow to the zoomed callout and it was perfectly synchronized to my master video. A little fade in/fade out animation completed the polished effect.
Hope this helps.


text:
Q: Android can't run UI Testing with "uiautomator: permission denied" error message My environment is:
Android phone : HTC Desired Z
Android version: 2.3.3
when i use the web method:http://developer.android.com/tools/testing/testing_ui.html
run the UI Testing with the command "adb shell uiautomator runtest LaunchSettings.jar -c com.uia.example.my.LaunchSettings"
it show the error message "uiautomator: permission denied" .
Anyone friend that tell me to the reason of error???
thank!~

A: Can you double-check a couple of things please?

*

*Which version of Android are you deploying the tests to? UIAutomator is only available on devices with API level 16 or later (Android 4.1 and 4.2) so it should not be available on a 2.3.3 device. Run the following command on a command-line to get the version of Android installed: adb shell grep ro.build.version.sdk= system/build.prop the result should be similar to ro.build.version.sdk=17 Here is a StackOverflow article on getting the version of Android using adb shell Getting Android SDK version of a device from command line

*What is the precise error message do you get when you run the adb shell uiautomator runtest LaunchSettings.jar -c com.uia.example.my.LaunchSettings command?

I tested with an AVD running 2.3.3 (API level 10) and ran the commands to build, deploy and then run the UI Automator tests from the Android example from http://developer.android.com/tools/testing/testing_ui.html  The error message I get is different from the one you report: I get uiautomator: not found rather than permission denied.
As a suggestion, try to run uiautomatorviewer from the command line when your device is connected (which you can check with the adb devices command - your device's serial number should be listed). When I run uiautomatorviewer against the AVD with 2.3.3 when I try to get a screen snapshot it tells me explicitly "UI Automator requires a device with API Level 16"
So in summary, AFAIK you need uiautomator with a device running API level 16 or later. In practice, UI Automator seems to be problematic on API level 16 (Android 4.1) and works best with devices running 4.2.1 of Android (API level 17).


text:
Q: Generic classes in "frameworkname"-Swift.h causes "Type name requires a specifier or qualifier" error in Xcode 6.3 I updated to Xcode 6.3, and I had two separate projects (one is a framework) in my workspace. Now, Xcode autogenerated this "frameworkname"-Swift.h header file, but when I had a generic class as a property, it produces the following lines:
@class Presentation;
SWIFT_CLASS("_TtC13BusinessLogic31MeetupDetailViewControllerModel")
@interface MeetupDetailViewControllerModel : NSObject
@property (nonatomic) /* RsvpStore<Rsvp> */ anRsvpStore;
@end

There is no equialent to gerenics in Objective-c, so how can I solve this problem?
I found that I can solve the problem if I set the type to NSObject like:
@property (nonatomic) NSObject * __nonnull anRsvpStore;

but with every build, this file is recreated to the same wrong version. So how can I force this build to set the type of this generic to NSObject?

A: I could stop creating this compatibility header by setting in Build Settings -> Swift Compiler - Code Generation -> Intall Objective-C Compatibility Header to No.
Since I've not written Objective-C code in my project, there is no problem with this option, but this is rather a workaround than a solution for generics in the compatibility header.
Another workaround is if you mark your properties with private, then they won't appear in the compatibility header.
Swift 2.0 update

A new
  @nonobjc
  attribute is introduced to selectively suppress ObjC export for instance members that would
  otherwise be
  @objc
  . (16763754)
  Blockquote

Not tested, but this looks like a solution.

A: I solved in #1873 https://github.com/realm/realm-cocoa/issues/1873
If you don't need to use swift in objc,just set Intall Objective-C Compatibility Header to No.
If you need to use swift in objc,you have to edited the -Swift.h and set it in Objective-C Generated Interface Header Name


text:
Q: Multidimensional array showing duplicate values I'm adding values to a multidimensional array using loops
var leg_array = {};
var enc_array = [];

for (var c = 0; c < result.routes[0].legs.length; c++) {
    leg_array[c] = {};

    for (var b = 0; b < result.routes[0].legs[c].steps.length; b++) {
        //var lat_lngs = result.routes[0].legs[c].steps[b].encoded_lat_lngs;  //encoded polyline representation
        var start_location_A = result.routes[0].legs[c].steps[b].start_location.A;
        var start_location_F = result.routes[0].legs[c].steps[b].start_location.F;

        var end_location_A = result.routes[0].legs[c].steps[b].end_location.A;
        var end_location_F = result.routes[0].legs[c].steps[b].end_location.F;

        enc_array[b] = start_location_A + "," + start_location_F + ":" + end_location_A + "," + end_location_F;
        leg_array[c] = enc_array;

    }
}

console.log(leg_array);

When i check the console log, the arrays in the first level of the multi dimensional array are identical.
How can i solve this?   Values of enc_array are duplicate in every leg_array
e.g.  leg_array[0] = enc_array, leg_array[1] = enc_array
enc_array is the same when the values should be different.

A: You are referencing the same array multiple times. If you want to create different arrays for each leg_array[c] value, use the Array.prototype.slice method instead:
leg_array[c] = enc_array.slice()

This will create a new copy of enc_array (in it's current form) to store in leg_array[c].
Of course, if you do that in the current location, it will set that same value multiple times (because it's inside the loop). Moving it to be inside the outer for loop will probably get the result you want.


text:
Q: Restangular: can I do Restangular.one('resource').get('123') to achieve GET /resource/123? Because earlier in my service I did: var somethingResource = Restangular.one('somethings') and in my getSomethings method I wanted to do somethingResource.getList() and in my getSomethingById methid I wanted to do 'somethingResource.get('123')' to achieve GET /somethings/123

A: Yes, it works.  Doing Restangular.one('resource').get('123') works to achieve GET /resource/123


text:
Q: Html form, how to send data by traditional post and jquery ajax to various servers at the same time I want to save html form data in my server and to an another server. For this data is sending by traditional post (refreshing the page) to local server and also by jquery ajax post (or javascript) to the remote server. The html form:
<!DOCTYPE HTML>

PHP Form Validation Example

* required field

<form method="post" id="registration" action="receiver1.php">
  Name: <input type="text" id="nameq" name="name" value="">
  *

  E-mail: <input type="text" id="email" name="email" value="">
  *

  Website: <input type="text" id="website" name="website" value="">

  Comment: <textarea id="comment" name="comment" rows="5" cols="40"></textarea>

  Gender:
  <input type="radio" id="gender" name="gender" value="female">Female
  <input type="radio" id="gender" name="gender" value="male">Male
  <input type="radio" id="gender" name="gender" value="other">Other
  *

        <input type='image' src='image/submit_button.jpg'>

</form>

here action="receiver1.php" is file in my server http://localhost/receiver1.php. I make handler on input type='image', e.js:
$(document).ready(function() {
    $("table tr input:image").click(function() {
        var cln = $("#nameq").val();
        $.post("https://remote-server/receiver2.php", {"cln": cln});
    });
});

https://remote-server/receiver2.php is file in an another server. But it does not work, I can't receive data in remote server. Have someone a perfect solution for this problem? Thanks in advance

A: Cross domain security probably stopping you doing this. You could post to one host and have that host use Curl to update the second host.


text:
Q: C# target host name for SSL/TLS (HTTPS) is always empty I have created a C# Web Server and I have some problems with the SSL/TLS certificates.
For the setup I have changed my /etc/hosts file for that any request to example.com will direct
to localhost. After that I have created a TCP server which works quite as expected. For the
HTTPS I added a System.Net.Security.SslStream layer with a default self-signed certificate which
also works as expected.
But for now I want to send a certificate that depends on the location the user requests. My server
code is like this:
var stream = new SslStream(
    innerStream: client.GetStream(),
    leaveInnerStreamOpen: false,
    userCertificateValidationCallback: null,
    userCertificateSelectionCallback: LocalCertificateSelection
);
stream.AuthenticateAsServer(
    // I am forced to provide a default certificate. null will throw an error
    serverCertificate:          Settings.Certificate,
    clientCertificateRequired:  false,
    enabledSslProtocols:        SslProtocols.None,
    checkCertificateRevocation: true
);

private X509Certificate LocalCertificateSelection(
    object sender,
    string targetHost,
    X509CertificateCollection localCertificates,
    X509Certificate remoteCertificate,
    string[] acceptableIssuers
)
{
    // at this point: targetHost == null && acceptableIssuers.Length == 0
    return Settings.Certificate;
};

But if I open the page in Firefox or in curl the targetHost and acceptableIssuers from my
certificate selection callback are always empty.
How am I supposed to get the host name to provide the correct certificate?
Edit 1:
My library is targeted for .Net Standard 2.1. Maybe this will help.
Edit 2:
I have added the certificate to the key store of the server (as it was mentioned in a comment), but this wont resolve the problem:
using var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadWrite);
store.Add(Settings.Certificate);

After that I have captured some packages with Wireshark and I have noticed the following:

*

*After TCP connection is finished:

*Client sends a TLS Hello request with a valid SNI extension (here is the host name I want to get)

*Debugger break point in my code is called. The SslStream tries to get a valid certificate: targetHost and acceptableIssuers are empty.

*Server sends the default certificate with possible invalid host name


text:
Q: what's the defference betwwen Firefox and Chrome? I want it works,but it only works on Chrome, in firefox and IE, it alert nothing,this's my code:
    var name;
function say() {
    alert(name);
}
function execute(someFunction, value) {
    name = value;
    someFunction;
}
execute(say(), "Hello");

A: The code is clearly wrong:
execute(say(), "Hello");

This passes the return value of say() to execute. However, you want to pass the function, so use execute(say, "Hello"); and in that function use someFunction() to execute it.

Even though it probably/hopefully doesn't matter anymore, the code does work in Firefox - it alerts undefined since say() is executed before execute() runs. The same thing happens in Chrome - however, it uses an empty alert box instead of showing the string undefined since apparently chrome (or at least its developer console) has a global variable ?name? defined by default which is an empty string.


text:
Q: Codeigniter handling errors in Model and Controller I'm trying to handling errors in Model and then pass them to Controller, but I can't catch the error in the Controller, I'm sure I'm doing some errors, but I don't know where.
[UPDATE]
Fixed errors.
public function updateOpera($image_id, $title, $author, $year, $annotation)
{
    try
    {
        $conn = $this->oracle_connect();
        $author = 50;
        $procedure = "pck_opere.updateOpera(:p_image_id, :p_title, :p_author, :p_year, :p_annotation);";
        $sql = oci_parse($conn, "DECLARE obj INTEGER; begin obj := {$procedure} end;");
        oci_bind_by_name($sql, ':p_image_id', $image_id, -1, OCI_B_INT);
        oci_bind_by_name($sql, ':p_title', $title, -1, SQLT_CHR);
        oci_bind_by_name($sql, ':p_author', $author, -1, OCI_B_INT);
        oci_bind_by_name($sql, ':p_year', $year, -1, OCI_B_INT);
        oci_bind_by_name($sql, ':p_annotation', $annotation, -1, SQLT_CHR);
        $ex = oci_execute($sql);
        if($ex == 1)
        {
            oci_commit();
            return true;
        }
        else
            throw new Exception('Update failed');
    }
    catch (Exception $e)
    {
        throw new Exception($e->getMessage());
    }
    $this->oracle_close($conn);
}

And here there is the Controller:
    public function edit_validation()
    {
        try
        {
            // CONTROLLO SE L'UTENTE E' LOGGATO
            if($this->session->userdata('logged_in') == FALSE )
                redirect(base_url().'index.php/account/login');
            else
            {
                if(isset($_POST['submit']))
                {
                    // RICEVO E SETTO VARIABILI
                    $image_id = $_POST['id'];
                    $title = $_POST['title'];
                    $author = $_POST['author'];
                    $year = $_POST['year'];
                    $annotation = $_POST['annotation'];
                    // CONTROLLO VALIDITA' VARIABILI
                    if($image_id != null && $title != null && $author != null && $year != null)
                    {
                        $this->load->model('opere_model');
                        $updateOpera = $this->opere_model->updateOpera($image_id, $title, $author, $year, $annotation);
                        if($updateOpera)
                            redirect(base_url().'index.php/opere/show/'.$image_id);
                    }
                    else
                        $this->load->view('edit_opera_view', $data['error'] = "Please fill out mandatory fields.");
                }
                else
                    $this->load->view('edit_opera_view', $data['error'] = "An error occurred. Please try to perform your changes later.");
            }
        }
        catch(Exception $e)
        {
            $data['error'] = $e->getMessage();
            // CARICO VISTE
            $this->load->view('header');
            $this->load->view('menu');
            $this->load->view ('edit_opera_view', $data);
        }
    }


text:
Q: DOM element loads before the data is passed into the controller I have a factory which makes a call to the API using AJAX like so
App.factory("DashboardData", function($q) {

method = 'POST';

var fetchDataFromApi = function(url, data) {
    code = null;
    response = null;

    return $.ajax({method: method, url: url, dataType: 'json', data: data}); };

return {

    counters: function() {
        var deferred = $q.defer();
        return data = fetchDataFromApi('http://solmon.belgiumcampus.ac.za/api/data/getdashboarddata');}
};});

I then have a controller which calls to this factory and populates an array with the response that it receives like so
App.controller("DashboardWidgets", function($scope, DashboardData) {
var response = DashboardData.counters();

    $scope.CounterData = [];
response.then(function(response) {
    $scope.CounterData = [
        response.onlineUnits,
        response.offlineUnits,
        response.overallVoltage,
        response.overallCurrent,
        response.maintenanceUnits
    ];

});
alert("Online from controller: " + $scope.CounterData[0]);});

If I take out the alert at the end then the DOM element does not display the data that is received. Why is this happening and how would you recommend I fix it?


text:
Q: inserting an related item to a table in SQL instead of making two db calls from c# In my scenario, when the user replies to a post, a notification should be sent to the post owner. Currently, first I make a db call to add the reply record. Then, I check if reply is inserted successfully. If so, I create an instance of Notification object, I make another call to db to insert the notification record.
To decrease the db load, I thought about adding the notification record when I make the first call for adding the reply record. In Add Reply SQL stored procedure, I can also include the INSERT code for adding the notification record.
Is handling this directly in SQL a recommended approach? What is a good way of doing this without multiple db calls?

A: Yes, handling that in the stored procedure is a perfectly fine approach.

A: I agree with Steve an sp or trigger would be best but regardless of how you do it it's still 2 calls as you are doing 2 inserts. If you do this from your application level you can do both queries by opening one connection but it's still 2 calls. If you really need to reduce this to one call I would rethink your application level and perhaps use the actual reply as the data that feeds the notification. So when checking for notifications you just check the reply table and have a field on there to indicate if it's an unread notification.


text:
Q: Variation of a signed measure This is Exercise 3.P in Bartle's The Elements of Integration and Lebesgue Measure. I think I have a proof but would appreciate it if anyone can spot any mistakes or suggest any improvements.
If $\mu$ is a charge [Bartle's term for a finite signed measure] on a sigma-algebra $\Sigma$, let $\nu$ be defined for $E \in \Sigma$ by
$$\nu(E) = \sup \sum_{j=1}^{n}|\mu(A_j)|$$
where the supremum is taken over all finite disjoint collections $\{A_j\}$ in $\Sigma$ with $E = \cup_{j=1}^{n}$. Show that $\nu$ is a measure on $\Sigma$. (It is called the variation of $\mu$.)

It is clear that $\nu(\emptyset) = 0$ and $\nu(E) \geq 0$ for all $E \in \Sigma$, so we need to show that $\nu$ is countably additive. Suppose that $(E_k)$ is a disjoint sequence of sets in $\Sigma$ whose union is $E$. For each $k$, let $\{A_{jk}\}_{j=1}^{n_k}$ be a finite disjoint collection of sets in $\Sigma$ such that $E_k = \cup_{j=1}^{n_k}A_{jk}$. Then
$$\{A_{jk} : k=1,\ldots,N\ \text{and}\ j=1,\ldots,n_k\}\ \text{and}\ E\setminus(\cup_{k=1}^{N}E_k)$$
is a finite disjoint collection of sets in $\Sigma$ whose union is $E$. Therefore,
$$\sum_{k=1}^{N}\sum_{j=1}^{n_k}|\mu(A_{jk})| \leq \sum_{k=1}^{N}\sum_{j=1}^{n_k}|\mu(A_{jk})| + |\mu(E\setminus(\cup_{k=1}^{N}E_k))| \leq \nu(E)$$
Taking the supremum for each fixed $k$, we obtain
$$\sum_{k=1}^{N}\nu(E_k) \leq \nu(E)$$
Taking the limit as $N \to \infty$, it follows that
$$\sum_{k=1}^{\infty}\nu(E_k) \leq \nu(E)$$
For the reverse inequality, fix $\epsilon > 0$ and let $\{B_m\}_{m=1}^{M}$ be a finite disjoint collection of sets in $\Sigma$ whose union is $E$, such that
$$\nu(E) \leq \sum_{m=1}^{M}|\mu(B_m)| + \epsilon$$
Note that $\{B_m \cap E_k : k \in \mathbb{N}\}$ is a countable disjoint collection of sets in $\Sigma$ whose union is $B_m$. Since $\mu$ is a charge, it is countably additive, so
$$\mu(B_m) = \sum_{k=1}^{\infty}\mu(B_m \cap E_k)$$
Therefore,
$$\begin{aligned}
\nu(E) &\leq \sum_{m=1}^{M}\left|\sum_{k=1}^{\infty}\mu(B_m \cap E_k)\right| + \epsilon \\
&\leq \sum_{m=1}^{M}\sum_{k=1}^{\infty}|\mu(B_m \cap E_k)| + \epsilon \\
&= \sum_{k=1}^{\infty}\sum_{m=1}^{M}|\mu(B_m \cap E_k)| + \epsilon \\
\end{aligned}$$
Changing the order of the summation is valid because the summands are nonnegative, so the double sum can be performed in any order without changing the result, even if it is infinite. Now $E_k$ is the disjoint union of $\{B_m \cap E_k : m = 1,\ldots,M\}$, so
$$\sum_{m=1}^{M}|\mu(B_m \cap E_k)| \leq \nu(E_k)$$
Therefore,
$$\nu(E) \leq \sum_{k=1}^{\infty}\nu(E_k) + \epsilon$$
Since this inequality holds for any $\epsilon > 0$, we conclude that
$$\nu(E) \leq \sum_{k=1}^{\infty}\nu(E_k)$$


text:
Q: How to calculate metacognitive efficiency when SDT is not applicable to the first order task? I'm currently working on some data from an associative-memory study. Participants have to learn associations between stimuli from two different classes (1 and 2). As stimulus from class 1 is presented participants have to select the corresponding stimulus from class 2 (trough sliding). After response selection participants have to rate their confidence (binary, 'low confidence', 'high confidence') concerning their response. After the confidence rating feedback ('true', 'false') and the correct response (the correct matching of S1 and S2) are provided. Participants are instructed to guess during the first block. There are four retrieval sessions (including the first block).
I would like to perform an analysis regarding the metacognitive capabilities of the participants. Therefore I would like to apply a Signal Detection Theory (SDT) approach:
Hits: high confidence correct responses
False alarms: high confidence incorrect responses
Correct rejections: low confidence incorrect responses
Misses: low confidence correct responses
Since meta d' is affected by the first-order performance it is wise to quantify metacognitive efficiency which is the ratio of meta d' and d'. And here is the problem: I can't apply SDT for the first order task (which is the pure memory performance without the confidence ratings). The only score I can get is the recall rate.
I would be very grateful if you could share your ideas on this. Thanks!


text:
Q: Going to next frame and then removing movieClip in it after a few seconds (Actionscript 2) I'm working on a shooting game. This is my case, how can I make my enemy going to next frame wich is contain impact movieclip when its being shoot by player and then remove the movieclip it self
It's just like when you shoot a car, and then explode and then the explode disappear after few second
here is my code in frame:

stop(); //add a stop function too!

var gameOver: Boolean = false;

var mainSpeed: Number = 10; //how fast the main guy can move

//BULLET TIMING VARIABLES
var cTime: Number = 0; //the amount of frames that has elapsed since last bullet shot
var cLimit: Number = 12; //amount of frames needed to shoot another bullet
var shootAllow: Boolean = false; //whether or not main can shoot
//ENEMY TIMING VARIABLES
//how much time before another enemy is made
var enemyTime: Number = 0;
//how much time needed to make an enemy
//it should be more than the shooting rate
//or else killing all of the enemies would
//be impossible :O
var enemyLimit: Number = 50;
//showing the amount of enemies that have been added to the stage
var enemyTotal: Number = 0;

//the player's score
var score: Number = 0;

//this movieclip will hold all of the bullets
_root.createEmptyMovieClip('bulletHolder', _root.getNextHighestDepth());

onEnterFrame = function() { //this function will run every frame (needed for moving the character
  if (Key.isDown(37) || Key.isDown(65)) { //if the "A" key or Left Arrow Key is Down
    bat._x -= mainSpeed; //then the move the guy left
  }
  if (Key.isDown(38) || Key.isDown(87)) { //if the "W" key or Up Arrow Key is Down
    bat._y -= mainSpeed; //then move the guy up
  }
  if (Key.isDown(39) || Key.isDown(68)) { //if the "D" key or Right Arrow Key is Down
    bat._x += mainSpeed; //then move the guy to the right
  }
  if (Key.isDown(40) || Key.isDown(83)) { //if the "S" key or Down Arrow Key is Down
    bat._y += mainSpeed; //then move the guy down
  }

  //keeping the main character within bounds
  if (bat._x <= 0) {
    bat._x += mainSpeed;
  }
  if (bat._y <= 0) {
    bat._y += mainSpeed;
  }
  if (bat._x >= 500) {
    bat._x -= mainSpeed;
  }
  if (bat._y >= 500) {
    bat._y -= mainSpeed;
  }

  if (Key.isDown(32) && shootAllow) { //if the space bar is pressed
    var bulletID: Number = Math.random(); //create a variable that we'll use at the bullet's id
    //then attach a bullet to the stage
    bulletHolder.attachMovie('fire', 'Bullet' + bulletID, _root.getNextHighestDepth());
    //setting the coordinates of the bullet to be the same as the main character
    bulletHolder['Bullet' + bulletID]._x = bat._x;
    bulletHolder['Bullet' + bulletID]._y = bat._y - 70;
    bulletHolder['Bullet' + bulletID].onEnterFrame = function() {
      //giving the bullet some actions
      this._y -= 50; //moving the bullet
      if (this._y < -1 * this._height) { //if the bullet goes off stage
        //then destroy it
        this.removeMovieClip();
      }

      //checking if the game is over
      if (gameOver) {
        //destroy this guy if the game is over
        this.removeMovieClip();
      }
    }
    shootAllow = false;
  }

  cTime++; //increment the time
  if (cTime == cLimit) { //if enough time has elapsed
    shootAllow = true; //allow shooting again
    cTime = 0; //reset the time
  }

  enemyTime++; //incrementing time for enemy
  if (enemyTime == enemyLimit) { //if enough time has elapsed
    _root.attachMovie('thug', 'en' + enemyTotal, _root.getNextHighestDepth()); //then add the enemy
    //setting it's coordinates
    _root['en' + enemyTotal]._x = int(Math.random() * Stage.width); //randomly within the boundaries
    _root['en' + enemyTotal]._y = -50; //sets this offstage at first
    _root['en' + enemyTotal].onEnterFrame = function() { //then give it some functions
      this._y += 5;

      //run a loop checking if it's touching any bullets
      for (var cBullet: String in _root.bulletHolder) {
        //if it's touching the bullet
        //we have to use coordinates because hit testing doesn't seem to work
        if (this._y >= _root.bulletHolder[cBullet]._y - 50 && this._y <= _root.bulletHolder[cBullet]._y) {
          if (this._x <= _root.bulletHolder[cBullet]._x + 25 && this._x >= _root.bulletHolder[cBullet]._x - 55) {
            //then destroy this guy
            //this is where I tried to make it work but
            //it just change the movieclip but not removed it
            this.gotoAndStop(2)
            if (_root.thug.frame = 2) {
              _root.thug.removeMovieClip();
            }
            //and destroy the bullet
            _root.bulletHolder[cBullet].removeMovieClip();

            //up the score
            _root.score += 5;
          }
        }
      }

      //hit testing with the user
      if (this.hitTest(_root.bat)) {
        //set the game to be over and go to lose screen
        gameOver = true;
        gotoAndStop(2);
      }

      //checking if the game is over
      if (gameOver) {
        //destroy this guy if the game is over
        this.removeMovieClip();
      }
    }
    enemyTime = 0; //reset the time
    enemyTotal++; //add 1 more to the amount of enemies total
  }

  //updating the score text field
  txtScore.text = 'Score:  ' + score;
}

Thank you..

A: Just make another function that would remove your movieclip and call it with a delay:
setTimeout(onTimeout, 2000); // call the onTimeout function with a delay of 2 seconds

function onTimeout()
{
    this.removeMovieClip();
}

I'm just not sure if you will be able to call this new function out of your main function because it was declared in the onEnterFrame scope. So if that doesn't work you might need to modify your main function a bit:
onEnterFrame = onEnterFrameFunction;

function onEnterFrameFunction()
{
    // move your onEnterFrame code here
}


text:
Q: iOS Implementing a Messaging System I'm currently making an iOS app and I want to include a messaging system similar to the standard iOS one.
I've done a google search and think UIBubbleTableView is probably the best view to for the front end. However, I'm struggling to find a good way to handle the backend. I'm using Parse as a database.
Would I have a table for the messages, and then have a sender & receiver ID in each row? Or have a table for each individual communication between users? Either way seems a bit like a stupid way of doing it, as you're either going to be searching a huge database for the correct messages, or have loads of tables..
I found this, however it isn't really what I want, as it's not showing communication between users, rather in a chat room.
Any help would be much appreciated!

A: What you need is a communication protocol. Take a look at XMPP (Extensible Messaging and Presence Protocol) which is XML based, open source and used widely for many well known messengers like Google Talk or Jabber. There are many open source libraries which you may use in your application.
http://en.wikipedia.org/wiki/XMPP
About hosting your own server somewhere: It is not necessary. You may use Google's Google Talk servers or the ones from Jabber.


text:
Q: convert pinelineRDD to datafame in pyspark via list? I try to load a comma delimited csv file into RSD but it gives me pipelinedRSD
and I try to convert to a proper dataframe.
csv file has format
userId,movieId,rating,timestamp
1,1,4.0,964982703
1,3,4.0,964981247
1,6,4.0,964982224
1,47,5.0,964983815
1,50,5.0,964982931
1,70,3.0,964982400

Whats the easiest way to do that? I am using pyspark 3.3 python 3.9.12
import findspark
findspark.init()
findspark.find()

from pyspark import SparkConf, SparkContext
import collections

conf = SparkConf().setMaster("local").setAppName("RatingsHistogram")
sc = SparkContext(conf = conf)

lines = sc.textFile("file:///sparkCourse/ml-latest-small/ratings.csv")
ratings = lines.map(lambda x: x.split()[2])

lines2=lines.collect()

type(lines2) #list

#['userId,movieId,rating,timestamp',
# '1,1,4.0,964982703',
# '1,3,4.0,964981247',
# '1,6,4.0,964982224',
# '1,47,5.0,964983815']


text:
Q: PHP snmp work with one connection Is there any way to make one connection and work with it?
Now I have this:
snmp2_get("ip", "public", ".1.3.6.1.2.1.1.5.0");
snmp2_get("ip", "public", ".1.3.6.1.2.1.1.6.0");

Is there any function to make one connection and work with it or how I can put multi OIDS?

A: SNMP over UDP, the default setup, is connectionless to begin with.  The PHP functions do not provide a means of generating a "handle" that can be reused; typically, you would create your own wrapper if you wanted this functionality.
Note, however, that PHP 5.4 introduced the "SNMP" class (see the documentation here), which would allow you to do exactly what you want.
For example:
$session = new SNMP( SNMP::VERSION_2C, "127.0.0.1", "public" );
$value1 = $session->get( ".1.3.6.1.2.1.1.5.0" );
$value2 = $session->get( ".1.3.6.1.2.1.1.6.0" );


text:
Q: Minus sign in logarithm of integral's solution I want to solve the following integral:
$
\int \frac{dp}{a(1-p)u-bp}
$
where $a$, $b$ and $u$ are some constants.
After integration I get:
$
p = -\frac{\log(-apu+au-bp)}{au+b} + C.
$
According to WolframAlpha it is equivalent to (citing precisely: "Which is equivalent for restricted $p$, $a$, $b$ and $u$ values to"):
$
p = -\frac{log(a(p-1)u+bp)}{au+b} + C,
$
or transforming it a bit, it is equivalent to:
$
p = -\frac{\log(apu-au+bp)}{au+b} + C.
$
So for some reasons a minus is "removed" from the logarithm. Could you please explain to me why?

A: Hint: compute $D(\log(-x))$ and compare with $D(\log(x))$.

A: Both $\log x$ and $\log(-x)$ are antiderivatives of $1/x$.  The difference (at least when we restrict our attention to real numbers) is that $\log x$ is only defined when $x$ is positive, and $\log(-x)$ is only defined when $x$ is negative.  So your solution is correct for values of $p$, $a$, $b$, and $u$ such that $-apu+au-bp$ is positive, while WolframAlpha's solution is correct when it is negative.  You can get a single antiderivative of $1/x$ that works for all nonzero (real) values of $x$ by combining the two cases as $\log|x|$.
The story is somewhat clarified by considering complex numbers.  It turns out that $\log x$ can be defined when $x$ is a negative real, and its value is $\log (-x)+i\pi$ (remembering that $-x$ is now a positive real).  Since $i\pi$ is just a constant, this means that the expressions $\log x+C$ and $\log(-x)+C$ are actually equivalent, because you can absorb the $i\pi$ into the $C$ term.  So in this sense WolframAlpha's answer isn't actually any different from yours.
(Actually, when you consider complex numbers, a new complication arises, which is that $\log x$ is only defined up to integer multiples of $2\pi i$, similar to how $\arcsin x$ is only defined up to integer multiples of $2\pi$, but that's a longer story.)

A: \begin{align}
I &= \int \frac{dp}{a(1-p)u - b p}  = \frac{1}{au} \, \int \frac{dp}{1 - \left( 1 + \frac{b}{au}\right) p } \\
&= \frac{1}{au+b} \, \int \frac{dx}{1-x} \hspace{10mm} \text{where} \quad  x = \left(1+\frac{b}{au}\right) \, p \\
&= - \frac{1}{au + b} \, \int \frac{dx}{x-1} \\
&= - \frac{1}{au+b} \, \ln(x-1) \\
&= - \frac{\ln(au\, (1-p) + bp) - \ln(au)}{au+b}.
\end{align}


text:
Q: Boundness of torsion in $R^i\pi_*\mathcal F$ for a smooth $\pi:X\rightarrow S$ Let $\pi:X\rightarrow S$ be a smooth scheme over $S$ and let's assume for simplicity that $S=\mathrm{Spec} R$ is affine, Noetherian and regular. Let $\mathcal F$ be a coherent sheaf on $X$ and let's assume as well that $\mathcal F$ is torsion-free. Then I can take the derived global sections $R^\bullet\pi_* \mathcal F$, taking further its cohomology I get some $R$-modules $R^i\pi_*\mathcal F$.
Now the question is:
Given $R^i\pi_* \mathcal F$ can I say anything about torsion in it (as in an $R$-module)? In particular is there an open dense $U\subset S$ such that $R^i\pi_*\mathcal F$ is torsion-free restricted to $U$?
If $\pi$ is proper this is automatic since then $R^i\pi_* \mathcal F$ is finitely generated over $R$. If $\pi$ is affine then $R^\bullet\pi_* \mathcal F=\pi_*\mathcal F$ and we just consider some torsion-free module $M$ over $R'$ as a module over $R$ under an injection $R\subset R'$, so the statement holds as well. For the general case I tried to use a Cech cover of $X$ by affine $S$-schemes, but what you get is a complex whose terms are infinitely generated $R$-modules (though torsion-free) and I'm not sure what I could use to bound the torsion in the cohomology there.
Also, not sure if this makes life any simplier, but under the assumptions above $\mathcal F$ is a perfect complex on $X$ and it would be enough to take $\mathcal F=\mathcal O_X$.

A: No, this isn't true even when $S = \text{Spec}(\mathbf{Z})$ because of an example of Anurag Singh. Set
$$
R = \mathbf{Z}[X, Y, Z, U, V, W]/(XU + YV + ZW)
$$
and let $\mathfrak a \subset R$ be the ideal generated by $X, Y, Z$ in $R$. Set
$$
X = \text{Spec}(R) \setminus V(\mathfrak a)
$$
Then $H^2(X, \mathcal{O}_X) = H^3_\mathfrak a(R)$ has a $p$-torsion element for infinitely many primes $p$ (see link given above).


text:
Q: How can I make query in PHP to search start_date and end_date I can't convert this query from Oracle database to PHP.
<input type="date" name="stardate" value="startdate" id="startdate" value="<?php echo isset($_GET["startdate"]);?>">
<input type="date" name="enddate" value="enddate" id="enddate" value="<?php echo isset($_GET["enddate"]);?>">

This is my query that is correct, but I don't know how to place it in PHP:
SELECT *
  FROM datepick
 WHERE start_date not between to_date('03/28/2019','mm/dd/yyyy') and to_date('03/30/2019','mm/dd/yyyy')
 and end_date not between to_date('03/28/2019','mm/dd/yyyy') and to_date('03/30/2019','mm/dd/yyyy');

A: After form submission get date in variables and stablish php-mysql connection using mysqli or pdo than with concatenation you can pass those value to mysql query.
<?php
// support you done form submit with get/post

$stardate = $_REQUEST['stardate']; // 03/28/2019
$enddate = $_REQUEST['enddate']; // 03/30/2019

// mysqli connection
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql="SELECT * FROM datepick WHERE
start_date not between to_date('".$stardate."','mm/dd/yyyy') and to_date('".$enddate."','mm/dd/yyyy')
and end_date not between to_date('".$stardate."','mm/dd/yyyy') and to_date('".$enddate."','mm/dd/yyyy')";
$result=mysqli_query($con,$sql);

// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
print_r ($row);
// check output and modify code accordingly
?>


text:
Q: Python and Sublime: can't open file I have recently downloaded Sublime 3. It was working fine for few days, but today, while trying to do a project, it was giving me an error.
So I did the simple 'Hello world' printing and it still gave the error:
print("Hello World")

Error: Sublime text 3
I also tried changing the environmental variables and tried to resintall Sublime, but it didn't worked.

A: As in the picture, you haven't saved the pssa.py yet, that's why the error is No such file or directory


text:
Q: Does Salesforce bulk api 2.0 support PK chunking by default? We have a use case where we want to query large amounts data(100 million) from our Salesforce Account. We are planning to use Salesforce bulk api 2.0 and according to this documentation PK chunking is automatically enabled for Bulk API 2.0. (https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/bulk_common_diff_two_versions.htm). But this documentation doesn't mention about PK chunking(https://developer.salesforce.com/docs/atlas.en-us.api_asynch.meta/api_asynch/query_bulk_api_2_0.htm).
Is is safe to assume that PK chunking is default enabled for Bulk 2.0 api ?


text:
Q: Picture on Google Glass without "Tap" cofirmation I'm trying to get a picture, but with my code, is neccesary to confirm the image through "Tap" gesture.
Here is my code:
private void takePicture() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, TAKE_PICTURE_REQUEST);
    }

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TAKE_PICTURE_REQUEST && resultCode == RESULT_OK) {
            String thumbnailPath = data.getStringExtra(Intents.EXTRA_THUMBNAIL_FILE_PATH);
            String picturePath = data.getStringExtra(Intents.EXTRA_PICTURE_FILE_PATH);

            processPictureWhenReady(picturePath);
            // TODO: Show the thumbnail to the user while the full picture is being
            // processed.
        }
        else{
            takePicture();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

I have see this post:
Is it possible to take a photo using Google Glass without "tap to accept"?
But I can't get the picture without Tap.
Is there any example?
Thanks!

A: For this you need to add a mechanism that would enable the gesture detection. In your case it is the TAP gesture. I would recommend putting this piece of code in your takePicture() method:
 @Override
    public boolean onKeyDown(int keycode, KeyEvent event) {
        if (keycode == KeyEvent.KEYCODE_DPAD_CENTER) {
            // user tapped touchpad, do something
            return true;
        }
        ...
        return super.onKeyDown(keycode, event);
    }

This would enable you to take picture only when you tap on the Glass and hence confirm. For more details please take a look at this document.


text:
Q: DB2 SQL, cant define column as I have some SQLthat is part of that is a section of a with statement
And I keep getting an error that "NEWID" is not valid in the context where it is used sqlstate 42703.
Update: The error has been comming from the group by clause using a having function I didnt put in the original code as I thought it wasnt the issue.So I updated the code to show the full version.
Does anyone know what the problem is with the statement?
HATSTABLE1 (HATId, NewID) as (
select HA.HATId as "ID",
round(
  cast(
    sum(
      case when HA.ID = 4 or
        HA.ID < 0
        then 1 else 0 end
    ) AS FLOAT
  ) / count(*) * 100,
  2
) AS NewID
from Hats T
   join Heads HD on
      T.ID=HD.HatID
group by T.ID
having NewID >1

A: try it
with tmp as (
select T.HATId as "ID",
sum(case when T.ID = 4 or HA.ID < 0 then 1 else 0 end) as sum1,
count(*) as nb
from Hats T
group by T.HATId
)
select HATId, round(cast(sum1 as decimal)/ nb * 100, 2) NewID
from tmp


text:
Q: Failed to Run Query: Exception in Connection.php line 673: SQLSTATE[42000]: Syntax error or access violation: 1064 I'm building a laravel application where there is a controller which functionality is we have to book a classroom where if a time has already booked or there in database we can't book a classroom in that time interval. I have used the following controller :
public function postAllocateRoom(Request $request)
    {

            $classRoom = new ClassRoom();

            $classRoom->department_id=$request->Input(['department_id']);
            $classRoom->room_id=$request->Input(['room_id']);
            $classRoom->course_id=$request->Input(['course_id']);
            $classRoom->day_id=$request->Input(['day_id']);
            $classRoom->start=$request->Input(['start']);
            $classRoom->end=$request->Input(['end']);
            $startTime = Carbon::parse($request->input('start'));
            $endTime = Carbon::parse($request->input('end'));
            $classRoom=DB::select('SELECT allocate_rooms.id
            FROM allocate_rooms
            WHERE '.$startTime.' BETWEEN allocate_rooms.start AND allocate_rooms.end')->count();

            $messages ="Class Room Already Taken";
            if ($classRoom>0) {
             return redirect('allocateRoomPage');
                    }
            else {
                 $classRoom->save();
            return redirect('allocateRoomPage');
            }
    }

But I'm getting following Error while saving in database:

QueryException in Connection.php line 673: SQLSTATE[42000]: Syntax
  error or access violation: 1064 You have an error in your SQL syntax;
  check the manual that corresponds to your MariaDB server version for
  the right syntax to use near '17:00:00 BETWEEN allocate_rooms.start
  AND allocate_rooms.end' at line 3 (SQL: SELECT allocate_rooms.id  FROM
  allocate_rooms WHERE 2016-05-08 17:00:00 BETWEEN allocate_rooms.start
  AND allocate_rooms.end)

How do I solve this?

A: The date needs to be quoted as well:
$classRoom=DB::select('SELECT allocate_rooms.id
FROM allocate_rooms
WHERE "' . $startTime . '" BETWEEN allocate_rooms.start AND allocate_rooms.end')->count();

I would suggest searching for a method to prepare MySQL queries in laravel, instead of writing them by hand.
Go through this blog post regarding the same: http://fideloper.com/laravel-raw-queries


text:
Q: Disable AjaxSubmitButton if text field is empty I have a form with textfield and submit button and I would like to disable submit button if textfield is empty and enable it again as soon as textfield is not empty anymore
<form wicket:id="form">

    <textarea wicket:id="textMessage" rows="4" cols="70" maxlength="300"></textarea>

        <button wicket:id="submitButton" class="btn btn-sm btn-primary">
            Save
        </button>

</form>

Form<Void> form = new Form<>("form");
TextArea<String> textMessageField = new TextArea<>("textMessage", textMessageModel);
Button submitBtn = new Button("submitButton");
submitBtn.add(new AjaxFormSubmitBehavior(form, "click") {
    @Override
    protected void onError(AjaxRequestTarget target) {
        target.add(getForm());
    }

    @Override
    protected void onSubmit(AjaxRequestTarget target) {
       //.....some code
    }

    @Override
    protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
        super.updateAjaxAttributes(attributes);
        attributes.setPreventDefault(true);
        }
    });
form.add(textMessageField);
form.add(submitBtn);

any ideas how to do it ?

A: You need to add a AjaxFormComponentUpdatingBehavior or OnChangeAjaxBehavior to your text field.
TextArea<String> textMessageField = new TextArea<>("textMessage", textMessageModel);
Button submitBtn = new Button("submitButton") {
    @Override
    protected void onConfigure() {
        super.onConfigure();
        String obj = textMessageField.getModelObject();
        setEnabled(obj != null && !obj.isEmpty());
    }
};
submitBtn.setOutputMarkupId(true);
textMessageField.add(new OnChangeAjaxBehavior() {
    @Override
    protected void onUpdate(AjaxRequestTraget target) {
        target.add(submitBtn);
    }
});


text:
Q: why to take logs and remove mean? I am replicating a paper (Gil Kim and David Vera 2017). They transform the price of oil by doing the following;
"for the real price of oil, we first deflate it, transform it into natural log and remove the mean"

*

*what is the reasoning behind removing the mean?

*I am not sure how to do it. Should I take the mean of the whole transformed series log(oilp) and then substract the same number to each observation of the transformed series? or to the original one?


text:
Q: Переход c HTTP на HTTPS Всем привет ! Не могу решить проблем с переносом с http на https.
У меня в .htaccess файле написано так:
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !/assets
RewriteRule ^(.*)$ index.php?/$1 [L,QSA]
RewriteRule page/assets/img/([^.]+\.(jpe?g|gif|bmp|png))$ /assets/img/$1 [R=301,L,NC]
RewriteRule page/assets/img/uploads/([^.]+\.(jpe?g|gif|bmp|png))$ /assets/img/uploads/$1 [R=301,L,NC]
RewriteRule admin/assets/img/([^.]+\.(jpe?g|gif|bmp|png))$ /assets/img/$1
[R=301,L,NC]
RewriteRule admin/assets/img/uploads/([^.]+\.(jpe?g|gif|bmp|png))$
/assets/img/uploads/$1 [R=301,L,NC]

Когда добавляю к себе еще
RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://site(.)by/$1 [R=301,L]

HTTPS появляется но сайт падает
Подскажите если сталкивались с такой проблемой.

A: RewriteCond %{HTTPS} =off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [QSA,L]
Попробуйте вот так.

A: Нужно переписать
RewriteCond %{HTTPS}=OFF
тогда оно будет перенаправлять ваш запрос
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [QSA,L]


text:
Q: stack trace interpretation on iOS Can someone help me make sense of the following iOS stacktrace?  I would love to know which UIViewController the issue originated from so I can pinpoint the issue:
0 libobjc.A.dylib 0x31576f78 objc_msgSend + 15
1 CoreFoundation 0x3168b3fd -[NSObject performSelector:withObject:withObject:] + 52
2 UIKit 0x31a9c6a1 -[UIApplication sendAction:fromSender:toTarget:forEvent:] + 64
3 UIKit 0x31a9c65b -[UIControl(Deprecated) sendAction:toTarget:forEvent:] + 46
4 UIKit 0x31a466a9 -[UIControl(Internal) _sendActionsForEventMask:withEvent:] + 488
5 UIKit 0x31a4516d -[UIFieldEditor becomeFieldEditorForView:] + 168
6 UIKit 0x31a44a9d -[UITextField _becomeFirstResponder] + 96
7 UIKit 0x3196291d -[UIResponder becomeFirstResponder] + 336
8 UIKit 0x31a614a7 -[UITextInteractionAssistant setFirstResponderIfNecessary] + 174
9 UIKit 0x31a60d71 -[UITextInteractionAssistant oneFingerTap:] + 1608
10 UIKit 0x31a60637 _UIGestureRecognizerSendActions + 106
11 UIKit 0x319f0d65 -[UIGestureRecognizer _updateGestureWithEvent:] + 304
12 UIKit 0x31c21479 ___UIGestureRecognizerUpdate_block_invoke_0541 + 48
13 UIKit 0x3196cf55 _UIGestureRecognizerApplyBlocksToArray + 176
14 UIKit 0x3196baa3 _UIGestureRecognizerUpdate + 898
15 UIKit 0x319787e9 _UIGestureRecognizerUpdateGesturesFromSendEvent + 28
16 UIKit 0x31978627 -[UIWindow _sendGesturesForEvent:] + 774
17 UIKit 0x319781f5 -[UIWindow sendEvent:] + 88
18 UIKit 0x3195e695 -[UIApplication sendEvent:] + 356
19 UIKit 0x3195df3b _UIApplicationHandleEvent + 5826
20 GraphicsServices 0x32b6122b PurpleEventCallback + 882
21 CoreFoundation 0x31705523 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 38
22 CoreFoundation 0x317054c5 __CFRunLoopDoSource1 + 140
23 CoreFoundation 0x31704313 __CFRunLoopRun + 1370
24 CoreFoundation 0x316874a5 CFRunLoopRunSpecific + 300
25 CoreFoundation 0x3168736d CFRunLoopRunInMode + 104
26 GraphicsServices 0x32b60439 GSEventRunModal + 136
27 UIKit 0x3198ccd5 UIApplicationMain + 1080
28 MyApp 0x000aa96b _mh_execute_header + 14699

A: From that stack trace we can deduce that the user tapped his finger on a text field.  If you only have one text field in your app, then you now know which UI element is involved, and maybe from that you can deduce which view controller is involved.
We can also see that the text field is sending its actions for becoming first responder.  If only one text field in your app has a target and action for the "Editing Did Begin" (UIControlEventEditingDidBegin) event, then you now know which UI element is involved, and maybe from that you can deduce which view controller is involved.
Otherwise, you cannot tell from that stack trace which view controller is involved.

A: "I would love to know which UIViewController the issue originated from" <- that can't be known from a stacktrace only. Set a breakpoint on the function that crashed and/or build with debug symbols enabled.


text:
Q: TypeScript equivalent to Dart `Completer` In Dart I have a Completer that returns a Future (Promise) and that Future can be completed somewhere else then where it was created, like
class SomeClass {
  final Completer<bool> initializationDone = new Completer<bool>();

  SomeClass() {
    _doSomeAsyncInitialization();
  }

  void _doSomeAsyncInitialization() {
    // some async initialization like a HTTP request
    fetchDataFromServer().then((data) {
      processData();
      initializationDone.complete(true);
    });
  }
}

main() {
  var some = new SomeClass();
  some.initializationDone.future.then((success) {
    // do something.
  });
}

I don't want a solution for this actual problem, this is only an example I came up with to demonstrate how a Completer is used in Dart.
What would be an equivalent to the Dart Completer in TypeScript?

A: made this simple class that worked for me:
export class Completer<T> {
    public readonly promise: Promise<T>;
    public complete: (value: (PromiseLike<T> | T)) => void;
    private reject: (reason?: any) => void;

    public constructor() {
        this.promise = new Promise<T>((resolve, reject) => {
            this.complete = resolve;
            this.reject = reject;
        })
    }
}

const prom = new Completer<bool>();

prom.complete(true);

A: This looks like an implementation of such a Completer in TypeScript https://github.com/angular/angular/blob/b0009f03d510370d9782cf76197f95bb40d16c6a/modules/angular2/src/facade/promise.ts
export {Promise};

export interface PromiseCompleter<R> {
  promise: Promise<R>;
  resolve: (value?: R | PromiseLike<R>) => void;
  reject: (error?: any, stackTrace?: string) => void;
}

export class PromiseWrapper {
  static resolve<T>(obj: T): Promise<T> { return Promise.resolve(obj); }

  static reject(obj: any, _): Promise<any> { return Promise.reject(obj); }

  // Note: We can't rename this method into `catch`, as this is not a valid
  // method name in Dart.
  static catchError<T>(promise: Promise<T>,
                       onError: (error: any) => T | PromiseLike<T>): Promise<T> {
    return promise.catch(onError);
  }

  static all(promises: any[]): Promise<any> {
    if (promises.length == 0) return Promise.resolve([]);
    return Promise.all(promises);
  }

  static then<T, U>(promise: Promise<T>, success: (value: T) => U | PromiseLike<U>,
                    rejection?: (error: any, stack?: any) => U | PromiseLike<U>): Promise<U> {
    return promise.then(success, rejection);
  }

  static wrap<T>(computation: () => T): Promise<T> {
    return new Promise((res, rej) => {
      try {
        res(computation());
      } catch (e) {
        rej(e);
      }
    });
  }

  static scheduleMicrotask(computation: () => any): void {
    PromiseWrapper.then(PromiseWrapper.resolve(null), computation, (_) => {});
  }

  static isPromise(obj: any): boolean { return obj instanceof Promise; }

  static completer(): PromiseCompleter<any> {
    var resolve;
    var reject;

    var p = new Promise(function(res, rej) {
      resolve = res;
      reject = rej;
    });

    return {promise: p, resolve: resolve, reject: reject};
  }
}


text:
Q: How to create a style based on default style? How to create a style based on default style in Silverlight?
For example, in WPF we make it like:
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
  <Setter Property="Margin" Value="2" />
  <Setter Property="Padding" Value="2" />
</Style>

A: Pretty much the same. Just minus the x:Type with more explicit naming.
<Style TargetType="TextBox" BasedOn="{StaticResource DefaultTextBoxStyle}">

More information here in the docs. PS, in case you need the default templates, TextBox for example would normally be found in CoreStyles.xaml
ADDENDUM as requested in the comments in case you're confused at the first read of the answer;
"you DO need a base style, which is really easy to do as you're meant to do it in an application theme like silverlight provides by default (wpf/uwp etc won't have these) that creates the files like ToolkitStyles.xaml, SDKStyles.xaml, CoreStyles.xaml, etc... Which is WHERE the staticresource name in the answer came from as targeting a silverlight version from the year this was originally answered."

A: I would recommand to have a look at :
https://justinmchase.com/2009/05/29/derived-styles-based-on-unnamed-default-styles/
It would go like this for you :
<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">

A: For Silverlight only:
To create a style based on the default style, you need to create a named style, then make the default style based on the named style (http://weblogs.asp.net/lduveau/silverlight-how-to-inherit-from-an-implicit-style)
<Style x:Key="DefaultCustomControlStyle" TargetType="local:CustomControl">
    <Setter Property="Padding" Value="2" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="local:CustomControl">
                <ContentPresenter />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<Style TargetType="local:CustomControl" BasedOn="{StaticResource DefaultCustomControlStyle}" />

If you're using WPF, it's much simpler to use the code in the original question instead.

A: If I understand correctly you are looking for OverridesDefaultStyle
<Style TargetType="{x:Type TextBox}">
      <Setter Property="OverridesDefaultStyle" Value="False" />
      <Setter Property="Margin" Value="2" />
      <Setter Property="Padding" Value="2" />
</Style>


text:
Q: How can I get width of div, which is written in CSS I want width of a div element which is specified by developer.
Means if you write $('body').width(), it will provide you width in px , whether you have specified it or not.
I need width of div specified in CSS/JavaScript but not which is calculated by jQuery (which was not actually specified but was inherited).
If not width is specified then I need to know.

A: <style type="text/css">
    .largeField {
        width: 65%;
    }
</style>
<script>
    var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    for (var i=0; rules.length; i++) {
        var rule = rules[i];
        if (rule.selectorText.toLowerCase() == ".largefield") {
            alert(rule.style.getPropertyValue("width"));
        }
    }
</script>

Possibly duplicate with get CSS rule's percentage value in jQuery or Getting values of global stylesheet in jQuery

A: The code below will loop through all stylesheets as well as the matching element's style property. This function will return an array of widths.
function getCSSWidths( id ) {

    var stylesheets = document.styleSheets;
    var widths = [];
    var styleWidth;

    // loop through each stylesheet
    $.each( stylesheets, function( i, sheet ) {

        var len = ( sheet.rules.length || sheet.cssRules.length );
        var rules = sheet.rules || sheet.cssRules;

        // loop through rules
        for (var i=0; i < len; i++) {

            var rule = rules[i];

            // if width is specified in css add to widths array
            if (rule.selectorText.toLowerCase() == "#" + id.toLowerCase() ) {
                widths.push( rule.style.getPropertyValue("width"));
            }
        }
    });

    var el = document.getElementById( id );

    // get width specified in the html style attribute
    if( el && el.style && el.style.width ) {
        widths.push( el.style.width );
    }

    return widths;
}

getCSSWidths( "test" );

Fiddle here
There is one issue that I can see though as multiple selectors can be specified in the selectorText i.e.
#id1, #id2, .class1 {
    // properties
}

In these cases the id passed in as an argument will not match the selectorText property. Maybe someone can come up with a regex expression that will match the specified id :)

A: For the Javascript specified width, you can try this:
document.getElementById("myDivElement").style.width
If the above returns an empty string, it means it has not been specified by Javascript.
As for rules specified through CSS, find the class name(s) of the element and then the rules specified for that class:
var className = document.getElementById("myDivElement").className;
var cssWidth = getWidthFromClassname(className);
Now you need to define getWidthFromClassname:
function getWidthFromClassname(className)
{
    var reqWidth;
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
    for(var x=0;x<classes.length;x++) {
        if(classes[x].selectorText==className) {
             reqWidth = classes[x].style.getPropertyValue("width");
             break;
        }
    }

    return reqWidth;
}

A: document.getElementById('divid').style.width

A: You could use the clientWidth property, it calculates the actual width of the element, regardless if set through CSS or if it's the natural flow of the document:
document.getElementById('divId').clientWidth

If you want the full content width with margins/paddings/border you can use offsetWidth:
document.getElementById('divId').offsetWidth

https://developer.mozilla.org/en-US/docs/DOM/element.offsetWidth
https://developer.mozilla.org/en-US/docs/DOM/element.clientWidth


text:
Q: Getting "1366 (HY000): Incorrect string value:" after specifying encoding Sorry I've seen the question answered before but can't seem to solve the problem. I'm trying to properly encode my SQL columns so it will accept emojis:
def create_table():
    op = '''CREATE TABLE conversation (
    text TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL,
    intent TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin,
    entities TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin,
    reply TEXT CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL
    )'''
    cursor.execute(op)

def insert_message(text, intent, entities, reply):
    try:
        #avoid using placeholders to prevent SQL injection, will pass text, intent and entities to transaction_builder() instead
        sql = """INSERT INTO conversation  (text, intent, entities, reply) VALUES (%s, %s, %s, %s)"""
        transaction_builder(sql, text, intent, entities, reply)
    except Exception as e:
        print ('error is', str(e))

with open('C:/Users/ELITEBOOK/documents/github/chatbot/chatbot/bot/robot_text.txt','r') as table:
        for robo_line in table.readlines():
            message_reply = robo_line
            message_intent = ''
            message_entities = ''
            insert_message(message_text, message_intent, message_entities, message_reply)

There's some code missing but this is what is relevant. It looks to me like the encoding should be set but it seems like it's not. Sorry if this is a duplicate
edit:
Traceback
1366 (HY000): Incorrect string value: '\xF0\x9F\x98\x81\xF0\x9F...' for column 'reply' at row 1


text:
Q: Angular 2 and SFDC We are going to use Angular 2 to build application in SFDC. I want to know what obstacles we can meet on this way.
First of all I am interesting:

*

*What best practices for deploy angular 2 applications for this time we have?

*Do we have problems with JavaScript
Remoting or Remote Objects using them in angular 2?

But I am interesting in all real experience, because information what I find is very poor.

A: If you're only planning on developing Angular in Visualforce, the task is fairly trivial. If you're trying to implement Angular in Lightning, the task is fairly complex.
Static Resource
Start by going into Setup, Develop, Static Resources. Upload a ZIP file that contains all the Angular code, or if minified to single file, you can just upload the file directly as a JavaScript resource.
Visualforce
In Visualforce, simply add this code:
<apex:includeScript value="{!URLFOR($Resource.angularJS)}" />

As in normal Angular, just add ng-app to the element where your app resides:
<apex:page>
  <apex:includeScript value="{!URLFOR($Resource.angularJS)}" />
  <div ng-app="myAppName">
    <!-- more content here -->
  </div>
</apex:page>

Lightning
This is a bit trickier, but not impossible. Read Using External JavaScript Libraries for more info.
Like Visualforce, you need to use an include statement:
<ltng:require scripts="{!$Resource.angularJS}" afterScriptsLoaded="{!c.setup}" />

As in Visualforce, you need to specify the root ng-app element, which can be anywhere in your component. However, unlike Visualforce, all of your AngularJS logic has to be contained inside the controller or helper files, which means your logic will be a bit more complicated.
Remote Objects
This works as expected with AngularJS; you simply call the appropriate constructor/methods from the "jsShorthand" namespace. If you understand how they work in plain JavaScript, they operate exactly the same in AngularJS. Similarly, JavaScript Remoting works the same as it does with any other JavaScript.
Notes
It's really hard to give a short, concise answer without a concrete problem to work with. I've personally toyed around with AngularJS in the past, and it works well in Visualforce. For Lightning, I'd skip it and just use Lightning. It's complicated enough on its own without a third-party library.


text:
Q: Show that for a gradient system $\bf\dot x= f(x)$, $\frac{\partial f_i}{\partial x_j}-\frac{\partial f_j}{\partial x_i}=0$ for $1 \leq i, j \leq d$
The dynamical system ${\bf \dot x} = {\bf f}({\bf x})$ is called a gradient system if there exists a function $V({\bf x})$ such that
  $$
{\bf f}({\bf x}) = - \nabla V({\bf x})
$$
  Show that if ${\bf \dot x} = {\bf f}({\bf x})$ is a gradient system, then
  $$
\frac{\partial f_i}{\partial x_j} - \frac{\partial f_j}{\partial x_i} = 0
$$
  for $1 \leq i, j \leq d$

So let ${\bf f}({\bf x}) = (f_1({\bf x}), f_2({\bf x}), \dots , f_n({\bf x}))$ and from the definition of a gradient system, we have
$$
(f_1({\bf x}), f_2({\bf x}), \dots , f_n({\bf x})) = - \left ( \frac{\partial V({\bf x})}{\partial x_1}, \frac{\partial V({\bf x})}{\partial x_2}, \dots, \frac{\partial V({\bf x})}{\partial x_n} \right )
$$
but then I don't see how to follow this to produce the required equation.

A: Hint
$V$ has two continuous derivatives, your equation is Schwarz' theorem in disguise.
$$\frac{\partial^2}{\partial x_i\partial x_j} V = \frac{\partial^2}{\partial x_j \partial x_i} V$$
now write this in terms of $f$.

A: $$ \frac{\partial f_i}{\partial x_j}-\frac{\partial f_j}{\partial x_i} = -\left(\frac{\partial}{\partial x_j}\frac{\partial V}{\partial x_i} - \frac{\partial}{\partial x_i} \frac{\partial V}{\partial x_j} \right) = -\left(\frac{\partial^2}{\partial x_j \partial x_i} - \frac{\partial^2}{\partial x_i \partial x_j} \right) V = 0 $$
if $V$ has continuous second partial derivatives.

A: By definition,
$$\frac{\partial f_{i}}{\partial x_{j}}=-\frac{\partial^{2}V}{\partial x_{j}\partial x_{i}}$$
$$\frac{\partial f_{j}}{\partial x_{i}}=-\frac{\partial^{2}V}{\partial x_{i}\partial x_{j}}$$
So they're equal by Schwarz theorem if $V$ is at least twice differentiable.


text:
Q: Differences between files and templates in ansible role dir Ansible: 2.9
Hi!
What is the difference between this two dirs: "files" vs "templates" in ansible role tree?
I know how to work with "templates" dir but how I can work with "files" dir?
Thank's a lot!

A: If you know what a template is, a file is basically a template that doesn't need to be processed.
For instance, if your role needs a task to copy a file, you can use copy module:
- name: Copy a file
  copy:
    src: my_file.txt
    dest: /etc/wherever

In an Ansible role, src is relative to role's files directory.

A: Q: "How I can work with 'files' dir?"
A: Read the whole section The magic of 'local' paths. Quoting only a part of it:

... "Using this magic, relative paths get attempted first with a 'files|templates|vars' appended (if not already present), depending on the action being taken, 'files' is the default. (in other words, include_vars will use vars/). The paths will be searched from most specific to most general (in other words, role before play). dependent roles WILL be traversed (in other words, the task is in role2, role2 is a dependency of role1, role2 will be looked at first, then role1, then play)" ...


text:
Q: How to import python modules and use python scripts in SwiftUI with PythonKit? **the SwiftUI file**
import SwiftUI
import PythonKit
let main = Python.import("main.py")
Button(action:{
        main.func($symptoms as! PythonConvertible)
    }) {
        Image(systemName: "arrowtriangle.forward")
            .font(.largeTitle)

            .foregroundColor(.black)
            .position(x:200, y:-200)
    }

**main.py**
from pathlib import Path
from datetime import datetime
from collections import defaultdict

def func():
    try:
       from googlesearch import search
    except ImportError:
       print("No module named 'google' found, please install it")

...

Hi I'm relatively new to Swift and iOS app development and I've been trying to write an iOS app which uses a Python script to search google for a result, I've already installed the PythonKit in Xcode but I still can't use the function I defined in main.py, despite referencing it in the SwiftUI file. Every time the button is pressed, the xCode emulator just crashes and macOS returns a lengthy error message. Does anyone know how to do this?


text:
Q: Why do we need ASP.NET Impersonation: Enabled on IIS 6.0 for default websites? Why would we need to enable, IIS Authentication settings for Default Web Sit ?
ASP.NET Impersonation: Enabled
Windows Authentication: Enabled
IIS 6.0 or IIS 7

A: When enabling the Asp.net impersonation on the IIS server, the client identity could access the windows resource of the server-side with the windows account of the server-side. this is out-dated technology, there is no need to care much about it.
https://learn.microsoft.com/en-us/previous-versions/aspnet/134ec8tc(v=vs.100)
https://learn.microsoft.com/en-us/troubleshoot/aspnet/implement-impersonation
Feel free to let me know if there is anything I can help with.


text:
Q: SQL query joing two tables on a date where one is a Numeric date (number of days) from unixepoch I am trying to join two tables on a date column, the only issue is one date is formatted as an integer, it is the number of days from 1970-01-10 (unixepoch). The other date is formatted as a date in the MM/DD/YYYY format. What function will allow me to essentially convert the numeric date by adding the days to the unixepoch? I have tried the query below but it overwrites all the dates as 1970-01-01 or produces an error.
INNER JOIN table3 AS T3
   ON T3.date = DATE(T1.date, 'unixepoch')

some random examples from the database

*

*T1.Date       T3.Date

*17432         12/28/2017

*17460         12/20/2017

*17464         12/25/2017

*17440         12/17/2017

*17500         12/05/2017

Update: I have converted the T1.Date to a DATE using the following Select statement, still looking to figure out how to convert the 'text' MM/DD/YYYY T3.Date in order to join
SELECT DATE('1970-01-01',  '+' || T1.Date || ' day') FROM T1

A: You may use the following join logic:
FROM table1 AS T1
INNER JOIN table3 AS T3
    ON substr(T3.Date,7) || substr(T3.Date,1,2) || substr(T3.Date,4,2)  =
       datetime(T1.date, 'unixepoch')

Note that while it is bad to store your dates in the format MM/DD/YYYY as text, it might be equally bad to store dates as different formats.

A: The date/time functions are highly database-specific.  However, I would do this by converting the unix epoch format to a date:
from table1 t1 join
     table3 t3
     on t1.date = date '1970-01-01' + t3.date * interval '1 day'

I should note that Unix epoch usually refers to the number of seconds or milliseconds since 1970-01-01, but that is easily adjusted in the interval expression.
The above is ANSI SQL.  Hence, it probably only works as written in Postgres.  But similar functionality is available in other databases, just with different syntax.


text:
Q: Folium changes default marker icon to info sign when adding color I am creating map of servers from a list. I have a function that filters these server and I would like to change marker color based on these filters. However, when I add color to marker as seen bellow, marker icon changes to info-sign and color is ignored. Anyone please know how to bypass this problem?
    for node in nodes:
        name = node[2]
        if node[-2] == 'unknown' or node[-1] == 'unknown':
            continue
        x = float(node[-2])
        y = float(node[-1])
        text = """
            NODE: %s, IP: %s
            URL: %s
            FULL NAME: %s
            LATITUDE: %s, LONGITUDE: %s
            """ % (node[2],
                   node[1],
                   node[7],
                   node[8],
                   node[9],
                   node[10])
        popup = folium.Popup(text.strip().replace('\n', '<br>'), max_width=1000)
        folium.Marker([x, y],popup=popup, icon=folium.Icon(color=color)).add_to(map_full)

    map_full.save('plbmng_server_map.html')

color is set at the beginning and can be one of the ['yellow', 'blue', 'red']

A: You could always just add icon='None' to your arguments for folium.Icon().
Also be aware of the difference between color and icon_color.


text:
Q: Retrieve XML-TEI information through XSLT I am a rookie and I would like to ask you the following questions:
I am using the XML-TEI language to study a manuscript. I would be interested in retrieving the proper names of the manuscript (marked with the [name] tag) through an XSLT stylesheet with information about its location (page [pb], chapter [div2], column [cb] and line [lb ].I have tried to write this data in a table, but it is impossible for me.
This is a fragment of the XML of the manuscript:

<?xml version="1.0" encoding="UTF-8"?>
<?xml-model href="http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng" type="application/xml" schematypens="http://relaxng.org/ns/structure/1.0"?>
<?xml-model href="http://www.tei-c.org/release/xml/tei/custom/schema/relaxng/tei_all.rng" type="application/xml"
 schematypens="http://purl.oclc.org/dsdl/schematron"?>
<TEI xmlns="http://www.tei-c.org/ns/1.0">
   <teiHeader>
      <fileDesc>
         <titleStmt>
            <title>Title</title>
         </titleStmt>
         <publicationStmt>

Publication Information

         </publicationStmt>
         <sourceDesc>

Information about the source

         </sourceDesc>
      </fileDesc>
   </teiHeader>
   <text>

<pb n="001r"/>
         <div1 type="book" n="01">

            <div2 type="chapter" n="001">
               <hi rend="red">Delas obras que <name type="proper">dios</name> fizo en los
                        prime<lb n="31"/>ros <num>.vj.</num> dias. </hi>
               <ab><add place="margin">I</add>
                  <phr function="time">Quando nuestro sennor <lb n="32"/><name type="proper"
                        >dios</name> crio enel comienço <phr function="list">el çielo<lb n="33"/>et
                        la tierra & todas las cosas que<lb n="34"/>enellos son</phr></phr>. <phr
                     function="source">segund quelo cuenta <name type="proper">moysen</name>
                     <phr function="adjetive" type="explanatory">que fue<lb n="35"/><phr
                           type="syntagm" function="copulative"><phr type="syntagm"
                              function="copulative" n="1">santo</phr> & <phr type="syntagm"
                              function="copulative" n="2">sabio</phr></phr></phr>. & otros
                     muchos <phr function="adjetive" type="restrictive">que acordaron con
                     el</phr></phr>.<lb n="36"/>departiolo & fizo lo todo en seys dias <phr
                     function="cataphoric">desta<lb n="37"/>guisa</phr>. <phr function="list">¶ <phr
                        function="list" n="1">El primero dia crio <phr type="syntagm"
                           function="copulative"><phr type="syntagm" function="copulative" n="1">la
                              luz</phr>. & <phr type="syntagm" function="copulative" n="2"
                                 >todas<lb n="38"/>las naturas delos angeles buenos et malos.<lb
                                 n="39"/><phr function="adjetive" type="explanatory">que son las
                                 criaturas spiritales</phr></phr></phr></phr>. ¶ Et partio<lb n="40"
                     />esse dia la luz delas tiniebras. Et ala luz<lb n="41"/>
                     <pb n="1v"/>
                     <cb n="a"/><lb n="1"/> llamo dia. & alas tiniebras noche. ¶ <phr
                        function="list" n="1">El<lb n="2"/> segundo dia fizo el firmamento. &
                        partio con el<lb n="3"/> las aguas de suso delas de deyuso</phr>. ¶ <phr
                        function="list" n="4">El terce<lb n="3"/> ro dia ayunto todas las aguas <phr
                           function="adjetive" type="restrictive">que so el çielo<lb n="5"/> son.
                              <phr function="explicative">los mares & las otras aguas dulces.
                                 <phr function="explicative">de<lb n="6"/> rios & de
                                 fuentes</phr></phr></phr>. & <phr function="time">quando las
                           aguas fueron <phr type="syntagm" function="copulative"><phr
                                 type="syntagm" function="copulative" n="1">a<lb n="7"/> partadas
                                 & <phr type="syntagm" function="copulative" n="1">ayuntadas en
                                    un logar</phr></phr></phr>. paresçio<lb n="8"/> lo seco que es
                           dicho tierra. Et crio estonçes <name type="proper">dios</name> en<lb
                              n="9"/> la tierra las yeruas & los aruoles de todas<lb n="10"/>
                           naturas</phr>. ¶ <phr function="list" n="4">El quarto alumbro los çielos
                           & la ti<lb n="11"/> erra con el sol & con la luna & con las
                              estrellas.<lb n="12"/> & puso las enel firmamento. El sol pora el
                              dia.<lb n="13"/> & la luna & las estrellas pora la
                        noche</phr>. ¶ <phr function="list" n="5">El<lb n="14"/> quinto dia fizo los
                           peçes & las aues de todas<lb n="15"/> maneras. Et bendixo los &
                           dixo que creçiessen<lb n="16"/> & amuchiguassen. & enchiessen las
                              aguas<lb n="17"/> & la tierra</phr>. ¶ <phr function="list"
                           n="final">El sexto dia crio las bestias<lb n="18"/> grandes & las
                           pequennas de todas naturas</phr></phr>.</phr> ¶ Et<lb n="19"/> esse dia
                  mesmo formo all omne a su yma<lb n="20"/> gen & asu semeiança que fuesse
                  adelantado & se<lb n="21"/> nnor de todas las otras criaturas que so el cielo
                     son.<lb n="22"/>
                  <add place="margin"> ¶</add>
                  <phr function="incise" type="absolute">Et faziendol <phr type="syntagm"
                        function="copulative"><phr type="syntagm" function="copulative" n="1">asu
                           ymagen</phr> & <phr type="syntagm" function="copulative" n="2">asu
                           semeiança</phr></phr></phr>. crio<lb n="23"/>
                  <phr type="syntagm" function="copulative"><phr type="syntagm"
                        function="copulative" n="1">los maslo</phr> & <phr type="syntagm"
                        function="copulative" n="2">fenbra</phr></phr>. <phr function="source">assi
                     como lo departen<lb n="24"/>
                     <phr type="syntagm" function="copulative"><phr type="syntagm"
                           function="copulative" n="1"><phr function="list"><phr function="list"
                                 n="1"><name type="proper">moysen</name></phr> & <phr
                                 type="syntagm" function="copulative" n="2"><name type="proper"
                                    >iheronimo</name></phr></phr> enel primero capitulo<lb n="25"/>
                           del <name type="book">genesis</name></phr>. <phr function="list" n="2">Et
                              <name type="proper">iosepho</name> otrossi enel primero<lb n="26"/>
                           dela estoria dela antiguedat delos iudios</phr>.<lb n="27"/>
                        <phr function="list" n="final"><add place="margin"> Et</add> otros muchos
                           quelo affirman con ellos</phr></phr></phr>. Et desi<lb n="28"/> bendixo
                  los <name type="proper">dios</name> & dixo les <quote type="indirect"
                     source="Dios"><phr type="coord" function="copulative"><phr type="coord"
                           function="copulative" n="1.1">que creçiessen &<lb n="29"/>
                           <phr type="coord" function="copulative" n="1.2">amuchiguassen</phr> &
                              <phr type="coord" function="copulative" n="1.3">enchiessen la
                              tierra</phr></phr>. & <phr type="coord" function="copulative"
                           n="final">quela<lb n="30"/> assennoreassen so el su
                     poder</phr></phr></quote>. <phr function="incise" type="absolute">bendiziendo
                        a<lb n="31"/> ellos</phr>. bendixo alas animalias dela tierra<lb n="32"/> en
                  ellos. ¶ Et mando que<phr type="syntagm" function="copulative"><phr type="syntagm"
                        function="copulative" n="1">los omnes</phr> & <phr type="syntagm"
                        function="copulative" n="final"> </phr></phr><lb n="33"/> animalias. <phr
                     type="coord" function="copulative"><phr type="coord" function="copulative"
                        n="1">comiessen</phr> & <phr type="coord" function="copulative"
                        n="final">uisquiessen <phr function="list"><phr function="list" n="1">delas
                              yeruas</phr><lb n="34"/>
                           <phr function="list" n="2">dela tierra</phr> & <phr function="list"
                              n="3">delas simientes della</phr>. & <phr function="list"
                              n="final">delas<lb n="35"/> fruytas delos
                     aruoles</phr></phr></phr></phr>. ¶ Enpos esto to<lb n="36"/> do cato nuestro
                  sennor <name type="proper">dios</name> todas las cosas <phr function="adjetive"
                     type="restrictive">que<lb n="37"/> auie fechas</phr>:' & uio que eran muy
                     buenas.<lb n="38"/>
                  <add place="margin"> Et</add> fue todo acabado de fazer. <emph>enel sexto di<lb
                        n="39"/> a</emph>. <phr function="cataphoric"><phr function="incise"
                        type="source" n="Moises">Como oyredes que diz <name type="proper"
                           >moysen</name> adelante</phr></phr>.<lb n="40"/>
               </ab>
            </div2>
         </div1>

   </text>
</TEI>

Here is the stylesheet that I created, in which I do not get anything ...

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"
    xmlns:tei="http://www.tei-c.org/ns/1.0">
    <xsl:output method="html"/>

    <xsl:template match="/">

                <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

Nombres propios

                        Nombres
                        Folio
                        Columna
                        Línea
                        Capítulo

                <xsl:apply-templates select="//tei:name[@type = 'proper']"/>

    </xsl:template>
    <xsl:template match="//tei:name[@type = 'proper']">

                    <xsl:value-of select="."/>

                <xsl:value-of select="node() "/>

    </xsl:template>
</xsl:stylesheet>


text:
Q: embedded sign using docusign without template id I create one form and these form is store in database and generate one pdf i want to get sign in this PDF with embedded rest api, I can done this with templateID but i don't use template i want to use my own pdf to signature..
I use below code for using templateId
$data = array("accountId" => $accountId,
    "emailSubject" => "DocuSign API - Embedded Signing Example",
    "templateId" => $templateId,
    "templateRoles" => array(
        array( "roleName" => $templateRoleName,
                "email" => $emailSender,
                "name" => $recipientName,
                "clientUserId" => $clientUserId
            )
        ),
    "status" => "sent");

Thank You

A: Have you read through the DocuSign Developer Center yet?  There's a features section that covers embedded signing (and sending) which shows an example that does not use a template.
You'll want to create a request that looks like this:
{
    "status": "sent",
    "emailSubject": "Envelope with Embedded Signer",
    "documents": [{
        "documentId": "1",
        "name": "contract.pdf",
        "documentBase64": "base64 document bytes...",
    }],
    "recipients": {
        "signers": [{
            "email": "john@email.com",
            "name": "John Doe",
            "recipientId": "1",
            "clientUserId": "1234"
        }]
    }
}

See the embedded signing section.


text:
Q: Preventing bash $PS4 from replicating first character According to the bash manual (emphasis mine):

PS4
  The value is the prompt printed before the command line is echoed when the -x option is set (see The Set Builtin). The first character of PS4 is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is '+ '.

Is there a way to disable this behavior? I thought of cursor left (\b), but bash seems to only consider the literal first character (\).

A: You can set PS4 to have its first character to be NUL, which takes no space on screen:
export PS4="\000 "

You will then have no visual indication of how deeply-nested the commands in question are.

A: @DopeGhoti's answer did not work for me but this did
PS4='\033[0D'

It moves the cursor 0 characters to the left, so it's basically a NOOP.


text:
Q: How to instantiate classes only from inside another class in Haxe I need to prevent class A from being instantiated anywhere but only from another class B, then class B can return the created instance of class A which can be used in any other class.
I understand that B could be a Factory in this example, I looked in the factory pattern in the Haxe code cookbook but it does not seem suit what I am looking for.
In my example class B is doing some work then should return the result in an instance of class A.
no one should be able to create an instance of class A because it is the result of the work that class B performs. anyone needs an instance of A should ask B to do the work and return the resulted A instance
hope I explained it clearly

A: You would usually do this by using @:allow() metadata in combination with a private constructor:
A.hx:
class A {
    @:allow(B)
    private function new() {}
}

B.hx:
class B {
    public static function create():A {
        return new A(); // compiles
    }
}

Trying to instantiate A outside of B will result in a compiler error:
class Main {
    static function main() {
        new A(); // Cannot access private constructor of A
    }
}

Note that it's still possible to work around this by using @:access() or @:privateAccess metadata - in Haxe, nothing is ever truly private. It follows a philosophy of "the programmer knows best", which can be very powerful.
Also, you might want to declare A as @:final so nothing can subclass it, because subclasses can access private fields in Haxe. But again, this can be overriden with @:hack metadata.


text:
Q: Android - Storing data without a database My application records user movement with Geofence boundaries, if the user exits the Geofence, alerts are appropriately escalated. These alert are counted and displayed in a summary at the end of the activity. However I would like to create a stats page where it displays the last week or month of activities as well as the number of alerts so that I can display these in a chart. Is there anyway to do this effectively without using a database?
I had thought of writing data to a log file and reading it but curious as to if there is a better option.

A: You can use java serialization if you dont want to use database.
You can also use XML/JSON for storing data.

A: You can use SharedPreferences but it will require a lot of controls, probably more then creating a database. If you insist not to use a database, put an integer to your shared preferences saving the count of your data, also that integer will become your id. Then you can store your data with a loop depending on your data.
Here is to write your data to shared preferences
SharedPreferences mSharedPrefs = getSharedPreferences("MyStoredData",
                MODE_PRIVATE);
        private SharedPreferences.Editor mPrefsEditor = mSharedPrefs.edit();

        int count = mSharedPrefs.getInt("storedDataCount", 0);

        for(int i = 0 ; i < yourCurrentDataCount ; i++) {
            mPrefsEditor.putInt("data" + count, yourData.get(i));
            count++;
        }
        mPrefsEditor.putInt("storedDataCount", count);

And to get your data,
int count = mSharedPrefs.getInt("storedDataCount", 0);
for(int i = 0 ; i < count ; i++) {
            yourData.add(mSharedPrefs.getString("data" + i, "defaultData"));
            count++;
        }

Edit:
I should have added some explaining. The idea is to save the count of your data to generate an id, and save the tag according to it. This code will work like this, lets say you have 5 strings. Since you don't have a MyStoredData xml, it will get created. Then since you don't have the "storedDataCount" tag, you will get 0 as a count. Your loop will iterate 5 times and in each iteration, you will add a tag to your xml like "<.data0>your first data<./data0><.data1>your second data <./data1>... After your loop is done, you will modify your storedDataCount and it will become <.storedDataCount>5<./ storedDataCount>. And the next time you use your app, your count will start from 5 so your tag will start from <.data5>. For reading, you will iterate through tags by checking "data0", "data1" and so on.

A: I support already mentioned favoritism towards using a DB for this task. Nevertheless, if I were to do it via FS, I would use a transactional async library like Square's tape is.
In your case I would keep the data during a session in JSON object (structure) and persist it (in onPause()) and restore it (in onRestore()) with tape's GSON Object Converter.
Should be easy out of the box, I believe.
Tape website: http://square.github.io/tape/
Alternatively to manually persisting a file or using a 3rd party library like tape, you could always (de)serialize your JSON to SharedPreferences.