text:
Q: Mup Deploy dont work on AWS i will explain my problem, im trying to deploy an Meteor App on EC2 AWS (Ubuntu 16), the code is download from bitbucket and i was trying deploy with Mup.
Mup Setup has no problems, but when using the Mup deploy command, it progresses to "minifying app code" and never goes forward.
Meteor 1.7.0.4
node v 10.9.0
mup --version
    1.4.5
Attach the Mup.js file and the putty session
module.exports = {
  servers: {
    one: {
      // TODO: set host address, username, and authentication method
      host: 'xxxx',
      username: 'ubuntu',
      pem: '../xxxx.pem'
      // password: 'server-password'
      // or neither for authenticate from ssh-agent
    }
  },

  app: {
    // TODO: change app name and path
    name: 'xxxx',
    path: '../',

    servers: {
      one: {},
    },

    buildOptions: {
      serverOnly: true,
      executable: 'meteor'
    },

    env: {
      ROOT_URL: 'http://xxxx',
      MONGO_URL: 'mongodb://mongodb/meteor',
      MONGO_OPLOG_URL: 'mongodb://mongodb/local',
    },

    docker: {
      // change to 'abernix/meteord:base' if your app is using Meteor 1.4 - 1.5
      image: 'abernix/meteord:node-8.4.0-base',
    },

    enableUploadProgressBar: true,
    deployCheckWaitTime: 120,
  },

  mongo: {
    version: '3.4.1',
    servers: {
      one: {}
    }
  },

};

Putty Session
Using username "ubuntu".
Authenticating with public key "imported-openssh-key"
Welcome to Ubuntu 16.04.4 LTS (GNU/Linux 4.4.0-1065-aws x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  Get cloud support with Ubuntu Advantage Cloud Guest:
    http://www.ubuntu.com/business/services/cloud

28 packages can be updated.
0 updates are security updates.

New release '18.04.1 LTS' available.
Run 'do-release-upgrade' to upgrade to it.

Last login: Fri Aug 17 22:06:59 2018 from xxxx
ubuntu@xxxx:~$ meteor --version
Meteor 1.7.0.4
ubuntu@xxxx:~$ node -v
v10.9.0
ubuntu@xxxx:~$ mup --version
1.4.5
ubuntu@xxxx:~$ cd xxxx
ubuntu@xxxx:~/xxxx$ cd .deploy
ubuntu@xxxx:~/xxxx/.deploy$ mup status
=> Servers
  - xxxx: Ubuntu 16.04

=> Docker Status
 - xxxx: 18.06.0-ce Running

=> Meteor Status
 - xxxx: created
    Created at 2018-08-17T16:17:42.747786756Z
    Restarted 0 times
    ENV:
     - ROOT_URL=http://xxxx
     - MONGO_URL=mongodb://mongodb:27017/xxxx
     - MONGO_OPLOG_URL=mongodb://mongodb/local
     - METEOR_SETTINGS={"public":{}}
     - PORT=80
     - PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
     - METEORD_DIR=/opt/meteord
     - NODE_VERSION=8.4.0
    Published Ports:
     - 80/tcp => 80
    App running at http://xxxx:80
     - Available in app's docker container: false
     - Available on server: false
     - Available on local computer: false

=> Mongo Status
  running on server xxxx
  Restarted 0 times
  Running since 2018-08-17T21:41:02.553644287Z
  Version: 3.4.1
  Connections: 1
  Storage Engine: wiredTiger
ubuntu@xxxx:~/xxxx/.deploy$ mup setup

Started TaskList: Setup Docker
[xxxx] - Setup Docker
[xxxx] - Setup Docker: SUCCESS

Started TaskList: Setup Meteor
[xxxx] - Setup Environment
[xxxx] - Setup Environment: SUCCESS

Started TaskList: Setup Mongo
[xxxx] - Setup Environment
[xxxx] - Setup Environment: SUCCESS
[xxxx] - Copying mongodb.conf
[xxxx] - Copying mongodb.conf: SUCCESS

Started TaskList: Start Mongo
[xxxx] - Start Mongo
[xxxx] - Start Mongo: SUCCESS

Next, you should run:
    mup deploy
ubuntu@xxxx:~/xxxx/.deploy$ mup deploy --verbose settings settings.json
Building App Bundle Locally
   Minifying app code

After several minutes the connection with the instance is lost and I have to restart it, please help me with this problem that i never had before and i need fix soon. Thanks!
I tried "mup deploy --verbose --settings settings.json" command with  a very basic app in the same instance of AWS, and get pass the "minifiying" problem, but throw the next error:
Next, you should run:
    mup deploy
ubuntu@xxxx/.deploy$ mup deploy --verbose --settings settings.json
Building App Bundle Locally

Started TaskList: Pushing Meteor App
[xxxx] - Pushing Meteor App Bundle                                                                              to the Server
[xxxx] - Pushing Meteor App Bundle                                                                              to the Server: SUCCESS
[xxxx] - Prepare Bundle
base: Pulling from abernix/meteord
...
Digest: sha256:5138e4ba3c55cc6fabe0ba859f984e9725599a9f53ed5d759dd4f350770a62b2
Status: Downloaded newer image for abernix/meteord:base
Finished Extracting
Creating Dockerfile
Finished creating Dockerfile
Building image
Sending build context to Docker daemon  67.59MB
Step 1/7 : FROM abernix/meteord:base
# Executing 1 build trigger
 ---> Running in cf74d5b4fa68
Removing intermediate container cf74d5b4fa68
 ---> 1f37c25d0989
Step 2/7 : RUN mkdir /built_app || true
 ---> Running in 1aee7bfde84f
Removing intermediate container 1aee7bfde84f
 ---> f82f6ad23a8a
Step 3/7 : ENV ROOT_URL=xxxx
 ---> Running in f26ac397298a
Removing intermediate container f26ac397298a
 ---> c2eb2e8861f7
Step 4/7 : ENV MONGO_URL=mongodb://mongodb:27017/xxxx
 ---> Running in be1f89f57b08
Removing intermediate container be1f89f57b08
 ---> 877e22ea42db
Step 5/7 : ENV MONGO_OPLOG_URL=mongodb://mongodb/local
 ---> Running in 7801b4f3be1e
Removing intermediate container 7801b4f3be1e
 ---> 657785f145b4
Step 6/7 : COPY ./ /built_app
 ---> 3043416670e1
Step 7/7 : RUN cd  /built_app/programs/server &&     npm install --unsafe-perm
 ---> Running in d2ae3b014734
...
Removing intermediate container d2ae3b014734
 ---> df4a55163cc2
Successfully built df4a55163cc2
Successfully tagged mup-xxxx:build
Error response from daemon: No such image: mup-xxxx:latest
Total reclaimed space: 0B
[xxxx] - Prepare Bundle: SUCCESS

Started TaskList: Configuring App
[xxxx] - Pushing the Startup Script
[xxxx] - Pushing the Startup Script                                                                             : SUCCESS
[xxxx] - Sending Environment Variab                                                                             les
[xxxx] - Sending Environment Variab                                                                             les: SUCCESS

Started TaskList: Start Meteor
[xxxx] - Start Meteor
using image
Error: No such image: mup-xxxx:previous
Image mup-xxxx:latest
Volume
Removing docker containers. Errors about nonexistent endpoints and containers ar                                                                             e normal.
Error: No such container: xxxx
Error response from daemon: endpoint xxxx not found
Error: No such container: xxxx-frontend
Error response from daemon: endpoint xxxx-frontend not found
Error: No such container: xxxx-nginx-letsencrypt
Error response from daemon: endpoint xxxx-nginx-letsencrypt not found
Error: No such container: xxxx-nginx-proxy
Error response from daemon: endpoint xxxx-nginx-proxy not found
Finished removing docker containers
0e23b10725796947401ab151a78b2349f32a3779249f3847d20f1b82d2c251a4
Ran abernix/meteord:base
[xxxx] - Start Meteor: SUCCESS
[xxxx] - Verifying Deployment
Container has no IP Address, likely from the app crashing.
Container has no IP Address, likely from the app crashing.
=> Container status:
Container spent too much time restarting.
restarted: 8 times {"Bridge":"","SandboxID":"d97cbb37a87106a3bdeaa51022acabd5e13                                                                             66a52317d11fcd75a3593730349bd","HairpinMode":false,"LinkLocalIPv6Address":"","Li                                                                             nkLocalIPv6PrefixLen":0,"Ports":{},"SandboxKey":"/var/run/docker/netns/d97cbb37a                                                                             871","SecondaryIPAddresses":null,"SecondaryIPv6Addresses":null,"EndpointID":"","                                                                             Gateway":"","GlobalIPv6Address":"","GlobalIPv6PrefixLen":0,"IPAddress":"","IPPre                                                                             fixLen":0,"IPv6Gateway":"","MacAddress":"","Networks":{"bridge":{"IPAMConfig":nu                                                                             ll,"Links":null,"Aliases":null,"NetworkID":"081a5c91dc08e96e9a6efc23130e8e602951                                                                             1153751498da778dac3c9a8beb9d","EndpointID":"","Gateway":"","IPAddress":"","IPPre                                                                             fixLen":0,"IPv6Gateway":"","GlobalIPv6Address":"","GlobalIPv6PrefixLen":0,"MacAd                                                                             dress":"","DriverOpts":null}}} {"Status":"restarting","Running":true,"Paused":fa                                                                             lse,"Restarting":true,"OOMKilled":false,"Dead":false,"Pid":0,"ExitCode":1,"Error                                                                             ":"","StartedAt":"2018-08-20T20:08:58.615954182Z","FinishedAt":"2018-08-20T20:08                                                                             :58.900441472Z"}
=> Logs:
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/built_app/main.js:4:1)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
=> Starting meteor app on port:80
/built_app/programs/server/boot.js:49
    const { pause } = require("./debug.js");
          ^

SyntaxError: Unexpected token {
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:373:25)
    at Object.Module._extensions..js (module.js:416:10)
    at Module.load (module.js:343:32)
    at Function.Module._load (module.js:300:12)
    at Module.require (module.js:353:17)
    at require (internal/module.js:12:17)
    at Object.<anonymous> (/built_app/main.js:4:1)
    at Module._compile (module.js:409:26)
    at Object.Module._extensions..js (module.js:416:10)
=> Starting meteor app on port:80
/built_app/programs/server/boot.js:49
    const { pause } = require("./debug.js");
          ^
Module._extensions..js (module.js:416:10)

To see more logs type 'mup logs --tail=200'

[xxxx] x Verifying Deployment: FAIL                                                                             ED

              ------------------------------------STDERR------------------------                                                                             ------------
              Container spent too much time restarting.
            at require (internal/module.js:12:17)
            at Object.<anonymous> (/built_app/main.js:4:1)
            at Module._compile (module.js:409:26)
            at Object.Module._extensions..js (module.js:416:10)
        => Starting meteor app on port:80
        /built_app/programs/server/boot.js:49
            const { pause } = require("./debug.js");
                  ^

        SyntaxError: Unexpected token {
            at exports.runInThisContext (vm.js:53:16)
            at Module._compile (module.js:373:25)
            at Object.Module._extensions..js (module.js:416:10)
            at Module.load (module.js:343:32)
            at Function.Module._load (module.js:300:12)
            at Module.require (module.js:353:17)
            at require (internal/module.js:12:17)
            at Object.<anonymous> (/built_app/main.js:4:1)
            at Module._compile (module.js:409:26)
            at Object.Module._extensions..js (module.js:416:10)
        => Starting meteor app on port:80
        /built_app/programs/server/boot.js:49
            const { pause } = require("./debug.js");
                  ^

        SyntaxError: Unexpected token {
            at exports.runInThisContext (vm.js:53:16)
            at Module._compile (module.js:373:25)
            at Object.Module._extensions..js (module.js:416:10)
            at Module.load (module.js:343:32)
            at Function.Module._load (module.js:300:12)
            at Module.require (module.js:353:17)
            at require (internal/module.js:12:17)
            at Object.<anonymous> (/built_app/main.js:4:1)
            at Module._compile (module.js:409:26)
            at Object.Module._extensions..js (module.js:416:10)
        => Starting meteor app on port:80
        /built_app/programs/server/boot.js:49
            const { pause } = require("./debug.js");
                  ^

        SyntaxError: Unexpected token {
            at exports.runInThisContext (vm.js:53:16)
            at Module._compile (module.js:373:25)
            at Object.Module._extensions..js (module.js:416:10)
            at Module.load (module.js:343:32)
            at Function.Module._load (module.js:300:12)
            at Module.require (module.js:353:17)
            at require (internal/module.js:12:17)
            at Object.<anonymous> (/built_app/main.js:4:1)
            at Module._compile (module.js:409:26)
            at Object.Module._extensions..js (module.js:416:10)
        => Starting meteor app on port:80
        /built_app/programs/server/boot.js:49
            const { pause } = require("./debug.js");
                  ^

              ------------------------------------STDOUT------------------------                                                                             ------------
              Container has no IP Address, likely from the app crashing.
        Container has no IP Address, likely from the app crashing.
        Container has no IP Address, likely from the app crashing.
        Container has no IP Address, likely from the app crashing.
        => Container status:
        restarted: 8 times {"Bridge":"","SandboxID":"d97cbb37a87106a3bdeaa51022a                                                                             cabd5e1366a52317d11fcd75a3593730349bd","HairpinMode":false,"LinkLocalIPv6Address                                                                             ":"","LinkLocalIPv6PrefixLen":0,"Ports":{},"SandboxKey":"/var/run/docker/netns/d                                                                             97cbb37a871","SecondaryIPAddresses":null,"SecondaryIPv6Addresses":null,"Endpoint                                                                             ID":"","Gateway":"","GlobalIPv6Address":"","GlobalIPv6PrefixLen":0,"IPAddress":"                                                                             ","IPPrefixLen":0,"IPv6Gateway":"","MacAddress":"","Networks":{"bridge":{"IPAMCo                                                                             nfig":null,"Links":null,"Aliases":null,"NetworkID":"081a5c91dc08e96e9a6efc23130e                                                                             8e6029511153751498da778dac3c9a8beb9d","EndpointID":"","Gateway":"","IPAddress":"                                                                             ","IPPrefixLen":0,"IPv6Gateway":"","GlobalIPv6Address":"","GlobalIPv6PrefixLen":                                                                             0,"MacAddress":"","DriverOpts":null}}} {"Status":"restarting","Running":true,"Pa                                                                             used":false,"Restarting":true,"OOMKilled":false,"Dead":false,"Pid":0,"ExitCode":                                                                             1,"Error":"","StartedAt":"2018-08-20T20:08:58.615954182Z","FinishedAt":"2018-08-                                                                             20T20:08:58.900441472Z"}
        => Logs:

        To see more logs type 'mup logs --tail=200'

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


text:
Q: How to remove/hide title bar in Windows 10? This was possible in XP and Windows 7 (see Is it possible to remove/hide Windows title bars?) - but I haven't been able to find the settings in Windows 10.  Is this still possible?  Thanks.

A: Given that the answer provided in the linked question still had issues (didn't work in Vista - follow up suggestion reduced taskbar icons), I don't believe there's much hope for a suitable function within Win 10.
However, the comment provided by Mokubai suggesting to use Autohotkey may still be applicable here.
The following code in AHK will remove the Title Bar for the active window.
WinSet, Style, -0xC00000, A

A: mostly by pressing F11 will work for most of the stuff i guess ( for example it works with windows explorer, chrome, etc) and if not then try Alt + Enter, anyway there will be some stubborn software who no matter what you do won't allow us to hide the title bar. Enjoy

A: Note that this also corresponds to Tablet mode vs. Desktop mode (Windows 10). I've discovered that in Tablet mode, it auto-hides the title bar unless you put your mouse at the top.
As for me personally, I find this extremely obnoxious, even if I'm using the touch screen, so I put it in Desktop mode.
To switch, click the icon at the bottom right of Windows 10 (where you set e.g. brightness, airplane mode, network settings, etc.). By default, you may have Tablet mode as one of your primary options; if not, click on Expand. (https://dottech.org/174526/how-to-switch-between-tablet-and-desktop-mode-in-windows-10-tip/)
To switch the default mode when you log in, go to the Windows 10 Settings app, click System => Tablet mode. It's straightforward from there.

A: Hey sorry to dig up kind of an old topic, but did anyone find a solution to this? I have my laptop plugged into my TV acting as a second monitor, and I have a Windows app which I'd like to take up the entire screen on the TV. Maximizing and F11 etc etc do not work.
The easy solution is tablet mode, but that doesn't allow for more than 1 display. I tried the AHK command listed above, and it worked on most windows but not this one. Not the end of the world if there's no solution since I can hide taskbar and the title bar is just black for this window, but I'd still like the entire screen if possible.

A: there is some tips:
Step 1 : Login to your Windows 10 PC(Which is Primitive Step)
Step 2 : Open File Explorer or Press Windows + E or Open This PC
[See : How to Create Shortcut for My computer(This PC) in Windows 10]
Step 3 : Click on File tab,Which is on top of the tab.
Step 4 : Select Change Folder and Search Options / Options.
Step 5 : Select View tab.
Step 6 : Click on File and Folders.
Step 7 : Find the Option, Display the Full Path in title Bar.

redpajama_set_name: RedPajamaStackExchange


text:
Q: trying to insert integer into byte array I have an array of bytes
app0 := []byte("\xff\xe0\x00\x10\x4a\x46\x49\x46\x00\x01\x01\x01\x00\x00\x00\x00\x00\x00")

I am trying to figure out how to replace app0[13:15] with two bytes containing 300.
Please help. I tried the following but it won't even compile:
app0[13:15] = []byte(300)

A: I'm a little confused what you are even trying to do with
app0[13:15] = []byte(300)

A single byte can't hold the value 300, and you have a slice of bytes.  I'll assume you want the value 300 converted into two bytes:
import (
    "fmt"
    "bytes"
    "encoding/binary"
)

func main() {
    app0 := []byte("\xff\xe0\x00\x10\x4a\x46\x49\x46\x00\x01\x01\x01\x00\x00\x00\x00\x00\x00")
    app0 =  append(app0[:13], append(intToBytes(uint16(300)), app0[15:]...)...)
    fmt.Println(app0)
}

func intToBytes(i uint16) []byte {
    buf := new(bytes.Buffer)
    _ = binary.Write(buf, binary.LittleEndian, i)
    return buf.Bytes()
}

https://play.golang.org/p/qADHwCCFQG
The trick here is you have to actually get an array of bytes, and then you can use the variadic operator (...) and then append function to replace the inner elements of the array.

A: For example,
package main

import "fmt"

func main() {
    app0 := []byte("\xff\xe0\x00\x10\x4a\x46\x49\x46\x00\x01\x01\x01\x00\x00\x00\x00\x00\x00")
    fmt.Println(app0)
    app0[13], app0[14] = 300>>8, 300&0xFF
    fmt.Println(app0)
}

Output:
[255 224 0 16 74 70 73 70 0 1 1 1 0 0 0 0 0 0]
[255 224 0 16 74 70 73 70 0 1 1 1 0 1 44 0 0 0]


text:
Q: Android, move data between services I have this problem, I'm creating an application which runs in background as a service. I've managed to make it persistent and run on boot, which I needed. Right now I have that situation:
In this service I start a thread -> In this thread I would like to start an Intent Service to gather data from GPS (location). This seems easy.
The problem I have is to return the location gathered via Intent Service to this thread.
I found many questions regarding passing data between an activity and a service, but none about services and threads.
I could of course nest my Intent Service inside my main service and change services' variable from Intent Service, checking if it has been changed within a loop. But it seems very inefficient - I would rather do it other way.
Therefore I'd like to ask about how to achieve it?
Thanks in advance

A:
In this service I start a thread -> In this thread I would like to start an Intent Service to gather data from GPS (location). This seems easy.

Not really.

The problem I have is to return the location gathered via Intent Service to this thread.

Then you are doing it wrong.
An IntentService is singularly useless for obtaining a location fix. Either the location fix is available immediately (in which case, the IntentService was unnecessary), or the location fix will only become available at some arbitrary time in the future (in which case, IntentService will have shut down long ago, preventing you from getting the fix reliably in the first place).
If you are using LocationClient from the Play Services SDK, just get the location from your thread in your main service.
If you are using LocationManager (e.g., you insist that you must use GPS, rather than the "fused location provider" employed by LocationClient), you will need to rewrite your app to avoid the blocking-until-the-location-is-available logic. Instead, use event-driven programming, using requestLocationUpdates() and processing those locations as they arrive. You can use the variant of requestLocationUpdates() that takes a Looper, tied to a HandlerThread that you create, to be able to process those fixes in a background thread.


text:
Q: PendingIntents in Notifications I would like to show a notification that displays the progress of an
ongoing operation. That works well for me.
But at the same time the remote view should contain cancel button to stop the ongoing operation. The usual content intent should still do something else, i.e. not cancel the ongoing operation. It seems though that I can only have one intent.
I have to specify a contentIntent that is launched when clicking on
the notification: If I don't specify that I get something along those
lines:
E/ActivityManager(   62): Activity Manager Crash
E/ActivityManager(   62): java.lang.IllegalArgumentException: contentIntent required ...

For the "cancel" button I set another intent:
Intent cancelSyncIntent = new Intent("com.xyz.CANCEL_SYNC");
contentView.setOnClickPendingIntent(R.id.cancel_sync,
                                    PendingIntent.getBroadcast(context, 0,
                                    cancelSyncIntent, 0));

But this never works. I always get the content intent when the button
is clicked. It looks like I cannot use buttons in remote views of
notifications?!
I could probably display a text: "<< Press to cancel operation >>", but that seems rather heavy handed.
Update: Afer J.'s recommendations:
    final Notification n = new Notification(R.drawable.gen_auto_notification_icon, context.getResources()
            .getString(
                    fastSyncOnly ? R.string.fast_synchronization_running_notification_title
                            : R.string.synchronization_running_notification_title), new Date().getTime());

    n.flags = Notification.FLAG_ONGOING_EVENT;

    final RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.in_progress_notification);
    n.contentView = contentView;

    // Intent cancelSyncIntent = new Intent("com.newsrob.CANCEL_SYNC");
    Intent cancelSyncIntent = new Intent();
    cancelSyncIntent.setClass(context, FireReceiver.class);
    PendingIntent pendingCancelSyncIntent = PendingIntent.getActivity(context, 0, cancelSyncIntent, 0);
    contentView.setOnClickPendingIntent(R.id.cancel_sync, pendingCancelSyncIntent);

    Intent showDashboardIntent = new Intent(context, DashboardListActivity.class);
    PendingIntent showDashboardPendingIntent = PendingIntent.getActivity(context, 0, showDashboardIntent, 0);
    n.contentIntent = showDashboardPendingIntent;

A: Short answer: You cannot have clickable child views in a notification view.
Longer answer...
I spent a day trying to get this to work as well and eventually gave up and looked at the Android source.  It looks like everything happens in makeNotificationView() within StatusBarService.java.  In there, the code inflates a layout named "status_bar_latest_event" for each row in the notification pull down shade.  It grabs a ViewGroup from that view it just inflated named "content", calls setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS) on it, and then adds your notification view as a child of that.  So, assuming I understand how FOCUS_BLOCK_DESCENDANTS works, it appears there is no hope of your view or any of its children getting focus or click events.
I also followed the logic of how the main PendingEvent that you associate with your Notification works.  The same ViewGroup that hosts your Notification view gets a setOnClickListener() call on it to register a listener class named "Launcher".  When that class gets an onClick() event, it simply calls the send() method on the PendingIntent you associated with the Notification.  I was hoping maybe the coordinate of the click might get passed along so I could at least attempt to compute which button was clicked on, but no such luck.
Anyway, if anyone knows of a way to work around this, I'd love to hear it.  For now, I'm just pulling my buttons out and moving on.

A: Intent cancelSyncIntent = new Intent();
        cancelSyncIntent .setClassName("com.xyz","com.xyz.CANCEL_SYNC");
PendingIntent pendingIntent = PendingIntent.getActivity(context,
    0 /* no requestCode */, cancelSyncIntent , 0 /* no flags */);
contentView.setOnClickPendingIntent(R.id.cancel_sync, pendingIntent);


text:
Q: What is the best way to access XML objects stored as object-relational in Oracle? Firstly, I am using Oracle 12 version 1
I need to retrieve objects stored as object-relational in Oracle Data Base but it is too slow - I am using Dom Documents for doing so.
The function I am using:
create or replace FUNCTION XML_myDistance(
  innXML XMLType,
  outXML XMLType
) RETURN number
IS
  total NUMBER := 0;
  docInn xmldom.DOMDocument;
  docOut xmldom.DOMDocument;
  nInn xmldom.DOMNode;
  nOut xmldom.DOMNode;
  nlInn xmldom.DOMNodeList;
  nlOut xmldom.DOMNodeList;
  len number;
BEGIN
--Converte os atributos xmltype para DOMDocuments.
docInn := dbms_xmldom.newDOMDocument(innXML);
docOut := dbms_xmldom.newDOMDocument(outXML);

nlInn := xmldom.getElementsByTagName(docInn, '*');
nlOut := xmldom.getElementsByTagName(docOut, '*');
len := xmldom.getLength(nlInn);

for i in 1..len-1 loop
        nInn := xmldom.item(nlInn, i);
        nOut := xmldom.item(nlOut, i);
        total := total + ABS(xmldom.getNodeValue(DBMS_XMLDOM.getFirstChild(nInn)) - xmldom.getNodeValue(DBMS_XMLDOM.getFirstChild(nOut)));
end loop;

DBMS_XMLDOM.freeDocument(docInn);
DBMS_XMLDOM.freeDocument(docOut);

RETURN total;
END;
/

I have tried through the following query too... but its performance is even worse...
create or replace FUNCTION myDistance(
  innXML XMLType,
  outXML XMLType
) RETURN number
IS
  total NUMBER;
BEGIN
  SELECT SUM( ABS(oFV.feature - iFV.feature) )
  INTO   total
  FROM   XMLTABLE(
           '//FeatureVector/feature'
           PASSING outXML
           COLUMNS rn       FOR ORDINALITY,
                   feature  NUMBER  PATH '.'
         ) oFV
         INNER JOIN
         XMLTABLE(
           '//FeatureVector/feature'
           PASSING innXML
           COLUMNS rn       FOR ORDINALITY,
                   feature  NUMBER  PATH '.'
         ) ifv
         ON ( oFV.rn = iFV.rn );

  RETURN total;
END;
/

Is there another way to access XML data stored as object-relational objects in Oracle? A more efficient one.


text:
Q: How can I find the voltage rating for a particular ceramic capacitor? I have an old tube radio. There is a ceramic cap with:"RMC / 0.1 / 1400V / Z5U " written from top to bottom, respectively. Now, this cap has broken at it's base and can't be resoldered and so must be replaced. I have another ceramic disk cap, almost the same radius (across the flat aspect) with: " RMC / 0.5 / 20% +- / Z5U " written on it in the same fashion.
I'm wondering what the voltage rating of this possible replacement cap is and whether or not it would make a suitable replacement for the whacked one.
I've been looking ALL OVER the Net for info on ceramics and their voltage ratings when not shown on the cap. I found nothing so any help would be appreciated. I read something that I find highly suspicious so I won't poison the mental pool here with that particular suggestion but I am quite interested in what the EE community has to say.

A: My hunch is that the part is 100nF, and your replacement is 500nF.
I wouldn't risk using a cap without a voltage rating indication on it. Also, you're better off replacing that Z5U dielectric with one that's more temperature stable, like NP0.
I'd source a 100nF, 2kV NP0 capacitor as a replacement.

A: Your cap isn't a good match being 5x the capacitance. I presume this is a snubber across the output transformer, that's generally the only place they'd have such a high voltage. Although they tend to be on the order of 1 - 10nF, not 100...
Since it's Z5U dielectric, I assume it's newer than the radio and not original. Find the schematic and see what part should actually be there. The value could be wrong, or the voltage could be much more than needed, if the person used whatever was handy. At least tell us where in the circuit it is, we should be able to make an educated guess as to what the value should be.
NP0 isn't necessary unless it is in a critical circuit, but Z5U is pretty junk. X7R is much better at not much more cost. (xxU and xxV caps lose something like 80% of their capacitance when running near rated voltage! The things should be illegal to rate at 0V)
edit: if it's an american power transformer-less style, an 'AA5', it might be the cap from the line to chassis to reduce noise. It would generally be 50nF or less though, there. I suppose you should use an X or Y rated cap there to meet modern safety, and read about the danger of hot chassis radios before you get zapped!


text:
Q: Aggregate rows in MySQL ignoring NULL values into a single row Given a table
id  date        job    color  qty
1   2018-12-10  12345  green  1
2   2018-12-11  12345
3   2018-12-15  12345
4   2018-12-21  12345  red
5   2018-12-21  12345         4
6   2018-12-22  12345

The id column is auto incrementing and is the tables primary key.
A simple query
SELECT * FROM `table` WHERE `job` = '12345' ORDER BY `id` ASC;

Would return all records for the job 12345 in the order they were inserted.
Question:
How would I query the table to only return a single row with the most recent values from each column?
The desired row would look like this
6   2018-12-22  12345  red    4

A: One way is using Group_Concat() with Substring_Index() to extract the latest non-null value. GROUP_CONCAT() would ignore the null values.
SELECT
  MAX(id) AS id,
  MAX(date) AS date,
  MAX(job) AS job,
  SUBSTRING_INDEX(GROUP_CONCAT(color ORDER BY id DESC), ',', 1) AS color,
  SUBSTRING_INDEX(GROUP_CONCAT(qty ORDER BY id DESC), ',', 1) AS qty
FROM `table`
WHERE `job` = '12345';

One assumption in the above query is that the maximum value of date corresponds to maximum id value.
Also, since we are only concerned with the "latest" value (fetching only one value); we will not be limited by the group_concat_max_len variable.

A: You may use a separate subquery to find the max value in each separate column:
SELECT
    (SELECT MAX(id) FROM yourTable) AS id,
    (SELECT MAX(date) FROM yourTable) AS date,
    (SELECT MAX(job) FROM yourTable) AS job,
    (SELECT MAX(color) FROM yourTable) AS color,
    (SELECT MAX(qty) FROM yourTable) AS qty;

Demo
I have no idea why you want to do this, and it might indicate bad database design/planning on your part.

A: Use LIMIT in your query as
SELECT * FROM `table` WHERE `job` = '12345' ORDER BY `id` DESC LIMIT 1;

A: You could use subqueries to get desired result:
select max(id) id,
       job,
       max(`date`) `date`,
      (select qty from tbl
      where qty is not null
       and tbl.job = job
      order by `date` desc
      limit 1) qty,
      (select color from tbl
      where color is not null
        and tbl.job = job
      order by `date` desc
      limit 1) color
from tbl
group by job


text:
Q: I Don't want to show some tables and some column in mysql while generating my record Since I have given to administrator to created the form dynamically.when he created form,What I have done is I have created the table for the form dynamically.Every thing is working fine.Now I want to show  table and column for report generation.In that I don't want to show (userlogin,place,venue) table for report generation and three columns (user_id,user_common_id,ayear) these three column are common for all the table which I created dynamically . I have given my code what I have done so far.
Guide me How to write the mysql query for this.
<?php
    $mysqli = new mysqli("localhost", "root", "", "event");
    $result = $mysqli->query("SHOW TABLES");
    while ( $row = $result->fetch_row() )
    {
    $table = $row[0];
    echo '
',$table,'
';
    $result1 = $mysqli->query("SELECT * FROM $table where ayear='1'");
    if($result1)
    {
    echo '
';
    $column = $mysqli->query("SHOW COLUMNS FROM $table");
    echo '
';
    while($row3 = $column->fetch_row() )
    {
    echo ''.$row3[0].'	';
    }
    echo '
';
    while($row2 = $result1->fetch_row() )
    {
    echo '
';
    foreach($row2 as $key=>$value) {
    echo '',$value,'	';
    }
    echo '
';
    }
    echo '

';
    }
    }
    $mysqli->close();
    ?>

When admin created the forms, here is code for dynamic table and columns.for better projection
$query1="create table ".$porg."(id INT NOT NULL AUTO_INCREMENT,".$VALUES.",user_id int(11),user_common_id int(11),ayear varchar(30),PRIMARY KEY (id)) ENGINE = INNODB";
      $result=mysql_query($query1);

A: Put the tables and columns you want to skip in arrays, then use in_array() to test the name before showing it.
Use fetch_assoc rather than fetch_row so you get the column names in the array keys.
<?php
    $skip_tables = array('userlogin', 'place', 'venue');
    $skip_columns = array('user_id', 'user_common_id', 'ayear');
    $mysqli = new mysqli("localhost", "root", "", "event");
    $result = $mysqli->query("SHOW TABLES");
    while ( $row = $result->fetch_row() )
    {
      $table = $row[0];
      if (in_array($table, $skip_tables)) {
        continue;
      }
      echo '
',$table,'
';
      $result1 = $mysqli->query("SELECT * FROM $table where ayear='1'");
      if($result1)
      {
        echo '
';
        $column = $mysqli->query("SHOW COLUMNS FROM $table");
        echo '
';
        while($row3 = $column->fetch_row() )
        {
          if (!in_array($row3[0], $skip_columns)) {
            echo ''.$row3[0].'	';
          }
        }
        echo '
';
        while($row2 = $result1->fetch_assoc() )
        {
          echo '
';
          foreach($row2 as $key=>$value) {
            if (!in_array($key, $skip_columns)) {
              echo '',$value,'	';
            }
          }
          echo '
';
        }
        echo '

';
      }
    }
    $mysqli->close();
    ?>


text:
Q: How could I list all virtual machines under Virtual Box? How can I list all VirtualBox virtual machines, including those created by other users?
By default, the VBoxManage list vms command lists the VMs owned by the current user. But what if there are many VMs, created by different users? I would like to run a VM created by another user, but cannot find any, even though I know it exists somewhere.

A: VirtualBox stores its data in your user profile directory - there's no "global virtualbox database" for the machine. You would have to get access to the virtualbox directory under the other user's profile.


text:
Q: Angular --prod flag break up component style sheets I'm have simple component which is used to show if data are rendered ASC or DESC. That simple component have some logic inside but for this case more important, it have it's own styleUrls. Unfortunately with --prod flag that styles are not build correctly.
My component looks like this:
@Component({
    selector: 'sort-header, [sort-header]',
    templateUrl: 'sort-header.component.html',
    styleUrls: ['./sort-header.component.scss'],
})
export class SortHeaderComponent implements OnInit {/* Component BODY */}

if we look at styles it's very simple:
.sort-header-container {
    & a {
        display: inline-block;
        position: relative;
        text-decoration: none;
        &:after {
            position: absolute;
            top: 2px;
            right: -19px;
            font-style: normal;
            font-weight: normal;
            font-family: monster;
            line-height: 1;
            padding: 0 4px;
            speak: none;
            -webkit-font-smoothing:antialiased;
        }
        &.sort-asc:after {
            content: '\E0AA';
        }
        &.sort-desc:after {
            content: '\E0A8';
        }
    }
}

Results of commands:
If I run command:
ng build recommender-portal --prod --aot --output-hashing=none --vendor-chunk --sourceMap=true

icon it should show is broken and if I inspect HTML / CSS on page content looks like this:

If I run exact same command without --prod:
ng build recommender-portal --aot --output-hashing=none --vendor-chunk --sourceMap=true

icon is not broken and if I inspect HTML / CSS on page it looks like this:

Conclusion
Few things that come in my mind of possible root cause:

*

*I upgraded Angular to 8 recently which may break something

*sort-header.component.scss is not mentioned in angular.json but I believe it only belong to component as I don't want it to be in main styles

However I didn't manage to find anything yet, maybe I just missed something obvious just because of looking wrong way so I will be happy for any advise or additional questions which can point me the right way.


text:
Q: How to make sprockets (or rack, or nginx?) motivate browsers to cache fonts and correctly return 304? In a Rails6 app with webpacker replaced by sprockets, I do not manage to let sprockets make my browser cache fonts. Edit: my browser does cache the font, but google complains and curl shows how the App responds (not as expected with a 304, see below).
Update
It seems that a 304 is only returned when you tell the server (via If-Modified-Since-headers) that you know exactly the last modified version. While I Mozillas Dev Resources do not state that this should clearly be the case (and I am not in RFC-reading mood), it might make sens:

*

*your server serves the asset on 2020-01-01 (appreviated date for simplicity)

*a browser visits you and stores the asset alongside its date

*next day same browser revisits, asks server for asset and tells it the last known date (2020-01-01 via If-Modified-Since-header)

*

*server answes 304: You know that stuff already

*next day a mistake happens and a dev-asset is served by the server

*browser revisits, gets new (but wrong asset with Last modified date of 2020-01-03) and stores it alongside that date

*server admins remove the wrong dev asset

*next day, browser visits and tells server "I know the thing from yesterday"

*

*server tells browser: no, forgot that, the correct payload is this, and this is the timestamp: 2020-01-01.

In my tests below, I used If-Modified-Since headers that did not correspond to the last (production) asset Timestamp. Thanks @bliof for help figuring that out.
As my ultimate goal was to make googles speed insight happy (now that I know that this 304- response works if all players behave well) I will follow Rails 5+ path of config.public_file_server.headers (https://blog.bigbinary.com/2015/10/31/rails-5-allows-setting-custom-http-headers-for-assets.html). The Rails guides also point out how you would usually let your webserver (or CDN) handle the situation (https://guides.rubyonrails.org/asset_pipeline.html#in-production), but my stack works somewhat different.
Original follows
The fonts are in e.g. app/assets/fonts/OTF/SourceSansPro-BoldIt.otf and correctly put in public/assets/OTF/...fingerprint... (accompanied by a .gz variant). They are referenced via a SCSS font-face rule, pointing to a file with the respective fingerprint in it (using font-url()).
When curling these, I seem to never get a HTTP/1.1 304 Not Modified, but a 200 with the given payload. With the other (JS, CSS) assets it works as expected.
I did not modify config/initializers/assets.rb, as all the subdirectories and files should already be picked up (and the assets:precompile output and content of public/assets shows that it works).
Digging into the sprockets code at https://github.com/rails/sprockets/blob/9909da64595ddcfa1e7ee40ed1d99738961288ec/lib/sprockets/server.rb#L73 seems to indicate that maybe an etag is not set correctly or something like that, but I do not really grock that code.
The application is deployed with dokku (basically a heroku) with a pretty standard nginx-configuration as far as I can tell: https://github.com/dokku/dokku/blob/master/plugins/nginx-vhosts/templates/nginx.conf.sigil . The app serves the assets itself (like in heroku).
What do I have to do such that sprockets adds the relevant headers / responds "correctly" with a 304? Any ideas how to debug that issue?
The relevant "debugging" parts
The initial request for CSS
curl -v https://...application-3d...c76c3.css \
  -H 'Accept: text/css,*/*;q=0.1'\
  -H 'Accept-Language: en-US,en;q=0.5'\
  --compressed # omitted: ... User-Agent, DNT, ...
# omitted: TLS handshake etc
> GET /assets/application-3d...c76c3.css HTTP/1.1
> Host: #the host
> Accept-Encoding: deflate, gzip
> User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:75.0) Gecko/20100101 Firefox/75.0
> Accept: text/css,*/*;q=0.1
> Accept-Language: en-US,en;q=0.5
> Referer: #the host
> DNT: 1
> Connection: keep-alive
> Cookie: #a cookie
>
< HTTP/1.1 200 OK
< Server: nginx
< Date: Tue, 21 Apr 2020 15:39:47 GMT
< Content-Type: text/css
< Content-Length: 41256
< Connection: keep-alive
< Last-Modified: Mon, 06 Apr 2020 11:59:56 GMT
< Content-Encoding: gzip
< Vary: Accept-Encoding
<
# payload

Subsequent fetch of CSS
(The relevant parts, other params and output omitted).
Note that a If-Modified-Since: Mon, 06 Apr 2020 11:59:56 GMT header is sent along.
curl -v 'https://.../assets/application-3d...c76c3.css' \
  -H 'If-Modified-Since: Mon, 06 Apr 2020 11:59:56 GMT'\
  -H 'Cache-Control: max-age=0'
> If-Modified-Since: Mon, 06 Apr 2020 11:59:56 GMT
> Cache-Control: max-age=0
>
< HTTP/1.1 304 Not Modified
< Server: nginx
< Date: Tue, 21 Apr 2020 15:50:52 GMT
< Connection: keep-alive

(Thats what I want: A 304 Not Modified.
The initial request for the font asset
curl -v 'https://.../assets/WOFF2/TTF/SourceSansPro-Light.ttf-32...d9.woff2' \
  -H 'Accept: application/font-woff2;q=1.0,application/font-woff;q=0.9,*/*;q=0.8'\
  -H 'Accept-Language: en-US,en;q=0.5'\
  --compressed \
  -H 'Referer: https://...assets/application-3d....c76c3.css'
  # ommitted: User Agent, Cookies, ....
> GET /assets/WOFF2/TTF/SourceSansPro-Light.ttf-32...d9.woff2 HTTP/1.1
> Host: #the host
> Accept-Encoding: deflate, gzip
> User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:75.0) Gecko/20100101 Firefox/75.0
> Accept: application/font-woff2;q=1.0,application/font-woff;q=0.9,*/*;q=0.8
> Accept-Language: en-US,en;q=0.5
> DNT: 1
> Connection: keep-alive
> Referer: https://.../assets/application-3d...c76c3.css
# cookie etc
>
< HTTP/1.1 200 OK
< Server: nginx
< Date: Tue, 21 Apr 2020 15:45:34 GMT
< Content-Type: application/font-woff2
< Content-Length: 88732
< Connection: keep-alive
< Last-Modified: Wed, 25 Mar 2020 20:09:14 GMT
<
# payload

Subsequent fetch of Font
curl -v 'https://.../assets/WOFF2/TTF/SourceSansPro-Light.ttf-32...ed9.woff2' \
  -H 'Referer: https://.../assets/application-3d...c76c3.css'\
  -H 'If-Modified-Since: Mon, 06 Apr 2020 11:59:56 GMT'
  -H 'Cache-Control: max-age=0'
# ....
> If-Modified-Since: Mon, 06 Apr 2020 11:59:56 GMT
> Cache-Control: max-age=0
>
< HTTP/1.1 200 OK
< Server: nginx
< Date: Tue, 21 Apr 2020 15:53:46 GMT
< Content-Type: application/font-woff2
< Content-Length: 88732
< Connection: keep-alive
< Last-Modified: Wed, 25 Mar 2020 20:09:14 GMT
# payload

What I find interesting, that the server actually sends a Last-Modified which is way before the If-Modified-Since. I guess clever browsers stop the conversation there, but I really want to see a well-behaved 304.

A: Here are few notes/findings:

It seems that it returns 304 when you match the timestamp.
In your example if you do the curl to the font with
-H 'If-Modified-Since: Wed, 25 Mar 2020 20:09:14 GMT'

You'll get the HTTP/1.1 304 Not Modified
Same thing for the .css if you don't exactly match the date, you'll get 200.

I've tried changing sprockets locally to add some puts calls and also to change the default log level of sprockets itself but nothing happens.
TBO I don't believe the Sprokets::Server#call is getting called.

I've tried with puma and with thin, both return 304 only when the dates match.

curl --compressed -H 'Cache-Control: max-age=0' -H 'If-Modified-Since: Thu, 23 Apr 2020 21:34:30 GMT' -v http://localhost:3000/assets/OTF/SpaceMeatball-d61519ff17fadd38b57e3698067894c0e75fcb6031ee91034f5f7d6f2daa4d4b.otf

> Cache-Control: max-age=0
> If-Modified-Since: Thu, 23 Apr 2020 21:34:30 GMT
>
< HTTP/1.1 200 OK
< Last-Modified: Thu, 23 Apr 2020 21:34:29 GMT

curl --compressed -H 'Cache-Control: max-age=0' -H 'If-Modified-Since: Thu, 23 Apr 2020 21:34:29 GMT' -v http://localhost:3000/assets/OTF/SpaceMeatball-d61519ff17fadd38b57e3698067894c0e75fcb6031ee91034f5f7d6f2daa4d4b.otf

> Cache-Control: max-age=0
> If-Modified-Since: Thu, 23 Apr 2020 21:34:29 GMT
>
< HTTP/1.1 304 Not Modified

I am running rails like this:
RAILS_SERVE_STATIC_FILES=1 RAILS_ENV=production ./bin/rails s
or
RAILS_SERVE_STATIC_FILES=1 RAILS_ENV=production bundle exec thin start

todo - find what exactly is returning the response :)


text:
Q: Bookmarklet to select all friends and add them to an event on Facebook I am trying to make a bookmarklet to allow me to select all my friends in the dialog to create an event on Facebook. Examining the source with Firebug shows the following:
The div container for each person gets a new class label of
selectedCheckable

when it it is clicked, So I have written this like of JS to try and select all the div's and give them this class:
$(".checkableListItem").addClass("selectedCheckable");

This works in selecting them, however when it comes time to press the "Save and close" button, the changes do not seem to have any effect in selecting all the friends to add to the event. It seems that FB has a different way of marking the friends that have been selected to add to the event. Would anyone be able to point me in the right direction so I can accomplish this? Thanks in advance, RayQuang :)

A: May I advise instead of making your own couldn't you just use one of these Greasmonkey scripts?
http://userscripts.org/scripts/search?q=facebook+invite&submit=
That's what I was doing and it was working for my events. Let me know if it works for you.


text:
Q: TeX edef macro blues I spent some time trying to write a 'helper' macro to test a parameter for a new value, else use the existing value -- default values exist for all parameter positions.
I wanted to be able to write:
\foo{left}{nil}{}{20pt}

so that the second parameter would used its current value but the third value would be the value empty string. I wanted to use the notation:
\edef\pA{\isnil{#1}{\pA){#1}} % one for each parameter

I defined \isnil like so:
\def\nil{nil}
\def\isnil#1#2#3{%
  \edef\nilTest{#1}%
  \ifx\nilTest\nil#2\else#3\fi
}

but when I tried to run it, TeX complained that \nilTest is an undefined control sequence.
That is true of course, but I want \pA to hold a value, not a recipe for a value, so it must be an \edef which means that all the macro test will be expanded but while will the \edef not protect the \nilTest -- is this a place to use \noexpand -- that did not seem to work for me.
EDIT: no digits in \cs names (yeah, I knew that.)

A: Why doesn't your solution work? \edef\pA{\isnil{#1}{\pA){#1}} expands \isnil and gets \edef\nilTest{.... Now \edef is not expandable and falls into a sequence of \pA as the first element. An attempt to expand the next macro \nilTest fails.
Use \setpar from the following code to change your parameter.
\def\nil{nil}
\def\setpar#1#2{%
  \edef\nilTest{#2}%
  \ifx\nilTest\nil\else\let#1\nilTest\fi}

\def\first{old first}
\def\second{old second}
\setpar \first{nil}
\setpar \second{new}

first = ``\first'', second = ``\second''

P.S. Do not use digits in your macro.


text:
Q: Type of sentence with "said that ..." I have searched for answers online but cannot find anything.
I recently did a grammar quiz and got a sentence-type question wrong.
For example, is the sentence: "John said that he would like his steak medium rare," a complex sentence or simple sentence.
I initially thought it should be simple but the quiz said that the 'that' makes the rest of the sentence a dependent clause.
Also, what if the sentence did not include 'that' and was just: "John said he would like his steak medium rare."


text:
Q: Unknown value during simulation Carry Look Ahead with CMOS I'm new to Verilog.

 I've been assigned to write a 4-bit CLA using pmos and nmos primitives.

 I found a website which details the schematic: Design of VLSI Systems

 The CLA is at 6.5.3. I'm using the static implementation.

 Starting from the schematic for wire c4, I designed 3 more schematics to calculate the values of wires c1, c2 and c3.

 I'm pasting my code:
module carryCMOS(a, b, c_in, sum, c_out);
    // variables
    input [3:0] a, b;
    input c_in;
    output [3:0] sum;
    output c_out;

    // VDD and GND
    supply1 vdd;
    supply0 gnd;

    // internal wires
    wire g0, g1, g2, g3;
    wire p0, p1, p2, p3;
    wire c1, c2, c3, c4;

    // for wire c4
    wire pw_c41, pw_c42, pw_c43, pw_c44;
    wire nw_c41, nw_c42, nw_c43, nw_c44;

    // for wire c3
    wire pw_c31, pw_c32, pw_c33;
    wire nw_c31, nw_c32, nw_c33;

    // for wire c2
    wire pw_c21, pw_c22;
    wire nw_c21, nw_c22;

    // for wire c1
    wire pw_c11;
    wire nw_c11;

    // carry look ahead formulas
    assign g0 = a[0] & b[0];
    assign g1 = a[1] & b[1];
    assign g2 = a[2] & b[2];
    assign g3 = a[3] & b[3];

    assign p0 = a[0] ^ b[0];
    assign p1 = a[1] ^ b[1];
    assign p2 = a[2] ^ b[2];
    assign p3 = a[3] ^ b[3];

    // c4
    pmos pm1_c4(c4, vdd, p3);
    pmos pm2_c4(c4, pw_c41, p2);
    pmos pm3_c4(c4, pw_c42, p1);
    pmos pm4_c4(c4, pw_c43, p0);
    pmos pm5_c4(pw_c41, vdd, g3);
    pmos pm6_c4(pw_c42, pw_c41, g2);
    pmos pm7_c4(pw_c43, pw_c42, g1);
    pmos pm8_c4(pw_c44, pw_c43, g0);
    pmos pm9_c4(c4, pw_c44, c_in);

    nmos nm1_c4(c4, gnd, g3);
    nmos nm2_c4(c4, nw_c41, g2);
    nmos nm3_c4(c4, nw_c42, g1);
    nmos nm4_c4(c4, nw_c43, g0);
    nmos nm5_c4(nw_c41, gnd, p3);
    nmos nm6_c4(nw_c42, nw_c41, p2);
    nmos nm7_c4(nw_c43, nw_c42, p1);
    nmos nm8_c4(nw_c44, nw_c43, p0);
    nmos nm9_c4(c4, nw_c44, c_in);

    // c3
    pmos pm1_c3(c3, vdd, p2);
    pmos pm2_c3(c3, pw_c31, p1);
    pmos pm3_c3(c3, pw_c32, p0);
    pmos pm4_c3(pw_c31, vdd, g2);
    pmos pm5_c3(pw_c32, pw_c31, g1);
    pmos pm6_c3(pw_c33, pw_c32, g0);
    pmos pm7_c3(c3, pw_c33, c_in);

    nmos nm1_c3(c3, gnd, g2);
    nmos nm2_c3(c3, nw_c31, g1);
    nmos nm3_c3(c3, nw_c32, g0);
    nmos nm4_c3(nw_c31, gnd, p2);
    nmos nm5_c3(nw_c32, nw_c31, p1);
    nmos nm6_c3(nw_c33, nw_c32, p0);
    nmos nm7_c3(c3, nw_c33, c_in);

    // c2
    pmos pm1_c2(c2, vdd, p1);
    pmos pm2_c2(c2, pw_c21, p0);
    pmos pm3_c2(pw_c21, vdd, g1);
    pmos pm4_c2(pw_c22, pw_c21, g0);
    pmos pm5_c2(c2, pw_c22, c_in);

    nmos nm1_c2(c2, gnd, g1);
    nmos nm2_c2(c2, nw_c21, g0);
    nmos nm3_c2(nw_c21, gnd, p1);
    nmos nm4_c2(nw_c22, nw_c21, p0);
    nmos nm5_c2(c2, nw_c22, c_in);

    // c1
    pmos pm1_c1(c1, vdd, p0);
    pmos pm2_c1(pw_c11, vdd, g0);
    pmos pm3_c1(c1, pw_c11, c_in);

    nmos nm1_c1(c1, gnd, g0);
    nmos nm2_c1(nw_c11, gnd, p0);
    nmos nm3_c1(c1, nw_c11, c_in);

    // sum and carry
    assign sum[0] = p0 ^ c_in;
    assign sum[1] = p1 ^ (!c1);
    assign sum[2] = p2 ^ (!c2);
    assign sum[3] = p3 ^ (!c3);

    assign c_out = !c4;

endmodule

module test_carry;
    reg [3:0] in1, in2;
    wire [3:0] out;
    reg c_in;
    wire c_out;
    carryCMOS carry(in1, in2, c_in, out, c_out);

    initial begin
        $dumpfile("carry.vcd");
        in1 = 4'd0;
        in2 = 4'd1;
        assign c_in = 0;
        #20;
        $display("time:%d in1:%d in2:%d c_in:%d out:%d c_out:%d", $time,
            in1, in2, c_in, out, c_out);
        #20;
        in1 = 4'd7;
        in2 = 4'd8;
        assign c_in = 1;
        #20;
        $display("time:%d in1:%d in2:%d c_in:%d out:%d c_out:%d", $time,
            in1, in2, c_in, out, c_out);
        #20;
        in1 = 4'd5;
        in2 = 4'd1;
        assign c_in = 1;
        #20;
        $display("time:%d in1:%d in2:%d c_in:%d out:%d c_out:%d", $time,
            in1, in2, c_in, out, c_out);
        #20;
        in1 = 4'd5;
        in2 = 4'd10;
        assign c_in = 0;
        #20;
        $display("time:%d in1:%d in2:%d c_in:%d out:%d c_out:%d", $time,
            in1, in2, c_in, out, c_out);
        $dumpvars(0, carry);
    end

endmodule

 The problem I have been facing is that when I simulate the model, I'm getting an unknown value at the sum for one of the test inputs.
Simulation

A: Check the following lines:
pmos pm1_c1(c1, vdd, p0);

The value of p0 at time 80 is low. Therefore the nmos is trying to drive c1 to high.
On the other hand:
nmos nm1_c1(c1, gnd, g0);

The value of g0 at time 80 is high. Therefore the nmos is trying to drive c1 to low.
Since c1 has two drivers of values 1 and 0, its true value is unknown, i.e. x.
EDIT:
I'm not sure if this design is correct. You are to convert c1=g0+p0.c0 to a CMOS netlist. Converting a Boolean equation to a CMOS netlist is very trivial. Here are some good references: http://cs.utexas.edu/users/fussell/cs310/lectures/cs310-lecture3.pdf and http://acipo.com/blog/cmos-design-intro
Looking at your code for C1 more closely, you got the NMOS part right. The PMOS network is just the dual of NMOS, that means pm1_c1 should have the same gate (i.e. control) signal as nm1_c1. Just change it, and it should fix the problem at least for C1!


text:
Q: Ergodicity of a sequence of independent blocks I am stuck with the problem given below, more precisely, with the part regarding ergodicity. I have a proof, also given in what follow, but it does not seem to be correct; well, at least, it does not sound like a solid mathematical proof.
Problem (Independent blocks, Exercise 7.1.6 in Durrett):
Let $X_1, X_2, \dotsc$ be a stationary sequence. Let $n < \infty$ and let $Y_1, Y_2, \dotsc$ be a sequence so that $(Y_{nk+1}, \dotsc, Y_{n(k+1)})$, $k \geq 0$ are i.i.d. and $(Y_1, Y_2, \dotsc, Y_n) = (X_1, X_2, \dotsc, X_n)$. Finally
let $\nu$ be uniformly distributed on $\{1, 2, \dotsc, n\}$, independent of Y, and let $Z_m = Y_{\nu + m}$ for $m \geq 1$. Show that Z is stationary and ergodic.
Proof (ergodicity only):
We know that, for an i.i.d. sequence, Kolmogorov's 0-1 law implies that the tail $\sigma$-field is trivial (Example 7.1.6 in Durrett). Therefore, the tail $\sigma$-field of the process formed by the (independent) blocks of the $Y$ sequence is trivial.
This tail $\sigma$-field is
\begin{align*}
  \mathcal{T}_Y & = \cap_{k = 1}^\infty \sigma(Y_{nk + 1}, \dots, Y_{n(k + 1)}, Y_{n(k + 1) + 1}, \dots, Y_{n(k + 2)}, \dots) \\
  & = \sigma(Y_{n + 1}, \dots) \cap \sigma(Y_{2n + 1}, \dots) \cap \sigma(Y_{3n + 1}, \dots) \cap \dots \\
  & = \mathcal{F}_{n + 1} \cap \mathcal{F}_{2n + 1} \cap \mathcal{F}_{3n + 1} \cap \dots
\end{align*}
Now, let us have a look at the tail $\sigma$-field of the $Z$ sequence:
\begin{align*}
  \mathcal{T}_Z & = \cap_{k = 1}^\infty \sigma(Z_k, Z_{k + 1}, \dots) = \cap_{k = 1}^\infty \sigma(Y_{\nu + k}, Y_{\nu + k + 1}, \dots) \\
  & = \sigma(Y_{\nu + 1}, \dots) \cap \sigma(Y_{\nu + 2}, \dots) \cap \sigma(Y_{\nu + 3}, \dots) \cap \dots \\
  & = \mathcal{F}_{\nu + 1} \cap \mathcal{F}_{\nu + 2} \cap \mathcal{F}_{\nu + 3} \cap \dots
\end{align*}
It can be seen that the $Z$ sequence of $\sigma$-algebras is seamless: depending on the outcome of $\nu$, it starts from $\mathcal{F}_{\nu + 1}$ (from $\mathcal{F}_{n + 1}$ in the worst case) and has not further gaps. On the other hand, the $Y$ sequence of $\sigma$-algebras starts from exactly $\mathcal{F}_{n + 1}$ and does have gaps. The more terms involved in an intersection, the smaller the resulting set. Hence, $\mathcal{T}_Z \subset \mathcal{T}_Y$, and, therefore, the $Z$ sequence is ergodic.
The idea here is to prove the ergodicity property of the $Z$ sequence by showing that the tail $\sigma$-field of this sequence is trivial, and this is done by showing that this tail $\sigma$-field is contained in the tail $\sigma$-field of the sequence formed by the independent blocks of the $Y$ sequence.
I would appreciate any suggestions.
Regards,
Ivan

A: The sequence $(Y_k)$ is $n$-dependent because the blocks of $n$ are independent. Using the fact that $\nu$ is independent of $Y$, we get that $Z$ is $2n$-independent. Then we use a similar argument as in the zero-one law.

A: I would be grateful if somebody could confirm that the following proof is correct.
Proof (ergodicity only):
By definition, the $Z$ sequence is ergodic if
$$
  P((Z_1, Z_2, \dotsc) \in B) \in \{0, 1\}
$$
whenever $B \in \mathcal{R}^{\{0, 1, \dotsc\}}$ has
$$
  \{ (Z_1, Z_2, \dotsc) \in B \} = \{ (Z_2, Z_3, \dotsc) \in B \}. \tag{$\ast$}
$$
Let $A = \{ (Z_1, Z_2, \dotsc) \in B \}$, which is shift invariant according to ($\ast$).
We are to show now that $P(A) \in \{0, 1\}$.
By iteratively applying the shift operator to ($\ast$), $A \in \sigma(Z_k, Z_{k + 1}, \dotsc)$ for $k \geq 1$; hence,
$$
  A \in \cap_{k = 1}^\infty \sigma(Z_k, Z_{k + 1}, \dotsc) = \mathcal{T}_Z, \text{ the tail $\sigma$-field of the sequence.}
$$
Next, for any $B \in \mathcal{R}$, due to the independence of $Y$ and $\nu$,
$$
  \{ Z_m \in B \} = \{ Y_{m + \nu} \in B \} = \cup_{k = 1}^n \{ \nu = k \} \cap \{ Y_{m + k} \in B \} \subseteq \cup_{k = 1}^n \{ Y_{m + k} \in B \}.
$$
Thus,
$$
  \sigma(Z_m) \subseteq \sigma(Y_{m + 1}, \dotsc, Y_{m + n}).
$$
Consequently,
$$
  \mathcal{T}_Z \subseteq \mathcal{T}_Y = \cap_{k = 1}^\infty \sigma(Y_k, Y_{k + 1}, \dotsc), \text{ the tail $\sigma$-field of the block sequence.}
$$
Finally, by Kolmogorov's zero-one law, the tail $\sigma$-field of the block sequence, $\mathcal{T}_Y$, is trivial.
Hence, $P(A) \in \{0, 1\}$ as $A \in \mathcal{T}_Z \subseteq \mathcal{T}_Y$.


text:
Q: Python parallelized code is taking much longer than it should EDIT: My goal with this post is to understand the source of the time-drain. I welcome other recommendations as well, but my main concern, and I want to learn about is why my code is not speeding up with parallelization? What is it that's causing the parallelization to slow down?
I previously asked a question about this, and I now realize that it wasn't a good one. I apologize for the poor post. So I'm re-asking having put more effort into solving it.
I have managed to implement a parallelized solution. However, the parallelized code is much much much slower than the serialized version.
EDIT: The foo() function below is rather simple, and can be put more concisely, but the real version of the function is a bit more complicated. The main problem is still the fact that at thousands of arrays, each of length ~70,000, the sheer number of comparisons is what's causing the slowness. So parallelization seems to be the best solution here. Of course, recommendations for making the steps more efficient are welcome, and I appreciate any such suggestions.
Problem
Consider a list of numpy arrays. I need to do pairwise comparisons on these arrays in the list. My real problem has thousands of arrays of length ~70,000, but the toy example below has much smaller numbers (can be adjusted with the listLen and arrayLen variables though)
Attempt
Here foo() is the comparison function that will be used. If you try playing around with arrayLen and listLen, you'll see that no matter what values you choose, the parallelized function do_calculations_mp is always slower than the non-parallelized version do_calculations_no_mp. From what I've read, multiprocesing.Process has less overhead than multiprocess.Pool, so it shouldn't be taking this long, right?
I'd really appreciate any help on this.
import numpy as np
from multiprocessing import Process
import itertools
import random
import sys
from datetime import datetime

def foo(arr1, arr2):
    matches = 0
    for i in range(len(arr1)):
        if arr1[i] == arr2[i]:
            matches += 1
    return(matches)

def do_calculations_mp(aList):
    flag_indices = []

    processes = []

    index_combns = list(itertools.combinations(range(len(aList)),2))
    for i,j in index_combns:
        p = Process(target = foo, args = (aList[i], aList[j]))
        processes.append(p)
        p.start()

    for procs in processes:
        procs.join()

    return(flag_indices)

def do_calculations_no_mp(aList):
    flag_indices = []
    index_combns = list(itertools.combinations(range(len(aList)),2))
    for i,j in index_combns:
        numMatches = foo(aList[i], aList[j])

    return(flag_indices)

if __name__ == '__main__':
    listLen = 50
    arrayLen = 300
    # Creates a list of listLen arrays, where each array has length arrayLen
    myList = [np.array([random.choice([0,1,2,5]) for i in range(arrayLen)]) for x in range(listLen)]

    print("Processing No MP:             " + str(datetime.now()))
    flagged = do_calculations_no_mp(myList)
    print("Done processing No MP:        " + str(datetime.now()))

    print("Processing MP:                " + str(datetime.now()))
    flagged_mp = do_calculations_mp(myList)
    print("Done processing MP:           " + str(datetime.now()))

A: A few general points:

*

*You have a finite number of processors. Your code is creating a number of processes equal to the number of combinations that you have, which might (greatly) exceed the number of processors and that is rather pointless.

*You cannot return results from a process with your return statement. You need another mechanism for doing so, such as passing a multiprocessing.Queue instance to your processes to which results are written (there are other ways).

*Using a multiprocessing pool solves issues 1. and 2.

*Keeping the arrays in shared memory will reduce the overhead of multiprocessing.

*The more CPU-intensive foo is, the better multiprocessing will perform compared to serial processing. This means having long lists.

I have modified your demo incorporating these ideas to demonstrate that multiprocessing can outperform serial processing. Note that foo now accesses myList as a global variable, which is a list of shared memory arrays, and so it now only has to be passed list indices.
from multiprocessing import Pool, Array
import itertools
import random
import sys
from time import time_ns

listLen = 6
arrayLen = 5_000_000

def foo(i, j):
    arr1 = myList[i]
    arr2 = myList[j]
    matches = 0
    for index in range(arrayLen):
        if arr1[index] == arr2[index]:
            matches += 1
    return(matches)

def generate_args():
    index_combns = list(itertools.combinations(range(listLen), 2))
    for i, j in index_combns:
        yield (i, j)

def init_pool_processes(aList):
    global myList
    myList = aList

def do_calculations_mp():
    numMatches = 0
    with Pool(initializer=init_pool_processes, initargs=(myList,)) as pool:
        for matches in pool.starmap(foo, generate_args()):
            numMatches += matches
        pool.close()
        pool.join()
    return numMatches

def do_calculations_no_mp():
    numMatches = 0
    for i, j in generate_args():
        numMatches += foo(i, j)
    return numMatches

if __name__ == '__main__':
    # Creates a list of listLen arrays, where each array has length arrayLen
    myList = [Array('i', [random.choice([0,1,2,5]) for i in range(arrayLen)], lock=False) for x in range(listLen)]

    start = time_ns()
    numMatches = do_calculations_no_mp()
    elapsed = (time_ns() - start) / 1_000_000_000
    print(f"Done processing No MP, numMatches = {numMatches}, elapsed time = {elapsed}")

    start = time_ns()
    numMatches = do_calculations_mp()
    elapsed = (time_ns() - start) / 1_000_000_000
    print(f"Done processing MP, numMatches = {numMatches}, elapsed time = {elapsed}")

Prints:
Done processing No MP, numMatches = 18748321, elapsed time = 10.0353228
Done processing MP, numMatches = 18748321, elapsed time = 2.7033887

With listLen defined as 70_000, however, which is approximately the length of your lists, we get:
Done processing No MP, numMatches = 261721, elapsed time = 0.1350159
Done processing MP, numMatches = 261721, elapsed time = 0.2939995

So the issue is that until your lists become longer, foo at the current complexity, is not sufficiently CPU-intensive to be more performant with multiprocessing. Of course, if your actual foo is far more complex, then ...
As the number of combinations become very large, you might want to consider using method multiprocessing.pool.imap_unordered with a suitable chunksize argument. foo would then need to be redefined to take a single tuple argument.

A: If performance matters, let's start from principles
Python Interpreter is interpreting instructions, use dis.dis( foo ) to see them below.
Python Interpreter is expensive if going to spawn processes (as detailed in your first question)
Python Interpreter is known to be awfully bad (read slow) if using serial-iterators (read for-loops, generator-based task-farming et al)
Python Interpreter in distributing "lightweight" tasks for scales of about 18M tasks, combined from data from 6E3 list-of-items, each item being about 1E6 long np.array-instance - as you described in your (now deleted) second question, will almost for sure kill its own capabilities (performance-wise), if all above are used at once inside multiprocessing.
def foo(arr1, arr2):
    matches = 0
    for i in range(len(arr1)):
        if arr1[i] == arr2[i]:
           matches += 1
return(matches)

was demonstrated as the MCVE-representation of the work-unit ( a task )
>>> dis.dis( foo )
  2           0 LOAD_CONST               1 (0)
              3 STORE_FAST               2 (matches)

  3           6 SETUP_LOOP              59 (to 68)
              9 LOAD_GLOBAL              0 (range)
             12 LOAD_GLOBAL              1 (len)
             15 LOAD_FAST                0 (arr1)
             18 CALL_FUNCTION            1
             21 CALL_FUNCTION            1
             24 GET_ITER
        >>   25 FOR_ITER                39 (to 67)
             28 STORE_FAST               3 (i)

  4          31 LOAD_FAST                0 (arr1)
             34 LOAD_FAST                3 (i)
             37 BINARY_SUBSCR
             38 LOAD_FAST                1 (arr2)
             41 LOAD_FAST                3 (i)
             44 BINARY_SUBSCR
             45 COMPARE_OP               2 (==)
             48 POP_JUMP_IF_FALSE       25

  5          51 LOAD_FAST                2 (matches)
             54 LOAD_CONST               2 (1)
             57 INPLACE_ADD
             58 STORE_FAST               2 (matches)
             61 JUMP_ABSOLUTE           25
             64 JUMP_ABSOLUTE           25
        >>   67 POP_BLOCK

  6     >>   68 LOAD_FAST                2 (matches)
             71 RETURN_VALUE

Using the amount of pseudo-instructions as a simplified measure of how much work has to be done ( where all of CPU-clocks + RAM-allocation-costs + RAM-I/O + O/S-system-management time spent must count and counts the actually accrued costs ), we start to see the relative-costs of all these ( unavoidable ) add-on costs, compared to the actual useful task ( i.e. how many pseudo-instructions are finally spent on what we want to compute --The-useful-WORK--, contrasting the amounts of already burnt overhead-costs and per-task add-on costs, that were needed to make this happen and run )
This fraction is cardinal if fighting for both performance & efficiency (of resources usage patterns).
For cases, where add-on overhead costs dominate, these cases are straight a sin of keeping anti-patterns stacked to their worst consequences
For cases, where instantiation + per-task add-on overhead costs make less than 0.01 % of the useful work, we still may result in pretty unsatisfactory low speedups (see the simulator and related details, as posted yesterday and see the devastated speedup line - i.e. from a day-long runtimes today, you will receive about a day-long runtimes, if keeping all these add-on costs as high as now )
For cases, where the scope of the useful work ( the actual foo(), yet performance-boosted to strip-off most of its performance antipatterns ) strongly dominates, i.e. diminishes all add-on + per-task overhead costs, there we still see the Amdahl's Law ceiling - called so, so self-explanatory - a "Law of diminishing returns" ( since adding more resources ceases to improve the performance, even if we add infinitely many CPU-cores and likes )
Let's test the foo()-speeds above ( as-was presented ) and below ( as-refactored ) :
from zmq import Stopwatch; aClk = Stopwatch()       # a [us]-resolution clock
import numpy as np

def test( aSize = 1E6 ):
    TheSIZE = int( min( 1E7, aSize ) )              # fused RAM-footprint < GB
    A = np.random.random_integers( 0, 9, TheSIZE )  # pre-allocate, fill
    B = np.random.random_integers( 0, 9, TheSIZE )  # pre-allocate, fill
    aClk.start() #----------------------------------# CRITICAL SECTION.start
    _ = np.where( A==B, 1, 0 ).sum()                #    smart compute "count"
    t = aClk.stop() #-------------------------------# CRITICAL SECTION.end
    MASK = ( "test( aSize = {0:>20d} ) "
           + "took {1: >20d} [us] "
           + " {2:} matches found in random filled A, B "
           + " ~ {3:} [us/loop]"
             )
    print MASK.format( TheSIZE, t, _, float( t ) / TheSIZE )

use the same to measure how long does the foo( A, B ) last in your serial-iterator code
a "naked"-foo( A, B ) took about 800 [ns] (!!) per array-cell( to that we mast add all SER/xfer/DES costs we pay for moving ~ 20[MB] of parameters' data, per task, which may take and costs hundreds of thousands of CPU-clocks, just to move the data into a remote process (worker), before it starts a few pseudo-instructions dis.dis( foo ) shown above, ouch, that hurts ... )
while
np.where()-code took under about 19 [ns] 42 X faster per array-cell ( 25 [ns] if all 4-cores on my localhost were background-loaded with desktop system running 3 TV-streams live, so less free CPU-cores to use numpy-multicore code tricks on-the-fly )
>>> test( 1E34 )
took 239712 [us]  999665 matches found in random filled A, B  ~ 0.0239712 [us/loop]
took 220671 [us] 1000246 matches found in random filled A, B  ~ 0.0220671 [us/loop]
took 227004 [us] 1001805 matches found in random filled A, B  ~ 0.0227004 [us/loop]
took 210587 [us]  999267 matches found in random filled A, B  ~ 0.0210587 [us/loop]
took 195863 [us]  998218 matches found in random filled A, B  ~ 0.0195863 [us/loop]
took 241407 [us] 1000017 matches found in random filled A, B  ~ 0.0241407 [us/loop]
took 193243 [us] 1001084 matches found in random filled A, B  ~ 0.0193243 [us/loop]

From the perspective of this comparison, start to try to properly refactor the process - the goal is to crawl all ~ 18M-pair-wise combinations from a 6E3-long list of ~10[MB]-large-np.arrays for all pairwise comparisons.
The faster the better, right?


text:
Q: bootstrap dropdown menu link to div content i want to make layout like this

I have a page, where in it there is a div. when click menu, then its contents will be displayed on the home page of this div. where the contents of each menu is another page (index.php/student,index.php/course etc)
how possible to create this layout with bootstrap?
anyone can help me?
thanks


text:
Q: Call methods on fragment - every object is null I have the following problem:
I have one Fragment, which implements a specified interface.
    @Override
public void sensorStatusChanged(double bearing, double pitch, double rotation) {
    if (radarView != null) {
        radarView.setBearing((float) bearing);
    }
    ....
}

The ParentActivity handles the Location-Listener and tries to inform the fragment that sensorData has changed.
At this part, I have the following behaviour: The method gets called, but the radarView is null. I'm 100% sure, that the radarView is not null. When I set some breakpoints into this code, the only part where the radarView is null, is inside of methods, which are called from the activitiy and not from the fragment itself.
I'm a total beginner in dealing with fragments (started today), so I think I'm doing something wrong.
How can I solve this behaviour?
Cheers

A: Okay, i found the mistake myself: I've created a fragment in onCreate of the activity. But when I change fragments, I recreated the fragments, without removing the listener of the old fragment..


text:
Q: strcpy when having char pointers in C I have a simple doubt in char arrays. I have a structure:
struct abc {
char *charptr;
int a;
}

void func1()
{
    func2("hello");
}

void func (char *name)
{
    strcpy(abc.charptr, name); // This is wrong.
}

This strcpy will result in a crash since I do not have any memory allocated to the charptr.
The question is : For mallocing this memory, can we do
abc.charptr = (char *) malloc(strlen(name)); //?
strcpy(abc.charptr, name); // Is this (or strncpy) right ?

Is this right ?

A: If you were to use malloc() you need to remember to make room for the null-terminator. So use malloc(strlen(name)+1) before calling strcpy().
But in this case you should just use strdup() which does the allocation and copying in one go:
abc.charptr = strdup(name);

The memory returned by strdup() has been allocated with malloc() and hence must be disposed of with a call to free().

A: It needs to be:
abc.charptr = malloc(strlen(name)+1); ?
strcpy(abc.charptr, name);

The return value of strlen doesn't include space for the null zero '\0'  at the end of the string.
You will also have to free your allocated memory at some point.

A: abc.charptr = (char *) malloc(strlen(name) + 1);

Note the +1, since you need space for the null terminator. Then strcpy() will be fine.


text:
Q: How to keep the values in the input fields when submitting a form in PHP? I have a form with a table with dynamic fields and dynamic rows. So initially the table contains one row with two fields, when I fill them both and click Enter, a jquery function will create a new row below.
When time comes to Submit the form, I am checking if there is any empty field, and if there is any it displays an error BUT the problem is here, it clears all fields. How can I still keep them when submitting?
Here is the HTML:
 <form action="" method="post">
           <button type="submit" class="btn" name="add_device">Add devices</button>
        <?php foreach ($dev_type_results as $row) {
        } ?>

                No.
                Serial no.
                IMEI

                1
                <input type="text" class="inputs" name="serial_no[]" value="<?php if (isset($_POST['serial_no'])) { echo htmlspecialchars($_POST['serial_no']);} ?>" />
                <input type="text" class="inputs lst" name="imei[]" value="<?php if (isset($_POST['imei'])) { echo htmlspecialchars($_POST['imei']); } ?>" />

    </form>

jquery function :
        var i = $('table tr').length;

    $(document).on('keyup', '.lst', function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            html = '
';
            html += '' + i + '	';

            <?php foreach ($dev_type_results as $row) {
            }
                html += '<input type="text" class="inputs" name="serial_no[]' + i + '"  value="<?php if (isset($_POST['serial_no'])) { echo htmlspecialchars($_POST['serial_no']);} ?>"/>	';
                html += '<input type="text" class="inputs lst" name="imei[]' + i + '" value="<?php if (isset($_POST['imei'])) { echo htmlspecialchars($_POST['imei']);} ?>"/>	';

            html += '
';
            $('table').append(html);
            $(this).focus().select();
            i++;
        }
    });

    $(document).on('keydown', '.inputs', function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            var index = $('.inputs').index(this) + 1;
            $('.inputs').eq(index).focus();
            event.preventDefault();
        }
    });

Below for brevity I will just post the PHP code where I validate:
if (count(array_filter($_POST['serial_no'])) < count($_POST['imei'])) {
  array_push($errors, "Found empty field in Serial no. column");
}else{
 //call function to post to database
}

I have tried already by using global variables but it doesn't work. What else can I try?

A: You could add ids to the inputs and use javascript to find it and change it's content.

    var Input_1 = document.getElementById(Input_1 - id);
    var Input_2 = document.getElementById(Input_2 - id);
    var Val_1;
    var Val_2;
    var completed = false;
    var i = $('table tr').length;

    $(document).on('keyup', '.lst', function(e) {
      var code = (e.keyCode ? e.keyCode : e.which);
      if (code == 13) {
        html = '
';
        html += '' + i + '	';
        html += '<input type="text" class="inputs" name="serial_no[]' + i + '"  value="<?php if (isset($_POST['
        serial_no '])) { echo htmlspecialchars($_POST['
        serial_no ']);} ?>
        "/>	';
        html += '<input type="text" class="inputs lst" name="imei[]' + i + '" value="<?php if (isset($_POST['
        imei '])) { echo htmlspecialchars($_POST['
        imei ']);} ?>"/>	';

        html += '
';
        $('table').append(html);
        $(this).focus().select();
        i++;
      }
    });

    $(document).on('keydown', '.inputs', function(e) {
      var code = (e.keyCode ? e.keyCode : e.which);
      if (code == 13) {
        completed = true
        var index = $('.inputs').index(this) + 1;
        $('.inputs').eq(index).focus();
        event.preventDefault();
        Input_1.value = Val_1;
        Input_2.value = Val_2;
      }
    });

    <form action="" method="post">
      <button type="submit" class="btn" name="add_device">Add devices</button>
      <?php foreach ($dev_type_results as $row) {
            } ?>

          No.
          Serial no.
          IMEI

          1
          <input type="text" class="inputs" name="serial_no[]" value="<?php if (isset($_POST['serial_no'])) { echo htmlspecialchars($_POST['serial_no']);} ?>" />
          <input type="text" class="inputs lst" name="imei[]" value="<?php if (isset($_POST['imei'])) { echo htmlspecialchars($_POST['imei']); } ?>" />

    </form>
    <?php
        if (count(array_filter($_POST['serial_no'])) < count($_POST['imei'])){
      array_push($errors, "Found empty field in Serial no. column");
    }else{
     //call function to post to database
    }
    ?>


text:
Q: Passing An Array of Values To Jquery I have a button like so:
<button id='abc' value=['fred', 26]></button>

I want to know how I can access those two values via JQuery's .val() function.
I have tried $("#abc").val()[0] but that just appears to give me the first character which is the bracket "[".
I would like .val()[0] to instead give me the value "Fred".

A: Your HTML is invalid. You should try;
<button id='abc' value="['fred', 26]"></button>

However, you should look at using valid JSON notation, to enable you to parse the data as an array. JSON requires double quotes for strings (rather than single '), so you should end up with;
<button id='abc' value='["fred", 26]'></button>

If you were to access $('#abc').val() directly now, you'd retrieve the string ["fred", 26]. To retrieve this data as an array, you should parse the data using jQuery.parseJSON();
var array = jQuery.parseJSON($('#abs').val());
for (var i=0;i<array.length;i++) {
    alert(array[i]);
};

A: Matt's suggestion is good (and he's right that your HTML is invalid).
Another approach, since the element has an ID, is to store the values separately, in your JavaScript rather than in the markup. Since IDs are unique on the page by definition, you could have:
<script>
var elementValues = {};
elementValues.abc = ['fred', 26];
</script>

...and then where you want to use it, if you know the ID (in your code you do, you're using it to find the element via $("#abc")):
var values = elementValues.abc;

...or in an event handler where you don't necessarily know the ID in the code, assuming this is the element in question (as it is in event handlers in jQuery):
var values = elementValues[this.id];

A: You can use eval
<button id="abc" value='["fred",26]'></button>

var values = eval($("#abc").val());
values[0]
values[1]

It will return array of values

A: Fix correct JSON format using " insted of ':
<button id="abc" value='["fred",26]'></button>

Parse the string:
$.parseJSON( $('#abc').val() )[0];

or
var abc = $.parseJSON( $('#abc').val() );

abc[0];


text:
Q: Writing to another python program's raw input without popping a new black screen I am trying to brute-force a python program:
what I need is to make another python file that will run
the first python code with an input (The first code takes input with raw_input)
The problem is that the first code uses pygame, so if I want to brute-force I need to run it, try a number, then open it again, and continue checking like that...
do you have any idea how to write to a process raw_input like a bruteforce?
This is a lite version of what I'm trying to do: (without pygame)
first code: (The one I need to bruteforce)
found = []
while 1:

    a =int(raw_input("ENTER : "))
    print "THE NUM: ", a
    if a in [74,82,101,550,990]:
        print a , "  Got number right!"
        found.append(a)

    if [74,82,101,550,990] == found:
        print "WINNER!!!!!"
        break

This one does not have pygame, but the idea stays the same..
I tried using this code:
import subprocess
for i in range(1000):
    process = subprocess.Popen(["grep", "PATH TO PYCODE"],
    stdin=subprocess.PIPE, stdout=subprocess.PIPE)
    process.stdin.write(i)
    print process.communicate()[0]
    process.stdin.close()

But it gives this error:
WindowsError: [Error 2] The system cannot find the file specified

and the path is 100% correct...
Edit:
if I write in cmd:
echo 5 | python PATH_TO_FILE

it pops this error:
EOFError: EOF when reading a line

Thanks for helping! :)

A: You have several issues.
First, the top program (which I'll call check.py) doesn't terminate on EOF, it throws an error.  Second, the top program is written to be interactive but you're using it noninteractively.  Removing the "INPUT : " should be enough to fix this for your purposes.
Try this:
import sys
found = []
for line in sys.stdin:
    line = line.strip();

    a = int(line);
    print "THE NUM: ", a
    if a in [74,82,101,550,990]:
        print a , "  Got number right!"
        found.append(a)

    if [74,82,101,550,990] == found:
        print "WINNER!!!!!"
        break

Third, the bottom program will never be the WINNER because it restarts the program for each guess.  Fourth, you're writing binary values into the pipe, but your program expects text.
import subprocess

process = subprocess.Popen(["python", "check.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
for i in range(1000):
    process.stdin.write("%d\n" % i)
print process.communicate()[0]
process.stdin.close()

Before running this you probably want to delete "THE NUM" printout from check.py.
However, your initial question did say that you need to restart the pygame each time, so in that case you would leave the loop on i as you had it originally -- that's just not what your example program is written to expect.
Here's the output, with the "THE NUM : " output commented out:
$ python pipe.py
74   Got number right!
82   Got number right!
101   Got number right!
550   Got number right!
990   Got number right!
WINNER!!!!!


text:
Q: How can I loop through a list and for each distinct value initiate another loop? I have a python list, this list is of any document that has been updated within a set timeframe and the documents are ID'd via a set value in the list.  There may be one or many in the resulting list.  What I am trying to figure out is how I can loop through the list of values (documents) and trigger another loop that iterates through another list I have of emails resulting in one email per address per document in the original list?  I tried to "stack" loops on top of each other (code snippet shown below), but this results in multiple emails to each email address all with a full list of documents (i.e. if there are two documents in the list, two emails are sent to each address with the details about both documents).
import boto3
from botocore.exceptions import ClientError
import requests
from datetime import datetime, timedelta

#first get request to pull all current endusers
GET1 = "https://abdc.com/api"

r1 = requests.get(url = GET1, auth=('username/token','APItoken'))

#convert to python dict
data = r1.json()

#create a list of all user's email addresses
emails = [user["email"] for user in data["users"]]

#create an timestamp of previous day and convert to epoch
ts1 = datetime.today() - timedelta(days =1)
ts2 = ts1.strftime("%s")

#set start time attribute as a parameter
params = {'start_time':ts2}

#second GET reqeust to pull all articles updated in the last 24 hrs
GET2 = "https://efdg.com/api"

r2 = requests.get(url = GET2, params=params, auth=('username/token','APItoken'))

#convert to python dict
data2 = r2.json()

#create list of all the target article titles and html url
updated_docs = [articles["html_url"] for articles in data2["articles"]]
doc_title = [articles["title"] for articles in data2["articles"]]

for y in updated_doc:

   #create loop to iterate throuhg all the email addresses and send
   individual emails to users
   for x in emails:
        # This address must be verified with Amazon SES.
        SENDER = "example@example.com"

        #To list
        RECIPIENT = x

        # Specify a configuration set. If you do not want to use a configuration
        # set, comment the following variable, and the
        # ConfigurationSetName=CONFIGURATION_SET argument below.
        #CONFIGURATION_SET = "ConfigSet"

        # If necessary, replace us-west-2 with the AWS Region you're using for Amazon SES.
        AWS_REGION = "us-east-1"

        # The subject line for the email.
        SUBJECT = "blah blah "

        # The email body for recipients with non-HTML email clients.
        BODY_TEXT = ("Amazon SES Test (Python)\r\n"
                     "This email was sent with Amazon SES using the "
                     "AWS SDK for Python (Boto)."
                     )

        # The HTML body of the email.
        BODY_HTML = """

l Documentation Notification

          <p1>Please click the link below for the most current version of this document.

          """+str(doc_title)+"""

          """+str(updated_docs)+"""
          </p1>

                    """

        # The character encoding for the email.
        CHARSET = "UTF-8"

        # Create a new SES resource and specify a region.
        client = boto3.client('ses', region_name=AWS_REGION)

        # Try to send the email.
        try:
            # Provide the contents of the email.
            response = client.send_email(
                Destination={
                    'ToAddresses': [
                        RECIPIENT,
                    ],
                },
                Message={
                    'Body': {
                        'Html': {
                            'Charset': CHARSET,
                            'Data': BODY_HTML,
                        },
                        'Text': {
                            'Charset': CHARSET,
                            'Data': BODY_TEXT,
                        },
                    },
                    'Subject': {
                        'Charset': CHARSET,
                        'Data': SUBJECT,
                    },
                },
                Source=SENDER,
                # If you are not using a configuration set, comment or delete the
                # following line
                #ConfigurationSetName=CONFIGURATION_SET,
            )
        # Display an error if something goes wrong.
        except ClientError as e:
            print(e.response['Error']['Message'])
        else:
            print("Email sent! Message ID:"),
            print(response['MessageId'])

A: So, you've completely changed your code, so I'm well confused, but if I can read between the lines properly you meant something like this:
#create loop to iterate through all documents in the list
for article in data2["articles"]:

    #create loop to iterate through all the email addresses and send individual emails to
    users
    for x in emails:
        # This address must be verified with Amazon SES.
        SENDER = "example@example.com"

        #To list
        RECIPIENT = x

        # The HTML body of the email.
        BODY_HTML = """

l Documentation Notification

          <p1>Please click the link below for the most current version of this document.

          """+str(article["title"])+"""

          """+str(article["html_url"])+"""
          </p1>

                    """

Notice how I iterate through data2["articles"] and update the BODY_HTML with article["title"] and article["html_url"],


text:
Q: Parsing log file to JSON object Does anyone know what the best way would be to parse a log file (Salesforce) into a structured JSON object
There are certain sections in the log file that can be identified, like EXECUTION_STARTED,EXECUTION_FINISHED, CODE_UNIT_STARTED CODE_UNIT_FINISHED and many more
There are also time information that I would like to have in the JSON object
Are there any libraries available in nodejs that could be used to accomplish this ?
I was looking into antlr4 but it seems quite complex
-Jani

A: Looks like a CSV -> JSON conversion
// Reading the file using default
// fs npm package
const fs = require("fs");
csv = fs.readFileSync("CSV_file.csv")

// Convert the data to String and
// split it in an array
var array = csv.toString().split("\r");

// All the rows of the CSV will be
// converted to JSON objects which
// will be added to result in an array
let result = [];

// The array[0] contains all the
// header columns so we store them
// in headers array
let headers = array[0].split(", ")

// Since headers are separated, we
// need to traverse remaining n-1 rows.
for (let i = 1; i < array.length - 1; i++) {
  let obj = {}

  // Create an empty object to later add
  // values of the current row to it
  // Declare string str as current array
  // value to change the delimiter and
  // store the generated string in a new
  // string s
  let str = array[i]
  let s = ''

  // By Default, we get the comma separated
  // values of a cell in quotes " " so we
  // use flag to keep track of quotes and
  // split the string accordingly
  // If we encounter opening quote (")
  // then we keep commas as it is otherwise
  // we replace them with pipe |
  // We keep adding the characters we
  // traverse to a String s
  let flag = 0
  for (let ch of str) {
    if (ch === '"' && flag === 0) {
      flag = 1
    }
    else if (ch === '"' && flag == 1) flag = 0
    if (ch === ', ' && flag === 0) ch = '|'
    if (ch !== '"') s += ch
  }

  // Split the string using pipe delimiter |
  // and store the values in a properties array
  let properties = s.split("|")

  // For each header, if the value contains
  // multiple comma separated data, then we
  // store it in the form of array otherwise
  // directly the value is stored
  for (let j in headers) {
    if (properties[j].includes(", ")) {
      obj[headers[j]] = properties[j]
        .split(", ").map(item => item.trim())
    }
    else obj[headers[j]] = properties[j]
  }

  // Add the generated object to our
  // result array
  result.push(obj)
}

// Convert the resultant array to json and
// generate the JSON output file.
let json = JSON.stringify(result);
fs.writeFileSync('output.json', json);

Change "CSV_file.csv" above to whatever your CSV file is.
Save the js file as app.js and run using
node app.js
Source: https://www.geeksforgeeks.org/how-to-convert-csv-to-json-file-having-comma-separated-values-in-node-js/


text:
Q: Multi threaded Linux Socket programming design I am trying to write a server program which supports one client till now and over the few days i was trying to develop it, I concluded i needed threads. The reason for such a decision was since I take input from a wifi socket and later process it and finally write to a file, the processing time is slow and hence i needed a input thread -> circular buffer -> output thread pattern with producer consumer model which is quite common in network programming.
Now, The situation becomes complicated, as I need to manage client disconnection and re connection. I thought of using pthread_exit() and cleaning up all the semaphores and then re initializing them each time the single client re connects.
My question is that is this a efficient approach i.e. everytime killing the threads and semaphores and re creating them. Are there any better solutions.
Thanks.

A:
My question is that is this a efficient approach i.e. everytime killing the threads and semaphores and re creating them. Are there any better solutions.

*

*Learn how to use non-blocking sockets and an event loop. Or use a library that provides TCP sessions for you using non-blocking sockets under the hood. Such as boost::asio.

*Learn how to use multi-threading without polluting your code with any synchronization primitives by using message passing to communicate between threads, not shared state. The event loop library you use for non-blocking I/O should also provide means for cross-thread message passing.

A: Some comments and suggestions.
1-In TCP detecting that the other side has silently disconnected it very difficult if not impossible. A client could disconnect sending a RST TCP message to the server or sending a FIN message, this is the good case. Sometimes the client can disconnect without notice (crash, cable disconnection, etc).

*

*One suggestion here is that you consider the way client and server will communicate. For example, you can use function "select" to set a timeout for receiving a message from client and detect a silent client.

*Additionally, depending on the programming language and operating system you may need to handle broken pipe (SIGPIPE) signal (in Linux, with C/C++), for a server trying to send a message through a connection closed by the client.
2-Regarding semaphores, you shouldn't need to clean semaphores in any especial way when a client disconnect. By applying common good practices of locking and unlocking mutexes should be enough. Also with resources like file descriptors, you need to release them before ending the thread either by returning from the thread start function or with pthread_exit. Maybe I didn't understand this part of the question.
3-Regarding threads: if you work with multiple threads to optimum is to have a pool of pre-created consumer/worker threads that will check the circular buffer to consume the next available connection. Creating and destroying threads is costly for the operating system.

*

*Threads are resource consuming and you may exhaust operating system resources if you need to create 1,000 threads for example.

*Another alternative, is to have only one consumer thread that manages all connections (sockets) asynchronously: a) Each connection has its own state. b) The main thread goes through all connections and use function "select" to detect when connection reads or a writes are ready. 3)Use of non-blocking sockets but this is not essential because from select you know which sockets are ready and will not block.

*You can use functions select, poll, epoll.
One link about select and non-blocking sockets: Using select() for non-blocking sockets
Other link with an example: http://linux.die.net/man/2/select


text:
Q: What is this device and what does it do? I have this device here and I do not know what it is or what it is used for. I literally found it on the ground of a store parking lot.
I've attempted to research the item and I think it is a tool used for debugging. I also have not a clue what debugging is in even a slight sense.
Some characteristics:

*

*It has 2 connectors

*

*One connector is a standard android jack

*The other is a 20 pin jack

*It has 1 button

Any info on this device is appreciated.

A: Maybe a controller/voice box for advertising displays.
Or maybe it's a virus vector for a worm transmitted via the USB port when you plug it into your computer.

A: It's a steering wheel control box for the stereo so you can retain steering wheel controls buttons with aftermarket stereo

A: I'm pretty sure it's a Bluetooth transmitter for your phone to your car radio. It comes with a wiring harness kit from Walmart for your car radio.


text:
Q: what is sync_extras_upload used for? Within the ContentResolver class, there are several constants that are used for syncadpaters. I want to know what the constant SYNC_EXTRAS_UPLOAD is used for?

A: If you check in the SyncManager.java file you find this comment:

If the ContentResolver.SYNC_EXTRAS_UPLOAD boolean in extras is
       * true then initiate a sync that just checks for local changes to send
       * to the server, otherwise initiate a sync that first gets any
       * changes from the server before sending local changes back to
       * the server.

and from the same file this is the implementation of the scheduleLocalSync API
public void scheduleLocalSync(Account account, String authority) {
    final Bundle extras = new Bundle();
    extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, true);
    scheduleSync(account, authority, extras, LOCAL_SYNC_DELAY,
            false /* onlyThoseWithUnkownSyncableState */);
}

The method onPerformSyncof your syncadapter receives those extras as one of the paramters