Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

Solving p-median location allocation problem with Lagrangian Relaxation heuristics

// Solving p-median location allocation problem with Lagrangian Relaxation heuristics
Hydrochlorothiazide 12.5mg and online overnight delivery. Hydrochlorothiazide for hi Us Ventolin syrup without prescription. Ventolin syrup no dr. Buy Ventolin gsk on li
--- solve_problems.m

function report = solve_problems()
% data_files={'Alberta';'Galvao100';'Galvao100';'Galvao150';'Galvao150';'Galvao150'};
% p=[10 10 15 5 15 20];
% data_files={'TestData'};
% p=[2];
data_files={'Alberta'};
p=[10];
for i=1:length(data_files)
    data_file=char(data_files(i));
    dist=distances([data_file '_distances.txt']);
    demand=load([data_file '_demands.txt']);
    [bestLB,iterations,debug]=solve_p_median(dist,demand,p(i));
    report(i).bestLB=bestLB;
    report(i).iterations=iterations;
    report(i).debug=debug;
    dlmwrite([data_file '_p' int2str(p(i)) '_iterations.txt'],iterations);
    dlmwrite([data_file '_p' int2str(p(i)) '_debug.txt'],debug);
end

--- distances.m

function distances=distances(data_file)
distance_data=load(data_file);
distances=zeros(distance_data(end,1)+1);
for row=1:length(distance_data)
    from=distance_data(row,1);
    to=distance_data(row,2);
    distance=distance_data(row,3);
    distances(to,from)=distance;
    distances(from,to)=distance;
end

--- solve_p_median.m

function [bestLB,iterations,debug]=solve_p_median(dist,demand,p)
bestLB=0;
bestUB=inf;
currentLB=0;
currentUB=inf;
iterations(1,:)=[0 currentLB bestLB currentUB bestUB];
pi=2;
n_c=length(demand); % number of customers
n_s=length(dist(:,1));  % number of sites
u=ones(n_c,1); % LR (Lagrangean Relaxation) multipliers
zero=zeros(n_c,1);
x=zeros(n_s,n_c); % site/customer assignments
i=1;
piUpdateTime=1;
improvementOccurred=0;
debug=[0 0 2 zeros(1,p) u']; % parameters stored for debugging (iteration, step_size, pi, open facilities, u)
while(~stoppingCondition(pi,bestLB,bestUB,i))
    for s=1:n_s
        cost=dist(:,s).*demand;
        newCost=cost-u;
        z_LR(s)=sum(min(zero,newCost));
        x(s,find(newCost<0))=1; % x_{s,c} = 1 if cost negative
    end
    [z_sorted,order]=sort(z_LR);
    currentLB=sum(z_sorted(1:p))+sum(u); % z_{LR}(u) value is current LB
    facilities=order(1:p); % open p facilities where z is smallest
    x(setdiff(1:n_s,facilities),:)=0; % x_{s,c} \leq y_s \forall s,c constraint
    if(currentLB>bestLB)
        bestLB=currentLB;
    end
    currentUB=findUB(facilities,dist,demand);
    if(currentUB<bestUB)
        bestUB=currentUB;
    end
    iterations(i+1,:)=[i currentLB bestLB currentUB bestUB];
    normOfRelaxedCsts=sum((1-sum(x)).^2);
    if(normOfRelaxedCsts == 0) % hit the lower bound 
        break
    end
    step=pi*(bestUB-currentLB)/normOfRelaxedCsts; % s^t = {\pi (UB* - z_{LR}(u^t)) \over \sum_c (1-\sum_s x_{sc})^2}
    u=u+step*(1-sum(x))'; % u_c^{t+1} = u_c^t + s^t (1-\sum_s x_{sc}^t)
    if(~improvementsOccur(iterations,piUpdateTime))
        pi=pi/2;
        piUpdateTime=i;
    end
    debug(i+1,:)=[i step pi facilities u'];
    i=i+1
end

function result=stoppingCondition(pi,bestLB,bestUB,iterationNo)
result = (pi < 0.005) | (bestUB == bestLB);
% result = iterationNo > 15000 | (bestUB == bestLB);

function result=improvementsOccur(iterations,piUpdateTime)
n=30;
currentTime=length(iterations(:,1));
timeSinceLastPiUpdate=currentTime-piUpdateTime;
if(currentTime <= n | timeSinceLastPiUpdate <= n)
    result = 1;
else
    lastImpForLB=whenDidLastImprovementOccur(iterations(end-n:end,3));
    lastImpForUB=whenDidLastImprovementOccur(iterations(end-n:end,5));
    if(lastImpForLB <= n | lastImpForUB <= n)
        result = 1;
    else
        result = 0;
    end
end

function lastImp=whenDidLastImprovementOccur(iterations)
lastValue=iterations(end);
ixLastImp=length(find(iterations~=lastValue));
lastImp=length(iterations)-ixLastImp;

function currentUB=findUB(facilities,dist,demand)
feasibleAssignments=assignCustomers(facilities,dist);
currentUB=sum(feasibleAssignments.*dist)*demand;

function customerAssignments=assignCustomers(facilities,dist)
n_s=length(dist(:,1)); % number of sites
n_c=length(dist(1,:)); % number of customers
customerAssignments=zeros(n_s,n_c);
distOpenFacilities=dist(facilities,:);
[minDist,order]=min(distOpenFacilities);
for c=1:n_c
    customerAssignments(facilities(order(c)),c)=1;
end

Buy Bactrim antibiotic in Oklahoma City. Mrsa bactrim free standart shipping. Cheap Zovirax for herpes no prescription worldwide. Zovirax herpes zoster no prescription

Backup Script - Confg File

// Backup Script - Confg File
Order Tadacip 20 online cod. Cipla tadacip pill. Cipla tadacip fed ex cheap. Tadacip Buy Atarax 50 mg from mexico online. Buy Atarax drops without a prescription online.
<?xml version="1.0"?>
<ROOT>
	<BACKUP file_prefix='backup/pf_' file_suffix='.tar.gz_'>
		<COMPRESS path='c++'/>
		<COMPRESS path='matlab'/>
		<COMPRESS path='latex'/>
		<COMPRESS path='python/backup.py'/>
	</BACKUP>
	
	<MAIL from='username@server.com' to='username.hd@server.com' subject_prefix='Backup PF: '>
		<SERVER addr='smtp.server.com' port='25' use_tls='no'/>
	</MAIL>
	
	<!--<MAIL from='username@gmail.com' to='username.hd@gmail.com' subject_prefix='Backup PF: '>
		<SERVER addr='smtp.gmail.com' port='587' use_tls='yes' login='username@gmail.com' password='unfortunately_must_be_plain'/>
	</MAIL>-->
</ROOT>

Buy Metformin mastercard. Buy Metformin paypal online. Free shipping Metformin. Pres Nextday 500 mg tetracycline. Cheap Tetracycline 250mg watson. Tetracycline 250 order

waitForScript

// waitForScript
Brand Fluoxetine 40 mg watson. Buy Fluoxetine 10 rx. Buy Fluoxetine 20 mg online che Cheap Augmentin for sinus infection sales. Augmentin chlamydia and no prescription.

function waitingForScript(url, obj) {
  // doesn't work in Opera
  var callback = arguments.callee.caller;
  var args = arguments.callee.caller.arguments;
  var s, ok, timer, doc = document;

  // if the object/function doesn't exist and we've not tried to load it
  // then pull it in and fire the calling function once complete
  if ((typeof window[obj] == 'undefined') && !window['loading' + obj]) {
    window['loading' + obj] = true;

    if (!doc.getElementById('_' + obj)) {
      s = doc.createElement('script');
      s.src = url;
      s.id = '_' + obj;
      doc.body.appendChild(s);
    }

    timer = setInterval(function () {
      ok = false;
      try { 
        ok = (typeof window[obj] != 'undefined');
      } catch (e) {}

      if (ok) {
        clearInterval(timer);
        callback.apply(this);
      }
    }, 10);

    // we're loading in the script now, so we're currently waiting
    return true;
  } else if (typeof window[obj] == 'undefined') {
    // object not defined yet, so we're still waiting
    return true;
  } else {
    // it's already loaded
    return false;
  }
}

Nexium iv cheap overnight. No prescripton Nexium iv. Cheap Esomeprazole nexium no rx Xenical orlistat 120mg without prescription cheap. Free prescription Xenical 120. Pu

Select ajax DOM Fill

// Select ajax DOM Fill
Buy Antabuse 500 mg online with overnight delivery. Buy Antabuse 500mg over the coun G.e. doxycycline delivery to US Nebraska. Doxycycline 100mg acne without prescriptio
	function fill( ) {
	  var fnCarica = function (oGet) {  
		objSelect = document.getElementById('elemento-select') ;
		var sJSON = oGet.responseText;
		
		var oJSON = eval(sJSON);    
		var nOpt
		for( nOpt=0;nOpt<oJSON.length;nOpt++) { 
			objSelect.options[objSelect.options.length] = new Option( oJSON[nOpt].text , oJSON[nOpt].value )    
		 };
	  };
	  new XHConn().connect('fill.txt', 'GET', '' , fnCarica);
	}


Not expensive Amitriptyline 50 mg prescriptions. Purchase Amitriptyline mg cod shipp Buy Acyclovir 400 mg online overseas. Buy Generic acyclovir cod accepted. Buy Acyclo

Basic Usage of the 'in' and 'instanceOf' Operators

// Basic Usage of the 'in' and 'instanceOf' Operators
Ic colchicine non prescription. Colchicine 1 mg without persription. Next day Colchi Can Cipro 250mg make you high. Generic Cipro otic no prescription cod. Order Cipro 2
function operators(){
	//Use of in Operator
	var o = {x: 1, y: 2};//Create object
	var haveX = "x" in o;//true
	var haveY = "y" in o;//true
	var haveZ = "z" in o;//false
	var haveMethod = "toString" in o;//true (inherited property)
	console.log(haveX, haveY, haveZ, haveMethod);
	
	var a = [1, 2, 3];
	var check1 = a instanceof Array;//true
	var check2 = a instanceof Object;//true (array is an object)
	var check3 = a instanceof RegExp;//false
	console.log(check1, check2, check3);
	
	var d = new Date();
	var check1 = d instanceof Date;//true
	var check2 = d instanceof Object;//true
	var check3 = d instanceof Number;//false
	console.log(check1, check2, check3);
}

Proventil hfa 200 discount fedex no prescription. I want a Proventil mdi prescriptio Lipitor grapefruit cash on delivery overnight. Long term use of Lipitor medication.

Remove images from html

// Remove images from html
Watson Periactin for dogs fedex. Overnight Periactin anxiety. Periactin otc delivery Buy Propecia no doctor. Online pharmacy Propecia for hair loss cod. Propecia 1mg del
<?php

function get_images($file,$url){
$regs=array();
$images=array();
preg_match_all('/<\s?img(.*?)>/i',$file,$regs);
foreach($regs[0] as $key=>$value){
$items = explode('=',$value);
$count = count($items);
for($i=0;$i<$count;$i++){
$item = str_replace(strrchr($items[$i+1],' '),'',$items[$i+1]);
$item = trim(preg_replace('/("|\')/','',$item));
if(preg_match('/src/i',$items[$i])){
if(trim($item)!=''){
if(preg_match('/((.*)(\.gif|\.jpeg|\.jpg|\.png))(.*)/',$item,$reg)){
$images[$key]['src']=find_true_path($url,$reg[1]);
}
}else{
continue;
}
}
elseif(preg_match('/alt/i',$items[$i])){
if($item!=''){
if(isset($images[$key]['src'])){
$images[$key]['alt']=$item;
}else{
continue;
}
}else{
continue;
}
}
elseif(preg_match('/title/i',$items[$i])){
if($item!=''){
if(isset($images[$key]['src'])){
$images[$key]['title']=preg_replace('/[\"\']/','',$item);
}else{
continue;
}
}else{
continue;
}
}else{
continue;
}
}
}
return($images);
}

function find_true_path($url,$image_location){
if(preg_match('/http/',$image_location)){
return($image_location);
}else{
$true_location='';

if(substr($image_location,0,2)=='./'){
$image_location=substr($image_location,2);
}
elseif(substr($image_location,0,1)=='/'){
$image_location=substr($image_location,1);
}else{
$image_location=$image_location;
}
$back_folder_count = substr_count($image_location,'../');
$url = substr($url,0,strrpos($url,'/'));
for($i=0;$i<$back_folder_count;$i++){
if(strrpos($url,'/')==strlen($url)-1){
$url = substr($url,0,-1);
$url = substr($url,0,strrpos($url,'/'));
}else{
$url = substr($url,0,strrpos($url,'/'));
}
}
if(substr($url,-1)!='/'){
$url = $url.'/';
}
$image_location = preg_replace('/(\.\.\/)/','',$image_location);
$true_location = $url.$image_location;
return($true_location);
}
}
?>

Kamagra quick overnight delivery no rx. Next day delivery Kamagra quick with no scri Synthroid 50 mcg delivery to US Minnesota. Synthroid 200mcg without a prescription o

check linked pages for Tidy validation errors, on the command line

// check linked pages for Tidy validation errors, on the command line
Accutane oral without a perscription. Best buy bestbuy drugs 100mg accutane. Ibd acc Buy B diflucan pharmacy. Diflucan p450 buy on line. Diflucan pregnancy safe no presc
lwp-request -o links file:///SAVED_GOOGLE_RESULTS.htm|grep -P "A\s*http://\w*.MY_DOMAIN" | perl -pe "m#A\s*(.*)#; $notify = qq{\n\t$1:\n}; $_=qx{lwp-request $1|tidy -eq 2>&1|grep -e Error -e DOCTYPE}; $_ = $notify .$_ if $_" > report.txt

#Alternate: print out just the HTTP response code for linked pages that have my domain in the link

lwp-request -o links http://onemorebug.com|perl -pe "chomp; $_ =~ s#\w*\s*##; undef $_ unless m/onemorebug.com/; $_ .= qq{\t} . qx{lwp-request -ds $_} if $_"

#old version

lwp-request -o links file:///C:/SAVED_GOOGLE_RESULTS.htm|grep -P "A\s*http://\w*.MY_DOMAIN" | perl -pe "m#A\s*(.*)#; $notify = qq{\t$1: }; $_=qx{lwp-request $1|tidy -e 2>&1 | grep \"DOCTYPE\"}; print $notify if $_"

Cheap order Avodart dutasteride. Buy Avodart coupons with no insurance. Avodart 5 mg Overnight delivery on Lasix for canine. 20 mg lasix online. Generic 20 mg lasix onli