Skip to content

Instantly share code, notes, and snippets.

@rangalo
Created August 22, 2010 10:13
Show Gist options
  • Save rangalo/543617 to your computer and use it in GitHub Desktop.
Save rangalo/543617 to your computer and use it in GitHub Desktop.
Division without / operator
class Divide {
public static int divide(int dividend, int divisor) throws Exception {
int result = 0;
int sign = 1;
if (divisor == 0) {
System.out.println("Divide by 0 error");
throw new Exception("Divide by 0");
}
if (divisor < 0 ) {
sign *= -1;
divisor *= -1;
}
if (dividend < 0) {
sign *= -1;
dividend *= -1;
}
while (dividend > divisor) {
dividend -= divisor;
result++;
}
return result * sign;
}
public static void main(String[] args) {
try {
int res = Divide.divide(-7,-3);
System.out.println(res);
}
catch(Exception e) {
e.printStackTrace();
}
}
}
@Tam-le-nho-cuoc
Copy link

Tam-le-nho-cuoc commented May 10, 2022

public function AddForm()
{
return $this->render('address/city-add');
}
public function add()
{
$name = $_POST['name_city'] ?? null;
$fag = 1;

    if ($name != null) {
        $pattern = "/^[a-z 'ÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚĂĐĨŨƠàáâãèéêìíòóôõùúăđĩũơƯĂẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼỀỀỂ ưăạảấầẩẫậắằẳẵặẹẻẽềềểỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪễệỉịọỏốồổỗộớờởỡợụủứừỬỮỰỲỴÝỶỸửữựỳỵỷỹ]+$/i";
        if (!preg_match($pattern, $name)) {
            session()->setFlash(\FLASH::ERROR, 'Invalid city name! Only unicode letter and space are allowed and maximum length is 191');
            $fag = 0;
        } else {
            $city = City::wherename($name)->first();
            if (!$city && $fag == 1) {
                $city = new City();
                $city->name = $name;
                $city->save();
                session()->setFlash(\FLASH::SUCCESS, 'City added successfully!');
            } else {
                session()->setFlash(\FLASH::WARNING, 'City name already existed!');
                
            }
        }
    } else {
        session()->setFlash(\FLASH::ERROR, 'City name must not be null!');
       
    }
    return $this->AddForm();
}
public function city_list()
{
    $items = City::paginate($this->getPerPage());
    $total = City::count();
    $pageper=$this->getPerPage();
    
    if($pageper==null) $pageper=15;
    $paginator = new Paginator($this->request, $items, $total,$pageper);
    $paginator->appends('city_id', '2');
    $paginator->onEachSide(2);

    if ($this->request->ajax()) {
        $html = $this->view->render('address/city-list', [
                                    'items' => $items,
                                    'paginator' => $paginator
                                ]);
        return $this->json([
            'data' => $html
        ]);
    }
    return $this->render('address/city', [
                        'items' => $items,
                        'paginator' => $paginator
                    ]);
}
public function delete()
{
    $id = $this->request->post('id');
    $city = City::find($id);
   
    if ($this->request->ajax()) {
        if ($city) {
            if ($city->delete()) {
                return $this->json( ['message'   => $city->name . 'has been deleted successfully.'], Response::HTTP_OK);
            }
            else {
                return $this->json(['message' => 'Unable to delete city'], Response::HTTP_BAD_REQUEST);    
            }
        }
        return $this->json([ 'message' => 'city ID dose not exists!'], Response::HTTP_NOT_FOUND);
    }

    if ($city) {
        if ($city->delete()) {

            session()->setFlash(\FLASH::SUCCESS, $city->name . 'has been deleted successfully.');
        }
        else {
            session()->setFlash(\FLASH::ERROR, "Unable to delete city");
        }
    }
    else {
        session()->setFlash(\FLASH::ERROR, "city D does not exists!");
    }

    $return_url = $this->request->post('return_url', '/home');
   
    return $this->redirect($return_url);
}

public function showFormedit($id)
{      
    
    $city = City::find($id);
    if($city==null){
       $this->city_list();
    }   
    else
        return $this->render('address/city-edit',['city'=>$city]);
         
}
public function edit()
{
    
    $id = $this->request->post('city_id');
    $city = City::find($id);
    $name = $_POST['name_city'];
    $fag=1;
    if ($city) {
        if ($name != '') {
            $pattern = "/^[a-z 'ÀÁÂÃÈÉÊÌÍÒÓÔÕÙÚĂĐĨŨƠàáâãèéêìíòóôõùúăđĩũơƯĂẠẢẤẦẨẪẬẮẰẲẴẶẸẺẼỀỀỂ ưăạảấầẩẫậắằẳẵặẹẻẽềềểỄỆỈỊỌỎỐỒỔỖỘỚỜỞỠỢỤỦỨỪễệỉịọỏốồổỗộớờởỡợụủứừỬỮỰỲỴÝỶỸửữựỳỵỷỹ]+$/i";
         
            if (!preg_match($pattern, $name)) {
                session()->setFlash(\FLASH::ERROR, 'Invalid city name! Only letter and space are allowed and maximum length is 191');
                $fag=0;
            }
            else{
                $city->name = $name;
                $city->save();
                session()->setFlash(\FLASH::SUCCESS, 'City name changed successfully!');
            }
        } else {
            session()->setFlash(\FLASH::ERROR, 'City name can not null!');
            $fag=0;
        }
    } else {
        session()->setFlash(\FLASH::ERROR, 'City id not found!');
        $fag=0;
    }
    
    if ($fag!=0){
        redirect('/city/list');
    }
    return $this->render('address/city-edit',['city'=>$city]);
}

@Tam-le-nho-cuoc
Copy link

use SoftDeletes;

protected $table = 'cities';

/**
 * Use timestamps 
 *
 * @var boolean
 */
public $timestamps = true;


protected $fillable = ['name'];

protected $dates = [];

/**
 * districts
 *
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function districts()
{
    return $this->hasMany(District::class, 'city_id');
}

public function wards()
{
    return $this->hasManyThrough(Ward::class, District::class);
}

@Tam-le-nho-cuoc
Copy link

Tam-le-nho-cuoc commented May 10, 2022

$(document).ready(function() {
  
    $(document).on('click', '.delete-city', function(event) {
      
        event.preventDefault();
       
        showConfirm(event.currentTarget);

       
    })
});


function showConfirm(e) {
    Swal.fire({
        title: 'Are you sure?',
        html: "<p>Delete <b>" + $(e).data('name') + "</b></p> <p>You won't be able to revert this!</p>",
        icon: 'warning',
        showCancelButton: true,
        cancelButtonColor: '#3085d6',
        confirmButtonColor: '#d33',
        confirmButtonText: 'Confirm'
    }).then((result) => {
        if (result.isConfirmed) {
            ajaxDelete(e);
        }
    });
}


function ajaxDelete(e) {
    var url = $(e).prop('href');
    var id = $(e).data('id');
    $.ajax({
        method: "POST",
        url: url,
        data: {
            id: id
        }
    }).done(function(response) { 
        let reload_url = $(e).data('return-url');
      
        let target = $('#city-list');
        reloadWardList(reload_url, target);
        Swal.fire(
            'Deleted!',
            response.message,
            'success'
        );

    }).fail(function(response) { 
        Swal.fire(
            'Error',
            response.responseJSON.message,
            'error'
        )
    });
}


function reloadWardList(url, target) {
    $.ajax({
        method: 'GET',
        url: url
    }).done(function(response) {
        $(target).html(response.data);
    }).fail(function() {
        Swal.fire(
            'Error',
            'Unable to reload the Ward list. Try again.',
            'error'
        )
    });
}

@Tam-le-nho-cuoc
Copy link

Tam-le-nho-cuoc commented May 10, 2022

Router::get('/city/add','App\Controllers\CityController@AddForm');

Router::post('/city/add','App\Controllers\CityController@add');
Router::get('/city/list','App\Controllers\CityController@city_list');
Router::post('/city/delete','App\Controllers\CityController@delete');
Router::get('/city/edit/(\d+)','App\Controllers\CityController@showFormedit');
Router::post('/city/edit','App\Controllers\CityController@edit');

@Tam-le-nho-cuoc
Copy link

<VirtualHost *:80>
DocumentRoot "D:/htdocs/mvc/public/"
ServerName mvc.local
ErrorLog "error.log"
CustomLog "access.log" common
<Directory "D:/htdocs/mvc/public/">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
Allow from all
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?url=$1

@Tam-le-nho-cuoc
Copy link

Tam-le-nho-cuoc commented May 11, 2022

<VirtualHost *:80>
DocumentRoot "D:/htdocs/mvc/public/"
ServerName mvc.local
ErrorLog "error.log"
CustomLog "access.log" common
<Directory "D:/htdocs/mvc/public/">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride All
Require all granted
Allow from all
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ index.php?url=$1

helllo moi ng

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment