def post(self, request, *args, **kwargs): front_url = get_front_url() user = self.get_object() username_field = self.model.USERNAME_FIELD impersonator_user_id = request.user.pk if not front_url: raise Problem(_("No shop configured.")) if user == request.user: raise Problem(_("You are already logged in.")) if not getattr(request.user, "is_superuser", False): raise PermissionDenied if getattr(user, "is_superuser", False) or getattr(user, "is_staff", False): raise PermissionDenied if not getattr(user, "is_active", False): raise Problem(_("This user is not active.")) if not hasattr(user, 'backend'): for backend in django_settings.AUTHENTICATION_BACKENDS: if user == load_backend(backend).get_user(user.pk): user.backend = backend break login(request, user) request.session["impersonator_user_id"] = impersonator_user_id message = _("You're now logged in as {username}").format(username=user.__dict__[username_field]) messages.success(request, message) return HttpResponseRedirect(front_url)
def process_user(self, user): if "E-Commerce.front.apps.auth" not in settings.INSTALLED_APPS: raise Problem(_(u"The `E-Commerce.front.apps.auth` app needs to be enabled for password reset.")) r = RecoverPasswordForm() r.request = self.request if r.process_user(user): messages.success(self.request, _(u"Password recovery email sent to %(email)s") % {"email": getattr(user, 'email', '')}) else: raise Problem(_(u"Sending the password recovery email failed."))
def _handle_set_is_active(self): state = bool(int(self.request.POST["set_is_active"])) if not state: if (getattr(self.object, 'is_superuser', False) and not getattr(self.request.user, 'is_superuser', False)): raise Problem(_("You can not deactivate a superuser.")) if self.object == self.request.user: raise Problem(_("You can not deactivate yourself.")) self.object.is_active = state self.object.save(update_fields=("is_active",)) messages.success(self.request, _("%(user)s is now %(state)s.") % { "user": self.object, "state": _("active") if state else _("inactive") }) return HttpResponseRedirect(self.request.path)
def post(self, request, *args, **kwargs): order = self.object = self.get_object() new_status = OrderStatus.objects.get(pk=int(request.POST["status"])) old_status = order.status if new_status.role == OrderStatusRole.COMPLETE and not order.can_set_complete(): raise Problem(_("Unable to set order as completed at this point")) if new_status.role == OrderStatusRole.CANCELED and not order.can_set_canceled(): raise Problem(_("Paid, shipped, or canceled orders cannot be canceled")) order.status = new_status order.save(update_fields=("status",)) message = _("Order status changed: {old_status} to {new_status}").format( old_status=old_status, new_status=new_status) order.add_log_entry(message, user=request.user, identifier="status_change") messages.success(self.request, message) return HttpResponseRedirect(get_model_url(self.get_object()))
def main(): while True: prob = Problem() #create problem size = prob.loadData( "data01.in") #load data of problem, return board size x = Individ([0] * size) pop = Population(x) alg = Algorithm(pop) alg.readParameters("param.in") printMainMenu() x = input() if x == "1": bestX, sample = alg.run() print(bestX) print(bestX.fitness()) plt.plot(sample) # function to show the plot plt.show() if x == "2": alg.run() sd, m = alg.statistics() print("Standard deviation " + str(sd)) print("Mean " + str(m)) if x == "0": return
def getTSPfromFile(self, filename): try: fh = open(filename, mode='r') except IOError: print("File " + filename + " does not exist, exiting.") exit(0) ncs = False # in node_coord_section of file problem = Problem.Problem() problem.setFilename(filename) for line in fh: if line.startswith("NODE_COORD_SECTION\n"): # Set flag for node coord data follows ncs = True elif line.startswith("NAME"): n = line.rsplit(":") name = str(n[1]).strip() problem.setName(name) elif line.startswith("COMMENT"): l = line.rsplit(":") desc = str(l[1]).strip() problem.setDescription(desc) elif line.startswith("EOF\n"): ncs = False elif ncs: # parse coordinates node = line.split() obj = Node.TSPNode(node[0], node[1], node[2]) problem.addNodeObj(obj) fh.close() return problem
def ship_products(self, shipment, product_quantities): # stocks are managed, do stocks check if self.supplier.stock_managed: insufficient_stocks = {} for product, quantity in product_quantities.items(): if quantity > 0: stock_status = self.get_stock_status(product.pk) if stock_status.stock_managed and stock_status.physical_count < quantity: insufficient_stocks[product] = stock_status.physical_count if insufficient_stocks: formatted_counts = [ _("%(name)s (physical stock: %(quantity)s)") % { "name": force_text(name), "quantity": force_text(quantity) } for (name, quantity) in insufficient_stocks.items() ] raise Problem( _("Insufficient physical stock count for following products: %(product_counts)s") % { "product_counts": ", ".join(formatted_counts) } ) for product, quantity in product_quantities.items(): if quantity == 0: continue sp = shipment.products.create(product=product, quantity=quantity) sp.cache_values() sp.save() shipment.cache_values() shipment.save()
def main(): # Parsing user input parser = ap.ArgumentParser() parser.add_argument('-i', '--input_problem', nargs='?', required=True, help='Input problem file (YAML filename).') parser.add_argument('-s', '--input_sols', nargs='*', required=True, help='Input policy files (YAML filename).') parser.add_argument('-o', '--output', nargs='?', required=True, help='Output policy file (YAML filename).') args = parser.parse_args() # Loading problem problem = Problem(args.input_problem) # Loading solutions sols = {s: None for s in args.input_sols} for sol_filename in sols: with open(sol_filename, 'r') as f: sols[sol_filename] = yaml.load(f.read()) # For each state pol = [] for s in problem.s: action = {} state = {} # For each agent for agent_idx, loc_idx in enumerate(s): # Agent and agent location agent = problem.agents[agent_idx] loc = problem.locs[loc_idx] # Agent state state[agent] = ['at', loc] # Agent Action for sol in sols.values(): for p in sol: if agent in p['action'] and agent in p[ 'state'] and loc in p['state'][agent]: action[agent] = p['action'][agent] # Appending policy entry: new state and corresponding action pol.append({'action': deepcopy(action), 'state': deepcopy(state)}) # Storing merged policy with open(args.output, 'w') as f: yaml.dump(pol, f)
def main(): # Parsing user input parser = ap.ArgumentParser() parser.add_argument('-i', '--input_problem', nargs='?', required=True, help='Input problem file (YAML filename).') parser.add_argument('-s', '--input_solution', nargs='?', required=True, help='Input solution file (HDF5 filename).') parser.add_argument('-o', '--output', nargs='?', required=True, help='Output policy file (YAML filename).') args = parser.parse_args() mdp = Mdp() mdp.load_policy(args.input_solution) raw_policy = mdp.p problem = Problem(args.input_problem) policy = problem.parse_policy(raw_policy) with open(args.output, 'w') as f: yaml.dump(policy, f)
def jobs_load(file_path='./ta000.txt'): """ Load jobs from file.txt in format: 1 2 4 4 6 8 1 3 4 :param file_path: path to .txt file :return: list(Job) """ with open(file_path, 'r') as f: jobs_list = [] lines = [] '''Load NAME and PARAMETERS''' for line in f: lines.append(line) name = lines.pop(0) param = lines.pop(0).rstrip().split(' ') jobs = int(param[0]) machines = int(param[1]) del param """Load times""" for line in lines: if 'str' in line: break values = [int(i) for i in line.split()] jobs_list.append(values) problem = Problem(machines, jobs, jobs_list) return problem
def save(self): parent_product = self.parent_product current_products = set(parent_product.get_package_child_to_quantity_map()) selected_products, removed_products, selected_quantities = self.get_selected_and_removed() with atomic(): try: clear_existing_package(parent_product) parent_product.make_package(package_def=selected_quantities) except ImpossibleProductModeException as ipme: six.raise_from( Problem( _("Unable to make package %(product)s: %(error)s") % {"product": parent_product, "error": ipme} ), ipme ) products_to_add = selected_products - current_products products_to_remove = current_products & removed_products message_parts = [] if products_to_add: message_parts.append(_("New: %d") % len(products_to_add)) if products_to_remove: message_parts.append(_("Removed: %d") % len(products_to_remove)) if message_parts and self.request: messages.success(self.request, ", ".join(message_parts))
def save(self): parent_product = self.parent_product current_products = set(parent_product.variation_children.all()) selected_products, unlinked_products = self.get_selected_and_unlinked() with atomic(): products_to_add = selected_products - current_products products_to_remove = current_products & unlinked_products for child_product in products_to_remove: child_product.unlink_from_parent() for child_product in products_to_add: try: child_product.link_to_parent(parent_product) except ImpossibleProductModeException as ipme: six.raise_from( Problem( _("Unable to link %(product)s: %(error)s") % {"product": child_product, "error": ipme} ), ipme ) message_parts = [] if products_to_add: message_parts.append(_("New: %d") % len(products_to_add)) if products_to_remove: message_parts.append(_("Removed: %d") % len(products_to_remove)) if message_parts and self.request: messages.success(self.request, ", ".join(message_parts))
def post(self, request, *args, **kwargs): # doccov: ignore command = request.POST.get("command") if command: dispatcher = getattr(self, "dispatch_%s" % command, None) if not callable(dispatcher): raise Problem(_("Unknown command %s") % command) dispatch_kwargs = dict(request.POST.items()) rv = dispatcher(**dispatch_kwargs) if rv: return rv self.request.method = "GET" # At this point, we won't want to cause form validation self.build_form() # and it's not a bad idea to rebuild the form return super(EditorView, self).get(request, *args, **kwargs) if request.POST.get("save") and self.form and self.form.is_valid(): self.form.save() self.save_layout() # after we save the new layout configs, make sure to reload the saved data in forms # so the returned get() response contains updated data self.build_form() if request.POST.get("publish") == "1": return self.dispatch_publish() return self.get(request, *args, **kwargs)
def main(): # Parsing user input parser = ap.ArgumentParser() parser.add_argument('-i', '--input_problem', nargs='?', required=True, help='Input problem file (YAML filename).') parser.add_argument('-s', '--input_solution', nargs='?', required=True, help='Input solution file (YAML filename).') parser.add_argument('-o', '--output', nargs='?', required=True, help='Output image file (directory and file prefix).') args = parser.parse_args() with open(args.input_solution, 'r') as f: policy = yaml.load(f.read()) problem = Problem(args.input_problem) problem.plot(policy, args.output)
def dispatch_command(self, request, command): product = self.object if command == "clear_package": clear_existing_package(product) messages.success(self.request, _("Package cleared.")) else: raise Problem("Unknown command: %s" % command) return HttpResponseRedirect(self.get_success_url())
def main3(): prob = Problem() pop = Swarm(prob) ctrl = Controller() res = ctrl.runAlg() fitnessOptim = res.fitness individualOptim = res.position print('Result: The detectet minimum point is (%3.2f %3.2f) \n with function\'s value %3.2f'% \ (individualOptim[0],individualOptim[1], fitnessOptim) )
def createInstances(self): for n in range(1,5): p=Problem(n,[0][0],[0][0]) for i in range (1, 5): for j in range (i+2, 5): s=State(4) s.matrix[i][j]=1 p.expand(p) self.listOfInstances.append(p)
def dispatch(self, request, *args, **kwargs): user = self.get_target_user() token = self.kwargs["token"] valid = (user is not None and self.token_generator.check_token(user, token)) if not valid: raise Problem(_(u"This recovery link is invalid.")) return super(RecoverPasswordConfirmView, self).dispatch(request, *args, **kwargs)
def get_user(self): bind_user_id = self.request.GET.get("user_id") if bind_user_id: bind_user = get_user_model().objects.get(pk=bind_user_id) if PersonContact.objects.filter(user=bind_user).exists(): raise Problem(_("User %(bind_user)s already has a contact", bind_user=bind_user)) else: bind_user = None return bind_user
def timedTest(): testProb = Problem.Problem(0.5, 1.0, 1, 1, 1) testState = Problem.ProblemStateWithRef(0, 1.0, False, 0, None) #timing out the 1 problem start = timer() res = aStarSearchWithRef(testState, testProb) end = timer() print(" Result of A* on MNKY = 1 is ", end - start) src = Problem.coordinate(0.5, 0.5) dest = Problem.coordinate(1.0, 1.0) tDProb = Problem.Problem(dest, src, 1, 1, 1) tDStart = Problem.ProblemStateWithRef(Problem.coordinate(0,0), src, False, 0, None) #timing the one problem on 2D start = timer() #res = aStarSearchWithRefTD(tDStart, tDProb ) end = timer()
def recent_submission(self, n): submission_keys = list(self.submissions.keys()) # print(submission_keys[0]) submission = self.submissions[submission_keys[-n]] problem = Problem.Problem(submission["problem"]) time = submission["time"] memory = submission["memory"] points_earned = submission["points"] verdict = submission["result"] return Submission.Submission(problem, verdict, time, points_earned, memory)
def dispatch_command(self, request, command): product = self.object if command == "unvariate": product.clear_variation() messages.success(self.request, _("Variation cleared.")) elif command == "simplify": product.simplify_variation() messages.success(self.request, _("Variation simplified.")) else: raise Problem("Unknown command: %s" % command) return HttpResponseRedirect(self.get_success_url())
def html_to_pdf(html, stylesheet_paths=[]): if not weasyprint: raise Problem(_("Could not create PDF since Weasyprint is not available. Please contact support.")) stylesheets = [] for stylesheet_path in stylesheet_paths: stylesheets.append(weasyprint.CSS(string=_fetch_static_resource_str(stylesheet_path))) return weasyprint.HTML( string=html, url_fetcher=_custom_url_fetcher ).write_pdf( stylesheets=stylesheets )
def handle_post_delete_file(self, data): shop = get_shop(self.request) file = _get_file_query(shop).get(pk=data["id"]) if _is_file_shared(file): message = _("Can not delete shared file.") return JsonResponse({"success": False, "message": message}) try: file.delete() except IntegrityError as ie: raise Problem(str(ie)) return JsonResponse({"success": True, "message": _("File deleted.")})
def inputFileToProblem(pb: Problem) -> None: with open(file) as f: nbRows, nbCols, nbVehicules, nbRides, bonus, maximumTime = f.readline( ).split() rides = [] for line in f: print(line) a, b, x, y, s, fin = line.split() startPoint = Point.Point(a, b) finishPoint = Point.Point(x, y) rides.append(Ride(startPoint, finishPoint, s, fin)) map = Map(nbRows, nbCols) return Problem(map, nbVehicules, rides, maximumTime)
def __init__(self, **kwargs): super(ReloadMethodForm, self).__init__(**kwargs) self.reload_methods = list(self.get_viable_reload_methods()) if not self.reload_methods: raise Problem(_("There are no viable reload methods available. Please contact your system administrator.")) self.fields["reload_method"] = forms.ChoiceField( choices=[(rm.identifier, rm.title) for rm in self.reload_methods], label=_("Reload Method"), initial=self.reload_methods[0].identifier, widget=forms.RadioSelect )
def parse_problems(filename): f = open(filename, "r") s = f.read() s = s.split("\n\n")[1:] # strip the first line f.close() problems = [] for paragraph in s: if len(paragraph) > 0: problems.append(Problem(paragraph)) return problems
def __init__(self, changing_user, target_user, *args, **kwargs): super(PasswordChangeForm, self).__init__(*args, **kwargs) self.changing_user = changing_user self.target_user = target_user if getattr(self.target_user, 'is_superuser', False) and not getattr(self.changing_user, 'is_superuser', False): raise Problem(_("You can not change the password of a superuser.")) if not ( self.changing_user == self.target_user or getattr(self.target_user, 'is_superuser', False) ): # Only require old password when changing your own or a superuser's password. self.fields.pop("old_password")
def main1(): #random.seed(datetime.now()) prob = Problem() pop = Population() alg = Algorithm(prob, pop) alg.run() res = alg.population.v[0] fitnessOptim = res.fittness(prob) individualOptim = res.x print('Result: The detectet minimum point is (%3.2f %3.2f) \n with function\'s value %3.2f'% \ (individualOptim[0],individualOptim[1], fitnessOptim) )
def timedTest(): origin = Problem.coordinate(0,0) src1 = Problem.coordinate(0.5,0) dest1 = Problem.coordinate(1.0,0) testProblem = Problem.Problem(dest1,src1,1,1,1) testState = Problem.ProblemStateWithRef(origin, dest1, False, 0,None) start = timer() bfs = BFSTD(testState, testProblem) end = timer() print("Time taken to run Breadth first search 1D: ", end - start) src2 = Problem.coordinate(0.5, 0.5) dest2 = Problem.coordinate(1.0, 1.0) tDProb = Problem.Problem(dest2, src2, 1, 1, 1) tDStart = Problem.ProblemStateWithRef(Problem.coordinate(0,0), src2, False, 0, None) # timing the one problem on 2D start = timer() bfs2 = BFSTD(tDStart, tDProb) end = timer() print("Time taken to run Breadth first search2D: ", end - start)