text:
Q: 'DNN' object has no attribute 'fit_generator' in ImageDataGenerator() - keras - python Following code is developed for identify 5 image classes using keras and python with tensorflow backend. I have used imageDataGenerator but when I run this, it's started to train and after a while, following error occured.
How can I solve this?

Training Step: 127  | total loss: 0.01171 |
  time: 32.772s | Adam | epoch: 005 | loss: 0.01171 - acc: 0.9971 --
  iter: 1536/1550 Training Step: 128  | total loss: 0.01055 | time:
  36.283s | Adam | epoch: 005 | loss: 0.01055 - acc: 0.9974 | val_loss: 3.05709 - val_acc: 0.6500 -- iter: 1550/1550
  -- Found 0 images belonging to 0 classes. Found 0 images belonging to 0 classes. Traceback (most recent call last):
File "", line 1, in
      runfile('D:/My Projects/FinalProject_Vr_01.2/CNN_IMGDG_stackoverflow.py', wdir='D:/My
  Projects/FinalProject_Vr_01.2')
File
  "C:\Users\Asus\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py",
  line 704, in runfile
      execfile(filename, namespace)
File
  "C:\Users\Asus\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py",
  line 108, in execfile
      exec(compile(f.read(), filename, 'exec'), namespace)
File "D:/My
  Projects/FinalProject_Vr_01.2/CNN_IMGDG_stackoverflow.py", line 191,
  in
      model.fit_generator(train_generator,
AttributeError: 'DNN' object has no attribute 'fit_generator'

import cv2
import numpy as np
import os
from random import shuffle
from tqdm import tqdm
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential

TRAIN_DIR = 'train'
VALID_DIR = 'validate'
TEST_DIR = 'test'
IMG_SIZE = 128
LR = 1e-3
train_samples = 1500
valdate_samples = 250
epochs = 5
batch_size = 10

MODEL_NAME = 'snakes-{}-{}.model'.format(LR, '2conv-basic')

def label_img(img):
    print("\nImage = ",img)
    print("\n",img.split('.')[-2])
    temp_name= img.split('.')[-2]
    print("\n",temp_name[:1])
    temp_name=temp_name[:1]
    word_label = temp_name

    if word_label == 'A': return [0,0,0,0,1]
    elif word_label == 'B': return [0,0,0,1,0]
    elif word_label == 'C': return [0,0,1,0,0]
    elif word_label == 'D': return [0,1,0,0,0]
    elif word_label == 'E' : return [1,0,0,0,0]

def create_train_data():
    training_data = []
    for img in tqdm(os.listdir(TRAIN_DIR)):
        label = label_img(img)
        path = os.path.join(TRAIN_DIR,img)
        img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
        img = cv2.resize(img,(IMG_SIZE,IMG_SIZE))
        training_data.append([np.array(img),np.array(label)])
    shuffle(training_data)
    np.save('train_data.npy', training_data)
    return training_data

def create_validate_data():
    validating_data = []
    for img in tqdm(os.listdir(VALID_DIR)):
        label = label_img(img)
        path = os.path.join(VALID_DIR,img)
        img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
        img = cv2.resize(img,(IMG_SIZE,IMG_SIZE))
        validating_data.append([np.array(img),np.array(label)])
    shuffle(validating_data)
    np.save('validate_data.npy', validating_data)
    return validating_data

def process_test_data():
    testing_data = []
    for img in tqdm(os.listdir(TEST_DIR)):
        path = os.path.join(TEST_DIR,img)
        img_num = img.split('.')[0]
        img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
        img = cv2.resize(img,(IMG_SIZE,IMG_SIZE))
        testing_data.append([np.array(img), img_num])
    shuffle(testing_data)
    np.save('test_data.npy', testing_data)
    return testing_data

train_data = create_train_data()
validate_data = create_validate_data()

import tflearn
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.estimator import regression

import tensorflow as tf
tf.reset_default_graph()

convnet = input_data(shape=[None, IMG_SIZE, IMG_SIZE, 1], name='input')

convnet = conv_2d(convnet, 32, 5, activation='relu')
convnet = max_pool_2d(convnet, 5)

convnet = conv_2d(convnet, 64, 5, activation='relu')
convnet = max_pool_2d(convnet, 5)

convnet = conv_2d(convnet, 128, 5, activation='relu')
convnet = max_pool_2d(convnet, 5)

convnet = conv_2d(convnet, 64, 5, activation='relu')
convnet = max_pool_2d(convnet, 5)

convnet = conv_2d(convnet, 32, 5, activation='relu')
convnet = max_pool_2d(convnet, 5)

convnet = fully_connected(convnet, 1024, activation='relu')
convnet = dropout(convnet, 0.8)

convnet = fully_connected(convnet, 5, activation='softmax')
convnet = regression(convnet, optimizer='adam', learning_rate=LR, loss='categorical_crossentropy', name='targets')

model = tflearn.DNN(convnet, tensorboard_dir='log')

if os.path.exists('{}.meta'.format(MODEL_NAME)):
    model.load(MODEL_NAME)
    print('model loaded!')

train = train_data[:]
validate = validate_data[:]

X = np.array([i[0] for i in train]).reshape(-1,IMG_SIZE,IMG_SIZE,1)
Y = [i[1] for i in train]

validate_x = np.array([i[0] for i in validate]).reshape(-1,IMG_SIZE,IMG_SIZE,1)
validate_y = [i[1] for i in validate]

model.fit({'input': X}, {'targets': Y}, n_epoch=epochs, validation_set=({'input': validate_x}, {'targets': validate_y}),
    snapshot_step=500, show_metric=True, run_id=MODEL_NAME)

train_datagen = ImageDataGenerator(
    rescale=1. / 255,
    shear_range=0.2,
    zoom_range=0.2,
    horizontal_flip=True)

validation_datagen = ImageDataGenerator(rescale=1. / 255)

train_generator = train_datagen.flow_from_directory('train',
                                                    target_size=(IMG_SIZE, IMG_SIZE),
                                                    batch_size=batch_size,
                                                    class_mode='categorical')

validation_generator = validation_datagen.flow_from_directory('validate',
                                                        target_size=(IMG_SIZE, IMG_SIZE),
                                                        batch_size=batch_size,
                                                        class_mode='categorical')

model.fit_generator(train_generator,
                    steps_per_epoch=25,
                    epochs=epochs,
                    validation_data=validation_generator,
                    validation_steps=25)

model.save(MODEL_NAME)

A: Your model object is an instance of the tflearn.DNN class, which simply does not have a fit_generator method. This method is only available for keras objects. Maybe you could define your architecture in keras and you would be able to use your data generators.

A: When you defining your Neural Network you can use do it using the Keras. (What you have done here is defining the network using Tensorflow. It's not having fit_generator method.)
import keras
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.models import Sequential

These are the layers that you can use with Keras for your application. Then initialize your DNN with DNN = Sequential()
Refer this simple classifier written with Keras and you'll get the idea.

A: Other Opinion
If you want to see a Model and the ACC, lose
You need to use tensorboard
Example 1 : In Colab
load_ext tensorboard
tensorboard --logdir='/tmp/tflearn_logs'


text:
Q: Is there a faster way of assigning an image to lots of buttons? I have a Windows Forms Application that I need to assign an image to all 100 buttons, the problem is, that I need to do it randomly every time... Is there a faster way of doing this?
My first idea was to use the basic method of assigning that image to a variable and then assigning the image to the button:
Bitmap P_Farm = new Bitmap(@"IMAGE PATH.jpeg");

this.button1.Image = P_Farm;

But the problem with that is that I will need to do this for all 100 buttons.
this.button1.Image = P_Farm; // "P_Farm is just the path to the image"
this.button2.Image = P_Farm;
this.button3.Image = P_Farm;
this.button4.Image = P_Farm;

I want to keep my code as dry as possible.
The reason I can't just do it through the "Image" option in the "Properties" window is because eventually I will have a random image for every button on every load of the app. So first it will be
this.button1.Image = Z_Farm;
this.button2.Image = C_Farm;
this.button3.Image = P_Farm;
this.button4.Image = P_Farm;

then
this.button1.Image = P_Farm;
this.button2.Image = P_Farm;
this.button3.Image = Z_Farm;
this.button4.Image = Z_Farm;

I was wondering if it was possible to do something like reading every line in a text file but instead of the line changing with each try, the button changes
int i = 0;

while (true) // Something like this loop but changing not the line, but the button
{
    this.button[i].image = P_Farm; // this obviously doesn't work
    I++;
}

Hopefully this makes sense
Thanks a lot!

A: You can also loop through all the controls in your form, find the ones that are buttons and change their image that way. Of course you don't want to change them all. What I usually do is set a number to the Tag property:
        foreach (Control control in Controls)
        {
            if (control is Button theButton && (int)theButton.Tag == 5)
            {
                theButton.Image = P_Farm;
            }
        }

This will not work if you have panels with buttons that you want to change too. You will have to write a recursive function that involves all the possible containers in your form such as panels.
If you want to change all the buttons in a container like a panel you would only change your foreach line to something like foreach (Control control in panel.Controls).
In the future, when you decide that not all buttons will have the same image, you could set an image based on the tag property like this:
        foreach (Control control in Controls)
        {
            if (control is Button theButton && (int)theButton.Tag >= 5)
            {
                switch ((int) theButton.Tag)
                {
                    case 100:
                        theButton.Image = P_Farm;
                        break;
                    case 101:
                        theButton.Image = Z_Farm;
                        break;
                }
            }
        }

Because we are assuming that all buttons have an int in their tag property, you should add a number to all buttons, including those that should not change like your Cancel and Ok buttons. Something like a zero to exclude them from the image assignement.
I'm sure that there are better ways. I haven't done WinForms in a while.

redpajama_set_name: RedPajamaStackExchange


text:
Q: StaleStateException when changing id in nhibernate Very new to NHibernate so I expect there will be a quick fix here.
The code I'm looking at has an unorthodox design.
public class Partner
{
    public virtual int Id { get; set;} //note the set is not private
    public virtual String Name { get; set;}
}

and is mapped with FluentNhibernate's Automappings
When Partner is created its Id is 0 but when
I call Flush to persist to the db:
        CurrentSession.SaveOrUpdate(obj);
        CurrentSession.Flush();

I get a  Unexpected row count: 0; expected: 1 StaleStateException
I'm assuming its because NHibernate doesn't like me changing the Primary Key, Id.
In this case I need to. How can I configure NH to let me achieve this abomination?

A: You can do the update with HQL:
session.CreateQuery("update Partner set Id = :newId where Id = :oldId")
       .SetParameter("newId", newId)
       .SetParameter("oldId", oldId)
       .ExecuteUpdate();

I suggest that you Evict the entity from the session, or use a stateless one if you are going to update the Id.


text:
Q: how to limit the number of datas in word I am exporting data from php page to word,, there i get 'n' number of datas in each page ....
How to set the maximum number of data that a word page can contain ,,,,
I want only 20 datas in a single page
This is the coding i use to export the  data to word
In mysql_table.php the table for the pdf document is be generated
<?php
require('mysql_table.php');

class PDF extends PDF_MySQL_Table
{
function Header()
{
    //Title
    $this->SetFont('Arial','',18);
    $this->Cell(0,6,'Country details',0,1,'C');
    $this->Ln(10);
    parent::Header();
}
}

//Connect to database
mysql_connect('localhost','root','');
mysql_select_db('cms');

$pdf=new PDF();
$pdf->AddPage();
//First table: put all columns automatically
$pdf->Table("SELECT
                (SELECT COUNT(*) FROM tblentercountry t2 WHERE t2.dbName <= t1.dbName and dbIsDelete='0')
                AS SLNO ,dbName as Namee,t3.dbCountry as Country,t4.dbState as State,t5.dbTown as Town
                FROM tblentercountry t1
                join tablecountry as t3,
                tablestate as t4,
                tabletown as t5
                where t1.dbIsDelete='0'
                and t1.dbCountryId=t3.dbCountryId
                and t1.dbStateId=t4.dbStateId
                and t1.dbTownId=t5.dbTownId
                order by dbName");
$pdf->AddPage();
//Second table: specify 3 columns
$pdf->AddCol('rank',20,'','C');
$pdf->AddCol('name',20,'tablecountry');
$pdf->AddCol('pop',20,'Pop (2001)','R');
$prop=array('HeaderColor'=>array(255,150,100),
            'color1'=>array(210,245,255),
            'color2'=>array(255,255,210),
            'padding'=>2);
//$pdf->Table('select dbCountry,dbCountryId from tablecountry  limit 0,10',$prop);
$pdf->Output();
?>

How to limit the number of datas in a page

A: LIMIT
eh? maybe?
http://dev.mysql.com/doc/refman/5.0/en/limit-optimization.html


text:
Q: Update value after render I am doing this:
const changePrice = (event) => {
  let {value} = event.target;
  priceBook = JSON.parse(value).price
}

return (

    <select onChange={changePrice}>
        {planes.map((book, index) => {
          return <option key={index} value={JSON.stringify(book)}>{book.pages}</option>
        })}
    </select>
    Price {priceBook}

);

And it loads the selector values well, but when I change the value I should update the price value in the view, which does not happen.

A: To implement stateful logic inside function based components use hooks:
const [priceBook, setPriceBook] = useState('such empty')
const changePrice = (event) => {
    let {value} = event.target;
    const priceBook = JSON.parse(value).price
    setPriceBook(pricebook)
  }

  return (

      <select onChange={changePrice}>
          {planes.map((book, index) => {
            return <option key={index} value={book.price}>{book.pages}</option>
          })}
      </select>
      Price {priceBook}

  );

A: You need to make a change to the state to trigger a component render. You can do this as answered by @Dupocas or try to use a setState in a class component, like this:
return (

    <select
      onChange={(event) => {
        let { value } = event.target;
        this.setState({
          priceBook: JSON.parse(value).price || 0
        })
      }}
    >
        {planes.map((book, index) => {
          return <option key={index} value={JSON.stringify(book)}>{book.pages}</option>
        })}
    </select>
    Price { this.state.priceBook }

);


text:
Q: How to make a correct unit test for this controller with Jest Well, I'm trying to understand how I could unit test my Controller on my express app, but I haven't found out how to do so... These are my code files for now:
// CreateUserController.ts
import { Request, Response } from "express";
import { CreateUserService } from "../services/CreateUserService";

class CreateUserController {
    async handle(request: Request, response: Response) {
        try {
            const { name, email, admin, password } = request.body;

            const createUserService = new CreateUserService();

            const user = await createUserService.execute({ name, email, admin, password });

            // if(user instanceof Error) {
            //     return response.send({ error: user.message });
            // }

            return response.send(user);
        } catch (error) {
            return response.send({ error });
        }
    }
}

export { CreateUserController };

// CreateUserService.ts
import { getCustomRepository } from "typeorm";
import { UsersRepositories } from "../repositories/UsersRepositories";
import { hash } from "bcryptjs";

interface IUserRequest {
    name: string;
    email: string;
    admin?: boolean;
    password: string;
}

class CreateUserService {
    async execute({ name, email, admin = false, password }: IUserRequest) {
            const usersRepository = getCustomRepository(UsersRepositories);

            if(!email) {
                throw new Error('Incorrect e-mail.');
            }

            const userAlreadyExists = await usersRepository.findOne({ email });

            if(userAlreadyExists) {
                throw new Error('User already exists.');
            }

            const passwordHash = await hash(password, 8);

            const user = usersRepository.create({ name, email, admin, password: passwordHash });

            const savedUser = await usersRepository.save(user);

            return savedUser;
    }
}

export { CreateUserService };

// Users.ts
import { Entity, PrimaryColumn, Column, CreateDateColumn, UpdateDateColumn } from "typeorm";
import { Exclude } from "class-transformer";
import { v4 as uuid } from "uuid";

@Entity("users")
class User {

    @PrimaryColumn()
    readonly id: string;

    @Column()
    name: string;

    @Column()
    email: string;

    @Column()
    admin: boolean;

    @Exclude()
    @Column()
    password: string;

    @CreateDateColumn()
    created_at: Date;

    @UpdateDateColumn()
    updated_at: Date;

    constructor() {
        if (!this.id) {
            this.id = uuid();
        }
    }
}

export default User;

// UsersRepositories.ts
import { EntityRepository, Repository } from "typeorm";
import User from "../entities/User";

@EntityRepository(User)
class UsersRepositories extends Repository<User> {}

export { UsersRepositories };

and what I want to test is the CreateUserController, but I think it is written in a way I can't test, or can I?
For now, I have something like this:
// CreateUserController.unit.test.ts
import { CreateUserController } from "./CreateUserController";
import { getCustomRepository } from "typeorm";
import { UsersRepositories } from "../repositories/UsersRepositories";
import { hash } from "bcryptjs";
import { v4 as uuid } from "uuid";

describe('testando', () => {
    it('primeiro it', async () => {
        const userId = uuid();
        const userData = {
            name: 'Fulano',
            email: 'email@d.com',
            password: '123456',
            admin: true
        };
        const returnUserData = {
            id: userId,
            name: 'Fulano',
            email: 'email@d.com',
            password: await hash('123456', 8),
            admin: true,
            created_at: new Date(),
            updated_at: new Date()
        };

        jest.spyOn(getCustomRepository(UsersRepositories), 'save').mockImplementation(async () => returnUserData);

        const user = await CreateUserController.handle(userData);
    });
});

Yeah, I know there are errors and it won't run, but that's all I got so far

A: Unit test for the controller means another controller's dependencies work well. In your case, the controller only has one dependence - CreateUserService.
To test the controller, you can imagine that the service returns a user or throw an unexpected exception. And you expect that .send function will be called with the correct parameter.
There are too many things that need to explain(I think so), you can try to investigate by yourself.
// CreateUserController.test.ts
import { mocked } from "ts-jest/utils";
import { Request, Response } from "express";
import { CreateUserController } from "./CreateUserController"
import { CreateUserService } from "./CreateUserService";

jest.mock('./CreateUserService'); // mock CreateUserService constructor

describe('CreateUserController', () => {
  const name = 'name';
  const email = 'email';
  const admin = true;
  const password = 'password';

  let controller: CreateUserController;
  let service: jest.Mocked<CreateUserService>;

  let request: Request;
  let response: Response;

  beforeEach(() => {
    request = {
      body: { name, email, admin, password },
    } as Request;
    response = {
      send: jest.fn().mockReturnThis(),
      status: jest.fn().mockReturnThis(),
    } as any;

    service = {
      execute: jest.fn(),
    }; // an instance of the service
    mocked(CreateUserService).mockImplementation(() => {
      return service;
    }); // mock the service constructor to return our mocked instance

    controller = new CreateUserController();
  });

  it('should response with user object when service returns the user', async () => {
    const user: any = 'user mocked';
    service.execute.mockResolvedValue(user);

    await controller.handle(request, response);

    expect(response.send).toHaveBeenCalledWith(user);
    expect(service.execute).toHaveBeenLastCalledWith({ name, email, admin, password });
  });

  it('should response with status 500 and error object when service throws a error', async () => {
    const error = new Error('Timed out!');
    service.execute.mockRejectedValue(error);

    await controller.handle(request, response);

    expect(response.status).toHaveBeenCalledWith(500);
    expect(response.send).toHaveBeenCalledWith({ error });
    expect(service.execute).toHaveBeenLastCalledWith({ name, email, admin, password });
  });
});

It will fail in the second case because I expect that the controller has to respond with status 500, to make it pass, let update your controller:
...
    } catch (error) {
      return response.status(500).send({ error });
    }
...


text:
Q: how to combine not null columns in query? I have a table with only a full column in each row And the rest of the columns are null as follows:
+--------------------------------------------------------------------------------+
|   f_id    |   cloumn1   |     cloumn2     |       cloumn3    |    cloumn4      |
----------------------------------------------------------------------------------
|   1       |   data      |     NULL        |       NULL       |    NULL         |
----------------------------------------------------------------------------------
|   1       |   NULL      |     data        |       NULL       |    NULL         |
----------------------------------------------------------------------------------
|   1       |   NULL      |     NULL        |       data       |    NULL         |
----------------------------------------------------------------------------------
|   1       |   NULL      |     NULL        |       NULL       |    data         |
+--------------------------------------------------------------------------------+
|   2       |   data1     |     NULL        |       NULL       |    NULL         |
----------------------------------------------------------------------------------
|   2       |   NULL      |     data1       |       NULL       |    NULL         |
----------------------------------------------------------------------------------
|   2       |   NULL      |     NULL        |       data1      |    NULL         |
----------------------------------------------------------------------------------
|   2       |   NULL      |     NULL        |       NULL       |    data1        |
+--------------------------------------------------------------------------------+

I need to Receive all data in one row
+----------------------------------------------------------------------------------------+
|   f_id        |   cloumn1     |       cloumn2     |       cloumn3    |    cloumn4      |
------------------------------------------------------------------------------------------
|    1          |   data        |     data          |       data       |    data         |
------------------------------------------------------------------------------------------
|    2          |   data1       |     data1         |       data1      |    data1        |
+----------------------------------------------------------------------------------------+

Do you have a good way of writing this query?

A: You may use Group by and Max.
SELECT f_id,
       MAX(cloumn1) AS cloumn1,
       MAX(cloumn2) AS cloumn2,
       MAX(cloumn3) AS cloumn3,
       MAX(cloumn4) AS cloumn4
FROM   table
GROUP  BY f_id

A: try this one.
  select f_id, max(column1),max(column2),max(column3),max(column4)
  from tableName group by f_id order by f_id


text:
Q: C: Passing pointers: incompatible pointer type warning I'm trying to pass a 2d-array (array of strings) to a function in C, but am running into an "incompatible pointer type" warning.
In function 'main':
warning: passing argument 1 of 'addCodonstoHash' from incompatible pointer type

Code follows below. I am trying to create a hash table using uthash that will have 3-letter strings as keys (representing DNA codons), and associated char values representing the amino acid that the codon is translated to. So in essence, from the below code, I would want a hash table of the form
{"GCT" : 'A', "GCC" : 'A', "GCA" : 'A', "GCG" : 'A', "GCN" : 'A'}
where 'A' represents Alanine. But right now, I'm having trouble simply passing the array of codons to the function that should parse them and add them to the hash table. I've read through
Incompatible pointer type
and
Passing an array of strings as parameter to a function in C
to no avail... I thought I understood how arrays are allocated and degrade to pointers, but obviously not.
Furthermore, when I try to compute the length of the array in addCodonstoHash (there are going to be many differently-sized arrays representing the various amino acids), it's returning 8 and 2, respectively, from the printf debug lines, and I can't figure out why this is so. Can you guys steer me in the right direction?
/* Helper method for adding codons to hash table from initialized arrays */
void addCodonstoHash(char AAarray[][4], char AAname)
{   int i, size1, size;
    size1 = sizeof(AAarray);
    size  = size1 / sizeof(AAarray[0]);

    /* Debugging lines */
    printf("%d\n", size1);
    printf("%d\n\n",size);

    for (i = 0; i < (sizeof(AAarray) / sizeof(AAarray[0])); i++)
    {   add_codon(AAarray[i], AAname);
        printf(AAarray[i]);
        printf("\n");
    }
}

int main(int argc, char *argv[])
{   /*
     * Generate arrays for codons corresponding to each amino acid, will
     * all eventually be incorporated into hash table as keys, with AA
     * values.
     */
    const char Ala[][4] = {"GCT", "GCC", "GCA", "GCG", "GCN"};
    ...

    addCodonstoHash(Ala, 'A');

    delete_all();
    return 0;
}

Thanks!

A: Ala has type const char(*)[4] (except when it is used as sizeof or & operand), but the parameter has type char(*)[4]. You need to declare this one as const.


text:
Q: How can margins display value labels (Stata) I estimate marginal effects of a continuous variable at certain levels of a factor. While I can define and change value labels for my factor variable, the margins command does not display those labels. Can this be changed?
* load data
set more off
use http://www.stata-press.com/data/r13/nlswork
describe

* set panel structure
xtset idcode year

* set labels
label define OCC_labels 1 "First"  2 "Second" 3 "Third"
label values occ_code OCC_labels
tab occ_code

* fixed effects regression, with interaction of continuous and factor variable
xtreg ln_wage c.wks_ue##i.occ_code, fe

* investigate marginal effects of weeks worked last year
margins, dydx(wks_ue) at(occ_code = (1 2 3))


text:
Q: Package is to be upgraded but I already have that version I want to install libdrm-dev package but I get the following issue:
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 libdrm-dev : Depends: libdrm2 (= 2.4.67-1) but 2.4.91-2~16.04.1 is to be installed
              Depends: libdrm-intel1 (= 2.4.67-1) but 2.4.91-2~16.04.1 is to be installed
              Depends: libdrm-radeon1 (= 2.4.67-1) but 2.4.91-2~16.04.1 is to be installed
              Depends: libdrm-nouveau2 (= 2.4.67-1) but 2.4.91-2~16.04.1 is to be installed
              Depends: libdrm-amdgpu1 (= 2.4.67-1) but 2.4.91-2~16.04.1 is to be installed
E: Unable to correct problems, you have held broken packages.

The real issue is that I checked version on synaptic

and the currently installed package have all the "is to be installed" version already, how can I fix this? Also installing via synaptic gives me the same error.


text:
Q: R install package curl: "handle.c:30:1: error: unknown type name 'curl_sslbackend'" Oracle Linux 7, R 3.3.0
[oracle@ildar ~]$ yum list | grep curl
curl.x86_64                          7.29.0-54.0.1.el7       installed
libcurl.x86_64                       7.29.0-54.0.1.el7       installed
libcurl-devel.x86_64                 7.29.0-54.0.1.el7       installed
python-pycurl.x86_64                 7.19.0-19.el7           @odadom1
libcurl.i686                         7.29.0-54.0.1.el7       ol7_latest
libcurl-devel.i686                   7.29.0-54.0.1.el7       ol7_latest
[oracle@ildar ~]$

i.e. libcurl installed.
next try to install curl package in R:
[oracle@ildar ~]$ ORE CMD INSTALL curl_4.1.tar.gz
* installing to library '/u01/app/oracle/product/19.0.0.0/dbhome_1/R/library'
* installing *source* package 'curl' ...
** package 'curl' successfully unpacked and MD5 sums checked
Found pkg-config cflags and libs!
Using PKG_CFLAGS=
Using PKG_LIBS=-lcurl
** libs
rm -f curl.so callbacks.o curl.o download.o escape.o fetch.o form.o getdate.o handle.o ieproxy.o init.o interrupt.o multi.o nslookup.o reflist.o split.o ssl.o typechecking.o utils.o version.o winidn.o writer.o
gcc -m64 -std=gnu99 -I/usr/lib64/R/../../include/R -DNDEBUG -DSTRICT_R_HEADERS -I/systemr/port/Linux-X64/include/zlib -I/systemr/port/Linux-X64/include/xz -I/systemr/port/Linux-X64/include/bzip2 -I/systemr/port/Linux-X64/include    -fvisibility=hidden -fpic  -g -O2  -c callbacks.c -o callbacks.o
gcc -m64 -std=gnu99 -I/usr/lib64/R/../../include/R -DNDEBUG -DSTRICT_R_HEADERS -I/systemr/port/Linux-X64/include/zlib -I/systemr/port/Linux-X64/include/xz -I/systemr/port/Linux-X64/include/bzip2 -I/systemr/port/Linux-X64/include    -fvisibility=hidden -fpic  -g -O2  -c curl.c -o curl.o
gcc -m64 -std=gnu99 -I/usr/lib64/R/../../include/R -DNDEBUG -DSTRICT_R_HEADERS -I/systemr/port/Linux-X64/include/zlib -I/systemr/port/Linux-X64/include/xz -I/systemr/port/Linux-X64/include/bzip2 -I/systemr/port/Linux-X64/include    -fvisibility=hidden -fpic  -g -O2  -c download.c -o download.o
gcc -m64 -std=gnu99 -I/usr/lib64/R/../../include/R -DNDEBUG -DSTRICT_R_HEADERS -I/systemr/port/Linux-X64/include/zlib -I/systemr/port/Linux-X64/include/xz -I/systemr/port/Linux-X64/include/bzip2 -I/systemr/port/Linux-X64/include    -fvisibility=hidden -fpic  -g -O2  -c escape.c -o escape.o
gcc -m64 -std=gnu99 -I/usr/lib64/R/../../include/R -DNDEBUG -DSTRICT_R_HEADERS -I/systemr/port/Linux-X64/include/zlib -I/systemr/port/Linux-X64/include/xz -I/systemr/port/Linux-X64/include/bzip2 -I/systemr/port/Linux-X64/include    -fvisibility=hidden -fpic  -g -O2  -c fetch.c -o fetch.o
gcc -m64 -std=gnu99 -I/usr/lib64/R/../../include/R -DNDEBUG -DSTRICT_R_HEADERS -I/systemr/port/Linux-X64/include/zlib -I/systemr/port/Linux-X64/include/xz -I/systemr/port/Linux-X64/include/bzip2 -I/systemr/port/Linux-X64/include    -fvisibility=hidden -fpic  -g -O2  -c form.c -o form.o
gcc -m64 -std=gnu99 -I/usr/lib64/R/../../include/R -DNDEBUG -DSTRICT_R_HEADERS -I/systemr/port/Linux-X64/include/zlib -I/systemr/port/Linux-X64/include/xz -I/systemr/port/Linux-X64/include/bzip2 -I/systemr/port/Linux-X64/include    -fvisibility=hidden -fpic  -g -O2  -c getdate.c -o getdate.o
gcc -m64 -std=gnu99 -I/usr/lib64/R/../../include/R -DNDEBUG -DSTRICT_R_HEADERS -I/systemr/port/Linux-X64/include/zlib -I/systemr/port/Linux-X64/include/xz -I/systemr/port/Linux-X64/include/bzip2 -I/systemr/port/Linux-X64/include    -fvisibility=hidden -fpic  -g -O2  -c handle.c -o handle.o
handle.c:30:1: error: unknown type name 'curl_sslbackend'
 curl_sslbackend default_ssl_backend;
 ^
make: *** [handle.o] Error 1
ERROR: compilation failed for package 'curl'
* removing '/u01/app/oracle/product/19.0.0.0/dbhome_1/R/library/curl'

no matter if I install from local file or from cloud, I get the same error
handle.c:30:1: error: unknown type name 'curl_sslbackend'

How to install curl without errors?

A: I found solution.
The reason is that curl 4.1 has error.
4.0 should be installed instead:
https://github.com/jeroen/curl/issues/204#issuecomment-532162699
install.packages("https://cran.r-project.org/src/contrib/Archive/curl/curl_4.0.tar.gz",repo=NULL,type="source")


text:
Q: I am trying to figure out how to do a virtual key press For example if they typed something in the console for the program it would act like they pressed the "a" key.
This is different from this How to react to keypress events in Go?… because that is if some key is pressed then do something mine is if some key is pressed then virtually press another key


text:
Q: AJAX GET 500 internal server error I am working on a project on Laravel and Elasticsearch. I am beginner to laravel. At one point, I am getting Internal server error in my ajax GET call. My ajax call looks like this.
function hint(str)
{
    $.ajax({
        url: "/search1/" + str, // str is argument to be passed to controller function
        type: 'GET',
        success: function(response) {
            document.getElementById("txtHint").innerHTML = this.response;
            console.log(this.response);
        },
        error: function(data) {
            console.log(this.response);
        }
    });
}

I am trying to call a controller function by passing string argument "str" along with function call. My route call to controller looks like this:
Route::get('/search1/{str}','SearchController@search');

and my controller function "search" looks like this:
public function search($str)
    {
        $client = ElasticSearch::create()->build(); // No error in this line
        $json = '{ // my json data }';
        $param1 = json_decode($json,true);
        //some code to modify a json field to "str";
        echo "something";
    }

I would not mind providing any further information regarding my work.

A: Try adding the csrf token in your ajax call:
function hint(str)
{
    $.ajax({
        url: "/search1/" + str, // str is argument to be passed to controller function
        data:'_token = <?php echo csrf_token() ?>',
        type: 'GET',
        success: function(response) {
            document.getElementById("txtHint").innerHTML = this.response;
            console.log(this.response);
        },
        error: function(data) {
            console.log(this.response);
        }
    });
}


text:
Q: io connection event is not fired second time With the help of chokidar module, I'm creating a folder watcher. My Server.js code is:
let express = require('express')
let app = express();
let http = require('http').Server(app);
let path = require('path');
let chokidar = require('chokidar');
let io = require('socket.io')(http);

let port = process.env.port || 1337;

let clientPath = path.join(__dirname, 'client');

app.use(express.static(clientPath));

app.get('/', function (req, res) {
    res.sendFile(path.join(clientPath, 'HTML1.html'));
});

http.listen(port, function () {
    console.log(`listning on ${port}`);
});

let watcher = chokidar.watch(path.join(clientPath, 'images'),
    { ignored: /^\./, persistent: true }
);

watcher
    .on('add', function (path) {
        console.log('File', path, 'has been added');
        io.sockets.on('connection', function (socket) {
            socket.emit('imageAddClient', { imagePath: path });
            socket.on('imageAddServer', function (data) {
                console.log(`${data.imagePath} has been processed at client`);
            });
        });
    })
    .on('change', function (path) {
        console.log('File', path, 'has been changed');
    })
    .on('unlink', function (path) {
        console.log('File', path, 'has been removed');
    })
    .on('error', function (error) {
        console.error('Error happened', error);
    });

At client side, I've created angular factory to auto load page once an image is added. My client code is:
var app = angular.module('imageLoaderApp', []);
app.controller('loadController', function ($scope, socket) {
    try {
        images = [];
        socket.on('imageAddClient', function (data) {
            let fileName = data.imagePath.substring(data.imagePath.lastIndexOf('\\') + 1);
            console.log(fileName);
            images.push({ name: fileName, src: fileName });
            socket.emit('imageAddServer', { imagePath: fileName });
        });

        $scope.images = images;
        //console.log($scope.images);
    }
    catch (exception) {
        console.log(`Error from loadController ${exception}`);
    }
});

app.factory('socket', function ($rootScope) {
    var socket = io.connect('http://localhost:1337');
    return {
        on: function (eventName, callBack) {
            socket.on(eventName, function () {
                let args = arguments;
                $rootScope.$apply(function () {
                    callBack.apply(socket, args);
                });
            });
        },
        emit: function (eventName, data, callBack) {
            socket.emit(eventName, data);
        }
    }
});

However, the 'connection' event from io is fired only once I start the server. Afterwords if I add an image file in the folder, I can see watcher event is fired but 'connection' event is not fired.
What am I doing wrong?

A: You need to declare the io.on('connection') outside the watcher. You'll need to assign it on startup so it knows when a socket is connected.

var io = require('socket.io')(http);

io.on('connection', function(socket) {
 console.log('Socket connected!');

 socket.on('imageAddServer', function(data) {
  console.log('image has been processed at the client')
 });
 socket.on('disconnect', function() {
  console.log('Socket disconnected');
 });
});

watcher
    .on('add', function (path) {
        console.log('File', path, 'has been added');
  io.emit('imageAddClient', { imagePath: path }); //send it to the client sockets that are connected
    });

Use this code as a reference to update your code.

A: Actually Murf put me on the right track. I just changed his sequence. I'm putting answer here just in case somebody needs it in future...
So the code for watcher and io goes like this:
io.on('connection', function (socket) {
    executeWatcher(socket);
    socket.on('imageAddServer', function (data) {
        console.log(`${data.imagePath} has been processed at client`);
    });
    socket.on('disconnect', function () {
        console.log('Client disconnected');
    });

});

let executeWatcher = function (socket) {
    watcher
        .on('add', function (path) {
            console.log('File', path, 'has been added');
            socket.emit('imageAddClient', { imagePath: path });
        })
        .on('change', function (path) {
            console.log('File', path, 'has been changed');
        })
        .on('unlink', function (path) {
            console.log('File', path, 'has been removed');
        })
        .on('error', function (error) {
            console.error('Error happened', error);
        });
}


text:
Q: How to use shouldOverrideKeyEvent to trigger Javascript function I'm currently building a simpel app for Android with a webview that loads a page that should be controlled from the app.
For this, I want to completly override the default keybehaviour, and just call a function with the keycode from the key that is pressed.
For this, I've tried the following
public boolean shouldOverrideKeyEvent(BWWebviewClient view, KeyEvent event){

if ((KeyEvent = KeyEvent.KEYCODE_ENTER)){

webview.loadUrl("javascript:getKeyCode(KeyEvent)");
}

return true;
}

The problem with this is that KeyEvent in my ifstatement cannot be resolved.
What I want to do is simple catch all keys, disable their default behaviour and call a JS function with the keycode as argument.
Can anyone help?

A: the KeyEvent var doesnt carry from Java to Javascript... what you're using in loadUrl is just a string, and KeyEvent probably exists nowhere in JS.


text:
Q: Jquery ajax not returning data while console does I have the following code inside a JS function:
$.post('script/route.php', {deliveryAddress: address}, function (data) {
    console.log(data);
    return "The distance to your location is "+data+ ".";
});

This function posts to a PHP file that calculates the distance between two addresses. The console shows the correct distance, but the string with data is not returned for some reason, the complete return seems to be ignored. How can this happen?


text:
Q: Get url parameter and query mysql data with ajax I want to get a parameter from an url. The url looks like this:

www.example.com/?v=12345

I want to get the parameter and query my mysql database to get the right data with ajax.
So i have my ajax call here:
$.ajax({
type:"POST",
url:"ajax2.php",
dataType:"json",
success:function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error:function(response){

alert("error occurred");
}
});

As you can see, the data which i want to get are in a json array and will be saved in javascript variables.
This is my php file:
 <?php

 // Connection stuff right here

 $myquery = "SELECT * FROM mytable **WHERE id= **$myurlvariable**;
 $result = mysql_query($myquery);
 while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array = array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);

 echo json_encode($array);

}

?>

The part where i want to query the right variable is bolded. I don't know how to query that. And Furthermore how to even get the url parameter in the proper form.
Can anybody help? Thank you!

A: You can get the query string using JavaScript and send it in the AJAX request.
Getting the query string(JavaScript) -
function query_string(variable)
{
   var query = window.location.search.substring(1);
   var vars = query.split("&");
   for (var i=0;i<vars.length;i++) {
           var pair = vars[i].split("=");
           if(pair[0] == variable){return pair[1];}
   }
   return(false);
}
//Getting the parameter-
v = query_string('v');  // Will return '12345' if url is www.example.com/?v=12345

This needs to be passed as data in the AJAX call.
$.ajax(
    {
        type:       "POST",
        dataType:   "json",
        url:        "ajax2.php",
        data:       "v="+v,
        success:    function(response){
                        var id = response['id'];
                        var url = response['url'];
                        var name = response['name'];
                        var image = response['image'];
                    },
        error:      function(jqXHR,textStatus,errorThrown){
                    //alert(JSON.stringify(jqXHR));
                    //alert(textStatus);
                    //alert(errorThrown);
                    alert(JSON.stringify(jqXHR)+" "+textStatus+" "+errorThrown);
                    //alert("error occurred");
                }
    }
);

This can be accessed as $_POST['v'] in the php form.
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
...

And in php form, before you echo out the json response, change the content type. Something like this-
header("Content-Type: application/json");
echo json_encode($array);

If there is a database error, then it has to be handled.
So do this -
<?php
    // Connection stuff right here
    header("Content-Type: application/json");
    if(isset($_POST['v'])){
        $myurlvariable = $_POST['v'];
        $myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
        $result = mysql_query($myquery) or die(json_encode(Array("error": mysql_error()));
        while($row = mysql_fetch_object($result))
        {
            $currentid = "$row->id";
            $currentname = "$row->name";
            $currenturl = "$row->url";
            $currentimage = "$row->image";
            $array[]= array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
        }
        echo json_encode($array);
    }else{
        echo json_encode(Array("error": "No POST values"));
    }
?>

So this way, if the query has not executed properly, then you will know what exactly the error is.

A: Without any error checking, just the important part:
$myquery = "SELECT * FROM mytable WHERE id=" . $_POST['v'];


text:
Q: How to fix 'Uncaught TypeError: $(...).daterangepicker is not a function' when add jquery 3.2.1 library in laravel? First, I want to make a datepicker, but when I add the jquery.min.js library I get an error 'daterangepicker is not a function' how to fix it?
I already tried removing the jquery.min.js library but what appeared was 't is not a function'
in pages dashboard blade.php

<canvas id="myChart"></canvas>

this is dashboard.php  to call function lib
 public function dashboard()
    {
        $pages['view'] = 'pages.dashboard.dashboard';

        $data['css'] = $this->css_dashboard();
        $data['js'] = $this->js_dashboard();
        $data['js'] = array_merge($this->js_dashboard(),[]);

        $data['icon'] = 'icon-home';
        $data['parent'] = 'Dashboard';

        $data['view'] = $this->page($pages);
        return $data;
    }

and this is controller.php to call library
public function css_dashboard()
    {
        $css = array(
            'jamtangan/css/library/daterangepicker.css',
        );
        return $css;
    }

    public function js_dashboard()
    {
        $js = array(
            'jamtangan/js/library/chart.js',
            'jamtangan/js/library/daterangepicker.min.js',
            'jamtangan/js/library/moment.min.js'
            'jamtangan/js/library/jquery.min.js'
        );
        return $js;
    }


text:
Q: In Spring project unable to start Tomcat from IntlleiJ I have spring project. Now i am configuring Tomcat Server in IntelliJ. When i run the Tomcat from IntelliJ, it shows the following console error.

SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.context.weaving.AspectJWeavingEnabler#0': Initialization of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loadTimeWeaver': Initialization of bean failed; nested exception is java.lang.IllegalStateException: ClassLoader [org.apache.catalina.loader.WebappClassLoader] does NOT provide an 'addTransformer(ClassFileTransformer)' method. Specify a custom LoadTimeWeaver or start your Java virtual machine with Spring's agent: -javaagent:org.springframework.instrument.jar
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1079)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:643)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:407)
    at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4723)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5226)
    at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5221)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:662)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loadTimeWeaver': Initialization of bean failed; nested exception is java.lang.IllegalStateException: ClassLoader [org.apache.catalina.loader.WebappClassLoader] does NOT provide an 'addTransformer(ClassFileTransformer)' method. Specify a custom LoadTimeWeaver or start your Java virtual machine with Spring's agent: -javaagent:org.springframework.instrument.jar
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.context.weaving.LoadTimeWeaverAwareProcessor.postProcessBeforeInitialization(LoadTimeWeaverAwareProcessor.java:95)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1413)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    ... 19 more
Caused by: java.lang.IllegalStateException: ClassLoader [org.apache.catalina.loader.WebappClassLoader] does NOT provide an 'addTransformer(ClassFileTransformer)' method. Specify a custom LoadTimeWeaver or start your Java virtual machine with Spring's agent: -javaagent:org.springframework.instrument.jar
    at org.springframework.context.weaving.DefaultContextLoadTimeWeaver.setBeanClassLoader(DefaultContextLoadTimeWeaver.java:83)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeAwareMethods(AbstractAutowireCapableBeanFactory.java:1436)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1408)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
    ... 28 more
Jul 18, 2011 2:43:51 PM com.sun.xml.ws.transport.http.servlet.WSServletContextListener contextInitialized
INFO: WSSERVLET12: JAX-WS context listener initializing
Jul 18, 2011 2:43:51 PM com.sun.xml.ws.server.MonitorBase createRoot
INFO: Metro monitoring rootname successfully set to: null
Jul 18, 2011 2:43:52 PM com.sun.xml.ws.server.MonitorBase createRoot
INFO: Metro monitoring rootname successfully set to: null
Jul 18, 2011 2:43:52 PM com.sun.xml.ws.server.MonitorBase createRoot
INFO: Metro monitoring rootname successfully set to: null
Jul 18, 2011 2:43:52 PM com.sun.xml.ws.transport.http.servlet.WSServletDelegate <init>
INFO: WSSERVLET14: JAX-WS servlet initializing
Jul 18, 2011 2:43:52 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Error listenerStart
Jul 18, 2011 2:43:52 PM org.apache.catalina.core.StandardContext startInternal
SEVERE: Context [] startup failed due to previous errors
Jul 18, 2011 2:43:52 PM com.sun.xml.ws.transport.http.servlet.WSServletDelegate destroy
INFO: WSSERVLET15: JAX-WS servlet destroyed
Jul 18, 2011 2:43:52 PM com.sun.xml.ws.transport.http.servlet.WSServletContextListener contextDestroyed
INFO: WSSERVLET13: JAX-WS context listener destroyed
Jul 18, 2011 2:43:52 PM org.apache.catalina.startup.HostConfig deployWAR
INFO: Deploying web application archive jamon.war
Jul 18, 2011 2:43:52 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory docs
Jul 18, 2011 2:43:53 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory examples
Jul 18, 2011 2:43:53 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory host-manager
Jul 18, 2011 2:43:54 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory manager
Jul 18, 2011 2:43:54 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory resweb
Jul 18, 2011 2:43:55 PM org.apache.catalina.startup.HostConfig deployDirectory
INFO: Deploying web application directory soapui
Jul 18, 2011 2:43:55 PM org.apache.coyote.AbstractProtocolHandler start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Jul 18, 2011 2:43:55 PM org.apache.coyote.AbstractProtocolHandler start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Jul 18, 2011 2:43:55 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 10133 ms
Connected to server

A: Your stacktrace says

Caused by: org.springframework.beans.factory.BeanCreationException:
  Error creating bean with name 'loadTimeWeaver': Initialization of bean
  failed; nested exception is java.lang.IllegalStateException:
  ClassLoader [org.apache.catalina.loader.WebappClassLoader] does NOT
  provide an 'addTransformer(ClassFileTransformer)' method. Specify a
  custom LoadTimeWeaver or start your Java virtual machine with Spring's
  agent: -javaagent:org.springframework.instrument.jar

Perhaps you could do as it suggests? Add a -javaagent to the VM args in the run-config.


text:
Q: how to give blur effect for css overflow visible content I have a div called "divimg" which is fixed and another div called "drag" it consist of a image . I am using this image to drag and resize and i have used overflow for div called divimg visible.
So my question is that , i want that visible content as blur .
Below is my code, please give me some suggestion? Hope you got my question.

<form id="form1" runat="server">

 <asp:Panel ID="Panel3" runat="server" Height="373px" Width="518px" style="margin-top: 0px; margin-left: 0px; text-align: center; overflow:hidden"  >

         <asp:Image ID="displayimg" runat="server" Height="224px" Width="340px" src="images/group1.jpg" style="left:-3%; top:-3%; overflow:visible; " BorderStyle="Ridge" BorderWidth="2px"  />

    </asp:Panel>

</form>

SOMETHING LIKE THIS:

I want that red bordered area to be blurred. Any Help ?

A: I got an answer to my question ..

.outter_div{width:400px; height: 200px;position: relative;}
.outter_div:after{content:"";border:50px solid rgba(255,255,255,0.5);position: absolute; top: 0;width: 300px;height: 100px;}
img{width: 100%;position:}


text:
Q: python, remove link from string How can the link from this string be removed
s=' hello how are you www.ford.com today '

so that the output is
s='hello how are you today'

A: Try the following list comprehension, which omits words of the pattern www._____.com:
' '.join(item for item in s.split() if not (item.startswith('www.') and item.endswith('.com')) and len(item) > 7) #the len(item) is to make sure that words like www.com, which aren't real URLs, aren't removed

>>> s=' hello how are you www.ford.com today '
>>> ' '.join(item for item in s.split() if not (item.startswith('www.') and item.endswith('.com') and len(item) > 7))
'hello how are you today'
>>>

A: This seems like a good situation for a regex substitution.
>>> import re
>>> s = ' hello how are you www.ford.com today www.example.co.jp '
>>> re.sub(r'\s*(?:https?://)?www\.\S*\.[A-Za-z]{2,5}\s*', ' ', s).strip()
'hello how are you today'

The above finds any string that starts with potential whitespace, then possibly https:// or http://, then www., then any non-whitespace characters, then . followed by 2-5 alphabetical characters, then potential whitespace. It replaces such strings with a single space, and then removes leading and trailing whitespace from the result.
Note that this is a naive example of a URL, as defined by your specific example. See this answer for a regex with a more complete definition of what constitutes a URL.

A: While you can certainly use strings methods, I prefer the regular expression based approach. It can handle spaces between words.
import re

s = " hello www.something.com there bobby"
s = re.sub(r'www\.\S+\.com', '',s)
print(s) # hello  there bobby
s = "hello www. begins and .com ends"
s = re.sub(r'www\.\S+\.com', '',s)
print(s) # hello www. begins and .com ends

A: In order to deal with the case where there is no space around the url, you can use the string split method like this:
if ".com" in s:
    s=''.join((s.split("www.")[0], " ", s.split(".com")[1]))


text:
Q: Jquery for asp.net treeview I am using a asp.net tree view control. I want to add the jquery style for the .net tree view control. But i can't do this. Please help me to fix this issue. I need the jquery for smooth expanding and collapse...
This is my design code. Where i can refer the jquery in asp.net control
 <asp:TreeView ID="MyTree" PathSeparator="|" ExpandDepth="1" runat="server" NodeIndent="15"
                    ShowLines="true">
                    <RootNodeStyle ImageUrl="~/images/folder-video.png" />
                    <ParentNodeStyle ImageUrl="~/images/root.png" />
                    <NodeStyle ImageUrl="~/images/node.png" />
                    <LeafNodeStyle ImageUrl="~/images/leaf_video.png" />
                    <SelectedNodeStyle BackColor="#B5B5B5"></SelectedNodeStyle>
                    <NodeStyle VerticalPadding="2" Font-Names="Tahoma" Font-Size="10pt" HorizontalPadding="2"
                        ForeColor="#000000"></NodeStyle>
                    <HoverNodeStyle Font-Underline="True" ForeColor="#6666AA"></HoverNodeStyle>
                    <Nodes>
                        <asp:TreeNode Text="Sunbusiness Solution" PopulateOnDemand="True" Value="Demos" />
                    </Nodes>
                </asp:TreeView>

A: I use treeview with checkboxes. On checkbox click  node expands.
function InitTreeViewClick(){    $('#" + treevew.ClientID + @" :input').each(function(){  $(this).unbind(); var   a=this.nextSibling; if(a.nodeName=='A')  $(this).bind('click',   function(){a.click();});});}
}

Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(InitTreeViewClick);

You can modify a.click() for example:   setTimeout(function(){a.click();},3000);
In my case this works perfectly.
And cs file code:
protected void Page_PreRender(object sender, EventArgs e)
    {
if (!this.Page.ClientScript.IsStartupScriptRegistered("treeview"))
        {
            string script = @"Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(InitTreeViewClick);

                          function InitTreeViewClick(){    $('#" + treevew.ClientID + @" :input').each(function(){ $(this).unbind(); var a=this.nextSibling; if(a.nodeName=='A')  $(this).bind('click',  function(){a.click();});});} ";
            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "treeview", script, true);
        }
}

In your case you can find all links
$('#" + treevew.ClientID + @" ).find('a').each( function(){$(this).click(
// your logic
);});

OR
 $('#" + treevew.ClientID + @" ).find('a').each(function(){$(this).click(function(){$(this).parentsUntil('table').parent('table').next().css('background','red').slideToggle("slow");});});

this code will slowly collapse and expand div with subitems when you click on parent node and background for child nodes will be red on this time.
Final solution (I applied this solution in my project too, because it looks fine).
 ASCX file code:
<asp:TreeView ID="treeview" runat="server" ForeColor="Black" CssClass="inputs" ExpandDepth="0" MaxDataBindDepth="2"
    EnableClientScript="true" ShowCheckBoxes="All" AutoGenerateDataBindings="false"  ShowLines="false"
     ShowExpandCollapse="false">

</asp:TreeView>

and cs file code:
 if (!this.Page.ClientScript.IsStartupScriptRegistered("treeview")) { string script = @"function InitTreeView(){$('#" + treeview.ClientID + @"' ).find('a').each(function(){$(this).unbind().removeAttr('onclick').removeAttr('href').click(function(){$(this).parentsUntil('table').parent('table').next().slideToggle('slow');});});} Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(InitTreeView);"; ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "treeview", script, true); }

I remove href  attribute  with __DoPostBack from tag anchor, because I need to save only checkboxes value.
Many thanks indeed user 1804985 for your question. :)


text:
Q: Issue regarding TX line of Arduino while communicating with Vending machine via MDB Protocol over USART I am trying to communicate with a Vending machine using MDB Protocol with the help of Arduino Mega and I am partially successful in doing so.
The circuit that I am using is attached here

While the circuit diagram is shown below

The Arduino Mega is communicating with laptop via Serial 1 and the vending machine communication is done via Serial 2 of Arduino Mega.
 USART is being use for communication.
The strange issue that I am facing is, the communication with the vending machine starts sending data only when brown colored wires A and B are initially not connected(which are connecting Arduino TX to Vending Machine RX). Once I see the data coming from Vending Machine, I short wires A and B and Arduino Starts sending data to the vending machine too.
But if Wires A and B are connected on the start of a vending machine, the vending machine doesn't send any data to Arduino and hence no communication takes place. I want to make it work without manually connecting wire A and B every time.
I have tried replacing Optocoupler PC817C with

*

*PC814

*4N35

*6N137 High Speed Optocoupler

I tried replacing Hex Inverter with

*

*74HC04AP

I tried putting a mechanical and then solid-state relay between wires A and B and tried connecting them via external input but nothing happens
I tired adding an optocoupler as a switch between wires A and B and tried controlling it via firmware.
I even tried replacing the hex inverter with hex buffer HCF4050BE and a NOT Gate but regardless of any combination of mentioned components the issue remains the same, it only works if Wires A and B are initially not connected and then shorted once data starts coming from the vending machine.

I am using MateDealer's code.

I want to automate this manual process and need a simple solution for that.

A: Some time ago I had a communication trouble between a PIC18F452 and a vending Machine that uses MDB protocol.
In that time I found that the communication since PIC toward Machine is negative to communicacion since Machine to PIC. This is because the electronic into vending machine that receive data had a optoacoplade circuit that inverts signal.
I remember that I saw that when I read the MDB protocol documentation, the section when is the electronic diagram VMC.
I advice that check that section, this can explaine why when you conect the A and B wire job, because you are invert twice signal.

A: Resolved

The issue was due to a missed state machine element. My Device is a LEVEL-1 MDB Device and the vending machine that I am using requires the slave devices(whether they are at LEVEL-1 or LEVEL-2) to even respond to LEVEL-2 SETUP poll which is not a standard case in MDB Specifications Document.

Why it was working when TX wire was de-attached?

My logic analyzer was displaying some random hex values when TX line was removed and that random stuff caused the device to work.
 By responding to the extra setup configuration poll of my vending machine I was able to make it work smoothly.
Below is the picture showing the configuration data sent by VMC which was discarded by my device making it behave strangely.


text:
Q: A piece of code gets executed only in immediate window in VS 2010 I have a line of code behaving weirdly.
objectType = ((DependencyObject)obj).GetValue(FrameworkElementExtensions.IdProperty) as string;

The above line returns "" when i run the code or even when i debug the code. But when i execute the same statement in the immediate window it returns me the proper string.
I tried executing the statement twice but still it didn't work.
Any idea why this could be happening?


text:
Q: How do I Modify the code snippet below ,so that if a page got a parent page the parent title/link is displayed instead in wordpress add_filter('avf_title_args', 'fix_page_title', 10, 1);
function fix_page_title($args) {

    $args['title'] = get_the_title();
    $args['link'] = get_permalink();

    return $args;

}

A: You can check for a parent using $post->post_parent and get the title using get_the_title():
add_filter('avf_title_args', 'fix_page_title', 10, 1);
function fix_page_title($args) {
    global $post;

    if($post->post_parent){
        $args['title'] = get_the_title();
    } else {
        $args['title'] = get_the_title( $post->post_parent );
    }
    $args['link'] = get_permalink();

    return $args;

}

Or:
$args['title'] = get_the_title($post->post_parent ?: NULL);


text:
Q: Download a txt file from EDGAR I want to download this file to my local drive:
https://www.sec.gov/Archives/edgar/data/1556179/0001104659-20-000861.txt
Here are my codes:
import requests
import urllib
from bs4 import BeautifulSoup
import re

path=r"https://www.sec.gov/Archives/edgar/data/1556179/0001104659-20-000861.txt"
r=requests.get(path, headers={"User-Agent": "b2g"})
content=r.content.decode('utf8')
soup=BeautifulSoup(content, "html5lib")
soup=str(soup)
lines=soup.split("\\n")

dest_url=r"C://Users/YL/Downloads/a.txt"
fx=open(dest_url,'w')
for line in lines:
    fx.write(line + '\n')

Here is the error message:

How should I download the file then? Thanks a lot!

A: The download is fine. The problem is that str(soup) is not well-defined, and throws html5lib into an endless loop. You probably meant
soup = soup.text

which (crudely) extracts the actual readable text from the BeatifulSoup object.

A: Your file has downloaded alright; it seems there's a problem with BeautifulSoup's parsing. Try changing the parser and doing it this way:
path=r"https://www.sec.gov/Archives/edgar/data/1556179/0001104659-20-000861.txt"
r=requests.get(path, headers={"User-Agent": "b2g"})
soup=BeautifulSoup(r.text, "html.parser")
soup

and you'll see the file is there.


text:
Q: React Native - How to create Loader with transparent view? I want to create transparent loader like facebook login, so the loader can stacked the view,
like this one:

I have a file called Loader.js:
class Loader extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.nyoba}>
          <Text style={[global.global.HeaderText, {color:'white', justifyContent:'center'}]}>Loading...</Text>
          <Text style={[global.global.HeaderText, {color:'white', justifyContent:'center', marginBottom:150}]}>Please Wait...</Text>
          <Spinner
            isVisible={true}
            size={100}
            type={'ThreeBounce'}
            color={'#ffffff'}
          />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  indicator: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    height: 80
  },
  container: {flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgba(0,0,0, 0.3)'},
  nyoba: {justifyContent: 'center', alignItems: 'center', backgroundColor: '#8B0000'},
});

And i want to called Loader.js in every screen while calling an API, but the Loader take's all the screen,
like this :

How can I makes the Loader.js work like I want? Is there's some way to makes my loader like facebook loader?

A: React Native's Modal component allows to present a view in an enclosing view. What you are trying to achieve can be done using Modal component.
Please have a look into Modal Component Docs.

A: Try Applying StyleSheet.absoluteFillObject and zIndex: 5 to your most parent View
import React from 'react';
import {
View,
Text,
StyleSheet
} from 'react-native';
export class Loader extends React.Component {
render() {
    return (
        <View style={[styles.container,
StyleSheet.absoluteFillObject]}>
            <View style={styles.nyoba}>
                <Text style={[ {color:'white',
justifyContent:'center'}]}>Loading...</Text>
                <Text style={[ {color:'white',
justifyContent:'center', marginBottom:0}]}>Please Wait...</Text>
                </View>
            </View>
        );
     }
   }

const styles = StyleSheet.create({
indicator: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    height: 80
},
container: {flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: 'rgba(0,0,0, 0.3)', zIndex: 5},
nyoba: {justifyContent: 'center', alignItems: 'center', backgroundColor: '#8B0000'},
});

A: Add this to Value> styles
   <!--   My Chose Diaog   -->
    <style name="Theme.CustomDialog" parent="Base.Theme.AppCompat.Light.Dialog">
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:padding">0.1dp</item>
        <item name="android:background">#8d8cdf</item>

Add this to the AndroidManifest file
<activity
      android:name=".Add_Posts_Buttons"
      android:theme="@style/Theme.CustomDialog" />

You can adjust transparency by setting the transparency of this color in the style
Examples :
<!--Transparent 50%-->
    <item name="android:background">#45ffffff</item>

    <!--Transparent 10%-->
        <item name="android:background">#8d8cdf</item>

    <!--Transparent 0%-->
        <item name="android:background">#ffffff</item>

    <!--Transparent 100%-->
        <item name="android:background">#00ffffff</item>


text:
Q: How can I animate specific views? I want to animate Bloc A to slide up and Bloc B to slide down when I move from Activity 1 to Activity 2
Can someone bring me a solution for this ? Thanks a lot for your help
Here's an illustration of what I want :

A: Try the following:
1) MainActivity.class:-------------
public class MainActivity extends AppCompatActivity implements Listener {

private Drawer m_Drawer;
private Button b;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    m_Drawer = new Drawer(this, this);

    b = (Button) findViewById(R.id.b); // click on this button to open drawer.
    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            m_Drawer.openDrawer();
        }
    });

}

@Override
public void AnimationFinished(int state) {
    if (state == 1) {
        b.setVisibility(View.VISIBLE); // you can start a new activity or do whatever here.
    }else if(state == 0){
        b.setVisibility(View.GONE);
    }
}

}

2) Drawer.class:-------
public class Drawer {

private static final String TAG = "Drawer";
private RelativeLayout topDrawer;//2
private RelativeLayout bottomDrawer;//2
private Activity activity;
private static final int DRAWER_UP = 1;
private static final int DRAWER_DOWN = 0;
private int mainlayoutHeight;
private TextView drawerTxt1;
private TextView drawerTxt;
private int direct;
private ConstraintLayout mainLayout;//1

private float mDownMotionX = 0;
private float mDownMotionY = 0;

private final int SWIPE_SENSITIVITY = 10;

private final int SWIPE_X_SENSITIVITY = 20;

private final int SWIPE_Y_SENSITIVITY_MIN = 0;
private int SWIPE_Y_SENSITIVITY_MAX = 0;

private Listener callback;

Drawer(Activity mainActivity , Listener l) {
    activity = mainActivity;
    if(l != null){
        this.callback = l;
    }
    initialize();
    getLayoutHeight();

}

private void initialize() {

    topDrawer =  (RelativeLayout) activity.findViewById(R.id.top_drawer);//2
    drawerTxt1 = (TextView) topDrawer.findViewById(R.id.drawer_txt1);
    drawerTxt1.setText("BLOCK A");
    bottomDrawer =  (RelativeLayout) activity.findViewById(R.id.bottom_drawer);//2
    drawerTxt = (TextView) bottomDrawer.findViewById(R.id.drawer_txt);
    drawerTxt.setText("BLOCK B");

    topDrawer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent ev) {

            Log.e(TAG, "Touch View");
            final int action = ev.getAction();

            switch (action & MotionEvent.ACTION_MASK) {

                case MotionEvent.ACTION_DOWN:
                    // Remember where the motion event started
                    mDownMotionX = ev.getX();
                    mDownMotionY = ev.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    // Scroll to follow the motion event
                    final float x = ev.getX();
                    final float y = ev.getY();

                    SWIPE_Y_SENSITIVITY_MAX = getScreenHeight();

                    if (Math.abs(y - mDownMotionY) >= SWIPE_SENSITIVITY &&
                            (mDownMotionY > SWIPE_Y_SENSITIVITY_MIN &&
                                    mDownMotionY <= SWIPE_Y_SENSITIVITY_MAX) &&
                            Math.abs(x - mDownMotionX) <= SWIPE_X_SENSITIVITY) {

                        if ((y - mDownMotionY) > 0) {
                            Log.d(TAG, "Dragging Down");
                        }
                    } else if ((y - mDownMotionY) < 0) {
                        closeDrawer();
                        Log.d(TAG, "Dragging Up");
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    break;
                case MotionEvent.ACTION_CANCEL:
                    break;
            }
            return true;
        }
    });

    bottomDrawer.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent ev) {

            Log.e(TAG, "Touch View");
            final int action = ev.getAction();

            switch (action & MotionEvent.ACTION_MASK) {

                case MotionEvent.ACTION_DOWN:
                    // Remember where the motion event started
                    mDownMotionX = ev.getX();
                    mDownMotionY = ev.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    // Scroll to follow the motion event
                    final float x = ev.getX();
                    final float y = ev.getY();

                    SWIPE_Y_SENSITIVITY_MAX = getScreenHeight();

                    if (Math.abs(y - mDownMotionY) >= SWIPE_SENSITIVITY &&
                            (mDownMotionY > SWIPE_Y_SENSITIVITY_MIN &&
                                    mDownMotionY <= SWIPE_Y_SENSITIVITY_MAX) &&
                            Math.abs(x - mDownMotionX) <= SWIPE_X_SENSITIVITY) {

                        if ((y - mDownMotionY) > 0) {
                            Log.d(TAG, "Dragging Down");
                            closeDrawer();
                        }
                    } else if ((y - mDownMotionY) < 0) {
                        Log.d(TAG, "Dragging Up");
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    break;
                case MotionEvent.ACTION_CANCEL:
                    break;
            }
            return true;
        }
    });

}

//********************************************************************************************** Open and Close the Drawer /Animation/
private void drawerMovement(int movement){
    switch (movement) {
        case DRAWER_UP: // --------------------------------------------------------------------- Drawer UP
            topDrawer.animate().translationY(-mainlayoutHeight/2); // you can add two animation listeners, but for now one is enough.
            bottomDrawer.animate().translationY(mainlayoutHeight)
                    .setListener(new animationListener());
            direct = DRAWER_UP;
            break;

        case DRAWER_DOWN: // ------------------------------------------------------------------- Drawer DOWN
            topDrawer.animate().translationY(0);
            bottomDrawer.animate().translationY(mainlayoutHeight/2)
                    .setListener(new animationListener());
            direct = DRAWER_DOWN;
            break;
    }
}

//**********************************************************************************************  Animation Listener
private class animationListener implements  Animator.AnimatorListener {

    @Override
    public void onAnimationStart(Animator animation) {
    }

    @Override
    public void onAnimationEnd(Animator animation) {
        callback.AnimationFinished(direct);
    }

    @Override
    public void onAnimationCancel(Animator animation) {
    }

    @Override
    public void onAnimationRepeat(Animator animation) {}
}

private void closeDrawer(){
    drawerMovement(DRAWER_UP);
}

public void openDrawer(){
    drawerMovement(DRAWER_DOWN);
}

// ********************************************************************************************* Get the Layout Height
private void getLayoutHeight() {
    mainLayout = (ConstraintLayout) activity.findViewById(R.id.main_layout);//1
    ViewTreeObserver vto = mainLayout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            mainlayoutHeight = mainLayout.getMeasuredHeight();
            topDrawer.setY(0);
            bottomDrawer.setY(mainlayoutHeight/2);
            ConstraintLayout.LayoutParams params = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, mainlayoutHeight/2);//1
            topDrawer.setLayoutParams(params);
            bottomDrawer.setLayoutParams(params);
            Log.d("Test", "Layout Height: " + mainlayoutHeight );
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                mainLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                mainLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        }
    });
}

private int getScreenHeight(){

    DisplayMetrics displayMetrics = new DisplayMetrics();
    activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    return displayMetrics.heightPixels;
}

}

3) Listener interface:----------
public interface Listener {

public void AnimationFinished(int state);

}

4) main_activity.xml:----------
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/main_layout"
tools:context=".MainActivity">

<RelativeLayout
     android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:id="@+id/bottom_drawer"
    android:background="?attr/colorPrimary">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/drawer_txt"
        android:textSize="28sp"
        android:gravity="center_horizontal|center_vertical" />

</RelativeLayout>

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:id="@+id/top_drawer"
    android:background="?attr/colorAccent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/drawer_txt1"
        android:textSize="28sp"
        android:gravity="center_horizontal|center_vertical" />

</RelativeLayout>

<LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="100dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:gravity="center_horizontal">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/b"
        android:text="Open Drawer"
        android:textAllCaps="false"
        android:layout_gravity="center"
        android:visibility="gone"
        android:textSize="28sp"
        android:textColor="@android:color/white">
    </Button>

</LinearLayout>

</android.support.constraint.ConstraintLayout>


text:
Q: How to convert a column into a count of occurences (in R)
This photo shows my current dataframe, containing information on the first year an invasive species was recorded in each country. I am not interested in the taxon data, just the number of taxa,  and instead want one row for each country and year, giving a count of the number of taxa that were introduced that year in that country.
E.g.
Afghanistan, 1996, 1.
Afghanistan, 1974, 1.
...
Alaska, 2020, 1.
Alaska, 2017, 2.
And so on.
I thought about looping through each row, but is there a quicker way to do this?

A: Is this what you're looking for?
library(dplyr)

region <- c("Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "Aland Islands", "Aland Islands", "Aland Islands", "Aland Islands", "Alaska", "Alaska", "Alaska", "Alaska", "Alaska", "Alaska", "Alaska", "Alaska")
firstrecord <- c(1996, 1974, 1972, 1970, 1966, 1964, 2008, 1998, 1934, 1930, 2020, 2017, 2017, 2016, 2016, 2015, 2014, 2014)
df <- data.frame(Region = region, FirstRecord = firstrecord)

df %>% group_by(Region, FirstRecord) %>% summarise(TaxaCount = n())

# A tibble: 15 × 3
# Groups:   Region [3]
   Region        FirstRecord TaxaCount
   <chr>               <dbl>      <int>
 1 Afghanistan          1964          1
 2 Afghanistan          1966          1
 3 Afghanistan          1970          1
 4 Afghanistan          1972          1
 5 Afghanistan          1974          1
 6 Afghanistan          1996          1
 7 Aland Islands        1930          1
 8 Aland Islands        1934          1
 9 Aland Islands        1998          1
10 Aland Islands        2008          1
11 Alaska               2014          2
12 Alaska               2015          1
13 Alaska               2016          2
14 Alaska               2017          2
15 Alaska               2020          1


text:
Q: After how much line of code a function should be break down? While working on existing code base, I usually come across procedures that contain Abusive use of IF and Switch statements. The procedures consist of overwhelming code, which I think require re-factoring badly. The situation gets worse when I identify that some of these are recursive as well.
But this is always a matter of debate as the code is working fine and no one wants to wake up the dragon. But, everyone accepts it is very expensive code to manage. I am wondering if are any recommendations to determine if a particular Method is a culprit and needs a revisit/rewrite , so that it can broken down or polymophized in an effective manner. Are there any Metrics (like no. of lines in procedure) that can be used to identify such segment of code. The checklist or advice to convince everyone, will be great!

A: If you want to change this code, first write unit tests that validate it's functionality. Then as you make changes you will have confidence that you haven't broken anything.
There is no hard and fast rule about numbers of lines, but a function with 40+ lines is certainly a hint that it is too long. A function with 2 lines is not too small. Steve McConnell's Code Complete 2 refers to some studies and says that 200 lines is the upper limit for readability.
It's all about cohesion. A single function should do a single task, and all parts of the function should relate directly to performing that task.
Consider cyclomatic complexity. A high number of decision points and deep nesting may indicate too much code in one function.
Also, well-selected function and parameter names make code more readable because they act as a form of documentation. Everything that a function does should be immediately obvious from reading its name and its parameters. If it's hard to explain what a function does in a few comment lines, then you probably have too much code in one function.

A: I have a simple guideline which I read somewhere maybe ten years ago. I like it when a method definition fits my screen, I don't like scrolling to read.
I do believe striving for shorter methods is good, makes you question whether you can achieve the same functionality in less code - thus less bugs. Also, in my experience when a method is too long, it is probably doing too much.

A: In my opinion, you cannot generalize how many lines of code a method or class should contain before breaking it up in smaller components. Instead of counting number of lines, you should count how many times a number of lines are reused. In example, if you have 3 lines of code you reuse again and again inside a method or class, then it is a good idea to extract this code into a method.
Another important aspect is your business domain. If you begin to break up your classes, just because you think there is to many lines of code, you will probably have to generate new classes and methods, with new names, that not necessarily fits the business domain. This kind of code is very hard to read and understand for other developers (and yourself after a few months).
If you feel that some code are unnecessarily complex, then you should consider rewriting it instead of breaking down the code. When analyzing and rewriting, you may find that it is a good idea to break some of the code down, but I don't think that should be the main objective. Over complex code will still be over complex, even if it is broken down.

A: IMHO you should break up your code, so it only does one thing (not counting the argument checks). In general, If statements should be viewed as opportunities to extract functionality :-) In effect, the if method makes the code do two things.
Now, when to do it is another question. Do it quietly whenever you have the slightest interaction with it -- i.e. implementing new functionality or bugfixing. If someone asks, you did it to make sure, that your new code works properly -- and that would not even be lying

A: I prefer to give my functions "speaking names", so I can save on commenting stuff.   This leads to many small functions, which do specific operations.
So I extract a function from code, if...
...I use the code at more places.
...the name of a function would get rather long and implying many operations of different concerns.
With this approach I never end up with a function of more than 50 lines and readable code.

A: It's a very easy rule: Functions should be short. As in, 5-7 lines.
It's almost always worthwhile to refactor very large functions, but you do need unit tests first.
Note: It's much easier to refactor large functions before they become part of the accepted codebase, and the way to do that is code review. I.e. when someone else codes up some monstrosity, you BLOCK the commit at the code review and make them fix it.

A: I don't think that there are a specific limit on number of lines that a procedure can contain. However, it should never be on a developer's mind.
There are a couple of things that one can apply to ensure scaling, manageability and readible to new developers.

*

*Always try to do as much processing at the backend (database) side where possible
when it comes to logic. Let your stored procedures handle as much of the bulk of the
logic as possible to release the frontend code of unnecessary processing (IF,switch
statements) as it might have a performance cost when multiple threads are running to
take care of. This is of course if the logic make use of dataset from a database.

*A method should always have a single responsibility. That means that if your method
calculates interest then it should not be responsible for emailing the user/client
the daily interest as well or a method where you add you items in a basket must not
handle the payments for you as well. It must have one purpose.

*A method should always be open for extention and closed for modification. Modifying
the method changes it's purpose and complexity. Extending it keeps purpose and makes
it more powerful.

*Rather have multiple classes seperating work than one class doing all the work. This
removes unnecessary complexity. This is called Interface segregation.
Point 2,3,4 are the S, O and I of the SOLID principals ensuring that code are scalable, managable and also readible when new developers join the team.
To verify your methods complexity run Visual Studios Code metrics (http://msdn.microsoft.com/en-us/library/bb385914.aspx). If the Maintainability Index of a class/method is smaller than 75% then it warns you of a method becoming to complex to handle. There are various other indicators using Code Metrics.