text:
Q: AWS SES, email attachment sends base64 string instead converting into DOCX format Requirement
What I am trying to do is, First I will download a document from S3 Bucket, Then sending that document through SES, sendRawEmail method as attachment with the file downloaded from S3.
What I Did till Now
I have downloaded the file from S3, I can send a mail with attachment. It reaches the destination as expected(form.docx)
Error
When I am sending the attachment, I have to append the base64 (which is the attachment)String in the formdata. I am attaching the string. But When I download the attachment. There I can see, inside the form.docx, there is converted base64 string inside the attachment. It is not as expected. I should see tables and some fill in the blanks kind of thing. But here it is a very big base64 string
Code
const AWS = require('aws-sdk');
const S3= new AWS.S3();
let ses = new AWS.SES();
exports.hello = async (event, context) => {
  try {
    const valueFromBucket = await S3.getObject({Bucket: '*******', Key: 'form.docx'}).promise();
    var buffer = valueFromBucket.Body.toString('base64');
    var message = '
 This is a test Message
';
    var fromEmail = '******@gmail.com';
    var toEmail = '*******@gmail.com';
    var ses_mail = "From: 'Email' <" + fromEmail + ">\n";
    ses_mail = ses_mail + "To: " + toEmail + "\n";
    ses_mail = ses_mail + "Subject: Subject Email\n";
    ses_mail = ses_mail + "MIME-Version: 1.0\n";
    ses_mail = ses_mail + "Content-Type: multipart/mixed; boundary=\"NextPart\"\n\n";
    ses_mail = ses_mail + "--NextPart\n";
    ses_mail = ses_mail + "Content-Type: text/html; charset=iso-8859-1\n\n";
    ses_mail = ses_mail + message+"\n";
    ses_mail = ses_mail + "--NextPart\n";
    ses_mail = ses_mail + "Content-Type: application/msword\n";
    ses_mail = ses_mail + "Content-Disposition: attachment; filename=\"form.docx\"\n\n";
    ses_mail = ses_mail + "Content-Transfer-Encoding: base64\n\n"
    ses_mail = ses_mail + buffer + "\n";
    ses_mail = ses_mail + "--NextPart--";

    var params = {
        RawMessage: { Data: new Buffer(ses_mail)},
        Destinations: [ "*******@gmail.com" ],
        Source: "'AWS Tutorial Series' <" + fromEmail + ">'"
    };
    const sendPromise = await new AWS.SES({ apiVersion: "2010-12-01" })
    .sendRawEmail(params)
    .promise();
    return{
      statusCode: 200,
      body: JSON.stringify(sendPromise)
    }
  }
  catch (err) {
    return {
      statusCode: err.statusCode || 400,
      body: err.message || JSON.stringify(err.message)
    }
  }
}

Any help or suggestions much appreciated
Thanks in Advance

A: The problem is that your code has two newlines for one of your section part headers.
Change this line of code:
ses_mail = ses_mail + "Content-Type: multipart/mixed; boundary=\"NextPart\"\n\n";

to this:
ses_mail = ses_mail + "Content-Type: multipart/mixed; boundary=\"NextPart\"\n";


text:
Q: match a variable with at least one value in an array - php I have one variable that comes from a database.
I then want to check whether that value is the same of one of the values in an array.
If the variable matches one of the array values, then I want to print nothing, and if the variable does not match one of the array values, then I want to print something.
This is the code I have been trying without luck, I know that contains is not valid code, but that is the bit I cannot find any info for:
<?php
$site = getStuff();
$codes = array('value2', 'value4');
if ($codes contains $site)
{
echo "";
}
else
{
echo "something";
?>

So if the database would return value1 for $site, then the code should print "something" because value1 is not in the array.

A: The function you are looking for is in_array.
if(in_array($site, array('value2', 'value4')))

A: if(!in_array($site,$codes)) {
    echo "something";
}

A: To provide another use way to do what the other answers suggest you can use a ternary if
echo in_array($site, $codes)?"":"something";

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular Js & html not able to clear the data using angular Js. I have assigned the value to null and empty. when i debug it the values are getting cleared but in front end the values are not clearing
                         $scope.callCancel = function() {
                 $scope.riskObj.areaName ="";
                 $scope.areaName ="";
                 $scope.riskObj.areaDesc ="";
                 $scope.areaDesc =""

            html code:

Risk Area Name

                    <input type="text" class="form-control input-sm text-field" data-ng-model="areaName" ng-keyup="getChangedAreaName(areaName)" ng-disabled="type == 2">

Risk Area Description

                    <input type="text" class="form-control input-sm text-field" data-ng-model="areaDesc" ng-keyup="getChangedAreaDesc(areaDesc)" ng-disabled="type == 2">

I need to clear the values I enter in the front end. Using the above code I am able to clear already entered data. But once I modify the value and call cancel function the values are not getting cleared

A: The main issue is you're not setting your ng-model accurately. For example, it should bind to riskObj.areaName as that is your data model, not just areaName. Additionally, you should be initializing these objects in your scope somewhere, like $scope.riskObj = {areaName:'', areaDesc:''};
There are a few issues with your code other than that.

*

*Utilize your anchor tags to be ng-click. Don't have an anchor with a hash for HREF and then put an ng-click inside on an image. Instead, just do something like <a href ng-click="...

*You have 3 divs in a row with ng-if="type==1" - why not just put those 3 in a
 - cleaner and easier to read/maintain

*Inside those conditionals, you have a ng-disabled="type==2" -- that will never ever do anything since the div will ONLY show if type=1

angular.module('selectExample', [])
  .controller('ExampleController', ['$scope', function($scope) {
    $scope.type = 1;
    $scope.riskObj = {
      areaName: '',
      areaDesc: ''
    };
    $scope.callCancel = function() {
      $scope.riskObj.areaName = "";
      $scope.areaName = "";
      $scope.riskObj.areaDesc = "";
      $scope.areaDesc = ""
    }
  }]);

Risk Area Name

          <input type="text" class="form-control input-sm text-field" data-ng-model="riskObj.areaName">

Risk Area Description

          <input type="text" class="form-control input-sm text-field" data-ng-model="riskObj.areaDesc">

        cancel


text:
Q: How do I copy a Shape from one Powerpoint presentation to another in VBA? I have VBA code to copy shapes matching a certain criteria from one Powerpoint presentation to another below.  However, when it pastes the shape, it is offset (down and to the right) from the original position.  How can I copy a shape while maintaining the original coordinates?
sourceShape.Copy
Presentations(2).Windows(1).Activate
ActivePresentation.Slides(x).Shapes.Paste (1)

A: Perhaps simply:
Shape s=ActivePresentation.Slides(x).Shapes.Paste (1)

s.Left=sourceShape.Left

s.Top=sourceShape.Top


text:
Q: Long-standing effort? Does long-standing sound right to native speakers in this context? Example: Your long-standing effort has paid off.
Does this sound idiomatic?

A: Given the fact that I would personally use long-lasting efforts, replacing standing with lasting and making it plural, I checked something objective and queried Google Books Ngram Viewer.
According to it, while the plural form is the more common, so, too, is long-standing, at least in printed form.

Per this, your use of long-standing effort (or long-standing efforts) is just fine.


text:
Q: One to many webrtc I want to create an "one to many" (with the max of 3 devices) webrtc setup. I have one device that is my main device. Other devices are connecting to that device. You can think about an walky talky. With one device who they are connecting to.
I have this code that works with an one to one connection.
import AVFoundation
import UIKit
import WebRTC
import SocketIO
import CoreTelephony
import ReachabilitySwift

let TAG = "ViewController"
let AUDIO_TRACK_ID = TAG + "AUDIO"
let LOCAL_MEDIA_STREAM_ID = TAG + "STREAM"

class ViewController: UIViewController, RTCPeerConnectionDelegate, RTCDataChannelDelegate {

    var mediaStream: RTCMediaStream!
    var localAudioTrack: RTCAudioTrack!
    var remoteAudioTrack: RTCAudioTrack!
    var dataChannel: RTCDataChannel!
    var dataChannelRemote: RTCDataChannel!

    var roomName: String!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        initWebRTC();
        sigConnect(wsUrl: "http://192.168.1.69:3000");

        localAudioTrack = peerConnectionFactory.audioTrack(withTrackId: AUDIO_TRACK_ID)
        mediaStream = peerConnectionFactory.mediaStream(withStreamId: LOCAL_MEDIA_STREAM_ID)
        mediaStream.addAudioTrack(localAudioTrack)
    }

    func getRoomName() -> String {
        return (roomName == nil || roomName.isEmpty) ? "_defaultroom": roomName;
    }

    // webrtc
    var peerConnectionFactory: RTCPeerConnectionFactory! = nil
    var peerConnection: RTCPeerConnection! = nil
    var mediaConstraints: RTCMediaConstraints! = nil

    var socket: SocketIOClient! = nil
    var wsServerUrl: String! = nil
    var peerStarted: Bool = false

    func initWebRTC() {
        RTCInitializeSSL()
        peerConnectionFactory = RTCPeerConnectionFactory()

        let mandatoryConstraints = ["OfferToReceiveAudio": "true", "OfferToReceiveVideo": "false"]
        let optionalConstraints = [ "DtlsSrtpKeyAgreement": "true", "RtpDataChannels" : "true", "internalSctpDataChannels" : "true"]

        mediaConstraints = RTCMediaConstraints.init(mandatoryConstraints: mandatoryConstraints, optionalConstraints: optionalConstraints)

    }

    func connect() {
        if (!peerStarted) {
            sendOffer()
            peerStarted = true
        }
    }

    func hangUp() {
        sendDisconnect()
        stop()
    }

    func stop() {
        if (peerConnection != nil) {
            peerConnection.close()
            peerConnection = nil
            peerStarted = false
        }
    }

    func prepareNewConnection() -> RTCPeerConnection {
        var icsServers: [RTCIceServer] = []

        icsServers.append(RTCIceServer(urlStrings: ["stun:stun.l.google.com:19302"], username:"",credential: ""))

        let rtcConfig: RTCConfiguration = RTCConfiguration()
        rtcConfig.tcpCandidatePolicy = RTCTcpCandidatePolicy.disabled
        rtcConfig.bundlePolicy = RTCBundlePolicy.maxBundle
        rtcConfig.rtcpMuxPolicy = RTCRtcpMuxPolicy.require
        rtcConfig.iceServers = icsServers;

        peerConnection = peerConnectionFactory.peerConnection(with: rtcConfig, constraints: mediaConstraints, delegate: self)
        peerConnection.add(mediaStream);

        let tt = RTCDataChannelConfiguration();
        tt.isOrdered = false;

        self.dataChannel = peerConnection.dataChannel(forLabel: "testt", configuration: tt)

        self.dataChannel.delegate = self
        print("Make datachannel")

        return peerConnection;
    }

    // RTCPeerConnectionDelegate - begin [ ///////////////////////////////////////////////////////////////////////////////

    /** Called when the SignalingState changed. */
    public func peerConnection(_ peerConnection: RTCPeerConnection, didChange stateChanged: RTCSignalingState){
        print("signal state: \(stateChanged.rawValue)")
    }

    /** Called when media is received on a new stream from remote peer. */
    public func peerConnection(_ peerConnection: RTCPeerConnection, didAdd stream: RTCMediaStream){
        if (peerConnection == nil) {
            return
        }

        if (stream.audioTracks.count > 1) {
            print("Weird-looking stream: " + stream.description)
            return
        }
    }

    /** Called when a remote peer closes a stream. */
    public func peerConnection(_ peerConnection: RTCPeerConnection, didRemove stream: RTCMediaStream){}

    /** Called when negotiation is needed, for example ICE has restarted. */
    public func peerConnectionShouldNegotiate(_ peerConnection: RTCPeerConnection){}

    /** Called any time the IceConnectionState changes. */
    public func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceConnectionState){}

    /** Called any time the IceGatheringState changes. */
    public func peerConnection(_ peerConnection: RTCPeerConnection, didChange newState: RTCIceGatheringState){}

    /** New ice candidate has been found. */
    public func peerConnection(_ peerConnection: RTCPeerConnection, didGenerate candidate: RTCIceCandidate){

            print("iceCandidate: " + candidate.description)
            let json:[String: AnyObject] = [
                "type" : "candidate" as AnyObject,
                "sdpMLineIndex" : candidate.sdpMLineIndex as AnyObject,
                "sdpMid" : candidate.sdpMid as AnyObject,
                "candidate" : candidate.sdp as AnyObject
            ]
            sigSendIce(msg: json as NSDictionary)

    }

    /** Called when a group of local Ice candidates have been removed. */
    public func peerConnection(_ peerConnection: RTCPeerConnection, didRemove candidates: [RTCIceCandidate]){}

    /** New data channel has been opened. */
    public func peerConnection(_ peerConnection: RTCPeerConnection, didOpen dataChannel: RTCDataChannel){
        print("Datachannel is open, name: \(dataChannel.label)")
        dataChannel.delegate = self
        self.dataChannelRemote = dataChannel
    }

    // RTCPeerConnectionDelegate - end ]/////////////////////////////////////////////////////////////////////////////////

    public func dataChannel(_ dataChannel: RTCDataChannel, didReceiveMessageWith buffer: RTCDataBuffer){
        print("iets ontvangen");
    }

    public func dataChannelDidChangeState(_ dataChannel: RTCDataChannel){
        print("channel.state \(dataChannel.readyState.rawValue)");
    }

    func sendData(message: String) {
        let newData = message.data(using: String.Encoding.utf8)
        let dataBuff = RTCDataBuffer(data: newData!, isBinary: false)
        self.dataChannel.sendData(dataBuff)
    }

    func onOffer(sdp:RTCSessionDescription) {
        print("on offer shizzle")

        setOffer(sdp: sdp)
        sendAnswer()
        peerStarted = true;
    }

    func onAnswer(sdp:RTCSessionDescription) {
        setAnswer(sdp: sdp)
    }

    func onCandidate(candidate:RTCIceCandidate) {
        peerConnection.add(candidate)
    }

    func sendSDP(sdp:RTCSessionDescription) {
        print("Converting sdp...")
        let json:[String: AnyObject] = [
            "type" : sdp.type.rawValue as AnyObject,
            "sdp"  : sdp.sdp.description as AnyObject
        ]

        sigSend(msg: json as NSDictionary);
    }

    func sendOffer() {
        peerConnection = prepareNewConnection();
        peerConnection.offer(for: mediaConstraints) { (RTCSessionDescription, Error) in

            if(Error == nil){
                print("send offer")

                self.peerConnection.setLocalDescription(RTCSessionDescription!, completionHandler: { (Error) in
                    print("Sending: SDP")
                    print(RTCSessionDescription as Any)
                    self.sendSDP(sdp: RTCSessionDescription!)
                })
            } else {
                print("sdp creation error: \(Error)")
            }

        }
    }

    func setOffer(sdp:RTCSessionDescription) {
        if (peerConnection != nil) {
            print("peer connection already exists")
        }
        peerConnection = prepareNewConnection();
        peerConnection.setRemoteDescription(sdp) { (Error) in

        }
    }

    func sendAnswer() {
        print("sending Answer. Creating remote session description...")
        if (peerConnection == nil) {
            print("peerConnection NOT exist!")
            return
        }

        peerConnection.answer(for: mediaConstraints) { (RTCSessionDescription, Error) in
            print("ice shizzle")

            if(Error == nil){
                self.peerConnection.setLocalDescription(RTCSessionDescription!, completionHandler: { (Error) in
                    print("Sending: SDP")
                    print(RTCSessionDescription as Any)
                    self.sendSDP(sdp: RTCSessionDescription!)
                })
            } else {
                print("sdp creation error: \(Error)")
            }

        }
    }

    func setAnswer(sdp:RTCSessionDescription) {
        if (peerConnection == nil) {
            print("peerConnection NOT exist!")
            return
        }

        peerConnection.setRemoteDescription(sdp) { (Error) in
            print("remote description")
        }
    }

    func sendDisconnect() {
        let json:[String: AnyObject] = [
            "type" : "user disconnected" as AnyObject
        ]
        sigSend(msg: json as NSDictionary);
    }

    // websocket related operations
    func sigConnect(wsUrl:String) {
        wsServerUrl = wsUrl;

        print("connecting to " + wsServerUrl)
        socket = SocketIOClient(socketURL: NSURL(string: wsServerUrl)! as URL)

        socket.on("connect") { data in
            print("WebSocket connection opened to: " + self.wsServerUrl);
            self.sigEnter();
        }
        socket.on("disconnect") { data in
            print("WebSocket connection closed.")
        }
        socket.on("message") { (data, emitter) in
            if (data.count == 0) {
                return
            }

            let json = data[0] as! NSDictionary
            print("WSS->C: " + json.description);

            let type = json["type"] as! Int

            if (type == RTCSdpType.offer.rawValue) {
                print("Received offer, set offer, sending answer....");
                let sdp = RTCSessionDescription(type: RTCSdpType(rawValue: type)!, sdp: json["sdp"] as! String)
                self.onOffer(sdp: sdp);
            } else if (type == RTCSdpType.answer.rawValue && self.peerStarted) {
                print("Received answer, setting answer SDP");
                let sdp = RTCSessionDescription(type: RTCSdpType(rawValue: type)!, sdp: json["sdp"] as! String)
                self.onAnswer(sdp: sdp);
            } else {
                print("Unexpected websocket message");
            }
        }

        socket.on("ice") { (data, emitter) in
            if (data.count == 0) {
                return
            }

            let json = data[0] as! NSDictionary
            print("WSS->C: " + json.description);

            let type = json["type"] as! String

            if (type == "candidate" && self.peerStarted) {
                print("Received ICE candidate...");
                let candidate = RTCIceCandidate(
                    sdp: json["candidate"] as! String,
                    sdpMLineIndex: Int32(json["sdpMLineIndex"] as! Int),
                    sdpMid: json["sdpMid"] as? String)
                    self.onCandidate(candidate: candidate);
            } else {
                print("Unexpected websocket message");
            }
        }

        socket.connect();
    }

    func sigRecoonect() {
        socket.disconnect();
        socket.connect();
    }

    func sigEnter() {
        let roomName = getRoomName();
        print("Entering room: " + roomName);
        socket.emit("enter", roomName);
    }

    func sigSend(msg:NSDictionary) {
        socket.emit("message", msg)
    }

    func sigSendIce(msg:NSDictionary) {
        socket.emit("ice", msg)
    }
}

So I thought that I need an array with the peers. And the mediaStream, localAudioTrack and the dataChannel needs to be one object because the local audio is the same? Are there good solutions for this? Because I don't know how to properly implement this.
I am investigating different questions and project referencing to an multi call webrtc setup.
I saw this (website) webrtc setup at GitHub:
https://github.com/anoek/webrtc-group-chat-example/blob/master/client.html
I'm going to try to reverse engineer this to swift:). Any help is really appreciated.

A: I would suggest against a one-to-many architecture where a single device needs to send its media to all others. This breaks awfully fast (like after 2-3 devices it needs to connect to).
The reason for that is that uplinks are usually limited in capacity and even when they aren't, devices aren't really geared to streaming so much data to many other devices.
To do what you want at "scale", use a server component that routes media to the other devices. Look at https://jitsi.org/ and http://www.kurento.org/ for starting points.

A: What you're trying to achieve can be achieved by multi-peer connection. Where one creates multiple peer connection with others which is a mesh topology from application level of view. This is most straight forward way and if it's the case that you're recently learning WebRTC and learnt how to implement a peer-connection you may try how to handle multiple peer connections. Look at this for more details on it click. But in practical where you will have dozens of clients, it will become hard because it will eats up the hardware resources and bandwidth. In that case what people do is: they maintain a shared server where all the client connects to and that server mixes the individual streams and distribute it. Which is a start topology. There are some well-known services for this like- tokbox, jitsi-meet.
You may also like to look into SFU model- https://webrtcglossary.com/sfu/


text:
Q: difference between leftJoin Yii2 and Raw SQL I want to use left join in my code and when I use Yii2 left join the result of code is not correct and it removes some records but when I use Raw SQL left join with given command the result is right:
sql : (it's correct)
SELECT tour_date.id as tdid,tour.*, tour_package.*, tour_package.id AS tpid
FROM tour_date
LEFT JOIN tour_package ON tour_date.tour_id=tour_package.tour_id
LEFT JOIN tour ON tour.id=tour_package.tour_id
WHERE tour_package.id

yii2 query : (it's wrong)
$tourQuery = TourDate::find()
        ->select(['tour_date.id as tdid','tour.*', 'tour_package.*', 'tour_package.id AS tpid'])
        ->leftJoin(TourPackage::tableName(), 'tour_date.tour_id=tour_package.tour_id')
        ->leftJoin(Tour::tableName(), 'tour.id=tour_package.tour_id')
        ->where(['tour_package.id' => $tourPackageId]);

A: If I get you right, you mean that you have two representations of the same query you want to execute.. and the former RAW query gives you the desired result, while Yii2-style query not.
Simply analyzing your queries I've noticed that WHERE clause in the former query is incomplete (you do not pass ID param), so it will not filter by tour_package.id attribute and you get more rows than expected..
Anyway if that is not the case, you can easily check what kind of query is generated from Yii2 QueryBuilder by calling
echo $tourQuery->createCommand()->rawSql;

So it'll give you the following result:
SELECT
  `tour_date`.`id` AS `tdid`, `tour`.*, `tour_package`.*, `tour_package`.`id` AS `tpid`
FROM `tour_date`
  LEFT JOIN `tour_package` ON tour_date.tour_id = tour_package.tour_id
  LEFT JOIN `tour` ON tour.id = tour_package.tour_id
WHERE `tour_package`.`id` = <your_id>

..compare this with your raw-query, and you'll find the answer

A: Your  two query are not the same
in RAW sql (first)  you have WHERE tour_package.id  where tour_package.id have not condition .
in Yii2 ActiveQuery sintax (second query)  you have ->where(['tour_package.id' => $tourPackageId]);  where tour_package.id must be equal to $tourPackageId.
so the two query return different result because are different query  ..
assuming the value of  $tourPackageId is 1
You should at least use WHERE tour_package.id = 1
However remeber also that  use of where conidtion in  leftjoin work as a inner join  ..
so for a correct use of where in left join  you should use the condition inside left join condition and not in explicit where
$tourQuery = TourDate::find()
    ->select(['tour_date.id as tdid','tour.*', 'tour_package.*', 'tour_package.id AS tpid'])
    ->leftJoin(TourPackage::tableName(), 'tour_date.tour_id=tour_package.tour_id
              and tour_package.id = ' . $tourPackageId)
    ->leftJoin(Tour::tableName(), 'tour.id=tour_package.tour_id ')


text:
Q: Can I get the first X bytes from AWS S3 using Go SDK 2 I would like to get the first X Bytes from a very large CSV file. I basically just want to get the first two rows so I get the column names and an example of the data in each. However, I know that this isn't going to be possible so I would like to just download enough bytes to reasonably have enough data to be able to look at the first two rows. I am therefore trying to download the first 64kB.
I am trying to do this using the s3 manager ( https://github.com/aws/aws-sdk-go/blob/master/service/s3/s3manager/download.go )
I tried using something like :
downloader := s3manager.NewDownloaderWithClient(svc, func(d *s3manager.Downloader) {
    d.PartSize = 1024 * 64
    d.Concurrency = 1
})

`
This hangs though. I'd imagine I am just telling it to download the file with a small part size and it stops there and never returns anything.
Can anybody cleverer than me tell me how I can download just the first X bytes of an S3 file in go?
Thanks!


text:
Q: Are there any battery-powered Ethernet-to-Wireless adaptors? Consider the following situation. I have several non-PC devices (e.g. robots & network cameras) and a PC on a wired network. The non-PC devices have an ethernet port and I plug LAN cables between them and the switch.
Normal wireless adapters come as USB sticks which you connect to the PC. So, is there a wireless adapter (battery powered) which I can plug into the ethernet port of my non-PC device which connects to a wireless router?

A: I didn't really enjoy EE classes, but I found an interesting discussion here that seems to boil down to this being somewhat unfeasible due to the power draw:

I looked at a couple of Access Points and 6 watts was about the lowest power that I saw. That was 12 v @ 500 ma. The "big" 9v batteries are 1100 mah, so they would last a little over 2 hours at that drain.

A: My associate who is the robotics expert suggests   Phoenix Contact

A: Iogear Ethernet-2-WiFiUniversal Wireless Adapter


text:
Q: Is server to server email transmission secure? We are running a website with a web to email form. We force https to secure the transmission from the browser to the web server. From the web server we use PHP to generate an email message containing the information received. The destination email server is in another location. I am wondering if the transmission of the email from the web server to the destination email server is secure.
So I have several related questions:
A) Is the transmission of emails from the sender server to the recipient server secured by default? (To be clear, this is NOT a question about the connection from an email client to an SMTP server)
B) if the transmission is not secured by default, how can I check if messages are being transmitted securely?
C) if transmission is currently not secured, how can I request/force a secure connection?
We are using the default PHP mail function (via a Joomla extension)
Thank you!

A: A) initially, a server-to-server smtp connection is always in plain text on port 25.
if both source and target server support the TLS extension then usually the plain connection gets converted into a encrypted connection with the STARTTLS command
B) To check if a mail was transmitted over an encrypted connection, read the "Received"-Headers in the resulting message after it was transmitted.
They look like this:
Received: from X.example.com (X.example.com [y.y.y.y])
    by z.example.net (Postfix) with ESMTPS id ......

The important part is the ESMTPS bit. The last S means "SECURED".
If it just says "ESMTP" or "SMTP" instead of "ESMTPS" the transmission was not encrypted.
C) if the target server does not support TLS there is nothing you can do except some sort of end-to-end encryption like PGP (as suggested by Álvaro G. Vicario). Some servers (like postfix) provide configuration options to prevent messages from going out at all if the target can not do TLS.
you can test manually with telnet if a server supports STARTTLS:
telnet gmail-smtp-in.l.google.com 25
Trying 173.194.70.27...
Connected to gmail-smtp-in.l.google.com.
Escape character is '^]'.
220 mx.google.com ESMTP 4si1878861eee.197 - gsmtp
EHLO mail.example.com              <--- you have to type that
250-mx.google.com at your service
250-SIZE 35882577
250-8BITMIME
250-STARTTLS                       <----- GMAIL supports TLS
250 ENHANCEDSTATUSCODES

A: In fact, I think it is a question about connection from an e-mail client to SMTP server after all. When source server connects to destination server to deliver a message it becomes a client. It uses the SMTP protocol just like your desktop e-mail program. There's a very important difference, though:

*

*When you use a regular e-mail client you normally use the same trusted provider that can (and should) offer certain security measures, including authentication and encryption.

*When a mail server connects to a third-party server, it connects anonymously and it needs to establish an unencrypted connection to port 25. They don't have a prior agreement to do things otherwise.
Given that the channel is in clear, server-to-server communication is not secure unless the message itself is encrypted (PGP or whatever). You can think of e-mail messages like snail mail post-cards.
(For this reason, those sites that e-mail your password in clear when you sign up are doing it wrong.)

A: With due respect to the very good answers so far, in Joomla! the SMTP mail function is handled by JMail which extends from the PHPMailer class. When setting up Joomla! you have three different options:

*

*PHP Mail - uses PHP mail() settings via PHPMailer.

*Sendmail - uses sendmail  via PHPMailer...

*SMTP - uses PHPMailer class

The PHPMailer class supports both tls and ssl in it's SMTP connection negotiation.
Of course, this is dependent on you setting it up your in Global Configuration->Server. In the pane titled Mail Settings you can turn on SMTP Security (SSL|TLS) and provide your Username and Password. These details are required to authenticate with your SMTP server.


text:
Q: Do something when a view loads I am making a quiz app and want it to have a 'witty remark' when it loads based on their score. For example...
Score 50 points : Good Job!
Score 100 points : You Rock!
Score 150 points : You're So Money!
And stuff like that. Any help is appreciated. Thanks!
Note: The last question of the quiz is a different .xib than the .xib with the witty remark.
The witty remark will be displayed with a UILabel. And each time the user answers a question, it adds to their score. I would also appreciate help for this part as I am not quite sure that the way I am using is the best way to do it. Heres my code:
-(IBAction)a {

switch(questionNumber)
{
    case 0:
        question.text = @"This is question one";
        questionNumber = 1;
        myScore = myScore + 1;
        break;

    case 1:
        question.text = @"This is question two";
        answerA.text = @"Yes";
        answerB.text = @"No";
        [answerC setHidden:YES];
        [answerD setHidden:YES];
        [answerButton3 setHidden:YES];
        [answerButton4 setHidden:YES];
        questionNumber = 2;
        myScore = myScore = 2;
        break;

and so on for the other questions.

A: I don't think you need to extend a UIView to do this.  You should be able to implement a UIViewController and use the viewDidLoad method to set the text into the UILabels at that time.
The steps would be:
1) Make a view-based XIB with the UILabel in it
2) Make a class that extends UIViewController with an IBOutlet for the UILabel
3) Add properties in the UIViewController for the score
4) Make the owning class of the XIB the extended UIViewController
5) Wire the UILabel to the UILabel outlet
6) Uncomment the viewDidLoad method in the extended UIViewController
7) Do your tests there
8) In the class that is loading the XIB and pushing it onto the view stack, set the score property in the new UIViewController (just after creation of the controller and before pushing it on the stack
9) Magical witty comments appear!

A: i think the best approch would be that u make a subclass of UIView which has one UILabel (displaying the Q) and four buttons for four options and two mthods and to dispaly the Q in right way (as I can guess that some of ur Q has 2 option and some have 4), and second method checks that the tapped answer is correct or not.
And make another subClass of NSObject which has few properties like
NSString* question;
NSArray* options;//[option count] = total button to dispaly
NSUInteger* correctOption;//index of correct answer
Now the first method in ur UIView subClass takes an object of this second class as an argument and display it accordingly;


text:
Q: White Space Appears Right of Browser Window When at Full Screen There is a giant rectangle of white space to the right and bottom of the browser window when it is at full screen. Does anybody know how to get rid of this?
JSFiddle: http://goo.gl/mTWfsj

A: You have this style on .copyright2
.copyright2{

    position: relative;
    left: 17.5%;
}

p {
    width: 100%;
}

So .copyright2 has width: 100% and start at left: 17.5%
To fix it remove left: 17.5% from .copyright2
Here a minimal example to illustrate:

.red{
  background: red;
  height: 100px;
}

.blue{
  background: blue;
  height: 50px;
  position: relative;
  left: 50px;
}


text:
Q: Conseguir o valor máximo de uma soma SQL SERVER Eu preciso saber o maior valor de uma soma, como fazer ?
select cod_prod,sum (quantidade) as quantidade from produtos
group by cod_prod

A: Você poderia fazer dessa maneira, apenas adicionando o "TOP" e o "ORDER BY"
SELECT TOP 1 cod_prod, sum (quantidade) as quantidade
FROM produtos
GROUP BY cod_prod
ORDER BY quantidade DESC


text:
Q: How to do downgrading cuda version I'm currently using the cuda version 4.2 but I need to change it to 3.1. Is it possible to uninstall the current version (ver 4.2) and then install the previous version (ver 3.1) ?
EDIT : Please refer that my os system is linux ubuntu 10.04 64bit.
EDIT : I found how to get the version of 3.1. I have to send e-mail to "devzoneupdate@nvidia.com" to request this old version. Now, please let me know how to uninstall 4.2 then install 3.1.
EDIT : I downloaded cuda 3.1 by request to nvidia, then installed toolkit and SDK. When install the cuda 3.1 toolkit there comes the question about uninstallation of current version. For SDK, we can just delete ~/NVIDIA_GPU_Computing_SDK directory directly for the uninstallation of it. After deleting I could install the cuda 3.1 SDK. I'm done, thanks all.

A: Yes, you can easily downgrade the CUDA version provided you aren't using the CUDA toolkit functions which are only present in version greater than 3.1.
Also you would have to modify your project settings to use CUDA Rules version 3.1.

A: WARNING:
ubuntu 12.04 upgraded to 12.10 with standard cuda 4.2 installed; in the process of downgrading to CUDA 4.0 using NVIDA installer resulted the !! COMPLETE REMOVAL !! /usr/bin/
probably is a good idea to choose "NO" when removing existing CUDA installation is offered; though I never got to try it as only already loaded firefox remained functional.


text:
Q: How to reach parent parent text using jquery? Using this.parentElement.parentElement.textContent = this.textContent; i change the parent of partent text from whatever clickedelement is!
The block which contains that is:
$(".class99 li").click(function (event) {
   var text_parrent = $(this).text();//new code
   //new code
   this.parentElement.parentElement.textContent = this.textContent;
});

How to get the parent of the parent using jquery?
I wish to be compatible with .empty() and .append() methods!
Also, I need to change in this method because the page is more dynamically and is changed and changed multiple time!

A: The equivalent jQuery code uses the .parent() method.
$(".class99 li").click(function (event) {
   var text_parrent = $(this).text();
   $(this).parent().parent().text(text_parrent);
});


text:
Q: MySQL show records month wise I have some records in my Database table.
User passes the start and the end date and then expects an output. If a user passes the start and end date for same month then it should show only one record, but if the end date is extended one or more month then it should displays month wise record.
For now I am able to collect total data while following this query.
SELECT m.data_date_time
     , SUM(m.kwh) total_kwh
     , m.cust_id Customer_ID
     , m.msn
  FROM mdc_meters_data m
 WHERE m.data_date_time >= '2020-04-01 00:00:00'
   AND m.data_date_time <= '2020-05-31 00:00:00'

Output
Data_Date_Time      == total_kwh == Customer_ID == MSN
2020-04-01 11:44:13 || 95585     || 37010114707 || 7898985212

Expected Output
As the month end date is 05 so it should show two records like below
Data_Date_Time      == total_kwh == Customer_ID == MSN
2020-04-01 11:44:13 || 50000     || 37010114707 || 7898985212
2020-05-01 10:25:05 || 45585     || 37010114707 || 7898985212

I have tried to put GroupBy data_date_time but it doesn't helped me out.
How can I do this ?
Any help would be highly appreciated.

A: SELECT m.data_date_time AS 'Data_Date_Time', SUM(m.kwh) AS total_kwh, m.cust_id AS 'Customer_ID', m.msn AS MSN, date_format(data_date_time, "%Y-%m") as monYear
FROM mdc_meters_data m WHERE m.data_date_time >=
2020-04-01 00:00:00' AND m.data_date_time`<='2020-05-31 00:00:00' group by monYear
Hope it will help you for getting idea

A: please check this answer
    SELECT m.`data_date_time` AS 'Data_Date_Time', SUM(m.`kwh`) AS total_kwh, m.`cust_id` AS 'Customer_ID', m.`msn` AS MSN
FROM table AS r JOIN (
        SELECT MAX(m.`data_date_time`) AS data_date_time
        FROM table AS t
        GROUP BY YEAR(m.`data_date_time`), MONTH(t.data_date_time)
    ) AS x USING (data_date_time)

`mdc_meters_data` m WHERE m.`data_date_time`>='2020-04-01 00:00:00' AND m.`data_date_time`<='2020-05-31 00:00:00'

A: You will have to use GROUP BY the correct manner.
SELECT DATE_FORMAT('m.`data_date_time`, '%Y-%m') AS Data_Date_Time,
       SUM(m.`kwh`) AS total_kwh,
       m.`cust_id` AS Customer_ID,
       m.`msn` AS MSN
FROM `mdc_meters_data` m
WHERE m.`data_date_time`>='2020-04-01 00:00:00' AND m.`data_date_time`<='2020-05-31 23:59:59'
GROUP BY Customer_ID, Data_Date_Time, MSN

Now the problem with the above query is that you don't need to group your results by MSN
One workaround is to use any_value function around your nonaggregated MSN columns in the select list. This will just pick any MSN value from the matching list and make sure you will still have only 2 entries shown in the results.
SELECT any_value(DATE_FORMAT('m.`data_date_time`, '%Y-%m')) AS Data_Date_Time,
       SUM(m.`kwh`) AS total_kwh,
       m.`cust_id` AS Customer_ID,
       any_value(m.`msn`)
FROM `mdc_meters_data` m
WHERE m.`data_date_time`>='2020-04-01 00:00:00' AND m.`data_date_time`<='2020-05-31 23:59:59'
GROUP BY Customer_ID, Data_Date_Time

Also, note how the 31st of May has been included in your query by giving by extending the range to the time 23:59:59.


text:
Q: Need help solving the ODF $ f''(r) + \frac{1}{r}f'(r) = 0 $ I am currently taking complex analysis, and this homework question has a part that requires the solution to a differential equation. I took ODE over 4 years ago, so my skills are very rusty. The equation I derived is this:
$$ f''(r) + \frac{1}{r}f'(r) = 0 $$
I made this substitution: $ v(r) = f'(r) $ to get get:
$$ v'(r) + \frac{1}{r}v(r) = 0 \implies \frac{dv}{dr} = - \frac{v}{r} \implies \frac{dv}{v} = - \frac{dr}{r} $$
Unsure of what to do now.
Edit: I forgot to add that the answer is $ a \log r + b $

A: Another way of doing this (which gets to the required form quicker in my opinion) is noticing that
$$ f''(r) + \frac{1}{r}f'(r) = 0 \implies \frac{1}{r}\left(r f'(r)\right)'=0$$
$$ \implies r f'(r) = c$$
$$ \implies  f'(r) = \frac{c}{r}$$
$$ \implies  f(r) = c \log(r) + d$$
where $c$ and $d$ are arbitary constants.

A: You now have:
1/v dv = -1/r dr
We can integrate this:
ln(v) = -ln(r) + C1
v = e^(-ln(r) + c1)
v = 1/r + c1
Thus we have:
df/dr = 1/r + c1 (since v = f'(r) = df/dr)
df = (1/r + c1) dr
f = ln(r) + c1(r) + c2
And thats our answer!


text:
Q: Measuring distance between two points I want to measure the distance between two points using scikit-image. Here is the image:

In the above photo I want to measure the distance between the red point and black point. The unit of measurement does not matter to me as I want to normalize the distance by the end of the day. Any idea how I can do it?
Thanks

A: You could get the job done through the following stepwise procedure:

*

*Compute distance from each pixel to red and black colors.

*Binarize using an appropriate threshold.

*Perform morphological closing.

*Determine the centroid coordinates of the resulting blobs.

*Calculate the distance between centroids.

Hopefully the code below will put you on the right track:
import numpy as np
from skimage import io
from skimage.morphology import closing
from skimage.measure import regionprops
import matplotlib.pyplot as plt
from matplotlib.patches import ConnectionPatch

img = io.imread('https://i.stack.imgur.com/vbOmy.jpg')

red = [255, 0, 0]
black = [0, 0, 0]

threshold = 10

dist_from_red = np.linalg.norm(img - red, axis=-1)
dist_from_black = np.linalg.norm(img - black, axis=-1)

red_blob = closing(dist_from_red < threshold)
black_blob = closing(dist_from_black < threshold)

labels = np.zeros(shape=img.shape[:2], dtype=np.ubyte)
labels[black_blob] = 1
labels[red_blob] = 2

blobs = regionprops(labels)

center_0 = np.asarray(blobs[0].centroid[::-1])
center_1 = np.asarray(blobs[1].centroid[::-1])

dist = np.linalg.norm(center_0 - center_1)

Demo
fig, ax = plt.subplots(1, 1)
ax.imshow(img)

con = ConnectionPatch(xyA=center_0, xyB=center_1,
                      coordsA='data', arrowstyle="-|>", ec='yellow')
ax.add_artist(con)

plt.annotate('Distance = {:.2f}'.format(dist),
             xy=(center_0 + center_1)/2, xycoords='data',
             xytext=(0.5, 0.7), textcoords='figure fraction', color='blue',
             arrowprops=dict(arrowstyle="->", color='blue'))
plt.show(fig)


text:
Q: Android Inflating multiple layouts inside a fragment I am working in a fragment. When the fragment is called it inflates a layout. Which all works.
 v = createTreeView( inflater,  container,  savedInstanceState);

On my action bar I have a search button which Onclicks changes the layout
btnSearch.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View arg0) {
             v = createFliterLivstView( linflate, VContainer);
             count = 1;

            Log.i("Create","creating tree view kind of ");
        }
});

Both views work separately, but when I move the createFilterListView to the OnClick functions it does nothing. The Log has been processed which means it is running through. It just is not inflating the layout.
Below is the onCreateView
@Override
public View onCreateView(  LayoutInflater inflater,   ViewGroup container,  final  Bundle savedInstanceState) {
     linflate = inflater;
     VContainer  =  container;

    m_Context = inflater.getContext();
    thisApp = (ThisApp)getActivity().getApplicationContext();

    v = createTreeView( inflater,  container,  savedInstanceState);

     FragmentActivity actionBar = getActivity();
     View d =  actionBar.getActionBar().getCustomView().findViewById(R.id.btn_search);
     ImageButton btnSearch = (ImageButton)d.findViewById(R.id.btn_search);

     btnSearch.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View arg0) {
             v = createFliterLivstView( linflate, VContainer);
             count = 1;

            Log.i("Create","creating tree view kind of ");
        }
    });

     View b =  actionBar.getActionBar().getCustomView().findViewById(R.id.btn_cancel_search);
     ImageButton btnCancelSearch = (ImageButton)b.findViewById(R.id.btn_cancel_search);
     btnCancelSearch.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View arg0) {

                 v = createTreeView( linflate,  VContainer,  savedInstanceState);
        }
    });

    return v;
}

Any help would be greatly appreciated. Thank you in advance.
private View  createFliterLivstView( LayoutInflater inflater, ViewGroup container){
    View v1 = linflate.inflate(R.layout.list_main, VContainer, false);

    historyContainer = (FrameLayout)v1.findViewById(R.id.history_container_layout);
     FragmentActivity actionBar = getActivity();
     View d =  actionBar.getActionBar().getCustomView().findViewById(R.id.txtSearch);

    EditText filterEditText = (EditText)d.findViewById(R.id.txtSearch);

    filterEditText.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            Log.i("anish", s.toString());
            historyContainer.removeAllViews();
            final List<String> tempHistoryList = new ArrayList<String>();
            tempHistoryList.addAll(historyList);

            for(String data : historyList) {
                if(data.indexOf(s.toString()) == -1) {
                    tempHistoryList.remove(data);
                }
            }

            viewStub = new ViewStub(getActivity().getBaseContext(), R.layout.history_schedule);

            viewStub.setOnInflateListener(new ViewStub.OnInflateListener() {

                @Override
                public void onInflate(ViewStub stub, View inflated) {
                    setUIElements(inflated, tempHistoryList);
                }
            });

            historyContainer.addView(viewStub);
            viewStub.inflate();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
    setViewStub();
    return v1;
}

Below is the CreateTreeView
private View createTreeView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
    View v = inflater.inflate(R.layout.layout_list_symptoms, container, false);
    makeList();

    Button btnNext = (Button)v.findViewById(R.id.btn_next);
    btnNext.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View arg0) {

            String bsafe = thisApp.app_pref.getString("BSAFE", "0");
            if(bsafe==null || bsafe.equalsIgnoreCase("0")) {
                thisApp.app_edit.putString("SYMTOMS", "");
                thisApp.app_edit.commit();
            }

            Set<Long> sel = fancyAdapter.selected;
            Iterator<Long> it = sel.iterator();
            boolean hasDone = false;
            int i = 0;
            while(it.hasNext()) {

                Long longId = it.next();
                //Log.i(TAG, "...id = " + longId);

                final Integer[] hierarchy = fancyAdapter.getManager().getHierarchyDescription(longId);

                // 5678
                WorkVO vo = list.get(longId.intValue());

                try {

                     pnObj.put("value" , jsonArr.put(vo.getName()) );

                    //i++;
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                hasDone = true;
            }

            jsonSymptoms.put(pnObj);

            Log.i("Symtoms ", "      json="+ jsonSymptoms.toString());
            thisApp.app_edit.putString("SYMTOMS", jsonSymptoms.toString());
            thisApp.app_edit.commit();

            if(hasDone) {
                if(bsafe!=null && bsafe.equalsIgnoreCase("1")) {
                    mCallback.onNextWork(DefinedConstants.FRAG_BSAFE_REPORT);
                } else {
                    mCallback.onNextWork(DefinedConstants.FRAG_FATIGUE_RATING);
                }
            } else {
                Toast.makeText(getActivity(), "Please make a selection", 0).show();
            }
        }
    });

    TreeType newTreeType = null;
    boolean newCollapsible;
    if (savedInstanceState == null) {
        manager = new InMemoryTreeStateManager<Long>();
        final TreeBuilder<Long> treeBuilder = new TreeBuilder<Long>(manager);
        for (int i = 0; i < NODES.length; i++) {
            treeBuilder.sequentiallyAddNextNode((long) i, NODES[i]);
        }
        //Log.d(TAG, manager.toString());
        newTreeType = TreeType.FANCY;
        newCollapsible = true;
    } else {
        manager = (TreeStateManager<Long>) savedInstanceState
                .getSerializable("treeManager");
        if (manager == null) {
            manager = new InMemoryTreeStateManager<Long>();
        }
        newTreeType = (TreeType) savedInstanceState
                .getSerializable("treeType");
        if (newTreeType == null) {
            newTreeType = TreeType.SIMPLE;
        }
        newCollapsible = savedInstanceState.getBoolean("collapsible");
    }
    treeView = (TreeViewList) v.findViewById(R.id.mainTreeView);
    fancyAdapter = new FancyColouredVariousSizesAdapter(getActivity(), selected,
            manager, LEVEL_NUMBER, job_kind, list);
    simpleAdapter = new SimpleStandardAdapter(getActivity(), selected, manager,
            LEVEL_NUMBER, job_kind, list);
    setTreeAdapter(newTreeType);
    setCollapsible(newCollapsible);
    registerForContextMenu(treeView);

    manager.collapseChildren(null);

    return v;
}

A: Inflate a view with this method.
View v = View.inflate(m_context,R.layout.yourlayout,null);

A: The createView method returns a View which sets the view for the fragment. What you are doing in the onClick is creating a view that isn't overriding your fragments main view.
To be honest it would be much easier and would require less state logic if on click you replaced the Fragment with a new Fragment with the layout you wanted.
Having a Fragment that handles two separate layouts is harder to maintain and to keep the correct state. Not to mention will make the class much larger.


text:
Q: Rotating a selection of features around their individual centroid rather than the combined centroid The rotate feature in QGIS 3 allows you to select multiple features at once and rotate them around the centroid of their combined geometries, as found in the documentation.
You can also use an anchor point different from the default feature centroid by pressing Ctrl or if you hold Shift before clicking on the map, the rotation will be done in 45 degree steps, which can be modified afterwards in the user input widget.
I would like to rotate a selection of multiple features around each features individual centroid?
Is this possible?

A: *

*Check Rotate tool in the QGIS's Toolbox. Leave Rotation anchor point blank.

*

*Or in edit mode, select features, enter Rotate in search box in status bar and use Rotate tool under Edit Selected Features. Again leave the second box blank,  so that the tool will use individual centroid of selected features.


text:
Q: How do I view all my bookmarks across all communities? How do I view all my bookmarks across all communities? I.e., see all bookmarks between Stack Overflow and Software Engineering and so on without needing to search through each one individually.
I know this is answered somewhere on meta, but for the life of me, I can't find it (ironically, I forgot to bookmark it). I'm hoping this will make it easier to search in the future.

A: You can find it in your network profile, it's one of the tabs there. Or you can use this direct link: https://stackexchange.com/users/current?tab=bookmarks. Here's how it looks like for me:

As @ShadowWizard notes in the comments, it only shows the 150 highest scoring/newest/... bookmarked questions (depending on the tab). If you want a complete list, you'll need the Stack Exchange Data Explorer. I wrote (kind of) that query here: Cross-site inbookmarks:mine search – it allows requires you to search for a keyword as well, which isn't a bad idea in such a long list.


text:
Q: How to make sure C multithreading program read the latest value from main memory?
Let's say thread 1(executed in Core 0) updates a global variable, and the updated global value is cached in Core 0's L1 cache(not flushed to the main memory). Then thread 2 starts to execute in Core 3, and it tries to read the global variable, and read it from the main memory(since it doesn't have the cached value), so thread 2 is reading a outdated value.
I know in C you can use volatile to force the compilier do not read the value form CPU registers, which means that volatile varaible will get its value from cache or main memory. In my above scenario, even if I declare the global variable with volatile, the latest value will still be cached in L1 cache, the main memory still has an old value which will be read by thread 2. So how can we fix this issue?
or maybe my understanding is wrong, using volatile will make the variable updated in main memory directly so everytime you try to read/write a volatile variable, you read/write it from/to the main memory directly?

A: To some extent, people noting that the premise of your question is flawed is a reasonable answer. In general, this happens rarely if at all, and is usually indistinguishable from a race condition.
However yes it can happen. See for example memory barriers which are a great example of how such a condition (albeit due to OOO execution etc.) can occur.
That being said, what you're looking for to make sure the specific occurrence you've noted cannot happen is called a "cache flush". This can be genuinely important on ARM/ARM64 processors where separate data and instruction caches exist, but it's also a good habit to get into for data that is passed between threads this way. You can also check out the __builtin___clear_cache c compiler builtin which performs a similar task. Hopefully one of these will help you get to the bottom of your problem.
However, most likely you're not running into a caching issue, and a race condition is far more likely to be arising. If memory barriers/cache flushes don't fix your issue, audit your code very carefully for raciness.

A:
How to make sure C multithreading program read the latest value from main memory?

You probably want to use some thread library like POSIX threads. Read some Pthread tutorial, see pthreads(7) and use pthread_create(3),  pthread_mutex_init, pthread_mutex_lock,  pthread condition variables, etc etc
Read also the documentation of GNU libc and of your C compiler (e.g. GCC, to be used as gcc -Wall -Wextra -g) and of your debugger (e.g. GDB).
Be prepared to fight against Heisenbugs.
In general you cannot prove statically that your C program don't have race conditions. See Rice's theorem. You could use tools like Frama-C or the Clang static analyzer, or write your own GCC plugin, or improve or extend Bismon described in this draft report.
You could be interested by CompCert.
you cannot be sure that your program read the "latest" value from memory.
(unless you add some assembly code)
Read about cache coherence protocols.


text:
Q: How do I calculate and output punctuation marks using ispunct() for an input file I have a text file with a huge paragraph and I wanna be able to count and output all the punctuation marks in my file.. here is my code so far, it just prints "0"
Thanks.
int main(){
inFile.open("Horoscope.txt");
if (!inFile)
{
    cerr << "Error: Input file opening failed\n";
    return EXIT_FAILURE;
}

int punct = 0;
char input = ' ';
while (inFile >> input)
{
    if (ispunct(input))
    {
        punct++;
    }
    inFile.close();
    cout << "There are " << punct << " punctuation marks in the text file"
<< endl;
}
}

A: From what you have posted, it looks like you are closing the file in the loop, thus stopping the search.
Close the file once you are done with it.
#include <iostream>
#include <fstream>

int main() {
    std::ifstream inFile;
    inFile.open("Horoscope.txt");
    if (!inFile)
    {
        std::cerr << "Error: Input file opening failed\n";
        return EXIT_FAILURE;
    }

    int punct = 0;
    char input = ' ';
    while (inFile >> input)
    {
        if (ispunct(input))
        {
            punct++;
        }
    }
    inFile.close();
    std::cout << "There are " << punct << " punctuation marks in the text file" << std::endl;
}


text:
Q: angularjs conditional render tags with the same content I encountered a problem while working with AngularJS as below

Content

Content

Given this example, is it possible to not duplicate the Content text? i.e. can AngularJS renders the tags independently?

A: I am assuming that you want to disable your anchor tag right?
Try solution from this question:
AngularJS - ng-disabled not working for Anchor tag


text:
Q: Concat query mysql I have this table:
reference - model - category
0001     - NON     - 2
0001     - NON     - 5
0001     - NON     - 12
0001     - SAN     - 2
0001     - SAN     - 5
0001     - SAN     - 12

I am looking for this result:
reference - model - categories
0001     - NON     - 2,5,12
0001     - SAN     - 2,5,12

I tried with concat and group_concat without any result like this. Is this possible in this case?

A: Select reference, model, group_concat(category) categories From tableName
 group by reference, model


text:
Q: Interpreting Rpart.plot() for a Regression tree I generally understand the CART algorithm but the rpart.plot values are confusing me a bit. Below is a picture of my plot. What exactly is the root node value representing? I thought it would be the mean of the response variable for 100% of my observations but this doesn't hold true.
As you can see the mean value at the root node is -3.5e-18 but the mean for the response for all observations is actually 2.121501e-18. This average logic along other nodes deeper in the tree does hold true but for whatever reason the root node value doesn't actually correspond to my entire data's mean for the response.
So, what exactly is this value of my root node doing?
Below is my code:

library(rpart)
library(rpart.plot)

regression_tree1 <- rpart(Rented_Bike_Count ~., data = Train_set_standardized, method = "anova")
summary(regression_tree1)
rpart.plot(regression_tree1)

# this number  does not correspond correctly with the root node of the plot
> mean(Train_set_standardized$Rented_Bike_Count)
[1] 2.121501e-18

# this number corresponds with the rpart.plot perfectly
> sapply(Train_set_standardized[Train_set_standardized$Temperature < -0.074,"Rented_Bike_Count"], mean)
Rented_Bike_Count
       -0.5214802


text:
Q: Generics passing type parameters I'm using dependancy injection from Unity. i..e Unity.Mvc5. I fetch all types from the various assemblies
Assembly assembly = Assembly.LoadFrom(string.Format("{0}\\{1}", AppStartPath, containerElement.InterfaceAssembly));
Assembly assembly2 = Assembly.LoadFrom(string.Format("{0}\\{1}", AppStartPath, containerElement.ConcreteClassAssembly));
Type type = assembly.GetType(containerElement.InterfaceName);
Type type2 = assembly2.GetType(containerElement.ConcreteClass);

Now the following works when I pass the types:
  container.RegisterType<IWarehouseBinController, WarehouseBinController>();

But this doesn't
container.RegisterType<type.GetTypeInfo().GetType(), type2.GetTypeInfo().GetType()>();

Anyone know why or how to resolve it? Basically I want to use this in an ASP.Net MVC site.

A: refereeing to this link you can see how you can do dynamic registration of all types
of dependencies even the generic type , but please note that example using autofac library but i believe all of them same .
  var builder = new Autofac.ContainerBuilder();
var assembly = Assembly.GetExecutingAssembly();
var assemblyTypes = assembly.GetTypes();

foreach (var type in assemblyTypes)
{
    // Ignore interfaces
    if (type.IsInterface)
        continue;

    var typeInterfaces = type.GetInterfaces();

    // Class should implement IDependecy or ISingletonDependency
    if (!typeInterfaces.Any(i => i.IsAssignableFrom(typeof(IDependency))))
        continue;

    var registration = builder.RegisterType(type).AsImplementedInterfaces();

    if (typeInterfaces.Any(i => i.IsAssignableFrom(typeof(ISingletonDependency))))
        registration.SingleInstance();
    else
        registration.InstancePerRequest();
}


text:
Q: html5media extracted code not working I'm using the java script library html5media.min.js to play mp3 file in Firefox.
my problem is that when I add the script link to my page as:
<script src = "http://api.html5media.info/1.1.5/html5media.min.js" type="text/javascript"></script>

It is working fine.
But if I get the code and save it in a local file, it is not working!!
i.e.
<script src="Scripts/html5media.min.js" type="text/javascript"></script>

A: Just add this code into your page after the the script tag
html5media.flowplayerSwf = "/path/to/your/flowplayer.swf";
html5media.flowplayerAudioSwf = "/path/to/your/flowplayer.audio.swf";
html5media.flowplayerControlsSwf = "/path/to/your/flowplayer.controls.swf";

You can see this


text:
Q: Custom Claims backend and frontend currently trying to work on something which is Custom claim.
I am trying to look through google , but doesnt have any idea on how to do .
Basically , i want to make a simple web for my users to claim the tokens(already deployed) assign to their wallet address. which means , i will upload the batch of address and the amount that each address can claim onto the backend of the server. so i will need to connect the front end to backend , then the users will connect wallet to call the contract(connected to the wallet address for claims) and show their available balance to claim. then they will claim themselves.
So i will need a contract code, and a server(dashboard or something for the admin to add in more address in the future)
Hope that someone professional will guide me on what to do first. Thank you!


text:
Q: Append not accepting Attributes in Jquery Working in sharepoint and currently having trouble with managing dynamic tables using jquery.
I used append(), but when I put some attributes along with the elements it wont accept my code.
here it is:
$('#matters_table tr:last-child').append('
<input type="text"></input>
');

Most of us know that this would fire fine:
$('#matters_table tr:last-child').append('
<input ></input>
');

But in my case i want to add attributes to it, and even add some styles="width:95%" inside the  tags. pls help. I am new to jquery. I'm not that familiar with it.

A: You would .append() to the table, or .after() to the last row.  Right now you're trying to .append() the last row, which is effectively trying to nest a new row INSIDE of your row.
Should be as simple as:
$('#matters_table').append('
<input type="text"></input>
');

Or:
$('#matters_table tr:last-child').after('
<input type="text"></input>
');

Personally, I feel appending to the table is cleaner.

A: Pardon me, Now I know why my codes are spitted out in the form.
It is because of SHarepoint, it was not a jquery problem.
double quotes are messing my codes up
instead of:
$('#matters_table tr:last-child').append('
<input type="text"></input>
');

it should be:
$('#matters_table tr:last-child').append('
<input type='text'></input>
');

anyway thanks for the help guys.


text:
Q: allow only numbers and slash in textbox vba The following code allows only numbers to be typed in TextBox1. But TextBox1 is for insertion of history (Date) and I want to with format "0000/00/00". How can I exclude "/" from IsNumeric In the error message?
Private Sub textbox1_Change()
If Not IsNumeric(TextBox1.Value) Then
   MsgBox "only numbers allowed"
   With TextBox1
  .SetFocus
  .SelStart = 0
  .SelLength = Len(.Text)
   End With
End If
Dim strTemp As String
If TextBox1.TextLength = 8 Then
  Me.TextBox1.Value = Format(Me.TextBox1.Value, "0000/00/00")
End If
End Sub

A: Use the KeyPress or KeyDown event (KeyPress is probably easier to use) to manage which characters can be added.
In your case above, you must control the character range based on the length of the string in the field.

*

*First character must be a digit (check for ascii 0 to 9)

*Second character can be a digit or a \

*If the second character is a digit, then append a \ for them!

This pattern repeats for the next digit block. The final digit block could be 2 or 4 digits.
Edit: I have my blocks in the reverse order from the OP. The first block would only accept 4 digits followed by the \ and the other two digit blocks as described above. But the concept is still the same, use the Key* event to control what can be entered based on what string is already in the TextBox.
Don't enable the "OK" button unless the string is complete. This means not until in the third digit block, and then only if there are 2 or 4 digits in the digit block.
At all times, the "Cancel" button is enabled, so they can escape any time they want. The above approach does not guarantee a valid date (if that is what you want) so additional checks are required before enabling the "OK" button.
Using the above approach, and not allowing the user to accept an invalid number means less error checking in your other code!
Of course, you could also use a DateTimePicker!


text:
Q: Rails/Ruby: Any way to shorten the stack traces? I would like to limit the size of the stack traces I am seeing in Rails. I'm not really interested in debugging the Rails stack as much as my own application. Is there any built-in way to have Rails do this dynamically?

A: Yes. Take a look at the ActiveSupport::BacktraceCleaner class. Nice explanation here.

A: You could wrap the code with your own exception catcher and just output how much you want.
Using the array from the backtrace-Method
Only alternative I could think of. Recompiling Ruby and changing the values which control the stack depth in eval.c (TRACE_HEAD and TRACE_TAIL)


text:
Q: Include Properties at All Level My model is:
public class WhereClause
{
    [Key]
    public int Id { get; set; }

    public int? ColumnId { get; set; }

    [StringLength(100)]
    public string Logic { get; set; }

    [StringLength(250)]
    public string Value { get; set; }

    public List<WhereClause?> WhereClauses { get; set; }

    public short HierarchyCount { get; set; }
}

As you see, model contain self-list of object and i want to include all inner list in any level at one fetch. Based on Entity Framework - Include Multiple Levels of Properties I know that can use Include and ThenInclude but i don't know how many level of inner list in model. currently i store HierarchyCount property at model for this purpose and create string of include like .Include("WhereClauses,WhereClauses.WhereClauses,WhereClauses.WhereClauses.WhereClauses") . but are there any solution better of that?
Update:
WhereClause is part of Report Table and can't load whole WhereClause for every report query:
public class Report:ModelAbstract
{
    [Key]
    public int Id { get; set; }

    [Required]
    [StringLength(100)]
    public string Name { get; set; }

    [Required]
    public Table Table { get; set; }

    public List<SelectClause> SelectClauses { get; set; }

    [ForeignKey("WhereClause")]
    public int? WhereClauseId { get; set; }

    public WhereClause WhereClause { get; set; }
}

A: You can use Recursive CTE for such task. CTE will help to return all children objects then we can filter out root. Under hood, EF Core will correct children collections automatically.
var sql = @"
WITH Clauses AS
(
    SELECT
        Id
    FROM WhereClause
    WHERE Id = {0}
    UNION ALL
    SELECT
        w.Id
    FROM Clauses c
        JOIN WhereClause w ON w.WhereClauseId = c.Id
)
SELECT wc.*
FROM WhereClause wc
JOIN Clauses c ON wc.Id = c.Id";

var whereId = 7;
var whereClause = ctx.WhereClause
    .FromSqlRaw(sql, whereId)
    .ToList()
    .First(w => w.Id == whereId);


text:
Q: "AttributeError" using mainloop() function I got an error that says:
"AttributeError: 'NoneType' object has no attribute 'mainloop'"
I wrote my first GUI in python but I got an error using the mainloop function.
import tkinter as tk

root = tk.Tk().configure(bg="black")

def main():
    logo1 = tk.PhotoImage(file="C:\Logo1.png")
    logo2 = tk.PhotoImage(file="C:\Logo2.png")
    logo3 = tk.PhotoImage(file="C:\Logo3.png")

    # Creates labels
    lab1 = tk.Label(root, image=logo1).pack()
    lab2 = tk.Label(root, image=logo2).pack()
    lab3 = tk.Label(root, image=logo3).pack()

    root.mainloop()

if __name__ == "__main__":
    main()

A: The .configure() method doesn't return anything (i.e. implicitly returns None). Try this instead:
root = tk.Tk()
root.configure(bg="black")

A: You need to do something like this -
root = tk.Tk()
root.configure(bg="black")

And rest remains the same. The error is because the result of configure is None and NoneType has no attribute called mainloop.


text:
Q: php implode issue I have an array $x = array(a,b,c); Each element of the array is a  url.
There is a function link($x[$i]) which converts every element of the array into a hyperlink.
function convert($x){
 $new = explode(',',$x);
 for($i=0;$i<count($new);$i++){
   echo  link($new[$i]);  // converts the url to hyperlink
 }

This displays the output as url1  url2 etc. But wht if i want the comma ',' between the 2 urls. How do i get that, without the comma ',' being part of the hyperlink?
desired output would be
hyperlink1 , hyperlink2 etc  // note comma ',' should not be part of the hyperlink

A: You can use the array_map and implode functions to make this easy.
$urls = array('http://www.google.com/', 'http://www.stackoverflow.com/');

$links = array_map("link", $urls);
echo implode(', ', $links);

A: $x = array(
  'http://google.pl',
  'http://yahoo.com',
  'http://msn.com'
);

function convert($array){
    $res = array();
    foreach ( $array as $url ) {
        $res[] = '' . $url . '';
    }
    return implode(', ', $res);
}

echo convert($x);

A: function convert($x){
 for($i=0;$i<count($new);$i++){
   echo  link($new[$i]) . ($i<count($new)-1?", ":"");  // converts the url to hyperlink
 }

A: function convert($x){
    return implode(',', array_map('link', explode(',',$x)));
}

A: function convert($x)
{
 $string = '';

 foreach($x as $element)
 {
   $string .= link($element).',';
 }

 $string = rtrim($string, ',');

 echo $string;
}

This to avoid the last link to have a comma at the end, as you want.
// echoes link1,link2,link3

A: $x = array('foo', 'bar', 'baz');

// then either:
$x = array_map('link', $x);

// or:
foreach ($x as &$value) {
    $value = link($value);
}

echo join(', ', $x);

A: $output = '';
foreach (explode(',',$x) as $url)
  $output .= link($url);
$output = substr($output,0,-1);
echo $output;


text:
Q: fast string fixing Hi I'm trying to prove something and i would appreciate some help.
Given an uniformly 2n long randomly  selected string  of Parenthesis( "(",")" ) prove that
it is possible to generate  a valid sequence of parenthesis by changing  csqrt(nlogn) chars
at most where c is constant in probability of 1-o(1) .

A: Given a string of parentheses, and $i\in \{1,\dots,2n\}$, let $o_i$ be the number of open parentheses in the first $i$ symbols of the string, and let $c_i$ be the number of closed parentheses in this prefix. There are two quantities of interest:

*

*Let $X=o_{2n}-c_{2n}$ be the excess of open parentheses over closed parentheses.

*Let $Y=\max_{0\le i\le 2n}(c_i-o_i)$ be the worst case excess of closed parentheses over open parentheses in any prefix.
I claim that you can make a permutation valid in $O(X+Y)$ moves. This can be done as follows:

*

*As long as there is an unmatched closed parenthesis, flip the leftmost unmatched parenthesis. This decreases $Y$ by at least one, and increases $X$ by two.

*Then, until the number of parentheses of each type are equal, flip the rightmost open parenthesis. This decreases $X$ by two without changing $Y$.
Therefore, all that remains is to show that $X+Y$ is at most $c\sqrt{n\log n}$ with probability at least $1-o(1)$. It is easy to see this is true of $X$, since $X$ is approximately normal with a mean of $0$ and a variance of $O(\sqrt{n})$. The variable $Y$ is much trickier. However, using the reflection principle, you can show that $Y$ shares the same probabilistic bound.
To give some details, identify parenthesis string with lattice walks, where an open parenthesis is the step $(1,1)$ and a closed parenthesis is the step $(1,-1)$. Then $Y$ is the absolute value of the lowest height of the path, while $X$ is the final height of the path. You can then show that, for any $k\ge 0$,
$$
P(Y> k)\le 2P(X> k)\tag{*}
$$
This is because paths whose lowest height is at least $k$ come in two flavors:

*

*Those paths whose final height is less than $-k$; the probability of this is exactly $P(X>k)$.

*Those whose final height is more than $-k$, but which attain $-k$ at some intermediate point. By taking the first point this path hits $-k$ and reflecting everything (that is, switching $(1,-1)$ with $(1,1)$), you get a path whose final height is less than $-k$. Since this process is reversible, the probability of these paths is at most $P(X>k)$.
As long as you believe $(*)$, you know now that $Y$ enjoys the same probability bound that $X$ does, which means the same is true of $X+Y$.


text:
Q: Best practice with pyGTK and Builder XML files I usually design GUI with Glade, thus producing a series of Builder XML files (one such file for each application window).
Now my idea is to define a class, e.g. MainWindow, that inherits from gtk.Window and that implements all the signal handlers for the application main window. The problem is that when I retrieve the main window from the containing XML file, it is returned as a gtk.Window instance.
The solution I have adopted so far is the following:
I have defined a class "Window" in the following way
class Window():
def __init__(self, win_name):
    builder = gtk.Builder()
    self.builder = builder
    builder.add_from_file("%s.glade" % win_name)
    self.window = builder.get_object(win_name)
    builder.connect_signals(self)

def run(self):
    return self.window.run()

def show_all(self):
    return self.window.show_all()

def destroy(self):
    return self.window.destroy()

def child(self, name):
    return self.builder.get_object(name)

In the actual application code I have then defined a new class, say MainWindow, that inherits frow Window, and that looks like
class Main(Window):
def __init__(self):
    Window.__init__(self, "main")

### Signal handlers #####################################################

def on_mnu_file_quit_activated(self, widget, data = None):
    ...

The string "main" refers to the main window, called "main", which resides into the XML Builder file "main.glade" (this is a sort of convention I decided to adopt).
So the question is: how can I inherit from gtk.Window directly, by defining, say, the class Foo(gtk.Window), and recast the return value of builder.get_object(win_name) to Foo?


text:
Q: Growl notifications when a user logs in to Minecraft server? Would love to be able to get a Growl notification when a user logs in to my (locally hosted) Minecraft server.
I took a peek in the Console but it doesn't seem to record the logins, although my server GUI shows activity on the server including logins.
It runs within Java, so maybe that's the issue with it not showing up in the Console, although some of my actions do seem to get recorded, but those seem related to the main Minecraft app and not the server.
Even if I could find the logs, I am at a loss as to how one sets up a Growl notification, although I assume it has to do with growlNotify: http://growl.info/extras.php#growlnotify

A: The minecraft server writes a log file into the directory minecraft_server.jar is installed in. From there you can use something like
tail -f server.log |
  while read m_date m_time m_type m_user m_ip m_action m_rest; do
    if [[ $m_action == logged ]]; then
      growlnotify -n Minecraft -m "$m_user logged in at $m_date $m_time" Minecraft;
    fi
  done

Starting this automatically together with your Minecraft server is possible but depends on the way you do start it.
To install this (without going too deep into Unix territory, ask an expert if it fails):

*

*open Terminal.app

*change to the directory where minecraft_server.jar is installed by typing cd followed by drag&dropping the folder with the server into the terminal window followed by return

*nano mc2growl

*write #!/bin/bash and press return (twice)

*paste the code from above

*press ^X and say Y at the prompt

*chmod +x mc2growl

*./mc2growl &

A: (Full disclosure: This is my app.)
I've made an app for Mac and Windows that does this, even for vanilla servers and Minecraft Realms servers!
http://www.creeprapp.com


text:
Q: How to update items of iOS Carplay templates I'm trying to update old carplay to iOS14 support carplay.
Currently, I implemented most UIs.
Simply, my carplay structure looks like this.
| tab1 | *tab2 | tab3 |
---
| fixed item > |
| additional item 1 > |
| additional item 2 > |
| ... |

When user selects tab2, it should shows user's list with few fixed items.
At this point, my question is 'How to update additional items(CPListItem) of tab2'
Because when the carplay app is initialized, the data can not be ready.
So at the time I created tab2 template, there is no additinal item.
I thought I can update CPListItem array like
tabbarTemplate.templates.replaceSubrange(tab2-index...tab2-index, with: [newTemplate])

But tabbarTemplate template's templates is immutable (get-only).
now I update tabbarTemplate itself
var mutable = tabbarTemplate.templates // [tab1, tab2, tab3]
mutable.replaceSubrange(....)   // change tab2 with new template
tabbarTemplate.updateTemplates(mutable)

It looks weird to me because it updates tabbarTemplate, not tab2.
I wonder if there is better way to update tab2 items.
thanks

A: Use the CPTabBarTemplateDelegate method to update the contents of the template when it is selected :
func tabBarTemplate(_ tabBarTemplate: CPTabBarTemplate, didSelect selectedTemplate: CPTemplate) {
    if let secondTemplate = selectedTemplate as? CPListTemplate {
        secondTemplate.updateSections(...)
    }
}


text:
Q: sql/spark-sql: if statement syntax in a query I am looking into some existing spark-sql codes, which trying two join to tables as below:
items_t1_t2 as (
    select *,
    if(id_t1 is not Null, True, False) as in_t1,
    if(id_t2 is not Null, True, False) as in_t2
    from item_t2 full join item_t1
    on id_t2 = id_t1)

I am wondering why there is three elements in the if parentheses? What does the if statement mean here and how it works here? Thanks a lot!

A: The "IF" statement in Spark SQL (and in some other SQL dialects) has three clauses:
IF (condition_to_evaluate, result_if_true, result_if_false)

In this case, for instance, the expression:
IF(id_t1 IS NOT NULL, True, False) AS in_t1

Is logically equivalent to this one:
id_t1 IS NOT NULL AS in_t1

Or, to put it in another way: in_t1 is just a flag saying "if id_t1 is not null" and the same goes for in_t2 and id_t2.


text:
Q: C# WPF StartupEvent get path My objective is that when I open a file with a specific extension it will open my program in C#. That part is done but now I want to get the path of the file that I clicked on previously.
This is just the main code of App.xaml.cs:
/// <summary>
/// Logique d'interaction pour App.xaml
/// </summary>
public partial class App : Application
{
    private void Application_Startup(object sender, StartupEventArgs e)
    {

    }
}

Here are my two commands to associate my extension to my program.
    ftype GDevDB=N:\Divers\GDevDB\bin\Debug\GDevDB.exe "%1"
    assoc .GDevDB=GDevDB

Solution :
I've put the command in a batch file and the %1 was the one of the batch file and it was returning an empty string value.

A: The file you clicked on will be in the first command line argument. The arguments are in the array of strings e.Args, in the StartupEventArgs. For the file you clicked on, you thus need to get e.Args[0].

A: You can also use Environment.GetCommandLineArgs() If you need those somewhere else. Index 0 is the path to your program. Index 1 is the file you are looking for

A: Try to do this:
 public partial class App : Application
        {
            private void Application_Startup(object sender, StartupEventArgs e)
            {
                foreach (string arg in e.Args)
                {
                    //Do something
                }
            }
        }


text:
Q: Struggling to get/set inputText value I have been struggling with this for a while now and need some help. Below I have table of orders being displayed using <apex:repeat>. By doing this I can create a table for each order I want to display.
The problem I am having is in the <apex:form> section. I have two fields "Teacher" and "Teacher Wage" that I want the user to fill in and then save. For the teacher field this is a list of values for them to select and for teacher wage it is input text field. Whenever I click Save I the values selected and inputted are not being past over to the controller.
I have added debug logs to my code and can see the only value I can take across to the controller is the order Id.
Any ideas?
Visualforce Code:
<apex:pageBlock title="Order Dan Testing" >
        <apex:repeat value="{!aorders}" var="o" rows="100">

                    <button class="tbutton" value="{!o.OrderNumber}">+</button>
                     Class Id
                     Account Name
                     Programme
                     Programme Code
                     Class Start Date
                     Class End Date
                     Class Amount
                     Status
                     Teacher

                     Teacher Wage

                      <apex:outputLink value="/{!o.id}">{!o.OrderNumber}</apex:outputLink>
                     <apex:outputField value="{!o.AccountId}"/>
                     <apex:outputField value="{!o.Programme__r.Name}"/>
                     <apex:outputField value="{!o.Programme_Code__c}"/>
                     <apex:outputField value="{!o.EffectiveDate}"/>
                     <apex:outputField value="{!o.EndDate}"/>
                     <apex:outputField value="{!o.Total_Cost_Of_Class__c}"/>
                     <apex:outputField value="{!o.Status}"/>
                     <apex:outputField value="{!o.ClassTeacher__r.Name}"/>

                    <apex:form >
                         <apex:selectList value="{!selectedVal}" size="1">
                            <apex:selectOptions value="{!openPresentationOptions}" />
                            </apex:selectList>

                            <apex:inputText value="{!o.Teacher_Wages__c}"/>

                            <apex:commandLink action="{!saveS}" value="saveS">
                                <apex:param name="saveOrder" value="{!o.id}"/>
                            </apex:commandLink>

                    </apex:form>

APEX:
public String selectedVal{get;set;}

    public List<SelectOption > getopenPresentationOptions(){
        List<SelectOption> options = new List<SelectOption>();
        options.add( new SelectOption('0000','Choose Teacher'));
        for( Contact teacher : [ SELECT Id, Name FROM Contact WHERE Type__c = 'Teacher' order by Id desc] ) {
            options.add( new SelectOption(teacher.Id,teacher.name));
        }
        return options;
    }

public List<Order> aorders {

        get{
        aorders = [
            SELECT Id, OrderNumber, AccountId, EffectiveDate , EndDate, Status, Total_Cost_Of_Class__c,
            ClassTeacher__r.Name, Teacher_Wage__c, Programme__r.Name, Programme_Code__c, ClassTeacher__r.Id
            FROM Order
            order by OrderNumber desc];
        return aorders;
        }
        set ;
    }

public void saveS() {

        string oid = ApexPages.currentpage().getParameters().get('saveOrder');
        Order singleRec;
        for (Order x: aorders) {
            if (oid == x.id) {
                singleRec = x;
                break;
            }
        }
        if (singleRec != null)

         System.debug('order ' +singleRec);
        System.debug('order number ' +singleRec.OrderNumber);
    System.debug('TEACHER WAGE ' +singleRec.Teacher_Wage__c);
    System.debug('TEACHER ' +singleRec.ClassTeacher__c);

        }

For the teacher wage I have also tried changing the inputText value to use {!TeacherWageFromPage} and create a getter and setters in the controller but still when I check the debug log after run it shows as NULL.
public Decimal getTeacherWageFromPage() {
        return teacherWage;

    }

    public void SetTeacherWageFromPage(Decimal s) {
        teacherWage = s;
    }

A: Because of the way you've got the getter for aorders written the query for data is performed every time you reference that member.
So, in your saveS method the for loop which is iterating over aorders is causing the query to be executed again and new data to be retrieved from the database. This query is overwriting the data which has been posted from the form in the page.
One possible solution is to check within the getter to see if the query has been executed already. If it has, return that data. If it has not, execute the query and then return. (example below)
Another solution would be to remove the query from the getter and place it in the controller's constructor. I would suggest doing the same thing for the getopenPresentationOptions getter. Doing this can also improve your page performance, depending on how many times these queries are being executed during the page lifecycle.
public List<Order> aorders {

    get {

        // check to see if this member is already populated with the results
        // of a previous call to the getter before executing the query
        if (aorders != null) {
            return aorders;
        }

        aorders = [
        SELECT Id, OrderNumber, AccountId, EffectiveDate , EndDate, Status, Total_Cost_Of_Class__c,
        ClassTeacher__r.Name, Teacher_Wage__c, Programme__r.Name, Programme_Code__c, ClassTeacher__r.Id
        FROM Order
        order by OrderNumber desc];
        return aorders;
    }
    set ;
}

A: Your page design is a wee irritating and feels like it needs a design spec more than code fixes:

*

*First of all, in what context is it shown?

*Why is there one table for each order?

*

*With this many columns — even having empty headers (?) —
a table doesn't seem to be the appropriate layout.

*

*Try boxes (/ divs).

*Why would your save function iterate all orders if you're only changing one at a time?

*

*What's your intention concerning singleRec?

*Your nesting of an apex:form feels something between semantically wrong and awkward.


text:
Q: External HDD not showing up in finder & Disk Utility but shows up in System info Finder is not displaying my external HDD. Disk utility also doesn't show it:
But when I went to system information, I can see my hard drive there:

Can someone advise as to how to get it to show in finder?
I am running 12.3.1 (21E258)
Also note that this hard drive has worked with my mac in the past, but the last time I used it was I think back in March or maybe December.


text:
Q: Visibility Binding using DependencyProperty I've some simple code below that uses a ToggleButton.IsChecked property to set the Visibility of a TextBlock.  It works fine.  Since this doesn't quite fit in with my program's structure, I'm trying to bind the visibility of another TextBlock to a DependencyProperty of "this".  It compiles fine, but it produces no effect.  I'm doing something wrong, just not sure what.
XAML
<Window x:Class="ToggleButtonTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Width="200" Height="100">
<Window.Resources>
    <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<StackPanel>
    <ToggleButton x:Name="toggleButton" Content="Toggle"
                  IsChecked="True" Checked="toggleButton_Checked"/>
    <TextBlock Text="Some Text"
               Visibility="{Binding IsChecked,
               ElementName=toggleButton,
               Converter={StaticResource BooleanToVisibilityConverter}}"/>
    <TextBlock Text="More Text"
               Visibility="{Binding ShowMoreText,
               ElementName=this,
               Converter={StaticResource BooleanToVisibilityConverter}}"/>
</StackPanel>
</Window>

C#
using System.Windows;

namespace ToggleButtonTest
{
    public partial class MainWindow : Window
    {
        static MainWindow()
        {
            FrameworkPropertyMetadata meta =
                new FrameworkPropertyMetadata(true,
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault);

            ShowMoreTextProperty =
                DependencyProperty.Register("ShowMoreText",
                typeof(bool), typeof(MainWindow), meta);
        }

        public MainWindow()
        {
            InitializeComponent();
        }

        public static readonly DependencyProperty ShowMoreTextProperty;
        public bool ShowMoreText
        {
            get
            {
                return (bool)GetValue(ShowMoreTextProperty);
            }
            set
            {
                SetValue(ShowMoreTextProperty, value);
            }
        }

        private void toggleButton_Checked(object sender, RoutedEventArgs e)
        {
            ShowMoreText = toggleButton.IsChecked.Value;
        }
    }
}

Edit:
Having had this answered, I want to post my working code...
XAML
<Window x:Class="ToggleButtonTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Width="200" Height="100"
    Name="thisWindow">
    <Window.Resources>
        <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
    </Window.Resources>
    <StackPanel>
        <ToggleButton x:Name="toggleButton"
                Content="Toggle"
                IsChecked="{Binding Path=ShowMoreText, ElementName=thisWindow}"/>
        <TextBlock Text="More Text"
                   Visibility="{Binding Path=ShowMoreText,
                   ElementName=thisWindow,
                   Converter={StaticResource BooleanToVisibilityConverter}}"/>
    </StackPanel>
</Window>

C#
using System.Windows;

namespace ToggleButtonTest
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public static readonly DependencyProperty ShowMoreTextProperty =
            DependencyProperty.Register("ShowMoreText", typeof(bool),
            typeof(MainWindow), new FrameworkPropertyMetadata(true,
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));

        public bool ShowMoreText
        {
            get
            {
                return (bool)GetValue(ShowMoreTextProperty);
            }
            set
            {
                SetValue(ShowMoreTextProperty, value);
            }
        }
    }
}

A: The way you have it set up currently won't ever set ShowMoreText to false. The Checked handler will only be called when the ToggleButton's IsChecked changes from false to true. To also go the other way you need a handler for Unchecked as well. The best way to handle this situation would be to instead set a Binding on the ToggleButton that will do both without any event handlers (using Jay's changes):
IsChecked="{Binding Path=ShowMoreText, ElementName=thisWindow}"

A: ElementName must really be an element name. this doesn't fly. Fortunately, you do have an element of type MainWindow here with a ShowMoreText property: the root Window element.
Give the Window a name and use that as ElementName, as below:
<Window x:Class="ToggleButtonTest.MainWindow"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     Title="MainWindow" Width="200" Height="100"
     x:Name="thisWindow">
<Window.Resources>
     <BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter"/>
</Window.Resources>
<StackPanel>
     <ToggleButton x:Name="toggleButton" Content="Toggle"
                        IsChecked="True" Checked="toggleButton_Checked"/>
     <TextBlock Text="Some Text"
                    Visibility="{Binding IsChecked,
                    ElementName=toggleButton,
                    Converter={StaticResource BooleanToVisibilityConverter}}"/>
     <TextBlock Text="More Text"
                    Visibility="{Binding ShowMoreText,
                    ElementName=thisWindow,
                    Converter={StaticResource BooleanToVisibilityConverter}}"/>
</StackPanel>
</Window>

Note that you can do the same using RelativeSource Self, but I prefer the method above.

A: Give your Window a name and set the ElementName to that name, instead of using "this".


text:
Q: "Disallow: /test/programmming" or "Disallow: /programming"? I manage a site under WordPress. We had to change the site URL to example.com/test. So, I now have 2 properties in Search Console: one with the root domain (example.com). The other with the subdirectory (example.com/test).
Whenever I search site:example.com in Google, it returns all the indexable URLs which is example.com/test for the home page. The domain root example.com is therefore not indexable anymore.
In robots.txt, I like to disallow some URLs such as example.com/test/programming.
Should I disallow: /programming OR disallow: /test/programmming so that example.com/test/programming becomes blocked?

A: Disallow values always represent the beginning of the URL path.
For https://example.com/test/programming, the path is /test/programming.
So, Disallow: /test/programming would block URLs like these:

*

*https://example.com/test/programming

*https://example.com/test/programming/

*https://example.com/test/programming.html

*https://example.com/test/programming/foo/bar
And Disallow: /programming would block URLs like these:

*

*https://example.com/programming

*https://example.com/programming/

*https://example.com/programming.html

*https://example.com/programming/foo/bar


text:
Q: How can I get rid of the the gap below absolutely positioned content? I'm trying to bottom-align some variably sized linked images in a horizontally-aligned unordered list. My HTML + CSS, below, do the trick for the most part. There just one small gotcha: the gap below the image (http://jsfiddle.net/ymSvr/).  As you can see I'm using absolute positioning to get the image to stick to the bottom. But even with bottom: 0 the image still doesn't quite go to the bottom.
Can someone please explain why this happens? And how can I resolve this?
Markup:

CSS:
ul li {
    display:inline-block;

}

.outer {
    background-color: #c0c0c0;
    display: block;
    height: 242px;
    position: relative;
    width: 200px;
}

.inner {
    bottom: 0;
    left: 0;
    position: absolute;
    right: 0;
    text-align: center;
}

A: add the following code
img {
    vertical-align:bottom;
}

http://jsfiddle.net/ymSvr/1/


text:
Q: Selecting rows from a pandas DataFrame: only rows with at least three ones need to be selected I have a pandas dataframe containing some 25000 rows. This is what the data looks like. I want to select only the rows with which have at least three 1s the columns cond1, cond2, cond3, cond4.
import pandas as pd
ds = {'gene': ['as01', 'as02', 'as03', 'as04', 'as05'],
        'tf': ['tf1', 'tf2', 'tf3', 'tf4', 'tf5'],
     'cond1': ['0', '1', '0', '1', '1'],
     'cond2': ['1', '0', '1', '1', '0'],
     'cond3': ['0', '0', 'NaN', '0', '0'],
     'cond4': ['1', '1', '1', '1', '0'] }
df = pd.DataFrame(data=ds)

print(df)
   gene   tf cond1 cond2 cond3 cond4
0  as01  tf1     0     1     0     1
1  as02  tf2     1     0     0     1
2  as03  tf3     0     1     NaN     1
3  as04  tf4     1     1     0     1
4  as05  tf5     1     0     0     0

I converted the NaN to 0, as it won't impact my downstream work and tried to select the rows by using the following line.  It did not work, I get an indexing error. I am not very experienced in using Python and having a hard time figuring it out.
   gene   tf cond1 cond2 cond3 cond4
0  as01  tf1     0     1     0     1
1  as02  tf2     1     0     0     1
2  as03  tf3     0     1     0     1
3  as04  tf4     1     1     0     1
4  as05  tf5     1     0     0     0

df_new=df.loc[ df.iloc[:,3:6].sum() > 3 ]

IndexingError: Unalignable boolean Series provided as indexer (index of the boolean Series and of the indexed object do not match).

Can anybody suggest a solution to this? It would be great if there is a way to do this without having to convert the NaN to 0.

A: If I understood correctly you can do the following:
mask = np.nansum(df.values[:, 2:6].astype(np.float), axis=1) >= 3

print(df[mask])

Output
   gene   tf cond1 cond2 cond3 cond4
3  as04  tf4     1     1     0     1

The function np.nansum will take care of converting the NaN to zero.

A: You need to add eq('1') and change slicing to 2-6
df[df.iloc[:,2:6].eq('1').sum(1) >= 3]

Out[450]:
   gene   tf cond1 cond2 cond3 cond4
3  as04  tf4     1     1     0     1


text:
Q: MediaConvert split audio into multiple output chunks I would like to create three audio chunks / segments from a 30-minute-long audio file using AWS MediaConvert. Is it possible to do this with MediaConvert and if so how?
Here is an example using ffmpeg
ffmpeg -i 30min_audio.wav -c copy -f segment -segment_times 0,600,1200 output%d.wav

A: Unfortunately, there isn't a way to do this in the service currently. The service does not support input clipping for audio only inputs [1].
A creative way (if you don't care about the output format as much) would be to use a adapative bitrate (ABR) packaging type, such as Apple HLS, set the segment length. Note this will give you consistent segmenting (except for the last segment).
One thing to point out is that in your ffmpeg command you are using the -c copy filter. This will perform a transmux. MediaConvert is a transcoding service, so an encode will be performed if you process jobs in the service.
I like to think of it as some bits in, new bits out.
Resources:
[1] https://docs.aws.amazon.com/mediaconvert/latest/ug/feature-limitations-for-audio-only.html