text:
Q: node JS firebase post to PHP I'm using Firebase functions and need to make a POST to a PHP page. I have the paid version of Firebase in which Cloud Functions theoretically supports this. The call is happening + not throwing an error, but it also doesn't do what it ought to. I've tried all of the things which are currently commented out, and none of them appear to be doing what I want. I am not attached to any of the solutions, just need the post to actually work.
const functions = require('firebase-functions');

const request = require('request');

// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

const cheerio = require('cheerio');
const $ = cheerio.load();

exports.sendClientData = functions.database.ref('/clients').onWrite((event) => {

  /*
  const original = event.data.val();

  const options = {
    url: "http://test.weblinxteam.com/index.php",
    json: {
      data: {
        submit: {
          name: "new name"
        },
        name: "test"
      },
    }
  }
  request({
    uri: "http://example/index.php",
    method: "POST",
    body: JSON.stringify({
      submit: {
        name: "test"
      },
      name: "test"
    }),
  }, function(a, s, d) {
    console.log("response is");
    console.log(a, s, d);
  });
  */

  $.ajax({
    type: 'POST',
    url: "http://example/index.php",
    data: {
      submit: {
        name: "test"
      },
      name: "test"
    },
    success: function() {
      console.log("deed it");
    },
    error: function(xhr, status, error) {
      console.log(xhr, status, error);
    }
  });

});

EDIT:
I know the exact $.ajax call there works and does what I want, as simply running it in a browser on any site with jquery produces the desired result.
Edit 2:
I get the following response in firebase console from the log when I use the request version, I am not sure how to interpret it. I know it appears cut off, this is the entirety of what appears.
5:08:05.111 PM
info
sendClientData
null IncomingMessage { _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: BufferList { head: null, tail: null, length: 0 }, length: 0, pipes: null, pipesCount: 0, flowing: true, ended: true, endEmitted: true, reading: false, sync: true, needReadable: false, emittedReadable: false, readableListening: false, resumeScheduled: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: false, domain: null, _events: { end: [ [Function: responseOnEnd], [Function] ], close: [ [Function], [Function] ], data: [Function], error: [Function] }, _eventsCount: 4, _maxListeners: undefined, socket: Socket { connecting: false, _hadError: false, _handle: null, _parent: null, _host: 'test.weblinxteam.com', _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: [Object], length: 0, pipes: null, pipesCount: 0, flowing: true, ended: false, endEmitted: false, reading: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, resumeScheduled: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: false, domain: null, _events: { end: [Object], finish: [Function: onSocketFinish], _socketEnd: [Function: onSocketEnd], free: [Function: onFree], close: [Object], agentRemove: [Function: onRemove], drain: [Function: ondrain], error: [Function: socketErrorListener] }, _eventsCount: 8, _maxListeners: undefined, _writableState: WritableState { objectMode: false, highWaterMark: 16384, needDrain: false, ending: true, ended: true, finished: true, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, corked: 0, sync: false, bufferProcessing: false, onwrite: [Function], writecb: null, writelen: 0, bufferedRequest: null, lastBufferedRequest: null, pendingcb: 0, prefinished: true, errorEmitted: false, bufferedRequestCount: 0, corkedRequestsFree: [Object] }, writable: false, allowHalfOpen: false, destroyed: true, _bytesDispatched: 173, _sockname: null, _pendingData: null, _pendingEncoding: '', server: null, _server: null, parser: null, _httpMessage: ClientRequest { domain: null, _events: [Object], _eventsCount: 5, _maxListeners: undefined, output: [], outputEncodings: [], outputCallbacks: [], outputSize: 0, writable: true, _last: true, upgrading: false, chunkedEncoding: false, shouldKeepAlive: false, useChunkedEncodingByDefault: true, sendDate: false, _removedHeader: [Object], _contentLength: null, _hasBody: true, _trailer: '', finished: true, _headerSent: true, socket: [Circular], connection: [Circular], _header: 'POST /index.php HTTP/1.1\r\nX-Requested-With: XMLHttpRequest\r\nhost: test.weblinxteam.com\r\ncontent-length: 44\r\nConnection: close\r\n\r\n', _headers: [Object], _headerNames: [Object], _onPendingData: null, agent: [Object], socketPath: undefined, timeout: undefined, method: 'POST', path: '/index.php', _ended: true, parser: null, res: [Circular] }, read: [Function], _consuming: true, _idleNext: null, _idlePrev: null, _idleTimeout: -1 }, connection: Socket { connecting: false, _hadError: false, _handle: null, _parent: null, _host: 'test.weblinxteam.com', _readableState: ReadableState { objectMode: false, highWaterMark: 16384, buffer: [Object], length: 0, pipes: null, pipesCount: 0, flowing: true, ended: false, endEmitted: false, reading: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, resumeScheduled: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: false, domain: null, _events: { end: [Object], finish: [Function: onSocketFinish], _socketEnd: [Function: onSoc
 null IncomingMessage {
  _readableState:
   ReadableState {
     objectMode: false,
     highWaterMark: 16384,
     buffer: BufferList { head: null, tail: null, length: 0 },
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: true,
     ended: true,
     endEmitted: true,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     defaultEncoding: 'utf8',
     ranOut: false,
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: false,
  domain: null,
  _events:
   { end: [ [Function: responseOnEnd], [Function] ],
     close: [ [Function], [Function] ],
     data: [Function],
     error: [Function] },
  _eventsCount: 4,
  _maxListeners: undefined,
  socket:
   Socket {
     connecting: false,
     _hadError: false,
     _handle: null,
     _parent: null,
     _host: 'test.weblinxteam.com',
     _readableState:
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [Object],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: false,
     domain: null,
     _events:
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        free: [Function: onFree],
        close: [Object],
        agentRemove: [Function: onRemove],
        drain: [Function: ondrain],
        error: [Function: socketErrorListener] },
     _eventsCount: 8,
     _maxListeners: undefined,
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        needDrain: false,
        ending: true,
        ended: true,
        finished: true,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: true,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: false,
     allowHalfOpen: false,
     destroyed: true,
     _bytesDispatched: 173,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: null,
     _server: null,
     parser: null,
     _httpMessage:
      ClientRequest {
        domain: null,
        _events: [Object],
        _eventsCount: 5,
        _maxListeners: undefined,
        output: [],
        outputEncodings: [],
        outputCallbacks: [],
        outputSize: 0,
        writable: true,
        _last: true,
        upgrading: false,
        chunkedEncoding: false,
        shouldKeepAlive: false,
        useChunkedEncodingByDefault: true,
        sendDate: false,
        _removedHeader: [Object],
        _contentLength: null,
        _hasBody: true,
        _trailer: '',
        finished: true,
        _headerSent: true,
        socket: [Circular],
        connection: [Circular],
        _header: 'POST /index.php HTTP/1.1\r\nX-Requested-With: XMLHttpRequest\r\nhost: test.weblinxteam.com\r\ncontent-length: 44\r\nConnection: close\r\n\r\n',
        _headers: [Object],
        _headerNames: [Object],
        _onPendingData: null,
        agent: [Object],
        socketPath: undefined,
        timeout: undefined,
        method: 'POST',
        path: '/index.php',
        _ended: true,
        parser: null,
        res: [Circular] },
     read: [Function],
     _consuming: true,
     _idleNext: null,
     _idlePrev: null,
     _idleTimeout: -1 },
  connection:
   Socket {
     connecting: false,
     _hadError: false,
     _handle: null,
     _parent: null,
     _host: 'test.weblinxteam.com',
     _readableState:
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [Object],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: false,
     domain: null,
     _events:
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSoc

Edit 3:
Thanks guys for the responses. I'm not sure exactly what the difference was, but this:
request.post('http://sample.com/index.php', {form:{submit:'value',name:"test"}});
did exactly what I wanted.


text:
Q: GeoTIFF compression on GeoServer I'm using GeoServer to provide maps generated from raster data (satellite imagery from Sentinel) to a web application via WMS layers.
Each raster consists of a file of about 1.8-2 gb. To save space on disk I tried to apply a gdal_translate using some compression algorithms.
I tried a simple gdal_translate -of GTiff -co "COMPRESS=JPEG" infile.tif outfile.tif.
Input GTiff file is obtained by extracting RGB band from the L2A source. Using JPEG compression each file reduces the dimensions to less than 500 mb.
Testing the web application (built using OpenLayers) I noticed a marked deterioration of performance in terms of speed and responsiveness.
Is the problem due to the computation required to GeoServer to process a compressed file? Is there a better solution among the compression methods provided by GDAL or the best possible performance requires a non-compressed raster?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Swift3 round two corners of UIView I know this question already asked so many times and their solutions also available but nothing works for me.
I am using Swift3 and I want to round any two sides of UIView for this purpose I found the following solution
Create a rectangle with just two rounded corners in swift?
and following is my code snippet of the above solution
extension UIView {

    /**
     Rounds the given set of corners to the specified radius

     - parameter corners: Corners to round
     - parameter radius:  Radius to round to
     */
    func round(corners: UIRectCorner, radius: CGFloat) -> Void {
         layer.addSublayer(_round(corners: corners, radius: radius))
    }

    /**
     Rounds the given set of corners to the specified radius with a border

     - parameter corners:     Corners to round
     - parameter radius:      Radius to round to
     - parameter borderColor: The border color
     - parameter borderWidth: The border width
     */
    func round(corners: UIRectCorner, radius: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
        let mask = _round(corners: corners, radius: radius)
        addBorder(mask: mask, borderColor: borderColor, borderWidth: borderWidth)
    }

    /**
     Fully rounds an autolayout view (e.g. one with no known frame) with the given diameter and border

     - parameter diameter:    The view's diameter
     - parameter borderColor: The border color
     - parameter borderWidth: The border width
     */
    func fullyRound(diameter: CGFloat, borderColor: UIColor, borderWidth: CGFloat) {
        layer.masksToBounds = true
        layer.cornerRadius = diameter / 2
        layer.borderWidth = borderWidth
        layer.borderColor = borderColor.cgColor;
    }

}

private extension UIView {

    func _round(corners: UIRectCorner, radius: CGFloat) -> CAShapeLayer {
        let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
        let mask = CAShapeLayer()
        mask.path = path.cgPath
        self.layer.mask = mask
        return mask
    }

    func addBorder(mask: CAShapeLayer, borderColor: UIColor, borderWidth: CGFloat) {
        let borderLayer = CAShapeLayer()
        borderLayer.path = mask.path
        borderLayer.fillColor = UIColor.clear.cgColor
        borderLayer.strokeColor = borderColor.cgColor
        borderLayer.lineWidth = borderWidth
        borderLayer.frame = bounds
        layer.addSublayer(borderLayer)
    }

}

This is the result I got. I don't know what I am doing wrong.
Can anyone please solve this?

A: Code tested and worked in Swift 3.
Use below extension to create roundCorners.
extension UIView {
func roundCorners(corners:UIRectCorner, radius: CGFloat) {
    let path = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
    let mask = CAShapeLayer()
    mask.path = path.cgPath
    self.layer.mask = mask
}
}

Usage: in viewDidLoad
yourViewName.roundCorners(corners: [.topRight, .bottomLeft], radius: 10)

Output:

A: First of all you will need to Make IBOutlet for that Textfield or Button which you
need to Be Rounded Corner

*

*Go to The ViewDidLoad() Method

*Write the name of IBOutLet

*Example Code mybutton.layer.cornerRadius=10

*Here is the Solution to Your Problem


text:
Q: Restrict permission levels change on SP2016 We are farm administrators of a SP2016 enterprise on-premise farm. We added some power users to "XXXX Owners" SP group which have "Contribute" permission. "XXXX Owners" is the group owner for all respective SP groups so that the power users can assign other users into different SP groups themselves.
However I would like to restrict them from modifying or adding Permission Levels to prevent them from changing SP groups' permission level to "Full Control". How can I do it?

A: If they are granted with permission to assign other users into different SP groups, they can modify permission levels.

Reference: https://docs.microsoft.com/en-us/sharepoint/sites/user-permissions-and-permission-levels


text:
Q: HashSet.RemoveWhere() and GetHashCode() Aloha,
Here's a simple class that overrides GetHashCode:
class OverridesGetHashCode
{
    public string Text { get; set; }

    public override int GetHashCode()
    {
        return (Text != null ? Text.GetHashCode() : 0);
    }
    // overriding Equals() doesn't change anything, so I'll leave it out for brevity
}

When I create an instance of that class, add it to a HashSet and then change its Text property, like this:
var hashset = new HashSet<OverridesGetHashCode>();
var oghc = new OverridesGetHashCode { Text = "1" };
hashset.Add(oghc);
oghc.Text = "2";

then this doesn't work:
var removedCount = hashset.RemoveWhere(c => ReferenceEquals(c, oghc));
// fails, nothing is removed
Assert.IsTrue(removedCount == 1);

and neither does this:
// this line works, i.e. it does find a single item matching the predicate
var existing = hashset.Single(c => ReferenceEquals(c, oghc));
// but this fails; nothing is removed again
var removed = hashset.Remove(existing);
Assert.IsTrue(removed);

I guess the hash it internally uses is generated when item is inserted and, if that's true, it's
understandable that hashset.Contains(oghc) doesn't work.
I also guess it looks up item by its hash code and if it finds a match, only then it checks the predicate, and that might be why the first test fails (again, I'm just guessing here).
But why does the last test fail, I just got that object out of the hashset? Am I missing something, is this a wrong way to remove something from a HashSet?
Thank you for taking the time to read this.
UPDATE: To avoid confusion, here's the Equals():
protected bool Equals(OverridesGetHashCode other)
    {
        return string.Equals(Text, other.Text);
    }

public override bool Equals(object obj)
    {
        if (ReferenceEquals(null, obj)) return false;
        if (ReferenceEquals(this, obj)) return true;
        if (obj.GetType() != this.GetType()) return false;
        return Equals((OverridesGetHashCode) obj);
    }

A: By changing the hash code of your object while that object is being used in a HashSet is a violation of the HashSet's contract.
Being unable to remove the object is not the problem here. You are not allowed to change the hash code in the first place.
Let me quote from MSDN:

The GetHashCode method for an object must consistently return the same
  hash code as long as there is no modification to the object state that
  determines the return value of the object's Equals method. Note that
  this is true only for the current execution of an application, and
  that a different hash code can be returned if the application is run
  again.

They tell the story a little differently but the essence is the same. They say, the hash code can never change. In practice, you can change it as long as you make sure no one uses the old hash code anymore. Not that this is good practice, but it works.

A: It's important that any items added to a hash based table (HashSet, Dictionary, etc.) not be modified once they are inserted into the structure (at least not until they are removed).
To find an object in the data structure it computes it hash code, and then finds a location based on that hash code.  If you mutate that object then the hash code it returns no longer reflects it's current location in that data structure (unless you're very, very lucky and it just happens to be a hash collision).
On the MSDN page for Dictionary is says:

As long as an object is used as a key in the Dictionary<TKey, TValue>, it must not change in any way that affects its hash value.

This same assertion applies to HashSet as well, as they both are implemented using hash tables.

A: There are good answers here and just wanted to add this. If you look at the decompiled HashSet<T> code, you'll see that Add(value) does the following:

*

*Calls IEqualityComparer<T>.GetHashCode() to get the hash code for value. For the default comparer this boils down to GetHashCode().

*Uses that hash code to calculate which "bucket" and "slot" the (reference to) value should be stored in.

*Stores the reference.

When you call Remove(value) it does steps 1. and 2. again, to find where the reference is at. Then it calls IEqualityComparer<T>.Equals() to make sure that it indeed has found the right value. However, since you've changed what GetHashCode() returns, it calculates a different bucket/slot location, which is invalid. Thus, it cannot find the object.
So, note that Equals() doesn't really come into play here, because it will never even get to the right bucket/slot location if the hash code changes.


text:
Q: WFLYEE0047: Incompatible conflicting binding at Got wired exception for very simple EJB with @Remote annotated interface in time of deploy to WildFly 17.0.1.Final
@Stateless
public class UserServiceImpl implements UserServiceRemote {

   @Override
   public List<UserRepr> getAllUsers() {
      return null;
   }
}

@Remote
public interface UserServiceRemote {

    List<UserRepr> getAllUsers();
}

The exception is
Caused by: java.lang.IllegalArgumentException: WFLYEE0047: Incompatible conflicting binding at java:jboss/exported/simple-webapp/UserServiceImpl!ru.geekbrains.jsf.UserServiceRemote source: org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor$2@6aba1c4b"},
    "WFLYCTL0412: Required services that are not installed:" => [
        "jboss.deployment.unit.\"simple-webapp.war\".beanmanager",
        "jboss.deployment.unit.\"simple-webapp.war\".WeldStartService"
    ],
    "WFLYCTL0180: Services with missing/unavailable dependencies" => [
        "jboss.deployment.unit.\"simple-webapp.war\".batch.artifact.factory is missing [jboss.deployment.unit.\"simple-webapp.war\".beanmanager]",
        "jboss.deployment.unit.\"simple-webapp.war\".weld.weldClassIntrospector is missing [jboss.deployment.unit.\"simple-webapp.war\".beanmanager, jboss.deployment.unit.\"simple-webapp.war\".WeldStartService]"
    ]
}

Could you help with some common explanation of what could be wrong here? Which bindings are conflicting?
At least what the meaning of this kind of exception? I don't know how to interpret it.
UPD. If I rename UserServiceImpl to UserServiseRemImpl it works. WTH is here?))))
UPD. Fragment from server logs with this exception
17:58:33,380 INFO  [org.jboss.as.jpa] (MSC service thread 1-5) WFLYJPA0002: Read persistence.xml for ds
17:58:33,451 INFO  [org.jboss.weld.deployer] (MSC service thread 1-1) WFLYWELD0003: Processing weld deployment simple-webapp.war
17:58:33,489 INFO  [org.jboss.as.ejb3.deployment] (MSC service thread 1-1) WFLYEJB0473: JNDI bindings for session bean named 'UserRepository' in deployment unit 'deployment "simple-webapp.war"' are as follows:

    java:global/simple-webapp/UserRepository!ru.geekbrains.persist.UserRepository
    java:app/simple-webapp/UserRepository!ru.geekbrains.persist.UserRepository
    java:module/UserRepository!ru.geekbrains.persist.UserRepository
    ejb:/simple-webapp/UserRepository!ru.geekbrains.persist.UserRepository
    java:global/simple-webapp/UserRepository
    java:app/simple-webapp/UserRepository
    java:module/UserRepository

17:58:33,489 INFO  [org.jboss.as.ejb3.deployment] (MSC service thread 1-1) WFLYEJB0473: JNDI bindings for session bean named 'RoleService' in deployment unit 'deployment "simple-webapp.war"' are as follows:

    java:global/simple-webapp/RoleService!ru.geekbrains.jsf.RoleService
    java:app/simple-webapp/RoleService!ru.geekbrains.jsf.RoleService
    java:module/RoleService!ru.geekbrains.jsf.RoleService
    ejb:/simple-webapp/RoleService!ru.geekbrains.jsf.RoleService
    java:global/simple-webapp/RoleService
    java:app/simple-webapp/RoleService
    java:module/RoleService

17:58:33,491 INFO  [org.jboss.as.jpa] (ServerService Thread Pool -- 379) WFLYJPA0010: Starting Persistence Unit (phase 1 of 2) Service 'simple-webapp.war#ds'
17:58:33,497 INFO  [org.jboss.as.ejb3.deployment] (MSC service thread 1-1) WFLYEJB0473: JNDI bindings for session bean named 'UserServiceImpl' in deployment unit 'deployment "simple-webapp.war"' are as follows:

    java:global/simple-webapp/UserServiceImpl!ru.geekbrains.jsf.UserServiceLocal
    java:app/simple-webapp/UserServiceImpl!ru.geekbrains.jsf.UserServiceLocal
    java:module/UserServiceImpl!ru.geekbrains.jsf.UserServiceLocal
    ejb:/simple-webapp/UserServiceImpl!ru.geekbrains.jsf.UserServiceLocal
    java:global/simple-webapp/UserServiceImpl!ru.geekbrains.jsf.UserServiceRemote
    java:app/simple-webapp/UserServiceImpl!ru.geekbrains.jsf.UserServiceRemote
    java:module/UserServiceImpl!ru.geekbrains.jsf.UserServiceRemote
    java:jboss/exported/simple-webapp/UserServiceImpl!ru.geekbrains.jsf.UserServiceRemote
    ejb:/simple-webapp/UserServiceImpl!ru.geekbrains.jsf.UserServiceRemote

17:58:33,497 INFO  [org.hibernate.jpa.internal.util.LogHelper] (ServerService Thread Pool -- 379) HHH000204: Processing PersistenceUnitInfo [
    name: ds
    ...]
17:58:33,577 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-5) MSC000001: Failed to start service jboss.deployment.unit."simple-webapp.war".INSTALL: org.jboss.msc.service.StartException in service jboss.deployment.unit."simple-webapp.war".INSTALL: WFLYSRV0153: Failed to process phase INSTALL of deployment "simple-webapp.war"
    at org.jboss.as.server@9.0.2.Final//org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:183)
    at org.jboss.msc@1.4.8.Final//org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1737)
    at org.jboss.msc@1.4.8.Final//org.jboss.msc.service.ServiceControllerImpl$StartTask.execute(ServiceControllerImpl.java:1699)
    at org.jboss.msc@1.4.8.Final//org.jboss.msc.service.ServiceControllerImpl$ControllerTask.run(ServiceControllerImpl.java:1557)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: java.lang.IllegalArgumentException: WFLYEE0047: Incompatible conflicting binding at java:jboss/exported/simple-webapp/UserServiceImpl!ru.geekbrains.jsf.UserServiceRemote source: org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor$2@73fbe2f8
    at org.jboss.as.ee@17.0.1.Final//org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor.addJndiBinding(ModuleJndiBindingProcessor.java:298)
    at org.jboss.as.ee@17.0.1.Final//org.jboss.as.ee.component.deployers.ModuleJndiBindingProcessor.deploy(ModuleJndiBindingProcessor.java:122)
    at org.jboss.as.server@9.0.2.Final//org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:176)
    ... 8 more

17:58:33,579 ERROR [org.jboss.as.controller.management-operation] (management-handler-thread - 12) WFLYCTL0013: Operation ("full-replace-deployment") failed - address: ([]) - failure description: {
    "WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"simple-webapp.war\".INSTALL" => "WFLYSRV0153: Failed to process phase INSTALL of deployment \"simple-webapp.war\"
    Caused by: java.lang.IllegalArgumentException: WFLYEE0047: Incompatible conflicting binding at java:jboss/exported/simple-webapp/UserServiceImpl!ru.geekbrains.jsf.UserServiceRemote source: org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor$2@73fbe2f8"},
    "WFLYCTL0412: Required services that are not installed:" => [
        "jboss.deployment.unit.\"simple-webapp.war\".beanmanager",
        "jboss.deployment.unit.\"simple-webapp.war\".WeldStartService"
    ],
    "WFLYCTL0180: Services with missing/unavailable dependencies" => [
        "jboss.deployment.unit.\"simple-webapp.war\".weld.weldClassIntrospector is missing [jboss.deployment.unit.\"simple-webapp.war\".beanmanager, jboss.deployment.unit.\"simple-webapp.war\".WeldStartService]",
        "jboss.deployment.unit.\"simple-webapp.war\".batch.artifact.factory is missing [jboss.deployment.unit.\"simple-webapp.war\".beanmanager]"
    ]
}
17:58:33,579 INFO  [org.jboss.as.jpa] (ServerService Thread Pool -- 379) WFLYJPA0011: Stopping Persistence Unit (phase 1 of 2) Service 'simple-webapp.war#ds'
17:58:33,592 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-6) WFLYSRV0028: Stopped deployment simple-webapp.war (runtime-name: simple-webapp.war) in 12ms
17:58:33,593 ERROR [org.jboss.as.server] (management-handler-thread - 12) WFLYSRV0014: Replacement of deployment "simple-webapp.war" by deployment "simple-webapp.war" was rolled back with the following failure message:
{
    "WFLYCTL0080: Failed services" => {"jboss.deployment.unit.\"simple-webapp.war\".INSTALL" => "WFLYSRV0153: Failed to process phase INSTALL of deployment \"simple-webapp.war\"
    Caused by: java.lang.IllegalArgumentException: WFLYEE0047: Incompatible conflicting binding at java:jboss/exported/simple-webapp/UserServiceImpl!ru.geekbrains.jsf.UserServiceRemote source: org.jboss.as.ejb3.deployment.processors.EjbJndiBindingsDeploymentUnitProcessor$2@73fbe2f8"},
    "WFLYCTL0412: Required services that are not installed:" => [
        "jboss.deployment.unit.\"simple-webapp.war\".beanmanager",
        "jboss.deployment.unit.\"simple-webapp.war\".WeldStartService"
    ],
    "WFLYCTL0180: Services with missing/unavailable dependencies" => [
        "jboss.deployment.unit.\"simple-webapp.war\".weld.weldClassIntrospector is missing [jboss.deployment.unit.\"simple-webapp.war\".beanmanager, jboss.deployment.unit.\"simple-webapp.war\".WeldStartService]",
        "jboss.deployment.unit.\"simple-webapp.war\".batch.artifact.factory is missing [jboss.deployment.unit.\"simple-webapp.war\".beanmanager]"
    ]
}
17:58:33,593 INFO  [org.jboss.as.server.deployment] (MSC service thread 1-2) WFLYSRV0027: Starting deployment of "simple-webapp.war" (runtime-name: "simple-webapp.war")
17:58:34,214 INFO  [org.jboss.as.jpa] (MSC service thread 1-1) WFLYJPA0002: Read persistence.xml for ds
17:58:34,235 INFO  [org.jboss.weld.deployer] (MSC service thread 1-7) WFLYWELD0003: Processing weld deployment simple-webapp.war
17:58:34,239 INFO  [org.jboss.as.jpa] (ServerService Thread Pool -- 379) WFLYJPA0010: Starting Persistence Unit (phase 1 of 2) Service 'simple-webapp.war#ds'
17:58:34,239 INFO  [org.hibernate.jpa.internal.util.LogHelper] (ServerService Thread Pool -- 379) HHH000204: Processing PersistenceUnitInfo [
    name: ds
    ...]
17:58:34,260 INFO  [org.jboss.as.ejb3.deployment] (MSC service thread 1-7) WFLYEJB0473: JNDI bindings for session bean named 'UserServiceBean' in deployment unit 'deployment "simple-webapp.war"' are as follows:

    java:global/simple-webapp/UserServiceBean!ru.geekbrains.jsf.UserServiceLocalBean
    java:app/simple-webapp/UserServiceBean!ru.geekbrains.jsf.UserServiceLocalBean
    java:module/UserServiceBean!ru.geekbrains.jsf.UserServiceLocalBean
    ejb:/simple-webapp/UserServiceBean!ru.geekbrains.jsf.UserServiceLocalBean
    java:global/simple-webapp/UserServiceBean!ru.geekbrains.jsf.UserServiceRemoteBean
    java:app/simple-webapp/UserServiceBean!ru.geekbrains.jsf.UserServiceRemoteBean
    java:module/UserServiceBean!ru.geekbrains.jsf.UserServiceRemoteBean
    java:jboss/exported/simple-webapp/UserServiceBean!ru.geekbrains.jsf.UserServiceRemoteBean
    ejb:/simple-webapp/UserServiceBean!ru.geekbrains.jsf.UserServiceRemoteBean

17:58:34,260 INFO  [org.jboss.as.ejb3.deployment] (MSC service thread 1-7) WFLYEJB0473: JNDI bindings for session bean named 'UserRepository' in deployment unit 'deployment "simple-webapp.war"' are as follows:

    java:global/simple-webapp/UserRepository!ru.geekbrains.persist.UserRepository
    java:app/simple-webapp/UserRepository!ru.geekbrains.persist.UserRepository
    java:module/UserRepository!ru.geekbrains.persist.UserRepository
    ejb:/simple-webapp/UserRepository!ru.geekbrains.persist.UserRepository
    java:global/simple-webapp/UserRepository
    java:app/simple-webapp/UserRepository
    java:module/UserRepository

17:58:34,260 INFO  [org.jboss.as.ejb3.deployment] (MSC service thread 1-7) WFLYEJB0473: JNDI bindings for session bean named 'RoleService' in deployment unit 'deployment "simple-webapp.war"' are as follows:

    java:global/simple-webapp/RoleService!ru.geekbrains.jsf.RoleService
    java:app/simple-webapp/RoleService!ru.geekbrains.jsf.RoleService
    java:module/RoleService!ru.geekbrains.jsf.RoleService
    ejb:/simple-webapp/RoleService!ru.geekbrains.jsf.RoleService
    java:global/simple-webapp/RoleService
    java:app/simple-webapp/RoleService
    java:module/RoleService

17:58:34,322 INFO  [org.jboss.as.connector.deployers.jdbc] (MSC service thread 1-3) WFLYJCA0005: Deploying non-JDBC-compliant driver class com.mysql.cj.jdbc.Driver (version 8.0)

A: I had this situation and I solved it by deleting TMP and DATA folders from ../wildfly_path/myApp/ folder and then restart myApp.

A: I was facing a similar issue where I was running into
"Caused by: java.lang.IllegalArgumentException: WFLYEE0047: Incompatible conflicting binding at" exception
I have my Session EJBs packaged in separate ejb artifact. I used the maven-ejb-plugin in ejb artifact POM.xml file:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-ejb-plugin</artifactId>
    <configuration>
      <ejbVersion>3.0</ejbVersion>
      <generateClient>true</generateClient>
      <clientExcludes>
        <clientExclude>**/*Bean.class</clientExclude>
      </clientExcludes>
    </configuration>
  </plugin>

In your case, you can try out:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-ejb-plugin</artifactId>
    <configuration>
      <ejbVersion>3.0</ejbVersion>
      <generateClient>true</generateClient>
      <clientExcludes>
        <clientExclude>**/*Impl.class</clientExclude>
      </clientExcludes>
    </configuration>
  </plugin>

A: I just encounter the same issue today:
Incompatible conflicting binding at java:jboss/exported/cloud/billing/CsOt125SkuProfileServiceImplRemote source
After removing the lib from the Artifacts war, and redeploy it works well!

A: I've the same issue with Wildfly 16.
I'am merging two library version and I forgot to copy an implementation of an interface.
For instance I've Packet_interface with AInterface and Packet_EJB with AImplementation. In BImplementation I use AInterface.
I forgot to copy AImplementation during merge.
The first launch of the application say:
not found a class implementing AInterface, used in BImplementation

I copy the forgotten clas, compile the EAR and deploy.
Now the error is
Caused by: java.lang.IllegalArgumentException: WFLYEE0047: Incompatible conflicting binding at ... refer to another EJB randomly

If i restart and redeploy the EAR, it say that i forgot CImplementation.
So, if you forgot a class or you have an unimplemented interface, correct the problem and restart wildfly.

A: In my case, it arose from inconsistencies around the declared db name in the service beans.
Resolve these discrepancies and restart jboss wildfly. The .ear should install.


text:
Q: laravel 5.5 Necesito incluir una variable dentro de un array tipo json Necesito incluir $token dentro del array $user en donde guardo mi consulta, estoy usando el framework laravel 5.5
 protected function respondWithToken($token,$documento){
    $user = User::select('id','nombre','email')->where('documento', $documento)->get();

     $token =  [
         'access_token' => $token,
         'token_type' => 'bearer'
     ];

    return $user;

}

Se que puedo juntar y concatenar dentro de una función array pero quedaría así, y no es la manera que busco. Deseo incluirlo dentro de un solo array.
{
    "user": [
        {
            "id": 2,
            "nombre": "Pedro",
            "email": "Gonzalez@gmail.com"
        }
    ],
    "token": "sfgt854dfgdf54dfg5df4gdf98g4df",
    "token_type": "bearer"
}

necesito incluir esa variable token dentro de mi objeto y retorne un json de esta manera
[
    {
        "id": 2,
        "nombre": "Pedro",
        "email": "Gonzalez@gmail.com",
        "token": "sdjkfhsdk65468541sdf3"

    }
]

A: Hola para ese tipo de casos es bueno usar compact
protected function respondWithToken($token,$documento){
    $user = User::select('id','nombre','email')->where('documento', $documento)->get();
    $token_type = 'bearer';
    $conjunto_variables = compact('user','token','token_type ');

    return $conjunto_variables ;

}

Que hace compact?

Bueno compact en términos simples crea un array con variables y sus valores, es muy útil si quieres enviar muchas variables a la vez y poder llamarlas en la vista o donde la retornas.
Su funcionamiento se basa principalmente en que el nombre de la variable queda como llave para llamarlo. Ejemplo: en tu compact hice que que user es el nombre de tu variable , bueno con ese mismo nombre la puedes llamar en otra parte así $user ,ya que lo retorné en ese compact y lo mismo puedo hacer con el resto de las variables.

PD: para que funcione el compact tiene que estar entre comillas y
  tener en nombre de la variable no otra. Espero te sirva .Saludos!.

A:     $user = User::select('id','nombre','email')->where('documento', $documento)->first()->toArray();
//first en vez de get

     $token =  [
         'access_token' => $token,
         'token_type' => 'bearer'
     ];

    return json_encode($user + $token);

Gracias a adolfo abegg jajaja

A: Me parece que lo mas sencillo es añadir el indice que quieres al array $user:
$user['token'] = $token['access_token']

En el caso de que $user sea un array, siempre puedes acceder al primer elemento (entiendo que aunque sea un array solo estas buscando un usuario) y hacer lo mismo:
$user[0]['token'] = $token['access_token']


text:
Q: Deleting environment variables doesn't work Why deleting an environment variable with reg delete HKCU\Environment /F /V TestVar in Windows 7 Professional removes it from the registry, but the variable still exists?
Here are the details: I created the following 3 .cmd files:
Check variable.cmd
echo TestVar = %TestVar%
pause

Set variable.cmd
setx TestVar 123
pause

Delete variable.cmd
reg delete HKCU\Environment /F /V TestVar
pause

Then I follow these steps (double clicking to make sure that I start a new session every time):

*

*Double click on Check variable.cmd and I see that TestVar does not exist

*Double click on Set variable.cmd and it says SUCCESS: Specified value was saved.

*Double click on Check variable.cmd and it shows the variable value. Good!

*Double click on Delete variable.cmd and it says The operation completed successfully.

*Double click on Check variable.cmd and it still shows the variable value. Bad!

*Click on the Start menu, type environment, click on Edit environment variables for your account to open the Environment Variables dialog box, click OK without changing anything

*Double click on Check variable.cmd and the variable does not exist anymore

I can find the value in the registry after step 2, I cannot find it after step 4, but step 5 still finds it. And even if I don't change anything, step 6 really deletes the variable.

A: Here is the solution to my problem. I don't know if it is the correct solution, but it works for me:
Check variable.cmd
set TestVar
@pause

Set variable.cmd
setx TestVar 123
@pause

Delete variable.cmd
reg delete HKCU\Environment /F /V TestVar
setx DummyVarUsedToDelete ""
reg delete HKCU\Environment /F /V DummyVarUsedToDelete
@pause

setx cannot be used to delete a variable, as explained here, but it does the missing broadcasting after a variable has been removed from the registry with reg delete.
EDIT
I added a line to delete the DummyVarUsedToDelete from the registry. This will not be broadcasted, but it is a small temporary problem.

A: You can use setx to delete an environment variable, this will broadcast the correct message:
setx TestVar ""
reg delete HKCU\Environment /F /V TestVar

(As discussed in the comments, using setx by itself will leave an empty entry behind in the registry, which should be deleted for the sake of consistency.)

A: The registry is read at boot. When a program is started it gets a copy of it's parent's environment, usually Explorer.exe's environment.
As the comment says, explorer (or any other graphical program that acts on the message) if it gets a message from some other program (like setx) warning it that the registry has been changed, rereads the registry.
The answer is simple
Use set and setx on sequential lines.

A: DELETING SYSTEM PATH VARIABLE
Method 1:
set var = C:\Users\mahidhai\cygwin64\usr\local\bin
REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V var

In my case , it didn't work even though i ran as administrator .
Command prompt displays error registry key not found
In such case go directly to registry keys file
Method2:
Go To register editor .
Run -> regedit
NAvigate to
HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

Edit directly the register key, by clicking on the register key name .
This should work fine
Method 3:
Sometimes not updated windows could be the issue . Check if any updates  available . If so update immediately


text:
Q: Cant download artifacts from gitlab Pls help!
I install gitlab server. And need download artifacts after pipline done.
I genereate Personal Access Tokens from my user profile
and try this:
curl -O --location --header "PRIVATE-TOKEN: 123NU9wDXSy1GFE7tiYF" "http://gitlab.local/cas/v-ui/-/jobs/1533/artifacts"

in output file i see only http text, with registration form.
Where i`m wrong ?

A: as i know this not working, so that i`m solve my problem add pipline step , that copy artifacts by ssh


text:
Q: NPM module or JS code to validate Firebase UIDs I am looking for some code that can generate amd validate a Firebase UID string as having the correct format
https://www.npmjs.com/package/firebase
Does anyone know if that exists? Can't find anything on NPM.


text:
Q: WebResource.axd JavaScript errors I'm getting JavaScript errors on a SharePoint publishing site, just browsing to any page.
In IE the errors are like:
Syntax error: WebResource.axd
Line: 1
Char: 1
Code: 0
URI: http://intranet/WebResource.axd?d=vpxv...

If I view them in the Firefox error console the errors look like:

Error: The stylesheet
  http://intranet/WebResource.axd?d=vpxv...
  was not loaded because its MIME type,
  "text/html", is not "text/css".
Source File: http://intranet/Pages/home.aspx
  Line: 0

(Note: I've truncated the URI of the WebResource.axd in the question here to fit it on the screen.)

A: I figured this out -- basically one of the assemblies I was using didn't have the necessary files embedded as resources.
First I used FireBug to view what was actually being pulled in by the calls to WebResource.aspx.  Rather than the .js and .css files they were supposed to be, they were just pulling in HTML error pages (hence the MIME type error.)
This useful question at StackOverflow links to this article which provides a way to decrypt the encrypted resource identifier in the d parameter of the WebResource.aspx call to determine which assembly is being referred to.
It turns out the assembly in question didn't have some files that were being referenced in the code actually included as embedded resources.


text:
Q: Как Вывести значение, которое дало "true" в "исключающем или" В этом коде предлагается ввести три значения, если два числа из трех равны, то их нужно вывести на экран.  Как понять какое из трех равенств возвратило "true"?
Scanner scanner = new Scanner(System.in);
int a = scanner.nextInt();
int b = scanner.nextInt();
int c = scanner.nextInt();

if ( a==b ^ a==c ^ b==c  ) \\ как понять какое из трех равенств возвратило "true"
    System.out.println(  );

A: Нужно несколько условий
 if ( a==b && a!=c) {
        System.out.println(a);
        System.out.println(b);
    }
    if ( a==c && a!=b) {
        System.out.println(a);
        System.out.println(c);
    }
    if ( c==b && a!=c) {
        System.out.println(b);
        System.out.println(c);
    }

A: Возвращает номер выражения:
public static int XOR(boolean... booleans){
    int trueNumber = -1;

    for(int i = 0; i < booleans.length; i++){
        if(booleans[i]){
            if(trueNumber == -1){
                trueNumber = i + 1;
            } else {
                return -1;
            }
        }
    }

    return trueNumber;
}

Если xor == false, то возвращает -1


text:
Q: $\lim_{n\rightarrow \infty}\int_{(0,1)^n}f\left(\left(\frac1n\sum _{x=1}^n x_i^a\right)^\frac{1}{a}\right)dx_1\cdots dx_n$ Given $x_1, \cdots, x_n>0$, $a\in\mathbb R$ and $f\in C[0,1]$, then can we compute
$$\lim_{n\rightarrow \infty}\int_{(0,1)^n}f\left(\left(\frac1n \sum _{i=1}^n x_i^a\right)^\frac{1}{a}\right)dx_1\cdots dx_n$$
In terms of $f, a$? Any help will be appreciated.

A: Probability theory makes the answer very simple. The limit exists and equals $f((\frac  1 {a+1})^{1/a}) $ at least when $a >-1$.
Let $(U_i)$ be i.i.d random variables uniformly distributed on $(0,1)$. By SLLN $\frac  1n \sum\limits_{k=1}^{n} U_i^{a} \to \int_0^{1} x^{a}dx=\frac 1 {a+1}$ almost surely. Hence the given integral tends to  $f((\frac 1 {a+1})^{1/a})$.


text:
Q: Change colorbar limits without changing the values of the data it represents in scatter I'm trying to change a colorbar attached to a scatter plot so that the minimum and maximum of the colorbar are the minimum and maximum of the data, but I want the data to be centred at zero as I'm using a colormap with white at zero. Here is my example
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 1, 61)
y = np.linspace(0, 1, 61)
C = np.linspace(-10, 50, 61)
M = np.abs(C).max() # used for vmin and vmax

fig, ax = plt.subplots(1, 1, figsize=(5,3), dpi=150)
sc=ax.scatter(x, y, c=C, marker='o', edgecolor='k', vmin=-M, vmax=M, cmap=plt.cm.RdBu_r)
cbar=fig.colorbar(sc, ax=ax, label='$R - R_0$ (mm)')
ax.set_xlabel('x')
ax.set_ylabel('y')

As you can see from the attached figure, the colorbar goes down to -M, where as I want the bar to just go down to -10, but if I let vmin=-10 then the colorbar won't be zerod at white. Normally, setting vmin to +/- M when using contourf the colorbar automatically sorts to how I want. This sort of behaviour is what I expect when contourf uses levels=np.linspace(-M,M,61) rather than setting it with vmin and vmax with levels=62. An example showing the default contourf colorbar behaviour I want in my scatter example is shown below
plt.figure(figsize=(6,5), dpi=150)
plt.contourf(x, x, np.reshape(np.linspace(-10, 50, 61*61), (61,61)),
                   levels=62, vmin=-M, vmax=M, cmap=plt.cm.RdBu_r)
plt.colorbar(label='$R - R_0$ (mm)')

Does anyone have any thoughts? I found this link which I thought might solve the problem, but when executing the cbar.outline.set_ydata line I get this error AttributeError: 'Polygon' object has no attribute 'set_ydata' .
EDIT a little annoyed that someone has closed this question without allowing me to clarify any questions they might have, as none of the proposed solutions are what I'm asking for.
As for Normalize.TwoSlopeNorm, I do not want to rescale the smaller negative side to use the entire colormap range, I just want the colorbar attached to the side of my graph to stop at -10.
This link also does not solve my issue, as it's the TwoSlopeNorm solution again.

A: After changing the ylim of the colorbar, the rectangle formed by the surrounding spines is too large. You can make this outline invisible. And then add a new rectangular border:
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 1, 61)
y = np.linspace(0, 1, 61)
C = np.linspace(-10, 50, 61)
M = np.abs(C).max()  # used for vmin and vmax

fig, ax = plt.subplots(1, 1, figsize=(5, 3), dpi=150)
sc = ax.scatter(x, y, c=C, marker='o', edgecolor='k', vmin=-M, vmax=M, cmap=plt.cm.RdBu_r)
cbar = fig.colorbar(sc, ax=ax, label='$R - R_0$ (mm)')

cb_ymin = C.min()
cb_ymax = C.max()
cb_xmin, cb_xmax = cbar.ax.get_xlim()
cbar.ax.set_ylim(cb_ymin, cb_ymax)
cbar.outline.set_visible(False)  # hide the surrounding spines, which are too large after set_ylim
cbar.ax.add_patch(plt.Rectangle((cb_xmin, cb_ymin), cb_xmax - cb_xmin, cb_ymax - cb_ymin,
                                fc='none', ec='black', clip_on=False))
plt.show()

A: Another approach until v3.5 is released is to make a custom colormap that does what you want (see also https://matplotlib.org/stable/tutorials/colors/colormap-manipulation.html#sphx-glr-tutorials-colors-colormap-manipulation-py)
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap

fig, axs = plt.subplots(2, 1)

X = np.random.randn(32, 32) + 2
pc = axs[0].pcolormesh(X, vmin=-6, vmax=6, cmap='RdBu_r')
fig.colorbar(pc, ax=axs[0])

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.cm as cm
from matplotlib.colors import ListedColormap

fig, axs = plt.subplots(2, 1)

X = np.random.randn(32, 32) + 2
pc = axs[0].pcolormesh(X, vmin=-6, vmax=6, cmap='RdBu_r')
fig.colorbar(pc, ax=axs[0])

def keep_center_colormap(vmin, vmax, center=0):
    vmin = vmin - center
    vmax = vmax - center
    dv = max(-vmin, vmax) * 2
    N = int(256 * dv / (vmax-vmin))
    RdBu_r = cm.get_cmap('RdBu_r', N)
    newcolors = RdBu_r(np.linspace(0, 1, N))
    beg = int((dv / 2 + vmin)*N / dv)
    end = N - int((dv / 2 - vmax)*N / dv)
    newmap = ListedColormap(newcolors[beg:end])
    return newmap

newmap = keep_center_colormap(-2, 6, center=0)
pc = axs[1].pcolormesh(X, vmin=-2, vmax=6, cmap=newmap)
fig.colorbar(pc, ax=axs[1])
plt.show()


text:
Q: Unity - Issue with Android Java JAR inclusion I have included a Java Jar "Assets/Plugins/Android/" however I am not able to use it properly in my Unity App.
I have verified I called into the Jar but the Jar fails.  I have determined it is due to the Jar including a text file in it. When I use this JAR and build via Android Build tools the files are put in "com/name/name/text.file".  In Unity it doesn't unpackage these files from the Jar into the folders like the Android Build tools.
Am I doing something wrong in Unity? Do I need to put the JAR in a different location?

A: Try to place the file at "Assets/Plugins/Android/com/name/name/text.file". If that doesn't work you might be able to use a post-processing build script to open up the .apk file and add the missing file to the appropriate location and then resign and realign it.
http://docs.unity3d.com/Manual/BuildPlayerPipeline.html


text:
Q: Conditioning a voltage using constant current for an ADC range I wish to make a set of temperature measurements inside a relatively inaccessible box.
The measurements can be made using Pt100 sensors - platinum Resistance Temperature Detectors (RTD) with a resistance of \$100\Omega\$ at \$0^{\circ}C\$. The change in resistance over \$80^{\circ}C\$ is around \$30\Omega\$.
I want to digitize this result within the box. I'm currently looking at microcontrollers like this STM32F373 model, which includes (several) 16-bit ADC.
To minimise the self-heating on the RTD, I want to minimise the current used. To make an accurate measurement, I would seem to need a constant current source. Wikipedia suggests several arrangements, at least one of which is given as an answer to this question - Zener Diode Current Source.
How can I go about arranging a known constant current, with only a constant voltage source?
Should I build a circuit similar to the 'Zener Diode' question, separate from any circuitry near the microcontroller, and then just pass the sense leads to the analogue input?
Is there a simple trick to precondition the voltages to lie within a good range for the ADC? Seemingly a combination of gain to scale the range to fit \$V_{DD} = \frac{30\Omega}{I_{const}}\$ along with a constant offset from another circuit would be appropriate - but perhaps this is just because I'm stunningly ignorant.

A: Making a constant-current source is, in principle, very easy if you have a precision voltage source. The basis for conditioning your RTDs is

simulate this circuit – Schematic created using CircuitLab
In this case the current is set by R1, and is equal to V1/R1. The output of the first op amp is equal to the current times the RTD value, but is negative. So op amp 2 is used to invert the signal (assuming you want a positive voltage to the ADC), and this section may have some gain associated with it. R5 is used to provide an offset to compensate for the fact that the RTD does not produce a zero resistance at one end of the useful range.
You'll need to be careful of your resistors. If you're going to the lengths of using a platinum unit and a 16-bit ADC, this suggests that you're trying for very accurate and precise measurements. Temperature coefficients in the resistors can adversely affect this accuracy, but you can get low-drift resistors with at tempco in the range of 25 ppm/deg C.

A: I use this constant current source for strain gauges and RTDs: -

The strain gauge or RTD fits where the block called "current out" is.
You start with a decent constant voltage source (V+) and you set a voltage at the non-inverting input of the op-amp (called Vref). This is set by R1 and R3.
The op-amp then tries to make the voltage on the inverting input equal the voltage on the non-inverting input. To do so it drives the BJT until the current through R2 produces a voltage across R2 that equals the voltage across R1.
Current through the load is then regulated; if the load resistance rises, the op-amp drives the BJT a bit harder until the voltage across R2 = the voltage across R1.
Ignoring the small current taken through the base/emitter to activate the BJT, the current flowing through R2 is the same as current in the load and this current is defined by the voltage across R1.
Try simulating it in LTSpice (or equivalent) and you'll see that it is pretty effective and accurate. If you find that the very small current drawn from the emitter and taken by the base is too much of an error (I'm talking about 0.2% from experience) then use a P channel MOSFET instead of a BJT.
Maybe if you don't quite follow the circuit, consider this NPN version with the load tied to the positive rail: -

A: As stated in the other answers you can build your own constant current source, but there are also designated ICs available for this purpose like the REF200 from TI.
You have to choose a low current to excite the RTD, or elsewise \$I^2R\$ losses will heat the sensor, thus affecting your measurements. With a low excitation current you get a low voltage drop across the RTD. To achieve a good signal for your ADC you can use an instrumentation amplifier to amplify the voltage drop over the RTD.
Here is an reference design by TI which shows a expanded version of what I described. It features a three wire connection and details filters on the input and output of the instrumentation amplifier.


text:
Q: How to use interfaces in exception handling I'm working on the exception handling layer for my application.
I have read few articles on interfaces and generics. I have used inheritance before quite a lot and I'm comfortable with in that area.
I have a very brief design that I'm going to implement:
public interface IMyExceptionLogger
{
   public void LogException();

   // Helper methods for writing into files,db, xml
}

I'm slightly confused what I should be doing next.
public class FooClass: IMyExceptionLogger
{

   // Fields
   // Constructors

}

Should I implement LogException() method within FooClass? If yes, than I'm struggling to see how I'm better of using an interface instead of the concrete class...
I have a variety of classes that will make a use of that interface, but I don't want to write an implementation of that interface within each class.
In the same time If I implement an interface in one class, and then use that class in different layers of the application I will be still using concrete classes instead of interfaces, which is a bad OO design...
I hope this makes sense.
Any feedback and suggestions are welcome.
Please notice that I'm not interested in using net4log or its competitors because I'm doing this to learn.
Thank you
Edit:
Wrote some more code. So I will implement variety of loggers with this interface, i.e. DBExceptionLogger, CSVExceptionLogger, XMLExceptionLogger etc. Than I will still end up with concrete classes that I will have to use in different layers of my application.

A: You cannot avoid having concrete classes implementing IMyExceptionLogger. However, you can stop the classes that need to do exception logging from having dependencies on those concrete classes. That is what the interface is for. So you inject the logger as a dependency of all classes that need to use it:
class MyClass
{
    public MyClass(IMyExceptionLogger exceptionLogger)
    {
        ....
        exceptionLogger.LogException(e);
    }
}

You could also look into some IoC containers such as Unity to help you manage these dependencies more easily.

A: Define an interface Logger and define as many concrete implementations as you want (implementing it).
Next use composition - each class that needs to log something should have a Logger injected into it (via ctor argument or a setter).
This sounds more natural to me.

A: yes you have to implement  LogException() method in the FooClass.
Advantage of interfaces in your case that you may create concrete type of the logger (FooClass, or DBExceptionLogger  or so) and pass around only IMyExceptionLogger reference. So that all your classes which log info will be independet from concrete realization of logger.

A: You should use an interface say IExceptionLog. If concrete clases have much in common e.g. XmlLogger, SOAPLogger you can create a base class for those. In classes where you want to use the logger a member having type IExceptionLog(the interface) should be created. The value of this member is set using dependency injection. You can use if you want a IoC containter


text:
Q: How do I read values from config.php file to another file I am new to coding with php and I need help with this.
I have a config.php file with these values
<?php
 define('DATABASE_HOST', 'localhost');
 define('DATABASE_NAME', 'voltrun');
 define('DATABASE_USERNAME', 'joy');
 define('DATABASE_PASSWORD', 'salty');
 ?>

I have also a db.php file with these values
<?php require_once"../config.php";
 echo 'DATABASE_HOST';
 echo 'DATABASE_NAME';
 echo 'DATABASE_USERNAME';
 echo 'DATABASE_PASSWORD'

  $db_host = 'DATABASE_HOST';
  $db_user = 'DATABASE_USERNAME';
  $db_password =  'DATABASE_PASSWORD';
  $db_database = 'DATABASE_NAME';

   $connection = mysqli_connect($db_host, $db_user, $db_password,    $db_database);

      if (!$connection) {
die('QUERY FAILED' . mysqli_error($connection));
   }

   ?>

Any help on how to get the parameters from the config.php file into the db.php variables? As I still get Query Failed error.
Thanks for the help.

A: This part of your code:
 echo 'DATABASE_HOST';
 echo 'DATABASE_NAME';
 echo 'DATABASE_USERNAME';
 echo 'DATABASE_PASSWORD'
                         ^ missing ; if that's your actual code.

  $db_host = 'DATABASE_HOST';
  $db_user = 'DATABASE_USERNAME';
  $db_password =  'DATABASE_PASSWORD';
  $db_database = 'DATABASE_NAME';

You've wrapped all your constants in quotes, treating them as string literals; remove them.
Plus, you've a missing semi-colon:
 echo DATABASE_HOST;
 echo DATABASE_NAME;
 echo DATABASE_USERNAME;
 echo DATABASE_PASSWORD; // < Added the missing semi-colon

that error reporting would have thrown a parse error
  $db_host = DATABASE_HOST;
  $db_user = DATABASE_USERNAME;
  $db_password =  DATABASE_PASSWORD;
  $db_database = DATABASE_NAME;

References:

*

*http://php.net/manual/en/language.constants.php

*http://php.net/manual/en/language.types.string.php

*http://php.net/manual/en/function.error-reporting.php
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

// rest of your code

Sidenote: Displaying errors should only be done in staging, and never production.
Also make sure that this is correct:
require_once"../config.php";

Error reporting will tell you that also.

A: You have to include/require the config file - then it gots executed and you could use the constants, you define in the conf file as any other constant.
include "config.php";
$db_host = DATABASE_HOST;
// ...

A: echo 'DATABASE_HOST';

This is echoing "DATABASE_HOST". You want to use the value, so you do this:
echo DATABASE_HOST;

Notice the quotation marks are gone.
You'd remove them when assigning to another variable too
$db_host = DATABASE_HOST;


text:
Q: Python - Run _thread with low CPU usage I have recently finally was able to run multiprocessing with _thread and I really thought it was the perfect script as I wanted but of course, it was not.
The issue: The issue is that it takes a lot of CPU usage when I run threads of 10. Which means I can't run concurrently a lot of tasks. (Race condition?)
What I want
Basically what I'm looking for the script to run the thread without using a lot of CPU usage: https://i.imgur.com/pZHDtYL.png - to run all the threads concurrently (at the same time as the picture) without taking a lot of CPU usage - If I do 10000 maybe it should kill my CPU but running etc 10 threads shouldn't take that much!
Code
def text():
    text = """

   Hello stack!

      """

    print(text)
    sys.exit()

def Checker(thread):
    global prod
    prod = int(thread) + 1
    _thread.start_new_thread(text, ())
    print('Profile-{} starting thread...'.format(prod))
    text()

def main():

    while True:
        try:
            accounts_num = int(input(Fore.WHITE + 'How many text do you wanna run? [NUMBERS] \n' + Fore.RESET))
        except ValueError:
            print(Fore.RED + "Stop being stupid" + Fore.RESET)
            continue
        else:
            jobs = []

            for i in range(0, accounts_num):
                p = multiprocessing.Process(target=Checker, args=(str(i),))
                jobs.append(p)
                time.sleep(.5)
                p.start()

            for p in jobs:
                p.join()

            sys.exit()

EDIT:
The issue is sitting at _thread.start_new_thread(text, ()) where when this starts, It starts to eat up the CPU.


text:
Q: NSXMLParserDelegate objective c How can I parse <param name="Weight">630.00 гр</param> to get 630? When I use the following I get elementName = param, but attributeDict contains only the dictionary - "name":"Weight".
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName
   attributes: (NSDictionary *)attributeDict

A: All you need to do is using the function below.
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
  //the parser found some characters in-between an opening and closing tag
  //what are you going to do?
}

You need to store the state, when the attributeDict contains the "name":"Weight" tag. Than the parser will call the above function, and you should be able to read 630 from there.


text:
Q: Bitwise operations on big bit-vectors I would need to run bitwise operations (and, or, xor, shifts, sets, etc..) on arrays of bits. So far I have used the 128 bit type to do so, but now I have met the need to work with bigger arrays. After a bit of search I found that CFBitVector and vBigNum in the Accelerate Framework could store this big numbers, but it appears that they don't have the operations I want.
Can anyone help me to solve this problem?
Language used is Objective-C or C
Thanks for your support

A: You can use regular arrays and interpret them as bit arrays. Let's say you use an array of chars, so every element has 8 bits. If you want to access bit 231, you will find it in 231/8=28th element of the array (the 231%8=7th bit of that array). This is easy when you deal with individual bits. If you use masks and shifts, it's not that easy but you can write some functions to do that.


text:
Q: Prove, by contradiction, that if a and b are nonzero real numbers, and $a<\frac{1}{a}Prove, by contradiction, that if a and b are nonzero real numbers, and $a<1/a<b<1/b$ then $a<−1$.
I understand that the first step is to assume that $a<1/a<b<1/b$ is true. Therefore, the hypotheses makes up:
$a ≠ 0$
$b ≠ 0$
$a<1/a<b<1/b$ is true
From here, to prove by contradiction, we find the negated version of $ a < -1$ which is $ a => -1 $.
Now we must find a contradiction within these statements, but I am struggling to pinpoint that contradiction.
FYI Answer:
I have accepted the completed answer for those who are looking for a quick answer but do check the other one for in-depth
analysis as well.

A: suppose $-1\le a$, i.e $a\in [-1,\infty)$.
Note that $a$ cannot be larger than $1$ or be in $(-1,0)$, otherwise, $\frac{1}{a}<a$. And $a$ cannot be $-1$ or $1$. otherwise, $\frac{1}{a}=a$. Therefore, $a\in(0,1)$ and $1<\frac{1}{a}$
But, there is $b$ such that $1<\frac{1}{a}<b$, thereofre, $\frac{1}{b}<1<b$, which contradicts to the assumption that $b<\frac{1}{b}$.

A: The trick is to note that $1$ is always between $|c|$ and $\frac 1{|c|}$ and So if $c \ne \pm 1$ then either you have have $0 < c < 1 < \frac 1c$ or $0< \frac 1c < \pm < c$ or $c < -1 < \frac 1c < 0$ or $\frac 1c < -1 < c < 0$.
So if $a < \frac 1a < b < \frac 1b$ then $a < \pm 1 < \frac 1a < b < \pm 1 < \frac 1b$.
Now there are only two possible $\pm 1$, $-1, 1$ and $-1< 1$ so si you have $\pm 1 < \pm 1$ the only true statement that makes sense is $-1 < 1$ so $a < -1 < \frac 1a < b < 1 < \frac 1b$.
and ... okay that was a direct proof and you were asked for a proof by contradiction:
......
Note that If $a < 0$ then $a < \frac 1a \implies a^2 > 1$ and $|a| >1$ so if $a<0$ then $a<-1$.
As we are assuming both $a \ge -1$ and $a < \frac 1a$ so that means $a \ge 0$ and as $a\ne 0$ we have $a > 0$.  So $a< \frac 1a \implies a^2 < 1$ and $|a| < 1$ so $0 < a < 1$.  Which means $\frac 1a > 1$
So we have $0 < a < 1 < \frac 1a$.
Can you finish?
If we assume $0 < a < 1 < \frac 1a < b < \frac 1b$ then $b > 1>0$ and .....


text:
Q: How can I merge/sum together a range of rows in a pandas DataFrame into one row? I have a pandas DataFrame and I am trying to sum together and merge the last several rows into a single row. Is there a way I can specify an index range and have that range of rows summed and merged into a single row across all the columns?

Thanks

A: Yes, you should be able to specify an index range and have that range of rows summed and merged into a single row across all the columns:
start_row = 18

df.iloc[start_row] = df.iloc[start_row:].sum()
df = df.iloc[:start_row+1]

A: Try this: I assume your data has only two columns (count & percent):
df.reset_index().replace({'index':[i for i in range(18,24)]}, {'index':18}).groupby('index', as_index=False).sum()

A: You can use pandas.DataFrame.groupby with a lambda function:
start = 18
df = df.groupby(lambda x: x if x < start else start).sum()


text:
Q: What is the entry address for a program loaded with SAM-BA? In the past few days I've found out that SAM-BA can not only write/read flash/ram, but it can also be used as a bootloader. My question is, how does one know where to put the program so that SAM-BA can run it after initial boot sequence? I couldn't find that information in ANY of pdfs provided as a documentation.
I've found a blog post by Adam Pierce and got a linker script that links the program against RAM. Now the RAM memory is at 0x00200000, but the entry point is linked at 0x00202000 - with an explanation that we need to leave "some" memory for SAM-BA.
Why 0x2000 bytes? How can I be sure if it's the right address, and where can I found some information to confirm this?

A: It's in section 21 of the datasheet.

21.5 Hardware and Software Constraints
SAM-BA boot copies itself in the SRAM and uses a block of internal SRAM for variables and stacks.
The remaining available size for the user code is 122880 bytes for
SAM7x512, 57344 bytes for SAM7X256 and 24576 bytes for SAM7X128.

Table 21-4 in that document shows that the user-area start address for all three devices is 0x202000.


text:
Q: Excel: Find set intersections from string data I have a column of strings made up of one or more letters, each referring to a group, like so:

A

1
A

2
AB

3
C

4
AC

5
DX

6
FX

7
R

8
RF

9
AC

10
AB

11
CD

12
XD

Where multi-letter strings mean that the item belongs to multiple groups, so item 1 is in group A only, and item 2 is in group A and in group B, and so on.
The groups themselves go from A to Z (ie there are 26 of them), and each individual item can be in no more than two groups.
I'm trying to build an Excel function that will output the size of the pairwise intersections of each of the sets A...Z, in order to calculate the overlap coefficients and other such statistics.
EDIT from advice in the comments:
The actual calculation is incidental - what I'm having trouble with is finding all of the set intersection sizes.
I have edited the sample data to make the output more interesting/varied. In this case, the intersections would have the following sizes:

A
B

1
A
5

2
AB
2

3
C
4

4
AC
2

5
DX
2

6
FX
1

7
R
2

8
RF
1

9
AC
2

10
AB
2

11
CD
1

12
XD
2

But what I want is to output a 26x26 matrix for all of the possible pairwise intersections. This is what I'm having trouble with. Ideally, the order of the input will not matter, ie BA will be counted the same as AB.
Thanks in advance!

A: This would maybe be easier if you separate the two values using Text to Columns with a fixed width of 1
You can then use the following formula for the left-hand column (Column A, formula is in column C in example below):
 =IFERROR(COUNTIF(A:A,A1)/MIN(COUNTIF(A:B,A1),COUNTIF(A:B,B1)),"")

And this one for the right-hand column (Column B, formula is in column D in example below):
=IFERROR(COUNTIF(A:A,B1)/MIN(COUNTIF(A:B,A1),COUNTIF(A:B,B1)),"")

To get the ratio I believe you want (if that is not what you are looking for, please edit your question to add the expected result for your mock data.
Sample results:

A: You can try the formula below:
=IF(LEN(A1)=1, COUNT(SEARCH("*" & A1 & "*",$A$1:$A$12)), COUNT(SEARCH("*" & A1 & "*",$A$1:$A$12)) + COUNT(SEARCH("*" & TEXTJOIN("",1,MID(A1,SEQUENCE(LEN(A1),,LEN(A1),-1),1)) & "*",$A$1:$A$12)))

Note that it works only for a maximum of 2 character combinations ie AB or R or YZ but not ABC nor LNR. You also need Excel 365.

A: I have found an answer that, while not particularly elegant, gives my desired matrix of intersection sizes:
Screenshot of matrix
The formula for the matrix is the following (Ctrl+Shift+Enter and drag):
=IF($C2=D$1,(SUM(LEN($A$1:$A$12)-LEN(SUBSTITUTE($A$1:$A$12,$C2,"")))),(SUM(LEN($A$1:$A$12)-LEN(SUBSTITUTE($A$1:$A$12,$C2&D$1,"")))/LEN($C2&D$1))+(SUM(LEN($A$1:$A$12)-LEN(SUBSTITUTE($A$1:$A$12,D$1&$C2,"")))/LEN(D$1&$C2)))

Also if anyone's interested here's the one for the unions rather than the intersections:
=IF($C30=D$29,(SUM(LEN($A$1:$A$12)-LEN(SUBSTITUTE($A$1:$A$12,$C30,"")))/LEN($C30)),(SUM(LEN($A$1:$A$12)-LEN(SUBSTITUTE($A$1:$A$12,$C30,"")))/LEN($C30))+(SUM(LEN($A$1:$A$12)-LEN(SUBSTITUTE($A$1:$A$12,D$29,"")))/LEN(D$29)))


text:
Q: How to keep a condition for null value in jolt? INPUT:
 {
   "itemName": null,
   "itemNumber": 22
 }

OUTPUT:
 {
   "isItemNameNull": true,
   "itemNumber": 22
 }

I should not map the value if its null but map 'isItemNameNull' to true,
SPEC:
[
 {
"operation": "shift",
"spec": {
  "itemName": {
    "null": {
      "true": "isItemNameNull"
    },
    "": {
      "#TRASH": "TRASH"
    },
    "*": {
      "@(2,itemName)": "itemName"
    }
  },
  "itemNumber": {
    "null": {
      "#TRASH": "TRASH"
    },
    "": {
      "#TRASH": "TRASH"
    },
    "*": {
      "@(2,itemNumber)": "itemNumber"
    }
  }
  }
 }
]

I mapped the flag but it did'nt took it from null condition.Can any one please suggest me a help.Thanks.

A: You can achieve this by a combination of default and shift operations.
First use a default to detect if itemName is null and assign it a default value of true
Then use a shift to process the itemName appropriately:

*

*if itemName is true (i.e. was set in the default because its original value was null), then set isItemNameNull using the value of itemName

*else copy itemName to the output (I've assumed that you want to do this, otherwise just leave this second bit out)

[
  {
    "operation": "default",
    "spec": {
      "itemName": true
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "itemName": {
        "true": {
          "@1": "isItemNameNull"
        },
        "*": {
          "@1": "itemName"
        }
      }
    }
  }
]

One caveat being that if the input has a string of "true" for itemName
{
  "itemName": "true",
  "itemNumber": 22
}

then the output will be
{
  "isItemNameNull": "true",
  "itemNumber": 22
}

So not foolproof!
To get around that pitfall you could use a 3 step approach:

*

*if itemName is null assign it an appropriate default "marker" value

*process itemName and if it has the "marker" value set isItemNameNull to String value "true"

*convert isItemNameNull to a boolean

[
  {
    "operation": "default",
    "spec": {
      "itemName": "null_marker"
    }
  },
  {
    "operation": "shift",
    "spec": {
      "*": "&",
      "itemName": {
        "null_marker": {
          "#true" :"isItemNameNull"
        },
        "*": {
          "@1": "itemName"
        }
      }
    }
  },
  {
    "operation": "modify-overwrite-beta",
    "spec": {
      "isItemNameNull": "=toBoolean"
    }
  }
]

A: I tried this case. I edited a little in your input json also.
Input Json
----------
{
  "itemName": "null",
  "itemNumber": 22
}

SPEC:
----
    [
      {
        "operation": "shift",
        "spec": {
          "itemName": {
            "null": {
              "#true": "isItemNameNull"
            }
          },
          "itemNumber": "itemNumber"
        }
       }
    ]

Output Json
-----------

{
  "isItemNameNull" : "true",
  "itemNumber" : 22
}

Try yourself please

A: There isn't a good way of doing that.


text:
Q: Does broadcast receiver also unregister if service is destroyed Hi I have Service where I am registering the broadcast receiver. I want to know if service is destroyed then broadcast receiver which I am adding is also unregistered or not.
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
    locationManager.addProximityAlert(
            latitude, // the latitude of the central point of the alert region
            longitude, // the longitude of the central point of the alert region
            radius, // the radius of the central point of the alert region, in meters
            -1, // time for this proximity alert, in milliseconds, or -1 to indicate no expiration
            proximityIntent // will be used to generate an Intent to fire when entry to or exit from the alert region is detected
    );

    IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
    registerReceiver(new ProximityIntentReceiver(), filter);

}

@Override
public void onDestroy() {
    super.onDestroy();
    locationManager.removeUpdates(listener);
}

A: No, according to documentation - You have to unregister you receivers in onDestroy method .
onDestroy is called by the system to notify a Service that it is no longer used and is being removed.  The service should clean up any resources it holds (threads, registered  receivers, etc) at this point. ...

A: Actullay no, where you register and unregister the receiver, for example, if you register a receiver in onCreate(Bundle) using the activity's context, you should unregister it in onDestroy() to prevent leaking the receiver out of the activity context. If you register a receiver in onResume(), you should unregister it in onPause() to prevent registering it multiple times (If you don't want to receive broadcasts when paused, and this can cut down on unnecessary system overhead). Do not unregister in onSaveInstanceState(Bundle), because this isn't called if the user moves back in the history stack. for more help refer this
public void unregisterBroadcastReceiver() {

    this.unregisterReceiver(broadCastReceiver);

    Toast.makeText(this, 'unregistered broadcst receiver', Toast.LENGTH_SHORT)
      .show();
   }


text:
Q: How to use sigPointsClicked in pyqtgraph I created a plot with pyqtgraph that displays a line with points:
self.gaussianPlot = GraphicsLayoutWidget()
self.gaussianPlot.resize(750, 250)

energyPlot=self.gaussianPlot.addPlot(row=1, col=1)
energyPlot.plot(self.scfenergies, symbol='o')
energyPlot.sigPointsClicked.connect(self.gausclicked())

I would like to detect which point on the energyPlot has been clicked. However, I get an error:
Traceback (most recent call last):
File "/home/shrx/PycharmProjects/moldy/moldy.py", line 358, in readGaussian
energyPlot.sigPointsClicked.connect(self.gausclicked)
AttributeError: 'PlotItem' object has no attribute 'sigPointsClicked'

How to correctly use the sigPointsClicked to detect which point was clicked?
UPDATE
Following @Luke's answer, here's how I rewrote the code:
self.energyPlot=self.gaussianPlot.addPlot(row=1, col=1)
self.energyPlotData=self.energyPlot.plot(self.scfenergies, symbol='o')
self.energyPlotData.sigPointsClicked.connect(self.gausclicked)

def gausclicked(self, points):
    print(points)
    print(self.energyPlot.listDataItems())

As a result, I get:
<pyqtgraph.graphicsItems.PlotDataItem.PlotDataItem object at 0x7f1a18065678>
[<pyqtgraph.graphicsItems.PlotDataItem.PlotDataItem object at 0x7f1a18065678>]

So there is no apparent way that I can detect which point in the dataset was clicked? It looks like sigPointsClicked returns the whole data set.
UPDATE 2
The final fix needed was to add a second argument to the gausclicked function:
def gausclicked(self, item, points):
    print(points)

A: There are two different classes you need to keep track of:

*

*PlotItem contains the entire plot area including the axes, viewbox, and all data contained within. This type is returned by GraphicsLayoutWidget.addPlot(). As the error indicates, it does not have sigPointsClicked.

*PlotDataItem is responsible for drawing the lines and points for a single dataset. This class has the sigPointsClicked signal and is returned when you call PlotItem.plot(...).


text:
Q: Trouble displaying data from MongoDb by using js/express.js, I have a hard time displaying data from my MongoDB to my frontpage. I can see that I get the right number of items in my collection but it tells me [object Object] when I try to display the chosen data. Can anyone help? Thank you
Code for getting data from the collection "title"
Call for displaying the 1 element in the title array
What the browser tells me

A: You are trying to display a whole object which results in [object Object]. You have to give your HTML a string like result[0].title (assuming you have a field title in your object)
You can also display the whole object with JSON.stringify(result[0]) in JS.

A: Thank you! I thought I had tried that but nope. Now it works:) Have a good day


text:
Q: VFP - Creating Project & exe build problems I have an application that consists of:

*

*1 program file

*6 main forms including the main menu

*5 search forms in every other form

*A few reports in each form

I'm trying to build an .exe file, using these forms and reports. When I run my program from within the FoxPro IDE it works perfectly, but when I create an .exe file, it gives me a lot of problems.
Can someone tell me step by step how to do this so that my program can be run on another computer without FoxPro?

A: Make sure you have paths to your objects in SET PATH TO ....


text:
Q: can any body please tell me how to create like this type of layout
finding too much examples but cant find this layout any example and please tell me the layout name
i am trying to take an Imageview but still it will not works for me because imageview can not work like that

A: Use Linear Layout, and imageView inside it.
Refer http://developer.android.com/reference/android/widget/LinearLayout.html
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
<ImageView
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="@drawable/YourImage">

</LinearLayout>

A: It's not complicated, just create with some imaging software (Photoshop, gimp, paint .net etc. ) a rectangle which looks like like this:

and just set the rest of the screen to be the same color as the white part.


text:
Q: Split information from two columns, R, tidyverse i've got some data in two columns:
# A tibble: 16 x 2
   code  niveau
   <chr>  <dbl>
 1 A          1
 2 1          2
 3 2          2
 4 3          2
 5 4          2
 6 5          2
 7 B          1
 8 6          2
 9 7          2

My desired output is:
 A tibble: 16 x 3
   code  niveau cat
   <chr>  <dbl> <chr>
 1 A          1 A
 2 1          2 A
 3 2          2 A
 4 3          2 A
 5 4          2 A
 6 5          2 A
 7 B          1 B
 8 6          2 B

I there a tidy way to convert these data without looping through it?
Here some dummy data:
data<-tibble(code=c('A', 1,2,3,4,5,'B', 6,7,8,9,'C',10,11,12,13), niveau=c(1, 2,2,2,2,2,1,2,2,2,2,1,2,2,2,2))

desired_output<-tibble(code=c('A', 1,2,3,4,5,'B', 6,7,8,9,'C',10,11,12,13), niveau=c(1, 2,2,2,2,2,1,2,2,2,2,1,2,2,2,2),
                       cat=c(rep('A', 6),rep('B', 5), rep('C', 5)))

Nicolas

A: Probably, you can create a new column cat and replace code values with NA where there is a number. We can then use fill to replace missing values with previous non-NA value.
library(dplyr)
data %>% mutate(cat = replace(code, grepl('\\d', code), NA)) %>% tidyr::fill(cat)

# A tibble: 16 x 3
#   code  niveau cat
#   <chr>  <dbl> <chr>
# 1 A          1 A
# 2 1          2 A
# 3 2          2 A
# 4 3          2 A
# 5 4          2 A
# 6 5          2 A
# 7 B          1 B
# 8 6          2 B
# 9 7          2 B
#10 8          2 B
#11 9          2 B
#12 C          1 C
#13 10         2 C
#14 11         2 C
#15 12         2 C
#16 13         2 C

A: We can use str_detect from stringr
library(dplyr)
library(stringr)
library(tidyr)
data %>%
     mutate(cat = replace(code, str_detect(code, '\\d'), NA)) %>%
     fill(cat)


text:
Q: Using google guava error - Not under a public suffix: display_url I'm trying to use the InternetDomainName function from google Guava; I've written the code in scala using Eclipse and it compiles fine, but when I run it, I keep getting an error message:
java.lang.IllegalStateException: Not under a public suffix: display_url
at com.google.common.base.Preconditions.checkState(Preconditions.java:176)
at com.google.common.net.InternetDomainName.topPrivateDomain(InternetDomainName.java:445)

I've already added "com.google.guava" % "guava" % "16.0" to the dependency library, and added the Guava library to the project. I'm not sure what it is implying. Is it because I've entered data that are not URL?

A: As always, the answer is in the documentation. Let's see the topPrivateDomain() method:

Throws:

*

*IllegalStateException - if this domain does not end with a public suffix

And, actually, "display_url" does not indeed end with a public suffix. So the method has nothing to return and throws as defined. Try some actually useful URL instead.


text:
Q: Using csv.DictWriter to output an in-memory gzipped csv file? I want to use a DictWriter from Python's csv module to generate a .csv file that's compressed using GZip. I need to do this all in-memory, so utilizing local files is out of the question.
However, I'm having trouble dealing with each module's type requirements in Python 3. Assuming that I got the general structure correctly, I can't make both modules work together because DictWriter needs to write to a io.StringIO buffer, while GZip needs a io.BytesIO object.
So, when I try to do:
buffer = io.BytesIO()
compressed = gzip.GzipFile(fileobj=buffer, mode='wb')
dict_writer = csv.DictWriter(buffer, ["a", "b"], extrasaction="ignore")

I get:
TypeError: a bytes-like object is required, not 'str'
And trying to use io.StringIO with GZip doesn't work either. How can I go about this?

A: A roundabout way would be to write it to a io.StringIO object first and then convert the content back to io.BytesIO:
s = io.StringIO()
b = io.BytesIO()

dict_writer = csv.DictWriter(s, ["a", "b"], extrasaction="ignore")

... # complete your write operations ...

s.seek(0)  # reset cursor to the beginning of the StringIO stream
b.write(s.read().encode('utf-8')) # or an encoding of your choice

compressed = gzip.GzipFile(fileobj=b, mode='wb')

...

s.close()   # Remember to close your streams!
b.close()

Though as @wwii's comment suggest, depending on the size of your data, perhaps it's more worthwhile to write your own csv in bytes instead.

A: You can use io.TextIOWrapper to seamlessly transform a text stream into a binary one:
import io
import gzip
import csv
buffer = io.BytesIO()
with gzip.GzipFile(fileobj=buffer, mode='wb') as compressed:
    with io.TextIOWrapper(compressed, encoding='utf-8') as wrapper:
        dict_writer = csv.DictWriter(wrapper, ["a", "b"], extrasaction="ignore")
        dict_writer.writeheader()
        dict_writer.writerows([{'a': 1, 'b': 2}, {'a': 4, 'b': 3}])
print(buffer.getvalue()) # dump the compressed binary data
buffer.seek(0)
dict_reader = csv.DictReader(io.TextIOWrapper(gzip.GzipFile(fileobj=buffer, mode='rb'), encoding='utf-8'))
print(list(dict_reader)) # see if uncompressing the compressed data gets us back what we wrote

This outputs:
b'\x1f\x8b\x08\x00\x9c6[\\\x02\xffJ\xd4I\xe2\xe5\xe52\xd41\x02\x92&:\xc6@\x12\x00\x00\x00\xff\xff\x03\x00\x85k\xa2\x9e\x12\x00\x00\x00'
[OrderedDict([('a', '1'), ('b', '2')]), OrderedDict([('a', '4'), ('b', '3')])]


text:
Q: Web service for Location name using Latitude & Longitude I have an iPhone application where i need to find out the current location(in terms of city name or probably the address). But i'm not been able to do that. I can find out the current latitude and longitude. Is there any web service(preferably free of cost) which can return me the current location name if i supply the latitude and longitude?

A: The feature you're looking for is called Reverse Geocoding.
Here is a list of web services that provide this function.
A couple of the most popular are Geonames.org, Google Maps Services API and Batchgeo.com for batch processing of multiple coordinates.

A: Assuming you are targeting iPhone OS 3.0 or higher, you can use MKReverseGeocoder which is part of the MapKit Framework. The Developer docs include a sample project. MKReverserGeocoder Class Reference

A: MKReverseGeocoder is a great class, but sometimes may return the error:
Error Domain=PBRequesterErrorDomain Code=6001 "Operation could not be completed. (PBRequesterErrorDomain error 6001.)
luvieere's suggestion above are a great place to start, which is what I did as an example using the Google HTTP reverse geocoder. Here's my implementation of a GoogleReverseGeocoder class I wrote. The full explanation of how to use it can be found HERE.
// Send Google A Request
NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%lf,%lf&output=csv&sensor=false",self.locationToGeocode.coordinate.latitude,self.locationToGeocode.coordinate.longitude];
NSURL *urlFromString = [NSURL URLWithString:urlString];
NSStringEncoding encodingType = NSUTF8StringEncoding;
NSString *reverseGeoString = [NSString stringWithContentsOfURL:urlFromString encoding:encodingType error:nil];

// Parse Out Response
NSArray *listItems = [reverseGeoString componentsSeparatedByString:@","];
NSArray *tempAddressArray = [[listItems objectAtIndex:2] componentsSeparatedByString:@"\""];
NSArray *tempCountryArray = [[listItems objectAtIndex:[listItems count]-1] componentsSeparatedByString:@"\""];

// Did Google Find Address? 200 is yes
if ([[listItems objectAtIndex:0] intValue] == 200)
{
    // Set Class Member Variables
    [self setGoogleReturnDidFindAddress:YES];
    [self setGoogleReturnAddress:[tempAddressArray objectAtIndex:[tempAddressArray count]-1]];
    [self setGoogleReturnCountry:[tempCountryArray objectAtIndex:0]];
    [self setGoogleReturnCode:[[listItems objectAtIndex:0] intValue]];
    [self setGoogleReturnAccuracy:[[listItems objectAtIndex:1] intValue]];

} else if ([[listItems objectAtIndex:0] intValue] > 600)
{
    [self setGoogleReturnDidFindAddress:NO];
}

A: Wanna do it your own?
Most of these services you'll have to pay for with a thousand of limitations. Maybe you can have your own list of states and cities, alongside their known latitude and longitude.
Do not try to build the list yourself. This project for example is a Brazilian database of states and cities:
https://github.com/kelvins/Municipios-Brasileiros
A list of 5.570 cities is small as 430KBytes! Totally worth it considering the amount of data you have to store and the benefit you get from such.
So the best approach is to find a similar project from your country and make it happen.
So now that I've got my own list of cities, I can get a user the 5 nearest cities or do anything else I want to. With this simple query to my application MySQL database! Look how simple yet powerful
set @lat=-20.0080509185791;
set @lng=-44.003021240234375;

-- The main SQL query that returns the closest 5 airports.
SELECT id, nome, lat, lng, 111.045 * DEGREES(ACOS(COS(RADIANS(@lat))
 * COS(RADIANS(lat))
 * COS(RADIANS(lng) - RADIANS(@lng))
 + SIN(RADIANS(@lat))
 * SIN(RADIANS(lat))))
 AS distance_in_km
FROM cities
ORDER BY distance_in_km ASC
LIMIT 0,5;


text:
Q: NSTableView set target and action cause cell problems I want to detect click on cell in NSTableView
so I did:
tableView.target = self;
tableView.action = @selector(tableViewClicked:);

but I saw that another @IBAction's that connected to the cell does not work.
what could be the problem?
thanks


text:
Q: Input field loses focus after typing one character in react app In my case I have a dropdown and based on the number selected with the dropdown some input fields appear. When I type into the input field the focus on that input field is lost after typing one character.
Setting a unique key for each field is not solving my problem.
Link to the project: https://codesandbox.io/s/stoic-brahmagupta-m5014

const ItemPrice = () => {
  const data = itemData.doReservation.eventPackage.item;

  let emptyCat = {};
  let emptyQnt = {};
  let promoNum = {};
  let emptyPromotion = {};

  const [promoNumber, setPromoNumber] = useState(promoNum);

  for (let it in data) {
    let cat = {};
    let promo = {};

    for (let bt in data[it].buyertypes) {
      cat[data[it].buyertypes[bt].id] = "";
      emptyQnt[data[it].buyertypes[bt].id] = 0;
      promo[data[it].buyertypes[bt].id] = "";
      promoNum[data[it].buyertypes[bt].id] = [];
      emptyPromotion[data[it].buyertypes[bt].id] = {};
    }
    emptyCat[data[it].id] = cat;
    cat = {};
  }

  const [quantity, setQuantity] = useState(emptyQnt);
  const [code, setCode] = useState(emptyPromotion);

  const handleQuantity = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    setQuantity({
      ...quantity,
      [name]: value
    });
    let num = [];
    for (let i = 1; i <= value; i++) {
      num.push(i);
    }
    setPromoNumber({ ...promoNumber, [name]: num });
    let num2 = {};
    for (let pn = 1; pn <= value; pn++) {
      if (code[name]["code" + name + pn] === undefined) {
        num2["code" + name + pn] = "";
      } else {
        num2["code" + name + pn] = code[name]["code" + name + pn];
      }
    }
    setCode({ ...code, [name]: num2 });
  };

  const handleCode = (e) => {
    e.preventDefault();
    const sp = e.target.name.split(",");
    const id1 = sp[0];
    const id2 = sp[1];
    const value = e.target.value;
    setCode({
      ...code,
      [id1]: {
        ...code[id1],
        [id2]: value
      }
    });
  };

  const ShowData = () => {
    let buyerTypes = [];
    let items = [];
    if (data) {
      for (let it in data) {
        items.push(

type

Quantity

Price category

        );
        for (let bt in data[it].buyertypes) {
          buyerTypes.push({
            dsc: data[it].buyertypes[bt].description,
            qntId: data[it].buyertypes[bt].id
          });
        }
        items.push(

            {buyerTypes.map((i, index) => (
              <div key={`a${index}`} className="selectionRowComp">
                <div key={`c${index}`} className="selectionRow">

{i.dsc}

                    <select
                      value={quantity[i.qntId]}
                      onChange={handleQuantity}
                      name={i.qntId}
                    >
                      {[0, 1, 2, 3, 4, 5, 6].map((l) => {
                        return (
                          <option value={l} key={l}>
                            {l}
                          </option>
                        );
                      })}
                    </select>

                  {promoNumber[i.qntId].map((p, index) => (
                    <div key={`s${index}`}>
                      code {p}:
                      <input
                        className="codeInput"
                        type="text"
                        value={code[i.qntId]["code" + i.qntId + (index + 1)]}
                        onChange={handleCode}
                        name={[i.qntId, "code" + i.qntId + (index + 1)]}
                        // required={hasPromotion[i.qntId]}
                      />

                  ))}

            ))}

        );
        buyerTypes = [];
      }
    }
    return (

        {items.map((it, index) => {
          return <div key={`w${index}`}> {it}
;
        })}

    );
  };

  const handleSubmit = (e) => {
    e.preventDefault();
  };

  return (

          <form onSubmit={handleSubmit}>
            <ShowData />
          </form>

  );
};

A: You have to decouple Parent (ItemPrice) and Child (ShowData) components respectively.
A through re-factor of your code is needed. Because dependencies like const data is defined in ItemPrise and used in child component ShowData, rather it should be sent down as Props to ShowData component.
ShowData component should not be directly dependent on any variable/const defined in ItemPrise component. All such dependencies should be passed using any of the following basis your use-case and application requirements:

*

*Props

*Context

*Global state management such as Redux

*Custom Hook


text:
Q: Is it possible to interrupt and cancel a build when a file is saved or key typed? Frequently, I'll make changes in an editor, then save and repeat this process. The build automatically flag in Eclipse starts to create a build as soon as I save. But, I'll make another change and then save again and the current build becomes invalid.
Is there a way to cancel a current build automatically when I start typing into an editor or when I save?

A: Automatically? No, there's just the Progress View and its ability to send a cancel request. Builds are triggered headlessly in all cases other than when you trigger it from the menu, which is only even available when it's not set to build automatically, and there's no UI dedicated for canceling them.


text:
Q: Many to many relationship in Laravel 4.1 get the same result please help i'm currently working on a real estate project and I have the following table as many to many relationship on Laravel 4.1
table categories

table services

table category_service

when I tested on PHPMyAdmin with the following query
SELECT C.category_name
FROM Categories AS C
LEFT JOIN category_service AS CS ON CS.category_id = C.id
LEFT JOIN Services S ON S.id = CS.service_id
WHERE S.id =1

the result is OK when I changed S.id to 2, but on Laravel the result was remain unchanged whether I changed its id = 2.
Here is my Category class
class Category extends Eloquent {
    protected $fillable = ['category_name'];
    public $timestamps = false;
    public function services() {
        return $this->belongsToMany('Service','category_service');
    }
}

and my Service class
class Service extends  Eloquent {
    protected $fillable = ['service_types'];
    public $timestamps = false;
    public function categories() {
        return $this->belongsToMany('Category','category_service');
    }
}

and the ServicesController
class ServicesController extends BaseController {
    public function getService($c) {

        //using raw query return the result unchanged
        $cat = DB::raw('
            SELECT C.category_name
            FROM Categories AS C
            LEFT JOIN category_service AS CS ON CS.category_id = C.id
            LEFT JOIN Services S ON S.id = CS.service_id
            WHERE S.id ='.$c
        );

        //using eloquent return the result unchanged
        $cat = Service::with('categories')->find($c);

        return View::make('members.cat')->with('cat',$cat);
    }
}

Expected result should be like this photo with S.id=1

Expected result should be like this photo with S.id=1
so what I did wrong with Laravel? I show the result the same S.id=1 although I gave S.id=0 that didn't exist in database.


text:
Q: PSD To Xamarin Android UI Is it Possible to convert HTML, CSS UI into Xamarin Android UI?  if yes Kindly tell me how.
I tried to use "EXPORT KIt" but it isn't properly configured with Adobe Photoshop. Any other way to convert? Thanks All of you in Advance.

A: Do you mean a tool that converts HTML + CSS into Android layout files? If yes, I do not think such a tool exists. You'd have to manually code the UI in XML. You can get started with this documentation > https://developer.android.com/guide/topics/ui/declaring-layout.html