text:
Q: SQLAlchemy custom load/save functionality (setter and getter) I am using the SQLAlchemy ORM for loading/saving from the database. However, I would like specific functions to be called on loading the data from the database, something like this:
class MyClass(Base):
    id = Column(Integer, primary_key = True)
    _data = relationship('Data')

    def __init__(self):
        self._data = []
        self.max_data = None
        self.min_data = None

    @property
    def data(self):
        return self._data

    @data.setter
    def data(self, data):
        print('gone through setter')
        self.min_data = min(data)
        self.max_data = max(data)
        self._data = data

However, I noticed that the setters and getters aren't called when saving/loading from the db. Is there a way to have these setters and getters called?
myclass = MyClass()
myclass.data = [0,1,2,3,4,5]
# gone through setter
myclass.max_data
# 5
myclass.min_data
# 0
session.add(myclass)
session.commit()

del myclass

myclass = session.query(MyClass).all()[0]
# setter is not called here
myclass.max_data
# None
myclass.min_data
# None

I would like the setter to be called on loading from the db as well, so that the min_data and max_data are set (without having to save them in the db explicitly)

A: To attach behavior on load, use the load event:
@event.listens_for(MyClass, "load")
def _set_min_max_on_load(target, context):
    target.max_data = max(target._data)
    target.min_data = min(target._data)

In this particular instance, it may be helpful to simply use hybrid_propertys instead:
class MyClass(Base):
    ...
    @hybrid_property
    def max_data(self):
        return max(self.data)

    @max_data.expression
    def max_data(cls):
        return select([func.max(Data.__table__.c.some_value)]).where(Data.__table__.c.my_class_id == cls.id)


text:
Q: 14.04 aborts in the middle of installation, but somehow works fine Last night I've tried upgrading my system to v14.04. The system aborted the upgrade about three hours in, saying that there were some files unable to be installed, and it said something along the lines of "run dpkg -a". Neither dpkg nor apt-get worked, so I rebooted my PC, and expected the worst.
My PC seemed to actually work fine after rebooting, and even confirmed that it was indeed running v14.04, which is also the reason why the command do-release-upgrade doesn't work. However, I feel that the upgrade is incomplete, though I have also done update-manager -d, just to be on the safe side. Is there anything else I should to to make sure nothing is broken or corrupted?

A: The OP said that Braiam's solution in the comment solved the problem:
sudo dpkg --configure -a and sudo apt-get -f install.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Entering a Formula using VBA in a Cell I have a table in a spreadsheet that I refresh daily. The number of rows in the worksheet changes from day to day and the formulas that I currently have in place to count up the items in the table do not include any new rows of data (if any) that are added to my table after a refresh.
I wanted to create a macro that would automatically update these formulas to include all rows in the table. The code below is my attempt. The code works just fine in terms of calculating the correct values, but it is not entering a formula into the cell. It is only entering in the result of the formula.
How can I change the code to enter the formula into the cell and not just the value?
Sub formula_update()

ThisWorkbook.Activate
    Worksheets("Summary").Activate
        Range("F9").Select

        Do Until IsEmpty(Selection)
            ActiveCell.Formula = Application.CountIfs(Range(ActiveCell.Offset(3, 0), ActiveCell.Offset(3, 0).End(xlDown)), "<>0")
            ActiveCell.Offset(0, 1).Select
        Loop

End Sub

A: Sub formula_update()

ThisWorkbook.Worksheets("Sheet4").Range("A3").Select

        Do Until IsEmpty(Selection)
            ActiveCell.Value = Application.CountIfs(Range(ActiveCell.Offset(3, 0), ActiveCell.Offset(3, 0).End(xlDown)), "<>0")
            ActiveCell.Offset(0, 1).Select
        Loop

End Sub


text:
Q: Twilio Android, incoming call receives "onCancelledCallInvite: CallException code: 31008" when answered I have Twilio Voice implemented and working on Android. However, often upon answering a call we immediately receive "onCancelledCallInvite: CallException code: 31008". The odd thing is that the connection stays active and voice communication with the caller continues to work. The issue is that the app thinks the call has dropped due to receiving the onCancelledCallInvite, and the call screen is closed. This creates an active orphaned call that is still in progress.
The app is using Voice Android version 5.6.2.
To answer the incoming call I call:
activeCallInvite.accept(context, callListener);

Below is the log file. Note in the log:
D/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): SipClient::disconnect
D/Twilio: [Core](517639025904): virtual void twilio::voice::SipCall::DisconnectCommand::executeCommand()

later followed by:
D/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): raiseCancelCallInvite

Also see in the log that after the CancelCallInvite the call continues.
Full Log:
I have Twilio Voice implemented and working on Android. However, often upon answering a call we immediately receive "onCancelledCallInvite: CallException code: 31008". The odd thing is that the connection stays active and voice communication with the caller remains active. The issue is that the app thinks the call has dropped due to receiving the onCancelledCallInvite, and the call screen is closed. This creates an active orphaned call that is still in progress.
The app is using Voice Android version 5.6.2.
To answer the incoming call I call:
activeCallInvite.accept(context, callListener);

Below is the log file. Note in the log:
D/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): SipClient::disconnect
D/Twilio: [Core](517639025904): virtual void twilio::voice::SipCall::DisconnectCommand::executeCommand()

later followed by:
D/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): raiseCancelCallInvite

Also see in the log that after the CancelCallInvite the call continues.
Full Log:
D/TwilioVoicePlugin: Answering call
D/TwilioVoicePlugin: Answering call
D/Twilio: [Core](518822861256): API Call createAudioSource
    [Core](518822861256): API Call createAudioTrack
I/Twilio: [Core](518822861256): Adding audio track ...
D/Twilio: [Core](518822861256): API Call getName
    [Core](518822861256): API Call getTrackId
    [Core](518822861256): API Call isEnabled
D/Twilio: [Core](518822861256): API Call accept
D/Twilio: [Core](518822861256): accept
D/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): SipClient::disconnect
D/Twilio: [Core](517639025904): virtual void twilio::voice::SipCall::DisconnectCommand::executeCommand()
D/Twilio: [Core](518822861256): API Call getWebRtcTrack
D/Twilio: [Core](518822861256): API Call RTCIceServers
    [Core](518822861256): API Call RTCIceServer
I/Twilio: [Core](518822861256): Creating peer connection ...
I/Twilio: [Core](518822861256): Adding local stream to peer connection ...
D/Twilio: [Core](518822861256): Create initial local offer
D/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): onCreateSessionLocalDescription
D/CallInviteProxy: release
D/Twilio: [Core](518822861256): ~CallInviteImpl
    [Core](518822861256): ~CallerInfoImpl
D/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): OnSignalingChange
    [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): Signaling state: have-local-offer
D/ConnectivityReceiver: Network event received
    Ignoring network event, sticky broadcast
D/CallInviteProxy: onEvent
D/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): onSetSessionLocalDescription
D/Twilio: [Core](MediaFactoryImpl::networking 0x0x78a67ff800): void twilio::media::NetworkMonitor::onNetworksChanged()
    [Core](MediaFactoryImpl::networking 0x0x78a67ff800): Network Name: wlan0, Cost: 10, Type : Wifi, Preference : 127, Active : 1, id: 3, prefix : 192.168.2.x and key : wlan0%192.168.2.x/24
    [Core](MediaFactoryImpl::networking 0x0x78a67ff800): Network Name: lo, Cost: 0, Type : Loopback, Preference : 126, Active : 1, id: 2, prefix : ::1 and key : lo%::1/128
    [Core](MediaFactoryImpl::networking 0x0x78a67ff800): Network Name: lo, Cost: 0, Type : Loopback, Preference : 125, Active : 1, id: 1, prefix : 127.0.0.x and key : lo%127.0.0.x/8
D/Twilio: [Core](MediaFactoryImpl::networking 0x0x78a67ff800): New preferred network reported by manager: key: wlan0%192.168.2.x/24, type: Wifi, cost: 10, id: 3
D/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): Local SDP - v=0
    o=- 5771264047219087907 2 IN IP4 127.0.0.x
    s=-
    t=0 0
    a=group:BUNDLE audio
    a=msid-semantic: WMS 9fCAE34C40bC829B219de4fbd1BFea93
    m=audio 9 UDP/TLS/RTP/SAVPF 111 103 104 9 0 8 106 105 13 110 112 113 126
    c=IN IP4 0.0.0.0
    a=rtcp:9 IN IP4 0.0.0.0
    a=ice-ufrag:NyGP
    a=ice-pwd:9BOEneVWrZVH+BtFNTJIudM5
    a=ice-options:trickle
    a=fingerprint:sha-256 17:02:69:E9:B7:EE:72:47:0A:41:39:1F:3C:3F:FD:72:CE:04:28:28:91:0A:71:C9:FA:61:33:06:96:97:1D:4A
    a=setup:actpass
    a=mid:audio
    a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level
    a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
    a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
    a=sendrecv
    a=rtcp-mux
    a=rtpmap:111 opus/48000/2
    a=rtcp-fb:111 transport-cc
    a=fmtp:111 minptime=10;useinbandfec=1
    a=rtpmap:103 ISAC/16000
    a=rtpmap:104 ISAC/32000
    a=rtpmap:9 G722/8000
    a=rtpmap:0 PCMU/8000
    a=rtpmap:8 PCMA/8000
    a=rtpmap:106 CN/32000
    a=rtpmap
    [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): twilio::voice::AsyncDnsResolver::AsyncDnsResolver(std::weak_ptr<DnsResolverObserver>)
    [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): AsyncDnsResolver resolving hostname = chunderm.gll.twilio.com
D/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): Gathered ICE candidate: candidate:926965826 1 udp 2122260223 192.168.2.x 38883 typ host generation 0 ufrag NyGP network-id 3 network-cost 10, id: SpXlrYSl
D/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): AsyncDnsResolver Resolved ip_addr = 54.85.119.44, error = 0
    [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): virtual void twilio::voice::SipClient::onResolveResult(twilio::voice::AsyncDnsResolver *, std::string, int)
    [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): onResolveResult for connect, hostname = sip:chunderm.gll.twilio.com:443;transport=tls, ip_addr = 54.85.119.44
    [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): New SipCall ..., this=0x78bc47dd00, handle = 4
I/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): Setting outbound proxy to: sip:54.85.119.44:443;transport=tls
D/CallInviteProxy: onEvent
D/EventPublisher: Start publishing events to : https://eventgw.twilio.com/v4/EndpointEvents
    {"name":"have-local-offer","group":"signaling-state","timestamp":"2021-03-03T02:49:46.289Z","level":"DEBUG","private":false,"payload_type":"application\/json","publisher":"twilio-voice-android","publisher_metadata":{"client_address":"FE80::EC6D:7AFF:FEE0:BB85","os_name":"android","os_version":"8.0.0","device_model":"SM-G935T","device_vendor":"samsung","device_type":"SM-G935T","cpu_architecture":"arm64-v8a","app_id":"com.MyApp.flutter","app_version":"0.1.0","app_build_number":"31","app_min_os_version":23,"app_target_os_version":30},"payload":{"timestamp_ms":1614739786285,"client_name":"5fc1a9b29d368c7292641c3e","call_sid":"CA335578454dc3db2d1f810944a6b51a97","message_sid":"RUc36021e53e6b591c645eb6d8f27fcd63","sdk_version":"5.6.2","platform":"android","direction":"INCOMING","selected_region":"gll"}}
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
D/EventPublisher: Start publishing events to : https://eventgw.twilio.com/v4/EndpointEvents
    {"name":"accepted-by-local","group":"connection","timestamp":"2021-03-03T02:49:46.307Z","level":"INFO","private":false,"payload_type":"application\/json","publisher":"twilio-voice-android","publisher_metadata":{"client_address":"FE80::EC6D:7AFF:FEE0:BB85","os_name":"android","os_version":"8.0.0","device_model":"SM-G935T","device_vendor":"samsung","device_type":"SM-G935T","cpu_architecture":"arm64-v8a","app_id":"com.MyApp.flutter","app_version":"0.1.0","app_build_number":"31","app_min_os_version":23,"app_target_os_version":30},"payload":{"timestamp_ms":1614739786301,"client_name":"5fc1a9b29d368c7292641c3e","call_sid":"CA335578454dc3db2d1f810944a6b51a97","message_sid":"RUc36021e53e6b591c645eb6d8f27fcd63","sdk_version":"5.6.2","platform":"android","direction":"INCOMING","selected_region":"gll"}}
D/CallInviteProxy: onEvent
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
D/CallInviteProxy: onEvent
D/EventPublisher: Start publishing events to : https://eventgw.twilio.com/v4/EndpointEvents
    {"name":"gathering","group":"ice-gathering-state","timestamp":"2021-03-03T02:49:46.325Z","level":"DEBUG","private":false,"payload_type":"application\/json","publisher":"twilio-voice-android","publisher_metadata":{"client_address":"FE80::EC6D:7AFF:FEE0:BB85","os_name":"android","os_version":"8.0.0","device_model":"SM-G935T","device_vendor":"samsung","device_type":"SM-G935T","cpu_architecture":"arm64-v8a","app_id":"com.MyApp.flutter","app_version":"0.1.0","app_build_number":"31","app_min_os_version":23,"app_target_os_version":30},"payload":{"timestamp_ms":1614739786319,"client_name":"5fc1a9b29d368c7292641c3e","call_sid":"CA335578454dc3db2d1f810944a6b51a97","message_sid":"RUc36021e53e6b591c645eb6d8f27fcd63","sdk_version":"5.6.2","platform":"android","direction":"INCOMING","selected_region":"gll"}}
D/Twilio: [Core](517639025904): mapToSipCall handle id is 1
D/Twilio: [Core](517639025904): casting handle id 1 to SipCall
    [Core](517639025904): onTerminated: reason 5, this=0x78bc47d300
    [Core](517639025904): onTerminated
D/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): raiseCancelCallInvite
D/Twilio: [Core](517639025904): ~SipCall(): 0x78bc47d300
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
    (HTTPLog)-Static: isSBSettingEnabled false
D/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): Gathered ICE candidate: candidate:3243252118 1 udp 1686052607 66.25.218.226 38883 typ srflx raddr 192.168.2.x rport 38883 generation 0 ufrag NyGP network-id 3 network-cost 10, id: I2J/daT2
D/CallInviteProxy: onEvent
D/CallInviteProxy: onEvent
D/EventPublisher: Response: 200 - OK
D/EventPublisher: Start publishing events to : https://eventgw.twilio.com/v4/EndpointEvents
    {"name":"ice-candidate","group":"ice-candidate","timestamp":"2021-03-03T02:49:46.343Z","level":"DEBUG","private":false,"payload_type":"application\/json","publisher":"twilio-voice-android","publisher_metadata":{"client_address":"FE80::EC6D:7AFF:FEE0:BB85","os_name":"android","os_version":"8.0.0","device_model":"SM-G935T","device_vendor":"samsung","device_type":"SM-G935T","cpu_architecture":"arm64-v8a","app_id":"com.MyApp.flutter","app_version":"0.1.0","app_build_number":"31","app_min_os_version":23,"app_target_os_version":30},"payload":{"timestamp_ms":1614739786333,"client_name":"5fc1a9b29d368c7292641c3e","call_sid":"CA335578454dc3db2d1f810944a6b51a97","message_sid":"RUc36021e53e6b591c645eb6d8f27fcd63","sdk_version":"5.6.2","platform":"android","direction":"INCOMING","selected_region":"gll","transport_id":"audio","is_remote":false,"ip":"192.168.2.34","port":38883,"protocol":"udp","candidate_type":"local","priority":2122260223,"url":"","deleted":false,"network-cost":10,"network-id":3,"related_port":0,"level":"DEBUG","related_address":"","network-type":"Wifi","name":"ice-candidate","tcp_type":""}}
D/EventPublisher: Response: 200 - OK
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
D/EventPublisher: Start publishing events to : https://eventgw.twilio.com/v4/EndpointEvents
    {"name":"ice-candidate","group":"ice-candidate","timestamp":"2021-03-03T02:49:46.385Z","level":"DEBUG","private":false,"payload_type":"application\/json","publisher":"twilio-voice-android","publisher_metadata":{"client_address":"FE80::EC6D:7AFF:FEE0:BB85","os_name":"android","os_version":"8.0.0","device_model":"SM-G935T","device_vendor":"samsung","device_type":"SM-G935T","cpu_architecture":"arm64-v8a","app_id":"com.MyApp.flutter","app_version":"0.1.0","app_build_number":"31","app_min_os_version":23,"app_target_os_version":30},"payload":{"timestamp_ms":1614739786381,"client_name":"5fc1a9b29d368c7292641c3e","call_sid":"CA335578454dc3db2d1f810944a6b51a97","message_sid":"RUc36021e53e6b591c645eb6d8f27fcd63","sdk_version":"5.6.2","platform":"android","direction":"INCOMING","selected_region":"gll","transport_id":"audio","is_remote":false,"ip":"66.25.218.226","port":38883,"protocol":"udp","candidate_type":"stun","priority":1686052607,"url":"stun:34.203.251.117:3478","deleted":false,"network-cost":10,"network-id":3,"related_port":38883,"level":"DEBUG","related_address":"192.168.2.34","network-type":"Wifi","name":"ice-candidate","tcp_type":""}}
D/EventPublisher: Response: 200 - OK
D/EventPublisher: Start publishing events to : https://eventgw.twilio.com/v4/EndpointEvents
    {"name":"complete","group":"ice-gathering-state","timestamp":"2021-03-03T02:49:46.398Z","level":"DEBUG","private":false,"payload_type":"application\/json","publisher":"twilio-voice-android","publisher_metadata":{"client_address":"FE80::EC6D:7AFF:FEE0:BB85","os_name":"android","os_version":"8.0.0","device_model":"SM-G935T","device_vendor":"samsung","device_type":"SM-G935T","cpu_architecture":"arm64-v8a","app_id":"com.MyApp.flutter","app_version":"0.1.0","app_build_number":"31","app_min_os_version":23,"app_target_os_version":30},"payload":{"timestamp_ms":1614739786394,"client_name":"5fc1a9b29d368c7292641c3e","call_sid":"CA335578454dc3db2d1f810944a6b51a97","message_sid":"RUc36021e53e6b591c645eb6d8f27fcd63","sdk_version":"5.6.2","platform":"android","direction":"INCOMING","selected_region":"gll"}}
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
E/PowerManager: WakeLock finalized while still held: flutter.twilio.wakelock:TAG
D/EventPublisher: Response: 200 - OK
D/EventPublisher: Response: 200 - OK
D/EventPublisher: Response: 200 - OK
D/Twilio: [Core](517643171056): mapToSipCall handle id is 1
    [Core](517643171056): casting handle id 1 to SipCall
    [Core](517643171056): virtual void twilio::voice::SipCall::onFailure(resip::ClientInviteSessionHandle, const resip::SipMessage &)
D/Twilio: [Core](517643171056): Received incoming SIP message from infra:
     SIP/2.0 410 Gone
    Via: SIP/2.0/TLS 192.168.2.x;received=66.25.218.226;branch=z9hG4bK-524287-1---4ef18fe6d5ee728a;rport=53761
    Contact: <sip:172.25.4.x:10193>
    To: <sip:chunderm.gll.twilio.com:443;transport=tls>;tag=24354603_6772d868_b679c346-1ce5-43a2-9d27-1b1da25f6c36
    From: <sip:VoiceSDK@chunderm.gll.twilio.com>;tag=26504677
    Call-ID: xC-6diTaJuSYY76Id55WVw..
    CSeq: 1 INVITE
    Server: Twilio
    X-Twilio-CallSid: CA335578454dc3db2d1f810944a6b51a97
    X-Twilio-EdgeHost: ec2-54-85-119-44.compute-1.amazonaws.com
    X-Twilio-EdgeRegion: us1
    X-Twilio-Zone: US_EAST_VIRGINIA
    Content-Length: 0
    [Core](517643171056): onFailure
    [Core](517643171056): mapToSipCall handle id is 1
    [Core](517643171056): casting handle id 1 to SipCall
    [Core](517643171056): onTerminated: reason 0, this=0x78bc47ce00
D/Twilio: [Core](517643171056): Received incoming SIP message from infra:
     SIP/2.0 410 Gone
    Via: SIP/2.0/TLS 192.168.2.x;received=66.25.218.226;branch=z9hG4bK-524287-1---4ef18fe6d5ee728a;rport=53761
    Contact: <sip:172.25.4.x:10193>
    To: <sip:chunderm.gll.twilio.com:443;transport=tls>;tag=24354603_6772d868_b679c346-1ce5-43a2-9d27-1b1da25f6c36
    From: <sip:VoiceSDK@chunderm.gll.twilio.com>;tag=26504677
    Call-ID: xC-6diTaJuSYY76Id55WVw..
    CSeq: 1 INVITE
    Server: Twilio
    X-Twilio-CallSid: CA335578454dc3db2d1f810944a6b51a97
    X-Twilio-EdgeHost: ec2-54-85-119-44.compute-1.amazonaws.com
    X-Twilio-EdgeRegion: us1
    X-Twilio-Zone: US_EAST_VIRGINIA
    Content-Length: 0
    [Core](517643171056): onTerminated
D/Twilio: [Core](MediaFactoryImpl::signaling 0x0x78a67ff800): raiseCancelCallInvite
D/Twilio: [Core](517643171056): ~SipCall(): 0x78bc47ce00
D/CallInviteProxy: onEvent
D/Twilio: [Core](517639025904): mapToSipCall handle id is 4
    [Core](517639025904): casting handle id 4 to SipCall
D/Twilio: [Core](517639025904): onNewSession:
    SIP/2.0 200 OK
    Via: SIP/2.0/TLS 192.168.2.x;received=66.25.218.226;branch=z9hG4bK-524287-1---402e10cecf0821ea;rport=53779
    Record-Route: <sip:172.18.10.x:10193;r2=on;transport=udp;ftag=cfed5cb9;lr>
    Record-Route: <sip:54.85.119.44:443;r2=on;transport=tls;ftag=cfed5cb9;lr>
    Contact: <sip:172.25.4.x:10193>
    To: <sip:chunderm.gll.twilio.com:443;transport=tls>;tag=28038694_6772d868_ad31a15b-3d32-411e-a406-19783f7c8dc5
    From: <sip:VoiceSDK@chunderm.gll.twilio.com>;tag=cfed5cb9
    Call-ID: _L5_J-dQSDSd9JQ33RRtSw..
    CSeq: 1 INVITE
    Allow: INVITE, ACK, CANCEL, OPTIONS, BYE
    Content-Type: application/sdp
    Server: Twilio
    X-Twilio-CallSid: CA335578454dc3db2d1f810944a6b51a97
    X-Twilio-EdgeHost: ec2-54-85-119-44.compute-1.amazonaws.com
    X-Twilio-EdgeRegion: us1
    X-Twilio-Zone: US_EAST_VIRGINIA
    Content-Length: 1045


text:
Q: How do I get git to track and commit files according to .gitignore (from the beginning)? Edit:
The detail in my question hides the true nature of the problem. However, as this is how the problem is likely to manifest to others, I've decided to keep it as is and just add this edit, and the answer below.

I am completely new to git.
I'm working on a PHP-based website and would like to track only my files:
ie only files in /plugins/my-plugins/ and /themes/my-theme/.
Having failed to get this to work I decide to create and play with a minimum working example.
According to https://git-scm.com/docs/gitignore:

Example to exclude everything except a specific directory foo/bar (note the /* - without the slash, the wildcard would also exclude everything within foo/bar):
$ cat .gitignore
# exclude everything except directory foo/bar
/*
!/foo
/foo/*
!/foo/bar

So, I created files/folders to match:
alan@lamp ~/GitPlay$ tree -a
.
|-- .gitignore
|-- README.md
|-- foo
|   |-- bar
|   |   -- shouldNOTbeExcluded_bar.txt
|   -- shouldBeExcluded_foo.txt
-- shouldBeExcluded.txt

2 directories, 4 files
alan@lamp ~/GitPlay$

According to https://dzone.com/refcardz/getting-started-git:

...initialize the directory as a Git repository by typing the following commands:
git init
git add .
git commit –m 'The first commit'

Before git add.:
alan@lamp ~/GitPlay$ git status
On branch master

Initial commit

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    .gitignore
    README.md
    foo/
    shouldBeExcluded.txt

nothing added to commit but untracked files present (use "git add" to track)
alan@lamp ~/GitPlay$

So, it's not tracking the files it shouldn't track. Which suggests it is tracking the files it should track.
So maybe I can just commit what is, apparently, being tracked:
alan@lamp ~/GitPlay$ git commit -m 'Very first commit after git init'
On branch master

Initial commit

Untracked files:
    .gitignore
    README.md
    foo/
    shouldBeExcluded.txt

nothing added to commit but untracked files present
alan@lamp ~/GitPlay$

"nothing added to commit".
OK, let's add something:
alan@lamp ~/GitPlay$ git add .

And now see what happened:
alan@lamp ~/GitPlay$ git status
On branch master

Initial commit

    Changes to be committed:
  (use "git rm --cached <file>..." to unstage)

    new file:   .gitignore
    new file:   README.md
    new file:   foo/bar/shouldNOTbeExcluded_bar.txt
    new file:   foo/shouldBeExcluded_foo.txt
    new file:   shouldBeExcluded.txt

alan@lamp ~/GitPlay$

Now it's planning to add everything in the next commit. Which is not what I want.
Lets' see what actually happens:
alan@lamp ~/GitPlay$ git commit -m 'Very first commit after git init'
[master (root-commit) dca0c49] Very first commit after git init
 5 files changed, 37 insertions(+)
 create mode 100644 .gitignore
 create mode 100644 README.md
 create mode 100644 foo/bar/shouldNOTbeExcluded_bar.txt
 create mode 100644 foo/shouldBeExcluded_foo.txt
 create mode 100644 shouldBeExcluded.txt
alan@lamp ~/GitPlay$

As I suspected, everything is committed.
So, my question:
How do I get git to track and commit files according to .gitignore from the beginning?
Or am I missing something fundamental?
Is the 'correct' procedure
to commit EVERYTHING in the very first commit regardless of .gitignore,
and then git will track changes according to .gitignore from the next git add . / git commit ... onwards?

According to
git add all except ignoring files in .gitignore file

I think you mean git add . which will add all of the files to the repo that AREN'T specified in the .gitignore - you can see these changes by typing git status
git add .
This will add all paths and ignore matches from .gitignore

Which doesn't match my experience: git add . adds ALL files and ignores .gitignore.
According to
Git add . ignores .gitignore

.gitignore is taking into consideration only for new files.

Which does fit what I'm finding.

Further play
Immediately following the first commit:
alan@lamp ~/GitPlay$ git status
On branch master
nothing to commit, working tree clean

So I thought, maybe clearing the staging cache will fix the problem:
alan@lamp ~/GitPlay$ git rm -r --cached .
rm '.gitignore'
rm 'README.md'
rm 'foo/bar/shouldNOTbeExcluded_bar.txt'
rm 'foo/shouldBeExcluded_foo.txt'
rm 'shouldBeExcluded.txt'

alan@lamp ~/GitPlay$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    deleted:    .gitignore
    deleted:    README.md
    deleted:    foo/bar/shouldNOTbeExcluded_bar.txt
    deleted:    foo/shouldBeExcluded_foo.txt
    deleted:    shouldBeExcluded.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    .gitignore
    README.md
    foo/
    shouldBeExcluded.txt

alan@lamp ~/GitPlay$ git rm -r --cached .
fatal: pathspec '.' did not match any files

alan@lamp ~/GitPlay$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    deleted:    .gitignore
    deleted:    README.md
    deleted:    foo/bar/shouldNOTbeExcluded_bar.txt
    deleted:    foo/shouldBeExcluded_foo.txt
    deleted:    shouldBeExcluded.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    .gitignore
    README.md
    foo/
    shouldBeExcluded.txt

alan@lamp ~/GitPlay$ git add .

alan@lamp ~/GitPlay$ git commit -m 'First commit'
On branch master
nothing to commit, working tree clean

alan@lamp ~/GitPlay$ git status
On branch master
nothing to commit, working tree clean

alan@lamp ~/GitPlay$ ll
total 24
drwxr-xr-x 4 alan alan 4096 Jul  3 15:08 ./
drwxr-xr-x 8 alan alan 4096 Jul  3 16:05 ../
drwxr-xr-x 8 alan alan 4096 Jul  3 17:16 .git/
-rw-r--r-- 1 alan alan  139 Jul  3 15:03 .gitignore
-rw-r--r-- 1 alan alan  588 Jul  3 14:47 README.md
drwxr-xr-x 3 alan alan 4096 Jul  3 15:09 foo/
-rw-r--r-- 1 alan alan    0 Jul  3 15:08 shouldBeExcluded.txt

alan@lamp ~/GitPlay$ git add -f .

alan@lamp ~/GitPlay$ git status
On branch master
nothing to commit, working tree clean

So now I can't stage and commit anything.

A: While you have a .gitignore file, you haven't told git about it. You need to track it first:
git add .gitignore

Once you've done that, then the files that you want ignored will be ignored.
The reason that running git add . didn't work is because .gitignore only works for untracked files. Adding all files makes everything tracked (even the files you want ignored), so at that point .gitignore isn't used.

A: This question could have been simply
How do I get git to track and commit files according to .gitignore?
Which, as @acsrujan pointed out in the question comments, has been answered by git add all except ignoring files in .gitignore file.
However, what my question did not show,
-- due to a markdown artefact, "Indent four spaces to create an escaped <pre> <code> block" --
is that my copy/paste of a .gitignore file from Git - gitignore documentation, introduced leading white space to each pattern line of my .gitignore file.
This seems to have the same effect as beginning lines with # -- "A line starting with # serves as a comment." -- or possibly git treats such lines as blank lines -- "A blank line matches no files, so it can serve as a separator for readability." Quotes from Git - gitignore documentation.
Removing the leading spaces solves the problem and the .gitignore file works as expected.


text:
Q: Power Query - Append Variable Dates to Existing Table as Headers I am having an issue w/ my below M Code. I have set up an simple example of what i am trying to do below, but know the issue is when try to append variable dates as headers into the table:
let
Set up steps.
.
.
.
    #"Appended Query" = Table.Combine({#"Removed Other Columns",Table.PromoteHeaders(Table.Transpose(Table.FromList(List.Dates(Date.StartOfWeek(DateTime.Date(DateTime.LocalNow()),  Day.Sunday), 52, #duration(7,0,0,0)), Splitter.SplitByNothing(), {"Dates"}, null, ExtraValues.Error)),[PromoteAllScalars=true])})
in
    #"Appended Query"

Error:
Expression.Error: 2 arguments were passed to a function which expects 1.
Details:
    Pattern=
    Arguments=List

The table starts like table A. I use some simple query functions to get to this point. But I need to add the columns w/ dates and the function (Table A: Total Qty/50) for all added date columns as in Table B.
Table A
Product Table A: Total Qty
a       323000
b       898807
c       844945
d       36330
e       281009
f       611092
g       633217

Table B
Product Table A: Total Qty  6/4/2017    6/11/2017   6/18/2017   6/25/2017   7/2/2017    7/9/2017
a       323,000             6,460       6,460       6,460       6,460       6,460       6,460
b       898,807             17,976      17,976      17,976      17,976      17,976      17,976
c       844,945             16,899      16,899      16,899      16,899      16,899      16,899
d       36,330              727         727         727         727         727         727
e       281,009             5,620       5,620       5,620       5,620       5,620       5,620
f       611,092             12,222      12,222      12,222      12,222      12,222      12,222
g       633,217             12,664      12,664      12,664      12,664      12,664      12,664

Hope you can help! Thanks in advance!
Alex


text:
Q: Symfony for propert_path for child form type I understand if I put
        ->add('visitor.name', TextType::class, [
            'property_path' => 'vistorName'
        ])

This will be identical to <input name="vistorName"
How can I do similar for child form, to have all the child field as a parent field name without putting in as a child array.
        $builder->add('customer', CustomerType::class);

CustomerType
    $builder
        ->add('name', TextType::class)
        ->add('email', EmailType::class)
        ->add('phone', PhoneNumberType::class, [
            'default_region' => 'GB', // TODO GLOBAL release
            'format' => PhoneNumberFormat::NATIONAL
        ]);

The above form should generate <input name="name"... <input name="email"... and not as following  <input name="customer[name]"...
how can I do that?
Following is complete code example
// Cart model
class Cart {

    protected $productName;

    /** @var Customer */
    protected $customer;
}

// Customer model
Class Customer {

    protected $name;

    protected $email;

    protected $phone;
}

//CustomerType form
$builder
    ->add('name', TextType::class)
    ->add('email', EmailType::class)
    ->add('phone', PhoneNumberType::class, [
        'default_region' => 'GB', // TODO GLOBAL release
        'format' => PhoneNumberFormat::NATIONAL
    ]);

// main parent form

class MainFormType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('productName', TextType::class)
            ->add('customer', CustomerType::class); // need property_path for this, so all the inner fields can be used as parent
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Cart::class,
            'required' => false
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'cart';
    }
}

A: It works the other way around:
Scenario:
VisitorEntity:

*

*TypeOfVisitorEntity

*CustomerEntity

Now you want to update a VisitorEntity customer.name:
class MainFormType extends AbstractType
{
    /**
     * {@inheritdoc}
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('productName', TextType::class)
            ->add('customerName', TextType::class, ['property_path'=>'customer.name'])
            ->add('customerEmail', TextType::class, ['property_path'=>'customer.email'])
            ->add('customerPhone', TextType::class, ['property_path'=>'customer.phone'])
    ;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => Cart::class,
            'required' => false
        ]);
    }

    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'cart';
    }
}

property_path
https://symfony.com/doc/3.4/reference/forms/types/form.html#property-path
type: any default: the field's name
Fields display a property value of the form's domain object by default. When the form is submitted, the submitted value is written back into the object.
If you want to override the property that a field reads from and writes to, you can set the property_path option. Its default value is the field's name.
If you wish the field to be ignored when reading or writing to the object you can set the property_path option to false, but using property_path for this purpose is deprecated, you should use the mapped option.


text:
Q: Nav list item auto size I have written this script with the help from some members on here (thanks for that) that gets the width of a nav, and all its list item children, works out how much space there is free and sets that as padding for each anchor in the list item. It works but im out by about 2 pixels per padding and not sure where i have gone wrong. anyone got any clues?
$(document).ready(function () {

    var numb = $("nav ul").children().length,
        nav = $('nav').outerWidth(),
        width = 0;

    $('nav ul li').each(function () {
        width += $(this).outerWidth();
    });

    var padding = ((nav - width) / numb) / 2;

    $('nav ul li a').css({
        'padding-right': padding,
        'padding-left': padding,
    });
});

here is a working/non working js fiddle of the issue http://jsfiddle.net/axXR4/
thanks!

A: Two changes are needed.
First, drop the decimal from your padding value:
var padding = Math.floor(((nav - width) / numb) / 2);

And remove the padding from  your ul:
nav ul {
    list-style:none;
    padding:0;
}

http://jsfiddle.net/axXR4/5/


text:
Q: Configuration to set favicon in a Mattermost website I would like to change favicon image on my Mattermost website (example image of a favicon http://www.dwuser.com/education/content/quick-tip-adding-a-favicon-to-your-website/images/chrome.jpg) but I don't find a configuration in which I can set this parameter.

A: It's not possible in configuration, see the feature request if you want to vote for it.
If you're hosting it outside of docker or building yourself you could just replace the files in <webapp>/images/favicon (that's where it is in the code it might be different in the built version).


text:
Q: Removing multiple instances of words from a single set in a string I have a string street that may contains:
street= "Siegfriedst strasse st 16.";

street= "Frontos strasse s .";

I want to remove the extra "st", "strasse" and "s".
I used:
 street= street.Replace("(", "").Replace(")", "").Replace(".", "").
                             Replace("-", "").Replace("strasse","").
                             Replace("st","").Replace("s","");

But I don't want to remove "st" from "Siegfriedst" and "s" from "Frontos".

A: Perhaps this is what you want, it's not clear if you only want to remove duplicate words or sub-strings:
public static string RemoveDuplicates(string input, params string[] wordsToCheck)
{
    var wordSet = new HashSet<string>(wordsToCheck);
    int taken = 0;
    var newWords = input.Split()
        .Select(w => !wordSet.Contains(w) || ++taken == 1 ? w : "");
    return string.Join(" ", newWords);
}

Usage:
string text = RemoveDuplicates("Siegfriedst strasse st 16.", "st", "strasse", "s");

Result: Siegfriedst strasse  16.

A: street = street.Replace(".", " ") //To better enable pattern matching
               .Replace(" strasse ", "")
               .Replace(" st ", " ")
               .Replace(" s ", "")
               .Replace("  ", " ")
               .Trim();  //Trim() removes the leading and trailing whitespaces

A: street = street.Replace("(", "")
               .Replace(")", "")
               .Replace(".", "")
               .Replace("-", "")
               .Replace(" strasse "," ")
               .Replace(" st "," ")
               .Replace(" s "," ");

A: You can write a helper method like:
public static string Cleanup(string text, string[] exclude)
{
    string[] parts = text.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

    List<string> words = new List<string>();

    foreach(string part in parts)
    {
        if (!exclude.Contains(part))
        {
            words.Add(part);
        }
    }

    return string.Join(" ", words.ToArray());
}

and then use it like:
string street = Cleanup("Siegfriedst strasse st 16.", new string[] { "strasse", "st", "s", " " });

A: You can use regular expressions.  This will match whole words "strasse" "st" or "s", but not in parts of words:
using System.Text.RegularExpressions;

Regex rgx = new Regex(@"\b(strasse|st|s)\b|\(|\)|\.");
street = rgx.Replace(street, "");

A: Based on the fact that you used concatenated Replace operations (thus not wanting any of the extra strings to appear) I would suggest the following LINQ query:
street = street.Split(' ').Where(s => s != "strasse" && s != "st" && s != "s").Aggregate((x, y) => x + " " + y);


text:
Q: How to graph Capacitated Vehicle Routing (CVRP) Problem with ORTOOLS The question is the same with JT-12's question last year here is the link
How to graph Google OR Tools Vehicle Routing Problem Solution?
I do exactly the same, I'm using the code from the tutorial https://developers.google.com/optimization/routing/cvrp. But it seems the link given from the top answer is not available. I'm a student and I'm a new learner, so any kind of help will be appreciated. Thanks


text:
Q: Populating dynamic form controls with data in Angular 2 I am working on an Angular 2 project where I am creating input fields dynamically on button click. I am taking the help of FormArray for the same. The creation of fields and data submission is working fine but when I am trying to populate the fields with some pre-defined data then it doesn't work. I have created a plunker for my issue.
https://plnkr.co/edit/PCFD43GK91zo2ivQ9lf7?p=preview
Here I want to populate the fields on the view with the data in the object itemData. For easy reference, following is Angular code -
//our root app component
import { Component, NgModule } from '@angular/core'
import { BrowserModule } from '@angular/platform-browser'
import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@angular/forms';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@Component({
  selector: 'my-app',
  template: `

                <form [formGroup]="orderForm" (ngSubmit)="OnSubmit(orderForm.value)">

                      Customer Name
                      <input type="text" formControlName="customerName"/>

                          Customer Name is required

                      Customer Email
                      <input type="text" formControlName="email"/>

                          Email is required

                        Item Name
                        <input type="text" formControlName="name" placeholder="Item name"/>

                          Item Name is required

                        Item Description
                        <input type="text" formControlName="description" placeholder="Item description"/>

                          Description is required

                        Item Price
                        <input type="text" formControlName="price" placeholder="Item price"/>

                          Price is required

                  <button type="submit">Save</button>
                  <button type="button" (click)="addItem()">Add More</button>
                  <button type="button" (click)="loadItems()">Load Items</button>
                </form>

`,
})

export class App {

  constructor(private formBuilder: FormBuilder) {  }

  public orderForm: FormGroup;
  public formSubmitAttempt: boolean;
  public itemData:any=`{
    "customerName":"Customer 1","email":"abc@xyz.com",
    "items":[{"name":"Item 1","description":"Item 1 Descr","price":"100"},
            {"name":"Item 2","description":"Item 2 Descr","price":"200"},
            {"name":"Item 3","description":"Item 3 Descr","price":"300"}]
  }`;

  ngOnInit() {
    this.orderForm = this.formBuilder.group({
      customerName: ['',[Validators.required]],
      email: ['',[Validators.required]],
      items: this.formBuilder.array([ this.createItem()])
    });
  }

  createItem(): FormGroup {
    return this.formBuilder.group({
      name: ['',[Validators.required,Validators.maxLength(10)]],
      description: '',
      price: ['',[Validators.required,Validators.pattern("[(0-9)]*")]]
    });
  }

  public loadItems(){
    this.orderForm = this.formBuilder.group({
      customerName: [this.itemData.customerName,[Validators.required]],
      email: [this.itemData.email,[Validators.required]],
      items: this.itemData.items
    });
  }

  get items(): FormArray {
    return this.orderForm.get('items') as FormArray;
  };

  addItem(): void {
    this.items.push(this.createItem());
  }

  public OnSubmit(formValue: any) {
    this.formSubmitAttempt = true;
    console.log(JSON.stringify(formValue));
  }

  public IsValidField(field: string, i?:number) {
    if(i!=null) {
      var f = this.orderForm
        .get('items') //retrieve items FormArray
        .get(i.toString()) //retrieve items FormGroup
        .get(field); //retrieve items form field

      return (f.invalid && f.touched) || (f.invalid && this.formSubmitAttempt);
    } else {
      return (this.orderForm.get(field).invalid && this.orderForm.get(field).touched) || (this.orderForm.get(field).invalid && this.formSubmitAttempt);
    }
  }
}

@NgModule({
  imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],
  declarations: [ App ],
  bootstrap: [ App ]
})
export class AppModule {}

Any help would be appreciated. Thanks.

A: The elements inside a formArray has to be formGroups, not just an object.
Run your this.itemData.items through the createItems function you already have when trying to assign default values to your formArray.
public loadItems(){
  this.orderForm.patchValue({
    customerName: this.itemData.customerName,
    email: this.itemData.email
  });

  this.itemData.forEach((item) => {
    (<FormArray>this.orderForm.get('items')).push(this.createItem(item));
  });

}

No need to recreate the form when data comes from a service, just patchValues and update form accordingly.
PS: you need to modify createItems to take some input data and return the formGroup with data.

A: the problem is in the definition of your itemData try to delete the ` to define the object:
public itemData:any={
    "customerName":"Customer 1","email":"abc@xyz.com",
    "items":[{"name":"Item 1","description":"Item 1 Descr","price":"100"},
            {"name":"Item 2","description":"Item 2 Descr","price":"200"},
            {"name":"Item 3","description":"Item 3 Descr","price":"300"}]
};

and in your loadItems method add brackets to assign the value of items :
public loadItems(){
   this.orderForm = this.formBuilder.group({
        customerName: [this.itemData.customerName,[Validators.required]],
        email: [this.itemData.email,[Validators.required]],
        items: [this.itemData.items]
      });
}

hope it helps :)


text:
Q: How can I start pagenumbers, where the first section occurs in LaTex? This question is related to the post about having abstract at the titlepage.
I want to reset the page numbering at the given section.

A: You can also reset page number counter:
\setcounter{page}{1}

However, with this technique you get wrong page numbers in Acrobat in the top left page numbers field:
\maketitle: 1
\tableofcontents: 2
\setcounter{page}{1}
\section{Introduction}: 1
...

A: I use
\pagenumbering{roman}

for everything in the frontmatter and then switch over to
\pagenumbering{arabic}

for the actual content. With pdftex, the page numbers come out right in the PDF file.

A: To suppress the page number on the first page, add \thispagestyle{empty} after the \maketitle command.
The second page of the document will then be numbered "2". If you want this page to be numbered "1", you can add \pagenumbering{arabic} after the \clearpage command, and this will reset the page number.
Here's a complete minimal example:
\documentclass[notitlepage]{article}

\title{My Report}
\author{My Name}

\begin{document}
\maketitle
\thispagestyle{empty}

\begin{abstract}
\ldots
\end{abstract}

\clearpage
\pagenumbering{arabic}

\section{First Section}
\ldots

\end{document}


text:
Q: Getting an error while trying to build an argument parser Code I entered and error message:
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="path to input image to be OCR'd")
ap.add_argument("-p", "--preprocess", type=str, default="thresh", help="type of preprocessing to be
                 done, choose from blur, linear, cubic or bilateral")
args = vars(ap.parse_args())

Error Message:
####usage: ipykernel_launcher.py [-h] -i IMAGE [-p PREPROCESS]
####ipykernel_launcher.py: error: the following arguments are required: -i/--image
####An exception has occurred, use %tb to see the full traceback.
####SystemExit: 2


text:
Q: Chaining 32bit content length field to 8bit message in js socket I'm using Flatbuffers over sockets, which sends 8 bit binary buffers between NodeJS based client to GO based server.
In order to support to dynamic size messages, I've added as suggested from another stackoverflow thread
I've added a 32 bit size content prefix header to announce the size of the message to deal with dynamic size messages.
I'm unsure as to if I've made the best possible way to convert (except using bitwise operations) the 32 bit value to 8 bit array. I'd be happy for recommendations for optimizations or other solutions.
const serializedMessage = builder.asUint8Array(); //returns the constructed flatbuffer message in binary format ready to be sent
let result = new Uint8Array(4 + serializedMessage.length); //adding 4 bytes to accomdate the 32 bit size content length
let view = new DataView(result.buffer);
view.setUint32(0, serializedMessage.length, true);
result.set(serializedMessage, 4);
socket.write(Buffer.from(result.buffer));


text:
Q: unable to find an inherited method for function 'readHTMLTable' for signature '"xml_document"' I'm looking to scrape webpages for betting odds, but keep coming across two problems.
I have come across the "html" is deprecated, use xml::read_table which works. Then I come across another issue with ReadHTMLTable, which gives me the error of
Error in (function (classes, fdef, mtable)  :
  unable to find an inherited method for function 'readHTMLTable' for signature '"xml_document"'
    library(RCurl)
    library(rvest)
    library(magrittr)
    library(XML)
    library(xml2)

# Append date to output file names:
    IncludeDateTime <- function(str, sep='_',
    date.format="%Y_%m_%d_%H_%M") {
    stopifnot(is.character(str))
    return(paste(str, format(Sys.time(), date.format), sep=sep))
    }

    # List of websites for data extraction:
    websiteList <- "http://www.betexplorer.com/soccer/england/premier-league/",

    betexplorer <- XML::xmlParse(websiteList)
    betexplorerTable <-
    readHTMLTable(betexplorer,header=T,which=1,stringsAsFactors=F)
    betexplorerTable <- betexplorerTable[2,]
    write.csv(betexplorerTable,
    file=paste(IncludeDateTime("BetexplorerTable"), ".csv"))

What I'd like to be able to do is select a table from the given webpage.


text:
Q: core data with tree structure - return only 1 level I'm using Core Data and I have a file-folder tree-like structure. So I've created 2 subclasses of NSManagedObject as follows:
FolderMO

Attributes:
  - FolderName
Relationships:
  - the FolderMO itself (since it can have sub-folders)
  - FileMO (it can have a list of files that belong in the folder)

FileMO

Attributes:
  - FileName

The data that I need to store is essentially 3 levels of folders, and then a level of files. On the 1st level I have ~20 Folders, and each Folder has ~20 sub-folders, and each sub-folder has a number of sub-sub-folders, and then finally I have the files that belong in said-folder. I have ~10,000 files total that I need to store.

My Question
Is there a way that I can retrieve only 1 level of my data at a time? ie: Will Core Data let me retrieve only the 1st level of folders to display to the user. Then, if they make a selection, I will retrieve the next level based on their selection? I don't want to have to load all my data into memory at once, especially since the user may not even use this portion of the application.
Thanks!
Sunny

A: Core data wont load all objects until you access them


text:
Q: Custom file properties in Dropbox Core API? In the Google Drive API there is something called custom file properties - https://developers.google.com/drive/web/properties - and they can be used to add your own as key/value pairs:
{
  'key':        'additionalID',
  'value':      '8e8aceg2af2ge72e78',
  'visibility': 'PRIVATE'
}

I would like to do the same in a desktop Java application with the Dropbox Core API, but I cannot find anything. Am I missing something or is this simply not available in Dropbox Core API?
If there is something, please provide an example of how it would be used in Java. Thanks!

A: Looks like Dropbox has begun to implement this feature.
In API v2 there are such endpoints:
properties/template/add
properties/template/get
properties/add
properties/remove
properties/update

and so on.
Details looks at API Documentation.
But all of them are marked as:

PREVIEW - may change or disappear without notice

Good luck with it.

A: The Dropbox API now offers the (now non-preview) ability to add arbitrary key/value data to Dropbox files via "file properties":
https://www.dropbox.com/developers/documentation/http/documentation#file_properties
If you're using an official Dropbox SDK, there will also be corresponding methods for these endpoints.


text:
Q: status code 400 error in ios I'm using iOS 7, where I work with NSURLSession to connect with the server.
I have tried the following codes:
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration
    defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:
    defaultConfigObject delegate: nil delegateQueue:
    [NSOperationQueue mainQueue]];
    NSURL * url = [NSURL URLWithString:@"http://**********/api/Users"];
    NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
     NSString * params
    =@"FirstName=Aravind&LastName=India&WorkingEmailAddress=aravind@gmail.com";
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
    completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
   {
    NSLog(@"Response:%@ %@\n", response, error);
    if(error == nil)
        {
         NSString * text = [[NSString alloc] initWithData: data encoding:
         NSUTF8StringEncoding];
         NSLog(@"Data = %@",text);
        }

    }];
    [dataTask resume];

And the error I am getting is as follows:
     { status code: 400, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 0;
Date = "Wed, 20 Nov 2013 05:05:39 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/7.5";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
 } } (null)
 2013-11-20 10:35:39.723 SessionApp[27223:a0b] Data = .

I can't understand. What should I do to check the error? Please guide me, I am new to iOS.

A: It seems like you are unaware of how to send Parameters request to Server. I would like you to have a look at this library and its examples. It would help you get out of this problem.
https://github.com/AFNetworking/AFNetworking
Example for sending parameters
NSDictionary *parameters = @{@"foo": @"bar", @"baz": @[@"firstName", @"lastName", @"Email"]};

A: As per server response, there is no content to post.
You can get idea through this link


text:
Q: Why have I this error? I am using last.fm API from here http://code.google.com/p/lastfm-java/
I downloaded it to my workspace, checked it as library, and imported it to my project...
The problem comes when I try to use one method of the API
Artist[] artist = LastFmServer.searchForArtist("hatebreed");

I dont know why, it says
Cannot make a static reference to the non-static method searchForArtist(String) from the type LastFmServer

But I have another error trying to solve it. It causes this line
String artist = Artist.getName();

Cannot make a static reference to the non-static method getName() from the type Artist

its my first time using APIs, and i started getting tired of these errors, please help

A: Like other said you need to Instantiate LastFmServer like
LastFmServer mLastFmServer= new LastFmServer();

and then called you method like
Artist[] artist = mLastFmServer.searchForArtist("hatebreed");

A: You have to instantiate a LastFmServer and Artist with new (or the appropriate factory method.

A: You need to instantiate the respective objects of LastFmServer and Artist by using new.
LastFmServer lastFmServerObj = new LastFmServer();

A: You have to call the methods through a object and not make a static reference.
I'm guessing you'd create an LastFmServer like so (depending on the constructor).
LastFmServer object = new LastFmServer();

I hope this helps.


text:
Q: How to get unique client/device id How to identify user of my website in IP non-based way? I'm looking for something like fingerprint2.js, but user identity should be the same no matter if user change browser or ip address. One device = one const identifier.

A: Short answer is you can't, at least not reliably, especially with just JavaScript.
Existing fingerprinting techniques leverage what are essentially considered by vendors as security flaws in the information the browser exposes to try and come up with a unique "fingerprint" for a user. This relies on browser-specific features, though.
Something which provided enough info/allowed you to store data which escapes the sandbox of a specific browser and persistently identifies a user computer-wide would almost certainly be considered a serious security flaw, and would be patched rather quickly.
See this question for more details.


text:
Q: Add value from Php array and increment next I have an array which holds a list of colours.
<?php $colours = array("pink", "red", "blue", "green", "yellow", "grey", "cyan"); ?>

I then have a Wordpress loop running to display posts. Is there a way that each post would have a value taken from the array and then the one after would have the other value?
For example:
First post:

Second post:

A: if it's a loop like this

 <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?>

you can simply add a counter like this

<?php $count = 0; ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

<div class="<?php echo $colours[$count % count($colours)]; ?>">
<?php $count++; ?>

<a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?>

A: <?php
foreach($colours as $color) {
?>
<div class="<?php echo $color; ?>">

<?php } ?>

A: You can make a decision over key. Check it if odd then it will go to the 1st div else even it will go to the 2nd div. Wish it helps.


text:
Q: Android CalendarView Display Specific Month Using CalendarView I need to display a particular month for when device is rotated. While I need to use "setDate" to set the date currently selected, I also need to display the month that was displayed which can be a totally different month to the date selected.  When the device was rotated, the user may be positioned on a completely different month to the month currently selected. I need to be able to position on that month in the new orientation. I have not been able to find a way to do that.

A: static final String STATE_DATA = "data";
private String mData;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Check whether we're recreating a previously destroyed instance
    if (savedInstanceState != null) {
        // Restore value of members from saved state
        mData = savedInstanceState.getString(STATE_DATA);
    } else {
        // Probably initialize members with default values for a new instance
        mData = "NewData";
    }
}

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {

     savedInstanceState.putString(STATE_DATA, mData);
    // Always call the superclass so it can save the view hierarchy state

     super.onSaveInstanceState(savedInstanceState);
}

Hope you aware of the lifecycle of Activity.


text:
Q: Triple pendulum simulation is out of control I'm trying to make a triple pendulum in html5's canvas element whilst using angular.

interface Bob {
  mass: number;
  length: number;
  angle: number;
  velocity: number;
  x: number;
  y: number;
  acc: number
}

export class PendulumBobs {
  private bob1: Bob = {
    mass: 10,
    length: 0,
    angle: Math.PI / 2,
    velocity: 0,
    x: 0, y: 0,
    acc: 0
  }

  private bob2: Bob = {
    mass: 10,
    length: 0,
    angle: Math.PI / 2,
    velocity: 10,
    x: 0, y: 0,
    acc: 0
  }

  private bob3: Bob = {
    mass: 10,
    length: 0,
    angle: Math.PI / 2,
    velocity: 0,
    x: 0, y: 0,
    acc: 0
  }

  public radius: number = 10;
  public color: string = 'black';

  private canvas!: any;
  private c!: CanvasRenderingContext2D;

  private gravity: number = 1;

  length = {
    bob1: 0, bob2: 0, bob3: 0
  }
  constructor(
    canvas: HTMLCanvasElement,
    color: string,
    radius: number,
    length1: number, length2: number, length3: number
  ) {

    this.canvas = canvas;
    this.c = this.canvas.getContext('2d');

    this.length.bob1 = length1;
    this.length.bob2 = length2;
    this.length.bob3 = length3;

    this.bob1.length = this.length.bob1;
    this.bob2.length = this.length.bob2;
    this.bob3.length = this.length.bob3;

    this.radius = radius
  };

  line(x1: number, y1: number, x2: number, y2: number, color: string) {
    this.c.beginPath();
    this.c.moveTo(x1, y1);
    this.c.lineTo(x2, y2);
    this.c.strokeStyle = color;
    this.c.stroke();
  }

  bob(xCoord: number, yCoord: number, radius: number, color: string) {
    this.c.beginPath();
    this.c.arc(xCoord, yCoord, radius, 0, Math.PI * 2, false);
    this.c.fillStyle = color;
    this.c.fill();
    this.c.closePath();
  }

  draw() {
    //drawing the pendulum
    this.line(this.c.canvas.width/2, 0, this.bob1.x, this.bob1.y, this.color);
    this.bob(this.bob1.x, this.bob1.y, this.radius, this.color);
    //first string and bob ^
    this.line(this.bob1.x, this.bob1.y, this.bob2.x, this.bob2.y, this.color);
    this.bob(this.bob2.x, this.bob2.y, this.radius, this.color);
    //second string and bob ^^
    this.line(this.bob2.x, this.bob2.y, this.bob3.x, this.bob3.y, this.color);
    this.bob(this.bob3.x, this.bob3.y, this.radius, this.color);
    //third string and bob ^^
  }

  update() {
    let formula1 = {
      part1: this.gravity*this.bob1.length*(this.bob1.mass*this.sin(this.bob1.angle)+this.bob2.mass*this.sin(this.bob1.angle)+this.bob3.mass*this.sin(this.bob1.angle))+this.bob2.mass*this.bob1.length*this.bob2.length*this.sin(this.bob1.angle-this.bob2.angle)*this.bob1.velocity*this.bob2.velocity,
      part2: this.bob3.mass*this.bob1.length*this.bob3.length*this.sin(this.bob1.angle-this.bob3.angle)*this.bob1.velocity*this.bob3.velocity+this.bob3.mass*this.bob1.length*this.bob2.length*this.sin(this.bob1.angle-this.bob2.angle)*this.bob1.velocity*this.bob2.velocity+this.bob1.length**2*this.bob1.acc*(this.bob1.mass+this.bob2.mass+this.bob3.mass),
      part3: this.bob2.mass*this.bob1.length*this.bob2.length*this.sin(this.bob2.angle-this.bob1.angle)*(this.bob1.velocity-this.bob2.velocity)*this.bob2.velocity+this.cos(this.bob1.angle-this.bob2.angle)*this.bob2.acc,
      part4: this.bob3.mass*this.bob1.length*this.bob2.length*this.sin(this.bob2.angle-this.bob1.angle)*(this.bob1.velocity-this.bob2.velocity)*this.bob2.velocity+this.cos(this.bob1.angle-this.bob2.angle)*this.bob2.acc,
      part5: this.bob3.mass*this.bob1.length*this.bob3.length*this.sin(this.bob3.angle-this.bob1.angle)*(this.bob1.velocity-this.bob3.velocity)*this.bob3.velocity+this.cos(this.bob1.angle-this.bob3.angle)*this.bob3.acc
    }
    this.bob1.angle = formula1.part1 + formula1.part2 + formula1.part3 + formula1.part4 + formula1.part5;

    let formula2 = {
      part1: this.gravity*this.bob2.length*(this.bob2.mass*this.sin(this.bob2.angle)+this.bob3.mass*this.sin(this.bob2.angle))+this.bob1.velocity*this.bob2.velocity*this.bob1.length*this.bob2.length*this.sin(this.bob2.angle-this.bob1.angle)*(this.bob2.mass+this.bob3.mass),
      part2: this.bob3.mass*this.bob2.length*this.bob3.length*this.sin(this.bob2.angle-this.bob3.angle)*this.bob2.velocity*this.bob3.velocity+this.bob2.length**2*this.bob2.acc*(this.bob2.mass+this.bob3.mass),
      part3: (this.bob2.mass+this.bob3.mass)*this.bob1.length*this.bob2.length*(this.sin(this.bob2.velocity-this.bob1.velocity)*( this.bob1.velocity-this.bob2.velocity)*this.bob1.velocity+this.cos(this.bob2.velocity-this.bob1.velocity)*this.bob1.acc),
      part4: this.bob3.mass*this.bob2.length*this.bob3.length*(this.sin(this.bob3.angle-this.bob2.angle)*( this.bob2.velocity-this.bob3.velocity)*this.bob3.velocity+this.cos(this.bob2.angle-this.bob3.angle)*this.bob3.acc)
    }
    this.bob2.angle = formula2.part1 + formula2.part2 + formula2.part3 + formula2.part4;

    let formula3 = {
      part1: this.bob3.mass*this.gravity*this.bob3.length*this.sin(this.bob3.angle)-this.bob3.mass*this.bob1.length*this.bob3.length*this.sin(this.bob2.angle-this.bob3.angle)*this.bob2.velocity*this.bob3.velocity-this.bob3.mass*this.bob1.length*this.bob3.length*this.sin(this.bob1.angle-this.bob3.angle)*this.bob1.velocity*this.bob3.velocity,
      part2: this.bob3.mass*this.bob1.length*this.bob3.length*(this.sin(this.bob3.angle-this.bob1.angle)*(this.bob1.velocity-this.bob3.velocity)*this.bob1.velocity+this.cos(this.bob1.angle-this.bob3.angle)*this.bob1.acc),
      part3: this.bob3.mass*this.bob1.length*this.bob3.length*(this.sin(this.bob3.angle-this.bob2.angle)*(this.bob2.velocity-this.bob3.velocity)*this.bob2.velocity+this.cos(this.bob2.angle-this.bob3.angle)*this.bob2.acc)+this.bob3.mass*this.bob2.length**2*this.bob3.acc
    }
    this.bob3.angle = formula3.part1 + formula3.part2 + formula3.part3;

    this.bob1.x =  this.canvas.width/2 + this.bob1.length * Math.sin(this.bob1.angle);
    this.bob1.y = this.bob1.length * Math.cos(this.bob1.angle);

    this.bob2.x = this.bob1.x + this.bob2.length * Math.sin(this.bob2.angle);
    this.bob2.y = this.bob1.y + this.bob2.length * Math.cos(this.bob2.angle);

    this.bob3.x = this.bob2.x + this.bob3.length * Math.sin(this.bob3.angle);
    this.bob3.y = this.bob2.y + this.bob3.length * Math.cos(this.bob3.angle);
    this.draw()
  }

  sin(x: number) {
    return Math.sin(x)
  }

  cos(x: number) {
   return Math.cos(x)
  }
}

The above code block is my triple pendulum class. For each of their angle I use the three formulas from https://www.researchgate.net/publication/336868500_Equations_of_Motion_Formulation_of_a_Pendulum_Containing_N-point_Masses

The formulas can be seen on the 5th and 6th pages.
When I finally completed the class I use it in my triple-pendulum component and initialize it
 @ViewChild('canvas', {static: false}) canvas!: ElementRef;
 private c!: CanvasRenderingContext2D;
 triplePendulum!: PendulumBobs;

 constructor() { };

 ngAfterViewInit(): void {
   this.c = this.canvas.nativeElement.getContext('2d');
   this.c.canvas.width = window.innerWidth;
   this.c.canvas.height = window.innerHeight;
   this.c.translate(0, 300)

   this.triplePendulum = new PendulumBobs(
     this.canvas.nativeElement,
     'black',
     10,
     this.canvas.nativeElement.width / this.canvas.nativeElement.height * 60,
     this.canvas.nativeElement.width / this.canvas.nativeElement.height * 60,
     this.canvas.nativeElement.width / this.canvas.nativeElement.height * 60,
   );
   this.animate()
 }

 animate() {
   requestAnimationFrame(() => this.animate());
   this.c.clearRect(0, -this.c.canvas.height, this.c.canvas.width, this.c.canvas.height * 2);
   this.triplePendulum.update();
 }

But when I run my project the triple pendulum is all erratic and doesn't look like a proper pendulum at all. I'm pretty sure the issue is in some variable of the bob objects in the pendulum class that I created, but I don't know what it is.

The above gif is just a representation of how unnatural and erratic the simulation is.
Please suggest a possible solution to this problem


text:
Q: Issue with socket.io join room I have a issue with socket.io with rooms.
See the server code:
This code below is working properly.
io.on('connection', function(socket){

 socket.join("myroom");

 socket.on('chat message', function(data){
  io.in("myroom").emit('chat message', data);
 });

});

But I want the user to enter the room after an event.
Like the code below.
io.on('connection', function(socket){

 socket.on('chat message', function(data){
  io.in("myroom").emit('chat message', data);
 });

 socket.on('join', function(name, device, room){
   socket.join("myroom");
 });

});

It's almost the same code , but does not work. What am I doing wrong?
The event is being called correctly.
Edit. Added the front-end code:
var socket = io.connect('http://localhost:5000');

   $('#msg_form').submit(function(){
     socket.emit('chat message', $("#m").val(), "myroom");
     $('#m').val('');
     return false;
   });

   $("#user").submit(function() {
      var name = $("#name").val();
      var room = $("#room").val();
      var device = navigator.userAgent;

      if (name === "" || name.length < 2) {
        $("#errors").empty();
        $("#errors").append("Please enter a name");
        $("#errors").show();
      } else {
        socket.emit("join", name, device, room);
        $("#messages").focus();
      }
    });

Thank you.

A: I made this small demo to explain, I simulate the client-side event by setTimeout functions:
Server side:
var http = require('http');
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);

server.listen(9999);

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function (socket) {

  socket.on('message', function(data){
  io.in("myroom").emit('message', data);
 });

 socket.on('join', function(name, device, room){
  console.log("new client has joining a room");
   socket.join("myroom");
 });
  });

Client Side:
    <script src="/socket.io/socket.io.js"></script>
<script>

var socket = io.connect('http://localhost:9999');

setTimeout(function () { console.log("msg emmited to server");
    socket.emit('join');

},

    10000);
setTimeout(function () {
 console.log("msg emmited to server");
    socket.emit("message","message from client");
},

    20000);

socket.on("message",function(data){
  console.log("message received from server ="+data);
    }
    );

</script>

A: In your $("#user").submit(...) handler, you do not prevent the default action of the form so it is likely that the page is reloaded right after you hit the submit button.  And, this will reset your connection right after you hit join, giving you a newly initialize connection that is not joined into the room.
You can either add return false; to that handler or add the e argument to the handler and call e.preventDefault() to prevent the page from reloading when you hit submit.
  $("#user").submit(function(e) {
      e.preventDefault();
      var name = $("#name").val();
      var room = $("#room").val();
      var device = navigator.userAgent;

      if (name === "" || name.length < 2) {
        $("#errors").empty();
        $("#errors").append("Please enter a name");
        $("#errors").show();
      } else {
        socket.emit("join", name);
        $("#messages").focus();
      }
    });


text:
Q: How to apply lookup transformation column wise multiple times I need to compare 2 data sets - excel and DB. While comparing need to check 4 fields say, A, B C & D columns from both the data sets. The output should tell which field is not matching like Mismatch A, Mismatch B etc. How can we implement this in SSIS?
I tried implementing using lookup transformations multiple times. 1st time for column A and non matching records with Mismatch A and send matching records to 2nd lookup for column A & column B comparison. No match output from 2nd lookup as Mismatch B like this..
But this is not working after 1st lookup.

A: Use a merge join transformation.  You would sort both inputs on the join key.  Once merged, use a derived column component to evaluate the columns.  i.e.
ExcelColumnA == dbColumnA ? "" : ("excel: + "ExcelColumnA + "; db: " + dbColumnA )

Name each column as mismatchA, etc.

A: It got solved !!! :) The issue was I was using output of 1st lookup in 2nd lookup as input instead of using the original input. Now am getting desired result.


text:
Q: Obtain the most concret type according to DBpedia class hierarchy in N-Triples file I have a N-Triples file with entity types like this (sample):
<http://es.dbpedia.org/resource/Volcán_Ichinski> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/Location> .
<http://es.dbpedia.org/resource/Volcán_Ichinski> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/NaturalPlace> .
<http://es.dbpedia.org/resource/Volcán_Ichinski> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/Place> .
<http://es.dbpedia.org/resource/Wayne_Watson> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/Agent> .
<http://es.dbpedia.org/resource/Wayne_Watson> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/Person> .
<http://es.dbpedia.org/resource/Weston_(Texas)> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/Location> .
<http://es.dbpedia.org/resource/Weston_(Texas)> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/Place> .
<http://es.dbpedia.org/resource/Weston_(Texas)> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/PopulatedPlace> .
<http://es.dbpedia.org/resource/Weston_(Texas)> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/Region> .

I want to obtain the most concrete type according to DBpedia class hierarchy for each entity. Thus, each entity in the file will only have 1 DBpedia type.
In this case, result will be something like this (sample):
<http://es.dbpedia.org/resource/Volcán_Ichinski> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/NaturalPlace> .
<http://es.dbpedia.org/resource/Wayne_Watson> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/Person> .
<http://es.dbpedia.org/resource/Weston_(Texas)> <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <http://dbpedia.org/ontology/Region> .

I don't know if this is possible, if not I will like to do something similar.
Hope you can help me. Thanks in advance.


text:
Q: Linq to get a combined list out of lists C# I have a list like this,
List<FruitCategory>
     List<Fruit>
          List<Order>

Now what I want is to get distinct Orders from all Fruits based on order id..
var orders =
FruitCategories.SelectMany(fruitCategories => fruitCategories.Fruits)
         .Where(fruit => fruit.Order).SelctMany... not sure rest

A:  var orders = FruitCategories.SelectMany(fc => fc.Fruits).SelectMany(f => f.Order);
 var distinctOrders = orders.GroupBy(o => o.Id).Select(og => og.First());

Where() acts like filter, not selector.
EDIT: didn't read about distinct by id requirement.


text:
Q: Excel VBA evaluate formula from another sheet Solved: The problem is in my formula where I'm referencing a cell using INDIRECT() which doesn't work when sheet is different. See answer.
I have a formula in one sheet and what I want to do is to use the formula from another sheet, using eval to evaluate the formula. However, the result is not as intended. It seems like the formula is using values at Sheet A instead of the caller Sheet B.
Formula in sheet A (See: Screenshot Sheet A)
=IF(ISERROR(INDEX('1516Activity'!$B:$B,MATCH(INDIRECT(ADDRESS(ROW(),COLUMN(D:D) )),'1516Activity'!$C:$C,0))),"-",IF(LEFT(INDEX('1516Activity'!$F:$F,MATCH(INDIRECT(ADDRESS(ROW(),COLUMN(D:D) )),'1516Activity'!$C:$C,0)))="0","N","Y"))

Usage in Sheet B (See: Screenshot Sheet B)
=Eval('CODE-VARS'!$G$5)

VBA:
Function Eval(Ref As String)
    Application.Volatile
    Eval = Application.ThisCell.Parent.Evaluate(Ref)
End Function

A: You are evaluating the String 'CODE-VARS'!$G$5 which would return the value in that cell not its formula.  Try this:
Function Eval(Ref As RAnge)
    Application.Volatile
    Eval = Application.ThisCell.Parent.Evaluate(Ref.formula)
End Function

A: It seems to me that it references values in whatever sheet is active.
In your Eval function,  ensure the target sheet is active:
Function Eval(Ref As String)
    Dim shCurrent As Worksheet: Set shCurrent = ActiveSheet
    Application.Volatile
    Application.ThisCell.Parent.Activate
    Eval = Application.ThisCell.Parent.Evaluate(Ref)
    shCurrent.Activate
End Function

A: I think you are looking for Application.Caller:
Function Eval(Ref As String)
    Application.Volatile
    Eval = Application.Caller.Parent.Evaluate(Ref)
End Function

A: The problem is I'm referencing a cell using INDIRECT() which doesn't work when the eval() is called from a different sheet.
This works:
INDEX(D:D,ROW())

This doesn't:
INDIRECT(ADDRESS(ROW(),COLUMN(D:D) ))


text:
Q: SQL join basic questions When I have to select a number of fields from different tables:

*

*do I always need to join tables?

*which tables do I need to join?

*which fields do I have to use for the join/s?

*do the joins effects reflect on fields specified in select clause or on where conditions?

Thanks in advance.

A: Very broad question, i would suggest doing some reading on it first but in summary:
1. joins can make life much easier and queries faster, in a nut shell try to
2. the ones with the data you are looking for
3. a field that is in both tables and generally is unique in at least one
4. yes, essentially you are createing one larger table with joins. if there are two fields with the same name, you will need to reference them by table name.columnname

A: Think about joins as a way of creating a new table (just for the purposes of running the query) with data from several different sources. Absent a specific example to work with, let's imagine we have a database of cars which includes these two tables:
CREATE TABLE car (plate_number CHAR(8),
                  state_code CHAR(2),
                  make VARCHAR(128),
                  model VARCHAR(128),);

CREATE TABLE state (state_code CHAR(2),
                    state_name VARCHAR(128));

If you wanted, say, to get a list of the license plates of all the Hondas in the database, that information is already contained in the car table. You can simply SELECT * FROM car WHERE make='Honda';
Similarly, if you wanted a list of all the states beginning with "A" you can SELECT * FROM state WHERE state_name LIKE 'A%';
In either case, since you already have a table with the information you want, there's no need for a join.
You may even want a list of cars with Colorado plates, but if you already know that "CO" is the state code for Colorado you can SELECT * FROM car WHERE state_code='CO'; Once again, the information you need is all in one place, so there is no need for a join.
But suppose you want a list of Hondas including the name of the state where they're registered. That information is not already contained within a table in your database. You will need to "create" one via a join:
car INNER JOIN state ON (car.state_code = state.state_code)

Note that I've said absolutely nothing about what we're SELECTing. That's a separate question entirely. We also haven't applied a WHERE clause limiting what rows are included in the results. That too is a separate question. The only thing we're addressing with the join is getting data from two tables together. We now, in effect, have a new table called car INNER JOIN state with each row from car joined to each row in state that has the same state_code.
Now, from this new "table" we can apply some conditions and select some specific fields:
SELECT plate_number, make, model, state_name
FROM car
INNER JOIN state ON (car.state_code = state.state_code)
WHERE make = 'Honda'

So, to answer your questions more directly, do you always need to join tables? Yes, if you intend to select data from both of them. You cannot select fields from car that are not in the car table. You must first join in the other tables you need.
Which tables do you need to join? Whichever tables contain the data you're interested in querying.
Which fields do you have to use? Whichever fields are relevant. In this case, the relationship between cars and states is through the state_code field in both table. I could just as easily have written
car INNER JOIN state ON (state.state_code = car.plate_number)

This would, for each car, show any states whose abbreviations happen to match the car's license plate number. This is, of course, nonsensical and likely to find no results, but as far as your database is concerned it's perfectly valid. Only you know that state_code is what's relevant.
And does the join affect SELECTed fields or WHERE conditions? Not really. You can still select whatever fields you want and you can still limit the results to whichever rows you want. There are two caveats.
First, if you have the same column name in both tables (e.g., state_code) you cannot select it without clarifying which table you want it from. In this case I might write SELECT car.state_code ...
Second, when you're using an INNER JOIN (or on many database engines just a JOIN), only rows where your join conditions are met will be returned. So in my nonsensical example of looking for a state code that matches a car's license plate, there probably won't be any states that match. No rows will be returned. So while you can still use the WHERE clause however you'd like, if you have an INNER JOIN your results may already be limited by that condition.

A:
do I always need to join tables?

No - you could perform multiple selects if you wished

which tables do I need to join?

Any that you want the data from (and need to be related to each other)

which fields do I have to use for the
  join/s?

Any that are the same in any tables within the join (usually primary key)

do the joins effects reflect on fields specified in select clause or on where conditions?

No, however outerjoins can cause problems

A: (1) what else but tables would you want to join in mySQL?
(2) those from which you want to correlate and retrieve fields (=data)
(3) best use indexed fields (unique identifiers) to join as this is fast. e.g. join
retrieve user-email and all the users comments in a 2 table db
(with tables: tableA=user_settings, tableB=comments) and both having the column uid to indetify the user by
select * from user_settings as uset join comments as c on uset.uid = c.uid where uset.email = "test@stackoverflow.com";
(4) both...


text:
Q: Trying to understand the BroadcastReceiver in android coding First off am a complete newbie to Android coding and the logic is really confusion me. Originally im Flash developer and im familiar with concepts from there, while Android is complete set of new concepts. For example (correct me if im wrong) a Intent is like an Event and BroadcastReceiver is a EventListener ?
Well it is here im stuck, if it is so, Intent is Event and broadcastReceiver is eventListener then my question is how do i assign a variable, data that ive handeled in onReceive method ?
Ive been searching for long time now and really get angry at myself for not understanding the logic. Im trying to compare and associate things to ActionScript3 and Javascript (some stuff in JS is pretty close to AS3).
Now to the code im trying to write and the problem i got.
Im trying to get myself into writing a Android Native Extension for Adobe AIR...
So, far so good at least in some way :)
The manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.as3breeze.air"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.BLUETOOTH"/>
    <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".BluetoothExtension"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

As i see, the main activity is my BluetoothExtension.java which is following:
Notice it implements FREExtension (created by Adobe for Native Extensions)
package com.as3breeze.air;

import com.adobe.fre.FREContext;
import com.adobe.fre.FREExtension;
import com.as3breeze.air.BluetoothExtensionContext;

public class BluetoothExtension implements FREExtension {

    protected BluetoothExtensionContext BEC;

    /** Called when the activity is first created. */
    @Override
    public FREContext createContext(String arg0) {
        BEC = new BluetoothExtensionContext();
        return BEC;
    }

    @Override
    public void dispose() {
        // TODO Auto-generated method stub
        BEC.dispose();
        BEC = null;
    }

    @Override
    public void initialize() {}
}

Thats the Activity, right ?
And it creates Context which is following (am leaving out the @imports):
public class BluetoothExtensionContext  extends FREContext {

public BluetoothAdapter bluetooth;
public Activity extensionActivity;
public FREArray nonBoundedDevices;

@Override
public void dispose() {
    // TODO Auto-generated method stub

}

@Override
public Map<String, FREFunction> getFunctions() {

    Map<String, FREFunction> functionMap=new HashMap<String, FREFunction>();

    functionMap.put("initialize", new Initialize());

    // Leaving out some stuff here and listing only the important things...

    functionMap.put("listDevices", new ListAvailableDevices());

    return functionMap;

    }
}

Now, as you see above i got some public vars for easier access, those are initiated inside new Initialize() which looks like this:
package com.as3breeze.air;

import android.bluetooth.BluetoothAdapter;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREObject;
import com.adobe.fre.FREWrongThreadException;
import com.as3breeze.air.BluetoothExtensionContext;

public class Initialize implements FREFunction {

    @Override
    public FREObject call(FREContext context, FREObject[] args) {

        BluetoothExtensionContext bluetoothContext = (BluetoothExtensionContext) context;
        bluetoothContext.bluetooth = BluetoothAdapter.getDefaultAdapter();
        bluetoothContext.extensionActivity = bluetoothContext.getActivity();

        FREObject returnData = null;
        if( bluetoothContext.bluetooth == null )
        {
            try {
                returnData = FREObject.newObject("notSupported");
            } catch (FREWrongThreadException e) {}
        }
        return returnData;
    }
}

Initiation works fine, i also got other methods listed in the Map such as enabling / disabling bluetooth, discoverability and few more, everything there works well.
But the problem is in this one: functionMap.put("listDevices", new ListAvailableDevices());
The class is created and running and returning, it looks like this:
package com.as3breeze.air;

import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.Toast;

import com.adobe.fre.FREASErrorException;
import com.adobe.fre.FREArray;
import com.adobe.fre.FREContext;
import com.adobe.fre.FREFunction;
import com.adobe.fre.FREInvalidObjectException;
import com.adobe.fre.FREObject;
import com.adobe.fre.FRETypeMismatchException;
import com.adobe.fre.FREWrongThreadException;

public class ListAvailableDevices implements FREFunction {

    static FREArray returnDevicesArr = null;

    @Override
    public FREObject call(FREContext context, FREObject[] args) {
        BluetoothExtensionContext bluetoothContext = (BluetoothExtensionContext) context;
        returnDevicesArr = bluetoothContext.nonBoundedDevices;

        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        BroadcastReceiver mReceiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                int index = 0;

                String action = intent.getAction();

                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    // Get the BluetoothDevice object from the Intent
                    BluetoothDevice bt = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                    Toast.makeText( context, "Searching devices...", Toast.LENGTH_SHORT).show();
                    FREArray deviceName;
                    try {
                        deviceName = FREArray.newArray(1);
                        deviceName.setObjectAt(0, FREObject.newObject(bt.getName()));
                        deviceName.setObjectAt(1, FREObject.newObject(bt.getAddress()));

                        returnDevicesArr.setObjectAt(index, deviceName);
                        index++;
                    } catch (FREASErrorException e) {
                        e.printStackTrace();
                    } catch (FREWrongThreadException e) {
                        e.printStackTrace();
                    } catch (FREInvalidObjectException e) {
                        e.printStackTrace();
                    } catch (FRETypeMismatchException e) {
                        e.printStackTrace();
                    }
                }
            }
        };
        bluetoothContext.extensionActivity.registerReceiver(mReceiver, filter);
        bluetoothContext.bluetooth.startDiscovery();
        return null; // Or to use return returnDeviceArr;

    }
}

As you see, im trying to store  all found devices in returnDeviceArr either to return from call() or in some "global" variable defined in BluetoothExtensionContext.java, it does not matter which way to go, i just need to get hold of that data.
Im not being able to reach the returnDeviceArr variable from onReceive method. Ive also tested to create a new FREArray inside onReceive and store devices data there, so it can be returned but return null; at bottom of call(){ ... } is fired and ultimately giving me null value.
So, how can i make it possible to replace that  return null with return returnDeviceArr; and get the array of available devices ?
Im hoping for code examples and explanations so i can start to understand Android coding without using visual components.

A: The BlueToothExtension class must extend the activity class. Declaring in the manifest alone is not enough. And you should register your broadcast receiver with the intent. Check out the android development guide for more detail.
For Intents to pass variables, you should put them in extras like
`Intent intent = new Intent(this, target.class);
intent.putExtra("variable", value);
startActivityForResult(intent, request_Code);`
In the target class you can fetch the variable using intent.getStringExtra("variable");


text:
Q: Java libgdx program not returning allocated Memory I am running a program in java ( Eclipse ) with the libgdx library.
Now I am at the point where I realized that when the program was running for about a minute
the FPS drops from solid 60 to bouncing from 10 to 40. Also the allocated Memory from the program is rising constantly. But the Heap size is seemingly not rising.
My question is now why the application is not returning the allocated memory to the OS ( windows ) and if there is a correlation between allocated memory and FrameRate.
Here is a link to a picture of an extract from the jconsole data:
http://de.tinypic.com/view.php?pic=jj9z6u&s=5#.UtFp9bSFd7s
( Stack overflow prevents me from uploading pictures directly... )

A: You are probably creating a lot of garbage for the garbage collector to collect.
Use the heap analysis tools in Eclipse or in the ADT to debug the issue.  See http://android-developers.blogspot.com/2011/03/memory-analysis-for-android.html for ideas.


text:
Q: Method to log amount of transmitted data per each IP address in linux I am looking for a method in linux to log the amount of data transmitted (received and sent separately) for every single IP address to which the data was sent to or received from. These statistics would be running on the router, behind which is a private network. I am looking for statistics between the private network and the internet.
I am aware of tools like vnstat, iptraf, also iptables capabilities, but from what I understand, neither of these can do so per each IP address with which communication occurred. Port does not matter here.
Perhaps there is a smart way to parse tcpdump .pcap output?
The application here would be to monitor anomalies from within a private network. I.e., if an unknown IP address seems to be receiving a large amount of data from within the network, it could mean an intrusion.

A: Another very basic tool, with much less functionality, but solving exactly the topic question is 'darkstat'. Provides in/out bytes per IP address in addition to general data usage graphs.

A: Check out ntop. It can do what you want.


text:
Q: Converting Lower Case Characters in a Text File to Upper Case Letters and Vice Versa I have a text file that contains the following text, without a new line character...
Hello World

I would like to convert the lower case characters to upper case, and vice versa, so that the same text file would end up with the following text...
hELLOW wORLD

Unfortuntately, when I run my code, it goes into an endless loop.  When I step through the code, I see that fseek() goes back one byte for the first loop, as expected, but it goes back two bytes for the second and subsequent loops.  I don't understand why it goes back two bytes instead of one.  Why is this the case?  Can someone please help?
Here's my code...
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    FILE *fp;
    int ch;
    long offset;

    fp = fopen("c:\\users\\domenic\\desktop\\test.txt", "r+");
    if (fp == NULL)
    {
        printf("error:  unable to open file\n");
        exit(1);
    }

    offset = ftell(fp);
    while (1)
    {
        ch = fgetc(fp);
        if (ch == EOF)
            break;
        if (isupper(ch))
        {
            fseek(fp, offset, SEEK_SET);
            fputc(tolower(ch), fp);
        }
        else if (islower(ch))
        {
            fseek(fp, offset, SEEK_SET);
            fputc(toupper(ch), fp);
        }
        offset = ftell(fp);
    }

    fclose(fp);

    return 0;
}

A: If I understand you just want to change upper to lower and lower to upper throughout a file, you may be making it a bit harder on yourself than it need be.
Before we look at an approach to make things a bit easier, let's talk about avoiding magic numbers and hardcoded paths within your code. C provides a definition for main that allows you to provide arguments to your code to avoid hardcoding values (such as file/path names) -- use them. The proper invocation of main with arguments is:
int main (int argc, char *argv[])

(or you will see the equivalent int main (int argc, char **argv))
The invocation without arguments is int main (void).
Now on to the question at hand. As mentioned in my comment, when dealing with ASCII, the bit that controls the case is the 6th-bit -- and from the discussion, if you are dealing with EBCDIC, the *case-bitis the 7th-bit. As @chux pointed out both can be handled seamlessly by determining the appropriate bitA ^ afor both (the result is32, e.g.(1 << 5)for ASCII, and64or(1 << 6)for EBCDIC. To toggle any bit on/off you simply XOR the *case-bit* with the current character(A-Za-z). So far any character'c', you wish to toggle the case of, you simply XOR it withA ^ a`, e.g.
if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'))
    c ^= A ^ a;

If c was uppercase, it's now lowercase, and vice-versa.
To do that for an entire file, taking the filename to convert as the first argument to the program (or reading from stdin by default if no argument is given) and outputting the resulting case-converted to stdout, you could do something as simple as the following:
#include <stdio.h>

int main (int argc, char **argv) {

    int c;
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    while ((c = fgetc(fp)) != EOF)          /* read each char */
        /* is it a letter ? */
        if (('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z'))
            putchar (c ^ ('A' ^ 'a'));      /* toggle case */
        else
            putchar (c);                    /* just output */

    if (fp != stdin) fclose (fp);    /* close file if not stdin */

    return 0;
}

Example Input
$ cat dat/captnjack.txt
This is a tale
Of Captain Jack Sparrow
A Pirate So Brave
On the Seven Seas.

Example Use/Output
$ ./bin/case_toggle < dat/captnjack.txt
tHIS IS A TALE
oF cAPTAIN jACK sPARROW
a pIRATE sO bRAVE
oN THE sEVEN sEAS.

If you want to write the output to a new file, simply redirect the output, e.g.
$ ./bin/case_toggle < dat/captnjack.txt > dat/captnjack_toggled.txt

Which would write the case-toggled output to dat/captnjack_toggled.txt.
Look things over and let me know if you have further questions.

A: To start off, fputc does not delete or rather act like an "insert" after you use fseek to go back 1 character.
In this case you are:

*

*getting a char

*fseek to before the char

*placing a upper/lowercase char before the char found in step 2

*setting new offset to right after your new character.

You probably get alot of hEEEEEEEEEEEEEEEEEE in your text file after exiting your endless loop?
To fix this I would create a temporary new file.. something like this:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main()
{
    FILE *fp, *new_f;
    int ch;
    long offset;

    fp = fopen("test.txt", "r+");
    new_f = fopen("test2.txt", "w" );

    if ( fp == NULL || new_f == NULL )
    {
        printf("error:  unable to open file\n");
        exit(1);
    }

    offset = ftell(fp);
    while (1)
    {
        ch = fgetc(fp);

        if (ch == EOF)
            break;

        if( !isalpha( ch ) )
        {
            fputc( ch, new_f );
        }
        else if (isupper(ch))
        {
            fputc(tolower(ch), new_f );
        }
        else if (islower(ch))
        {
            fputc(toupper(ch), new_f);
        }
    }

    fclose( fp );
    fclose( new_f );

    return 0;
}


text:
Q: How can I send the output of a long-running program to stdout in tcl without fileevent? I need to collect the output from a long running external program in Tcl. I can't use exec, because this would block until the other program has finished. So, I think I should open a pipe:
set pipe [open "|long_running_program" "r"]

but then it is not clear to me how to send the output to stdout. I'm using pure Tcl, without the event loop, so I can't use fileevent.

A: What you should do is put the pipe into non-blocking mode. Then you can use read to get everything currently available on the pipe, ready to transfer to stdout. However, you'll need to figure out when to look for output yourself; the fileevent command is Tcl's solution for that, but that requires the use of an event loop. (You could start a temporary one via update or vwait, of course; using tclsh doesn't mean no event loop, but rather just means no default event loop.)
fconfigure $pipe -blocking 0

set data [read $pipe]
if {[eof $pipe]} {
    # Other side is finished; close the pipe?
} elseif {[fblocked $pipe]} {
    # No data available right now; try later
} else {
    # Print to stdout; use the newlines already in the data
    puts -nonewline $data
}

You should also be aware that many programs only deliver data in bursts when they're writing to a pipe. They change their behavior depending on whether they're writing to a pipe or to a terminal. This can matter a lot, especially if you're doing command automation; if it does to you, your best option is the Expect extension package.