text:
Q: Why I get nothing back from node.js server on android I'm developing a android app with Socket connections. I followed a tutorial on the Internet with a sample server and android client (http://myandroidsolutions.blogspot.nl/2012/07/android-tcp-connection-tutorial.html).
the tutorial worked perfectly.
But I'm trying to connect to a Node.js socket io server with same android client contact. I can send messages with it but I can not received while the server sends a ping every second.
Why its not working?
what am I doing wrong?
The Node.js socket io server is working fine, the iPhone version of the app can send and receive.
All ports are open.
Can someone help me please? Thank u!
Source
TCPClient.java
 public class TCPClient {

    private String serverMessage;
    public static final String SERVERIP = "*ip-addres*"; //your computer IP address
    public static final int SERVERPORT = 4444;
    private OnMessageReceived mMessageListener = null;
    private boolean mRun = false;

    PrintWriter out;
    BufferedReader in;

    /**
     *  Constructor of the class. OnMessagedReceived listens for the messages received from server
     */
    public TCPClient(OnMessageReceived listener) {
        mMessageListener = listener;
    }

    /**
     * Sends the message entered by client to the server
     * @param message text entered by client
     */
    public void sendMessage(String message){
        if (out != null && !out.checkError()) {
            out.println(message);
            out.flush();
        }
    }

    public void stopClient(){
        mRun = false;
    }

    public void run() {

        mRun = true;

        try {
            //here you must put your computer's IP address.
            InetAddress serverAddr = InetAddress.getByName(SERVERIP);

            Log.e("TCP Client", "C: Connecting...");

            //create a socket to make the connection with the server
            Socket socket = new Socket(serverAddr, SERVERPORT);

            try {

                //send the message to the server
                out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                Log.e("TCP Client", "C: Sent.");

                Log.e("TCP Client", "C: Done.");

                //receive the message which the server sends back
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                //in this while the client listens for the messages sent by the server
                while (mRun) {
                    serverMessage = in.readLine();

                    if (serverMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(serverMessage);
                    }
                    serverMessage = null;

                }

                Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");

            } catch (Exception e) {

                Log.e("TCP", "S: Error", e);

            } finally {
                //the socket must be closed. It is not possible to reconnect to this socket
                // after it is closed, which means a new socket instance has to be created.
                socket.close();
            }

        } catch (Exception e) {

            Log.e("TCP", "C: Error", e);

        }

    }

    //Declare the interface. The method messageReceived(String message) will must be implemented in the MyActivity
    //class at on asynckTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }}

ChatActivity.java
    public class ChatActivity extends Activity{
 private ListView mList;
    private ArrayList<String> arrayList;
    private MyCustomAdapter mAdapter;
    private TCPClient mTcpClient;
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);

        arrayList = new ArrayList<String>();

        final EditText editText = (EditText) findViewById(R.id.editText);
        Button send = (Button)findViewById(R.id.send_button);

        //relate the listView from java to the one created in xml
        mList = (ListView)findViewById(R.id.list);
        mAdapter = new MyCustomAdapter(this, arrayList);
        mList.setAdapter(mAdapter);

        // connect to the server
        new connectTask().execute("");

        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                String message = editText.getText().toString();

                //add the text in the arrayList
                arrayList.add("c: " + message);

                //sends the message to the server
                if (mTcpClient != null) {
                    mTcpClient.sendMessage(message);
                }

                //refresh the list
                mAdapter.notifyDataSetChanged();
                editText.setText("");
            }
        });

    }

    public class connectTask extends AsyncTask<String,String,TCPClient> {

        @Override
        protected TCPClient doInBackground(String... message) {

            //we create a TCPClient object and
            mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
                @Override
                //here the messageReceived method is implemented
                public void messageReceived(String message) {
                    //this method calls the onProgressUpdate
                    publishProgress(message);
                }
            });
            mTcpClient.run();

            return null;
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);

            //in the arrayList we add the messaged received from server
            arrayList.add(values[0]);
            // notify the adapter that the data set has changed. This means that new message received
            // from server was added to the list
            mAdapter.notifyDataSetChanged();
        }
    }
}

Node JS Server
    var net = require('net');
var mysql = require('mysql');
var colorize = require('colorize');
var cconsole = colorize.console;

var clients = [];
var count = 0;

var messages = [];

function create_id()
{
        return count += 1;
}

setInterval(function()
{
        for(i = 0; i < clients.length; i++)
        {
                var client = clients[i];

                var params = {};
                params.type = "ping";

                if(client.socket.write(JSON.stringify(params)))
                {
                        console.log("ping send");
                }
                else
                {
                        clients.splice(i, 1);
                }
        }
}, 1000);

var server = net.createServer(function( socket )
{
        cconsole.log("#red[Client connected to the server with ip: " + socket.remoteAddress+"]");

        socket.on("error",function(error)
        {
                console.log("error" + error);
        });

        socket.on("close",function()
        {
                cconsole.log("#red[Client has disconnected]");
        });

        socket.on("data",function(data)
        {
                try
                {
                        var packet = JSON.parse(data);

                        if(packet.type == "register")
                        {
                                var client = [];

                                client.socket = socket;
                                client.clientID = create_id();
                                client.username = packet.username;

                                messages[packet.username] = [];

                                clients.push(client);

                                var params = {};

                                params.type = "register";
                                params.clientID = client.clientID;

                                socket.write(JSON.stringify(params));

                                console.log("Registered client : " + params.clientID);
                        }

                        if(packet.type == "online")
                        {
                                var params = {};
                                var identifiers = [];

                                for(i = 0; i < clients.length; i++)
                                {

                                        identifiers.push(clients[i].clientID);
                                }

                                params.type = "online";
                                params.clients = identifiers;

                                socket.write(JSON.stringify(params));
                        }

                        if(packet.type == "message")
                        {
                                var client = packet.sender;
                                var recipient = packet.recipient

                                for(i = 0; i < clients.length; i++)
                                {
                                        if(clients[i].clientID.toString() == recipient.toString())
                                        {
                                                var params = {}

                                                params.type = "message";
                                                params.sender = packet.sender;
                                                params.recipient = packet.recipient;
                                                params.message = packet.message;

                                                clients[i].socket.write(JSON.stringify(params));

                                                console.log("Wrote message " + params.message + " from sender " + params.sender +  " to recipient " + recipient)
                                                return;
                                        }
                                }
                                        console.log("Recipient was not valid");
                        }
                }
                catch(e)
                {
                        cconsole.log(e.message);
                }
        });
});

server.listen(8124,"<Server IP>", function()
{
        //'listening' listener
        cconsole.log('Server is listening for incoming connections');
});

A: Check the Endian-ness of your client and server programs. Your Android app may be sending things in Network Byte Order (Big Endian) while your server is expecting them in Little Endian.
If this is the case, you should make both of your clients transmit with the same byte order, e.g. by using a specific serializer that deals in the correct byte order.

A: while (mRun) {
                serverMessage = in.readLine();
                // check if you get a message here..

                if (serverMessage != null && mMessageListener != null) {
                    //call the method messageReceived from MyActivity class
                    mMessageListener.messageReceived(serverMessage);
                }
                serverMessage = null;

            }

try to log from the comment to see if you actually get something


text:
Q: How to stop Reverse Proxy on particular node? Is it possible to stop only Reverse Proxy service/process without affecting everything else?
As far as I see the only way to disable it currently is to stop the whole windows Service Fabric Host Service which literally means to take node down.

A: Hi @BulakaievOleksandr
I am not sure what kind of cluster you are running so I hope my assumption that you are talking about standalone cluster are correct.
As far as I know ReverseProxy is disable by default so in order to enable it the steps should be taken. I think if we reverse them - we should be able to disable ReverseProxy.
According to this and this we should check the following:
In ClusterConfig.json please check that all NodeTypes have their reverseProxyEndpointPort property removed.
"properties": {
   ...
    "nodeTypes": [
        {
            "name": "NodeType0",
            ...
            "reverseProxyEndpointPort": "19081",
            ...
        }
    ],
   ...
}

Then please make sure that inside fabricSettings you have turned off the ApplicationGateway/Http.
"fabricSettings": [
...
    {
        "name": "ApplicationGateway/Http",
        "parameters": [
             {
                 "name": "IsEnabled",
                 "value": "false"
             }
        ]
}
],
...

Hope this helps.

A: Didn't check this but I think it is possible. When you configure cluster configuration you can specify node types:
"nodeTypes": [
            {
                "name": "PrimaryNodeType",
                "clientConnectionEndpointPort": "19000",
                "clusterConnectionEndpointPort": "19001",
                "leaseDriverEndpointPort": "19002",
                "serviceConnectionEndpointPort": "19003",
                "httpGatewayEndpointPort": "19080",
                "reverseProxyEndpointPort": "19081",
                "applicationPorts": {
                    "startPort": "20001",
                    "endPort": "20031"
                },
                "isPrimary": true
            }
        ]

Notice that name for this node type is "PrimaryNodeType". You can add secondary node type and do not configure "reverseProxyEndpointPort". Use this node type for nodes you want to disable reverse proxy:
"nodes": [
        {
            "nodeName": "VM01",
            "iPAddress": "10.1.0.11",
            "nodeTypeRef": "PrimaryNodeType",
            "faultDomain": "fd:/dc0/r1",
            "upgradeDomain": "UD1"
        },
        {
            "nodeName": "VM02",
            "iPAddress": "10.1.0.12",
            "nodeTypeRef": "SecondaryNodeType",
            "faultDomain": "fd:/dc0/r2",
            "upgradeDomain": "UD2"
        },

It should work, although with Service Fabric you never know. Common sense solutions often do not work. Please let me know.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Php. Не могу подключиться к БД Mssql (sqlsrv) SQLSTATE[IMSSP]: This extension requires the Microsoft ODBC Driver for SQL Server to communicate with SQL Server. Access the following URL to download the ODBC Driver for SQL Server for x64: https://go.microsoft.com/fwlink/?LinkId=163712

A: Решил установкой ODBC драйвера на Windows


text:
Q: BSOD when installing AMD graphics drivers This problem is a recurring one. I've had it happen before, but I've always been able to fix it. Whenever I try to install Windows drivers for my MSI R6570 graphics card, I get a blue screen with something along the lines of "faulty drivers." Before, it was simply a matter of installing the chipset and integrated graphics drivers before attempting to install the new drivers. However, this time they were already installed and verified to be working.
Here's a link to a set of relevant data (including all of the steps of the process, the BSOD, and some potentially useful system files):
https://drive.google.com/folderview?id=0B2tLzzy_FsHsflZPOU9XWHdZNzRVcE1mV3pzYThrYXNINi1zaWRPTDJtQVIzdWtWMzVVenM&usp=sharing

A: You get the bugcheck 0xCA - PNP_DETECTED_FATAL_ERROR:
PNP_DETECTED_FATAL_ERROR (ca)
PnP encountered a severe error, either as a result of a problem in a driver or
a problem in PnP itself.  The first argument describes the nature of the
problem, the second argument is the address of the PDO.  The other arguments
vary depending on argument 1.
Arguments:
Arg1: 000000000000000b, Deleted PDO reported as relation
    One of the removal relations for the device being removed has
    already been deleted.

You still use the Windows 7 RTM from 2009 without any updates.
Windows 7 Kernel Version 7600 MP (2 procs) Free x64
Product: WinNt, suite: TerminalServer SingleUserTS
Built by: 7600.16385.amd64fre.win7_rtm.090713-1255

First install the Sp1 + all updates and now try to install the AMD catalyst driver.

A: This could be happening for a variety of reasons.

*

*Drivers - you mentioned this so I'll put it first, but make sure all the necessary system drivers are installed properly.

*Faulty equipment - Your GPU, Mobo, RAM, HDD, all can produce BSOD messages.  Since you mentioned you've got it working before this probably isn't the problem.  But in my experience most BSOD errors are actually caused by faulty hardware.

*Insufficient Power - If the card or other computer components aren't receiving enough electricity they will often BSOD.  I'd make sure you have enough power throughout the system.


text:
Q: retrieve multidimension array data How to retrieve the data from array like this :
$module =  array(array ( [module_id] => 1 ),
                 array ( [module_id] => 2 ),
                 array ( [module_id] => 3 ),
                 array ( [module_id] => 4 ),
                 array ( [module_id] => 5 )
                );

I just want to retrieve the value (1,2,3,4 or 5) and save to string variable

A: Try this -
$module =  array(array ( 'module_id' => 1 ),
               array ( 'module_id' => 2 ),
               array ( 'module_id' => 4 ),
               array ( 'module_id' => 5 ),
               array ( 'module_id' => 6 ));

$string = '';
foreach($module as $mod) {
    $string .= $mod['module_id'].',';
}
$string = substr($string,0,-1);

echo $string;


text:
Q: How to get messages from ActiveMQ using REST requests I am sending message to queue using following request:
POST http://localhost:8161/api/message/PR?type=queue
Host: localhost:8161
Authorization: Basic YWRtaW46YWRtaW4=
User-Agent: curl/7.48.0
Accept: */*
Content-Type: application/x-www-form-urlencoded
Content-Length: 12

Then I go to the admin UI and I see the queue and the message there.
Now the question, how can I retrieve this message?


text:
Q: Jetpack Joyride user movement i am trying to create a game similar to jetpack joyride in which the user can hold the spacebar to go up and let go to travel downward. I am using timers to simulate the gravity and using keyPressed and keyReleased to check if the user is holding the spacebar. I am using print statements to know for sure that both keyPressed and keyReleased are working, but i dont know why the physics arent running. I dont know whether the problem is my if statements not updating, if it is the new timers being created inside of the if statement. Either way, the gravity is not changing, and im stuck. Help is appreciated.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Calendar;

public class Game implements KeyListener {
    JFrame frame;
    JLabel player;

    public boolean grounded = false;
    public int velocity = 0;
    public int finalY = 0;
    public boolean spaceHeld = false;

    Action spaceAction;

    Game() {

        frame = new JFrame("Nicholas Seow-Xi Crouse");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(1920, 1080);
        frame.setLayout(null);

        frame.setFocusable(true);
        frame.addKeyListener(this);

        player = new JLabel();
        player.setBackground(Color.red);
        player.setBounds(10, 1800, 50, 50);
        player.setOpaque(true);

        frame.add(player);
        frame.setVisible(true);

         Timer flightTime = new Timer();
         TimerTask flight = new TimerTask() {

            public void run() {
                  if(velocity > -5) {
                  velocity -= 1;
                  }
                  else{
                  velocity = -5;
                  }
                  if (finalY < -61) {
                   finalY = finalY + velocity;
                   }
                   else{
                   finalY = -61;
                   }
                   player.setLocation(player.getX(), player.getY() + finalY);
                   if (player.getY() <= 0){
                   cancel();
                   velocity = 0;
                   finalY = 0;
                   player.setLocation(player.getX(), 0);

                   }
            }
      };

         Timer gravityTime = new Timer();
         TimerTask gravity = new TimerTask() {

            //creates a timer run method that simulates the falling gravity when not grounded
            public void run() {
                if(velocity < 5){
                velocity += 1;
                }
                else{
                velocity = 5;
                }
                //creates the variable the tells where the player is located
                if (finalY < 61) {
                finalY = finalY + velocity;
                }
                else{
                finalY = 61;
                }
                player.setLocation(player.getX(), player.getY() + finalY);
                if (player.getY() >= 1000){
                cancel();
                velocity = 0;
                finalY = 0;
                player.setLocation(player.getX(), 990);
                }

            }
        };

        if (spaceHeld == false ) {
            gravityTime.scheduleAtFixedRate(gravity, 0, 33);
        }
        if (spaceHeld == true ) {
            flightTime.scheduleAtFixedRate(flight, 0 ,33);
    }
}

public void keyTyped(KeyEvent e) {
}

public void keyPressed(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_SPACE){
spaceHeld = true;
//debug
System.out.println(spaceHeld);
}
}

public void keyReleased(KeyEvent e) {
if(e.getKeyCode() == KeyEvent.VK_SPACE){
spaceHeld = false;
//debug
System.out.println(spaceHeld);
}
}
}

A: Code is event based, and currently nothing triggers your timers to start. To do this you can simply move the timer schedule/start actions inside the key events:
public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_SPACE){

            //Cancel the other timer here so that they don't overlap
            gravity.cancel();
            gravityTime.cancel();

            //Create a new instance of the timer
            flightTime = new Timer();
            flight = new TimerTask() {

                public void run() {
                    if(velocity > -5) {
                        velocity -= 1;
                    }
                    else{
                        velocity = -5;
                    }
                    if (finalY < -61) {
                        finalY = finalY + velocity;
                    }
                    else{
                        finalY = -61;
                    }

                    player.setLocation(player.getX(), player.getY() + finalY);
                    if (player.getY() <= 0){
                        cancel();
                        velocity = 0;
                        finalY = 0;
                        player.setLocation(player.getX(), 0);
                    }
                }
            };

            //Now start the timer
            flightTime.scheduleAtFixedRate(flight, 0 ,33);
        }
    }

    //Do the same for the gravity method
    public void keyReleased(KeyEvent e) {
        if(e.getKeyCode() == KeyEvent.VK_SPACE){

            ......

        }
    }
}

Note above that you should also cancel the other scheduled task with the opposing key events so that they do not overlap each other and value strange results.
And to make flightTime and gravityTime accessible to the keyPressed method simply declare them as class variables:
public class Game implements KeyListener {
    JFrame frame;
    JLabel player;

    public boolean grounded = false;
    public int velocity = 0;
    public int finalY = 0;
    public boolean spaceHeld = false;

    //Move them here but don't assign a value:
    public Timer flightTime;
    public TimerTask flight;
    public Timer gravityTime;
    public TimerTask gravity;

You can still create the object later in the Game method:
flightTime = new Timer();
flight = new TimerTask() {
    ....
};


text:
Q: jQuery load() from within ajaxComplete() callback causing multiple loads I've been staring at this one for a while and I'm completely stumped. You'll need firebug for this, take a look at the AJAX requests. They seem to be multiplying after each click of next and previous until it's too slow to load entirely:
http://www.ftsdev.com/freegreen/virtual-tour-prototype/virtual-tour.html
All the JavaScript source for this is in:
/freegreen/virtual-tour-prototype/js/virtual-tour.js

Functions to look at:
launchVirtualTour()
$('#vt-next').one('click',function()
$('#vt-prev').one('click',function()

When ajaxComplete() is called I check the file that loaded against an Array outside of the callback function. This allows me to determine whether or not it's the first or last element in the series so that I can hide the Previous or Next buttons accordingly. I have a feeling that the problems lies somewhere in lines 80-82 where I add 1 to the inArray() value stored in indexInArray.
I've searched around but can't find any similar situations out there, any help is much appreciated.
Thanks!

A: I briefly tried out the page. From a quick skim of the code and my gut reaction, it looks like you aren't unbinding previously bound click events. As far as I can tell this is the flow to your bug:

*

*User clicks to bring up a slide show

*You bind next/prev click events

*User clicks around, using the next/prev buttons

*User clicks out of the current slide show

*User clicks into another slide show

*You bind next/prev click events

*User clicks around, using the next/prev buttons, causing content to be called twice

You need to unbind the click events when the user clicks out of the first slide show. Or don't bind in step 6.


text:
Q: Byte-based length of CLR string Short version of the question: Is there a way of counting how many bytes will it take to store the characters of a string in a VARCHAR(n) column in an Oracle database?
Longer version: The following Oracle SQL script will fail at the third statement. It will try to insert 10 characters in a VARCHAR(10) column; however, one of these characters is the A with an acute accent.
CREATE TABLE TESTTABLE (NAME VARCHAR(10) NULL);

INSERT INTO TESTTABLE (NAME) VALUES ('abcdefghij');
--1 rows inserted.

INSERT INTO TESTTABLE (NAME) VALUES ('ábcdefghij');
--ORA-12899: value too large for column "ACME"."TESTTABLE"."NAME" (actual: 11, maximum: 10)

My C# application stores strings in an Oracle database and I can't just change the column type to NVARCHAR2(10), which would work. The application is expected to trim any larger string to a limit of 10 characters, so Oracle won't complain about its length. But a String.Length-based trim is a very naif strategy: it would blindly leave "ábcdefghij" intact with all its 10 CLR characters.
How can I detect that 'á' will take 2 bytes in the database row so I can trim the string to "ábcdefghi" before issuing the INSERT statement?
EDIT: this question is similar to Best way to shorten UTF8 string based on byte length

A: Oracle function length(string) returns number of characters, lengthb(string) returns number of bytes.

A: This depends on the encoding you have Oracle set to use. You convert the string instance into a byte array using the corresponding System.Text.Encoding instance, such as System.Text.Encoding.UTF8. (You're looking for the "GetBytes" method)

A: By default, VARCHAR2(10) allocates 10 bytes of storage which may or may not equate to 10 characters depending on the database character set and the data.  You can, however, declare the column so that it will always store 10 characters.
When you are using a variable-width character set, you almost always want to declare the column using character-length semantics VARCHAR2(10 CHAR).  Then you can always store 10 characters whether you happen to have some characters that require more than 1 byte of storage.
If you're stuck declaring columns using byte-length semantics for some reason, you could use the LENGTHB or VSIZE function to return the length of the string in bytes.
select lengthb('ábcdefghij'), vsize('ábcdefghij')
  from dual;

will return 11 for both columns of the result.

A: You can get the lenght in bytes of the string like this:
UTF8Encoding Encoding = new UTF8Encoding();
byte[] UTF8String = Encoding.GetBytes("ábcdefghij");
int StringLenght = UTF8String.Length

In fact, for your example, it returns 11.


text:
Q: Puzzle: Minimum distance from m points to n fixed points on the straight line The formal statement of the problem is follows: given N points on a straight line, and the sequence n1, n2, n3... is non-decreasing. Arrange M points so that the sum of the distances from the nearest points ni, n(i+1)... to the point mi would be minimal for i = 1...M.
Informal interpretation of the problem: arrange M gas stations on the road so that N people living along the road spend as little time as possible getting to the gas station. For a single gas station, the condition is simple: the number of people to the right and left of the gas station must be equal.
M<=N

For a larger number of gas stations, the task becomes more complicated. I gave an example of placing 3 gas stations among 10 dots. Each of them creates a certain segment, and on this segment there are the same number of people to the right and to the left of the gas station.
However, this is not the optimal solution. My assumption: for optimality, an additional condition is required: on the right and on the left there must be the same number of points for which this gas station is the closest. An example of such an arrangement is shown in the figure below, and indeed, the sum of the distances for such a situation is less.
The problem is that I do not understand how to check at the stage of arranging gas stations which point will be the closest. This can be seen in the first picture: we place the dots so that there are the same number of people on each side, but after the placement it turns out that the gas station nearest to them is not the one we expected.


text:
Q: Best way to search two queries and eliminate rows without a relationship I am working on a property website and have record sets for property and for unit, unit has a one-to-many relationship with property. What I'm trying to figure out is how to best create a search function which will output results based on criteria from both. So if I search for a property with the location Manchester and a unit with a freehold tenure I'd like to eliminate all properties which don't have a unit with the tenure of freehold.
A potential solution I've considered is to create a record set for properties which match the property criteria and then create a unit record set for units which match the unit criteria and then finally loop through the property record set in server-side code and eliminate any properties which aren't related to any of the units in the unit record set. Really not sure if this is the best way to do things though so would be keen to hear any suggestions?
Thanks
EDIT (Added table structure and MySQL):
--
-- Table structure for table `property`
--

CREATE TABLE IF NOT EXISTS `property` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` text NOT NULL,
  `street` text NOT NULL,
  `town` text NOT NULL,
  `postcode` text NOT NULL,
  `description` longtext NOT NULL,
  `team_member` varchar(255) NOT NULL DEFAULT '',
  `pdf` text NOT NULL,
  `default_image_id` int(11) DEFAULT NULL,
  `virtual_tour_link` text NOT NULL,
  `date` date NOT NULL DEFAULT '0000-00-00',
  `archive` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='' AUTO_INCREMENT=13 ;

--
-- Table structure for table `unit`
--

CREATE TABLE IF NOT EXISTS `unit` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` text NOT NULL,
  `description` text NOT NULL,
  `size_sq_ft` int(11) DEFAULT NULL,
  `size_acres` float DEFAULT NULL,
  `price` float DEFAULT NULL,
  `rental_price` float DEFAULT NULL,
  `on_application` tinyint(1) DEFAULT NULL,
  UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='Stores data for property units' AUTO_INCREMENT=5;

--
-- Table structure for table `property_to_unit`
--

CREATE TABLE IF NOT EXISTS `property_to_unit` (
  `property_id` int(11) NOT NULL,
  `unit_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- MySQL which produces list of properties
--

SELECT
    P.id AS id,
    P.name AS name,
    P.street AS street,
    P.town AS town,
    P.postcode AS postcode,
    P.description AS description,
    P.team_member AS team_member,
    P.pdf AS pdf,
    P.virtual_tour_link AS virtual_tour_link,
    P.date AS date,
    P.archive AS archive,
    PI.name as image,
    P2.image_ids as image_ids,
    L2.location_ids as location_ids,
    U2.unit_ids as unit_ids

FROM property P

-- Get default image and join using property id

LEFT JOIN property_image PI ON PI.id = P.default_image_id

-- Create a list of image_ids from property_image and
-- property_to_property_image tables then join using property_id

LEFT JOIN (

    SELECT
        property_id,
        GROUP_CONCAT(CAST(id AS CHAR)) as image_ids
    FROM property_to_property_image PTPI
    LEFT JOIN property_image PI ON PI.id = PTPI.property_image_id
    GROUP BY property_id

) P2 ON P2.property_id = P.id

-- Create a list of locations from property_location table
-- and join using property_id

LEFT JOIN (
    SELECT
        property_id,
        property_location_id,
        GROUP_CONCAT(CAST(property_location.id AS CHAR)) AS location_ids
    FROM property_to_property_location
    INNER JOIN property_location ON property_location.id = property_to_property_location.property_location_id
    GROUP BY property_id
) L2 ON L2.property_id = P.id

-- Create a list of units from unit table
-- and join using property_id

LEFT JOIN (
    SELECT
        property_id,
        unit_id,
        GROUP_CONCAT(CAST(unit_id AS CHAR)) AS unit_ids
    FROM property_to_unit
    INNER JOIN unit ON unit.id = property_to_unit.unit_id
    GROUP BY property_id
) U2 ON U2.property_id = P.id

--
-- MySQL which produces list of units
--

SELECT
id,
name,
description,
size_sq_ft,
size_acres,
price,
rental_price,
on_application,
tenure_ids,
tenure_names,
type_ids,
type_names
FROM unit AS U

-- join tenure ids and names

LEFT JOIN (

    SELECT
        unit_id,
        GROUP_CONCAT( CAST(UT.id AS CHAR) ) AS tenure_ids,
        GROUP_CONCAT(UT.name) AS tenure_names
    FROM unit_to_unit_tenure UTUT
    INNER JOIN unit_tenure UT ON UT.id = UTUT.unit_tenure_id
    GROUP BY unit_id

) UT ON UT.unit_id = U.id

-- join type ids and names

LEFT JOIN (

    SELECT
        unit_id,
        GROUP_CONCAT( CAST(UTYPE.id AS CHAR) ) AS type_ids,
        GROUP_CONCAT(UTYPE.name) AS type_names
    FROM unit_to_unit_type UTUT
    INNER JOIN unit_type UTYPE ON UTYPE.id = UTUT.unit_type_id
    GROUP BY unit_id

) UTYPE ON UTYPE.unit_id = U.id

WHERE 0=0

I'm currently using a dynamically created WHERE statement appended to each MySQL query to filter the property and unit results.

A: Your situation requires a posted foreign key in the property table. Store the unit_id in the property table and use a join in your query such as:
select * from property p, unit u
where p.unit_id = u.id
and p.town = ....

EDIT: So I just noticed the rest of your SQL. If you require to keep the many-to-many relationship table for the unit -> property relationship then you will need to join unit and property off of that table.

A: You're making it a bit more complicated than it is.  If I understand correctly, you can easily do this in a single query.  This would search properties that have units with a particlar unit tenure id:
select *
from property p
where p.id in (
    select pu.property_id
    from property_to_unit pu
        inner join unit u ON pu.unit_id = u.id
        inner join unit_to_unit_tenure uut ON u.id = uut.unit_id
    where uut.id = <cfqueryparam value="#uutid#">
)

Using two queries and then looping through to cross-check sounds like it could be dog slow.


text:
Q: How to design this type of swappable card view with left and right side animation in iOS? How to design this type of swappable card view with left and right side animation in iOS?

A: You should always do your research on your own, there is a huge variety of Open Source Libraries and Developer SDKs which already support this kind of UI.
e.g. 5 seconds search in awesome-ios lead to this


text:
Q: Terminal app which takes up the whole terminal I have been trying to figure out how to make an app similar to emacs in that when you run it, it runs in the terminal but it takes up the whole terminal and acts almost like a window.  I can't find anything online about this, can anyone give me pointers of where to get started to figure this out?

A: For *nix, there is ncurses.
Wikipedia explains it to you: It is a library to write "GUI-like" applications in text format.
Also: Ncurses for Windows


text:
Q: Using JQuery editInPlace on Ajax injected HTML I am successfully using JQuery editInPlace plug-in on a static HTML page.
It's not working with the same HTML when the HTML is injected by an Ajax call.
I understand that using .on() such as '$('.edit_inplace_field').on(...)' should help in resolving the problem but I'm not sure how exactly it should be done for this specific plug-in.
The plug-in: http://code.google.com/p/jquery-in-place-editor/
The working static HTML code looks like:

Enter Name

The associated script that is used with the static HTML:
$('.edit_inplace_field').editInPlace({
    callback: function(unused, enteredText) { return enteredText; },
// url: './server.php',
show_buttons: false
});

Help will be greatly appreciated.

A: Using the information pointed by:
1. Dave Hauenstein - the jquery live api and by
2. Using an example on http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_event_live_newel I resolve the above.
The event in use above was the click event. With this in mind the solution:
Putting the above jquery code inside a .live() function:
$('.edit_inplace_field').live("click",function() {
             // --> code from above here, object is replaced by $(this)
     $(this).editInPlace({
         callback: function(unused, enteredText) { return enteredText; },
         show_buttons: false
    }); // --<
});

Comment: if using a more advanced jQuery 1.7+ version it is suggested to use .on() function.
See here why.


text:
Q: Image Upload to mysql database not working I am loading an image file using jquery filedialog. And then sending an ajax request to a php file to upload the image to database.
Here is my ajax request being sent
$("#imgfile").on("change",function(e){
                    var file_data = $('#imgfile').prop('files')[0];
                e.preventDefault();
                var form_data = new FormData();
                form_data.append('file', file_data);
                //alert(form_data);
                $.ajax({
            url: 'changeProfileImg.php', // point to server-side PHP script
            contentType: "image/jpeg",  // what to expect back from the PHP script, if anything
            cache: false,
            dataType: "image",
            processData: false,
            data: form_data,
            type: 'post',
            success: function(php_script_response){
                alert(php_script_response); // display response from the PHP script, if any
            }
            });
                });

Here is my php code
include_once 'dbconnect.php';
    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '
';
    }
    else {
        //move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
        $file=$_FILES['file']['name'];
        $id=$_SESSION['id'];
        $sql="UPDATE  mainadmin set photo='$file' where id='$id'";
        mysql_query($sql);
        echo 'success';
        $_SESSION['photo']=$file;
    }

But i see some garbase thing is being inserted into database not showing the image. How can i do it working.

A: See below URL and code I think this is helpful to you.
Simple jQuery progress bar percentage
This is my tested code file upload with progress bar percentage
But u can manage or modify as per Your requirement.
<!doctype html>

<title>File Upload Progress Demo #1</title>

File Upload Progress Demo #1

    <input type="file" name="myfile">
        <form action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="uploadedfile">

        <input type="submit" value="Upload File to Server">
    </form>

0%

my php code
<?php
$target_path = "uploads/";

$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);

if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}
?>


text: Q: How to get JSLint errors to show up in Eclipse Problems view? I've installed Aptana Studio 3 Plugin (v3.2.2) in Eclipse (STS 3.0, actually) for its JSLint integration.  Any errors/warnings show up fine as markers when I open a particular JavaScript file.  I'd also like JSLint to run at build time and show its output in Eclipse's Problems view, just like Java build errors/warnings.  How do I enable this?


text:
Q: GIT deleted file still submitted I was making the process to update my Heroku APP via Github from my local folder
When reaching git push origin masterI got an error because a json file was too big. So I manually deleted the file from the folder.
Then I did:
git add -A
git commit - m
git push origin master

And got again the same message as if the file was not deleted.
If I run git status I get Your branch is ahead of origin/master by 5 commits
I found a lot of questions about this but couldn't get this working. A lot of solutions depends on updates in your local repo from the server, but in my case my local files are the last updated.
Any clues welcome. Thanks in advance!


text:
Q: Something with my php 7.0.2 I just installed PHP 7.0.2 Apache on my Windows and everything I visit,
 like index.php I get the source code so PHP info() will show me
 <html xmlns="http://www.w3.org/1999/xhtml"><head>
<style type="text/css">
 and all other html tags..
I don't know what I did but PHP 7.0.1 worked fine for me. I tried to use the older php.ini but that didnt work and still had the same problem. I though first it would be something in my .htaccess but also not the problem.
I also tried to put PHP 7.0.1 back and now even that version doesn't work.


text:
Q: Why does a 32 bit microcontroller has only 16 pins in each port I have used 8 bit microcontrollers and each of their ports has 8 pins. So, I thought a 32 bit microcontroller will have 32 pins in each port (i.e. 32 bit data bus). But today i saw STM32F070RB pin configuration and noticed that each of its port has only 16 pins (instead of 32). Why is that so? Am i missing something here or each port can have any number of pins (irrespective of microcontroller)?

A: STM32's port definition allow only 16 pins/port, because they re-use the upper 16 bits.
Look at how the BRR and BSRR registers work - the upper 16 bits have a complemantary function.

A: The simplest answer is: cost. More pins mean a larger, more expensive package. Since the number of applications which actually require a 32-bit port are vanishingly small, especially compared to the number of applications which might require 2, 16-bit ports or 4, 8-bit ports, no sane manufacturer is going to go that route.
Since the tiny minority can be addressed (usually) by driving multiple smaller ports, partitioning I/O pins into smaller ports makes excellent sense. Additionally, a processor with 32 I/O pins configured as a single port would be far less useful to most users than one with more, smaller ports. Such a device (a single 32-bit port) would occupy, and dominate, a fabulously small niche, and the manufacturer would lose money.
TL;DR - There just aren't enough people who want such a device to make it worth anybody's while to make them.


text:
Q: .htaccess - "Too many redirects" Установил SSL сертификат и началась проблема с редиректом. Если в htaccess ничего не указывать, то сайт работает и с https и без. Заходит и так и так, но у меня не получается редиректнуть с http://spteh.com.ua/ на https://spteh.com.ua/ что бы всегда заходило только на https.

# SEO URL Settings
RewriteEngine On

RewriteBase /
RewriteRule ^sitemap.xml$ index.php?route=extension/feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=extension/feed/google_base [L]
RewriteRule ^system/storage/(.*) index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]

В таком варианте работают обе линки, а если добавить

RewriteCond %{HTTP_HOST} spteh.com.ua
RewriteRule (.*) https://spteh.com.ua/$1 [R=301,L]

RewriteCond %{SERVER_PORT} !^443$
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{THE_REQUEST} ^([A-Z]{3,9})\ (/[^?]*)(\?([^\ ]*))?\ HTTP/
RewriteRule .? - [E=method:%1,E=myURI:%2,E=curURI:%2,E=myQS:%4,E=curQS:%4]
RewriteCond %{HTTP_HOST} ^(.*)$
RewriteRule .? - [E=myHOST:%1]

начинает редиректить на https://spteh.com.ua но выдает ошибку Too many redirects Где, я ошибся?

A: У вас вот эта часть:
RewriteCond %{HTTP_HOST} spteh.com.ua
RewriteRule (.*) https://spteh.com.ua/$1 [R=301,L]

всегда имеет значение "Истина".
Поскольку вы проверяете HTTP_HOST на равенство имени домена spteh.com.ua, и редирект происходит на этот же домен, то в этом месте происходит зацикливание, приводящее к результату Too many redirects.

A: Нашел решение

RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]


text:
Q: Cloudformation aws-glue inline command My goal is to create a glue job via cloudformation. Problem that im dealing with is that Command property doesnt seem to support inline code (like cloudformation lamba Code property does).
My question, is there a way to create a fully functional glue job solely with cloudformation template, is there a way around uploading command file in advance (and specifying ScriptLocation) ?

A: Something like this may work (untested, so you might have to tweak). Basically you create a custom resource to facilitate uploading your glue code to S3 and then reference the custom resource to obtain the location. Below you'll find the CloudFormation template, and below that the Rubycfn code you can use to generate the template dynamically.
{
  "AWSTemplateFormatVersion": "2010-09-09",
  "Description": "Glue Job Example Stack",
  "Resources": {
    "GlueCode": {
      "Properties": {
        "BucketName": "my-amazing-bucket-for-glue-jobs",
        "Content": {
          "Fn::Join": [
            "\n",
            [
              "# some job code",
              "# for glue"
            ]
          ]
        },
        "CreateMode": "plain-literal",
        "FileName": "gluecode.sh",
        "ServiceToken": {
          "Fn::GetAtt": [
            "InlineS3UploadFunction",
            "Arn"
          ]
        }
      },
      "Type": "Custom::InlineUpload"
    },
    "GlueJob": {
      "Properties": {
        "Command": {
          "Name": "myglueetl",
          "ScriptLocation": {
            "Fn::Join": [
              "",
              [
                "s3://my-amazing-bucket-for-glue-jobs/",
                {
                  "Ref": "GlueCode"
                }
              ]
            ]
          }
        },
        "DefaultArguments": {
          "--job-bookmark-option": "job-bookmark-enable"
        },
        "ExecutionProperty": {
          "MaxConcurrentRuns": 2
        },
        "MaxRetries": 0,
        "Name": "glue-job-1",
        "Role": {
          "Ref": "SomeRole"
        }
      },
      "Type": "AWS::Glue::Job"
    },
    "InlineS3UploadFunction": {
      "Properties": {
        "Code": {
          "ZipFile": {
            "Fn::Join": [
              "\n",
              [
                "import boto3",
                "import cfnresponse",
                "import hashlib",
                "import json",
                "import logging",
                "import signal",
                "import zipfile",
                "",
                "from urllib2 import build_opener, HTTPHandler, Request",
                "",
                "LOGGER = logging.getLogger()",
                "LOGGER.setLevel(logging.INFO)",
                "",
                "def lambda_handler(event, context):",
                "    # Setup alarm for remaining runtime minus a second",
                "    try:",
                "        signal.alarm((context.get_remaining_time_in_millis() / 1000) - 1)",
                "        LOGGER.info('REQUEST RECEIVED: %s', event)",
                "        LOGGER.info('REQUEST RECEIVED: %s', context)",
                "        if event['RequestType'] == 'Create' or event['RequestType'] == 'Update':",
                "            LOGGER.info('Creating or updating S3 Object')",
                "            bucket_name = event['ResourceProperties']['BucketName']",
                "            file_name = event['ResourceProperties']['FileName']",
                "            content = event['ResourceProperties']['Content']",
                "            create_zip = True if event['ResourceProperties']['CreateMode'] == 'zip' else False",
                "            literal = True if event['ResourceProperties']['CreateMode'] == 'plain-literal' else False",
                "            md5_hash = hashlib.md5(content).hexdigest()",
                "            with open('/tmp/' + file_name, 'w') as lambda_file:",
                "                lambda_file.write(content)",
                "                lambda_file.close()",
                "                s3 = boto3.resource('s3')",
                "                if create_zip == True:",
                "                    output_filename = file_name + '_' + md5_hash + '.zip'",
                "                    zf = zipfile.ZipFile('/tmp/' + output_filename, mode='w')",
                "                    try:",
                "                        zf.write('/tmp/' + file_name, file_name)",
                "                    finally:",
                "                        zf.close()",
                "                        data = open('/tmp/' + output_filename, 'rb')",
                "                        s3.Bucket(bucket_name).put_object(Key=output_filename, Body=data)",
                "                else:",
                "                    if literal == True:",
                "                        data = open('/tmp/' + file_name, 'rb')",
                "                        s3.Bucket(bucket_name).put_object(Key=file_name, Body=content)",
                "                    else:",
                "                        extension = file_name.split(\".\")[-1]",
                "                        output_filename = \".\".join(file_name.split(\".\")[:-1]) + '_' + md5_hash + '.' + extension",
                "                        data = open('/tmp/' + file_name, 'rb')",
                "                        s3.Bucket(bucket_name).put_object(Key=output_filename, Body=content)",
                "            cfnresponse.send(event, context, cfnresponse.SUCCESS, { 'Message': output_filename } )",
                "        elif event['RequestType'] == 'Delete':",
                "            LOGGER.info('DELETE!')",
                "            cfnresponse.send(event, context, cfnresponse.SUCCESS, { 'Message': 'Resource deletion successful!'} )",
                "        else:",
                "            LOGGER.info('FAILED!')",
                "            cfnresponse.send(event, context, cfnresponse.SUCCESS, { 'Message': 'There is no such success like failure.'} )",
                "    except Exception as e: #pylint: disable=W0702",
                "        LOGGER.info(e)",
                "        cfnresponse.send(event, context, cfnresponse.SUCCESS, { 'Message': 'There is no such success like failure.' } )",
                "",
                "def timeout_handler(_signal, _frame):",
                "    '''Handle SIGALRM'''",
                "    LOGGER.info('Time exceeded')",
                "    raise Exception('Time exceeded')",
                "",
                "signal.signal(signal.SIGALRM, timeout_handler)"
              ]
            ]
          }
        },
        "Handler": "index.lambda_handler",
        "Role": {
          "Fn::GetAtt": [
            "LambdaExecutionRole",
            "Arn"
          ]
        },
        "Runtime": "python2.7",
        "Timeout": "30"
      },
      "Type": "AWS::Lambda::Function"
    },
    "LambdaExecutionRole": {
      "Properties": {
        "AssumeRolePolicyDocument": {
          "Statement": [
            {
              "Action": [
                "sts:AssumeRole"
              ],
              "Effect": "Allow",
              "Principal": {
                "Service": [
                  "lambda.amazonaws.com"
                ]
              }
            }
          ],
          "Version": "2012-10-17"
        },
        "Path": "/",
        "Policies": [
          {
            "PolicyDocument": {
              "Statement": [
                {
                  "Action": [
                    "logs:CreateLogGroup",
                    "logs:CreateLogStream",
                    "logs:PutLogEvents"
                  ],
                  "Effect": "Allow",
                  "Resource": "arn:aws:logs:*:*:*"
                },
                {
                  "Action": "s3:*",
                  "Effect": "Allow",
                  "Resource": "arn:aws:s3:::*"
                }
              ],
              "Version": "2012-10-17"
            },
            "PolicyName": "root"
          }
        ]
      },
      "Type": "AWS::IAM::Role"
    }
  }
}

The Rubycfn code is below. Use the https://rubycfn.com/ CloudFormation compiler or the Rubycfn gem gem install rubycfn to compile:
ENV["GLUEBUCKET"] ||= "my-amazing-bucket-for-glue-jobs"

description "Glue Job Example Stack"

resource :glue_code,
         type: "Custom::InlineUpload" do |r|
  r.property(:service_token) { :inline_s3_upload_function.ref(:arn) }
  r.property(:bucket_name) { ENV["GLUEBUCKET"] }
  r.property(:file_name) { "gluecode.sh" }
  r.property(:create_mode) { "plain-literal" }
  r.property(:content) do
    [
      "# some job code",
      "# for glue"
    ].fnjoin("\n")
  end
end

resource :glue_job,
         type: "AWS::Glue::Job" do |r|
  r.property(:command) do
    {
      "Name": "myglueetl",
      "ScriptLocation": ["s3://#{ENV["GLUEBUCKET"]}/", :glue_code.ref].fnjoin
    }
  end
  r.property(:default_arguments) do
    {
      "--job-bookmark-option": "job-bookmark-enable"
    }
  end
  r.property(:execution_property) do
    {
      "MaxConcurrentRuns": 2
    }
  end
  r.property(:max_retries) { 0 }
  r.property(:name) { "glue-job-1" }
  r.property(:role) { :some_role.ref }
end

resource :inline_s3_upload_function,
         type: "AWS::Lambda::Function" do |r|
  r.property(:code) do
    {
      "ZipFile": [
        "import boto3",
        "import cfnresponse",
        "import hashlib",
        "import json",
        "import logging",
        "import signal",
        "import zipfile",
        "",
        "from urllib2 import build_opener, HTTPHandler, Request",
        "",
        "LOGGER = logging.getLogger()",
        "LOGGER.setLevel(logging.INFO)",
        "",
        "def lambda_handler(event, context):",
        "    # Setup alarm for remaining runtime minus a second",
        "    try:",
        "        signal.alarm((context.get_remaining_time_in_millis() / 1000) - 1)",
        "        LOGGER.info('REQUEST RECEIVED: %s', event)",
        "        LOGGER.info('REQUEST RECEIVED: %s', context)",
        "        if event['RequestType'] == 'Create' or event['RequestType'] == 'Update':",
        "            LOGGER.info('Creating or updating S3 Object')",
        "            bucket_name = event['ResourceProperties']['BucketName']",
        "            file_name = event['ResourceProperties']['FileName']",
        "            content = event['ResourceProperties']['Content']",
        "            create_zip = True if event['ResourceProperties']['CreateMode'] == 'zip' else False",
        "            literal = True if event['ResourceProperties']['CreateMode'] == 'plain-literal' else False",
        "            md5_hash = hashlib.md5(content).hexdigest()",
        "            with open('/tmp/' + file_name, 'w') as lambda_file:",
        "                lambda_file.write(content)",
        "                lambda_file.close()",
        "                s3 = boto3.resource('s3')",
        "                if create_zip == True:",
        "                    output_filename = file_name + '_' + md5_hash + '.zip'",
        "                    zf = zipfile.ZipFile('/tmp/' + output_filename, mode='w')",
        "                    try:",
        "                        zf.write('/tmp/' + file_name, file_name)",
        "                    finally:",
        "                        zf.close()",
        "                        data = open('/tmp/' + output_filename, 'rb')",
        "                        s3.Bucket(bucket_name).put_object(Key=output_filename, Body=data)",
        "                else:",
        "                    if literal == True:",
        "                        data = open('/tmp/' + file_name, 'rb')",
        "                        s3.Bucket(bucket_name).put_object(Key=file_name, Body=content)",
        "                    else:",
        "                        extension = file_name.split(\".\")[-1]",
        "                        output_filename = \".\".join(file_name.split(\".\")[:-1]) + '_' + md5_hash + '.' + extension",
        "                        data = open('/tmp/' + file_name, 'rb')",
        "                        s3.Bucket(bucket_name).put_object(Key=output_filename, Body=content)",
        "            cfnresponse.send(event, context, cfnresponse.SUCCESS, { 'Message': output_filename } )",
        "        elif event['RequestType'] == 'Delete':",
        "            LOGGER.info('DELETE!')",
        "            cfnresponse.send(event, context, cfnresponse.SUCCESS, { 'Message': 'Resource deletion successful!'} )",
        "        else:",
        "            LOGGER.info('FAILED!')",
        "            cfnresponse.send(event, context, cfnresponse.SUCCESS, { 'Message': 'There is no such success like failure.'} )",
        "    except Exception as e: #pylint: disable=W0702",
        "        LOGGER.info(e)",
        "        cfnresponse.send(event, context, cfnresponse.SUCCESS, { 'Message': 'There is no such success like failure.' } )",
        "",
        "def timeout_handler(_signal, _frame):",
        "    '''Handle SIGALRM'''",
        "    LOGGER.info('Time exceeded')",
        "    raise Exception('Time exceeded')",
        "",
        "signal.signal(signal.SIGALRM, timeout_handler)"
      ].fnjoin("\n")
    }
  end
  r.property(:handler) { "index.lambda_handler" }
  r.property(:role) { :lambda_execution_role.ref(:arn) }
  r.property(:runtime) { "python2.7" }
  r.property(:timeout) { "30" }
end

resource :lambda_execution_role,
         type: "AWS::IAM::Role" do |r|
  r.property(:assume_role_policy_document) do
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Principal": {
            "Service": [
              "lambda.amazonaws.com"
            ]
          },
          "Action": [
            "sts:AssumeRole"
          ]
        }
      ]
    }
  end
  r.property(:path) { "/" }
  r.property(:policies) do
    [
      {
        "PolicyName": "root",
        "PolicyDocument": {
          "Version": "2012-10-17",
          "Statement": [
            {
              "Effect": "Allow",
              "Action": %w(logs:CreateLogGroup logs:CreateLogStream logs:PutLogEvents),
              "Resource": "arn:aws:logs:*:*:*"
            },
            {
              "Effect": "Allow",
              "Action": "s3:*",
              "Resource": "arn:aws:s3:::*"
            }
          ]
        }
      }
    ]
  end
end


text:
Q: Cython throws same runtime errors on all Python scripts I did a pip install --upgrade cython without problems on Cygwin.
However, every script I try to run with cython, gives me the following runtime errors, and GINMF (Google Is Not My Friend):
$ cat /tmp/hello_cython.py
print("hello cython")

$ cython /tmp/hello_cython.py -o /tmp/hello_cython.exe

$ /tmp/hello_cython.exe
/tmp/hello_cython.exe: line 1: /bin: is a directory
/tmp/hello_cython.exe: line 65: syntax error near unexpected token `a+k,'
/tmp/hello_cython.exe: line 65: `          PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)'

Anyone knows what is going on?

My Environment:

*

*Cython version 0.22

*CYGWIN_NT-6.1-WOW64 DellIns14 1.7.33-2(0.280/5/3) 2014-11-13 15:45 i686 Cygwin

A: OP acted under the assumption that cython will produce a compiled output, when it actually producesses a c file, which needs to be compiled and linked.


text:
Q: C++: Overloaded template alias Currently programming a specialized Standard Library, and I find that in a particular case this is necessary for me:
namespace std
{
  // key, value
  template<class K, class V>
  using vector_map = other_namespace::vector_map<K, V>;

  // key, value, compare
  template<class K, class V, class C>
  using vector_map = other_namespace::vector_map<K, V, C>;
}

It does, however, not work. Not surprising. But what are my options to achieving this?
I have thought about using the precprocessor, but I want to know what you guys think.
I want to be able to selective alias template class into another namespace, if possible.
Solution (in my case) was to add a default value instead of having several usings:
namespace std
{
  // key, value, compare
  template<class K, class V, class C = default_value>
  using vector_map = other_namespace::vector_map<K, V, C>;
}

A: If you want to write a fancy conditional forwarder, you'll have to not just use using.
template<class A, class B, class... C>
struct vector_map_helper {
  using type = other_namespace::vector_map<A,B>;
};
// specialize for 3:
template<class A, class B, class C>
struct vector_map_helper<A,B,C> {
  using type = other_namespace::vector_map<A,B,C>;
};
template<class A, class B, class C, class D, class...Z>
struct vector_map_helper<A,B,C,D, Z...>; // error 4 or more

template<class A, class B, class... C>
using vector_map = typename vector_map_helper<A,B,C...>::type;

in general, even if you are implementing a std library, you should avoid adding any "user facing" interfaces to your std that do not come from the std library.  And the stuff you do support should match std specifications.
Have a nonstd or a std_ext namespace for non-std extensions.  This will both make existing code either fail to compile or work when ported over, and it will avoid training your programmer-users in bad habits about what is in std.
It is also illegal to add most things to std with narrow exceptions, like std::hash specializations.


text:
Q: Which Schema.org type to use for computer games? The Schema.org website offers a variety of types for books, movies, recipes etc., but there doesn't appear to be a specific one for computer games.
This leaves me with two options:

*

*CreativeWork: http://schema.org/CreativeWork

*Product: http://schema.org/Product
Bearing in mind that the website I am working on is an e-commerce site for games, I'm inclined to go with the Product option.
Unless anyone has alternate suggestions.

A: As of 11 December 2014 there is a new type available:
http://schema.org/VideoGame
This is both a subtype of a new CreativeWork type, Game, and of SoftwareApplication.

A: It seems like Software Application is the thing you're looking for. Under Properties from SoftwareApplication the first property is applicationCategory. The description says:

Type of software application, e.g. "Game, Multimedia".

A: Actually I've just come across an extension to the product schema which defines PC Games.
http://www.productontology.org/doc/PC_game#microdata
So it looks like Product is the right option to go with, even if you don't extend it.
Hopefully this will come in handy for other developers working on e-commerce games websites like myself.


text:
Q: Go from vertical scrolling to horizontal and then back to vertical I am creating a very long page that has a very wide SVG image in the middle of it.I basically want the page to scroll vertically until it gets to that image, and then scroll horizontally to the end of the image, and then continue scrolling vertically to the bottom of the page.
I have been researching this for hours and cannot find anything, so I would really really appreciate any suggestions. Thank you very much!

A: Ok this would be my solution:
Divide the page in three sections:
Upper container, SVG and the bottom container.
By default, give bottom container value "Display: none".
I would wrap the SVG to a div, giving the wrapper value "overflow: hidden;

        svg or whatever image content goes here...

Div 'inner' would be horizontally draggable, I would start diggin in there: http://jqueryui.com/draggable/
Then I would make event listener and when the 'inner' x value would be something else than 0, I'd set Upper contained "display: none;" so that the svg wrapper and it's contents would be the only objects visible.
When the svg would be dragged enough (x value would be -(svg width - screen width)) i'd set bottom area "disply: block;".
Does this make any sense to you?


text:
Q: How to delete an unused content db in SharePoint Error: Databases required upgrade or not supported :
The following databases require upgrade because their versions are older than the backwards compatible range:
SearchServiceApplication1_CrawlStoreDB
Issue- Upgrade-SPContentDatabase –Identity SearchServiceApplication1_CrawlStoreDB
"Upgrade-SPContentDatabase : The content database could not be found."
This is Not the Search Service Application Crawl Store DB that our site uses. It looks as though a new DB was created and that one is being used.
Question - How do I delete a database that is recognized by SharePoint but not being used by SharePoint?

A: You cannot delete content DB from SP. You have to open SQL Server Management Studio. From there you can delete the specific content DB.

A: You can delete content database from SQL Server using the Remove-SPContentDatabase cmdlet, see this for usage.

A: If you only need a list of all content databases, use SharePoint Central Administration.
In the Application Management section just click Manage content databases to go to a page that lists content databases used in your farms. These are the only Content DB used in your farm. Open SQL Server Management Studio and match with the list of Content DB in Central Admin site. Unmatched Content DB should be deleted from SQL Server.
The other thing, if you want to get a list of SharePoint databases that your SharePoint is currently using. You should run this command on SharePoint Management Shell:
Get-SPDatabase | Sort-Object Name | Select Name

If you want the list of databases to be saved in a text file, then you may run the same command but with a paramter:
Get-SPDatabase | Sort-Object Name | Select Name | Out-File D:\temp\SharepointDBsInUseList.txt

Now open SQL Server Management Studio and login to the database server instance of your SharePoint Farm. Again match the databases with databases listed in text file (in our case, SharepointDBsInUseList.txt) and proceed with deletion of unused databases.


text:
Q: My Website is slow with Chrome. But not in any other browser even in Incognito I am fairly new to Web Development. I have created this site - www.hum3r.com
If you try to open the site in Chrome it loads and scrolls so slowly. But in IE, Safari, Firefox and even in Incognito Window of Chrome itself handles perfectly. Please advise why and any suggestion to fix slow  n unsmooth scrolls

A: This sounds like an extensions issue, probably with something that checks scripts as they are downloaded, like AdBlock Plus or a virus scanner. Check which extensions you are running; 99% chance one of them is to blame. Extensions are disabled in incognito mode, which is why it works okay.
Also, as @cale_b said, you should minify and bundle those scripts and stylesheets; those will put a hit on any browser.


text:
Q: Sorting by sheet name below is the macro code which i am using for sorting the sheet name. but i am getting error Getting

Run time error '438' Object doesn't support this property or method".

Can some please help me to resolve this issue.
Sort by sheet name and number <>
Range("B2").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add2 Key:=Range("C2:C" + CStr(ShCount)) _
,SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add2 Key:=Range("D2:D" + CStr(ShCount)) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("B2:D" + CStr(ShCount))
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("B2").Select

Here is the error window:

And here is the code error highlighted in yellow.


text:
Q: How to filter out entries that have the same clustering label I want to compute the Rand Index between two clusterings I have of a dataset, but I have 80,000 entries in the dataset and the R packages I've found so far that compute the Rand Index cannot actually handle a dataset that large. (For example, the error from mclust is Error in table(x, y) : attempt to make a table with >= 2^31 elements)
What I want to do then to reduce the size of the dataset is to filter out entires in my dataset that have the same clustering label. So for example if I have a table
   clusteringA | clusteringB
1       a      |      a
2       b      |      b
3       c      |      b
4       d      |      c
5       d      |      c
6       e      |      d
7       e      |      e

Then what I would like to do is to filter out rows 1, 4 and 5 since they will return 1 for all pairwise comparisons. Is there a computationally efficient way to do this? Will doing this actually allow me to compute the Rand Index?
If not, the other possibility I thought of is to break my dataset into chunks and compute the Rand Index separately on those chunks. Does this seem reasonable? I am guessing that there is a fair amount of equal label assignments between the two clusterings; the Rand Index of the first 500 rows is 1.

A: In clustering, you cannot assume that label a in clustering 1 is the same as label a in clusterings. In the other clustering, this may be label 42 instead.
Because of this, Rand index does not compare labels directly, but rather labels of pairs of points. So 4 and 5 have the same label in clustering 1, they are a pair. They also are a pair in clustering 2, so the two clusterings agree that these points should be in the same cluster.


text:
Q: How to find multiple strings between tag/sub-strings? I have a string which has defined tags around specific words or sub-strings. For example:
text = 'Bring me to <xxx>ibis and the</xxx> in <ccc>NW</ccc> and the <sss>Jan</sss>
<hhh>10</hhh>'

How can I get the strings <xxx>ibis and the</xxx>, <ccc>NW</ccc>, <sss>Jan</sss> and <hhh>10</hhh>. These tags can be anything but the tags covering a word or few words will be similar. Also, if a start or end tag is missing, I don't want that string to be returned. For example:
text = 'Bring me to <xxx>ibis and the in NW</ccc> and the <sss>Jan</sss>
<hhh>10</hhh>'

In this case, only <sss>Jan</sss> and <hhh>10</hhh> has to be returned.

A: Generally, you don't want regex to parse (X)HTML (more info in this answer) Better option is using a parser. This example is with beautifulsoup:
data = '''text = 'Bring me to <xxx>ibis and the</xxx> in <ccc>NW</ccc> and the <sss>Jan</sss>
<hhh>10</hhh>'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'html.parser')

for tag in soup.select('xxx, ccc, sss, hhh'):
    print(tag.get_text(strip=True))

Prints:
ibis and the
NW
Jan
10

EDIT: To get whole tag string:
for tag in soup.select('xxx, ccc, sss, hhh'):
    print(tag)

Prints:
<xxx>ibis and the</xxx>
<ccc>NW</ccc>
<sss>Jan</sss>
<hhh>10</hhh>

EDIT II: If you have list of tags to find:
list_of_tags = ['xxx', 'ccc', 'sss', 'hhh']
for tag in soup.find_all(list_of_tags):
    print(tag)

EDIT: In case of malformed HTML it's necessary to change the parser:
data = '''text = 'Bring me to <xxx>ibis and the in NW</ccc> and the <sss>Jan</sss>
<hhh>10</hhh>'''

from bs4 import BeautifulSoup

soup = BeautifulSoup(data, 'lxml')

list_of_tags = ['xxx', 'ccc', 'sss', 'hhh']
for tag in soup.find_all(list_of_tags):
    if tag.find_all(list_of_tags):
        continue
    print(tag)

Prints:
<sss>Jan</sss>
<hhh>10</hhh>


text:
Q: What prevented the Sphere Builders from correcting their mistakes? In Star Trek: Enterprise, Archer saved humanity from the Xindi, but he didn't really care about the real enemy, the Sphere Builders.
In the episode Zero Hour, the crew of the Enterprise NX-01 destroyed Sphere 41 which started a chain reaction destroying all the spheres. But, the spheres weren't really destroyed if you think about time: they were still there in the Delphic Expanse if you move back in time.
The Sphere Builders altered the past to experiment one thing and failed to get the desired outcome. What could stop them from experimenting again?

A: The Sphere-Builders exist in a parallel dimension to our own, they could only enter ours by using the Spheres to modify our space so that they could survive in it. In the Star Trek: Enterprise episode Zero Hour the crew of the Enterprise blows up Sphere 41, which initiates a chain reaction, causing all of the spheres to be destroyed.
Archer has no time-travel capabilities himself, and is unable to enter the parallel dimension in which the Sphere builders reside. By this time, he has accomplished everything that he possibly can to defeat the Sphere-Builders. Presumably if he had failed at stopping them then he would be told by Crewman Daniels, so we have to assume that he succeeded.
Edit: In fact he was told by Crewman Daniels that his actions fixed the entire timeline, meaning that the threat of the Sphere-Builders is over.

A: Think of the resources that the Sphere Builders would have had to invest into invading normal space. The destruction of the Spheres meant the loss of all of those resources. Destroying the Spheres could have been all that was needed to stop the threat. The Spheres were the Sphere Builders' entire ability to interact with normal space. They may not have been able to go back without the Spheres in place.
Those resources invested in the Spheres could have been way too finite, in Sphere Builder space, and completely invested in the invasion attempt. After the Spheres were gone, the Sphere Builders would be completely cut off from those resources, and physically unable to stage another invasion attempt, even a small enough incursion to prevent the Spheres' destruction.
Another possibility is even simpler: The loss of those resources could have crashed the Sphere Builders' economy, and led to a change in Sphere Builder leadership to those less likely to pursue an invasion of normal space, and there was no will among the new leadership to fund another incursion to prevent the Spheres' destruction.


text:
Q: How do I know Rails has loaded/cached an Activerecord class attributes? Suppose I have a ActiveRecord class "User".
I realize the first time I use it via User.new, Rails makes a call to the database to get the actual attributes of User from the users table. Subsequent times it is cached, and doesn't require a database call.
This is fine.. and straightforward in a single thread.
Suppose I have multiple threads running in a single process. The first thread that calls User.new (or anything that involves User, such as finding one), will lookup the attributes in the database. The subsequent ones will have them cached.
Is there a way to check to see if the ActiveRecord attributes are cached or not?
I don't want to have to always check out a database connection via ActiveRecord::Base.connection_pool.with_connection when I call User.new, when I don't plan on using the database connection - Yes not even saving it.
u = nil

ActiveRecord::Base.connection_pool.with_connection do # I don't want to checkout a conn if User attributes are cached.
   u = User.new
end

#manipulation of u. but u.save NEVER ever gets called.

I won't fully explained my entire reasoning, but doing so would detract people from answering because in a word: it's complicated. Here's an article if interested though that is similar to my problem: https://bibwild.wordpress.com/2014/07/17/activerecord-concurrency-in-rails4-avoid-leaked-connections/ I basically do NOT want to checkout a database connection if possible, but still want to call User.new to manipulate with it but NOT save it.

A: Yes and no. The actual schema cache can be found under ActiveRecord::Base.connection.schema_cache, but the act of calling connection causes it to be opened. If ActiveRecord::Base.connected? if false you can assume there is no schema cache, and if it is true you would have to inspect the @columns ivar of your schema_cache instance.
This is hacky because the Active Record pattern assumes that objects are connected to a datasource. If you need domain objects that are independent of your DB, I would recommend writing them as POROs using Virtus + ActiveModel::Validation, or dry-struct etc.


text:
Q: line 39: 'if' cannot be used as a variable or function name Can anyone please help me understand what is the issue with the code I have written below.
My apologies, I am a new coder and I'm finding the debugging process to be difficult. The error I'm getting is in the Title.
line 39: 'if' cannot be used as a variable or function name.
//@version=5
strategy(title="Trend Following Strategy", overlay=true, pyramiding = true)

//Trend Filter Variables
ma_slow = ta.ema (close, 200) // moving average
ma_fast = ta.ema (close, 50) // moving average
ma_prev_high= ta.highest(ma_slow, 500) //Previous high of the EMA
trending_Market = ma_slow >= ma_prev_high//Current ma value is greater than previous ma value

//Trigger Condition
[macdLine, macdSig, macdHist ] = ta.macd(close, 12, 26, 9) // get MACD indicator
trigger = ma_fast > ma_slow and close > ma_slow and macdLine < 0 and macdSig <0 and macdLine > macdSig and macdHist[1] > 0 and macdHist[2] > 0

//Stop Loss Variables
prev_lows = ta.lowest(low, 150) //Price action Low
atr = ta.atr(14) //Average True Range - Stop Loss Buffer
price_stop = 0.0 //Stop initially set as null

//Long Condition
longCondition = trending_Market and trigger //go long if market is trending and trigger is hit
if (longCondition)
   strategy.entry("long", strategy.long)

//Once in the position declare the below variables
if (strategy.position_size> 0)

// Stop Loss Computation
   stopValue = prev_lows - atr //Stop loss value including ATR buffer
   price_stop := math.max(stopValue, price_stop[1] ) //Trailing condition for SL

else
   price_stop := 0 // If no position set SL to null

//Conditions for entering a second position adjusting for risk already in the portfolio

//If trigger is hit while I have an open position and the trrailing SL has moved so that the position does not contain any risk
//- then buy a full unit of risk
if (strategy.position_size> 0 and longCondition and math.avg(strategy.opentrades.entry_price(1),close)< price_stop)// If SL is above the average price of the 2 entries
   strategy.entry("long2_fullunit", strategy.long)

//If trigger is hit while I have an open position and SL is below the average price -
//i.e. there is still risk present from the initial position

if (strategy.position_size> 0 and longCondition and math.avg(strategy.opentrades.entry_price(1),close)> price_stop)// If SL is below the average price

//Declaraing Risk management variables
   avg_price = math.avg(strategy.opentrades.entry_price(1),close)//Average price of the initial entry and the current price at which the second postion will execute
   lot2 = (avg_price/(avg_price - price_stop))*10000// Lot size per 1 unit of risk at current SL and average price
   lot2_qty = lot2/close //Investment amount in share quantity
   risk_adjusted_qty = lot2 - strategy.position_size // The difference in the proposed quantity of shares to purchase in the second postion and thequantity of shares already held

   strategy.entry("long2_risk_adjusted_unit", strategy.long, qty = risk_adjusted_qty ) // enter the second trade at a risk adjusted ammount, keeping risk always at 1R.

//exit condition
if (strategy.position_size>0) //apply the exit strategy with variables declared upon entry
   strategy.exit(id= "Stop Loss", stop= price_stop  )

A: The local blocks in conditional structures must be indented by four spaces or a tab. You have three spaces as far as I can see and if I fix those indentation issues, there are no errors.
//@version=5
strategy(title="Trend Following Strategy", overlay=true, pyramiding = true)

//Trend Filter Variables
ma_slow = ta.ema (close, 200) // moving average
ma_fast = ta.ema (close, 50) // moving average
ma_prev_high= ta.highest(ma_slow, 500) //Previous high of the EMA
trending_Market = ma_slow >= ma_prev_high//Current ma value is greater than previous ma value

//Trigger Condition
[macdLine, macdSig, macdHist ] = ta.macd(close, 12, 26, 9) // get MACD indicator
trigger = ma_fast > ma_slow and close > ma_slow and macdLine < 0 and macdSig <0 and macdLine > macdSig and macdHist[1] > 0 and macdHist[2] > 0

//Stop Loss Variables
prev_lows = ta.lowest(low, 150) //Price action Low
atr = ta.atr(14) //Average True Range - Stop Loss Buffer
price_stop = 0.0 //Stop initially set as null

//Long Condition
longCondition = trending_Market and trigger //go long if market is trending and trigger is hit
if (longCondition)
    strategy.entry("long", strategy.long)

//Once in the position declare the below variables
if (strategy.position_size> 0)

// Stop Loss Computation
    stopValue = prev_lows - atr //Stop loss value including ATR buffer
    price_stop := math.max(stopValue, price_stop[1] ) //Trailing condition for SL

else
    price_stop := 0 // If no position set SL to null

//Conditions for entering a second position adjusting for risk already in the portfolio

//If trigger is hit while I have an open position and the trrailing SL has moved so that the position does not contain any risk
//- then buy a full unit of risk
if (strategy.position_size> 0 and longCondition and math.avg(strategy.opentrades.entry_price(1),close)< price_stop)// If SL is above the average price of the 2 entries
    strategy.entry("long2_fullunit", strategy.long)

//If trigger is hit while I have an open position and SL is below the average price -
//i.e. there is still risk present from the initial position

if (strategy.position_size> 0 and longCondition and math.avg(strategy.opentrades.entry_price(1),close)> price_stop)// If SL is below the average price

//Declaraing Risk management variables
    avg_price = math.avg(strategy.opentrades.entry_price(1),close)//Average price of the initial entry and the current price at which the second postion will execute
    lot2 = (avg_price/(avg_price - price_stop))*10000// Lot size per 1 unit of risk at current SL and average price
    lot2_qty = lot2/close //Investment amount in share quantity
    risk_adjusted_qty = lot2 - strategy.position_size // The difference in the proposed quantity of shares to purchase in the second postion and thequantity of shares already held
    strategy.entry("long2_risk_adjusted_unit", strategy.long, qty = risk_adjusted_qty ) // enter the second trade at a risk adjusted ammount, keeping risk always at 1R.

//exit condition
if (strategy.position_size>0) //apply the exit strategy with variables declared upon entry
    strategy.exit(id= "Stop Loss", stop= price_stop  )


text:
Q: TreeMap sorting for a foreach, by keys I would like some advice from the community about some code I wrote.  I have ...
TreeMap<Integer,TreeMap<Integer,String>> tableError;

... and I have this toString() method:
public String toString(){
    StringBuilder s = new StringBuilder();

    for( Integer line : this.tableError.keySet()){
        for(Integer pos : this.tableError.get(line).keySet()){
            s.append("line: "+line);
            s.append(":"+pos);
            s.append("\t"+this.tableError.get(line).get(pos));
            s.append("\n");
        }
    }
    return s.toString();
}

I know that TreeMaps are algorithmically sorted by their keys.  I want know whether the Strings obtained via that toString() method will always be sorted by my pos variable too?
My confusion arises in part because the javadocs for keySet() say that it returns a Set, but that doesn't explicitly promise that the key set is sorted. At least, I didn't see any such guarantee.


text:
Q: Is there a similar command in VSC like "run App" in RStudio? I am working with R in Visual Studio Code, which is usually working fine. To start my Shiny app I used: (source("app.R"))
Until yesterday, this worked fine, just as "run App" button in RStudio, but now I get some different behavior in some lines of code of my app leading to an error. What is working in VSC is to run all line of "app.R" in a sequence separately.
Is there a similar command or button in VSC like the "run App" button in RStudio?


text:
Q: pushing to Heroku gives error "We're sorry, but something went wrong." I've been at this for an hour or two, but can't seem to figure out what the problem may be.
I was using sqlite3 for dev but before pushing to heroku I decided to switch to pg (using ubuntu), and it works fine on my local dev environment.
then I pushed to Heroku I keep getting a blank bage with the follow:
We're sorry, but something went wrong.

'this doesn't really help. Is there a log file for production I can access via heroku?
Also my best guess is it has something to do with the bd, maybe it didn't load properly. I checked my heroku account and click the following addon:
Heroku Postgres Dev :: Olive
now my db says size of 6mb but tables 0, which is concerning. However I don't know how to query my db on heroku and there seems to be no interface on the site to view my db. Does db not automatically push with "git push heroku master"
Anyways, db is my best guess at the moment but I can't be certain, I'm not sure what to do since I have no logs
EDIT:
I was able to check the db on heroku using:
heroku pg:psql

from https://devcenter.heroku.com/articles/heroku-postgresql
however, there are no enteries in my db, there are enteries in my dev db but apparently it did not transfer to heroku, is there a way to push (or overwrite) your heroku db with the one in your dev environment?
Kyle:
I tried the taps thing,Failed to connect to database:
  Sequel::DatabaseConnectionError -> PG::Error: FATAL:  password authentication fai
led for user "pc"
FATAL:  password authentication failed for user "pc" however I get the error:

pc us my username for pg on my ubuntu machine, however my password is ok since its working on my local machine
my database.yml file
development:
  adapter: postgresql
  encoding: utf8
  reconnect: false
  database: someapp_development
  pool: 5
  username: pc
  password: ***

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  adapter: postgresql
  encoding: utf8
  reconnect: false
  database: someapp_development
  pool: 5
  username: pc
  password: ***

production:
  adapter: postgresql
  encoding: utf8
  reconnect: false
  database: someapp_development
  pool: 5

EDIT: I checked the log and it is infact the db causing the problem, the enteries in my table aren't being pushed into heroku and with an empty db my app is crashing (bad design I know)

A: You may need to migrate your production database
heroku run rake db:migrate
heroku restart

If you need the data imported to your heroku db, see this
 gem install taps
 heroku db:push

edit:
try this alternative method:
heroku db:push postgres://user:pass@localhost/dbname

A: If I remember correctly the user postgres has no DB password set on Ubuntu by default. That means, that you can login only to that account when you use the postgres OS user account.
Assuming, that you have root access on the box you can do:
sudo -u postgres psql

If that fails with database "postgres" does not exists error, then you are most likely not on a Ubunutu or Debian server :-) In this case simply add template1 to the command:
sudo -u postgres psql template1

The any of those commands fail with an error psql: FATAL: password authentication failed for user "pc" then check the file /etc/postgresql/8.4/main/pg_hba.conf: There must be a line like this as the first non-comment line:
local   all         postgres                          ident

For newer versions of PostgreSQL ident actually might be peer. That's OK also.
Inside the psql shell you can give the DB user postgres a password:
ALTER USER postgres PASSWORD 'newPassword';

Now you should be able to give pgAdmin a valid password for the DB superuser and it will be happy too. :-)


text:
Q: How to load react's staticfiles from s3 in django - react So I have a Django - React application. All the static files are served by s3
I ran
npm run build

and then i coped the build folder into my django project folder. and then i setup the template dirs and staticfiles dirs in my settings.py file.
when i try to load the django-admin page. everything works perfectly. the static files are served by aws s3. But when i try to load the react page. it tries to look for static files locally which obviously does not exist.
so how do i tell my react app to look for the staticfiles in s3?
this is how my index.html looks
<!doctype html>

    <meta charset="utf-8"/>
    <link rel="icon" href="/favicon.ico"/>
    <meta name="viewport" content="width=device-width,initial-scale=1"/>
    <meta name="theme-color" content="#000000"/>
    <meta name="description" content="jgprth."/>
    <link rel="apple-touch-icon" href="/logo192.png"/>
    <link rel="manifest" href="/manifest.json"/>
    <title>test</title>

You need to enable JavaScript to run this app.

A: Set the PUBLIC_URL configuration in the .env file (read by the ReactJS compiler). The string you set there will be used to prefix all static file addresses, so it could be the address of the static files in local development (like http://localhost:8000/static) or a S3 bucket address (like https://foobar.s3.amazonaws.com).
Hints found here, react docs for PUBLIC_URL here.
EDIT: The only solution that I found, and that actually worked, was to serve the static files from Nginx (instead of S3) when running on AWS.
The React.JS app is compiled with an absolute path within the same domain:
PUBLIC_URL=/rjsstatic/foo/bar/

The Django site is handles the route rjsstatic/foo/bar/(?<path>.+)$ to a view that serves static files (just for development setups). I used this method:
from django.contrib.staticfiles.views import serve

REACT_JS_APP_PATH = 'my_reactjs_app'

def serve_react_app_files(request, path):
    return serve(request, os.path.join(REACT_JS_APP_PATH, path))

In this example, the files are stored in static/my_reactjs_app/.
And on production Nginx is configured to capture this same route and serve the static files. A simple alias configuration is used:
location /rjsstatic/foo/bar/ {
    alias /path/to/reactjs/static/files/;
}


text:
Q: in nested UIStackView when I add more than one arranged subview, it breaks the layout, why? Playing with UIStackView I encountered a weird issue which does not allow me to add extra arranged subview in nested UIStackView:
 override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white

        let subViews = [UIColor.gray, UIColor.darkGray, UIColor.lightGray].map { (color) -> UIView in
            let v = UIView()
            v.backgroundColor = color
            return v
        }

        let redView = UIStackView(arrangedSubviews: subViews)
        redView.distribution = .fillEqually
        redView.heightAnchor.constraint(lessThanOrEqualToConstant: 100).isActive = true

        let blueView = UIView()
        blueView.backgroundColor = .blue

        let buttons = [UIColor.gray, UIColor.darkGray, UIColor.lightGray].map { (color) -> UIView in
            let v = UIView()
            v.backgroundColor = color
            return v
        }

        let buttonsView = UIStackView(arrangedSubviews: buttons)
        buttonsView.distribution = .fillEqually
        buttonsView.heightAnchor.constraint(lessThanOrEqualToConstant: 100).isActive = true

        let stackView = UIStackView(arrangedSubviews: [redView, blueView, buttonsView])

        view.addSubview(stackView)
        stackView.axis = .vertical
        stackView.fillSuperview()

    }

In result, I get full-stretched blue view instead of expecting behavior:

But when I leaving ONE subview in bottom stack view - it appears as expected
   let buttons = [UIColor.gray].map { (color) -> UIView in
        let v = UIView()
        v.backgroundColor = color
        return v
    }

    let buttonsView = UIStackView(arrangedSubviews: buttons)
    buttonsView.distribution = .fillEqually
    buttonsView.heightAnchor.constraint(lessThanOrEqualToConstant: 100).isActive = true

    let stackView = UIStackView(arrangedSubviews: [redView, blueView, buttonsView])

why ? What is wrong with the code ? Any help or hint is appreciated, I tried translatesAutoresizingMaskIntoConstraints = false on top and bottom stack views as well but without any luck

A: on the bottom stackview it was required to set
buttonView.heightAnchor.constraint(equalToConstant: 100).isActive = true
instead of
buttonView.heightAnchor.constraint(lessThanOrEqualToConstant: 100).isActive = true