text:
Q: Jasmine Headless Webkit spec file running before assets? To run the spec files & assets as coffee script, I decided to go with jasmine-headless-webkit. I believe I have everything installed correctly, but perhaps something wrong in my jasmine.yml file:
src_files:
  - spec/support/javascripts/jquery-1.7.2.js
  - app/assets/javascripts/application.js
helpers:
  - helpers/**/*
spec_files:
  - "**/*_spec.*"
src_dir:
  - vendor/assets/javascripts
spec_dir: spec/javascripts

When I run the command, I get three errors, all along the same lines:
Editor should have an array named tables. (/Users/aaronmcleod/Documents/awesome_model/spec/javascripts/editor_spec.js.coffee:20)
ReferenceError: Can't find variable: AwesomeModel

The AwesomeModel variable is my hash I'm using that I export to the window object. I then attach things like the Editor class to it. Any ideas as to why this isn't defined? Here's my spec file if it helps:
fixture_text = ->
  "Company has_many:Employee\n" +
  "  id : int\n" +
  "  name : varchar\n" +
  "Employee belongs_to:Company\n" +
  "  id : int\n" +
  "  name : varchar\n" +
  "  phone : varchar\n" +
  "ComplicatedTable-Name\n" +
  "  id : int"

class DummyPane
  constructor: ->
    @viewport = {}

  clean_up: ->

describe "Editor", ->

  it "should have an array named tables", ->
    editor = new AwesomeModel.Editor(fixture_text())
    expect(editor.tables).toBeDefined()

  describe "#parse_table_names", ->
    text = fixture_text()
    editor = new AwesomeModel.Editor(text)

    it "tables should be of three length", ->
      editor.parse_table_names()
      expect(editor.tables.length).toEqual(3)

    it "the first table name should be 'Company'", ->
      editor.parse_table_names()
      expect(editor.tables[0].name).toEqual("Company")

    it "the third table name should be 'ComplicatedTable-Name'", ->
      editor.parse_table_names()
      expect(editor.tables[2].name).toEqual("ComplicatedTable-Name")

  describe "#add_columns", ->
    text = fixture_text()
    editor = new AwesomeModel.Editor(text)
    editor.parse_table_names()

    describe "first table", ->
      it "the first table should have two columns", ->
        editor.add_columns()
        table = editor.tables[0]

        expect(table.columns.length).toEqual(2)

      it "the first column of first table should be named 'id : int'", ->
        editor.add_columns
        table = editor.tables[0]
        expect(table.columns[0].name).toEqual('id : int')

A: Found an answer by utilizing guard. No changes to the spec file, a few minor changes to the jasmine.yml file. Here's my gemfile:
source 'https://rubygems.org'

gem 'rails', '3.2.0'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'

  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer'

  gem 'uglifier', '>= 1.0.3'
end

gem 'haml-rails'

gem 'jquery-rails'

platforms :ruby do
  gem 'pg'
end

platforms :jruby do
  gem 'jruby-openssl'
  gem 'activerecord-jdbcpostgresql-adapter'
end

group :test, :development do
  gem 'rspec-rails'
  gem 'capybara'
  gem 'jasmine'
  gem 'guard'
  gem 'guard-coffeescript'
end

My guardfile:
# A sample Guardfile
# More info at https://github.com/guard/guard#readme

guard 'coffeescript', input: 'spec/javascripts', output: 'spec/javascripts'

Jasmine.yml
src_dir:
  - assets/javascripts
src_files:
  - assets/application.js
helpers:
  - helpers/**/*
spec_files:
  - "**/*_spec.js"

spec_dir: spec/javascripts

I changed the assets path to not use the local folder structure, but the asset path properly.
To run this, just run guard in one tab, and rake jasmine in another. As you save spec files, the .js version will be compiled by guard.


text:
Q: "attachment for"? JavaLatte gave an excellent answer in 2017 about the verb attach, which takes the preposition "to". My question concerns attachment in a non-physical sense. "His attachment to his ex-girlfriend made him miserable for years." Here "to" feels too physical. I find myself preferring "for" when attachment is used in a mental/emotional sense: "His attachment for his ex finally ended when he fell in love with somebody else. Attached to her, he let go of his ex." For me, the to/for issue seems to concern the noun (attachment for), not the verb (attached to). Any thoughts?

A: If it is the word "attachment" that sounds more physical in your context, you can use another word.
So, if you want to avoid this you can use a different word, like "affection for" or "passion for" - the solution to make it sound less physical is not in the preposition but in the word attachment /affection.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get rid of useless nodes from this AST tree? I have already looked at this question and even though the question titles seem to be the same; it doesn't answer my question, at least not in any way that I can understand.
Parsing Math
Here is what I am parsing:
PI -> 3.14.
Number area(Number radius) -> PI * radius^2.

This is how I want my AST tree to look, minus all the useless root nodes.
how it should look http://vertigrated.com/images/How%20I%20want%20the%20tree%20to%20look.png
Here are what I hope are the relevant fragments of my grammar:
term : '(' expression ')'
     | number -> ^(NUMBER number)
     | (function_invocation)=> function_invocation
     | ATOM
     | ID
     ;

power : term ('^' term)* -> ^(POWER term (term)* ) ;
unary : ('+'! | '-'^)* power ;
multiply : unary ('*' unary)* -> ^(MULTIPLY unary (unary)* ) ;
divide : multiply ('/' multiply)* -> ^(DIVIDE multiply (multiply)* );
modulo : divide ('%' divide)* -> ^(MODULO divide (divide)*) ;
subtract : modulo ('-' modulo)* -> ^(SUBTRACT modulo (modulo)* ) ;
add : subtract ('+' subtract)* -> ^(ADDITION subtract (subtract)*) ;

relation : add (('=' | '!=' | '<' | '<=' | '>=' | '>') add)* ;

expression : relation (and_or relation)*
           | string
           | container_access
           ;
and_or : '&' | '|' ;

Precedence
I still want to keep the precedence as illustrated in the following diagrams, but want to eliminate the useless nodes if at all possible.
Source: Number a(x) -> 0 - 1 + 2 * 3 / 4 % 5 ^ 6.
Here are the nodes I want to eliminate:
how I want the precedence tree to look http://vertigrated.com/images/example%202%20desired%20result.png
Basically I want to eliminate any of those nodes that don't directly have a branch under them to binary options.

A: Your rule (and other like it)
 add : subtract ('+' subtract)* -> ^(ADDITION subtract (subtract)*) ;

produces the useless production when you don't have a sequence of add operations.
I'm not an ANTLR expert, but I'd guess you need two cases, one for an add term
that is unary, and one for a set of children, the first of which generates your
standard tree, and the second of which simply passes the child tree up to the parent,
without creating a new node?
add : subtract ( ('+' subtract)+ -> ^(ADDITION subtract (subtract)*)
               | -> subtract ) ;

Similar changes for other rules with sequences of operands to an operator.

A: You must realize that the two rules:
add : sub ( ('+' sub)+ -> ^(ADD sub (sub)*) | -> sub ) ;

and
add : sub ('+'^ sub)* ;

do not produce the same AST. Given the input 1+2+3, the first rule will produce:
  ADD
   |
.--+--.
|  |  |
1  2  3

where the second rule produces:
     (+)
      |
   .--+--.
   |     |
  (+)    3
   |
.--+--.
|     |
1     2

The latter makes more sense: infix expressions are expected to have 2 child nodes, not more.
Why not simply remove the literals in your parser rules and just do:
add : sub (ADD^ sub)*;

ADD : '+';

Creating the same AST using a rewrite rule would look like this:
add : (sub -> sub) ('+' s=sub -> ^(ADD $add $s))*;

Also see chapter 7: Tree Construction from The Definitive ANTLR Reference. Especially the paragraphs Rewrite Rules in Subrules (page 173) and Referencing Previous Rule ASTs in Rewrite Rules (page 174/175).

A: Even though I accepted Barts's answers as correct, I wanted to post my own complete answer with example code that I got working just for completeness.
Here is what I did based on Bart's answer:
unary : ('+'! | '-'^)? term ;
pow : (unary -> unary) ('^' s=unary -> ^(POWER $pow $s))*;
mod : (pow -> pow) ('%' s=pow -> ^(MODULO $mod $s))*;
mult : (mod -> mod) ('*' s=mod -> ^(MULTIPLY $mult $s))*;
div : (mult -> mult) ('/' s=mult -> ^(DIVIDE $div $s))*;
sub : (div -> div) ('-' s=div -> ^(SUBTRACT $sub $s))*;
add : (sub -> sub) ('+' s=sub -> ^(ADD $add $s))*;

And here is what the resulting tree looks like:
working answer http://vertigrated.com/images/working_answer.png
There is an alternative solution to just not use the rewrites and promote the symbols themselves to roots, but I want all descriptive labels in my tree if at all possible. I am just being anal about how the tree is represented so that my tree walking code will be as clean as possible!
power : unary ('^'^ unary)* ;
mod : power ('%'^ power)* ;
mult : mod ('*'^ mod)* ;
div : mult ('/'^ mult)* ;
sub : div ('-'^ div)* ;
add : sub ('+'^ sub)* ;

And this looks like this:
without rewrites http://vertigrated.com/images/without_the_rewrites.png

A: To get rid of the irrelevant nodes, just be explicit:
 subtract
    :
    modulo
    (
       ( '-' modulo)+  -> ^(SUBTRACT modulo+) // no need for parenthesis or asterisk
       |
      () -> modulo
    )
    ;


text:
Q: Programmatically submitting a form while using AjaxForm I wanted to find a way to upload a single file*, in the background, have it start automatically after file selection, and not require a flash uploader, so I am trying to use two great mechanisms (jQuery.Form and JQuery MultiFile) together. I haven't succeeded, but I'm pretty sure it's because I'm missing something fundamental.
Just using MultiFile, I define the form as follows...
<form id="photoForm" action="image.php" method="post" enctype="multipart/form-data">

The file input button is defined as...
<input id="photoButton" "name="sourceFile" class="photoButton max-1 accept-jpg" type="file">

And the Javascript is...
$('#photoButton').MultiFile({
    afterFileSelect: function(){
         document.getElementById("photoForm").submit();
    }
});

This works perfectly. As soon as the user selects a single file, MultiFile submits the form to the server.

If instead of using MultiFile, as shown above, let's say I include a Submit button along with the JQuery Form plugin defined as follows...
 var options = {
  success: respondToUpload
 };

 $('#photoForm').ajaxForm(options);

... this also works perfectly. When the Submit button is clicked, the form is uploaded in the background.

What I don't know how to do is get these two to work together. If I use Javascript to submit the form (as shown in the MultiFile example above), the form is submitted but the JQuery.Form function is not called, so the form does not get submitted in the background.
I thought that maybe I needed to change the form registration as follows...
$('#photoForm').submit(function() {
 $('#photoForm').ajaxForm(options);
});

...but that didn't solve the problem. The same is true when I tried .ajaxSubmit instead of .ajaxForm.
What am I missing?

*

*BTW: I know it might sound strange to use MultiFile for single-file uploads, but the idea is that the number of files will be dynamic based on the user's account. So, I'm starting with one but the number changes depending on conditions.

A: The answer turns out to be embarrassingly simple.
Instead of programmatically submitting using...
document.getElementById("photoForm").submit();

... I used...
$("#photoForm").submit();

Also, since I only need to upload multiple files on occasion, I used a simpler technique...
1)  The form is the same as my original...
<form id="photoForm" action="image.php" method="post" enctype="multipart/form-data">

2)  The file input field is basically the same...
<input id="photoFile" "name="sourceFile" style="cursor:pointer;" type="file">

3)  If the file input field changes, submit is executed...
$("#photoFile").change(function() {
    $("#photoForm").submit();
});

4)  The AjaxForm listener does its thing...
var options = {
    success: respondToUpload
};
$('#photoForm').ajaxForm(options);


text:
Q: ImportError when I try to run a .py script using CherryPy I'm using python 2.7 and cherrypy 3.7, and am running them on Ubuntu 14.04.
I have a simple hello world file that I am trying to run with the command:
python HelloWorld.py

This results in the following error:

ImportError: No module named cherrypy

Please explain why Python couldn't find the module.

A: Ubuntu is going to have a native version of python 2.6 for instance.  So you'll need the full path to your python file.  Try to run this and if it fails search your system for a python2.7 folder.
/usr/local/bin/python2.7 tut01.py

Hope this helps!


text:
Q: Using Android to Communicate with a USB HID Device I am new to USB and to Android so please forgive me if I don't explain myself clearly.
I have a USB HID device that I can communicate with in Windows.  I am trying to establish communication using an Acer Iconia A500 tablet running Android 3.1.
I am able to find the device, enumerate it, get its only available interface, get the only available endpoint (0), and determine what type of endpoint it is (transfer interrupt from device to host).
My understanding of the USB spec is that all HID devices are required at a munimum to have a control endpoint (Endpoint 0) and an interrupt IN endpoint. But it seems that endpoint 0 here is the interrupt In endpoint, not the control endpoint.
Yet in order for the device to enumerate it must successfully transfer its descriptor data across the control endpoint.  I deduce that the control endpoint therefore must be getting found (and used) because the host does, in fact, enumerate the device.
This is as far as I am able to proceed, as stated above, the only interface/endpoint presented to me at the application level is an interrupt type going from device to host. No endpoint available to my app going from host to device, interrupt or control. So the device waits to be told what to do and the host waits for something to happen in the device.  Not very stimulating.
Bear in mind that this device responds properly when connected to Windows, e.g. I am able to send a report containing 13 bytes of data that causes the device to light an LED.  So it seems to be complying with the USB HID spec.  As an act of desperation I have tried using this one endpoint as both a control endpoint and as a interrupt OUT endpoint, using controltransfer() and UsbRequest() to submit the data to the device, no response in either case.
So my question is: "The control transfer endpoint is (?) being used to set up the device, why am I not able to find & use it?"
Thanks for any insight, below is the relevant code, I can include the rest in its entirety if needed:
private UsbManager mUsbManager;
private UsbDevice mDevice;
private UsbDeviceConnection mConnectionRead;
private UsbDeviceConnection mConnectionWrite;
private UsbEndpoint mEndpointRead;
private UsbEndpoint mEndpointWrite;

    // check for existing devices
    for (UsbDevice device :  mUsbManager.getDeviceList().values())
    {
        //Need to filter for my device when other HIDs are also connected, but for now...
        String devName = device.getDeviceName();
        if (DEBUG == 1){
        Toast.makeText(UsbHidDeviceTesterActivity.this, "My device got connected: " + devName, Toast.LENGTH_LONG).show();
        }
        //mDevice = device;
        setHIDDevice(device);
    }

private boolean setHIDDevice(UsbDevice device)
{
    UsbInterface usbInterfaceRead = null;
    UsbInterface usbInterfaceWrite = null;
    UsbEndpoint ep1 = null;
    UsbEndpoint ep2 = null;
    boolean UsingSingleInterface = true;

    mDevice = device;

    //This HID device is using a single interface
    if (UsingSingleInterface)
    {
        //usbInterfaceRead = device.getInterface(0x00);//only 1 EP on this interface
        usbInterfaceRead = findInterface(device);

        //Try getting an interface at next index
        //usbInterfaceWrite = device.getInterface(0x01);//throws exception

        // Try using the same interface for reading and writing
        usbInterfaceWrite = usbInterfaceRead;

        int endPointCount = usbInterfaceWrite.getEndpointCount();
        if (DEBUG == 2)
        {
            Toast.makeText(UsbHidDeviceTesterActivity.this, "Endpoints: " + endPointCount, Toast.LENGTH_LONG).show();
            //Toast.makeText(UsbHidDeviceTesterActivity.this, "Interface: " + usbInterfaceRead, Toast.LENGTH_LONG).show();
        }

        if (endPointCount == 1)//only getting 1 endpoint
        {
            ep1 = usbInterfaceRead.getEndpoint(0);
            //As an act of desperation try equating ep2 to this read EP, so that we can later attempt to write to it anyway
            ep2 = usbInterfaceRead.getEndpoint(0);
        }
        else if (endPointCount == 2)
        {
            ep1 = usbInterfaceRead.getEndpoint(0);
            ep2 = usbInterfaceRead.getEndpoint(1);
        }
    }

    else        // ! UsingSingleInterface
    {
        usbInterfaceRead = device.getInterface(0x00);
        usbInterfaceWrite = device.getInterface(0x01);
        if ((usbInterfaceRead.getEndpointCount() == 1) && (usbInterfaceWrite.getEndpointCount() == 1))
        {
            ep1 = usbInterfaceRead.getEndpoint(0);
            ep2 = usbInterfaceWrite.getEndpoint(0);
        }
        if (DEBUG == 3)
        {
            Toast.makeText(UsbHidDeviceTesterActivity.this, "Using Dual Interface", Toast.LENGTH_LONG).show();
        }
    }

    //because ep1 = ep2 this will now not cause a return unless no ep is found at all
    if ((ep1 == null) || (ep2 == null))
    {
        if (DEBUG == 4)
        {
            Toast.makeText(UsbHidDeviceTesterActivity.this, "One EP is null", Toast.LENGTH_LONG).show();
        }
        return false;
    }

    // Determine which endpoint is the read, and which is the write
    if (ep1.getType() == UsbConstants.USB_ENDPOINT_XFER_INT)//I am getting a return of 3, which is an interrupt transfer
    {
        if (ep1.getDirection() == UsbConstants.USB_DIR_IN)//I am getting a return of 128, which is a device-to-host endpoint
        {
            mEndpointRead = ep1;
            if (DEBUG == 5)
            {
                Toast.makeText(UsbHidDeviceTesterActivity.this, "EP1 type: " + ep1.getType(), Toast.LENGTH_LONG).show();
            }
        }
        if (ep1.getDirection() == UsbConstants.USB_DIR_OUT)//nope
        {
            mEndpointWrite = ep1;
            if (DEBUG == 6)
            {
                Toast.makeText(UsbHidDeviceTesterActivity.this, "EP1 is a write", Toast.LENGTH_LONG).show();
            }
        }
    }

    if (ep2.getType() == UsbConstants.USB_ENDPOINT_XFER_INT)
    {
        if (ep2.getDirection() == UsbConstants.USB_DIR_IN)
        {
            //Try treating it as a write anyway
            //mEndpointRead = ep2;
            mEndpointWrite = ep2;
        }
        else if (ep2.getDirection() == UsbConstants.USB_DIR_OUT)
        {
            //usbEndpointWrite = ep2;
            mEndpointWrite = ep2;
        }
    }

    //check that we should be able to read and write
    if ((mEndpointRead == null) || (mEndpointWrite == null))
    {
        return false;
    }
    if (device != null)
    {
        UsbDeviceConnection connection = mUsbManager.openDevice(device);
        if (connection != null && connection.claimInterface(usbInterfaceRead, true))
        {
            Log.d(TAG, "open SUCCESS");
            mConnectionRead = connection;
            // Start the read thread
            //Comment out while desperately attempting to write on this connection/interface
            //Thread thread = new Thread(this);
            //thread.start();

        }
        else
        {
            Log.d(TAG, "open FAIL");
            mConnectionRead = null;
        }
     }
    if (UsingSingleInterface)
    {
        mConnectionWrite = mConnectionRead;
    }
    else //! UsingSingleInterface
    {
        mConnectionWrite = mUsbManager.openDevice(device);
        mConnectionWrite.claimInterface(usbInterfaceWrite, true);
    }
    return true;
}

// searches for an interface on the given USB device
 private UsbInterface findInterface(UsbDevice device) {
    Log.d(TAG, "findInterface " + device);
    int count = device.getInterfaceCount();
    if (DEBUG == 7)
    {
        Toast.makeText(UsbHidDeviceTesterActivity.this, "Interface count: " + count, Toast.LENGTH_LONG).show();
    }

    for (int i = 0; i < count; i++) {
        UsbInterface intf = device.getInterface(i);
        String InterfaceInfo = intf.toString();
        Log.d(TAG, "Interface: " + InterfaceInfo);
        //Class below is 3 for USB_HID
        if (intf.getInterfaceClass() == 3 && intf.getInterfaceSubclass() == 0 &&
                intf.getInterfaceProtocol() == 0) {
            return intf;
        }
        //....try just returning the interface regardless of class/subclass
        //return intf;
    }

    return null;
}
 private boolean sendControlTransfer(byte[] dataToSend)
 {
    synchronized (this)
    {
    if (mConnectionRead != null)
     {
        //byte[] message = new byte[13];  // or 14?
        byte[] message = dataToSend;
         if (DEBUG == 9)
         {
             Toast.makeText(UsbHidDeviceTesterActivity.this, "Sending Control Transfer", Toast.LENGTH_LONG).show();
         }

         //first field ox21 is bin 00100001 which splits into 0 01 00001 for direction(1bit)/type(2b)/recipient(5b)
         //To set direction as 'host to Device' we need 0, To set type to HID we need 11 (3), and for recipient we want 00001
         //second field 0x09 is class specific request code, 0x09 is listed as 'reserved for future use'
         //third field 0x200 is value
         //int transfer = mConnectionRead.controlTransfer(0x21, 0x9, 0x200, 0, message, message.length, 0);
         //try with type set to HID
         int transfer = mConnectionRead.controlTransfer(0xC1, 0x9, 0x200, 0, message, message.length, 0);
         if (DEBUG == 10)
         {
             Toast.makeText(UsbHidDeviceTesterActivity.this, "Transfer returned " + transfer, Toast.LENGTH_LONG).show();
         }
     }
    }
    return true;
 }

private boolean sendInterruptTransfer(byte[] dataToSend)
{
    int bufferDataLength = mEndpointWrite.getMaxPacketSize();//The write endpoint is null unless we just copy the read endpoint
    if (DEBUG == 12)
    {
        Toast.makeText(UsbHidDeviceTesterActivity.this, "Max Packet Size: " + bufferDataLength, Toast.LENGTH_LONG).show();
    }

    ByteBuffer buffer = ByteBuffer.allocate(bufferDataLength + 1);
    UsbRequest request = new UsbRequest();
    buffer.put(dataToSend);

    request.initialize(mConnectionWrite, mEndpointWrite);
    request.queue(buffer, bufferDataLength);

    try
    {
        /* only use requestwait on a read
        if (request.equals(mConnectionWrite.requestWait()))
        {
            return true;
        }
        */
    }
    catch (Exception ex)
    {
        // An exception has occurred
        if (DEBUG == 13)
        {
            Toast.makeText(UsbHidDeviceTesterActivity.this, "Caught Write Exception", Toast.LENGTH_LONG).show();
        }
    }

    return true;
}

A: Control transfer doesn't show any interface descriptor and its endpoint number is 0 by default, for both in and out transfer.
if you have other interfaces the index of those interfaces should start from 0 i.e. default control transfer interface does not count.
So your interface 0 holds the endpoint 1 descriptor. use the UsbEndpoint methods to find the attributes of the endpoint whether it is interrupt type or not. if it is then endpoint type by UsbEndpoint.getType() should return 0x03 and endpoint number by UsbEndpoint.getEndpointNumber() should return 0x81 which is usual value for endpoint 1.
below your code is wrong:
//first field ox21 is bin 00100001 which splits into 0 01 00001 for direction(1bit)/type(2b)/recipient(5b)
     //To set direction as 'host to Device' we need 0, **To set type to HID we need 11 (3)**, and for recipient we want 00001
     //second field 0x09 is class specific request code, **0x09 is listed as 'reserved for future use'**
     //**third field 0x200 is value**
     //int transfer = mConnectionRead.controlTransfer(0x21, 0x9, 0x200, 0, message, message.length, 0);
     //try with type set to HID
     int transfer = mConnectionRead.controlTransfer(0xC1, 0x9, 0x200, 0, message, message.length, 0);

Type 2 bits is used to indicate class specific request, i.e. its value is 01,
0x09 is Hid class specific request SET_REPORT, not reserved.
value is the wValue which is used as Report ID for Hid class, for your case it is probably 0, if you have only one report at you HID descriptor.
and the 4 th parameter is wIndex which should be used to indicate the recipient, for your case it should be 0x01 for interface as recipient.
So your code for control transfer for Read or receive data form device should be:
int transfer = mConnectionRead.controlTransfer(0xA1, 0x01, 0x00, 0x01, message, message.length, 0);

where 0x01 in second parameter is GET_REPORT is Hid calls specific request.
And your code for control transfer for Write or send data to device should be:
int transfer = mConnectionWrite.controlTransfer(0x21, 0x09, 0x00, 0x01, message, message.length, 0);

Since you only have Interrupt IN endpoint 1, Bulk or Interrupt transfer should be like:
int transfer = bulkTransfer (ep1, message, message.length, 0);

to have the interrupt Out endpoint there should be a endpoint descriptor for that at the interface descriptor of firmware of your device.

A: So, I have been researching similar things. I cannot confirm, but what I believe is happening is:

*

*Android does not list the control endpoint when it enumerates it's endpoints. It only lists other endpoints.

*A connection to any endpoint can send control transfers to endpoint 0, through the controlTransfer method, which (quoting from the api) "Performs a control transaction on endpoint zero for this device."

*So, in your above code, I would use the 0th endpoint as an interrupt input endpoint, but it will still allow for control transfers.

*An example of someone using a HID device is the Missle Launcher demo, the device it uses is a HID device with an interrupt endpoint.

A: You can get a full list of the details of interfaces and endpoint by using the following:
UsbManager mManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = mManager.getDeviceList();
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();

while (deviceIterator.hasNext())
    {
        UsbDevice device = deviceIterator.next();
        Log.i(TAG,"Model: " + device.getDeviceName());
        Log.i(TAG,"ID: " + device.getDeviceId());
        Log.i(TAG,"Class: " + device.getDeviceClass());
        Log.i(TAG,"Protocol: " + device.getDeviceProtocol());
        Log.i(TAG,"Vendor ID " + device.getVendorId());
        Log.i(TAG,"Product ID: " + device.getProductId());
        Log.i(TAG,"Interface count: " + device.getInterfaceCount());
        Log.i(TAG,"---------------------------------------");
   // Get interface details
        for (int index = 0; index < device.getInterfaceCount(); index++)
        {
        UsbInterface mUsbInterface = device.getInterface(index);
        Log.i(TAG,"  *****     *****");
        Log.i(TAG,"  Interface index: " + index);
        Log.i(TAG,"  Interface ID: " + mUsbInterface.getId());
        Log.i(TAG,"  Inteface class: " + mUsbInterface.getInterfaceClass());
        Log.i(TAG,"  Interface protocol: " + mUsbInterface.getInterfaceProtocol());
        Log.i(TAG,"  Endpoint count: " + mUsbInterface.getEndpointCount());
    // Get endpoint details
            for (int epi = 0; epi < mUsbInterface.getEndpointCount(); epi++)
        {
            UsbEndpoint mEndpoint = mUsbInterface.getEndpoint(epi);
            Log.i(TAG,"    ++++   ++++   ++++");
            Log.i(TAG,"    Endpoint index: " + epi);
            Log.i(TAG,"    Attributes: " + mEndpoint.getAttributes());
            Log.i(TAG,"    Direction: " + mEndpoint.getDirection());
            Log.i(TAG,"    Number: " + mEndpoint.getEndpointNumber());
            Log.i(TAG,"    Interval: " + mEndpoint.getInterval());
            Log.i(TAG,"    Packet size: " + mEndpoint.getMaxPacketSize());
            Log.i(TAG,"    Type: " + mEndpoint.getType());
        }
        }
    }
    Log.i(TAG," No more devices connected.");
}

A: Maybe it is a late answer or off topic. However, I hope someone will one day find this answer useful.
Github now contains great Android libraries to communicate with custom HID devices:

*

*Mine in Kotlin

*in Java
The good thing is that if you are lucky, then you only need to know the device VID:PID and the commands it accepts. You don't need to worry about USB protocol or communication details.
If interested about how USB works, then you can have a closer look at library source code.


text:
Q: vm extension from storage account in terraform Trying to create VM extension in terraform. file stored in Azure storage account.
resource "azurerm_virtual_machine_extension" "VMextn1" {
    name                 = "avmextn1"
    virtual_machine_id = azurerm_windows_virtual_machine.vm.id
    publisher            = "Microsoft.Compute"
    type                 = "CustomScriptExtension"
    type_handler_version = "1.10"
    auto_upgrade_minor_version = true
    settings             = <<SETTINGS
      {
          "fileUris": ["https://iotstorage15081.blob.core.windows.net/scriptscont/installNodeJS.ps1"],
          "commandToExecute": "powershell -ExecutionPolicy Unrestricted -file installNodeJS.ps1"
      }
  SETTINGS
  }

able to access file from VM by logging into it. but not able to do it from terraform. when executed, it is going into infinite loop i guess. below is the error:
Error: Future#WaitForCompletion: context has been cancelled: StatusCode=200 -- Original Error: context deadline exceeded

A: This error may cause the azure default timeouts is minimum. When we use custom script extension that runs for longer than an expected and it started failing on us with error
Try to add timeouts block on Resource
resource "azurerm_resource_group" "test" {
  name     = "test-resource-group"
  location = "West Europe"

  timeouts {
    create = "20m"
    delete = "40m"
  }
}

And try to use updated provider version like below:
terraform {
  required_providers {
    azurerm = {
      source  = "hashicorp/azurerm"
      version = "=3.0.0"
    }
  }
}

Reference:  Resource Timeouts for creation terraform-provider-azurerm by Tom Harvey


text:
Q: Postgres INSERT INTO with Two Select Statements I'm trying to insert into a relational table with the result of two SELECT queries.
table 1:
id | url
-------------------------
1  | http://something.com

table 2:
id | address
----------------------------
1  | something@something.com

table 3:
table1_id | table2_id
---------------------
1         | 1

And I'm trying to build a INSERT query combined out of two SELECTs and a UNION
I've been working with this:
INSERT INTO table3
SELECT id FROM table1
WHERE table1.url = 'http://something.com'
UNION
SELECT id FROM table2
WHERE table2.address = 'something@something.com';

Where have I gone wrong with this? I'm getting an error on the second SELECT, it is able to SELECT the first ID and pass it into the INSERT, but it's trying to insert (1, null) even though the second SELECT is valid on its own.

A: INSERT INTO table 3
    select A.id, B.id
    from Table1 A
    cross join Table2 B
    where A.url = 'http://something.com'
      and B.address = 'something@something.com'


text:
Q: Model Agency Database Schema I would like to make a model agency based on codeigniter, but im a but stuck with the database, exactly the registration part.
I would like to allow users to sign up as, model, photohgrapher, studo.
I was searchin around the net but couldnt really find anything helpful.
Could someone please give me a hint where i can find a schema for a model agency database? or someghing similar?
I would like to have 3 acount tpye in the registration, models, photographers, studios
And im stuck at this part, so actually the models will have more options like the photographer or the studos, and i dont really want to store all options in one table.
Thank you
Or if someone could give me and opinion would be happy about it.

A: You have to work with a role based system:
account
id - description - role
0 - Model    - 2
1 - Photographer - 0
2 - Studio  - 1
role
id - add_photos - edit_data - view_model_details
0 - 1 - 0 - 0
1 - 0 - 1 - 1
2 - 1 - 1 - 1
Users
Id - name - account
0 - Norma Jean - 0
1 - Max - 2
2 - James Hickey - 1
The role table lets you define different actions for the groups.

A: Model
  id  Integer
  name String

Studio
  id Integer
  name String

Registration
  id  Integer
  model_id Integer
  studio_id Integer
  reg_date Date


text:
Q: how I can mapping complex JSON to other JSON I am trying to build aggregation services, to all third party APIs that's I used,
this aggregation services taking json values coming from my main system and it will put this value to key equivalent to third party api key then, aggregation services it will send request to third party api with new json format.
example-1:
package main

import (
    "encoding/json"
    "fmt"
    "log"

    "github.com/tidwall/gjson"
)

func main() {
    // mapping JSON
    mapB := []byte(`
    {
        "date": "createdAt",
        "clientName": "data.user.name"
    }
    `)

    // from my main system
    dataB := []byte(`
    {
        "createdAt": "2017-05-17T08:52:36.024Z",
        "data": {
            "user": {
                "name": "xxx"
            }
        }
    }
    `)

    mapJSON := make(map[string]interface{})
    dataJSON := make(map[string]interface{})
    newJSON := make(map[string]interface{})

    err := json.Unmarshal(mapB, &mapJSON)
    if err != nil {
        log.Panic(err)
    }

    err = json.Unmarshal(dataB, &dataJSON)
    if err != nil {
        log.Panic(err)
    }

    for i := range mapJSON {
        r := gjson.GetBytes(dataB, mapJSON[i].(string))
        newJSON[i] = r.Value()
    }

    newB, err := json.MarshalIndent(newJSON, "", "  ")
    if err != nil {
        log.Println(err)
    }

    fmt.Println(string(newB))
}

output:
{
  "clientName": "xxx",
  "date": "2017-05-17T08:52:36.024Z"
}

I use gjson package to get values form my main system request in simple way from a json document.
example-2:
import (
    "encoding/json"
    "fmt"
    "log"

    "github.com/tidwall/gjson"
)

func main() {
    // mapping JSON
    mapB := []byte(`
    {
        "date": "createdAt",
        "clientName": "data.user.name",
        "server":{
            "google":{
                "date" :"createdAt"
            }
        }
    }
    `)

    // from my main system
    dataB := []byte(`
    {
        "createdAt": "2017-05-17T08:52:36.024Z",
        "data": {
            "user": {
                "name": "xxx"
            }
        }
    }
    `)

    mapJSON := make(map[string]interface{})
    dataJSON := make(map[string]interface{})
    newJSON := make(map[string]interface{})

    err := json.Unmarshal(mapB, &mapJSON)
    if err != nil {
        log.Panic(err)
    }

    err = json.Unmarshal(dataB, &dataJSON)
    if err != nil {
        log.Panic(err)
    }

    for i := range mapJSON {
        r := gjson.GetBytes(dataB, mapJSON[i].(string))
        newJSON[i] = r.Value()
    }

    newB, err := json.MarshalIndent(newJSON, "", "  ")
    if err != nil {
        log.Println(err)
    }

    fmt.Println(string(newB))
}

output:
panic: interface conversion: interface {} is map[string]interface {}, not string

I can handle this error by using  https://golang.org/ref/spec#Type_assertions, but what if this json object have array and inside this array have json object ....
my problem is I have different apis, every api have own json schema, and my way for mapping json only work if
third party api have json key value only, without nested json or array inside this array json object.
is there a way to mapping complex json schema, or golang package to help me to do that?

A: EDIT:
After comment interaction and with updated question. Before we move forward, I would like to mention.

I just looked at your example-2 Remember one thing. Mapping is from one form to another form. Basically one known format to targeted format. Each data type have to handled. You cannot do generic to generic mapping logically (technically feasible though, would take more time & efforts, you can play around on this).

I have created sample working program of one approach; it does a mapping of source to targeted format. Refer this program as a start point and use your creativity to implement yours.
Playground link: https://play.golang.org/p/MEk_nGcPjZ
Explanation: Sample program achieves two different source format to one target format. The program consist of -

*

*Targeted Mapping definition of Provider 1

*Targeted Mapping definition of Provider 2

*Provider 1 JSON

*Provider 2 JSON

*Mapping function

*Targeted JSON marshal

Key elements from program: refer play link for complete program.
type MappingInfo struct {
    TargetKey     string
    SourceKeyPath string
    DataType      string
}

Map function:
func mapIt(mapping []*MappingInfo, parsedResult gjson.Result) map[string]interface{} {
    mappedData := make(map[string]interface{})
    for _, m := range mapping {
        switch m.DataType {
        case "time":
            mappedData[m.TargetKey] = parsedResult.Get(m.SourceKeyPath).Time()
        case "string":
            mappedData[m.TargetKey] = parsedResult.Get(m.SourceKeyPath).String()
        }
    }
    return mappedData
}

Output:
Provider 1 Result: map[date:2017-05-17 08:52:36.024 +0000 UTC clientName:provider1 username]
Provider 1 JSON: {
  "clientName": "provider1 username",
  "date": "2017-05-17T08:52:36.024Z"
}

Provider 2 Result: map[date:2017-05-12 06:32:46.014 +0000 UTC clientName:provider2 username]
Provider 2 JSON: {
  "clientName": "provider2 username",
  "date": "2017-05-12T06:32:46.014Z"
}

Good luck, happy coding!

Typically Converting/Transforming one structure to another structure, you will have to handle this with application logic.
As you mentioned in the question:

my problem is I have different apis, every api have own json schema

This is true for every aggregation system.

One approach to handle this requirement effectively; is to keep mapping of keys for each provider JSON structure and targeted JSON structure.
For example: This is an approach, please go with your design as you see fit.
JSON structures from various provider:
// Provider 1 : JSON structrure
{
  "createdAt": "2017-05-17T08:52:36.024Z",
  "data": {
    "user": {
      "name": "xxx"
    }
  }
}

// Provider 2 : JSON structrure
{
  "username": "yyy"
  "since": "2017-05-17T08:52:36.024Z",
}

Mapping for target JSON structure:
jsonMappingByProvider := make(map[string]string)

// Targeted Mapping for Provider 1
jsonMappingByProvider["provider1"] = `
{
    "date": "createdAt",
    "clientName": "data.user.name"
}
`

// Targeted Mapping for Provider 2
jsonMappingByProvider["provider2"] = `
{
    "date": "since",
    "clientName": "username"
}
`

Now, based the on the provider you're handling, get the mapping and map the response JSON into targeted structure.
// get the mapping info by provider
mapping := jsonMappingByProvider["provider1"]

// Parse the response JSON
// Do the mapping

This way you can control each provider and it's mapping effectively.


text:
Q: Linq Expression gets Convert function inserted In my project for certain properties the expression for the form (x=>x.property) comes out as (x=>Convert(x.property)) at runtime as shown :

It depends upon property type, double and DateTime seem to be the culprit. Works fine for string properties (e.g Speed and ForeColour are both strings)
Why is it coming out this way?

A: double and DateTime are value types. The compiler is using Expression.Convert to represent the boxing operation, basically.
string is already a reference type, so no conversion is required.
You can see the same thing in normal code:
double d = 0.5;
string s = "hello";

object o1 = d;
object o2 = s;

... compiles to:
// d = 0.5
IL_0001:  ldc.r8     0.5
IL_000a:  stloc.0

// s = "hello"
IL_000b:  ldstr      "hello"
IL_0010:  stloc.1

// o1 = d - boxing!
IL_0011:  ldloc.0
IL_0012:  box        [mscorlib]System.Double
IL_0017:  stloc.2

// o2 = s - no boxing required!
IL_0018:  ldloc.1
IL_0019:  stloc.3


text:
Q: HTML5 & CSS3 | Is it semantically correct or not?
 I've got a question: is it a bad practice to make this lines by css & html code, or it's better just to get this lines from .psd layout and just paste it in html as a picture?
 Thank you for your attention!
Here is some pics:

A: Semantically it depends on your needs: If you need to change colors frequently it's more efficient to use html than always have to create a new image file...if it's an one time modification, image is enough. But technically by code is a better option because you save bandwidth and processing from your infrastructure.

A: In a world of increasing resolution, it's a good idea to avoid images if you can.
Using HTML/CSS or SVG guarantees perfect results regardless of the resolution of the viewer's device.
Using an image guarantees that somewhere, sometime, someone will display it in a way that makes it look blurry and poor quality.


text:
Q: User defined functions in jQuery + Delay I have this code:
function rotate(x){
  $('#card').css({
    transform: 'rotate('+x+')'
  })
}

$(function(){
  $('#rotation-test').click(function(){
    rotate('3600deg').delay(15000).rotate('-36000deg');
  })
});

What I want to do is to call function rotate when element is clicked. Then wait 15 sec, and call same function again (with different param). I am aware this is not legit. How would I get the same effect?

A: As people commented to my question, there seems to be no other way than using setTimeout, so this is how I did it in case someone gets same problem.
function rotate(x){
  $('#card').css({
    transform: 'rotate('+x+')'
  })
}

$(function(){
  $('#rotation-test').click(function(){
    setTimeout(rotate,0,'3600deg');
    setTimeout(rotate,10000,'-3600deg');
  })
});


text:
Q: Query to pull unique qty of an item I have a table:

item
qty
area

1234
12
AAA

1234
11
BBB

1234
10
CCC

5678
5
AAA

4578
10
AAA

852
8
AAA

852
9
BBB

852
10
CCC

And the expected result to show only item available only in area AAA no other area

item
qty
area

5678
5
AAA

4578
10
AAA

I was trying to use the below query but the result was not sufficient as it give all the item in AAA not the unique ones I am looking for
select
  item
  , coalesce(sum(case when area = 'AAA' then qty end ) ,0) as 'AAA'
from MyTable
group by item

A: Use NOT EXISTS to check that no other area exists for the same item.
select item, qty, area
from MyTable mt1
where area = 'AAA'
and not exists (
    select 1
    from MyTable mt2
    where mt2.item = mt1.item and mt2.Area <> 'AAA'
);

A: Something like this perhaps.  In the CASE expression, using "else 0" will avoid nulls and the warning message about them being eliminated.
WITH MyTable as (
    SELECT *
    FROM (
        VALUES
            ('1234', 12, 'AAA'),
            ('1234', 11, 'BBB'),
            ('1234', 10, 'CCC'),
            ('5678', 5, 'AAA'),
            ('4578', 10, 'AAA'),
            ('852', 8, 'AAA'),
            ('852', 9, 'BBB'),
            ('852', 10, 'CCC')
        ) t (item, qty, area)
)
SELECT item, coalesce(sum(case when area = 'AAA' then qty else 0 end ) ,0) as 'AAA'
from MyTable
group by item
having count(*) = 1

[Edit] This also works, but I think Dale's answer is still better.
SELECT item, SUM(qty) as 'AAA'
from MyTable
group by item
having count(*) = 1 AND MIN(area) = 'AAA'


text:
Q: Java file not written to stream with new line characters We're streaming a CSV file from a web service.  It appears that we're losing the new line characters when streaming - the client gets the file all on a single line.  Any idea what we're doing wrong?
Code:
 public static void writeFile(OutputStream out, File file) throws IOException {
    BufferedReader input = new BufferedReader(new FileReader(file)); //File input stream
    String line;
    while ((line = input.readLine()) != null) { //Read file
        out.write(line.getBytes());  //Write to output stream
        out.flush();
    }
    input.close();
}

A: The readline method uses the newline chars to delimit what gets read, so the newlines themselves are not returned by readLine.
Don't use readline, you can use a BufferedInputStream and read the file one byte at a time if you want, or pass your own buffer into OutputStream.write.
Note that, like BalusC and Michael Borgwardt say, Readers and Writers are for text, if you just want to copy the file you should use InputStream and OutputStream, you are only concerned with bytes.

A: There are several things wrong with that code. It may also mutilate any NON-ASCII text since it converts via the platform default encoding twice - and for no good reason at all.
Don't use a Reader to read the file, use a FileInputStream and transfer bytes, avoiding the unnecessary and potentially destructive charset conversions. The line break problem will also be gone.

A:
Any idea what we're doing wrong?

Yes. This line drops the "new line character"
while ((line = input.readLine()) != null) {

And then you write it without it:
 out.write(line.getBytes());

This this related question.

A: Don't use BufferedReader. You already have an OutputStream at hands, so just get an InputStream of the file and pipe the bytes from input to output it the usual Java IO way. This way you also don't need to worry about newlines being eaten by BufferedReader:
public static void writeFile(OutputStream output, File file) throws IOException {
    InputStream input = null;
    byte[] buffer = new byte[10240]; // 10KB.
    try {
        input = new FileInputStream(file);
        for (int length = 0; (length = input.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
        }
    } finally {
        if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
    }
}

Using a Reader/Writer would involve character encoding problems if you don't know/specify the encoding beforehand. You actually also don't need to know about them here. So just leave it aside.
To improve performance a bit more, you can always wrap the InputStream and OutputStream in an BufferedInputStream and BufferedOutputStream respectively.

A: BufferedReader.ReadLine() does not preserve the newline. Thus you'll have to add it when writing it out

A: You can use a PrintWriter which offers a prinln() method. This will also save you from converting the string into an array of chars.
public static void writeFile(OutputStream o, File file) throws IOException {
   PrintWriter out = new PrintWriter(new OutputStreamWriter(o));
   BufferedReader input = new BufferedReader(new FileReader(file)); //File input stream
   String line;
   while ((line = input.readLine()) != null) { //Read file
       out.println(line);  //Write to output stream
       out.flush();
   }
   input.close();
}


text:
Q: How to change the language of all Web Applications of the ArcGIS Server manager (for ASP.NET)? ArcGIS Server manager (ASP.NET) comes by default the English language. I would like to configure it to Portuguese of Brazil.
It is ok if the administrative tool is in English.
But I'd really like is that the maps Labels were in Portuguese. As in the words: Results, "Query Attributes", "Find", and others.
So my users to access my Web Applications in the native language of maps here.
I know I could edit the Labels in Visual Studio (VS), but this is laborious. And my co-workers do not know how to work in VS. Because I'm the Analyst Informatics and they cartographers. VS is complex for them who do not know how to program.
How to configure all Web Application to another language?
Thank you!

A: Solved!
To do this, simply edit the text file in the Labels:

C:\inetpub\wwwroot\ArcGIS\Manager\Modules\Applications\Templates\mv_cs\default.aspx

That way, all the new Web Applications will be ok.
Thankful! ;)


text:
Q: Cefpython cx_freeze errors After much trying ive finally found a way to compile my Cefpython code:
import json
import urllib.request
from cefpython3 import cefpython as cef
import platform
import sys

url = "https://google.com/"

def main():
    check_versions()
    sys.excepthook = cef.ExceptHook
    cef.Initialize()
    cef.CreateBrowserSync(url=url,
                          window_title="browser")
    cef.MessageLoop()
    cef.Shutdown()

def check_versions():
    ver = cef.GetVersion()
    print("[hello_world.py] CEF Python {ver}".format(ver=ver["version"]))
    print("[hello_world.py] Chromium {ver}".format(ver=ver["chrome_version"]))
    print("[hello_world.py] CEF {ver}".format(ver=ver["cef_version"]))
    print("[hello_world.py] Python {ver} {arch}".format(
           ver=platform.python_version(),
           arch=platform.architecture()[0]))
    assert cef.__version__ >= "57.0", "CEF Python v57.0+ required to run this"

if __name__ == '__main__':
    main()

(the jason and urllib.request are there so that the compilers (py2exe pyinstaller ect) dont give errors)
Using cx_Freeze but when I run the exe cx_freeze gives me this happens:
[0930/071436.905:ERROR:main_delegate.cc(710)] Could not load locale pak for en-US
[0930/071436.906:ERROR:main_delegate.cc(717)] Could not load cef.pak
[0930/071436.906:ERROR:main_delegate.cc(734)] Could not load cef_100_percent.pak
[0930/071436.906:ERROR:main_delegate.cc(743)] Could not load cef_200_percent.pak
[0930/071436.907:ERROR:main_delegate.cc(753)] Could not load cef_extensions.pak
[0930/071436.926:ERROR:content_client.cc(272)] No data resource available for id 101

(from the debug.log)
I think this is a cefpython thing but I dont know.


text:
Q: Issue With Arrays For Finding Duplicate Integers I am currently doing practice with programming (particularly with C Programming) and I am trying out an end of chapter problem which has this description:
"Use a single-subscripted array to solve the following problem.
Read in 20 numbers, each of which is between 10 and 100, inclusive. As each number is read, print
it only if it's not a duplicate of a number already read. Provide for the "worst case" in which all 20
numbers are different. Use the smallest possible array to solve this problem"
Here is what I have so far:
#include <stdio.h>
#include <stdbool.h> //used this library for the ability to use true and false
#define SIZE 20

bool searchArray(int integer, unsigned int j); //prototype for the searchArray function

int main (void)
{

bool print;
int numbers[20];
unsigned int i;

for (i = 0; i < SIZE; i++)
{
    scanf("%d", &numbers[i]);
    print = searchArray(numbers[i], i); //receives true or false

    if (print == true)
    {
        printf("\nNumber at element %d: %d\n", i, numbers[i]);
    }
    else if (print == false)
    {
        printf("\nThis element has a copy in the array already\n");
    }

}

}

bool searchArray(int integer, unsigned int j) //function that helps decide whether or not to print out the integer
{
static int numberscopy[20];
unsigned int n;

numberscopy[j] = integer;

for (n = 0; n < SIZE; n++)
{

        if (numberscopy[n] == numberscopy[j] && n != j) // for making sure that the inputted integer is equal to any element that's currently in the array and making sure it's not including the very same integer that was just input on it's first appearance
        {
            return false;
        }
    return true;
}

}

EXPLANATION: What I did in this program was that I defined a function called searchArray which based on the inputs of the current array element and array index return a boolean value (true or false). In my for loop in the main function, I used scanf to receive integers from the user one at a time. Each of those integer elements are put into an array index in an array called "numbers".
Then, both the array element and the current index of the array that the program is on is put into the searchArray function. Within the searchArray function, each element is input into the function's local 20 element array called "numberscopy" (where in that array each number is put in is based on the current value of i that gets passed the searchArray). Then within the searchArray function, there is a for loop which searches through all the current elements in the numberscopy array and checks if that integer that was just put in is already in the numberscopy array. If found, it returns "false". If not, then "true" gets automatically returned instead.
I thought this would work, but the problem is that it seems to only be able to detect duplicates of the very first integer that is input on each run. For an example, if a number 25 is input first, then a 32 next, then a 25 again and then a 32 again, it properly detects the 25 is already in the array when I put 25 in the second time, but for the 32, it doesn't seem to detect it and prints 32 when it's put in again. The example here
Anyone know why this is not working like I thought it would?

A: for (n = 0; n < SIZE; n++)
{

        if (numberscopy[n] == numberscopy[j] && n != j)
        {
            return false;
        }

}
        return true;
}

instead of
for (n = 0; n < SIZE; n++)
{

        if (numberscopy[n] == numberscopy[j] && n != j)
        {
            return false;
        }
    return true;
}

}


text:
Q: Sakai + Preference Tool + make Visible I want to change the language of sakai . so I need the preference tool. How do I make visible to administrator?
Thanks,
Nirav

A: Using the Admin Workspace Sites tool you can add the User Preferences tool to the ~admin site and then the admin user can manage their own language. Other users can do the same via their My Workspace site.
Note that if you want to change the language of the entire Sakai installation, you need to set it in JAVA_OPTS.

A: To change the default language of Sakai specify it as a command line option when starting tomcat. For example to change the default language to french add:
-Duser.language=fr

to the startup options. More details can be found on the Sakai i18n FAQ. Currently it isn't possible to change the default language for all users of Sakai using the web interface.


text:
Q: Sorting in create selector I have a list of conversations and I want to sort them according to the updatedAt property. Is it possible to do the following when using createSelector:
export const getSortedConversations = createSelector(
  (state) => state.entities.chat,
  (chat) => chat.conversations.sort((a, b) => a.updatedAt - b.updatedAt)
)

I'm attempting to do so but when I use that selector the conversations don't get set into the state at all.


text:
Q: Prolog list of predicates to list of lists I have a list like: [a([x,y]), b([u,v])] and I want my result as [[x,y], [u,v]].
Here is my code:
p(L, Res) :-
    findall(X, (member(a(X), L)), A1), append([A1],[],L1),
    findall(Y, (member(b(Y), L)), A2), append(L1,[A2],L2),
    append(L2, Res).

This provides a partially good result but if my list is [a([x,y]), c([u,v])], I would like the result to be: [[x,y],[]] and it is [[x,y]].
 More examples:
 p([b([u,v]), a([x,y]), c([s,t]), d([e,f])], R)

The result I get: [[x,y],[u,v]] (as expected).
p([b([u,v]), z([x,y]), c([s,t]), d([e,f])], R)

The result I get: [[u,v]]'.
The result I want: [[],[u,v]].
EDIT: Added more examples.

A: Now that it's clear what the problem statement really is, the solution is a little more understood. Your current solution is a little bit overdone and can be simplified. Also, the case where you want to have a [] element when the term isn't found falls a little outside of the paradigm, so can be handled as an exception. @AnsPiter has the right idea about using =../2, particularly if you need a solution that handles multiple occurrences of a and/or b in the list.
p(L, Res) :-
    find_term(a, L, As),     % Find the a terms
    find_term(b, L, Bs),     % Find the b terms
    append(As, Bs, Res).     % Append the results

find_term(F, L, Terms) :-
    Term =.. [F, X],
    findall(X, member(Term, L), Ts),
    (   Ts = []              % No results?
    ->  Terms = [[]]         % yes, then list is single element, []
    ;   Terms = Ts           % no, then result is the list of terms
    ).

Usage:
| ?- p([b([u,v]), z([x,y]), c([s,t]), d([e,f])], R).

R = [[],[u,v]]

yes
| ?-  p([b([x,y]), a([u,v])], L).

L = [[u,v],[x,y]]

yes
| ?-

The above solution will handle multiple occurrences of a and b.
If the problem really is restricted to one occurrence of each, then findall/3 and append/3 are way overkill and the predicate can be written:
p(L, [A,B]) :-
    (   member(a(A), L)
    ->  true
    ;   A = []
    ),
    (   member(b(B), L)
    ->  true
    ;   B = []
    ).

A: Term =.. List :  Unifies List with a list whose head is the atom corresponding to the principal functor of
Term and whose tail is a list of the arguments of Term.
Example :
| ?- foo(n,n+1,n+2)=..List.
List = [foo,n,n+1,n+2] ?

| ?- Term=..[foo,n,n+1,n+2].
Term = foo(n,n+1,n+2)

rely on your suggestion; you have a term contains a single argument List
so ;
p([],[]).
p([X|Xs], Result) :-
            X=..[F,Y],
            (%IF
            \+(F='c')-> % not(F=c)
            Result=[Y|Res];
            %ELSE
            Result = Res % Result = [Res] ==> [[x,y],[]]
            ),
            p(Xs,Res).

Test :
| ?- p([a([x,y]), c([u,v])],R).
R = [[x,y]] ?
yes

| ?- p([a([x,y]), b([u,v])],R).
R = [[x,y],[u,v]] ?
yes


text:
Q: Warning Messages appeared after upgrade saxon to 9.5.1.8 We are upgrading saxon 9.3.0.2 to saxon ee-9.5.1.8 after the upgrade is finised we get's alot of warning's
net.sf.saxon.trans.XPathException: The source document is in namespace [MY-NAME-SPACE] , but none of the template rules match elements in this namespace
    at net.sf.saxon.Controller.warning(Controller.java:954)
    at net.sf.saxon.Controller.transformDocument(Controller.java:2081)
    at net.sf.saxon.Controller.transform(Controller.java:1911)

I removed the namespace from the xsl and i still get this warning
Anyone know's what's going on ? How to remove this warning ?

A: The first thing to do is to establish whether the warning is a false alarm.
The warning was added to Saxon because of the large number of people making the same mistake (about one a day ask the question on StackOverflow, so heaven only knows how many are suffering silently). In particular, the mistake is to have a source document like this:
<foo xmlns="http://default.namespace.com/">
  <bar/>
  <baz/>
</foo>

and then to write match patterns like
<xsl:template match="foo"/>
<xsl:template match="bar"/>

which will never match anything because they ignore the namespace.
So what Saxon does is this: if
(a) the outermost element of the source document is in a namespace
(b) there are template rules in the stylesheet that match specific element names
(c) there's no intersection between the namespaces of elements that are matched by the stylesheet and the namespaces that actually occur in the source document
then it outputs this warning.
If it really is a false alarm, there are a couple of ways you can suppress it:
(a) add a dummy template rule to your stylesheet, perhaps with a predicate that means it will never match anything, but which uses the namespace of the source document, just to tell the processor you know what you're doing.
(b) set the configuration property FeatureKeys.SUPPRESS_XSLT_NAMESPACE_CHECK, which can do from within the API like this:
import net.sf.saxon.s9api.Processor;
import net.sf.saxon.s9api.XsltCompiler;

Processor processor = new Processor(configuration);
processor.setConfigurationProperty(FeatureKeys.SUPPRESS_XSLT_NAMESPACE_CHECK, "true");
XsltCompiler xsltCompiler = processor.newXsltCompiler();

or from the command line by adding --suppressXsltNamespaceCheck:on.
It it is a false alarm, I would love to see the details so that we can refine the checking. We do know that there are cases where the conditions can occur quite legitimately, for example when your initial source document is a simple list of files to be processed, and all the real work of the stylesheet is in processing those files; but we thought it worth having a small number of false alarms to save beginners the frustration of solving this simple and common problem.


text:
Q: Adding Items with same ids together in Local Storage I am working on creating an add to cart option in local storage to send to our ESP for cart abandonment. I have the items once added to the cart storing in Local Storage under the key: cart. The cart creates an array and each time a product is added a new object is inserted into the array. What I am trying to figure out now is, when an item with the same sku is added again, how to I get it to update the object that is already there instead of inserting another object into the array.
// Try to retreive the count of shopping cart items from localStorage
var cartCounter = localStorage.getItem('cartCounter');

if (cartCounter != null) {
  // We already have at least one item in localStorage so increment the counter
  cartCounter = parseInt(cartCounter) + 1
}
else {
  // No items in localStorage so initialize the counter
  cartCounter = 1;
}

// Get the data layer push
var pr = {{DL - Add To Cart}};

// Store product sku, name, and price in localStorage
// Using string format product[cartCounter]attribute for the key
localStorage.setItem('product' + cartCounter + 'sku', pr.fullProductSKU);
localStorage.setItem('product' + cartCounter + 'name', pr.name);
localStorage.setItem('product' + cartCounter + 'price', pr.price);
localStorage.setItem('product' + cartCounter + 'quantity', pr.quantity);

var addItem = function (sku, qty, price) {
    var oldItems = JSON.parse(localStorage.getItem('cart')) || [];
    var newItem = {
        'product-sku': sku,
        'product-qty': qty,
        'product-price': price
    };
    oldItems.push(newItem);
    localStorage.setItem('cart', JSON.stringify(oldItems));
};

console.log(JSON.parse(localStorage.getItem('cart')));
addItem(pr.fullProductSKU, pr.quantity, pr.price);

Here is the output I get which is great but the first two items have the same SKU so I want the to be combined into 1 object with qty showing 2 and price to be updated as well.
[{product-sku: "965000070", product-qty: 1, product-price: 40.99}
 {product-sku: "965000070", product-qty: 1, product-price: 40.99}
 {product-sku: "965000244", product-qty: 1, product-price: 48.99}]

Here is what I would the output to be:
[{product-sku: "965000070", product-qty: 2, product-price: 81.98}
 {product-sku: "965000244", product-qty: 1, product-price: 48.99}]

A: You could just look in the array retrieved from cart, and check if the product is already included, and then update the quantity. For instance, find can be used for that look-up:
var addItem = function (sku, qty, price) {
    var oldItems = JSON.parse(localStorage.getItem('cart')) || [];
    var match = oldItems.find(function (item) {
        return item['product-sku'] === sku;
    });
    if (match) {
        match['product-qty'] += qty;
        match['product-price'] += price;
    } else {
        var newItem = {
            'product-sku': sku,
            'product-qty': qty,
            'product-price': price
        };
        oldItems.push(newItem);
    }
    localStorage.setItem('cart', JSON.stringify(oldItems));
};


text:
Q: Phoenix seems to be preventing image caching for  tags dynamically added to the DOM Each time the Add button is pressed in this example, a request goes to the server even though the cache-control header is set to prevent that.
cachetest.html.eex:
<button onclick="add()">Add</button>

avatar_controller.ex
...
  def image(conn, %{"avatar_id" => id}) do
    a = Avatars.get_avatar(id)
    img = a.image_jpg
    conn
    |> Conn.put_resp_content_type("image/jpeg")
    |> Conn.put_resp_header("cache-control", "max-age=3600, public")
    |> Conn.send_resp(200, img)
  end
...

When I copy cachetest.html.eex to index.html and open it directly in a browser, the caching works fine and no additional requests are made to the server.
How can I get the caching to work within Phoenix?

A: As it happens, caching was disabled in the browser dev tools. Turning it back on fixed the problem.


text:
Q: Android Studio: Error parsing XML & URI is not registered After adding a new Activity to my project I get following error while compiling the layout

Gradle: Error parsing XML: not well-formed (invalid token)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:orientation="vertical" >

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/tv_password"
        android:text="<password>"/>
</LinearLayout>

"http://schemas.android.com/apk/res/android" is marked red and hovering pops following message up

URI is not registered ( Setting | Project Settings | Schemas and DTDs )

My Settings>Project Settings>Schemas and DTDs look like that:

I already found some similar questions around here but nothing helped me to solve this issue. I hope someone has an idea... :)

A: For me, the problem occured when I created my own subfolder for old code.
Specifically, Android Studio threw an error for all layout files that weren't in the default folder ../res/drawable/, but instead placed in my own subfolder ../res/drawable/backup.

A: I got the same error for a long time and none of the answers I found online really helped me, or probably I wasn't looking the right way. At the end what I found out was the way I named the directory. So, I was trying to make the landscape layout for my app and named it layout_land. That kept showing me the URI is not registered error. I just had to change the directory name to layout-land.
Summary: No underscores in directory names!

A: I was having a similar issue. However, the comments did not assist me in the solution to this issue. This answer from this question actually solved my problem.
Summary:
Go to "File > Project Structure > Modules", click "add" and then click "android" and "apply/ok". That should solve anyone having a similar problem but the comments for this question are not helping you.

A: My issue was creating new resource directory for some animation work. The files were .xml and I chose file type as "xml". I got this problem. Changing the file type to "values" and the problem went away. No idea why, could someone explain this to me? I'm using Android Studio on an iMac.

A: GO to settings >Language&Framework >Schemas&DTD
here add Uri used in your code.

A: Some special characters not allowed here.
Directly to assign text then with warning
android:text="value"

@string file from get then avoid warning
android:text="@string/hello"

res/values/strings.xml
 <?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello!</string>
</resources>

A: For me this problem was gone when I have made following changes to my project structure on Android Studio.
file->project structure ->SDK Location -> enable check mark for "Use embedded JDK (recommended).
Hope this will help someone.

A: First thing is go to the project folder in the Android studio and check for any folders which are created by you. It will show this error if you have created any folder on your own.


text:
Q: mysql data inline command Is it possible to use "load data local infile" in mysql and set a column to a certain value...
So for example if my commannd is:
mysql_query('load data local infile "'.$filename.'" into table products fields terminated by "|" lines terminated by "\n" (column2, column3, column4)');

Then have a table like this
Column 1 | Column 2 | Column 3 | Column 4

can set column 1 equal to value I choose and have it done in this query? I am trying to have column 1 be equal to the filename it is importing...how would I set this into the sql query?

A: According to load data infile syntax you can do it like this:
mysql_query('load data local infile "'.$filename.'" into table products fields terminated by "|" lines terminated by "\n" (column2, column3, column4) SET column1=\'' . $filename . '\'');

From the link above: "The SET clause can be used to supply values not derived from the input file..."
(I'm not sure if something is messed up with single/double quotes...didn't try it).


text:
Q: "no-unused-variable": true is not working in VSCode I am trying to use tslint with typescript in an Ionic3 project. When I add "no-unused-variable": true in the tslint.json, it has no effect. Please help me.

A: You can use the code editor feature to remove the unused import variables. e.g. vscode provide a feature run-code-actions-on-save
Add below config in your settings.json file of vscode:
{
  "[typescript]": {
    "editor.codeActionsOnSave": {
      "source.organizeImports": true
    }
  }
}

It will remove the unused import variables and organize your import statement.

A: People have reported problems with that rule while using VSCode.
A potential fix is to remove it from your tslint.json, and replace it with "noUnusedLocals": true in your tsconfig.json


text:
Q: Scraping infinite scrolling table data I want to ask how to scrape table data at this website https://gis.dukcapil.kemendagri.go.id/peta/ using python?
Data at this table:

A: If you inspect the network tab in your browser tools. You will see the data is being population via rest api call. In such cases, you can directly make the api call to get the data. There is no need to extract data from the table.
For this particular website, this is api call that is loading the entire data in the table.
https://gis.dukcapil.kemendagri.go.id/arcgis/rest/services/Data_Baru_26092017/MapServer/3/q[…]rsects&outFields=*&resultOffset=0&resultRecordCount=25

Happy Scraping :)


text:
Q: Plot residuals in linear model for specific date Edit: Took the first answer given and made a function for further use out of it, but not using the dplyr-package. Still, it builds heavily on the given answer, so thank you.
plot_one_day <- function(LM,Day,DF) {Residuals<-resid(LM)
Filter=cbind(DF,Residuals)
Filterdata= Filter[Filter$Time>=paste(Day,"00:00:00") & Filter$Time<=paste(Day,"23:50:00"),]
Filter_NARM=Filterdata[!is.na(Filterdata$Residuals),]
plot(Residuals ~ Time, data=Filter_NARM, main=paste("Correlation for the",substr(Filter_NARM[1,1],1,10)),xlab="Time",
     xlim=range(Filterdata$Time), ylim=range(Filter_NARM$Residuals))
abline(h=0, col="red")
}

plot_one_day(LM_1,"2015-05-07",MyData)

When you have a dataframe like this:
start <- as.POSIXct("2015-05-05 06:00:00", format="%Y-%m-%d %H:%M:%S")
end   <- as.POSIXct("2015-05-07 20:00:00", format= "%Y-%m-%d %H:%M:%S")
Time=seq.POSIXt(start, end, by="10 min")

MyData=data.frame(Time=Time,Rain=rep(0,(length(Time))),Rain_Binary=rep(0,(length(Time))),People=rep(0,(length(Time))))
MyData[c(2:4,154:157,324:328),2]=5
MyData$People=round(runif(length(Time),0,50), digits=0)

for (Z in 1:nrow(MyData)) {Today= substr(MyData[Z,1], 1, 10)
if(any(MyData$Rain[((MyData$Time>= strptime(paste(Today, "06:30:00", sep = " "),format="%Y-%m-%d %H:%M:%S"))&
                    (MyData$Time<= strptime(paste(Today, "09:00:00", sep = " "),format="%Y-%m-%d %H:%M:%S")))]>0)) {MyData$Rain_Binary[(MyData$Time>=strptime(paste(Today, "06:30:00", sep = " "),format="%Y-%m-%d %H:%M:%S"))&
                                                                                (MyData$Time<= strptime(paste(Today, "20:00:00", sep = " "),format="%Y-%m-%d %H:%M:%S"))]=1
}
}
MyData$Rain_Binary=as.factor(MyData$Rain_Binary)

And generate a linear model of it:
LM_1 = lm(People ~ Time + Rain_Binary, data=MyData, na.action = na.exclude)

You check the residuals of it:
plot(resid(LM_1) ~ c(1:dim(MyData)[1]), data=MyData, main="Correlation complete",xlab="Time")

Question: How do I adress only one day in the dataframe against which the residuals are plotted? This here gives an error:
plot(resid(LM_1) ~ MyData$Time[substr(MyData$Time,1,10)==strptime("2015-05-06",format="%Y-%m-%d")], data=MyData, main="Correlation 1 Day \n 2015-09-03", xlab="Time")

A: First I cannot reproduce your code before the plot, it gives an error:
start <- as.POSIXct("2015-05-05 06:00:00", format="%Y-%m-%d %H:%M:%S")
> end   <- as.POSIXct("2015-05-07 20:00:00", format= "%Y-%m-%d %H:%M:%S")
> Time=seq.POSIXt(start, end, by="10 min")
>
> MyData=data.frame(Time=Time,Rain=rep(0,(length(Time))),Rain_Binary=rep(0,(length(Time))),People=rep(0,(length(Time))))
> MyData[c(2:4,154:157,324:328),2]=5
> MyData$People=round(runif(length(Time),0,50), digits=0)
> MyData$Rain_Binary=as.factor(MyData$Rain_Binary)
>
> for (Z in 1:nrow(MyData)) {Today= substr(MyData[Z,1], 1, 10)
+ if(any(MyData$Rain[((MyData$Time>= strptime(paste(Today, "06:30:00", sep = " "),format="%Y-%m-%d %H:%M:%S"))&
+                     (MyData$Time<= strptime(paste(Today, "09:00:00", sep = " "),format="%Y-%m-%d %H:%M:%S")))]>0)) {MyData$Rain_Binary[(MyData$Time>=strptime(paste(Today, "06:30:00", sep = " "),format="%Y-%m-%d %H:%M:%S"))&
+                                                                                (MyData$Time<= strptime(paste(Today, "20:00:00", sep = " "),format="%Y-%m-%d %H:%M:%S"))]=1
+ }
+ }
There were 50 or more warnings (use warnings() to see the first 50)
>
> LM_1 = lm(People ~ Time + Rain_Binary, data=MyData, na.action = na.exclude)
Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
  contrasts can be applied only to factors with 2 or more levels

So guessing what you might want I alter the code:
start <- as.POSIXct("2015-05-05 06:00:00", format="%Y-%m-%d %H:%M:%S")
end   <- as.POSIXct("2015-05-07 20:00:00", format= "%Y-%m-%d %H:%M:%S")
Time=seq.POSIXt(start, end, by="10 min")

MyData=data.frame(Time=Time,Rain=rep(0,(length(Time))),Rain_Binary=rep(0,(length(Time))),People=rep(0,(length(Time))))
MyData[c(2:4,154:157,324:328),2]=5
MyData$People=round(runif(length(Time),0,50), digits=0)
for (Z in 1:nrow(MyData)) {Today= substr(MyData[Z,1], 1, 10)
if(any(MyData$Rain[((MyData$Time>= strptime(paste(Today, "06:30:00", sep = " "),format="%Y-%m-%d %H:%M:%S"))&
                    (MyData$Time<= strptime(paste(Today, "09:00:00", sep = " "),format="%Y-%m-%d %H:%M:%S")))]>0)) {
  MyData$Rain_Binary[(MyData$Time>=strptime(paste(Today, "06:30:00", sep = " "),format="%Y-%m-%d %H:%M:%S"))&
  (MyData$Time<= strptime(paste(Today, "20:00:00", sep = " "),format="%Y-%m-%d %H:%M:%S"))]=1
}
}
MyData$Rain_Binary=as.factor(as.character(MyData$Rain_Binary))

Finally we plot the residuals over time specifically for one day:"2015-05-06"
library(dplyr)
LM_1 = lm(People ~ Time + Rain_Binary, data=MyData)
MyData$Residuals<-resid(LM_1)
filteredData<-filter(MyData,Time>"2015-05-06 00:00"&Time<"2015-05-06 23:50")
plot(Residuals ~ Time, data=filteredData, main="Correlation 1 Day \n 2015-09-03",xlab="Time")

Hope this helps


text:
Q: $.mobile.loadPage() not Working $.mobile.loadPage('view-video'); is not working, and i have sample code bellow. Please help me to resolve this issue.
I am getting the Alert "Function Triggered"
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

Welcome To My Homepage

I Am Now A Mobile Developer!!

    Load Video

Footer Text

    Your Video Will be Here.

A: First the documentation says

Note: jQuery.mobile.loadPage is deprecated as of jQuery Mobile 1.4.0 and will be removed in 1.5.0. Use the pagecontainer widget's load() method instead.

Got it working in this Fiddle with JavaScript. Instead of $(':mobile-pagecontainer').pagecontainer('load', "view-video); it have to be $(':mobile-pagecontainer').pagecontainer('change', "#view-video");! (change instead of load and with # cause it's an id)
See jQuery Mobile Demos for detail instructions.
Important is that each page has it data-role="page" attribute => jQuery Mobile Tutorial


text:
Q: calculating the amount of months to reach a down payment Write a script that includes the definition of house_loan() that you just wrote. When the script is executed, it should ask the user to enter the following values and then use the house_loan() function to calculate the months needed to save enough money for a down payment. Note that all the arguments needs to be float numbers.

*

*The starting annual salary

*The portion of salary to be saved

*The cost of your dream home

Test Case #1
>>>
Enter your annual salary: 120000
Enter the percent of your salary to save, as a decimal: .10
Enter the cost of your dream house: 1000000
Number of months: 183
>>>

Test Case #2
>>>
Enter your annual salary: 80000
Enter the percent of your salary to save (as a decimal): .15
Enter the cost of your dream home: 500000
Number of months: 105
>>>

When I execute my code, I either get a super high number or a number that's below it. I cannot figure out the right way to set up my code in order for it to pass the 1st and 2nd Case. Moreover, I just help in setting it up correctly, in order to get the correct answer.
Code
annual_salary = float(input('What's your annual salary? \n'))
portion_saved = float(input('What portion would you like to save (as a decimal)? \n'))
portion_downpayment = 0.25
total_cost = float(input('What is the total cost of your dream house? \n'))

def house_loan(annual_salary,
               portion_saved,
               portion_downpayment,
               total_cost):

    cost_to_be_paid = total_cost - portion_downpayment    #calculat the pending money to be paid
    monthly_salary = annual_salary/12                     #calculate the monthly salary
    monthly_savings = monthly_salary*portion_saved        #calculate monthly savings in salary
    total_months = cost_to_be_paid/monthly_savings        #returning the months required to pay money

    return total_months
print('The months required to pay enough money for the down payment is: ',house_loan(annual_salary, portion_saved, portion_downpayment, total_cost))

A: Your portion_downpayment wasn't a global variable, so it never got passed into your function.  This works:
annual_salary = float(input('Whats your annual salary? \n'))
portion_saved = float(input('What portion would you like to save (as a decimal)? \n'))
total_cost = float(input('What is the total cost of your dream house? \n'))

def house_loan(annual_salary,
               portion_saved,
               portion_downpayment,
               total_cost):

    portion_downpayment = 0.25
    cost_to_be_paid = total_cost * portion_downpayment      #calculat the pending money to be paid
    monthly_salary = annual_salary / 12                     #calculate the monthly salary
    monthly_savings = monthly_salary * portion_saved        #calculate monthly savings in salary
    total_months = cost_to_be_paid / monthly_savings        #returning the months required to pay money
    return(total_months)

print('The months required to pay enough money for the down payment is: %s' % house_loan(annual_salary, portion_saved, portion_downpayment, total_cost))


text:
Q: Quaternion Rings Let $R$ be a commutative ring. Define the Hamilton quaternions $H(R)$ over $R$ to be the free $R$-module with basis $\{1, i, j, k\}$, that is,
$$H(R)=\{a_0+a_1i+a_2j+a_3k\;\;:\;\;a_l\in R\}.$$
and multiplication is defined by: $i^2=j^2=k^2=ijk=-1$.
Is well-known that over a field $F$ (with char $F\neq 2$) the ring $H(F)$ is a division ring or isomorphic to $M_2(F)$. What can we say  about the Hamilton quaternions over an arbitrary commutative ring $R$? Is still true that $H(R)$ is a division ring or isomorphic to $M_2(R)$? We must impose some conditions to the ring to make it happen?

A: (Your definition of the multiplication looks slightly strange to me.  I would prefer to write $k = ij = -ji$.  This implies your relations; as Arturo shows in his comment below, your relations also imply mine, but to my mind it's sort of mixing two different ways to give an $R$-algebra: you could either give it via generators and relations, or if it's a free $R$-module you can give an explicit basis and the structure constants.)
If $R$ is a field of characteristic different from $2$, then $H(R)$ is by definition the quaternion algebra $\left( \frac{-1,-1}{R} \right)$.  In general, for $a,b \in R^{\times}$, the quaternion algebra
$\left( \frac{a,b}{R} \right) = R\langle i,j \rangle/(i^2 = a, j^2 = b, ji = -ij)$
is indeed always a division algebra or isomorphic to $M_2(R)$: see e.g. $\S 5.1$ of these notes.
(If $R$ is a field of characteristic $2$, then $H(R)$ is a commutative ring, so is not what you want.  There are analogues of quaternion algebras in characteristic $2$ defined slightly differently.)
If $R$ is a domain, then the center of $H(R)$ is $R$.  It follows that if $R$ is not a field, $H(R)$ is not a division ring.  Note also that if $R \subset S$ is an extension of domains, then $H(S) \cong H(R) \otimes_R S$.
In particular $H(\mathbb{Z})$ is not a division ring.  Neither is it isomorphic to $M_2(\mathbb{Z})$: if so, then $H(\mathbb{\mathbb{R}})$ would be isomorphic to $M_2(\mathbb{Z}) \otimes_{\mathbb{Z}} \mathbb{R} \cong M_2(\mathbb{R})$, but $H(\mathbb{R}) = \left( \frac{-1,-1}{\mathbb{R}}\right)$ is the classical Hamiltonian quaternions, which is well-known to be a division ring.
In general, if $R$ is a domain of characteristic different from $2$ with fraction field $K$, then $H(R)$ is an order in the quaternion algebra $H(K)$.  This is more a definition than anything else, but it gives you a name.  There is a vast literature on quaternion orders: for just a little bit, see e.g. these notes.


text:
Q: Eclipse modifies shared ant-launch configuration storing last launched tag in it In Eclipse 3.8 I need to run my build.xml ant script within the workspace JRE. So I altered my ant launch configuration choosing

*

*"Run in the same JRE as the workspace"

in the JRE tag, stored the launch configuration in the shared file (on the common tab) and then commited the .launch file to the repository. Now all developers sharing this configuration and the build.xml script work correctly.
My problem is, that each time someone runs different targets from my build.xml, the eclipse alters the .launch configuration adding/modifing the last runned target. Then the modification popups in the commit window, that irritates developers and produces merge conflicts, if commited.
The change to .launch file is:
...
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_ANT_TARGETS" value="build,"/>
...

My question is, how can I prevent Eclipse from modifing my .launch configuration files?
Thank you!
PS
Source code management is IBM Synergy


text:
Q: Does java support class Foo ,if no,why? Does java support class Foo<T super X> ,if no,why ?
Where T is a type parameter and X is a type.

A: No. The super keyword in the context of Generics could only be used in combination with a wildcard (?) when declaring (consumer) variables or method parameters (consumers) that are of some Generic type.
For example, these are valid:
List<? super Something> list = someListReference;

public void methodThatPopulatesAList(List<? super Something> consumer) {
    ...
    list.add(new Something());
    ...
}

More info:

*

*What is PECS?

*Wildcards in Java

A: you can use generic declaration Foo<? super X> in order to make things like this possible:
List<? super Integer> foo3 = new ArrayList<Object>();

but you can't use it in class declaration

A: For Class :
class Foo<T extends X>

For Object :
Object<? extends X>


text:
Q: How to change entry point to a function with parameters of C program compiled with gcc? I would like to pass a parameter to a function using the GNU ld linker entry point option.
The ld's documentation says:

3.4.1 Setting the Entry Point
The first instruction to execute in a program is called the entry
point. You can use the ENTRY linker script command to set the entry
point. The argument is a symbol name:
ENTRY(symbol)
There are several ways to set the entry point. The linker will set the
entry point by trying each of the following methods in order, and
stopping when one of them succeeds:

*

*the '-e' entry command-line option;

*the ENTRY(symbol) command in a linker script;

*the value of a target-specific symbol, if it is defined; For many    targets this is start, but PE- and BeOS-based systems for example
check a list of possible entry symbols, matching the first one found.

*the address of the first byte of the '.text' section, if present;

*The address 0.

But is not clear how to pass a parameter to the entry point.
This is a sample code:
#include <stdio.h>
#include <stdlib.h>

int entry(int p)
{
    printf("%i \n", p);
    exit(0);
}

To compile I run:
gcc -nostartfiles -e entry entry.c -o entry

Output:
./entry 1
-836386416

It seems that the parameter is ignored.
Is it possible pass parameters to an entry point? All the sources I consulted do not pass parameters.


text:
Q: SQL not exists self-join I've got a table which stores all letters sent out to customers. I need to run a query to select all account_id's that have received letter_2 but not letter_1. So for example the below results should be accounts 2 & 3.
Account_ID Letter_Type
1          Letter_1
1          Letter_2
1          Letter_3
1          Letter_2
2          Letter_2
2          Letter_3
3          Letter_2

Thanks in advance!

A: A straightforward way of doing this, is to use except:
select account_id
from the_table
where letter_type = 'Letter_2'
except
select account_id
from the_table
where letter_type = 'Letter_1'

An anti-join using not exists would look like this:
select t1.account_id
from the_table t1
where t1.letter_type = 'Letter_2'
  and not exists (select *
                  from the_table t2
                  where t2.letter_type = 'Letter_1' and
                    and t1.account_id = t2.account_id);

You didn't state your DBMS, but the above is standard ANSI SQL


text:
Q: Cmake override find_package for a given target We have a CMakeLists.txt that links (for instance) opencv to our various binaries. This is done as follow:
find_package(OpenCV REQUIRED core imgproc highgui contrib)
target_link_library(XXX opencv_core)

We also would like to allow the person building the library to provide its own opencv library. It seems that this could be done setting -DCMAKE_PREFIX_PATH to the right path.
cmake -DCMAKE_PREFIX_PATH=".../mybuild/include;.../mybuild/lib" .

However I would like to be sure the library used is exactly the one specified by the client (i.e. if there is nothing in /mybuild/lib the configuration fails).
How can I allow somebody building the library to override the library used ? (if nothing is specified it should fall back to find_package-s)

A: In short

*

*If the package provides <package>Config.cmake script, user may specify <package>_DIR CMake variable for locate this script.
Searching other places in that case may be disabled with NO_DEFAULT_PATH option for find_package().

*If a package is searched with Find<package>.cmake script, there is no (generic) way for disable searching other places if user provides hint variable but it is wrong.
Explanations
Firstly, CMAKE_PREFIX_PATH provides additional installation tree for all packages. As this variable is applied to all find_package() calls, it is not wise to require all packages to be found under it.
When talk about the ways for specify installation directory for specific package, we need to distinguish two kinds of "find" scripts:

*

*<package>Config.cmake (or some alternative names, see find_package documentation).
These scripts are shipped with the packages themselves. And there is universal way for user to specify location of such packages: CMake variable <package>_DIR, which should point to the directory with *Config.cmake script.
While default behaviour of find_package() is treating <package>_DIR variable as an additional hint, passing NO_DEFAULT_PATH option disables all implicit paths:
if(<package>_DIR) # Variable is set by the user or by previous `cmake` run.
    # Search only under given directory.
    find_package(<package> NO_DEFAULT_PATH)
else()
    # Search everywhere (as documented for 'find_package').
    find_package(<package>)
endif()

*Find<package>.cmake.
This script either is shipped with CMake or should be shipped with the project.
Most of such scripts allows to hint about package location with variable (CMake or environment one) like <package>_DIR, <package>_ROOT or so.
However, almost all such scripts treat hint variable only as additional search place, so if variable is set to wrong value, they simply ignore it. And without modifying the script you cannot change that behavior.


text:
Q: Unable to use Except in update postgres I am facing a problem when I am trying to use Except with an update statement, It is required because I don't want to use <> for each field when updating a record.
Here is the real example where I am trying to use except
    update_existing_item_sales AS(
    UPDATE daily_item_sales
    SET sales_amt = jd.sales_amt,
    sales_qty = jd.sales_qty,
    sales_prc=jd.sales_prc,
    sales_promo_amt = jd.sales_promo_amt,
    sales_promo_qty = jd.sales_promo_qty,
    discount_amt = jd.discount_amt,
    discount_qty = jd.discount_qty,
    coupon_amt = jd.coupon_amt,
    coupon_qty = jd.coupon_qty,
    price_override_amt = jd.price_override_amt,
    price_override_qty = jd.price_override_qty,
    return_amt = jd.return_amt,
    return_qty = jd.return_qty,
    item_scanned = jd.item_scanned,
    item_keyed = jd.item_keyed
    FROM updated_Item_data jd
    WHERE daily_item_sales.id = jd.id
    EXCEPT (select jd.* from updated_Item_data jd
        INNER JOIN daily_item_sales on
    WHERE daily_item_sales.id = jd.id
    AND daily_item_sales.sales_amt = jd.sales_amt
    AND daily_item_sales.sales_qty = jd.sales_qty
    AND daily_item_sales.sales_promo_amt = jd.sales_promo_amt
    AND daily_item_sales.sales_promo_qty = jd.sales_promo_qty
    AND daily_item_sales.discount_amt = jd.discount_amt
    AND daily_item_sales.discount_qty = jd.discount_qty
    AND daily_item_sales.coupon_amt = jd.coupon_amt
    AND daily_item_sales.coupon_qty = jd.coupon_qty
    AND daily_item_sales.price_override_amt = jd.price_override_amt
    AND daily_item_sales.price_override_qty = jd.price_override_qty
    AND daily_item_sales.return_amt = jd.return_amt
    AND daily_item_sales.return_qty = jd.return_qty
    AND daily_item_sales.item_scanned = jd.item_scanned
    AND daily_item_sales.item_keyed = jd.item_keyed)
)

The error:
ERROR:  syntax error at or near "EXCEPT"

                                            ^
SQL state: 42601
Character: 37

A: You can rewrite the query as follows:
update app_user
set deleted = false
where end_timestamp is not null

A: EXCEPT is a set-based operator -- like UNION, UNION ALL, and INTERSECT -- that connects result sets generated by SELECT.  It does not make sense with UPDATE.
But, it is easily replaced using NOT EXISTS:
with u as (
    UPDATE daily_item_sales
        SET sales_amt = jd.sales_amt,
            sales_qty = jd.sales_qty,
            sales_prc=jd.sales_prc,
            sales_promo_amt = jd.sales_promo_amt,
            sales_promo_qty = jd.sales_promo_qty,
            discount_amt = jd.discount_amt,
            discount_qty = jd.discount_qty,
            coupon_amt = jd.coupon_amt,
            coupon_qty = jd.coupon_qty,
            price_override_amt = jd.price_override_amt,
            price_override_qty = jd.price_override_qty,
            return_amt = jd.return_amt,
            return_qty = jd.return_qty,
            item_scanned = jd.item_scanned,
            item_keyed = jd.item_keyed
        FROM updated_Item_data jd
        WHERE daily_item_sales.id = jd.id AND
              NOT EXISTS (SELECT 1
                          FROM daily_item_sales dis
                          WHERE dis.id = jd.id AND
                                dis.sales_amt = jd.sales_amt AND
                                dis.sales_qty = jd.sales_qty AND
                                dis.sales_promo_amt = jd.sales_promo_amt AND
                                dis.sales_promo_qty = jd.sales_promo_qty AND
                                dis.discount_amt = jd.discount_amt AND
                                dis.discount_qty = jd.discount_qty AND
                                dis.coupon_amt = jd.coupon_amt AND
                                dis.coupon_qty = jd.coupon_qty AND
                                dis.price_override_amt = jd.price_override_amt AND
                                dis.price_override_qty = jd.price_override_qty AND
                                dis.return_amt = jd.return_amt AND
                                dis.return_qty = jd.return_qty AND
                                dis.item_scanned = jd.item_scanned AND
                                dis.item_keyed = jd.item_keyed
                               )
. . .

That said, this is probably better handled using ON CONFLICT with a unique constraint.

A: Could be simplified as
update daily_item_sales as t set
    (sales_amt, sales_qty, sales_prc, ...) = (s.sales_amt, s.sales_qty, s.sales_prc, ...)
from updated_Item_data as s
where
    t.id = s.id and
    (t.sales_amt, t.sales_qty, t.sales_prc, ...) is distinct from (s.sales_amt, s.sales_qty, s.sales_prc, ...)


text:
Q: IONIC - background image not showing with apk I'm my html page I have a ion-content with the class getstart, with a background image, placed in assets/img.
It works perfectly into the web browser, but wen I test the app with the apk, the background remains white.
I know that It's a recurrent question, but all the answers that I found (in this and other sites) don't work for me.
This is my scss code, placed inside app.scss
  .getstart{
    background: url('../assets/img/venice.jpg') no-repeat center center fixed;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    background-size: cover;

  }

I tried changing che image url like '/assets/img/venice.jpg' , but nothing worked.
I'm really stuck :(
Thank you in advance!
SOLVED: Silly mistake. My background image was venice.JPG and not .jpg so the apk didn't recognize any image. I changed my extension's file an all worked.
Thank for the help!

A: Everything seems to be correct, just as you already tried the link "assets/img/venice.jpg".
Did you inspect your device via chrome? maybe the picture si missing there.
Try to change the name of the picture. No idea why but this helped my once.

A: every thing is perfect but i thing this would the best try to use this
enter code here background: url(../../assets/imgs/Login.png) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;


text:
Q: CSRF issue in django settings.py
INSTALLED_APPS = [
    ...
    'corsheaders',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

ALLOWED_HOSTS = ['*']
CORS_ORIGIN_ALLOW_ALL = True

ajax request
            $.ajax({
                type: "POST",
                url: `https://example.com/requestlink/`,
                crossDomain: true,
                data: {
                    link: link,
                    csrfmiddlewaretoken: csrf,
                },

                success: function (data) {
                    if (data) {
                        data.forEach(src => {
                            createresult(src);
                        })
                    }
                    icon.classList.replace('loading', 'search');
                },
                error: function (data) {
                    icon.classList.replace('loading', 'search');
                }
            })

Now when i do ajax post request,
I got this in console tab
Status 403 Forbidden
Version HTTP/1.1
Transferred 1.53 KB (2.50 KB size)
Referrer Policy no-referrer-when-downgrade

and this in backend
Forbidden (Referer checking failed - https:// anotherexample.com / does not match any trusted origins.): /requestlink/
Why so?


text:
Q: In a webpack app, I need to ask IntelliJ to add the ./app directory as basePath for import I am working on a webpack, nodejs and react application.
I am trying to enable an import feature in IntelliJ IDEA 2016.
I wan't all the import from my ./app directory to be 'linked'.
By 'linked' I mean that I can enter a method by using CTRL+LEFT CLICK or an import by doing CTRL+LEFT CLICK on the string responsible for the import.
So far, this feature work fine for node_modules and relative import, I need it also for the ./app folder
Is there a way to ask IntelliJ to found my javascript single page application under the ./app folder so the import with webpack can be ctrl+clicked (enter in file)

A: It is not currently possible in March 2017 to configure import path in IDEA IntelliJ for a webpack 2.0 project.
There is an issue open if you wish to track it's status : https://youtrack.jetbrains.com/issue/WEB-17254
You could try to write your application in the project directory, sorry.