text:
Q: Android: ListView with RelativeLayout -> NullReference I'm trying to implement a ListView relative layout using a ViewHolder. In getView(), I'm running into a NullReference. I've modeled the code after an example I found here on Stack Overflow. Here's the code:
private ViewHolder mViewHolder;

public View getView(int position, View convertView, ViewGroup parent) {

    final ToDoItem toDoItem = mItems.get(position);

    if (convertView==null){
        mViewHolder = new ViewHolder();
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.todo_item, parent, false);

        RelativeLayout itemLayout = (RelativeLayout) convertView.findViewById(R.id.RelativeLayout1);

        mViewHolder.tvTitle = (TextView) convertView.findViewById((R.id.title));
        mViewHolder.cbStatus = (CheckBox) convertView.findViewById(R.id.statusCheckBox);
        mViewHolder.tvPriority = (TextView) convertView.findViewById(R.id.priority);
        mViewHolder.tvDate = (TextView) convertView.findViewById(R.id.date);

        convertView.setTag(mViewHolder);
    }else{
        mViewHolder = (ViewHolder) convertView.getTag();
    }

    --->mViewHolder.tvTitle.setText(toDoItem.getTitle());
    mViewHolder.tvPriority.setText(toDoItem.getPriority().toString());
    mViewHolder.tvDate.setText(toDoItem.getDate().toString());
    mViewHolder.cbStatus.setChecked(false);

    if (toDoItem.getStatus().toString() == "DONE") mViewHolder.cbStatus.setChecked(true);

    final TextView titleView = mViewHolder.tvTitle;
    final CheckBox statusView = mViewHolder.cbStatus;
    final TextView priorityView = mViewHolder.tvPriority;
    final TextView dateView = mViewHolder.tvDate;

    itemLayout.addView(titleView);
    itemLayout.addView(statusView);
    itemLayout.addView(priorityView);
    itemLayout.addView(dateView);

    return convertView;

The NullReference is thrown on the line following the closing bracket of the
if (convertView == null)
and is marked with ---->
I've tried to assign different entities to the ViewHolder with little success. I'd appreciate any help anyone has to offer. Thanks in advance!
Markb

A: toDoItem Could be null as well if that object in the list is null.


text:
Q: Typescript eslint and strict_check errors due to any keyword Code snippet below with comments explaining the code.
  // The function here is to check whether the two arguments are equivalent or
  // not empty or not. So, we cannot have any specific type defined for the
  // arguments and the arguments are given a generic type of Object.
  /**
   * @param {Object} a - the first object to be compared.
   * @param {Object} b - the second object to be compared.
   * @return {boolean} - true if a is equivalent to b, false otherwise.
   */
  isEquivalent(a: Object, b: Object): boolean {
    if (a === null || b === null) {
      return a === b;
    }
    if (typeof a !== typeof b) {
      return false;
    }
    if (typeof a !== 'object') {
      return a === b;
    }
    // Create arrays of property names.
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);
    if (aProps.length !== bProps.length) {
      return false;
    }
    for (var i = 0; i < aProps.length; i++) {
      var propName = aProps[i];
      if (!this.isEquivalent(a[propName], b[propName])) {
        return false;
      }
    }
    return true;
  }

I'm running this with typescript checks --strict_checks, which gives me the following error message:
error TS7053: Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Object'.
No index signature with a parameter of type 'string' was found on type 'Object'.
When I modify the for loop to the following:
for (var i = 0; i < aProps.length; i++) {
    var propName = aProps[i];
    const aObj: {[index: string]: any} = a;
    const bObj: {[index: string]: any} = b;
    if (!this.isEquivalent(aObj[propName], bObj[propName])) {
      return false;
    }
 }

the --strict_check errors are fixed. However, I now receive typescript eslint errors since the use of keyword "any" is prohibited in eslint. Can anyone point me in the right direction on getting around these errors without disabling the checks?

A: You shouldn't use Object as a type. You can use object (see the docs here), but you'll still get the any-error when using loops and accessing properties because object isn't indexable. The solution is to provide your own interface:
interface IndexableObject {
    [key: string]: string | IndexableObject
}

Assuming the objects you're comparing are possibly recursive, you can define the IndexableObject's value as either a string, or itself another IndexableObject.
Another thing that leads to errors is the fact you're checking if a is an object, but not if b is an object as well. The compiler will complain because you will later possibly be accessing a string as if it were an object (a[propName/b[propName]). While that will actually work, because in JS everything is an object (so 'foo'[0] will yield "f"), the TypeScript compiler won't like it. So you should check for that as well.
With these changes, your function will work as expected:
interface IndexableObject {
    [key: string]: string | IndexableObject
}

// The function here is to check whether the two arguments are equivalent or
// not empty or not. So, we cannot have any specific type defined for the
// arguments and the arguments are given a generic type of Object.
/**
 * @param {Object} a - the first object to be compared.
 * @param {Object} b - the second object to be compared.
 * @return {boolean} - true if a is equivalent to b, false otherwise.
 */
function isEquivalent(a: IndexableObject | string, b: IndexableObject | string): boolean {
    if (a === null || b === null) {
      return a === b;
    }
    if (typeof a !== typeof b) {
      return false;
    }
    if (typeof a !== 'object' || typeof b !== 'object') {
      return a === b;
    }
    // Create arrays of property names.
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);
    if (aProps.length !== bProps.length) {
      return false;
    }
    for (var i = 0; i < aProps.length; i++) {
      var propName = aProps[i];
      if (!isEquivalent(a[propName], b[propName])) {
        return false;
      }
    }
    return true;
  }

  const ex1 = { 'foo': 'bar' };
  const ex2 = { 'foo': 'bar' };
  const ex3 = { 'foo': 'foo' };
  const ex4 = { 'foo': { 'foo2': 'foo3' } };
  const ex5 = { 'foo': { 'foo2': 'foo3' } };
  const ex6 = { 'foo': { 'foo2': 'foo4' } };

  console.log(isEquivalent(ex1, ex2)); // true
  console.log(isEquivalent(ex1, ex3)); // false
  console.log(isEquivalent(ex4, ex5)); // true
  console.log(isEquivalent(ex4, ex6)); // false

By the way, if you have Lodash in your project, they have solved this problem quite nicely already. It is my experience "rolling your own" is more fun, but you'll sooner or later run into edge cases others have already tackled, at which point the fun pretty much stops. That's just my $0.02 though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass data from Service to Broadcastreceiver I am calling broadcast receiver from service through this method.
   Intent intent = new Intent(NotifyService.this, AlarmReciever.class);
   intent.putExtra("TIME",ttime);
   PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(),    34324243, intent, 0);
   AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
   alarmManager.set(AlarmManager.RTC_WAKEUP,timee,pendingIntent);

In Broadcastreceiver page I am receiveing through this method.
   Bundle b = in.getExtras();
   date = b.getString("TIME");

Problem is In Broadcastreceiver page I am getting null value.
My Question is :-
How to pass data from service to broadcastreceiver ?

A: In your main activity start your service as
i = new Intent(this, SimpleService.class);
startService(i);
registerReceiver(broadcastReceiver, new IntentFilter(SimpleService.BROADCAST_ACTION));

use send broadcast to send any value from service class to mainactiviy class as
intent.putExtra("textval", s);
sendBroadcast(intent);

and then in your main activity class receive it as
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {

            //do your coding here using intent
        }

    };

A: OK i assume  the "ttime" is  a bundle (  from the  code  your  wrote it seems  to make  sense)
Try and  recieve the  data  like  this
   Bundle b=  in.getBundleExtra("TIME");

In case the "tttime" is  of  other format  say a  String  or Int   you can  get the  data  in onReceive of Broadcastreceiverlike this
String :
in.getStringExtra("TIME");

Integer :
in.getIntExtra("TIME", -1) // -1 is  default value  which  will be  return incase  no matching integer  found with the key "TIME" in intent "in"

For  full details and  how to get data from  intent  of different type  refer to android  documentation

A: you missed to do like this:-
Intent intent = new Intent(NotifyService.this, AlarmReciever.class);
sendBroadcast(intent);

You can call pendingIntent Like this:-
    PendingIntent operation = PendingIntent.getBroadcast(Service.this,
            0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis(),5* 60 * 1000, operation);

If you are passing any time data to broadcast class,then you can receive that data in receiver class as
String mTime = NotifyService.time;

Try this. Inform me also.


text:
Q: docker login fails on gitlab Im trying to deploy a django app using the gitlab ci and using docker for the same .
My deploy.sh file:
ssh -o StrictHostKeyChecking=no ec2-user@$EC2_PUBLIC_IP_ADDRESS << 'ENDSSH'
  cd /home/ec2-user/app
  export $(cat .env | xargs)
  docker login -u $CI_REGISTRY_USER -p $CI_JOB_TOKEN $CI_REGISTRY
  docker pull $IMAGE:web
  docker pull $IMAGE:nginx
  docker-compose -f docker-compose.prod.yml up -d
ENDSSH

.yml:
deploy:
  stage: deploy
  script:
    - mkdir -p ~/.ssh
    - echo "$PRIVATE_KEY" | tr -d '\r' > ~/.ssh/id_rsa
    - cat ~/.ssh/id_rsa
    - chmod 700 ~/.ssh/id_rsa
    - eval "$(ssh-agent -s)"
    - ssh-add ~/.ssh/id_rsa
    - ssh-keyscan -H 'gitlab.com' >> ~/.ssh/known_hosts
    - chmod +x ./deploy.sh
    - scp  -o StrictHostKeyChecking=no -r ./.env ./docker-compose.prod.yml ec2-user@$EC2_PUBLIC_IP_ADDRESS:/home/ec2-user/app
    - bash ./deploy.sh

I have a running instance on AWS EC2..
Error :
Get https://registry.gitlab.com/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)

 Error response from daemon: Get https://registry.gitlab.com/v2/: net/http: request canceled while waiting for connection (Client.Timeout exceeded while awaiting headers)

I have tried to change dns by editing /etc/docker/daemon.json
{
  "dns": ["192.168.4.1", "8.8.8.8"]
}

sudo service docker restart

But no changes!

A:  DOCKER_OPTS="--dns 8.8.8.8"

inside /etc/default/docker fixed the issue


text:
Q: Paypal Adaptive Payments Plugin Not Working with WooCommerce I have a wordpress ecommerce site, selling online ebooks and guides. I installed this plugin:
https://www.woothemes.com/products/paypal-adaptive-payments
I want to use it to send commissions automatically from the primary paypal account, to a 2nd account.
It worked for about 1 day, then for some reason now won't work. Everytime I click on "Proceed to Paypal" to make the payment, I get this error at the top of the page:
"An error has occurred while processing your payment, please try again. Or contact us for assistance."
I followed all documentation to the bone, and I know my API credentials are correct, the API was approved and is Live.
Any help please?

A: I have the same issue.  My site has SSL.
Woothemes Support is very limited and takes days to respond.
Their latest response was to make sure I am using the latest version 1.1.5, but from what I gather, that version isn't even available at this time. So the ball is back in Woothemes court & expect another couple days for a response.
Right now, I have PayPal working on it. I called in and they said they put in an "integration" ticket with their developers who will reach out to me to fix it.
So they're in the process of working it out, with my fingers crossed.  It's likely best to call in to PayPal.
Best of luck!


text:
Q: Arduino AccelStepper Library not reversing direction I am running an Arduino Mega, LCD Sheild 1602, TB6600 Driver, Nema 17 motor.
Code: https://pastebin.com/6HGLhADF
The code for "running" works fine.
I have tried several different options (like setting negative value or moveTo) to "reset" the motor but when I select the reset menu item I want the motor to run in counter clockwise. the speed changes but the direction does not.
Can anyone help me understand why the motor is not running in reverse direction?
Code also Pasted below if needed: I used Paul Siewerts LCD tutorial as my base.
    Name    : LCD Button Shield Menu
    Author  : Paul Siewert
    Created : June 14, 2016
    Last Modified: June 14, 2016
    Version : 1.0
    Notes   : This code is for use with an Arduino Uno and LCD/button shield. The
              intent is for anyone to use this program to give them a starting
              program with a fully functional menu with minimal modifications
              required by the user.
    License : This program is free software. You can redistribute it and/or modify
              it under the terms of the GNU General Public License as published by
              the Free Software Foundation, either version 3 of the License, or
              (at your option) any later version.
              This program is distributed in the hope that it will be useful,
              but WITHOUT ANY WARRANTY; without even the implied warranty of
              MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
              GNU General Public License for more details.
 ***************************************************************************************/
/*
   This program is designed to get you as close as possible to a finished menu for the standard Arduino Uno LCD/button shield. The only required modifications
   are to add as menu items to the master menu (menuItems array) and then modify/adjust the void functions below for each of those selections.
*/

#include <AccelStepper.h>
// defines pins numbers
  //Motor Pins
const int stepPin = 11;
const int dirPin = 2;
const int enPin = 13;
AccelStepper stepper(1,stepPin, dirPin, enPin);

// defines variables
int maxStepSpeed = 10000;
//long stepSpeed = 316.0299659;
//long stepResetSpeed = -1000;
//int forwarddir = 44802;

// You can have up to 10 menu items in the menuItems[] array below without having to change the base programming at all. Name them however you'd like. Beyond 10 items, you will have to add additional "cases" in the switch/case
// section of the operateMainMenu() function below. You will also have to add additional void functions (i.e. menuItem11, menuItem12, etc.) to the program.
String menuItems[] = {"Start", "Reset"};

// Navigation button variables
int readKey;

// Menu control variables
int menuPage = 0;
int maxMenuPages = round(((sizeof(menuItems) / sizeof(String)) / 2) + .5);
int cursorPosition = 0;

// Creates 3 custom characters for the menu display
byte downArrow[8] = {
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b10101, // * * *
  0b01110, //  ***
  0b00100  //   *
};

byte upArrow[8] = {
  0b00100, //   *
  0b01110, //  ***
  0b10101, // * * *
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b00100, //   *
  0b00100  //   *
};

byte menuCursor[8] = {
  B01000, //  *
  B00100, //   *
  B00010, //    *
  B00001, //     *
  B00010, //    *
  B00100, //   *
  B01000, //  *
  B00000  //
};

#include <LiquidCrystal.h>

// Setting the LCD shields pins
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

void setup() {

  // Initializes serial communication
  Serial.begin(9600);

  // Initializes and clears the LCD screen
  lcd.begin(16, 2);
  lcd.clear();

  // Creates the byte for the 3 custom characters
  lcd.createChar(0, menuCursor);
  lcd.createChar(1, upArrow);
  lcd.createChar(2, downArrow);
  stepper.setMaxSpeed(maxStepSpeed);
//  stepper.setSpeed(stepSpeed);
//  stepper.moveTo(44803);
  stepper.disableOutputs();
}

void loop() {
  mainMenuDraw();
  drawCursor();
  operateMainMenu();
}

// This function will generate the 2 menu items that can fit on the screen. They will change as you scroll through your menu. Up and down arrows will indicate your current menu position.
void mainMenuDraw() {
  Serial.print(menuPage);
  lcd.clear();
  lcd.setCursor(1, 0);
  lcd.print(menuItems[menuPage]);
  lcd.setCursor(1, 1);
  lcd.print(menuItems[menuPage + 1]);
  if (menuPage == 0) {
    lcd.setCursor(15, 1);
    lcd.write(byte(2));
  } else if (menuPage > 0 and menuPage < maxMenuPages) {
    lcd.setCursor(15, 1);
    lcd.write(byte(2));
    lcd.setCursor(15, 0);
    lcd.write(byte(1));
  } else if (menuPage == maxMenuPages) {
    lcd.setCursor(15, 0);
    lcd.write(byte(1));
  }
}

// When called, this function will erase the current cursor and redraw it based on the cursorPosition and menuPage variables.
void drawCursor() {
  for (int x = 0; x < 2; x++) {     // Erases current cursor
    lcd.setCursor(0, x);
    lcd.print(" ");
  }

  // The menu is set up to be progressive (menuPage 0 = Item 1 & Item 2, menuPage 1 = Item 2 & Item 3, menuPage 2 = Item 3 & Item 4), so
  // in order to determine where the cursor should be you need to see if you are at an odd or even menu page and an odd or even cursor position.
  if (menuPage % 2 == 0) {
    if (cursorPosition % 2 == 0) {  // If the menu page is even and the cursor position is even that means the cursor should be on line 1
      lcd.setCursor(0, 0);
      lcd.write(byte(0));
    }
    if (cursorPosition % 2 != 0) {  // If the menu page is even and the cursor position is odd that means the cursor should be on line 2
      lcd.setCursor(0, 1);
      lcd.write(byte(0));
    }
  }
  if (menuPage % 2 != 0) {
    if (cursorPosition % 2 == 0) {  // If the menu page is odd and the cursor position is even that means the cursor should be on line 2
      lcd.setCursor(0, 1);
      lcd.write(byte(0));
    }
    if (cursorPosition % 2 != 0) {  // If the menu page is odd and the cursor position is odd that means the cursor should be on line 1
      lcd.setCursor(0, 0);
      lcd.write(byte(0));
    }
  }
}

void operateMainMenu() {
  int activeButton = 0;
  while (activeButton == 0) {
    int button;
    readKey = analogRead(0);
    if (readKey < 790) {
      delay(100);
      readKey = analogRead(0);
    }
    button = evaluateButton(readKey);
    switch (button) {
      case 0: // When button returns as 0 there is no action taken
        break;
      case 1:  // This case will execute if the "forward" button is pressed
        button = 0;
        switch (cursorPosition) { // The case that is selected here is dependent on which menu page you are on and where the cursor is.
          case 0:
            menuItem1();
            break;
          case 1:
            menuItem2();
            break;
        }
        activeButton = 1;
        mainMenuDraw();
        drawCursor();
        break;
      case 2:
        button = 0;
        if (menuPage == 0) {
          cursorPosition = cursorPosition - 1;
          cursorPosition = constrain(cursorPosition, 0, ((sizeof(menuItems) / sizeof(String)) - 1));
        }
        if (menuPage % 2 == 0 and cursorPosition % 2 == 0) {
          menuPage = menuPage - 1;
          menuPage = constrain(menuPage, 0, maxMenuPages);
        }

        if (menuPage % 2 != 0 and cursorPosition % 2 != 0) {
          menuPage = menuPage - 1;
          menuPage = constrain(menuPage, 0, maxMenuPages);
        }

        cursorPosition = cursorPosition - 1;
        cursorPosition = constrain(cursorPosition, 0, ((sizeof(menuItems) / sizeof(String)) - 1));

        mainMenuDraw();
        drawCursor();
        activeButton = 1;
        break;
      case 3:
        button = 0;
        if (menuPage % 2 == 0 and cursorPosition % 2 != 0) {
          menuPage = menuPage + 1;
          menuPage = constrain(menuPage, 0, maxMenuPages);
        }

        if (menuPage % 2 != 0 and cursorPosition % 2 == 0) {
          menuPage = menuPage + 1;
          menuPage = constrain(menuPage, 0, maxMenuPages);
        }

        cursorPosition = cursorPosition + 1;
        cursorPosition = constrain(cursorPosition, 0, ((sizeof(menuItems) / sizeof(String)) - 1));
        mainMenuDraw();
        drawCursor();
        activeButton = 1;
        break;
    }
  }
}

// This function is called whenever a button press is evaluated. The LCD shield works by observing a voltage drop across the buttons all hooked up to A0.
int evaluateButton(int x) {
  int result = 0;
  if (x < 60) {
    result = 1; // right
  } else if (x < 300) {
    result = 2; // up
  } else if (x < 500) {
    result = 3; // down
  } else if (x < 700) {
    result = 4; // left
  }
  return result;
}

// If there are common usage instructions on more than 1 of your menu items you can call this function from the sub
// menus to make things a little more simplified. If you don't have common instructions or verbage on multiple menus
// I would just delete this void. You must also delete the drawInstructions()function calls from your sub menu functions.
void drawInstructions() {
  lcd.setCursor(0, 1); // Set cursor to the bottom line
  lcd.print("Use ");
  lcd.print(byte(1)); // Up arrow
  lcd.print("/");
  lcd.print(byte(2)); // Down arrow
  lcd.print(" buttons");
}

void menuItem1() { // Function executes when you select the 1st item from main menu
  int activeButton = 0;

  lcd.clear();
  lcd.setCursor(3, 0);
  lcd.print("running");
  long stepSpeed = 316.0299659;
  stepper.setSpeed(stepSpeed);

  while (activeButton == 0) {
    stepper.runSpeed();
    int button;
    readKey = analogRead(0);
    if (readKey < 790) {
      delay(100);
      readKey = analogRead(0);
    }
    button = evaluateButton(readKey);
    switch (button) {
      case 4:  // This case will execute if the "back" button is pressed
        button = 0;
        activeButton = 1;
        break;
    }
  }
}

void menuItem2() { // Function executes when you select the 2nd item from main menu
  int activeButton = 0;

  lcd.clear();
  lcd.setCursor(3, 0);
  lcd.print("resetting");
  long stepSpeed = -1000;
  stepper.setSpeed(stepSpeed);

  while (activeButton == 0) {
    stepper.runSpeed();
    int button;
    readKey = analogRead(0);
    if (readKey < 790) {
      delay(100);
      readKey = analogRead(0);
    }
    button = evaluateButton(readKey);
    switch (button) {
      case 4:  // This case will execute if the "back" button is pressed
        button = 0;
        activeButton = 1;
        break;
    }
  }
}

A: Looking at the AccelStepper API, the first parameter for the constructor is the motor type. You have specified "1" which means DRIVER.  In this case, the enum for DRIVER says "Stepper Driver, 2 driver pins required."  and the constructor description says "AccelStepper::DRIVER (1) means a stepper driver (with Step and Direction pins). If an enable line is also needed, call setEnablePin() after construction."
So my conclusion is that you're probably setting up the stepper incorrectly. Unless the documentation I linked to is wrong, you are incorrectly passing the enable pin as a parameter to the constructor.


text:
Q: On 10.04, should I upgrade from Python 2.6.5 to 2.6.6? The default Python version on Ubuntu 10.04 server edition is 2.6.5.  The latest version of the Python 2.6 series is 2.6.6.  Does Ubuntu support 2.6.6 or should I leave it at the default version.  If I can upgrade the version, what's the corresponding apt-get command to upgrade the Python?

A: if Ubuntu will support to Python 2.6.6 when you run:
apt-get update

and then:
apt-get upgrade

automatically youll see the new version of python to upgrade, meanwhile you can keep the version 2.6.5...
cheers!!


text:
Q: Invalid CSS Styles in Safari on Mac I developing on Next.js.
The problem is happening on the GridInput component that included two components.
At first, it styled correctly while I'm developing on Chrome until I open my website on Safari that notice me the problem.
I tried to check <!doctype HTML> and restart server already.
GridInput:
let error = '';
let data = '';

if (this.state.error.length) {
   error = (

         <button className={style.error_btn} onClick={this.handleErrorClick}>X</button>

            {this.state.error.map((err, i) =>
{err}
)}

   )
} else {
   error = ''
}

if (this.state.data?.length) {
   data = this.state.data.map(data => (
      <GridBody
         key={data}
         data={data}
         editable={this.props.isContentEditable}
         info={this.state.info.hasOwnProperty(data) ? this.state.info[data] : '-'}
         onClick={this.handleDelete.bind(undefined, data)}
         onEditClick={this.handleEditClick.bind(undefined, data)}
      />
   ))
} else {
   data = ''
}

   <button title="Clear data" className={style.reset_btn} onClick={this.handleResetClick}>X</button>
      <GridHeader
         title={this.props.title}
         subTitle={this.props.subTitle}
      />
   <form className={style.form} onSubmit={this.handleSubmit} autoComplete="off">
      <input
         type="text"
         name="name"
         className={style.input}
         onKeyDown={this.handleInputKeyDown}
         onChange={this.onChange}
         value={this.state.name}
         disabled={this.state.type === 'edit' ? true : false}
         ref={this.inputRef}
      />

         {
            this.props.isInfoRequired && (optional)
         }

     <input type="submit" className={style.input} />
   </form>
   {error}
   {data}

GridInput.module.css:
.settings {
    display: flex;
    flex-direction: column;
    position: relative;

    margin-bottom: 2rem;
}

.form {
    display: grid;
    grid-template-columns: 70% 20% 10%;
    align-items: stretch;
    justify-items: center;
    width: 100%;
    min-height: 3rem;
    background: #1f1f23;
}

.input {
    width: 100%;
    height: 100%;
    background: #1f1f23;
    border-top: 3px solid #2b2c31fb;
    border-right: 3px solid #2b2c31fb;
    text-align: center;
    position: relative;
    font-size: 1rem;
}
.optional {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    color: rgb(177, 177, 177);
}
.input_info {
    width: 100%;
    padding: 1rem;
    background: #1f1f23;
    overflow: visible;
}
.input_info:focus {
    outline: none;
}
input.input:last-of-type {
    border-right: none;
}
.error_container {
    background: #1f1f23;
    padding: 1rem 0;
    /* margin-top: 10px; */
    border-top: 3px solid #2b2c31fb;
    position: relative;
}
.error_btn {
    background: transparent;

    position: absolute;
    top: 0.25rem;
    right: 0.25rem;

    width: 2rem;
    height: 2rem;
}
.error_ul {
    margin: 0;
}
.error_li {
    margin: 0.25rem 0;
}
.reset_btn {
    color: #000;
    height: 2rem;
    width: 2rem;
    border: none;
    cursor: pointer;
    border-radius: 50%;
    position: absolute;
    top: 1.5rem;
    right: 2.5rem;
    transform: translate(50%, -50%);
}

GridHeader:

   {props.title}
   {props.subTitle}
   -

GridHeader.module.css:
.header {
    display: grid;
    grid-template-columns: 70% 20% 10%;
    align-items: stretch;
    justify-items: center;
    width: 100%;
    min-height: 3rem;
    background: #1f1f23;
}
.head {
    width: 100%;
    line-height: 3rem;
    text-align: center;
    border-right: 3px solid #2b2c31fb;
}
.head:last-of-type {
    border: none;
}

GridBody:

   {props.data}
   {props.info}
   <button className={style.body} onClick={props.onClick}>Delete</button>
   {props.editable ? <button className={style.edit} onClick={props.onEditClick}>Edit</button> : ''}

GridBody.module.css:
.container {
    display: grid;
    grid-template-columns: 70% 20% 10%;
    align-items: stretch;
    justify-items: center;
    width: 100%;
    min-height: 3rem;
    background: #1f1f23;
    position: relative;
}
.body {
    border-top: 3px solid #2b2c31fb;
    width: 100%;
    line-height: 3rem;
    text-align: center;
    border-right: 3px solid #2b2c31fb;

    font-size: 1rem;
    position: relative;
}
button.body {
    background: #1f1f23;
}
button.body:last-of-type {
    border-right: none;
}
.edit {
    width: 3rem;
    background: transparent;
    position: absolute;
    top: 50%;
    right: -4rem;
    transform: translateY(-50%);

    border: 1px solid #fff;
    border-radius: 10px;
}

FireFox:
Correct style
Chrome:
Correct style
Safari:
incorrect style
My sandbox


text:
Q: Terraform reports aws_instance created even though user_data failed How to control user_data return code (bash script) while running terraform apply command.
I am running the standard terraform apply command to create an aws_instance. The resource definition includes user_data (bash script). The terraform log content is telling me
'aws_instance.xyz: Creation complete after 54s (ID: i-04de6d5dfd569cbd7)...',
'Apply complete! Resources......'

even despite the fact that bash script failed. What is the 'state of the art' procedure to catch this problem? I mean, as long as the user_data script doesn't succeed, the instance can not be considered as successful 'created' and completed in green color.


text:
Q: Permission denied (publickey) Google Cloud ssh-copy-id root@34.71.159.89
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@34.71.159.89: Permission denied (publickey).
qaisarmughal69@lamp-upwork-1:~/.ssh$
I have a server public key i have to add it to my cloud VM and im not able to authenticate it after via command ssh root@34.71.159.89

A: I'm not sure to fully understand your problem since their isn't any proper formatting to your question, but I think the problem is that you're not prompted for root's password, hence the Permission denied (publickey) error.
This might be related to the possibility of Cloud Engine's VMs having the SSH option PasswordAuthentication set to no by default, but I'm not sure.
One way to authorize your SSH key would be to go in Google Cloud UI and then from the menu Compute Engine > Metadata add your public SSH key.
Another way would be to use Cloud Shell which should be able to connect via SSH to the VM. And then from there you could add your key manually by editing /root/.ssh/authorized_keys.


text:
Q: One to Many bidirectional relationship not working in in memory HSQL DB I have a one to many mapping between city and people. One City can have many People.
After persisting data, on fetching the People object from hibernate  i m getting the city object also.City is the parent table/entity.
But on fetching the  city object using hibernate , the people object(set or list) is empty. The same code when tried against a MYSQL DB works fine. But while using HSQL in memory DB, i am facing the issue.
PFB the details:-
City entity:-
@Entity
@Table(name="CITY")
public class City {
    @Id
    @GeneratedValue
    @Column(name="CITY_ID")
    private long id;
    @Column(name="CITY_NAME", nullable=false, unique= true)
    private String name;

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "city" )
    private Set<People> people = new HashSet<People>(0);

The People Entity:-
@Entity
@Table(name="People")
public class People {
    @Id
    @GeneratedValue
    @Column(name="People_ID")
    private long id;
    @Column(name="People_NAME", nullable=false, unique= true)
    private String name;
    @ManyToOne
    @JoinColumn(name = "CITY_ID")
    City city;

I will insert values to City table first.Example values:-("London")..and after persisting if teh generated cityid is "1001"
Then will insert values to people table.Example values:-("John",1001)
Then on fetching the values for City object using hibernate , the people(set) is empty.
But if i fetch the values for People object, the city object has values.
PFb my xml file:-
<bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
            <property name="url" value="jdbc:hsqldb:TEST" />
            <property name="username" value="sa" />
            <property name="password" value="" />
        </bean>
        <bean id="sessionFactory"                class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
            <property name="dataSource" ref="dataSource" />
            <property name="packagesToScan" value="entity" />
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">org.hibernate.dialect.HSQLDialect</prop>
                    <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
                    <prop key="hibernate.show_sql">true</prop>
                </props>
            </property>
        </bean>

        <bean id="transactionManager"
            class="org.springframework.orm.hibernate3.HibernateTransactionManager">
            <property name="sessionFactory" ref="sessionFactory" />
        </bean>
        <tx:annotation-driven transaction-manager="transactionManager" />
    </beans>

Is it a limitation of the in memory DB, or am i missing anything.
Any suggestions or link will be helpful

A: I recently created a sample app to demonstrate this kind of relationship using hibernate, following is the code for that.
@Entity
@Table(name = "COMPANY")
public class Company {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Column(name = "COMP_NAME", length = 1000)
    private String companyName;
    @Column(name = "COMP_ADDRESS", length = 1000)
    private String companyAddress;
    @OneToOne(mappedBy = "company")
    private Employee emp;

    @OneToMany
    private Set<Department> departments = new HashSet<Department>();

    public Set<Department> getDepartments() {
        return departments;
    }

    public void setDepartments(Set<Department> departments) {
        this.departments = departments;
    }

Following is my Department.java
@Entity
@Table(name = "DEPARTMENT")
public class Department {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String deptName;
    @ManyToOne
    private Company company;

    public Company getCompany() {
        return company;
    }

    public void setCompany(Company company) {
        this.company = company;
    }

See that I didn't use @JoinColumn and this resulted in the creation of a relationship table, just remove @JoinColumn from your People class and you will get the collection of people from your City class.

A: Check the transactions should be committed for all inserts before you select, and make sure the entities get flushed/cleared in the current context before you fetch, some times hibernate might be returning you the same entities which are not detached from the current persistence context, hope this helps!!


text:
Q: Does changing f(mystruct *a) to f(const mystruct *a) breaks API/ABI in C? 1: void f(mystruct *a)
2: void f(const mystruct *a)

Does changing the function signature from 1->2 break API/ABI in C?
How about changing 2->1?

A: From C99 standard 6.2.5/26 "Types":

pointers to qualified or unqualified versions of compatible types shall have the same representation and alignment requirements.

So the ABI/API should not be affected going from 1 to 2. (The API doesn't change because a pointer to a non-const-qualified type may be converted to a pointer to a const-qualified version of the type  - 6.3.2.3/2 "Conversions - Pointers").
However, if you go from 2 to 1, then the API changes because a pointer to a const object cannot be implicitly converted to a pointer to a non-const object. The following code would compile under version 2, but would not compile under version 1:
static const mystruct foo;

f(&foo);

A: Other than stated in the two previous answers going from 1->2 may or may not break the API. This depends on the base type mystruct. The API would break if other than what the name indicates mystruct would be a typedef to an array type.
typedef struct toto mystruct[1];

For such a beast
mystruct A;
f(&A);

the call to f would be valid before the API change but invalid afterwards.

A: It depends on what you mean by API.  At compile-time, a T * may always be implicitly converted to a const T * (Note: apart from the exception that Jens Gustedt has pointed out in his answer!).  The inverse is not true; a const T * won't be implicitly converted to a T *, so a cast is always required in order to avoid a compiler error.  So if you change the declaration of an interface function from const to non-const, then none of your client code will compile.  (You can get round this simply by casting away the const-ness in all calls, but doing so should be avoided unless absolutely unavoidable, as the behaviour is undefined, and it means that you've broken your own interface's contract).
At the bit level (i.e. the ABI), there will be no difference between the representations of your pointers or objects.  However, that's not to say that the compiler won't have made optimisation/assumptions based on something being marked const when generated machine code the handles these representations; if you cast away the const-ness, these assumptions may no longer hold, and the code will break.

A: As far as the ABI is concerned, no, the const only influences errors during compilation stage. Compiled object files should have no remnants of const specifiers.

A: OLD: void f(mystruct *a)
NEW: void f(const mystruct *a)

ABI: If a was an out-parameter, then old apps may be broken.
API: Seems to be compatible.
OLD: void f(const mystruct *a)
NEW: void f(mystruct *a)

ABI: The function f may try to change a parameter value, that supposed to be unchanged by old apps.
API: Compiler error.
EDIT (1): This is an example to show a compiler error than changing the parameter to be non-const:
library header.h:
struct mystruct {
    int f;
};
void f(struct mystruct *a);

application:
int main()
{
    const struct mystruct x = {1};
    f(&x);
    return 0;
}

compiler error (gcc -Werror app.c):
error: passing argument 1 of 'f' discards qualifiers from pointer target type
note: expected 'struct mystruct *' but argument is of type 'const struct mystruct *'

It's really a warning in C by default, but an error in C++. So, you will break C-based apps compiled with -Werror option and C++-based apps compiled using G++.


text:
Q: Spin and SO groups associated to a degenerate symmetric bilinear form In "Spin geometry" by Lawson and Michelsohn it is defined the Clifford algebra $Cl(g)$ associated to a symmetric bilinear form $g$ in general, including the degenerate case. But the rest of the book is devoted exclusively to the non-degenerate case.
Are there any references concerned with the spin group $Spin(g)$, the group $SO(g)$, their representations, corresponding to a degenerate symmetric bilinear form $g$?

A: Some naive comments. Any real vector space $V$ with a symmetric bilinear form $g$ admits an orthogonal direct sum decomposition $V_0 \oplus V_1$ where $V_0$ consists of the vectors $v$ such that $g(v, -) = 0$ and $g$ is nondegenerate on $V_1$ (e.g. by the spectral theorem). An inspection of the defining relation
$$\frac{uv + vu}{2} = g(u, v)$$
of the Clifford algebra shows that $\text{Cl}(V,  g)$ is the (graded) tensor product $\Lambda(V_0) \otimes \text{Cl}(V_1, g)$. So this is not too bad.
The corresponding special orthogonal group is more complicated; $\text{SO}(g)$ consists of block matrices
$$\left[ \begin{array}{cc} A & B \\\ 0 & C \end{array} \right]$$
where $A \in \text{GL}(V_0), C \in \text{O}(V_1, g)$, $B$ is an arbitrary linear map $V_1 \to V_0$, and $\det(A) \det(C) = 1$. This does not seem like a very nice group to work with and I have no comment on what the corresponding spin groups might look like.


text:
Q: SpringBoot 1.5.10.RELEASE: REST service keeps geting 404 I'm seeing dozens of similar posts but none of the proposed solutions worked for me. I have a WAR with the following structure:
The folder "controller" contains a REST controller having the following code:
@RestController
@RequestMapping("/api")
public class HmlRestController
{
  ...........
  @RequestMapping(value = "/myResource/", method = RequestMethod.POST)
  public ResponseEntity<?> myResource(@RequestBody HmlEvent hmlEvent)
  {
    ..........
  }
}

The application.properties file has the following entry:
server.context-path=/hml

Running the WAR in Tomcat embedded and going to localhost:8080/hml displays the index.html file but trying to POST to localhost:8080/hml/api/myResource returns HTTP 404.
If I move this code into the HmlApplication class, like this:
@SpringBootApplication
@RestController
@RequestMapping("/api")
public class HmlApplication
{
  public static void main(String[] args)
  {
    SpringApplication.run(HmlApplication.class, args);
  }

  @RequestMapping(value = "/myResource/", method = RequestMethod.POST)
  public ResponseEntity<?> myResource(@RequestBody HmlEvent hmlEvent)
  {
    ..........
  }`enter code here`
}

then it works as expected.
Could someone please shed some lights here and let me know what is going on here ?
Many thanks in advance,
Nicolas

A: By using Spring Boot and its @SpringBootApplication, you automatically enable component scanning (see @ComponentScan on the @SpringBootApplication annotation).
You didn't mention your package structure, but your other package hierarchies should be below your main app with the @SpringBootApplication annotation, HmlApplication in your case.
You can add packages explicitly by adding an extra @ComponentScan annotation to your application class.
@ComponentScan("my.package")
@SpringBootApplication
public class HmlApplication {

A: I don't know exactly what happened but restarting everything solved the issue. The only thing I could think at is that, during the IntelliJ session, some message saying something about several Spring contexts has been displayed and I choose the default action. But I'm not any more sure. So for now, I'm closing this issue.
Kind regards,
Nicolas


text:
Q: Stuck on question regarding Cantor's theorem and sets I'm trying to prove that a set of all sets does not exist, meaning that the following does not exist:
$$
    D = \{ S \mid S \text{ is a set} \}
$$
I can use Cantor's Theorem and the proof of cardinality of sets which says that if $A⊆B$ then $A≤B$.  But I'm stuck with where to go next.

A: If there were a set $D$ containing every set $S$ as an element, consider the power set $P(D)$.  The elements of $P(D)$ are subsets of $D$, so in particular they are sets, so we must have $P(D) \subseteq D$.  Why does this contradict Cantor's Theorem?
One more technical push: if $\iota: A \hookrightarrow B$ is an injection of nonempty sets, then there is a surjection $s: B \rightarrow A$.  To define $s$, let $a_0 \in A$.  Then for $b \in B$, if $b$ lies in the image $\iota(A)$ then we must have $b = \iota(a)$ for a unique $a$, and we set $\sigma(b) = a$.  If $b$ does not lie in $\iota(A)$, we set $\sigma(b) = a_0$.  (For the cognoscenti: this does not use the Axiom of Choice.  The converse does.)

A: Since you seem to have an "is a set" predicate, I assume you are not using standard ZFC set theory. Not a problem. I also assume you are not necessarily prohibiting set self-membership. Much easier then, without using Cantor's theorem or cardinality, is to first assume to the contrary the existence of your $D$. Then select the subset $R$  of $D$ consisting of those and only those sets are that are not elements of themselves. This leads to the well known contradiction from Russell's Paradox since $R$, the so-called Russell Set, would also itself be a set. So, $D$, as defined here, cannot exist.


text:
Q: How to set Facebook Access (from server) in JavasScript SDK If I am using the server side flow to authenticate a user and acquire an access token, how can I set that access token in the JavaScript SDK and use it to make calls from the client side?

A: Once the user has finished the server side authentication flow the user is already authorized for your app, all you need to do is to use the FB.getLoginStatus method:
FB.getLoginStatus(function(response) {
    if (response.status === "connected") {
        console.log("authResponse: ", response.authResponse);
        FB.api("me", function(response2) {
            console.log("Hey there " + response2.name);
        });
    }
    else if (response.status === "not_authorized") {
        // user is logged in to facebook but hasn't authorized your app, should not happen if he went through the server side authentication
    }
    else {
        // user is logged out of facebook, also should not happen
    }
}

As you can see you can simply use the js sdk to query the graph, there's no need to get the token manually, but in case you still need it, the authResponse should have the following format:
authResponse: {
    accessToken: "aaaaaaa",
    expiresIn: "bbbbbb",
    signedRequest: "cccccc",
    userID: "dddddd"
}

Edit
If the user is logged into facebook and has allowed and interacted with your app then yes the getLoginStatus should return a valid access token.
There are a few cases in which this is not the case, one of them being that the token has expired.
As it states in the Handling Invalid and Expired Access Tokens:

Desktop Web and Mobile Web apps which implement authentication with the Javascript SDK
Calling FB.getLoginStatus() or ensuring status: true is set when you
  call FB.init() means that the next time a user lands on your
  application and is signed into Facebook, the authResponse object you
  are passed as a result of those calls will contain a fresh, valid
  access token.
In this case, its simply the act of the user using your application
  which implicitly generates a new access token.


text:
Q: Animated textView change the text and animate again (animated countdown) I am trying to make an animated countdown on android plataform, that show de number 3 in textView growing up from 0 to 1.5 on scale property, so the number 2, 1 and "GO!".
I'm using a textView, an Animation and an AnimationListener, but the animation doesn't work as I want, it works just in first animation showing number 3, so it shows the word "go!"   without animating.
What am I doing wrong?
Thanks!
Here the View counter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_height="fill_parent"

android:layout_width="fill_parent" android:gravity="center_vertical|center_horizontal">

    <TextView
        android:id="@+id/txtCount"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="3" android:textColor="#ffffff" android:textSize="150dp"/>

</LinearLayout>

<?xml version="1.0" encoding="UTF-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:interpolator="@android:anim/linear_interpolator"
        android:fromXScale="0"
        android:toXScale="1.5"
        android:fromYScale="0"
        android:toYScale="1.5"
        android:fillAfter="false"
        android:duration="1000" />
</set>

My code:
public class AdivinhacaoActivity extends Activity {

...

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    //async task
    new loaderImages(this).execute();
}

private class loaderImages extends AsyncTask<Void, String, Bitmap[]> {

    Activity activity;
    public loaderImages(Activity act){
        activity = act;
    }

    protected Bitmap[] doInBackground(Void... arg0) {

        ...

        return list;
    }

...
    int countCounter;
    protected void onPostExecute(Bitmap[] imagens){
        bmps = imagens;
        carregaContagem();
        final Animation anima = AnimationUtils.loadAnimation(activity, R.anim.counter);

        countCounter = 3;

        anima.setAnimationListener(new AnimationListener() {

                    public void onAnimationStart(Animation anim){};
                    public void onAnimationRepeat(Animation anim){};

                    public void onAnimationEnd(Animation anim)
                    {
                //here I tried txtCount.clearAnimation() but it doesn't work
                        countCounter--;
                        if(countCounter >= 0){
                    //change the text
                            if(countCounter > 0){
                                txtCount.setText("" + countCounter);
                            }
                            else{
                                txtCount.setText("GO!");
                            }
                    //start animation again with text changed
                            txtCount.startAnimation(anim);
                        }
                        else{
                            ...
                        }
                    };
                });

        //start animation first time
        txtCount.startAnimation(anima);

        }

    }

}

A: I managed solve my problem, using one textView and one animation instance for each count, yes it works, but I couldn't understand why reason my original solution didn't work!


text:
Q: Why is the text ignored by Mysql? I have a problem with my PHP code. The problem lies in $_GET['id']. As you can see, I output the resultset of a user that matched with the user id.
The Question is, why do I get the same result (resultset of user with id 1) when I enter two different values on the url?
URL 1:
URL2:
Shouldn't the text (randomtext) be taken in consideration, because the code seems to ignore it.
<?php

    try {
        $db = new PDO('mysql:host=127.0.0.1;dbname=ptp', 'root', 'root');
        $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {

    }
    $id = $_GET['id'];
    $sql = "SELECT * FROM users WHERE id = :id";

    echo $id . '<br/>';

    $query = $db->prepare($sql);

    $query->bindParam(':id', $id);
    $query->execute();

        while($r = $query->fetch(PDO::FETCH_ASSOC)) {
            print_r($r);
        }

    ?>

A: Just like PHP, MySQL will cast the string "1random" to int 1. So if your id field is a number, the query will be seen as "SELECT * FROM users WHERE id = 1" even if there is some random text after the 1
just try this in PHP : var_dump('1dfg' == 1) it will return true. it's the same in MySQL.
However, if you try to find a user with id "dfg1", nothing will be returned because this string can't be casted as an int.


text:
Q: Linear Programming One cake requires $150$gm flour and $50$gm fat and other requires $75$gm flour and $75$ gm fat. Amara wants to make as many cakes as possible when $1.5$kg flour and $0.6$kg fat are available. How many of each kind should she make?
My Attempt:
Let $x$ be the number of cakes of the first kind and $y$ be the number of second kind.
First Case;:
$$2x+y\leq 20$$
Second case;:
$$2x+3y\leq 24$$..
But whats next?

A: If you first take the number from the exercise the constraints are
$150x+75y\leq 1500$
$50x+75y\leq 600$
The first constraint can be divided by 75 and the second constraint can be divided by 25. And we get your form of the constraints.
If we have no other information we can assume the two cakes have the same utility (consumer) or the same price. In this case the coefficients of x and y have to be equal at the objective function. Let´s take 1 as the coefficient for both cakes.
$\texttt{max} \ \ x+y$
And finally x and y have to be non-negative whole numbers. To make the calculation more simple we just say x and y have to be non-negative numbers.
$x,y \geq 0$
Your definition of x and y is fine.
Remark:
This problem has only 2 variables. Therefore it can be solved graphically.


text:
Q: UITabBar in a UIViewController with transition I have no clue on how to approach this.
This is my initial view embedded in  HomeViewController:

I would like on first tab tap to have the post creation view to pop from the bottom

Then I would like to be able to switch from one tab to another like in a UITabViewController. I have been stuck on this for hours. Does anyone has an idea on how to perform this?
At the moment I add NewPostViewController.view as a subview of HomeViewController :
    NewPostViewController *someController = [[NewPostViewController alloc] init];
    someController.view.frame = CGRectMake(0, 568, 320, 568);

    [self.view addSubview:someController.view];
    [UIView animateWithDuration:0.3
                 animations:^{
                     someController.view.frame = CGRectMake(0, 0, 320, 568);
                 }];

and then add buttons to switch between views. Here is an example of one tab button :
    UIButton *Tab = [[UIButton alloc] initWithFrame:CGRectMake(0, 60, 320, 20)];
    [Tab setTitle:@"Done" forState:UIControlStateNormal];
    [Tab addTarget:self
         action:@selector(done)
   forControlEvents:UIControlEventTouchUpInside];
   [self.view addSubview:Tab];

but I get a "unrecognized selector sent to instance" when I tap the button.


text:
Q: How to create Angular2 Modal Component WITHOUT Bootstrap and WITHOUT jQuery? All searches on this topic lead to importing existing components that depend on Bootstrap.
I don't want to use Bootstrap. I want my own simpler HTML markup and way less class names to remember and crowd an already-complicated markup.
I'm fairly comfortable with components, component lifecycle, services, templates, events, observables, and other Angular2 concepts, but I am only able to build an application with nested components whose "parent page" end up in <router-outlet>.
I feel that there may be some lesser-known concepts of Angular2 that most tutorials and even video courses don't address, that would allow me to achieve modal popups. I think I will have to somehow "hack" the DOM to insert some html at the root of the entire webpage so that I can absolutely position the modal. I don't want to use jQuery because it might violate Angular2's inner workings and principles. If possible, I want to know an Angular2-safe way to manipulate the DOM if I have to - I prefer not to chase DOM elements from component code.
I do not only want alert confirmations and prompts. I want to be able to put a form-component on the modal window that would allow the user to save something to the database or choose an item from a list.
I know I'm asking for a lot, but specifically:

*

*What html markup and CSS should my popup component have at a minimum? Ideally, I want to put a translucent cover over the entire page, and the actual modal on top of it. to ensure that users can't click outside that modal window.

*How, if absolutely required, would services and observables be used to pull this?

*Can I just include this modal component's markup (as defined in its @Component({}) decorator) on a host/parent component and open it?

*Ideally, on the host component's code, I want to be able to call something like selectRecordModal.onSelected(selectedItem => { .... }).onCancelled( () => { ... });

A: Have you considered using material design? If so they call their 'modals' just overlays as a more generic feature as they can be used for everything from menus to alerts.
Otherwise, you can easily do modals with mostly css and a simple onclick event for loading/closing. Infact you can do it with just css but with limited browser support.
Something like this:
http://drublic.github.io/css-modal/#!
Which even supports  ie8 (kind of)


text:
Q: Algorithm to find `balanced number` - the same number of even and odd dividers We define balanced number as number which has the same number of even and odd dividers e.g (2 and 6 are balanced numbers). I tried to do task for polish SPOJ however I always exceed time.
The task is to find the smallest balance number bigger than given on input.
There is example input:
2 (amount of data set)
1
2

and output should be:
2
6

This is my code:
import java.math.BigDecimal;
import java.util.Scanner;

public class Main {
    private static final BigDecimal TWO = new BigDecimal("2");

    public static void main(String[] args) throws java.lang.Exception {
        Scanner in = new Scanner(System.in);
        int numberOfAttempts = in.nextInt();
        for (int i = 0; i < numberOfAttempts; i++) {
            BigDecimal fromNumber = in.nextBigDecimal();
            findBalancedNumber(fromNumber);
        }
    }

    private static boolean isEven(BigDecimal number){
        if(number.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) != 0){
            return false;
        }
        return true;
    }

    private static void findBalancedNumber(BigDecimal fromNumber) {
        BigDecimal potentialBalancedNumber = fromNumber.add(BigDecimal.ONE);
        while (true) {
            int evenDivider = 0;
            int oddDivider = 1; //to not start from 1 as divisor, it's always odd and divide potentialBalancedNumber so can start checking divisors from 2
            if (isEven(potentialBalancedNumber)) {
                evenDivider = 1;
            } else {
                oddDivider++;
            }
            for (BigDecimal divider = TWO; (divider.compareTo(potentialBalancedNumber.divide(TWO)) == -1 || divider.compareTo(potentialBalancedNumber.divide(TWO)) == 0); divider = divider.add(BigDecimal.ONE)) {
                boolean isDivisor = potentialBalancedNumber.remainder(divider).compareTo(BigDecimal.ZERO) == 0;
                if(isDivisor){
                    boolean isEven = divider.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) == 0;
                    boolean isOdd = divider.remainder(new BigDecimal("2")).compareTo(BigDecimal.ZERO) != 0;
                    if (isDivisor && isEven) {
                        evenDivider++;
                    } else if (isDivisor && isOdd) {
                        oddDivider++;
                    }
                }
            }
            if (oddDivider == evenDivider) { //found balanced number
                System.out.println(potentialBalancedNumber);
                break;
            }
            potentialBalancedNumber = potentialBalancedNumber.add(BigDecimal.ONE);
        }
    }
}

It seems to work fine but is too slow. Can you please help to find way to optimize it, am I missing something?

A: As @MarkDickinson suggested, answer is:
private static void findBalancedNumberOptimized(BigDecimal fromNumber) { //2,6,10,14,18,22,26...
        if(fromNumber.compareTo(BigDecimal.ONE) == 0){
            System.out.println(2);
        }
        else {
            BigDecimal result = fromNumber.divide(new BigDecimal("4")).setScale(0, RoundingMode.HALF_UP).add(BigDecimal.ONE);
            result = (TWO.multiply(result).subtract(BigDecimal.ONE)).multiply(TWO); //2(2n-1)
            System.out.println(result);
        }
    }

and it's finally green, thanks Mark!


text:
Q: Fetch only the HTTP headers with coldfusion for a remote URL I have a function that parses urls given to it, and based on the content it finds on that page it decides to use open graph to make embeded videos show up, just display the title, etc.
I want to extend it to detect if a direct video file or music file has been provided as a URL.
I have no interest at all to download the entire contents of the file, but I do want just the headers first to see if it's an audio/mpg, text, html, etc.
Is there a way to get the http headers of a remote file/page without fetching all the content?
Using CFHTTP it will connect and give me the data I need, but it ties up processing time to download the rest of the content.
By knowing the header contents I can decide if I should try and download the entire page to parse it for the extra open graph data.

A: Try <cfhttp> with method="head"

HEAD: identical to the GET method, but
  the server does not send a message
  body in the response. Use this method
  for testing hypertext links for
  validity and accessibility,
  determining the type or modification
  time of a document, or determining the
  type of server.

http://help.adobe.com/en_US/ColdFusion/9.0/CFMLRef/WSc3ff6d0ea77859461172e0811cbec22c24-7ffc.html


text:
Q: cant insert user input from form submit into the database.empty row is adding my table name is events..my database name is admin_data.can help how to rectify it.
here is my php file:events.php .in table event_date and event_class was 0000 in table and other fields are empty in the row.

<title>Events</title>

<?php
if(isset($_POST['save']))
{
$dbhost = 'localhost';
$dbuser = 'admin';
$dbpass = 'admin@123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
  die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
   $Event_Title = addslashes ($_POST['Event_Title']);
   $Event_Date = addslashes ($_POST['Event_Date']);
   $Event_Description = addslashes ($_POST['Event_Description']);
   $Event_Class = addslashes ($_POST['Event_Class']);
}
else
{
   $Event_Title = $_POST['Event_Title'];
   $Event_Date = $_POST['Event_Date'];
   $Event_Description = $_POST['Event_Description'];
   $Event_Class = $_POST['Event_Class'];
}

   $Event_Date = $_POST['Event_Date'];

  $sql = "INSERT INTO events (Event_Title,Event_Date,Event_Description,Event_Class) VALUES ('$Event_Title','$Event_Date','$Event_Description','$Event_Class')";
mysql_select_db('admin_data');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
  die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}
else
{
?>
<!DOCTYPE HTML>

    <title>EVENTS</title>
    <link rel="stylesheet" type="text/css" href="css/events.css">

                <form method="post" action="<?php $_PHP_SELF ?>">
                            EVENT TITLE<input type="text" placeholder="EVENT TITLE" id="Event_Title">
                    EVENT DATE<input type="date" placeholder="EVENTS DATE" id="Event_Date">
                    EVENT DESCRIPTION<textarea name="Name" id="Event_Description" rows="8" cols="40"></textarea>
                    GRADE
                    <select class="Event_Class">
                        <option>KG1</option><option>KG2</option><option>A</option><option>B</option>
                        <option>C</option><option>D</option><option>E</option>
                        <option>F</option><option>G</option><option>H</option><option>I</option><option>J</option><option>K</option>
                    </select>
                    <input type="submit" ' name="save" id="save" value="Save">

                    <input type="reset" button onclick="javascript:eraseText() name="reset" id="reset" value="Reset">

        </form>

<?php
}
?>

here is my css code:events.php

     .layout
{
    height:600px;
    width:1300px;
    background-color:gray;
    position:relative;
}
.heading
{
    height:55px;
    width:1200px;
    position:relative;
    float:left;
    left:40px;
    background-color: white;
    top:10px;
    background-image: url("../images/logo.png");
    background-size: 300px;
}
.menu
{
    position:relative;
    float:left;
    height: 500px;
    width:500px;
    background-color:white;
    left: 140px;top:20px;
}
.img1
{
    background-image: url("../images/images.jpg");
    float: left;
    height: 192px;
    left: 63px;
    position: relative;
    top: 119px;
    width: 258px;
}
.Event_Title
{
    position: relative;
top: 0px;
left: 0px;
}
#Event_Title
{
    position: relative;
left: 15px;
}

.Event_Date
{
    position: relative;
top: 50px;
left: -255px;
}
#Event_Date
{
    position: relative;
top: 20px;
left: 110px;
}
.Event_Class
{
    top: -170px;
position: relative;
left: -50px;
}
.Event_Class1
{
    position: relative;
top: -169px;
left: -30px;
}
.Event_Description
{
    position: relative;
top: 180px;
left: -159px;
}
#Event_Description
{
    position: relative;
top: 180px;
left: 90px;
}

#save
{
    position: relative;
top: 216px;
left: 100px;
}
#reset
{
    position: relative;
float: left;

width: 60px;
left: 295px;
top: 216px;
}
.img2 {
background-image: url("../images/images (1).jpg");

float: left;
height: 192px;
left: 590px;
position: relative;
top: -120px;
width: 258px;
}

A: Rewrite your query like this...
$sql = "INSERT INTO events (`Event_Title`,`Event_Date`,`Event_Description`,`Event_Class`) VALUES ('$Event_Title','$Event_Date','$Event_Description','$Event_Class')";

Why it didn't work for you ?

*

*You had improper concatenations.

*You forgot to properly quote the variables.

*You forgot to add a comma between the variables.

Add the name attribute to all your fields...
EVENT DATE<input type="date" name="Event_Date"  placeholder="EVENTS DATE" id="Event_Date">
                                                               ^^^^^^^^^^^^^^^^^


text:
Q: Select fields from two tables based on availibility condition I want to create a view which will return fields based on condition: if data is available in table 1 retrieve data from table 1, else retrieve from table 2
Use case:
select name, age, date
from table 1
where date = x

If no data in table 1 is there for date=x, then
Select name, age, date
 from table 2 where date = x
The view should this.
Is there a wal to have (select *) inside a case statem t

A: Something like this
Select name, age, date from table 1 where date = x
Union All
Select name, age, date from table 2 where date = x
Where Not Exists (select 1 from table 1 where date = x)

A: I believe you are looking something like this. Below I have tried a re-runnable query which will fetch data from Table2 if Table1 has no rows.
CREATE TABLE TABLE1
(NAME VARCHAR(50), AGE INT, DATE1 DATE)

CREATE TABLE TABLE2
(NAME VARCHAR(50), AGE INT, DATE1 DATE)

INSERT INTO TABLE2 VALUES('NAME1', 10, '01-JAN-2017')

CREATE VIEW vw AS
SELECT NAME, AGE, DATE1 FROM TABLE1 WHERE DATE1 = '01-JAN-2017'--if condition
UNION
SELECT NAME, AGE, DATE1 FROM TABLE2 WHERE NOT EXISTS(SELECT 1 FROM TABLE1 WHERE DATE1 = '01-JAN-2017') -- else condition

Your View will give you result from Table2 when Table1 is empty
 SELECT * FROM vw;


text:
Q: html2canvas text-shadow and font-smoothing I use these two types of css attributes but they won't render at all with html2canvas.
text-shadow: -2px 0 #e0dedb, 0 2px #e0dedb, 2px 0 #e0dedb, 0 -2px #e0dedb;

-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;

I read that htmlcanvas can render a text-shadow if formatted this way though:
text-shadow: 2px 2px 2px #e0dedb;

But it's nowhere near the effect I need to achieve (I need a sharp stroke around my font while this is a blury shadow)
And the font-smoothing won't occur neither, so I get a very thick rendered font on all browsers that doesn't look like my font on the original webpage (well yes, it's the same one but super bold).
Is there any workaround in order to achieve these two results on the rendered image?


text:
Q: Проблемы запуска проекта с Maven Есть у меня проект, создал его в IDE, там же подключил библиотеки(guava и для записи CSV файлов), проект содержит ввод данных через args[ ]. Добавил начальные данные для компиляции(пути к файлам) - в IDE все работает, решил поставить проект на Maven, написал, подключил зависимости:
<?xml version="1.0" encoding="UTF-8"?>

<modelVersion>4.0.0</modelVersion>
<groupId>groupId</groupId>
<artifactId>Java</artifactId>
<version>12</version>
<packaging>jar</packaging>

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

<dependencies>
    <dependency>
        <groupId>com.opencsv</groupId>
        <artifactId>opencsv</artifactId>
        <version>3.3</version>
    </dependency>
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>23.0</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <mainClass>vasiuk.Main</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>8</source>
                <target>8</target>
            </configuration>
        </plugin>
    </plugins>
</build>

Запустил его через командную строку, построился jar,
но при открытие jara в строке (java -jar Project.jar argumen1 argument2) возникли пробелы:

понимаю что сложно без всего проекта сказать, но что может быть причиной данных ошибок, заранее Спасибо.

A: Вы прописали <addClasspath>true</addClasspath>, что добавляет параметр Class-Path в файл MANIFEST.MF, внутри вашего jar файла, с перечислением jar файлов ваших зависимостей. Но в той директории, из которой вы его запускаете, jar файлов ваших зависимостей нет и, судя по вашему pom.xml, их нет даже в директории target вашего проекта. Поэтому загрузчик классов не находит классы ваших зависимостей. У вас есть два способа решить эту проблему:
Способ 1:
Скопировать jar файлы зависимостей в ту же дирекеторию, что и ваш jar файл или в директорию lib рядом с ним:
<plugin>
    <artifactId>maven-dependency-plugin</artifactId>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>copy-dependencies</goal>
            </goals>
            <configuration>
                <outputDirectory>${project.build.directory}/lib</outputDirectory>
            </configuration>
        </execution>
    </executions>
</plugin>

Поскольку в этом примере указана директория lib, её нужно добавить как префикс к перечисляемому в Class-Path. Для этого пропишите в настройках <manifest> вашего maven-jar-plugin:
<classpathPrefix>lib/</classpathPrefix>

Когда вы будете запускать ваш jar, вы должны находиться в той же директории, в которой находится директория lib. Например в директории target.
Способ 2:
Cобрать jar файл, который будет содержать классы всех зависимостей внутри себя:
<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
    </configuration>
    <executions>
        <execution>
            <id>make-assembly</id>
            <phase>package</phase>
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>

При этом у вас будут создаваться два jar файла: один как и раньше и другой со всеми классами внутри и с jar-with-dependencies в своём имени.


text:
Q: Is "composition over inheritance" violating "dry principle"? For example, consider I have a class for other classes to extend:
public class LoginPage {
    public String userId;
    public String session;
    public boolean checkSessionValid() {
    }
}

and some subclasses:
public class HomePage extends LoginPage {

}

public class EditInfoPage extends LoginPage {

}

In fact, the subclass has not any methods to override, also I would not access the HomePage in generic way, i.e.: I would not do something like:
for (int i = 0; i < loginPages.length; i++) {
    loginPages[i].doSomething();
}

I just want to reuse the login page. But according to https://stackoverflow.com/a/53354, I should prefer composition here because I don't need the interface LoginPage, so I don't use inheritance here:
public class HomePage {
    public LoginPage loginPage;
}

public class EditInfoPage {
    public LoginPage loginPage;
}

but the problem comes here, at the new version, the code:
public LoginPage loginPage;

duplicates when a new class is added. And if LoginPage needs setter and getter, more codes need to be copied:
public LoginPage loginPage;

private LoginPage getLoginPage() {
    return this.loginPage;
}
private void setLoginPage(LoginPage loginPage) {
    this.loginPage = loginPage;
}

So my question is, is "composition over inheritance" violating "dry principle"?

A: Er wait you're concerned that repeating
public LoginPage loginPage;

in two places violates DRY? By that logic
int x;

can now only ever exist in one object in the entire code base. Bleh.
DRY is a good thing to keep in mind but come on. Besides
... extends LoginPage

is getting duplicated in your alternative so even being anal about DRY wont make sense of this.
Valid DRY concerns tend to focus on identical behavior needed in multiple places being defined in multiple places such that a need to change this behavior ends up requiring a change in multiple places. Make decisions in one place and you will only need to change them in one place. It doesn't mean only one object can ever hold a reference to your LoginPage.
DRY shouldn't be followed blindly. If you're duplicating because copy and paste is easier than thinking up a good method or class name then you're probably in the wrong.
But if you want to put the same code in a different place because that different place is subject to a different responsibility and is likely to need to change independently then it's probably wise to relax your enforcement of DRY and let this identical behavior have a different identity. It's the same kind of thinking that goes into forbidding magic numbers.
DRY isn't just about what the code looks like. It's about not spreading the details of an idea around with mindless repetition forcing maintainers to fix things using mindless repetition. It's when you try to tell yourself that the mindless repetition is just your convention that things are headed in a real bad way.
What I think you are really trying to complain about is called boilerplate code. Yes, using composition rather than inheritance demands boilerplate code. Nothing gets exposed for free, you have to write code that exposes it. With that boilerplate comes state flexibility, the ability to narrow the exposed interface, to give things different names that are appropriate for their level of abstraction, good ol indirection, and you're using what you're composed of from the outside, not the inside, so you're facing it's normal interface.
But yes, it's a lot of extra keyboard typing. As long as I can prevent the yo-yo problem of bouncing up and down an inheritance stack as I read the code it's worth it.
Now it's not that I refuse to ever use inheritance. One of my favorite uses is to give exceptions new names:
public class MyLoginPageWasNull extends NullPointerException{}

A: A common misunderstanding with the DRY principle is that it is somehow related to not repeating lines of code. The DRY principle is "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system". It's about knowledge, not code.
LoginPage knows about how to draw the page for logging in. If EditInfoPage knew how to do this then that would be a violation. Including LoginPage via composition is not in any way a violation of the DRY principle.
The DRY principle is perhaps the most misused principle in software engineering and it should always be thought of not as a principle for not duplicating code, but as a principle for not duplicating abstract domain knowledge. Actually, in many cases if you apply DRY correctly then you will be duplicating code, and this is not necessarily a bad thing.

A: Short answer: yes, it does - to some minor, acceptable degree.
At a first glance, inheritance sometimes can save you some lines of code, since it has the effect of saying "my reusing class will contain all the public methods and attributes in a 1:1 manner". So if there is a list of 10 methods in a component, one does not have to repeat them in code in the inherited class. When in a composition scenario 9 of those 10 methods should be exposed publicly through a reusing component, then one has to write down 9 delegating calls, and let the remaining one out, there is no way around this.
Why is this tolerable? Look at the methods which are replicated in a composition scenario - these methods are exclusively delegating calls to the interface of the component, so containing no real logic.
The heart of the DRY principle is to avoid having two places in code where the same logical rules are encoded - because when these logical rules change, in non-DRY code it is easy to adapt one of those place and forget about the other one, which introduces an error.
But since delegating calls don't contain logic, these are normally not subject of such a change, so not causing a real problem when "prefering composition over inheritance". And even if the interface of the component changes, which might induce formal changes at all classes using the component, in a compiled language the compiler will tell us when we forgot to change one of the callers.
A note to your example: I don't know how your HomePage and your EditInfoPage look like, but if they have login functionality, and a HomePage (or an EditInfoPage) is a LoginPage, then inheritance might be the correct tool here. A less debatable example, where composition will be the better tool in a more obvious manner, would probably make things clearer.
Assuming neither HomePage nor EditInfoPage are a LoginPage, and one wants to reuse the latter, as you wrote, than it is pretty likely that one requires only some parts of the LoginPage, not everything. If that is the case, a better approach than using composition in the shown way might be to

*

*extract the reusable part of LoginPage into a component of its own

*reuse that component in HomePage and EditInfoPage the same way it is used now inside LoginPage
That way, it will typically become much clearer why and when composition over inheritance is the right approach.


text:
Q: How do I keep a Google Map marker in the center of the map without lag? I'm trying to keep a marker in the center of the map when a user drags the camera.
I'm currently doing this by using an OnCameraChangeListener like so:
@Override
public void onCameraChange(CameraPosition position) {
    marker.setPosition(map.getCameraPosition().target);
}

My problem with this is lag. The marker flickers and doesn't stay in place perfectly until I stop dragging.
I'm assuming a better way of doing this is to add some sort of overlay over-top the map.
Any suggestions?

A: Yes. You are better of putting your MapFragment or MapView inside FrameLayout (or RelativeLayout) with another ImageView or anything else and setting its gravity to center.


text:
Q: Outlook plugin not loading after clicking mailto links I've created an Outlook 2007 AddIn that among other things has to perform some  actions when user creates a new email. I've hooked to proper events and everything works correctly in all but one case.
The problem is that if Outlook is not running and user clicks mailto URL then Outlook opens only one explorer where user can compose the email. The other parts of the app are not loaded at that time. The problem is that in this case my plugin is not loading so I cannot add my custom code there.
I'd like to know if there's a way to overcome this problem.
I see two possible solutions but I don't know if they are possible.

*

*Make plugin load on mailto links (one explorer mode). I suspected this would be provided out-of-the-box by VSTO but it's not. I couldn't find anything about that on MSDN nor MS Outlook Programming book.

*Change mailto URL handler on client machine to launch full Outlook (like you would click Outlook shortcut) instead of just one Explorer. This would load my plugin before opening email explorer and would probably work as I intended.

Does anyone knows if any of that solutions is possible? Or maybe you have another that might work.

A: I had the same problem too but with Outlook 2003. The reason for this behaviour is security. Imagine a user installs an evil addin by mistake, which answers to mailto links and therefore does some evil stuff...
In my case I have developed a workaround. Instead of using the mailto links, I have created an own link (it's a simple shell extension which can easily be created look here) which starts a little helper application. This helper applications starts Outlook in full mode ( Outlook.exe /recycle) after having a little check for the load behaviour value (must be set to "3").
This way you can start Outlook in fullmode in order to use your addin ;)


text:
Q: MAMP 6.7 How to stop web servers? MAMP 6.7 on MacOS 13.1 (Intel). Starting the servers works as expected and pages in the document root are displayed correctly from localhost:8888. After selecting "Stop" the icon begins to cycle between its Orange and Green states and the WebStart icon switches between dimmed and solid states.
Checking Activity Monitor, I can see that MAMP starts an httpd process (and its expected child processes). Selecting "Stop" does not stop these processes (bash processes and their child mysqld processes die and restart).
If the MAMP application is quit, the httpd process continues using the same PID that was reported while MAMP was active.
I've tried deleting and reinstalling MAMP. The problem persists. Restarting the machine kills the httpd process as expected but upon starting it in MAMP and attempting to stop, it continues to persist.


text: Q: Temporarily mount SMD 2x5 header for programming I can't mount the 2x5 header permanently on the PCB, so need a way to temporarily mount it to the solder pad the PCB already has for this 2x5 header. Soldering it would create a mess and is not a quick way to mount it. Any suggestions on what could be used to hold the header to the pads, use it for programming, and then take it off in a clean way once done using it. I saw some similar threads but they mostly talk about keeping the component in place to assist soldering, I am looking for an alternative to soldering to temporarily mount an SMD header component.


text:
Q: Why is rspec reporting the time with fractions? A somewhat lighthearted question:  My rspec tests end with:
Finished in 7/5 minutes 0.78322 seconds

What exactly does that mean?   It did feel approximately like 1-2 minutes, but why the fraction plus decimal seconds?

A: FWIW, it certainly looks like RSpec (or somebody) is calculating the number of minutes as a Rational instead of a normal Numeric. That's the only reason I can imagine you'd see a fractional value.


text:
Q: Custom Headers on Blog Posts Page So I have created my own template that has a set header for all of my pages home (which is a static front page), about, services, contact, etc....
I have recently created two newer pages products and blog.  Products is using CataBlog to list my products and their information so I don't want the same header that I have used on the content pages.  This also holds true for the blog page.
I went into my header.php file and did the following:
            <?php

            if (is_page('blog')) { ?>

hi

        <?php
            }

            if (is_page('product')) { ?>

hi

        <?php
            }

            else {?>

<img src="<?php bloginfo('stylesheet_directory') ?>/images/01.jpg" alt="Pawtucket Pawnbrokers" />

<img src="<?php bloginfo('stylesheet_directory') ?>/images/02.jpg" alt="We Buy Gold" />

<img src="<?php bloginfo('stylesheet_directory') ?>/images/03.jpg" alt="Need Cash?" />

<img src="<?php bloginfo('stylesheet_directory') ?>/images/04.jpg" alt="Instant Cash Loans" />

        <?php
            }

        ?>

Now, when I go to the blog page the header maintains that of the static pages however the header on the product page is changed to display "hi" as expected.  I changed the name blog in the is_page function to another of the static pages and received the desired result.  I am assuming this means somewhere in my template files that original header is being called to display on the blog page.  If this is true where should I look to make that change? If this is not the case what am I doing wrong?
Any help is always appreciated!

A: If the conditional works when using is_page( 'products' ), but does not work when using is_page( 'blog' ), then that means that WordPress isn't finding a static page with the slug blog. First thing to do: verify your slug name.
A second alternative is that the static page blog is using a custom page template, and that the custom page template is calling a different header file, resulting in the above code never getting executed. Are you using a custom page template for the static page blog? If so, you'll need to look at the custom page template file.
Edit
From your comment below:

i forgot to mention that as home is set as my static page in the admin panel the blog page is set as my blog page.

There's your answer. I should have picked up on it, but somehow didn't. Take a look at the Template Hierarchy. You're using the static page blog as your Blog Posts Index, Instead of using is_page( 'blog' ), you need to be using is_home(), which returns true when displaying the Blog Posts Index.


text:
Q: Custom editor in MPS I have an concept in Jetbrains MPS which I would like to create a custom editor for.
The concept have a number of children.
For each child I would like to display the child's own editor but with a "-" in front of it.
I'm not completely sure I'm trying to solve this in the right way.
But my first attempt is a custom cell looping over the child nodes.
My problem is that I can't figure out how to find the editor cell of the child nodes:
My cell provider:
return new AbstractCellProvider(node) {
@Override
public EditorCell createEditorCell(EditorContext ctx) {
  EditorCell_Collection cells = EditorCell_Collection.createVertical(ctx, node);
  foreach n in node.elements {
    EditorCell_Collection a = EditorCell_Collection.createHorizontal(ctx, node);
    EditorCell_Label label = new EditorCell_Constant(ctx, node, "-");
    a.addEditorCell(label);
    cells.addEditorCell(a);

       how to add the child node's editor here?

   }
return cells;
}

A: What are you really trying to achieve? An example might help here...
Without further context (so I may misunderstand your problem), I think you could use an EditorComponent (https://www.jetbrains.com/help/mps/editor.html#editorcomponentsandeditorcomponentcells) for the original editor and then make an editor with a "-" constant followed by the EditorComponent to achieve the desired effect.


text:
Q: Why is "plummet", as an intransitive verb, followed by a noun?
Consumer confidence plummeted a breathtaking 15 points, to its lowest level in ten years.

The cable just snapped. The elevator plummeted ten flights.

Stock prices plummeted 40 percent during the scandal.

What grammatic role do the bolded nouns play in the sentence?

A: They function adverbially. (Terminology will vary.) It is very common for nominal phrases to modify verbs this way (!), and neither the word "plummet" nor numbers need to be involved:

Consumer confidence rose Monday.
The elevator shook a great deal.
Stock prices have risen many times since the last recession.


text:
Q: How to create a readonly on the condition using html helper and using custom displayview in asp.net mvc? 1. for example i have next helper and i need set status readonly (or disabled)
@Html.TextBoxFor(model => model.RequestTypeAdditional, new { @class = "form-control",   @autocomplete = "off" , **readonly = IsReadOnly(Model.IsClosed)**  })

@functions
{
    private static string IsReadOnly( bool isClosed)
    {
        if (RoleHelpers.IsInRoles("Master"))
            return "readonly";
        else if (RoleHelpers.IsInRoles("Operator") && (!isClosed))
            return string.Empty;
        else if (RoleHelpers.IsInRoles("Operator") && (isClosed))
            return "readonly";
        else if (RoleHelpers.IsInRoles("Administrator"))
            return string.Empty;
        else
            return "readonly";
    }
}

2.  i have custom view for model :-
@Html.DisplayFor(model => model.RequestType, new { **@readonly = IsReadOnly(Model.IsClosed)** })

works only  if the readonly (or disabled) explicitly specified or not. custom helpers not suitable

A: Why can't you do this:
@if (IsReadOnly(Model.IsClosed))
{
@Html.TextBoxFor(model => model.RequestType, new { @readonly = "readonly" })
}
else
{
@Html.TextBoxFor(model => model.RequestType)
}

A: Do not try an brute force it. I agree you don't want your form code bloated with multiple repeating blocks.
I would recommend taking the code suggested by Sergey Shabanov above and placing it into display template. Then use a UIHint in our model to link to the display template. Presto, code complete with no bloat in your form code. You get to keep your DisplayFor and generally it resolves to a single line of UI code. Finally, you keep the implementation in a single location so changing it is not as error prone.

A: I also think this could be one of the best ways to implement your strongly-typed TextBox custom helper:
public static MvcHtmlString TextBoxFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>>expression, bool isReadonly, bool isAutocomplete)
{
    MvcHtmlString html = default(MvcHtmlString);
    if (isReadonly)
    {
        html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression, new { @class = "readOnly form-control", @autocomplete = isAutocomplete ? "on" : "off", @readonly = "read-only" });
    }
    else
    {
        html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression, new { @class = "readOnly form-control", @autocomplete = isAutocomplete ? "on" : "off" });
    }

    return html;
}


text:
Q: Auto-size data-grid of react-grid-layout I am using responsive react grid layout in a container where i have expandable/collapsible side bar. As of now when RGL is getting loaded with all its data-grid items, it looks perfect however when i expand/collapse sidebar (which changes the parent div size of the RGL), RGL items doesn't get resized automatically. its works perfect with window resize however not with container size change.
I have tried modifying height/width pragmatically which works then placeholder and drag/drop starts failing
Anyone have a quick solution for this


text:
Q: Rsync from NFS to remote server - not syncing files anymore I'm having some real issues trying to rsync a large amount of MP3 files (3.5TB worth) from an NFS mounted partition to a remote server using a Debian cloud based node. It appeared to sync a lot of files at first but now it's stopped syncing.
The directory is constantly updated with files so I know there will be files that should be synced. This is what happens whenever I try and sync:
root@node:/# rsync -Pav -e 'ssh -i /keyfile.pem' /nfs/src ubuntu@ec2:/dest
sending incremental file list
./

sent 2332901 bytes  received 75 bytes  15710.28 bytes/sec
total size is 529754905288  speedup is 227072.59

When usually it would show progress, it no longer shows any files being transferred. The newly updated files on the NFS mount can be accessed directly without problems.
I've updated rsync to the latest 3.1.2 but still no luck.


text:
Q: Laravel incorrect stored datetime into database on jpbs and queues simply after creating data into database i see wrong datatime as created_at and updated_at into phpMyAdmin,
i set Asia/tehran in laravel config/app file and my system date time is correct and updated and when i logging now() with carbon i get this output:
Carbon @1532117471 {#1179 ▼
  date: 2018-07-21 00:41:11.142496 Asia/Tehran (+04:30)
}

and this is correct with my system datetime, on database datetime for created_at and updated_at is: 2018-07-20 19:58:26
THIS PROBLEM HAPPENS WHEN I USE LARAVEL JOB-QUEUE
clock in this time is 00:41:11 not 19:58:26, how can i resolve this problem and fix that?

A: You're looking into created_at and updated_at of laravel. They are being used as timestamps of when it was created based of your larave's config/app timezone.
How can you change this?
Option 1. Go to config/app.php and change timezone to your desired one.
Option 2. Manage a model's created at with mutators.

https://laravel.com/docs/5.6/eloquent-mutators#defining-a-mutator

On your Eloquent Model, you simply create:
public function setCreatedAtAttribute($value) {
  /*
  $value is the value it is going to initially be stored
  This date format is required due to mySql's timestamp restriction.
  However, you can create a date with Carbon, and as long as you format into that
  structure Y-d-m H:i:s it will do just fine
  */
  $this->attributes['created_at'] = Date("Y-m-d H:i:s);
}

Note: In order to trigger this function, you're required to use Eloquent's Create, as in:
$data = ['some_field' => 'hi',
         'some_ther_field' => 'hiSomeOtherField'];
SomeModel::create($data);


text:
Q: Connecting Qt client to Thrift server? I've looked through the site and haven't found any guidance on connecting my QTcpSocket to my Thrift C++ server. This was the closest match, although the solutions proposed don't work.
Client code (Qt Quick Application):
QHostAddress addr {"104.236.6.118"};
quint16 port {9090};

QTcpSocket socket;
socket.connectToHost(addr, port);

if(socket.state() == QTcpSocket::ConnectedState)
{
    qDebug()<<"Connection accepted";
} else
{
    qDebug()<<"Connection failed";
}

Server code (Thrift C++):
class testerHandler : virtual public testerIf {
   public:
     testerHandler()
     {
        printf("Got an incoming connection....");
     }
};

int main()
{
   int port = 9090;
   shared_ptr<testerHandler> handler(new testerHandler());
   shared_ptr<TProcessor> processor(new testerProcessor(handler));
   shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
   shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory());
   shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
   TSimpleServer server(processor, serverTransport, transportFactory, protocolFactory);

   try
   {
      server.serve();
   }
   catch (...)
   {
     printf("ERROR");
   }
   return 0;
}

Does anyone have any experience or advice on connecting these?


text:
Q: How to catch constraint violation and give a user defined error message in PL/SQL? How can I provide a user defined error message in PL/SQL when a check constraint is violated?
      CREATE TABLE "AP"."SOURCE"
      (
        ,"RATING" CHAR(30 BYTE)
        ,"SUBMISSION_STATUS" CHAR(12 BYTE)
        ,"UOANAME" CHAR(32 BYTE)
        ,"W_INSERT_DT" TIMESTAMP (6)
        ,"W_UPDATE_DT" TIMESTAMP (6)
        ,"SCIVAL_CIT_CATEGORY" NUMBER(5,0)
        ,"TOTAL_AUTHORS" BINARY_DOUBLE
        ,"REF2014" CHAR(3 BYTE)
      CONSTRAINT "Submission_Rating_not_valid"
      CHECK ( Submission_status ='To be scored'
            and Rating is null
            or Submission_status ='NO'
            and Rating is null
            or Submission_status = 'Potential'
            and Rating is not null
            and Rating != 'Not REF Eligible'
            or  Submission_status ='Yes'
            and Rating is not null
            and Rating != 'Not REF Eligible'
            or  Submission_status ='No'
            and Rating is not null
            and Rating != 'Not REF Eligible'
            or  Submission_status ='No'
            and Rating = 'Not REF Eligible'*) ENABLE
       )

A: In PL/SQL there is a EXCEPTION keyword to handle the excpetions.
EXCEPTION

Then you can set inside the PL/SQL block what to do if the execution of PL/SQL code raise specific exception.
WHEN <name of the exception> THEN <statements to handle it>;

When you need a fallback for all nonmentioned exceptions, use OTHERS:
WHEN OTHERS THEN <statements to handle it>;

To raise a custom exception for the user with custom errortext, use RAISE_APPLICATION_ERROR.
Example:
CREATE OR REPLACE PROCEDURE "APEXDEV01"."ADD_OMT_SOURCE" (
  rating VARCHAR2,
  submission_status VARCHAR2,
  uoaname VARCHAR2,
  scival_cit_category NUMBER,
  total_authors BINARY_DOUBLE,
  selfselected VARCHAR2,
  ref2014 VARCHAR2)
AS
BEGIN
  INSERT INTO "APEXDEV01"."OMT_SOURCE" VALUES (
    rating, submission_status, uoaname, SYSDATE, SYSDATE,
    scival_cit_category, total_authors, selfselected, ref2014);
  EXCEPTION
    WHEN "Submission_Rating_not_valid" THEN
      RAISE_APPLICATION_ERROR(-20081, "Submission rating not valid");
    WHEN OTHERS THEN
      RAISE_APPLICATION_ERROR(-20086,sqlerrm);
END;
/

It is also worth mentioning that the condition in your DDL statement combines ANDs and ORs and those should be managed by some parentheses to aviod mess and confusion in its logic.

A: you need one parenthesis and use separate  parenthesis for and or condition
    CREATE TABLE "AP"."SOURCE"
 (

"RATING" CHAR(30 BYTE),

 "SUBMISSION_STATUS" CHAR(12 BYTE),

"UOANAME" CHAR(32 BYTE),

 "W_INSERT_DT" TIMESTAMP (6),

"W_UPDATE_DT" TIMESTAMP (6),

"SCIVAL_CIT_CATEGORY" NUMBER(5,0),

"TOTAL_AUTHORS" BINARY_DOUBLE,

"REF2014" CHAR(3 BYTE),

CONSTRAINT "Submission_Rating_not_valid"

CHECK ( (Submission_status ='To be scored' and Rating is null)  or

(Submission_status ='NO' and Rating is null )
     or ( Submission_status = 'Potential' and
       Rating is not null and Rating != 'Not REF Eligible')

or ( Submission_status ='Yes' and Rating  is not null
     and Rating != 'Not REF Eligible' )
  or ( Submission_status ='No'
  and Rating  is  not null and Rating != 'Not REF Eligible')
 or  (Submission_status ='No' and Rating = 'Not REF Eligible'
      ) ENABLE

   )
 )