language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
PHP | UTF-8 | 1,290 | 2.671875 | 3 | [] | no_license | <?php
/**
* This file is part of Bamboo CMS Application Framework.
*
* (c) Ahmad Fajar <ahmad.fajar234@yahoo.com>
*
*/
// namespace Bamboo\CoreBundle\Thumbnail;
/**
* Class ThumbnailFactory
*
* @author Ahmad Fajar
* @since 08/02/2014, modified: 14/03/1014 01:26
* @version 1.0.0
* @category CoreBundle
* @package Bamboo\CoreBundle\Thumbnail
*/
final class ThumbnailFactory
{
/**
* Create a thumbnail interface in a handy ways.
*
* @param null|string $filename the image location
* @param array $options processing parameters
* @param bool $isDataStream
*
* @return ThumbnailInterface
* @throws \RuntimeException
*/
public static function create($filename = null, array $options = array(), $isDataStream = false)
{
if (extension_loaded('gmagick')) {
return new GmagickThumbnail($filename, $options, $isDataStream);
}
elseif (extension_loaded('imagick')) {
return new ImagickThumbnail($filename, $options, $isDataStream);
}
elseif (extension_loaded('gd')) {
return new GDThumbnail($filename, $options, $isDataStream);
}
throw new \RuntimeException(
"The installed PHP doesn't support image manipulation. Please install gmagick or imagick or GD extension.",
RUNTIME_ERROR
);
}
} |
Java | UTF-8 | 2,350 | 2.234375 | 2 | [] | no_license | package com.ao.recyclerview_snapping.fork;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.ao.recyclerview_snapping.R;
import org.w3c.dom.Text;
import java.util.List;
public class Adapter_forf extends RecyclerView.Adapter<Adapter_forf.View_Holder> {
List<Contact_fork> contact_forks;
Context context;
public Adapter_forf(List<Contact_fork> contact_forks, Context context) {
this.contact_forks = contact_forks;
this.context = context;
}
@NonNull
@Override
public View_Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_fork, parent,false);
return new View_Holder(view);
}
@Override
public void onBindViewHolder(@NonNull View_Holder holder, final int position) {
final Contact_fork id_contact_fork = contact_forks.get(position);
holder.nemeFork1.setText(id_contact_fork.nameOne);
holder.nemeFork2.setText(id_contact_fork.nameTow);
if (onClickItem != null){
holder.nemeFork1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onClickItem.OnItemClick(position, id_contact_fork);
}
});
}
if (onClickItem2 != null){
holder.nemeFork2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onClickItem2.OnItemClick(position, id_contact_fork);
}
});
}
}
public void setOnClickItem(OnClickItem onClickItem) {
this.onClickItem = onClickItem;
}
OnClickItem onClickItem;
OnClickItem onClickItem2;
public void setOnClickItem2(OnClickItem onClickItem2) {
this.onClickItem2 = onClickItem2;
}
public interface OnClickItem{
void OnItemClick(int pos, Contact_fork contact_fork);
}
@Override
public int getItemCount() {
if ( contact_forks == null)return 0;
return contact_forks.size();
}
public class View_Holder extends RecyclerView.ViewHolder {
TextView nemeFork1,nemeFork2;
public View_Holder(@NonNull View itemView) {
super(itemView);
nemeFork1 = itemView.findViewById(R.id.textfork1);
nemeFork2 = itemView.findViewById(R.id.textfork2);
}
}
}
|
Python | UTF-8 | 7,198 | 2.828125 | 3 | [
"MIT"
] | permissive | from flask import Flask, render_template, request, redirect, session, flash
# the "re" module will let us perform some regular expression operations
import re
# create a regular expression object that we can use run operations on
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$')
# import the Connector function
from mysqlconnection import MySQLConnector
app = Flask(__name__)
app.secret_key = 'KeepItSecretKeepItSafe'
# connect and store the connection in "mysql" note that you pass the database name to the function
mysql = MySQLConnector(app, 'full_friends')
# an example of running a query
# our index route will handle rendering our form
@app.route('/')
def index():
session['what_page'] = "index"
if not 'full_list' in session:
session['full_list'] = []
if not 'email' in session:
session['email'] = ""
if not 'first_name' in session:
session['first_name'] = ""
if not 'last_name' in session:
session['last_name'] = ""
if not 'returner' in session:
session['returner'] = False
if not 'what_page' in session:
session['what_page'] = ""
if not 'current_id' in session:
session['current_id'] = -1
return render_template("index.html")
@app.route('/friends', methods=['GET'])
def friend_render():
session['what_page'] = "friend_render"
return render_template("friends.html")
# this route will handle our form submission
# notice how we defined which HTTP methods are allowed by this route
@app.route('/friends', methods=['POST'])
def create():
# do some validations here.
session['what_page'] = "create"
session['returner'] = False # Use this so you add multiple flash messages at once.
if len(request.form['email']) < 1:
flash("You must type in an email address.")
session['returner'] = True
elif not EMAIL_REGEX.match(request.form['email']):
flash("You must type in a valid email address.")
session['returner'] = True
if len(request.form['first_name']) < 1:
flash("You must type in your first name.")
session['returner'] = True
elif not str.isalpha(str(request.form['first_name'])):
flash("Your first name cannot contain numbers or symbols. Sorry, we're biased like that.")
session['returner'] = True
if len(request.form['last_name']) < 1:
flash("You must type in your last name.")
session['returner'] = True
elif not str.isalpha(str(request.form['last_name'])): # Done twice in rare case of last name not written but first name written correctly.
flash("Your last name cannot contain numbers or symbols. Sorry, we're biased like that.")
session['returner'] = True
# Set session variables.
session['email'] = request.form['email']
session['first_name'] = request.form['first_name']
session['last_name'] = request.form['last_name']
# redirect if you passed validation!
if session['returner'] == False:
mysql.query_db("INSERT into friends (first_name, last_name, email, created_at) values ('"+session['first_name']+"','"+session['last_name']+"','"+session['email']+"',now())")
flash(""+session['first_name']+" "+session['last_name']+" is now on your friends list!")
results = []
for item in mysql.query_db("SELECT * FROM friends"):
results.append(item['id'])
results.append(item['first_name'])
results.append(item['last_name'])
results.append(item['email'])
results.append(item['created_at'])
session['full_list'] = results
return redirect('/')
# If you got this far, you didn't pass validation. Aw.
return redirect('/friends')
@app.route('/friends/<id>/edit', methods=['GET'])
def edit(id):
# do some validations here.
session['what_page'] = "edit"
session['current_id'] = id
return render_template("friends.html")
@app.route('/friends/<id>', methods=['POST'])
def update(id):
# do some validations here.
session['what_page'] = "update"
session['returner'] = False # Use this so you add multiple flash messages at once.
if len(request.form['email']) < 1:
flash("You must type in an email address.")
session['returner'] = True
elif not EMAIL_REGEX.match(request.form['email']):
flash("You must type in a valid email address.")
session['returner'] = True
if len(request.form['first_name']) < 1:
flash("You must type in your first name.")
session['returner'] = True
elif not str.isalpha(str(request.form['first_name'])):
flash("Your first name cannot contain any numbers, spaces, or symbols. Sorry, we're biased like that.")
session['returner'] = True
if len(request.form['last_name']) < 1:
flash("You must type in your last name.")
session['returner'] = True
elif not str.isalpha(str(request.form['last_name'])): # Done twice in rare case of last name not written but first name written correctly.
flash("Your last name cannot contain any numbers, spaces, or symbols. Sorry, we're biased like that.")
session['returner'] = True
# Set session variables.
session['email'] = request.form['email']
session['first_name'] = request.form['first_name']
session['last_name'] = request.form['last_name']
# redirect if you passed validation!
if session['returner'] == False:
# REMEMBER: ID needs to be connected to the database! Should grab ID from database...
mysql.query_db("UPDATE `full_friends`.`friends` SET `first_name`='"+request.form['first_name']+"', `last_name`='"+request.form['last_name']+"', `email`='"+request.form['email']+"' WHERE `id`='"+id+"'")
# mysql.query_db("INSERT into friends (first_name, last_name, email, created_at) values ('"+session['first_name']+"','"+session['last_name']+"','"+session['email']+"',now())")
flash("Your friend "+request.form['first_name']+" "+request.form['last_name']+" has been updated successfully.")
results = []
for item in mysql.query_db("SELECT * FROM friends"):
results.append(item['id'])
results.append(item['first_name'])
results.append(item['last_name'])
results.append(item['email'])
results.append(item['created_at'])
session['full_list'] = results
return redirect('/')
# If you got this far, you didn't pass validation. Aw.
return redirect( '/friends/'+id+'/edit')
@app.route('/friends/<id>/delete', methods=['POST'])
def delete(id):
# do some validations here.
session['what_page'] = "delete"
session['returner'] = True
# Set session variables.
flash("You've successfully deleted one of your friends.")
mysql.query_db("DELETE FROM `full_friends`.`friends` WHERE `id`='"+session['current_id']+"'")
results = []
for item in mysql.query_db("SELECT * FROM friends"):
results.append(item['id'])
results.append(item['first_name'])
results.append(item['last_name'])
results.append(item['email'])
results.append(item['created_at'])
session['full_list'] = results
return redirect("/")
if __name__ == "__main__":
app.run(debug=True) # run our server
|
C# | UTF-8 | 3,789 | 2.90625 | 3 | [] | no_license | using HackerNewsScraper.HackerNewApi;
using HackerNewsScraper.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
namespace HackerNewsScraper.Services
{
public class GetStories
{
public void Execute(string api)
{
var storyIds = new List<int>();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://hacker-news.firebaseio.com/v0/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = client.GetAsync(api).Result;
if (response.IsSuccessStatusCode)
{
storyIds = JsonSerializer.Deserialize<List<int>>(response.Content.ReadAsStringAsync().Result);
}
else
{
Console.WriteLine("Internal server Error");
}
var existingStories = new HackerNewsContext().Story.Select(x => x.StoryId).ToList();
foreach (var storyId in storyIds.Except(existingStories))
{
var story = new HackerNewsStory();
HttpResponseMessage responseStory = client.GetAsync($"item/{storyId}.json").Result;
if (responseStory.IsSuccessStatusCode)
{
story = JsonSerializer.Deserialize<HackerNewsStory>(responseStory.Content.ReadAsStringAsync().Result);
if(story == null)
{
continue;
}
}
else
{
Console.WriteLine("Internal server Error");
}
try
{
var currentDateTime = DateTime.Now;
using (var context = new HackerNewsContext())
{
var newStory = new Story
{
StoryId = story.id,
Title = story.title,
CreatedBy = story.by,
Type = story.type,
Url = story.url,
Score = story.score,
Descendants = story.descendants,
Time = story.time,
CreatedDate = currentDateTime
};
if (story.kids != null && story.kids.Any())
{
foreach (var commentId in story.kids)
{
newStory.Comment.Add(new Comment
{
CommentId = commentId,
CreatedDate = currentDateTime
});
}
}
context.Story.Add(newStory);
context.SaveChanges();
Console.WriteLine($"Added Story {newStory.Title}");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
}
}
|
TypeScript | UTF-8 | 10,273 | 2.78125 | 3 | [
"MIT",
"LicenseRef-scancode-public-domain"
] | permissive | /*!
* Copyright (c) Microsoft Corporation and contributors. All rights reserved.
* Licensed under the MIT License.
*/
import { assert } from '@fluidframework/common-utils';
import { copyPropertyIfDefined, fail } from './Common';
import { NodeId, TraitLabel } from './Identifiers';
import { Delta, Forest, isParentedForestNode } from './Forest';
import { NodeData, Side } from './persisted-types';
/**
* Specifies the location of a trait (a labeled sequence of nodes) within the tree.
* @public
*/
export interface TraitLocation {
readonly parent: NodeId;
readonly label: TraitLabel;
}
/**
* An immutable view of a distributed tree node.
* @public
*/
export interface TreeViewNode extends NodeData<NodeId> {
/** The IDs of the children under this node */
readonly traits: ReadonlyMap<TraitLabel, readonly NodeId[]>;
/** The parent and trait under which this node resides. Undefined iff this is the root node of the tree (i.e. {@link initialTree}). */
readonly parentage?: TraitLocation;
}
/**
* Index of a place within a trait.
* 0 = before all nodes,
* 1 = after first node,
* etc.
* @public
*/
export type PlaceIndex = number & { readonly PlaceIndex: unique symbol };
/**
* Index of a node within a trait.
* 0 = first node,
* 1 = second node,
* etc.
* @public
*/
export type TraitNodeIndex = number & { readonly TraitNodeIndex: unique symbol };
/**
* A place within a particular `TreeView` that is anchored relative to a specific node in the tree, or relative to the outside of the trait.
* Valid iff 'trait' is valid and, if provided, sibling is in the Location specified by 'trait'.
* @public
*/
export interface TreeViewPlace {
readonly sibling?: NodeId;
readonly side: Side;
readonly trait: TraitLocation;
}
/**
* Specifies the range of nodes from `start` to `end` within a trait within a particular `TreeView`.
* Valid iff start and end are valid and are within the same trait.
* @public
*/
export interface TreeViewRange {
readonly start: TreeViewPlace;
readonly end: TreeViewPlace;
}
/**
* Contains some redundant information. Use only in computations between edits. Do not store.
* @public
*/
export interface NodeInTrait {
readonly trait: TraitLocation;
readonly index: TraitNodeIndex;
}
/**
* A view of a distributed tree.
* @public
*/
export abstract class TreeView {
public readonly root: NodeId;
protected readonly forest: Forest;
private readonly rootNode: TreeViewNode;
/**
* A cache of node's index within their parent trait.
* Used to avoid redundant linear scans of traits.
* Not shared across views; initialized to empty each time a TreeView is created.
*/
private traitIndicesCache?: Map<NodeId, TraitNodeIndex>;
protected constructor(root: NodeId, forest: Forest) {
this.root = root;
this.forest = forest;
this.rootNode = this.getViewNode(root);
}
/** @returns the number of nodes in this view */
public get size(): number {
return this.forest.size;
}
/** @returns true iff a node with the given id exists in this view */
public hasNode(id: NodeId): boolean {
return this.forest.has(id);
}
/**
* @returns the index just after place (which specifies a location between items).
* Performance note: this is O(siblings in trait).
*/
public findIndexWithinTrait(place: TreeViewPlace): PlaceIndex {
if (place.sibling === undefined) {
return this.getIndexOfSide(place.side, place.trait);
}
return getIndex(place.side, this.getIndexInTrait(place.sibling));
}
/** @returns the node associated with the given id in this view. Fails if the node does not exist in this view. */
public getViewNode(id: NodeId): TreeViewNode {
return this.tryGetViewNode(id) ?? fail('NodeId not found');
}
/** @returns the node associated with the given id in this view, or undefined if the node does not exist in this view */
public tryGetViewNode(id: NodeId): TreeViewNode | undefined {
const forestNode = this.forest.tryGet(id);
if (forestNode !== undefined && isParentedForestNode(forestNode)) {
const viewNode: TreeViewNode = {
definition: forestNode.definition,
identifier: forestNode.identifier,
traits: forestNode.traits,
parentage: {
label: forestNode.traitParent,
parent: forestNode.parentId,
},
};
copyPropertyIfDefined(forestNode, viewNode, 'payload');
return viewNode;
}
return forestNode;
}
/**
* @returns the label of the trait under which a node with the given id resides. Fails if the node does not exist in this view or if
* it is the root node.
*/
public getTraitLabel(id: NodeId): TraitLabel {
return this.forest.getParent(id).traitParent;
}
/**
* @returns the label of the trait under which a node with the given id resides, or undefined if the node is not present in this
* view or if it is the root node
*/
public tryGetTraitLabel(id: NodeId): TraitLabel | undefined {
return this.forest.tryGetParent(id)?.traitParent;
}
/**
* @returns the parent of the node with the given id. Fails if the node does not exist in this view or if it is the root node.
*/
public getParentViewNode(id: NodeId): TreeViewNode {
const parentInfo = this.forest.getParent(id);
return this.getViewNode(parentInfo.parentId);
}
/**
* @returns the parent of the node with the given id. Returns undefined if the node does not exist in this view or if it is the root
* node.
*/
public tryGetParentViewNode(id: NodeId): TreeViewNode | undefined {
const parentInfo = this.forest.tryGetParent(id);
if (parentInfo === undefined) {
return undefined;
}
return this.getViewNode(parentInfo.parentId);
}
/**
* @returns the trait location of the node with the given id. Fails if the node does not exist in this view or of it is the root
* node
*/
public getTraitLocation(id: NodeId): TraitLocation {
const parentData = this.forest.getParent(id);
return {
parent: parentData.parentId,
label: parentData.traitParent,
};
}
/**
* @returns the trait location of the node with the given id, or undefined if the node does not exist in this view or if it is the root
* node
*/
public tryGetTraitLocation(id: NodeId): TraitLocation | undefined {
const parentData = this.forest.tryGetParent(id);
if (parentData === undefined) {
return undefined;
}
return {
parent: parentData.parentId,
label: parentData.traitParent,
};
}
/**
* @returns the index within the trait under which the node with the given id resides. The node must exist in this view and must have a
* parent.
* Performance note: this is O(siblings in trait).
*/
public getIndexInTrait(id: NodeId): TraitNodeIndex {
const index = this.tryGetIndexInTrait(id);
return index ?? fail('ID does not exist in the forest.');
}
/**
* @returns the index within the trait under which the node with the given id resides, or undefined if the node does not exist in this
* view or does not have a parent.
* Performance note: this is O(siblings in trait).
*/
public tryGetIndexInTrait(id: NodeId): TraitNodeIndex | undefined {
const cachedIndex = this.traitIndicesCache?.get(id);
if (cachedIndex !== undefined) {
return cachedIndex;
}
const parentData = this.forest.tryGetParent(id);
if (parentData === undefined) {
return undefined;
}
const parent = this.forest.tryGet(parentData.parentId);
if (parent === undefined) {
return undefined;
}
const trait = parent.traits.get(parentData.traitParent) ?? fail('inconsistent forest: trait parent not found');
let foundIndex: TraitNodeIndex | undefined;
if (trait.length === 0) {
return foundIndex;
}
this.traitIndicesCache ??= new Map();
for (let i = 0; i < trait.length; i++) {
const nodeInTrait = trait[i];
const index = i as TraitNodeIndex;
this.traitIndicesCache.set(nodeInTrait, index);
if (nodeInTrait === id) {
foundIndex = index;
}
}
return foundIndex;
}
/**
* @returns the trait at the given location. If no such trait exists, returns an empty trait.
*/
public getTrait(traitLocation: TraitLocation): readonly NodeId[] {
return this.getViewNode(traitLocation.parent).traits.get(traitLocation.label) ?? [];
}
/** Asserts that the view's internal state is consistent. Useful for testing/validation. */
public assertConsistent(): void {
this.forest.assertConsistent();
}
public [Symbol.iterator](): IterableIterator<TreeViewNode> {
return this.iterateNodeDescendants(this.rootNode);
}
/** @returns true iff the given view is equal to this view */
public abstract equals(view: TreeView): boolean;
/**
* @returns true iff the given view's forest of nodes is equivalent to this view's forest of nodes
* @param strict - if true, the views' forests must be the same object, otherwise they must merely be equivalent
*/
public hasEqualForest(view: TreeView, strict = false): boolean {
if (this.root === view.root) {
// TODO:#49100:Perf: make this faster and/or remove use by PrefetchingCheckout.
return strict ? this.forest === view.forest : this.forest.equals(view.forest);
}
return false;
}
private *iterateNodeDescendants(node: TreeViewNode): IterableIterator<TreeViewNode> {
yield node;
for (const label of [...node.traits.keys()].sort()) {
const trait = node.traits.get(label);
for (const childId of trait ?? fail('Expected trait with label')) {
const child = this.getViewNode(childId);
yield* this.iterateNodeDescendants(child);
}
}
}
private getIndexOfSide(side: Side, traitLocation: TraitLocation): PlaceIndex {
return side === Side.After ? (0 as PlaceIndex) : (this.getTrait(traitLocation).length as PlaceIndex);
}
/**
* Calculate the difference between two `TreeView`s
* @param view - the other view to compare to this one
* @returns A {@link Delta} which nodes must be changed, added, and removed to get from `this` to `view`.
* The views must share a root.
*/
public delta(view: TreeView): Delta<NodeId> {
assert(this.root === view.root, 0x63d /* Delta can only be calculated between views that share a root */);
return this.forest.delta(view.forest);
}
}
function getIndex(side: Side, index: TraitNodeIndex): PlaceIndex {
// eslint-disable-next-line @typescript-eslint/restrict-plus-operands
return (side + index) as PlaceIndex;
}
|
C | UTF-8 | 1,853 | 3.03125 | 3 | [] | no_license | int randomNum() {
int num;
num = rand() % 10;
return num;
}
void inicializaLista(lista* L) {
int i = 0;
L->disp = 0;
L->prim = -1;
for( ; i < MAX - 1 ; i++)
L->elementos[i].prox = i + 1;
L->elementos[i].prox = -1;
}
lista FLVazia(lista* L) {
int i = 0;
while(i < MAX) {
L->elementos[i].elem = -1;
i++;
}
return *L;
}
boolean vazia(lista* L) {
if(L->prim == -1) return TRUE;
return FALSE;
}
boolean retira(lista* L, int* item, int pos, boolean* flag) {
int p;
p = L->prim;
if(vazia(L) || pos >= MAX)
*flag = FALSE;
if(L->elementos[pos].elem == -1)
*flag = FALSE;
else {
*item = L->elementos[pos].elem;
L->elementos[pos].elem = -1;
while(L->elementos[p].prox != pos) p++;
L->elementos[p].prox = L->elementos[p].prox;
L->disp = pos;
L->numElem--;
*flag = TRUE;
}
return *flag;
}
boolean insere(lista* L, int* item, boolean* flag) {
int pos;
int i = 0;
pos = L->disp;
if(L->numElem == MAX)
*flag = FALSE;
else if(vazia(L)) {
L->prim = pos;
L->elementos[pos].elem = *item;
L->disp = L->elementos[pos].prox;
L->numElem++;
*flag = TRUE;
}
else {
L->elementos[pos].elem = *item;
L->numElem++;
while(L->elementos[i].elem != -1) i++;
L->disp = i;
L->elementos[pos].prox = i;
}
return *flag;
}
void imprime(lista* L) {
int p;
p = L->prim;
while(L->elementos[p].prox != L->disp) {
printf("\nElemento: %d\tPosição: %d", L->elementos[p].elem, p);
p = L->elementos[p].prox;
}
printf("\nElemento: %d\tPosição: %d", L->elementos[p].elem, p);
} |
SQL | UTF-8 | 6,737 | 4.21875 | 4 | [] | no_license | USE Hotel;
-- QUERY 1
-- Write a query that returns a list of reservations that end in July 2023,
-- including the name of the guest, the room number(s), and the reservation dates.
SELECT
Guest.FirstName,
Guest.LastName,
Room.RoomNumber,
Reservation.CheckInDate,
Reservation.CheckOutDate
FROM Guest
INNER JOIN GuestReservation ON Guest.GuestId = GuestReservation.GuestId
INNER JOIN Reservation ON GuestReservation.ReservationId = Reservation.ReservationId
INNER JOIN RoomReservation ON Reservation.ReservationId = RoomReservation.ReservationId
INNER JOIN Room ON RoomReservation.RoomNumber = Room.RoomNumber
WHERE CheckOutDate BETWEEN '2023-07-01' AND '2023-07-31';
-- Ina Zekthi 205 2023-06-28 2023-07-02
-- Walter Holaway 204 2023-07-13 2023-07-14
-- Wilfred Vise 401 2023-07-18 2023-07-21
-- Bettyann Seery 303 2023-07-28 2023-07-29
-- QUERY 2
-- Write a query that returns a list of all reservations for rooms with a jacuzzi,
-- displaying the guest's name, the room number, and the dates of the reservation.
SELECT
Guest.FirstName,
Guest.LastName,
Room.RoomNumber,
Reservation.CheckInDate,
Reservation.CheckOutDate
FROM Room
INNER JOIN RoomReservation ON Room.RoomNumber = RoomReservation.RoomNumber
INNER JOIN Reservation ON RoomReservation.ReservationId = Reservation.ReservationId
INNER JOIN GuestReservation ON Reservation.ReservationId = GuestReservation.ReservationId
INNER JOIN Guest ON GuestReservation.GuestId = Guest.GuestId
WHERE HasJacuzzi = 1;
-- Karie Yang 201 2023-03-06 2023-03-07
-- Bettyann Seery 203 2023-02-05 2023-02-10
-- Karie Yang 203 2023-09-13 2023-09-15
-- Ina Zekthi 205 2023-06-28 2023-07-02
-- Wilfred Vise 207 2023-04-23 2023-04-24
-- Walter Holaway 301 2023-04-09 2023-04-13
-- Mack Simmer 301 2023-11-22 2023-11-25
-- Bettyann Seery 303 2023-07-28 2023-07-29
-- Duane Cullison 305 2023-02-22 2023-02-24
-- Bettyann Seery 305 2023-08-30 2023-09-01
-- Ina Zekthi 307 2023-03-17 2023-03-20
-- QUERY 3
-- Write a query that returns all the rooms reserved for a specific guest,
-- including the guest's name, the room(s) reserved, the starting date of the reservation,
-- and how many people were included in the reservation. (Choose a guest's name from the existing data.)
SELECT
Guest.FirstName,
Guest.LastName,
Room.RoomNumber,
Reservation.CheckInDate,
Reservation.CheckOutDate,
Reservation.Adults + Reservation.Children AS TotalPeople
FROM Guest
INNER JOIN GuestReservation ON Guest.GuestId = GuestReservation.GuestId
INNER JOIN Reservation ON GuestReservation.ReservationId = Reservation.ReservationId
INNER JOIN RoomReservation ON Reservation.ReservationId = RoomReservation.ReservationId
INNER JOIN Room ON RoomReservation.RoomNumber = Room.RoomNumber
WHERE Guest.GuestId = 9;
-- RESULTS
-- Walter Holaway 301 2023-04-09 2023-04-13 1
-- Walter Holaway 204 2023-07-13 2023-07-14 4
-- QUERY 4
-- Write a query that returns a list of rooms, reservation ID, and per-room cost for each reservation.
-- The results should include all rooms, whether or not there is a reservation associated with the room.
SELECT
Room.RoomNumber,
Reservation.ReservationId,
CASE
WHEN (((Room.RoomNumber BETWEEN '201' AND '204') OR (Room.RoomNumber BETWEEN '301' AND '304')) AND Reservation.Adults <= 2)
THEN ((Room.BasePrice) * DATEDIFF(Reservation.CheckOutDate, Reservation.CheckInDate))
WHEN (((Room.RoomNumber BETWEEN '201' AND '204') OR (Room.RoomNumber BETWEEN '301' AND '304')) AND Reservation.Adults > 2)
THEN ((Room.BasePrice + ((Reservation.Adults - Room.StandardOccupancy) * 10) * DATEDIFF(Reservation.CheckOutDate, Reservation.CheckInDate)))
WHEN ((Room.RoomNumber BETWEEN '205' AND '208') OR (Room.RoomNumber BETWEEN '305' AND '308'))
THEN ((Room.BasePrice) * DATEDIFF(Reservation.CheckOutDate, Reservation.CheckInDate))
WHEN (((Room.RoomNumber BETWEEN '401' AND '402')) AND Reservation.Adults <= 3)
THEN ((Room.BasePrice) * DATEDIFF(Reservation.CheckOutDate, Reservation.CheckInDate))
WHEN (((Room.RoomNumber BETWEEN '401' AND '402')) AND Reservation.Adults > 3)
THEN ((Room.BasePrice + ((Reservation.Adults - Room.StandardOccupancy) * 20) * DATEDIFF(Reservation.CheckOutDate, Reservation.CheckInDate)))
END AS Total
FROM Guest
RIGHT OUTER JOIN GuestReservation ON Guest.GuestId = GuestReservation.GuestId
RIGHT OUTER JOIN Reservation ON GuestReservation.ReservationId = Reservation.ReservationId
RIGHT OUTER JOIN RoomReservation ON Reservation.ReservationId = RoomReservation.ReservationId
RIGHT OUTER JOIN Room ON RoomReservation.RoomNumber = Room.RoomNumber;
-- 201 4 199.99
-- 202 7 349.98
-- 203 2 999.95
-- 203 21 399.98
-- 204 16 184.99
-- 205 15 699.96
-- 206 12 599.96
-- 206 23 449.97
-- 207 10 174.99
-- 208 13 599.96
-- 208 20 149.99
-- 301 9 799.96
-- 301 24 599.97
-- 302 6 224.99
-- 302 25 699.96
-- 303 18 199.99
-- 304 14 184.99
-- 305 3 349.98
-- 305 19 349.98
-- 306
-- 307 5 524.97
-- 308 1 299.98
-- 401 11 1199.97
-- 401 17 459.99
-- 401 22 1199.97
-- 402
-- QUERY 5
-- Write a query that returns all the rooms accommodating at least
-- three guests and that are reserved on any date in April 2023.
SELECT
Room.RoomNumber
FROM RESERVATION
INNER JOIN RoomReservation ON Reservation.ReservationId = RoomReservation.ReservationId
INNER JOIN Room ON RoomReservation.RoomNumber = Room.RoomNumber
WHERE (Reservation.Adults + Reservation.Children) > 2
AND ((Reservation.CheckInDate BETWEEN '2023-04-01' AND '2023-04-30')
OR (Reservation.CheckOutDate BETWEEN '2023-04-01' AND '2023-04-30'));
-- No results
-- QUERY 6
-- Write a query that returns a list of all guest names and the number of reservations per guest,
-- sorted starting with the guest with the most reservations and then by the guest's last name.
SELECT
g.Firstname,
g.Lastname,
COUNT(gr.GuestId) AS TotalReservations
FROM Reservation r
INNER JOIN GuestReservation gr ON r.ReservationId = gr.ReservationId
INNER JOIN Guest g ON gr.GuestId = g.GuestId
GROUP BY g.FirstName
ORDER BY TotalReservations DESC, g.LastName;
-- Mack Simmer 4
-- Bettyann Seery 3
-- Duane Cullison 2
-- Walter Holaway 2
-- Aurore Lipton 2
-- Ina Zekthi 2
-- Maritza Tilton 2
-- Joleen Tison 2
-- Wilfred Vise 2
-- Karie Yang 2
-- Zachery Luechtefield 1
-- QUERY 7
-- Write a query that displays the name, address, and phone number of a guest
-- based on their phone number. (Choose a phone number from the existing data.)
SELECT
g.guestId,
g.FirstName,
g.LastName,
g.Street,
g.City,
g.State,
g.Zip,
g.Phone
FROM GUEST AS g
WHERE g.Phone ='(666) 666-6666';
-- Ina Zekthi 666 Columbia Uni New York Baby NY 51501 (666) 666-6666 |
JavaScript | UTF-8 | 721 | 3.21875 | 3 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | function getFirstSelector(selector) {
return document.querySelector(selector)
}
// function nestedTarget() {
// return document.querySelector('#nested').querySelector('.target')
// }
function nestedTarget() {
return document.getElementById('nested').querySelector('.target')
}
function increaseRankBy(n) {
const ranked = document.querySelectorAll('.ranked-list')
for (var i = 0; i < ranked.length; i++) {
let children = ranked[i].children
for (var j = 0; j < children.length; j++) {
children[j].innerHTML = parseInt(children[j].innerHTML) + n
}
}
}
function deepestChild() {
const array = document.querySelector('#grand-node').querySelectorAll('*')
return array[array.length - 1]
}
|
JavaScript | UTF-8 | 991 | 2.578125 | 3 | [] | no_license | $(document).ready(function(){
let slides = $(".slider-quote .slides").children(".slide");
let width = $(".slider-quote .slides").width();
let i = slides.length;
let offset = i * width;
let cheki = i-1;
$(".slider-quote .slides").css('width',offset);
for (j=0; j < slides.length; j++){
if (j==0) {
$(".slider-quote .navigation").append("<div class='dot active'></div>");
}
else {
$(".slider-quote .navigation").append("<div class='dot'></div>");
}
}
let dots = $(".slider-quote .navigation").children(".dot");
offset = 0;
i = 0;
$('.slider-quote .navigation .dot').click(function(){
$(".slider-quote .navigation .active").removeClass("active");
$(this).addClass("active");
i = $(this).index();
offset = i * width;
$(".slider-quote .slides").css("transform","translate3d(-"+offset+"px, 0px, 0px)");
});
}); |
PHP | UTF-8 | 2,240 | 2.59375 | 3 | [
"Apache-2.0"
] | permissive | <?php
namespace app\index\model;
use think\Model;
use think\Db;
use think\Cache;
use think\Validate;
/**
*PHP是世界上最好的语言
*@param 房间模型
**/
class Room extends Model
{
protected $name = 'room';
//用户自主添加房间并返回房间信息
public function create_room($room_id,$level)
{
$is_have_room_data = $this->is_have_room($room_id);
if($is_have_room_data === false){
$data = ['room_id'=>$room_id,'level'=>$level,'create_type'=>2];
$room = new room;
$room->isUpdate(false)->save($data);
$id = $room->id;
$data = ['id'=>$id,'room_id'=>$room_id,'level'=>$level];
return return_msg('0000','房间添加成功',$data);
}else{
return return_msg('80001','该房间号已存在',$is_have_room_data);
}
//$room_id =
}
//查询是否存在该房间
public function is_have_room($room_id)
{
$data = self::field('id,room_id,level,password')
->where('room_id',$room_id)
->limit(1)
->find();
if(empty($data)){
return false;
}else{
// if($data['is_in_game'] == 1){
// echo json(return_msg('0000','房间正在游戏中'));die;
// }
return $data->toArray();
}
}
public function confirm_room_pass($room_id,$password){
$data = self::field('id,room_id,level')
->where('room_id',$room_id)
->where('password',$password)
->limit(1)
->find();
if(empty($data)){
return return_msg('30003','密码错误');
}else{
return return_msg('0000',lang('REQUEST_SUCCESS'),$data);
}
}
//系统自动创建房间并返回房间信息
public function sys_create_room($level = 1,$password = "",$room_gold = "")
{
$room_id = rand_room($level);
while($this->is_have_room($room_id) !== false){
$room_id = rand_room($level);
}
if(empty($password)){
$use_pass = 0;
}else{
$use_pass = 1;
}
$data = ['room_id'=>$room_id,'level'=>$level,'password'=>$password,'c_time'=>time(),'room_gold'=>$room_gold,'use_pass'=>$use_pass];
$room = new room;
$room->isUpdate(false)->save($data);
$id = $room->id;
$data = ['id'=>$id,'room_id'=>$room_id,'level'=>$level,'room_gold'=>$room_gold];
return $data;
}
//
// protected function room_info()
// {
// $data = self::
// }
} |
Java | UTF-8 | 485 | 1.976563 | 2 | [] | no_license | package org.ng12306.ngsql.parser.ast.stmt;
import org.ng12306.ngsql.parser.ast.ASTNode;
/**
* @author <a href="mailto:wenjie.0617@gmail.com">wuwj</a>
*/
public interface SQLStatement extends ASTNode {
public static enum StmtType {
DML_SELECT,
DML_DELETE,
DML_INSERT,
DML_REPLACE,
DML_UPDATE,
DML_CALL,
DAL_SET,
DAL_SHOW,
MTL_START,
/** COMMIT or ROLLBACK */
MTL_TERMINATE,
MTL_ISOLATION
}
}
|
C++ | UTF-8 | 3,857 | 3.1875 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <climits>
#define TEMP 1000
using namespace std;
struct Point{
int x, y;
};
bool checkBounds(int x, int y, int xMin, int yMin, int xMax, int yMax){
return xMin <= x && xMax >= x && yMin <= y && yMax >= y;
}
double CalcPosteriorProb(int x,int y,double priorP,Point* points, int numOfPoints, int xMin, int yMin,
int xMax, int yMax){
int xInter = (xMin + xMax) / 2;
int yInter = (yMin + yMax) / 2;
double numOfC1 = 0, numOfC2 = 0, numOfC3 = 0, numOfC4 = 0;
for(int i = 0; i < numOfPoints; i++)
{
int x = points[i].x, y = points[i].y;
if(checkBounds(x, y, xMin, yInter, xInter, yMax))
numOfC1++;
else if(checkBounds(x, y, xInter, yInter, xMax, yMax))
numOfC2++;
else if(checkBounds(x, y, xInter, yMin, xMax, yInter))
numOfC3++;
else
numOfC4++;
}
double likelihoodR1 = numOfC1 / numOfPoints;
double likelihoodR2 = numOfC2 / numOfPoints;
double likelihoodR3 = numOfC3 / numOfPoints;
double likelihoodR4 = numOfC4 / numOfPoints;
if(checkBounds(x, y, xMin, yInter, xInter, yMax))
return likelihoodR1*priorP;
else if(checkBounds(x, y, xInter, yInter, xMax, yMax))
return likelihoodR2*priorP;
else if(checkBounds(x, y, xInter, yMin, xMax, yInter))
return likelihoodR3*priorP;
else
return likelihoodR4*priorP;
}
int main(){
int totalNoOfPoints = 0;
ifstream inputFile("data_nb4.txt", ios::in);
if(!inputFile){
cout<<"Cannot open the file";
return 1;
}
Point points1[TEMP], points2[TEMP];
int numOfClass1 = 0, numOfClass2 = 0;
int class1XMin = INT_MAX, class1YMin = INT_MAX;
int class1XMax = INT_MIN, class1YMax = INT_MIN;
int class2XMin = INT_MAX, class2YMin = INT_MAX;
int class2XMax = INT_MIN, class2YMax = INT_MIN;
int x = -1, y = -1, c = -1;
while(!inputFile.eof())
{
c=-1;
inputFile>>x>>y>>c;
if(c == -1){
continue;
}
// cout<<x<<" "<<y<<" "<<c<<endl;
if(c == 1)
{
points1[numOfClass1].x = x;
points1[numOfClass1].y = y;
numOfClass1++;
if(class1XMin > x)
class1XMin = x;
if(class1XMax < x)
class1XMax = x;
if(class1YMin > y)
class1YMin = y;
if(class1YMax < y)
class1XMax = y;
}
else
{
points2[numOfClass2].x = x;
points2[numOfClass2].y = y;
numOfClass2++;
if(class2XMin > x)
class2XMin = x;
if(class2XMax < x)
class2XMax = x;
if(class2YMin > y)
class2YMin = y;
if(class2YMax < y)
class2YMax = y;
}
}
inputFile.close();
totalNoOfPoints = numOfClass1 + numOfClass2;
double priorP1 = (double)numOfClass1 / totalNoOfPoints;
double priorP2 = (double)numOfClass2 / totalNoOfPoints;
cout<<x<<" "<<y<<endl;
double posteriorP1= CalcPosteriorProb(x,y,priorP1,points1,numOfClass1,class1XMin,class1YMin,class1XMax,class1YMax);
double posteriorP2= CalcPosteriorProb(x,y,priorP2,points2,numOfClass2,class2XMin,class2YMin,class2XMax,class2YMax);
cout<<posteriorP1<<" "<<posteriorP2<<endl;
cout<<"Class ";
if(posteriorP1>posteriorP2)
cout<<"1\n";
else
cout<<"2\n";
return 0;
}
|
C | UTF-8 | 708 | 2.546875 | 3 | [] | no_license | #include "fdf_bonus.h"
void arg_error(void)
{
ft_putstr_fd(ANSI_COLOR_GREEN, 2);
ft_putstr_fd("Usage: ./fdf <filename>.fdf\n", 2);
ft_putstr_fd(ANSI_UNSET_GREEN, 2);
exit(0);
}
void file_error(void)
{
ft_putstr_fd("./fdf : Error reading the map\n", 2);
exit(0);
}
void format_error(char *str)
{
free(str);
ft_putstr_fd("./fdf : Error in map format\n", 2);
exit(0);
}
void rgb_format_error(char *str)
{
free(str);
ft_putstr_fd("./fdf : colors (if specified) ", 2);
ft_putstr_fd("have to be like: 0xFFFFFF\n", 2);
exit(0);
}
void line_length_error(char *str)
{
free(str);
ft_putstr_fd("./fdf : error in line length. ", 2);
ft_putstr_fd("Make sure the map is recangular\n", 2);
exit(0);
}
|
Python | UTF-8 | 1,855 | 3.40625 | 3 | [] | no_license | import heapq
from .field import Cell, Field
class PriorityQueue:
def __init__(self):
self.elements = []
def is_empty(self):
return len(self.elements) == 0
def put(self, item, priority):
heapq.heappush(self.elements, (priority, item))
def get(self):
return heapq.heappop(self.elements)[1]
def heuristic_distance(a: Cell, b: Cell):
(x1, y1) = a.x, a.y
(x2, y2) = b.x, b.y
return abs(x1 - x2) + abs(y1 - y2)
def a_star_search(field: Field, start_cell: Cell, goal_cell: Cell):
frontier = PriorityQueue()
frontier.put(start_cell.coords_tuple(), 0)
came_from = {}
cost_so_far = {
start_cell: 0
}
came_from[start_cell] = None
while not frontier.is_empty():
current = frontier.get()
current_cell = field.get_cell_at_xy(*current)
if current_cell == goal_cell:
break
for next_direction, next_cell in field.get_neighbor_cells(current_cell):
if not next_cell.is_accessible:
continue
new_cost = cost_so_far[current_cell] + 1 # TODO: Add support for cost of movement
if next_cell not in cost_so_far or new_cost < cost_so_far[next_cell]:
cost_so_far[next_cell] = new_cost
priority = new_cost + heuristic_distance(next_cell, goal_cell)
frontier.put(next_cell.coords_tuple(), priority)
came_from[next_cell] = (current_cell, next_direction)
return reconstruct_path(came_from, start_cell, goal_cell)
def reconstruct_path(came_from, start_cell, goal_cell):
current = goal_cell
path = []
while current != start_cell:
direction = came_from[current][1]
path.append((current, direction))
current = came_from[current][0]
path.reverse() # optional
return path
|
C# | UTF-8 | 1,117 | 2.59375 | 3 | [] | no_license | using System;
using System.Threading.Tasks;
using BookLibrary.DAL.Models;
using BookLibrary.DAL.Repositories.InterfacesRepositories;
using Microsoft.Extensions.DependencyInjection;
namespace BookLibrary.DAL.UnitOfWork
{
public class UnitOfWork : IUnitOfWork
{
private readonly BookLibraryDbContext _context;
private readonly IServiceProvider _serviceProvider;
private IAuthorRepository _authorRepository;
private IBookRepository _bookRepository;
public UnitOfWork(BookLibraryDbContext context,
IServiceProvider serviceProvider)
{
_context = context;
_serviceProvider = serviceProvider;
}
public IAuthorRepository AuthorRepository =>
_authorRepository ?? (_authorRepository = _serviceProvider.GetService<IAuthorRepository>());
public IBookRepository BookRepository =>
_bookRepository ?? (_bookRepository = _serviceProvider.GetService<IBookRepository>());
public Task<int> SaveAsync()
{
return _context.SaveChangesAsync();
}
}
} |
Java | UTF-8 | 1,873 | 3.296875 | 3 | [] | no_license | package com.javarush.task.task36.task3602;
import java.lang.reflect.Modifier;
import java.util.Collections;
import java.util.List;
/*
Найти класс по описанию
*/
public class Solution {
public static void main(String[] args) {
System.out.println(getExpectedClass());
}
public static Class getExpectedClass() {
for (Class clazz : Collections.class.getDeclaredClasses()) { //get Classes
for (Class intrf : clazz.getInterfaces()) { //get interfaces
if (intrf.getSimpleName().equals("List") && Modifier.isStatic(clazz.getModifiers())) {
{
//System.out.println(clazz.getName());
// But here i see only:
//java.util.Collections$CheckedList
//java.util.Collections$SynchronizedList
//java.util.Collections$UnmodifiableList
//Where is ?
//java.util.Collections$EmptyList
//Чтобы появился java.util.Collections$EmptyList надо проверять интерфейсы еще и у родителей по иерархии
//в данном случае AbstractList от которого наследуется java.util.Collections$EmptyList и реализует интерфейс List
//В текущем алгоритме интерфейсы проверяются только у самого класса, а надо как я написал.
//Задачу здал благодаря хаку, ниже.
}
}
}
}
//Googling... This is true answer...
try {
return Class.forName("java.util.Collections$EmptyList");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
/*
for (Class aClass : Collections.class.getDeclaredClasses())
if (Modifier.isStatic(aClass.getModifiers()) &&
List.class.isAssignableFrom(aClass))
return aClass;
return null;
*/
}
}
|
Java | UTF-8 | 2,463 | 3.703125 | 4 | [
"MIT"
] | permissive | import java.math.BigInteger;
import java.util.Random;
import java.util.Scanner;
/**
* Class que mostra como criar threads até descobrir qual o limite
* do sistema operacional em um determinado computador para criar threads,
* de acordo com as condições atuais de sobrecarga de tal computador
* (quantidade de aplicações em execução e número de threads total).
*
* @author Manoel Campos da Silva Filho
*/
public class ThreadLimit implements Runnable {
private int maxThreads;
private Scanner scanner = new Scanner(System.in);
private void start(){
System.out.println("Criando threads. Por favor aguarde...\n");
new Thread(this::loop).start();
int opcao;
do{
System.out.println("1 - Exibir total de threads criadas");
System.out.println("0 - Sair");
System.out.print("Digite uma opção:");
opcao = scanner.nextInt();
if(opcao == 1){
System.out.printf("Threads em execução: %d\n", Thread.activeCount());
}
}while(opcao != 0);
System.out.printf("Máximo de Threads criadas: %d\n", maxThreads);
}
/**
* Inicia o loop de criação de threads até descobrir qual
* o limite para o SO, computador e condições atuais de sobrecarga da computador.
*/
private void loop(){
while(true){
try{
new Thread(this).start();
}catch(Exception e){
System.out.println(
"Total de threads que foi possível de serem criadas para o SO, PC e condições de sobrecarga atuais: " + maxThreads);
return;
}
}
}
/**
* Define uma operação qualquer a ser executada pelas threads.
* Neste caso, apenas soma um total aleatório de números.
*/
@Override
public void run(){
updateMaxThreadNumber();
final Random rand = new Random();
final int max = rand.nextInt();
long sum = 0;
for(int i = 0; i < max; i++){
sum += i;
try{
int time = (int)(rand.nextDouble()*5)+1;
//Thread.sleep(time);
}catch(Exception e){
}
}
}
private synchronized void updateMaxThreadNumber(){
maxThreads = Math.max(maxThreads, Thread.activeCount());
}
public static void main(String[] args) {
new ThreadLimit().start();
}
} |
Markdown | UTF-8 | 1,025 | 2.6875 | 3 | [] | no_license | # Widget : Crud LIST
## Description
This widget intends to display a list with some content extracted from a CRUD module.
## Attributes
| Parameter | Type | Description |
|---------------|---------------|---------------|
| entityName | String | Name of the entity in the confiiguration files to use |
| pageStart | Integer | Page to display (pagination) |
| length | Integer | Number of item in the page (default : 10) |
| searchKey | String | String to search in the fields described in the configuration |
| filters | Composed | Key/ Values of filters to apply format (key$value\|key2$value2\|key3$value3) |
| orderBy | String | Attribut to use for ordering |
| orderWay | String | ASC or DESC, to decide to sort way |
## Usage in a sunshing page
## Usage in React JSX
```
...
import CrudList from '../widgets/CrudList.jsx';
...
<CrudList index={this.props.index} widget={this.props.widget} />
```
## Used Webservice |
C++ | UTF-8 | 560 | 3.21875 | 3 | [] | no_license | /*
* File Name: student.h
* Program Description: Polymorphism
* Course Name: Workshop in C++
* Assignment Number: 7
* Author: Abraham Murciano
*/
#ifndef student_h
#define student_h
#include <stdlib.h>
#include <string>
using namespace std;
class student {
protected:
// Data
int id;
string name;
string surname;
int nCourses;
public:
// Constructors
student();
student(int id, string name, string surname, int nCourses);
virtual ~student() = 0;
// Methods
virtual bool entitled() const = 0;
virtual void print() const;
};
#endif
|
C++ | UTF-8 | 1,617 | 3.796875 | 4 | [] | no_license | #include <iostream>
#include <string.h>
static const bool debug_mode = true;
/*
Time complexity: O(2)
void replace_char(char *input, unsigned int length)
{
O(1) unsigned int i = 0;
O(1) unsigned int j = 0;
O(n) for (i = 0; i < length; i++)
{
if (input[i] == ' ')
{
O(n) for (j = length; j > i; j--)
{
input[j+2] = input[j];
O(1) }
O(1) input[i] = '&';
O(1) input[i+1] = '3';
O(1) input[i+2] = '2';
O(1) length+=2;
}
}
}
O(1)+O(1)+O(n)*(O(n) + O(1)+ O(1)+ O(1)+ O(1)) = O(2)+O(n)*O(n+4) = O(2) + O(n^2+4n) = O(2) + O(n^2) = O(n^2)
Space complexity: O(1)
Tha auxiliary spaces used are counters i and j, not related to input size.
*/
void replace_char(char *input, unsigned int length)
{
unsigned int i = 0;
unsigned int j = 0;
for (i = 0; i < length; i++)
{
if (input[i] == ' ')
{
if (debug_mode)
std::cout << "add synbols at position " << i << std::endl;
for (j = length; j > i; j--)
{
if (debug_mode)
std::cout << "replace position" << j+2 << " by " << j << std::endl;
input[j+2] = input[j];
if (debug_mode)
std::cout << "partial: " << input << std::endl;
}
input[i] = '&';
input[i+1] = '3';
input[i+2] = '2';
length+=2;
if (debug_mode)
std::cout << "add synbols: " << input << std::endl;
}
}
}
int main()
{
char *my_array = (char *) malloc(100*sizeof (char));
strcpy(my_array, "User is not allowed");
std::cout << my_array << std::endl;
replace_char(my_array, 19);
std::cout << my_array << std::endl;
return 0;
}
|
TypeScript | UTF-8 | 4,313 | 2.59375 | 3 | [] | no_license | /*
* @Author: your name
* @Date: 2020-03-18 17:41:02
* @LastEditTime: 2020-03-18 17:41:02
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \devui-language-service\language-service\src\complier_metadata.ts
*/
import * as html from './ast';
import * as chars from './chars';
export class CompileHTMLTemplateMetadata {
htmlAst: ParseTreeResult|null;
constructor({htmlAst}: {
htmlAst: ParseTreeResult|null,
}) {
this.htmlAst = htmlAst;
}
// toSummary(): CompileTemplateSummary {
// return {
// ngContentSelectors: this.ngContentSelectors,
// encapsulation: this.encapsulation,
// styles: this.styles,
// animations: this.animations
// };
// }
}
export class ParseTreeResult {
constructor(public rootNodes: html.Node[], public errors: ParseError[]) {}
}
class ParseError {
constructor(
public span: ParseSourceSpan, public msg: string,
public level: ParseErrorLevel = ParseErrorLevel.ERROR) {}
contextualMessage(): string {
const ctx = this.span.start.getContext(100, 3);
return ctx ? `${this.msg} ("${ctx.before}[${ParseErrorLevel[this.level]} ->]${ctx.after}")` :
this.msg;
}
toString(): string {
const details = this.span.details ? `, ${this.span.details}` : '';
return `${this.contextualMessage()}: ${this.span.start}${details}`;
}
}
class ParseSourceSpan {
constructor(
public start: ParseLocation, public end: ParseLocation, public details: string|null = null) {}
toString(): string {
return this.start.file.content.substring(this.start.offset, this.end.offset);
}
}
export class ParseLocation {
constructor(
public file: ParseSourceFile, public offset: number, public line: number,
public col: number) {}
toString(): string {
return this.offset != null ? `${this.file.url}@${this.line}:${this.col}` : this.file.url;
}
moveBy(delta: number): ParseLocation {
const source = this.file.content;
const len = source.length;
let offset = this.offset;
let line = this.line;
let col = this.col;
while (offset > 0 && delta < 0) {
offset--;
delta++;
const ch = source.charCodeAt(offset);
if (ch == chars.$LF) {
line--;
const priorLine = source.substr(0, offset - 1).lastIndexOf(String.fromCharCode(chars.$LF));
col = priorLine > 0 ? offset - priorLine : offset;
} else {
col--;
}
}
while (offset < len && delta > 0) {
const ch = source.charCodeAt(offset);
offset++;
delta--;
if (ch == chars.$LF) {
line++;
col = 0;
} else {
col++;
}
}
return new ParseLocation(this.file, offset, line, col);
}
// Return the source around the location
// Up to `maxChars` or `maxLines` on each side of the location
getContext(maxChars: number, maxLines: number): {before: string, after: string}|null {
const content = this.file.content;
let startOffset = this.offset;
if (startOffset != null) {
if (startOffset > content.length - 1) {
startOffset = content.length - 1;
}
let endOffset = startOffset;
let ctxChars = 0;
let ctxLines = 0;
while (ctxChars < maxChars && startOffset > 0) {
startOffset--;
ctxChars++;
if (content[startOffset] == '\n') {
if (++ctxLines == maxLines) {
break;
}
}
}
ctxChars = 0;
ctxLines = 0;
while (ctxChars < maxChars && endOffset < content.length - 1) {
endOffset++;
ctxChars++;
if (content[endOffset] == '\n') {
if (++ctxLines == maxLines) {
break;
}
}
}
return {
before: content.substring(startOffset, this.offset),
after: content.substring(this.offset, endOffset + 1),
};
}
return null;
}
}
class ParseSourceFile {
constructor(public content: string, public url: string) {}
}
enum ParseErrorLevel {
WARNING,
ERROR,
}
|
SQL | UTF-8 | 367 | 2.96875 | 3 | [
"MIT"
] | permissive | SELECT
ruledarea_level5.aname,
ageometry AS geometrie,
canton AS kanton,
organisation.aname AS betreiber
FROM
awa_stromversorgungssicherheit.supplyscy_rldreas_ruledarea_level5 AS ruledarea_level5
LEFT JOIN awa_stromversorgungssicherheit.supplyscy_rldreas_organisation AS organisation
ON organisation.t_id = ruledarea_level5."operator"
;
|
Markdown | UTF-8 | 2,741 | 2.8125 | 3 | [] | no_license | # Problem
This website can be rendered only by picobrowser, go and catch the flag! [https://2019shell1.picoctf.com/problem/32205/](https://2019shell1.picoctf.com/problem/32205/) or http://2019shell1.picoctf.com:32205
## Hints:
You dont need to download a new web browser
## Solution:
We first try to observe the site:

Try to get the flag:

Let's spoof the [user agent](https://en.wikipedia.org/wiki/User_agent):
```bash
curl -A "picobrowser" https://2019shell1.picoctf.com/problem/32205/flag
<!DOCTYPE html>
<html lang="en">
<head>
<title>My New Website</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
<link href="https://getbootstrap.com/docs/3.3/examples/jumbotron-narrow/jumbotron-narrow.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="header">
<nav>
<ul class="nav nav-pills pull-right">
<li role="presentation" class="active"><a href="/">Home</a>
</li>
<li role="presentation"><a href="/unimplemented">Sign In</a>
</li>
<li role="presentation"><a href="/unimplemented">Sign Out</a>
</li>
</ul>
</nav>
<h3 class="text-muted">My New Website</h3>
</div>
<!-- Categories: success (green), info (blue), warning (yellow), danger (red) -->
<div class="alert alert-success alert-dismissible" role="alert" id="myAlert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<!-- <strong>Title</strong> --> picobrowser!
</div>
<div class="jumbotron">
<p class="lead"></p>
<p style="text-align:center; font-size:30px;"><b>Flag</b>: <code>picoCTF{p1c0_s3cr3t_ag3nt_ee951878}</code></p>
<!-- <p><a class="btn btn-lg btn-success" href="admin" role="button">Click here for the flag!</a> -->
<!-- </p> -->
</div>
<footer class="footer">
<p>© PicoCTF 2019</p>
</footer>
</div>
<script>
$(document).ready(function(){
$(".close").click(function(){
$("myAlert").alert("close");
});
});
</script>
</body>
</html>
```
Got it!
Flag: picoCTF{p1c0_s3cr3t_ag3nt_ee951878}
|
JavaScript | UTF-8 | 1,847 | 2.671875 | 3 | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-ecma-no-patent"
] | permissive | // Copyright (C) 2016 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-%typedarray%.prototype.findindex
description: >
Change values during predicate call
info: |
22.2.3.11 %TypedArray%.prototype.findIndex ( predicate [ , thisArg ] )
%TypedArray%.prototype.findIndex is a distinct function that implements the
same algorithm as Array.prototype.findIndex as defined in 22.1.3.9 except that
the this object's [[ArrayLength]] internal slot is accessed in place of
performing a [[Get]] of "length".
...
22.1.3.9 Array.prototype.findIndex ( predicate[ , thisArg ] )
...
6. Repeat, while k < len
...
c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
...
includes: [compareArray.js, testBigIntTypedArray.js]
features: [BigInt, TypedArray]
---*/
testWithBigIntTypedArrayConstructors(function(TA) {
var arr = [10n, 20n, 30n];
var sample;
var result;
sample = new TA(3);
sample.findIndex(function(val, i) {
sample[i] = arr[i];
assert.sameValue(val, 0n, "value is not mapped to instance");
});
assert(compareArray(sample, arr), "values set during each predicate call");
sample = new TA(arr);
result = sample.findIndex(function(val, i) {
if ( i === 0 ) {
sample[2] = 7n;
}
return val === 7n;
});
assert.sameValue(result, 2, "value found");
sample = new TA(arr);
result = sample.findIndex(function(val, i) {
if ( i === 0 ) {
sample[2] = 7n;
}
return val === 30n;
});
assert.sameValue(result, -1, "value not found");
sample = new TA(arr);
result = sample.findIndex(function(val, i) {
if ( i > 0 ) {
sample[0] = 7n;
}
return val === 7n;
});
assert.sameValue(result, -1, "value not found - changed after call");
});
|
Markdown | UTF-8 | 1,462 | 2.765625 | 3 | [] | no_license | PD4: czas na wykonanie 31-10-2018 do 7-11-2018
Na wykładzie trzecim omawialiśmy różne zagadnienia związane z percepcją i rolą kolorów na wykresie.
Zadanie: z poprzednich prac domowych PD1-PD3 wybrać pracę innego studenta a następnie pokazać dane z tej pracy domowe za pomocą dwóch wykresów:
A) Wykresu czarnobiałego, na którym stosować można jedynie kolory biały, czarny i odcienie szarości
B) Wykresy z kolorami, na krórym można stosować (z umiarem) kolory aby przedstawić jakąś zmienną, wyróżnić obserwacje, poprawić estetykę wykresu.
W katalogu https://github.com/pbiecek/TechnikiWizualizacjiDanych2018/tree/master/PraceDomowe/PD4 umieść skrypt knitr (wraz ze skompilowaną wersją html) z kodem R dla wersji A i B wykresu.
Skomentować czy i co wnosi dodanie koloru do wykresu A.
Pracę domową należy wykonać indywidualnie.
**BONUS:**
Zamiast wybierać dane z pracy domowej innego studenta, można otrzymać bonusowy 1 punkt za znalezienie ciekawych danych nawiązujących do Dnia Zmarłych lub Halloween.
-------
Skala:
* 5 - dobrze wykonana praca domowa
* 4 - pracochłonnie wykonana praca domowa
* 3 - kompletna praca domowa
* 2 - niekompletna praca domowa
* 1 - połowicznie wykonana praca domowa
* 0 - brak pracy domowej lub praca nie na temat
Osoby pracujące na tych samych danych i prezentujące dane w bardzo podobny otrzymują znacznie mniej punktów (do 0 w zależności od stopnia podobieństwa).
|
C | UTF-8 | 2,471 | 3.109375 | 3 | [] | no_license | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jmichaud <jmichaud@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/21 15:39:31 by jmichaud #+# #+# */
/* Updated: 2017/06/22 16:27:22 by jmichaud ### ########.fr */
/* */
/* ************************************************************************** */
#include <unistd.h>
#include "libft.h"
#include "get_next_line.h"
#include <fcntl.h> // open
#include <stdlib.h> // malloc && free
int get_next_line(const int fd, char **line);
static int return_error(const char *str, int ret)
{
ft_putstr_fd(str, 2);
return (ret);
}
static int while_gnl(int fd)
{
int ret;
char *line;
while ((ret = get_next_line(fd, &line)))
{
if (ret == -1)
return (return_error("gnl() failed\n", 0));
ft_putstr("->");
ft_putstr(line);
ft_putendl("<-");
free(line);
}
return (1);
}
static int one_gnl(int fd, int nb)
{
int ret;
char *line;
ret = get_next_line(fd, &line);
if (ret == -1)
return (return_error("gnl() failed\n", 0));
if (!ret)
return (1);
ft_putnbr(nb);
ft_putstr("->");
ft_putstr(line);
ft_putendl("<-");
free(line);
return (1);
}
int main(int argc, const char *argv[])
{
int i;
int *fd;
if (argc == 1 && !while_gnl(0))
return (1);
else
{
if (!(fd = (int *)malloc(sizeof(*fd) * (argc - 1))))
return (return_error("malloc() failed\n", 1));
for (i = 0; i < argc - 1; i++)
if ((fd[i] = open(argv[i + 1], O_RDONLY)) == -1)
return (return_error("open() failed\n", 1));
for (i = 0; i < 2; i++)
if (!one_gnl(fd[0], 0) ||
!one_gnl(fd[1], 1) ||
!one_gnl(fd[0], 0) ||
!one_gnl(fd[2], 2) ||
!one_gnl(fd[1], 1))
return (1);
for (i = 0; i < argc - 1; i++)
{
if (!while_gnl(fd[i]))
return (1);
if (!one_gnl(fd[i], i))
return (1);
if (close(fd[i]) == -1)
return (return_error("close() failed\n", 1));
}
free(fd);
}
return (0);
}
|
Java | ISO-8859-1 | 4,310 | 3.5625 | 4 | [] | no_license | /**
A class calledImageis provided below. This class can be used to manage a two-dimensional array of pixels.
The basic class structure has been defined for you, with oneinstance variable:pixels,thatstores a set of
hexadecimal color values as a two-dimensional array of Strings, and several helper methods that manipulate the
data as needed. The constructorinitializes thepixelsarray for you, but you will need to create the new String array.
You must complete the constructor, and defineone method: filterRed().
As usual, the items we want you to complete are described in "TODO" comments. Anything not specificedby these
comments (anything outside of the filterRed() method and Image constructor) should be left as is. If you accidentally
change something, you can always reset your assignment.
For the constructor, write a single statement that reserves new memory for a two-dimensional String array, pixels.
In thefilterRedmethod, you should iterate through all of the individual pixels, checking each using the
mostlyRed method to determine if the red portion of the hex color string should be zeroed out. If the pixel
is mostly red, store a new String in that pixel location made up of "00" for red, and the current green and blue components of the given pixel.
Ex.pixels[10][127]="FF1A48"; // before method call
pixels[10][127] = "001A48"; // after method call
filterRedchanges the pixel at location row=10, column=127, because the amount of red ("FF", i.e., 255)
is bigger than the amount of green ("1A" -> 26) and the amount of blue ("48" -> 72). The amount of red ("FF") is
replaced by two zeros ("00") and the green and blue are appended on to that String.
**/
import java.util.Random;
public class Image {
String[][] pixels;
public Image(int width, int height) {
/*** TODO: Create an empty two-dimensional String array, with height rows
and width columns ***/
pixels = new String[width][height];
loadPixels();
}
public void filterRed() {
/*** TODO: Iterate over every String element in pixels
If element is mostly red, set red to "00", do not change green or blue ***/
for(int i=0;i<pixels.length;i++){
for(int j=0;j<pixels[i].length;j++){
if(mostlyRed(pixels[i][j])==true){
String temp="";
for(int k=0;k<2;k++)
{
temp+="0";
}
temp+=pixels[i][j].substring(2);
pixels[i][j]=temp;
}
}
}
}
public void loadPixels() {
/*** initialization of pixels is not shown
data stored as hexadecimal color string, i.e. "C28E0E" ***/
Random r = new Random();
for (int i = 0; i < pixels.length; i++) {
for (int j = 0; j < pixels[i].length; j++) {
pixels[i][j] = makeHex(r.nextInt(256)) + makeHex(r.nextInt(256)) + makeHex(r.nextInt(256));
}
}
}
public String makeHex(int x) {
String s = Integer.toHexString(x);
if (s.length() < 2) s = "0" + s;
return s;
}
public boolean mostlyRed(String p) {
int r = hexToDecimal(p.substring(0,2));
int g = hexToDecimal(p.substring(2,4));
int b = hexToDecimal(p.substring(4));
return (r > g && r > b);
}
public int hexToDecimal(String hex) {
char first = hex.charAt(0);
char second = hex.charAt(1);
int dec = (int)((first < 65) ? (first - 47) : (first - 65)) * 10;
dec = dec + (int)((second < 65) ? (second - 47) : (second - 65));
return dec;
}
public String toString() {
String s = "<html><head></head><body><table style='border-collapse: collapse; padding: 0px;'>";
for (int i = 0; i < pixels.length; i++) {
s = s + "<tr>";
for (int j = 0; j < pixels[i].length; j++) {
s = s + "<td style='height: 1px; width: 1px; background-color: #" + pixels[i][j] + ";'></td>";
}
s = s + "</tr>";
}
s = s + "</table></body></html>";
return s;
}
public static void main(String[] args) {
Image img = new Image(10,12);
System.out.println("<html><head></head><body>Before Filter</body></html>");
System.out.println(img);
img.filterRed();
System.out.println("<html><head></head><body>After Filter</body></html>");
System.out.println(img);
}
}
|
Python | UTF-8 | 2,056 | 3.171875 | 3 | [] | no_license | # файл camp_cactus.py
import pygame
from cactus import cactus
from const import *
import random
# список врагов
def arr_image():
arr_enemy = [
{
"image": pygame.image.load('Objects/Cactus0.png'),
"height": 50,
"width": 69
},
{
"image": pygame.image.load('Objects/Cactus1.png'),
"height": 89,
"width": 37
},
{
"image": pygame.image.load('Objects/Cactus2.png'),
"height": 79,
"width": 40
},
]
return arr_enemy
# создание врагов врагов
def arr_create_enemy(display):
array = arr_image()
choice = []
for index in range(len(array)):
choice.append(random.randrange(0, len(array)))
camp_enemy = []
for index in range(0, len(array)):
camp_enemy.append(cactus(display, array[choice[index]]["image"], array[choice[index]]["height"],
array[choice[index]]["width"]))
return camp_enemy
# проверка на спавн врагов
def arr_draw_enemy(array, display):
array_enemy = arr_image()
for enemy in array:
check = enemy.draw()
if not check:
radius = find_radius(array)
choice = random.randrange(0, len(array))
enemy.return_self(display, radius,
array_enemy[choice]["image"],
array_enemy[choice]["height"],
array_enemy[choice]["width"])
# алгоритм спавна кактусов
def find_radius(array):
maximum = max(array[0].position_x, array[1].position_x, array[2].position_x)
if maximum < DISPLAY_WIDTH:
radius = DISPLAY_WIDTH
if radius - maximum < 200:
radius += 200
else:
radius = maximum
choice = random.randrange(0, 5)
if choice == 0:
radius += random.randrange(15, 85)
else:
radius += random.randint(300, 450)
return radius
|
Python | UTF-8 | 7,547 | 3.859375 | 4 | [] | no_license | """
In search.py, you will implement generic search algorithms which are called by
Pacman agents (in searchAgents.py).
"""
import util
import sys
from time import sleep
from game import Directions
n = Directions.NORTH
s = Directions.SOUTH
e = Directions.EAST
w = Directions.WEST
class SearchProblem:
"""
This class outlines the structure of a search problem, but doesn't implement
any of the methods (in object-oriented terminology: an abstract class).
You do not need to change anything in this class, ever.
"""
def getStartState(self):
"""
Returns the start state for the search problem.
"""
util.raiseNotDefined()
def isGoalState(self, state):
"""
state: Search state
Returns True if and only if the state is a valid goal state.
"""
util.raiseNotDefined()
def getSuccessors(self, state):
"""
state: Search state
For a given state, this should return a list of triples, (successor,
action, stepCost), where 'successor' is a successor to the current
state, 'action' is the action required to get there, and 'stepCost' is
the incremental cost of expanding to that successor.
"""
util.raiseNotDefined()
def getCostOfActions(self, actions):
"""
actions: A list of actions to take
This method returns the total cost of a particular sequence of actions.
The sequence must be composed of legal moves.
"""
util.raiseNotDefined()
# Source code https://github.com/Deus1223/Pac-Man/blob/master/search.py
def depthFirstSearch(problem):
'''
return a path to the goal
'''
# TODO 05
from util import Stack
# the component of frontier is (state, the path to the state)
frontier = Stack()
frontier.push(((problem.getStartState()), []))
# print(f"frontier: {frontier}, problem.getStartState(): {problem.getStartState()}")
# frontier: <util.Stack object at 0x7f373dfd0640>, problem.getStartState():
# ((11, 6), <game.Grid object at 0x7f373dfd0790>)
# store the visited state
visited = [problem.getStartState()]
while not frontier.isEmpty():
print("\n\nFrontier before poping: ")
for node in frontier.getNodesInStack():
print(f"\t{node[0][0]}")
# state[0] is coordinates and state[1] is game.Grid object
(state, path) = frontier.pop()
print(f"\n\tPOPED, its state: {state[0]}, its path: {path}")
if(problem.isGoalState(state)):
print(f"\n\n\n\n\n\nGoal, state={state} , path: {path}")
break
# successors contain node, game.Grid, path, cost
successors = problem.getSuccessors(state)
print(f"\n\tsuccessors: {successors}")
for i in successors:
#print(f"i: {i} in successors ^^^")
if(i[0] not in visited): # any state has been visited doesn't need to be visited again
print(f"\n\t\ti[0]: {i[0]} not in visited:visited")
visited.append(i[0])
frontier.push((i[0], path + [i[1]]))
print(f"\n\t\tPushed i[0]^^, path + [i[1]]: it path[direction: e.g: W, T, E,...]")
return path
util.raiseNotDefined()
def breadthFirstSearch(problem):
'''
return a path to the goal
'''
# TODO 06
from util import Queue
# the component of frontier is (state, the path to the state)
frontier = Queue()
frontier.enqueue(((problem.getStartState()), []))
# store the visited state
visited = []
while(not frontier.isEmpty()):
(state, path) = frontier.dequeue()
if(problem.isGoalState(state)):
print(f"path: {path}")
return path
successors = problem.getSuccessors(state)
for i in successors:
if(i[0] not in visited): # any state has been visited doesn't need to be visited again
visited.append(i[0])
frontier.enqueue((i[0], path + [i[1]]))
return path
util.raiseNotDefined()
def uniformCostSearch(problem):
'''
return a path to the goal
'''
# TODO 07
from util import PriorityQueue
frontier = PriorityQueue()
frontier.push((problem.getStartState(), [], 0), 0)
print(problem.getStartState())
visited = []
while not frontier.isEmpty():
#print(f"\n\nfrontier: {frontier}")
curNode, path, curCost = frontier.pop()
#print(f"\n\tcurCost: {curCost}, curNode: {curNode}, path: {path}")
if curNode not in visited:
visited.append(curNode)
if problem.isGoalState(curNode):
print(f"Path to goal: {path}")
return path
successors = problem.getSuccessors(curNode)
#print(f"\n\t\t{successors}")
for neighborNode, direction, cost in successors:
#if neighbor not in visited:
print(f"\n\nneighbor: {neighborNode}, direction: {direction}, cost: {cost}")
frontier.update((neighborNode, path + [direction], curCost + cost), curCost + cost)
def nullHeuristic(state, problem=None):
"""
A heuristic function estimates the cost from the current state to the nearest
goal in the provided SearchProblem. This heuristic is trivial.
"""
return 0
# TODO 08 + 09
'''
students propose at least two heuristic functions for A*
'''
def manhattanHeuristic(position, problem):
# The Manhattan distance heuristic for a PositionSearchProblem
pacPosition = position[0]
xy2 = problem.getStartState()
foods = xy2[1].asList()
for food in foods:
print(f"food: {food}, foods: {foods}, pacPosition: {pacPosition}")
return abs(pacPosition[0] - food[0]) + abs(pacPosition[1] - food[1])
def euclideanHeuristic(position, problem):
# The Euclidean distance heuristic for a PositionSearchProblem
pacPosition = position[0]
xy2 = problem.getStartState()
foods = xy2[1].asList()
for food in foods:
return ((pacPosition[0] - food[0]) ** 2 + (pacPosition[1] - food[1]) ** 2) ** 0.5
def aStarSearch(problem, heuristic=nullHeuristic):
'''
return a path to the goal
'''
from util import PriorityQueue
# TODO 10
startingNode = problem.getStartState()
if problem.isGoalState(startingNode):
return []
visitedNodes = []
pQueue = util.PriorityQueue()
#((coordinate/node , action to current node , cost to current node),priority)
pQueue.push((startingNode, [], 0), 0)
while not pQueue.isEmpty():
currentNode, path, prevCost = pQueue.pop()
print(f"\n\nCurrentNode: {currentNode[0]}, \n\tgoals: {currentNode[1].asList()}")
if currentNode not in visitedNodes:
visitedNodes.append(currentNode)
if problem.isGoalState(currentNode):
print(f"Path: {path}")
return path
for nextNode, direction, cost in problem.getSuccessors(currentNode):
print(f"\n\tnextNode: {nextNode}")
newAction = path + [direction]
newCostToNode = prevCost + cost
heuristicCost = newCostToNode + heuristic(nextNode,problem)
print(f"\theuristicCost: {heuristicCost}, costToNode: {newCostToNode}")
pQueue.push((nextNode, newAction, newCostToNode),heuristicCost)
util.raiseNotDefined()
# Abbreviations
bfs = breadthFirstSearch
dfs = depthFirstSearch
astar = aStarSearch
ucs = uniformCostSearch
|
Markdown | UTF-8 | 1,616 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | # ConnectionResponse
- **класс** `ConnectionResponse` (`php\jsoup\ConnectionResponse`)
- **исходники** `php/jsoup/ConnectionResponse.php`
**Описание**
Class ConnectionResponse
---
#### Методы
- `->`[`headers()`](#method-headers)
- `->`[`cookies()`](#method-cookies)
- `->`[`statusCode()`](#method-statuscode) - _Get the status code of the response._
- `->`[`statusMessage()`](#method-statusmessage) - _Get the status message of the response._
- `->`[`charset()`](#method-charset)
- `->`[`body()`](#method-body)
- `->`[`bodyAsBytes()`](#method-bodyasbytes)
- `->`[`contentType()`](#method-contenttype) - _Get the response content type (e.g. "text/html");_
- `->`[`parse()`](#method-parse)
---
# Методы
<a name="method-headers"></a>
### headers()
```php
headers(): array
```
---
<a name="method-cookies"></a>
### cookies()
```php
cookies(): array
```
---
<a name="method-statuscode"></a>
### statusCode()
```php
statusCode(): int
```
Get the status code of the response.
---
<a name="method-statusmessage"></a>
### statusMessage()
```php
statusMessage(): string
```
Get the status message of the response.
---
<a name="method-charset"></a>
### charset()
```php
charset(): string
```
---
<a name="method-body"></a>
### body()
```php
body(): string
```
---
<a name="method-bodyasbytes"></a>
### bodyAsBytes()
```php
bodyAsBytes(): string
```
---
<a name="method-contenttype"></a>
### contentType()
```php
contentType(): string
```
Get the response content type (e.g. "text/html");
---
<a name="method-parse"></a>
### parse()
```php
parse(): Document
``` |
Markdown | UTF-8 | 803 | 2.734375 | 3 | [] | no_license | ---
title: "Honest Security"
subtitle: "A guide to security that's collaborative, not adversarial."
version: "1.0"
tenets:
- "The values your organization stands behind **should be well-represented in your security program.**"
- "**A positive working relationship** between the end-user and the security team is incredibly valuable and worth fostering."
- "This relationship is built on a foundation of trust that is demonstrated through **informed consent and transparency.**"
- "The security team should **anticipate and expect that end-users use their company owned devices for personal activities** and design their detection capabilities with this in mind."
- "End-users are capable of making **rational and informed decisions about security risks** when educated and honestly motivated."
---
|
Python | UTF-8 | 13,041 | 3.515625 | 4 | [] | no_license | from ..classes import cable
from ..classes import district as dt
from ..algorithms import randomize
import copy, random
class Greedy(randomize.Random):
"""
This algorithm connects every house to the battery with the shortest
manhatten distance to the house that is available.
This algorithm does that in two different ways.
- One is by putting the houses in a queue to connect
- The other is by putting the batteries in a queue
to fill up with connections to houses that are nearby.
"""
def __init__(self, district, w1, w2):
self.district = copy.deepcopy(district)
self.w1 = w1
self.w2 = w2
def house_score(self, house, battery):
"""
Given a battery, this method assigns a score to a house.
This score is determined by the manhatten distance and the output of the house.
The lower the score, the better.
"""
# Retrieving coordinates of house and battery
h_x = house.position[0]
h_y = house.position[1]
b_x = battery.position[0]
b_y = battery.position[1]
# Calculating manhatten distance
manhatten_distance = abs(h_x - b_x) + abs(h_y - b_y)
# Retrieving house max output
output = house.maxoutput
# Scoring the house by distance and output
score = self.w1 * manhatten_distance + self.w2 * output
return score
def find_battery(self, house):
"""
Given a house, this method searches for the closest available battery
with respect to the manhatten distance.
"""
# Retrieving house position
h_x = house.position[0]
h_y = house.position[1]
# Declaring a list of all possible manhatten distances per battery
manhatten_distances = {}
# Make list of all batteries that the house can be connected to
possible_batteries = [battery for battery in self.district.batteries if battery.remainder > house.maxoutput]
# If there are batteries available, search for the closest one to the house
if len(possible_batteries) > 0:
for battery in possible_batteries:
b_x = battery.position[0]
b_y = battery.position[1]
manhatten_distance = abs(h_x - b_x) + abs(h_y - b_y)
manhatten_distances[battery] = manhatten_distance
closest_battery = min(manhatten_distances.keys(), key=lambda k: manhatten_distances[k])
return closest_battery
# If there were no batteries available return False
return False
def find_houses(self, battery):
"""
Given a battery, this method searches for all the houses that it can connect to.
The houses are sorted in ascending order with respect to the manhatten distance.
"""
# Make list of eligible houses (no connections)
houses = [house for house in self.district.houses if len(house.cables) == 0]
# Sorting house by manhatten distance to the battery
houses.sort(key=lambda house:self.house_score(house, battery))
return houses
def connect_house(self, house, battery, cable):
"""
This function saves the connection between battery and house with the inputted cable.
"""
house.add_cable(cable)
self.district.add_cable(cable)
battery.add_house(house)
return None
def run_houses(self, houses):
"""
This function runs the greedy algorithm with houses (the inputted list of houses) in the queue and returns
the total price with the list of houses that were not connected.
"""
# Declaring variables that keep track of whether config is one that satisfies constraints.
success = False
no_connections = []
# Check for every house if it can be connected to a suitable battery
for house in houses:
battery = self.find_battery(house)
# If battery was found, connect the house to the battery
if battery != False:
cable = self.generate_random_cable(house, battery)
self.connect_house(house, battery, cable)
# If battery is not found, house has no connection
else:
no_connections.append(house)
# Configuration satisfies the constraints if all houses are connected
if len(no_connections) == 0:
success = True
# Calculate the price after configuration is made
self.district.calculate_price()
return {"no_connections": no_connections, "total_cost": self.district.total_cost, "district": self.district}
def run_battery(self):
"""
This function runs the greedy algorithm with batteries in the queue and returns
the total price with the list of houses that were not connected.
"""
# Variable to keep track whether configuration satisfies constraints
success = False
# Check what houses can be connected per battery
for battery in self.district.batteries:
# Find houses that can possibly be connected to battery
houses = self.find_houses(battery)
no_connections = []
# First add the shorter distance houses until not possible anymore
if len(houses) > 0:
while houses[0].maxoutput < battery.remainder:
house = houses[0]
cable = self.generate_random_cable(house, battery)
self.connect_house(house, battery, cable)
houses.pop(0)
if len(houses) == 0:
break
# Add the farther houses in the list if possible
for house in houses:
if house.maxoutput < battery.remainder and len(house.cables) == 0:
cable = self.generate_random_cable(house, battery)
self.connect_house(house, battery, cable)
else:
no_connections.append(house)
# Configuration satisfies the constraints if all houses are connected
if len(no_connections) == 0:
success = True
# Calculate the price after configuration is made
self.district.calculate_price()
return {"success": success, "no_connections": no_connections, "total_cost": self.district.total_cost, "district": self.district}
class SwapGreedy(Greedy):
"""
This algorithm runs the greedy algorithm and tries swapping afterward if
the result was of the greedy algorithm was not successfull. Even after swapping,
the result can still be unsuccessfull.
"""
def order_batteries(self):
"""
This function sorts the list of batteries from biggest to smallest remainder.
"""
batteries = [battery for battery in self.district.batteries]
batteries.sort(key=lambda x:x.remainder, reverse=True)
return batteries
def remove_connection(self, house, battery):
"""
This function removes the connection between inputted battery and house.
"""
self.district.delete_cable(house.cables[0])
house.delete_cable()
battery.delete_house(house)
return None
def swap_houses(self, battery):
"""
This functions tries to move the houses connected to the given battery to other batteries
(with lowest remainder battery as priority) if possible.
"""
for house in battery.connected:
# List of available batteries to choose from, other than the one the house is currently connected to
new_battery_choices = []
for battery_option in self.district.batteries:
# Add battery to list if it is available
if (battery_option != battery) and house.maxoutput < battery_option.remainder:
new_battery_choices.append(battery_option)
if len(new_battery_choices) > 0:
# Choosing battery with least remainder
battery_choice = min(new_battery_choices, key=lambda x:x.remainder)
# Remove old connection.
self.remove_connection(house, battery)
# Generate new cable
new_cable = self.generate_random_cable(house, battery_choice)
# Make new connection for house.
self.connect_house(house, battery_choice, new_cable)
return None
def run_houses_swap_choice(self, choice):
"""
This function runs the greedy algorithm with houses in the queue and tries swapping
(if the result was not successfull) afterward.
"""
houses = self.district.houses
# Sorting the houses by their choice (by output or random)
if choice == "random":
random.shuffle(houses)
elif choice == "sort":
houses.sort(key=lambda x:x.maxoutput, reverse=True)
# Run the greedy algorithm with houses in the queue
result = self.run_houses(houses)
# If all houses are connected, swapping is not needed
if len(result["no_connections"]) == 0:
# Calculate the price after configuration is made
self.district.calculate_price()
# We already have succes and give the result
return {"success": True, "swap": False, "district": self.district}
# Sort the batteries from biggest to smallest remainder
batteries = self.order_batteries()
# Start swapping per battery
for battery in batteries:
# Try swapping by emptying the inputted battery
self.swap_houses(battery)
# Try connecting the houses again that were not connected yet
new_result = self.run_houses(result["no_connections"])
# If swapping worked, stop and return the result
if len(new_result["no_connections"]) == 0:
# Calculate the price after configuration is made
self.district.calculate_price()
# We have succes and give the result
return {"success": True, "swap": True, "district": self.district}
# Calculate the price after configuration is made
self.district.calculate_price()
# If swapping did not help for all batteries, we have no success
return {"success": False, "swap": True, "district": self.district}
def run_houses_swap(self):
"""
This function repeats the houses swap procedure (run_houses_swap_choice),
where the queue of houses is determined randomly, until a solution is found.
"""
success = False
while success == False:
result = self.run_houses_swap_choice("random")
success = result["success"]
# If there is no success, we reset the district and try again.
if success == False:
self.reset_district()
return result
def run_battery_swap(self):
"""
This function runs the greedy algorithm with batteries in the queue and tries swapping
(if the result was not successfull) afterward.
"""
# Run the greedy algorithm with batteries in the queue
result = self.run_battery()
# If all houses are connected, swapping is not needed
if len(result["no_connections"]) == 0 :
# Calculate the price after configuration is made
self.district.calculate_price()
# We have succes and give the result
return {"success": True, "swap": False, "district": self.district}
# Sort the batteries from biggest to smallest remainder
batteries = self.order_batteries()
# Start swapping per battery
for battery in batteries:
# Try swapping by emptying the inputted battery
self.swap_houses(battery)
# Try connecting the houses again that were not connected yet
new_result = self.run_houses(result["no_connections"])
# If swapping worked, stop and return the result
if len(new_result["no_connections"]) == 0:
# Calculate the price after configuration is made
self.district.calculate_price()
# We have succes and give the result
return {"success": True, "swap": True, "district": self.district}
# Calculate the price after configuration is made
self.district.calculate_price()
# If swapping for all batteries did not work, we have no succes
return {"success": False, "swap": True, "district": self.district}
|
C | UTF-8 | 243 | 3.125 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
float y, y2;
for (float i = 1; i <= 20; i += 1) {
y = exp(i);
}
for (float i = 1; i <= 20; i += 0.1) {
y2 = exp(i);
}
printf("%f %f", y, y2);
return 0;
}
|
Python | UTF-8 | 455 | 2.796875 | 3 | [] | no_license | #!/usr/bin/python
import sys
try:
from bcrypt import hashpw, gensalt
except ImportError:
print "[!] Error importing 'bcrypt': %s" % err
sys.exit()
DEFAULT_ROUNDS = 10
def main():
if len(sys.argv) < 2:
usage()
hashed_password = hashpw(sys.argv[1], gensalt(DEFAULT_ROUNDS))
print "%s" % hashed_password
def usage():
print "Usage: %s <password>" % sys.argv[0]
sys.exit(0)
if __name__ == '__main__':
main()
|
Python | UTF-8 | 659 | 3.15625 | 3 | [] | no_license | # Introduction of Pandas
# Dependency needed to install file
# !pip install xlrd
# Import required library
import pandas as pd
# Read data from CSV file
csv_path = 'https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%204/Datasets/TopSellingAlbums.csv'
df = pd.read_csv(csv_path)
# Print first five rows of the dataframe
df.head()
print(df.head())
# Read data from Excel File and print the first five rows
xlsx_path = 'https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/PY0101EN/Chapter%204/Datasets/TopSellingAlbums.xlsx'
df = pd.read_excel(xlsx_path)
df.head()
print(df.head()) |
Python | UTF-8 | 290 | 3.125 | 3 | [] | no_license | import math
t = int(input())
while t!=0:
n,a,b = map(int, input().split(" "))
total = 0
numSilverPerQuest = a
if a > b:
numSilverPerQuest = math.floor(a/b) * a + (a % b)
min_num_quests = math.ceil(n/numSilverPerQuest)
print(min_num_quests)
t-= 1 |
Java | UTF-8 | 7,163 | 2.03125 | 2 | [] | no_license | package cn.wong.pojo;
import java.util.Date;
public class Kefudenglu {
private Integer id;
private String xingming;
private String shoujihaoma;
private String mima;
private Integer zhuangtai;
private String shenfenzheng;
private Date zuihoudenglu;
private Date zuihouqiandao;
private Integer cuowucishu;
private String youxiang;
private String xingbie;
private Integer qiandaocishu;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getXingming() {
return xingming;
}
public void setXingming(String xingming) {
this.xingming = xingming == null ? null : xingming.trim();
}
public String getShoujihaoma() {
return shoujihaoma;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column kefudenglu.ShouJiHaoMa
*
* @param shoujihaoma the value for kefudenglu.ShouJiHaoMa
*
* @mbg.generated
*/
public void setShoujihaoma(String shoujihaoma) {
this.shoujihaoma = shoujihaoma == null ? null : shoujihaoma.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column kefudenglu.MiMa
*
* @return the value of kefudenglu.MiMa
*
* @mbg.generated
*/
public String getMima() {
return mima;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column kefudenglu.MiMa
*
* @param mima the value for kefudenglu.MiMa
*
* @mbg.generated
*/
public void setMima(String mima) {
this.mima = mima == null ? null : mima.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column kefudenglu.ZhuangTai
*
* @return the value of kefudenglu.ZhuangTai
*
* @mbg.generated
*/
public Integer getZhuangtai() {
return zhuangtai;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column kefudenglu.ZhuangTai
*
* @param zhuangtai the value for kefudenglu.ZhuangTai
*
* @mbg.generated
*/
public void setZhuangtai(Integer zhuangtai) {
this.zhuangtai = zhuangtai;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column kefudenglu.ShenFenZheng
*
* @return the value of kefudenglu.ShenFenZheng
*
* @mbg.generated
*/
public String getShenfenzheng() {
return shenfenzheng;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column kefudenglu.ShenFenZheng
*
* @param shenfenzheng the value for kefudenglu.ShenFenZheng
*
* @mbg.generated
*/
public void setShenfenzheng(String shenfenzheng) {
this.shenfenzheng = shenfenzheng == null ? null : shenfenzheng.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column kefudenglu.ZuiHouDengLu
*
* @return the value of kefudenglu.ZuiHouDengLu
*
* @mbg.generated
*/
public Date getZuihoudenglu() {
return zuihoudenglu;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column kefudenglu.ZuiHouDengLu
*
* @param zuihoudenglu the value for kefudenglu.ZuiHouDengLu
*
* @mbg.generated
*/
public void setZuihoudenglu(Date zuihoudenglu) {
this.zuihoudenglu = zuihoudenglu;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column kefudenglu.ZuiHouQianDao
*
* @return the value of kefudenglu.ZuiHouQianDao
*
* @mbg.generated
*/
public Date getZuihouqiandao() {
return zuihouqiandao;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column kefudenglu.ZuiHouQianDao
*
* @param zuihouqiandao the value for kefudenglu.ZuiHouQianDao
*
* @mbg.generated
*/
public void setZuihouqiandao(Date zuihouqiandao) {
this.zuihouqiandao = zuihouqiandao;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column kefudenglu.CuoWuCiShu
*
* @return the value of kefudenglu.CuoWuCiShu
*
* @mbg.generated
*/
public Integer getCuowucishu() {
return cuowucishu;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column kefudenglu.CuoWuCiShu
*
* @param cuowucishu the value for kefudenglu.CuoWuCiShu
*
* @mbg.generated
*/
public void setCuowucishu(Integer cuowucishu) {
this.cuowucishu = cuowucishu;
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column kefudenglu.YouXiang
*
* @return the value of kefudenglu.YouXiang
*
* @mbg.generated
*/
public String getYouxiang() {
return youxiang;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column kefudenglu.YouXiang
*
* @param youxiang the value for kefudenglu.YouXiang
*
* @mbg.generated
*/
public void setYouxiang(String youxiang) {
this.youxiang = youxiang == null ? null : youxiang.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column kefudenglu.XingBie
*
* @return the value of kefudenglu.XingBie
*
* @mbg.generated
*/
public String getXingbie() {
return xingbie;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column kefudenglu.XingBie
*
* @param xingbie the value for kefudenglu.XingBie
*
* @mbg.generated
*/
public void setXingbie(String xingbie) {
this.xingbie = xingbie == null ? null : xingbie.trim();
}
/**
* This method was generated by MyBatis Generator.
* This method returns the value of the database column kefudenglu.qiandaocishu
*
* @return the value of kefudenglu.qiandaocishu
*
* @mbg.generated
*/
public Integer getQiandaocishu() {
return qiandaocishu;
}
/**
* This method was generated by MyBatis Generator.
* This method sets the value of the database column kefudenglu.qiandaocishu
*
* @param qiandaocishu the value for kefudenglu.qiandaocishu
*
* @mbg.generated
*/
public void setQiandaocishu(Integer qiandaocishu) {
this.qiandaocishu = qiandaocishu;
}
} |
TypeScript | UTF-8 | 18,551 | 3 | 3 | [
"MIT"
] | permissive | // IMPORTACIONES
let assert = require("chai").assert;
let path = require("path");
let fs = require("fs");
let fsExtra = require("fs-extra");
let aut = require("../dist/aut/automation");
function remove(ruta) {
let bool = false;
try {
if (fs.existsSync(ruta)) { // Si exite el directorio lo borramos
if (fs.statSync(ruta).isDirectory()) { // Si es un directorio
fsExtra.emptyDirSync(ruta); // Borra todo lo que haya dentro menos el propio directorio
bool = true;
} else { // Si es un archivo
fs.unlinkSync(ruta); // Borramos el archivo
bool = true
}
}
} catch (error) {
console.log(error)
}
return bool
}
describe("UnitTest AUTOMATION", () => {
it.only("walkDirSrc CORRECT", () => {
// Comprobamos que si le pasamos dos rutas recorre el proyecto Electron, y si encuentra un fichero html genera
// un fichero de la toolkit.
let appElectron = path.join(__dirname, "materialIN", "appElectron");
let appSpectron = path.join(__dirname, "materialOUT", "appSpectron");
// Borramos lo que teniamos
remove(appSpectron);
// Ejecutamos walkDirSrc y comprobamos que nos genera los ficheros
aut.walkDirSrc(appElectron, appSpectron);
assert.equal(fs.existsSync(path.join(appSpectron, "src", "html1", "html1.awe.ts")), true);
assert.equal(fs.existsSync(path.join(appSpectron, "src", "html2", "html2.awe.ts")), true);
// Comprobamos que el contenido es el que tiene que ser paara html1
let content = fs.readFileSync(path.join(appSpectron, "src", "html1", "html1.awe.ts"), 'utf8');
let expected = fs.readFileSync(path.join(__dirname, "materialOUT", "html1.awe.ts"), 'utf8');
assert.equal(content, expected);
// Comprobamos que el contenido es el que tiene que ser paara html2
content = fs.readFileSync(path.join(appSpectron, "src", "html2", "html2.awe.ts"), 'utf8');
expected = fs.readFileSync(path.join(__dirname, "materialOUT", "html2.awe.ts"), 'utf8');
assert.equal(content, expected);
});
// it.only("walkDirSrc FAIL", () => {
// // Comprobamos que si pasamos dos numeros, falla porque el proyecto Electron tiene que ser un string
// aut.walkDirSrc(123, 123);
// assert.equal(fs.existsSync(123), false);
// // Comprobamos que si al primero le pasamos un número y al segundo un string sigue fallando por lo mismo
// aut.walkDirSrc(123, "hola");
// assert.equal(fs.existsSync("hola"), false);
// // Comprobamos que si al primero le pasamos un string y al segundo un número sigue fallando, en este caso porque el proyecto Spectron tiene que ser un string
// aut.walkDirSrc(path.join(__dirname, "materialIN", "appElectron"), 123);
// assert.equal(fs.existsSync(123), false);
// // Comprobamos que si le pasamos dos string sí que lo hace, y lo crea en la raíz del proyecto
// aut.walkDirSrc(path.join(__dirname, "materialIN", "appElectron"), "hola");
// assert.equal(fs.existsSync("hola"), true);
// // Todos estos errores están controlados, ya que este método es accesible sólo por mí, además cuando lo llamo,
// // lo llamo de forma adecuada con los string correspondintes
// });
it.only("createDirectory CORRECT", () => {
// Comprobamos que si le pasamos una ruta nos genera el directorio
let ruta = path.join(__dirname, "materialOUT", "prueba", "createDirectory");
// Borramos antes lo que tenía si existía
remove(path.join(__dirname, "materialOUT", "prueba"));
// Comprobamos que todavía no se ha creado
assert.equal(fs.existsSync(ruta), false);
// Creamos el directorio
aut.createDirectory(ruta);
// Comprobamos que se ha creado
assert.equal(fs.existsSync(ruta), true);
})
// it.only("createDirectory FAIL", () => {
// // Comprobamos que si no le pasamos nada no hace nada y falla
// aut.createDirectory();
// // Comprobamos que si le pasamos un number falla, ya que el parámetro tiene que ser un string
// aut.createDirectory(123);
// assert.equal(fs.existsSync(123), false);
// // Estos errores están controlados, ya que soy yo el único que puede manejar este método, y cuando
// // llamamos a este método le pasamos el string de forma correcta con la ruta adecuada
// })
it.only("createFile CORRECT", () => {
// Comprobamos que si le pasamos los parámetros de forma correcta crea el fichero
let file = "createFile1.html";
let electronPath = path.join(__dirname, "materialIN", "appElectron", "src", "html1", "html1.html");
let spectronPath = path.join(__dirname, "materialOUT", "appSpectron", "src", "html1");
// Borramos si ya estaba creado
remove(path.join(__dirname, "materialOUT", "appSpectron", "src", "createFile1.awe.ts"))
// Comprobamos que no existe
assert.equal(fs.existsSync(path.join(__dirname, "materialOUT", "appSpectron", "src", "createFile1.awe.ts")), false);
// Creamos el archivo
aut.createFile(file, electronPath, spectronPath);
// Comprobamos que lo ha creado
assert.equal(fs.existsSync(path.join(__dirname, "materialOUT", "appSpectron", "src", "createFile1.awe.ts")), true);
})
// it.only("createFile FAIL", () => {
// // Comprobamos que si le pasamos tres number falla, ya que tienen que ser tres string
// // No hace falta comprobar que pasa si unos son string y otrs number, ya que con que
// // haya un parámetro que no sea string falla
// aut.createFile(123, 132, 132);
// // Estos errores están controlados, ya que solo yo tengo acceso al método, y solo lo llamo
// // cuando tengo los parámetros de forma correcta.
// })
it.only("checkAppPath CORRECT", () => {
// Comprobamos que si le pasamos el parámetro de forma correcta si que lo realiza
let ruta = path.join(__dirname, "..", "..", "..");
let bool = aut.checkAppPath(ruta);
assert.equal(bool, true);
// Comprobamos que si le pasamos una ruta que no es un proyecto devuelve false
ruta = path.join(__dirname, "..", "..", "..", "..");
bool = aut.checkAppPath(ruta);
assert.equal(bool, false);
// Comprobamos que si le pasamos otra ruta nos devuelve true, ya que las rutas las maneja internamente fileSystem
// bool = aut.checkAppPath("B:/WORKSPACE\\NODE-WORKSPACE/TFG\\spectron-e2e/node_modules\\testing-awe");
// assert.equal(bool, true);
})
// it.only("checkAppPath FAIL", () => {
// // Comprobamos que si le pasamos un number falla, ya que le tenemos que pasar un string
// let ruta = 123;
// let bool = aut.checkAppPath(ruta);
// assert.equal(bool, false);
// // Comprobamos que si no le pasamos nada falla, ya que le tenemos que pasar un string
// bool = aut.checkAppPath();
// assert.equal(bool, false);
// // Comprobamos que si le pasamos una ruta mal, nos devuelve false ya que no existe el directorio
// ruta = path.join(__dirname, "prueba");
// bool = aut.checkAppPath(ruta);
// assert.equal(bool, false);
// // Comprobamos que si le pasamos otra ruta mal, nos devuelve false
// bool = aut.checkAppPath("B:/WORKSPACE|NODE-WORKSPACE/TFG|spectron-e2e/node_modules\\testing-awe");
// assert.equal(bool, false);
// })
it.only("checkSameRoot CORRECT", () => {
// Comprobamos que si le pasamos los datos de forma correcta hace lo que tiene que hacer
let appElectron = path.join(__dirname, "materialIN");
let appSpectron = path.join(__dirname, "materialOUT");
let bool = aut.checkSameRoot(appElectron, appSpectron);
assert.equal(bool, true);
})
// it.only("checkSameRoot FAIL", () => {
// // Comprobamos que si le pasamos por cabecera algo distinto de un string devuelve false
// let bool = aut.checkSameRoot(123, 123);
// assert.equal(bool, false);
// bool = aut.checkSameRoot(123, true);
// assert.equal(bool, false);
// bool = aut.checkSameRoot(true, 123);
// assert.equal(bool, false);
// bool = aut.checkSameRoot(true, true);
// assert.equal(bool, false);
// // Este error no va suceder, ya que este método lo controlo yo, y a este método solo le pasamos dos string
// })
it.only("checkExistDirectory CORRECT", () => {
// Comprobamos que hace lo que tiene que hacer cuando le pasamos el parámetro correcto
let ruta = path.join(__dirname, "materialIN", "appElectron");
let bool = aut.checkExistDirectory(ruta)
assert.equal(bool, true);
// Comprobamos que si una ruta no existe nos devuelve false
ruta = "B:/TFG/Mario";
bool = aut.checkExistDirectory(ruta);
assert.equal(bool, false);
});
// it.only("checkExistDirectory FAIL", () => {
// // Comprobamos que si introducimos un number, o no enviamos nada nos devuelve false
// let ruta = 123;
// let bool = aut.checkExistDirectory(ruta)
// assert.equal(bool, false);
// bool = aut.checkExistDirectory()
// assert.equal(bool, false);
// // Comprobamos que si le pasamos una ruta incorrecta nos devuelve false
// // bool = aut.checkExistDirectory("B:/WORKSPACE|NODE-WORKSPACE/TFG|spectron-e2e/node_modules\\testing-awe")
// // assert.equal(bool, false);
// // Comprobamos que si le pasamos una ruta correcta pero "rara" nos devuelve true
// // bool = aut.checkExistDirectory("B:/WORKSPACE\\NODE-WORKSPACE/TFG\\spectron-e2e/node_modules\\testing-awe")
// // assert.equal(bool, true);
// // Estos errores no van a suceder porque siempre que llamamos a este método, le pasamos un string, y luego
// // el ya dependiendo de si existe la ruta o no devuelve verdadero o falso
// })
it.only("check CORRECT", () => {
// Comprobamos que pasandole los parámetros de forma correcta funciona
let appElectron = path.join(__dirname, "project", "appElectron");
let appSpectron = path.join(__dirname, "project", "appSpectron");
let bool = aut.check(appElectron, appSpectron);
assert.equal(bool, true);
})
// it.only("check FAIL", () => {
// // Comprobamos que si no le pasamos dos string falla y devuelve false
// let bool = aut.check(123, 123);
// assert.equal(bool, false);
// bool = aut.check(123, true);
// assert.equal(bool, false);
// bool = aut.check(true, 123);
// assert.equal(bool, false);
// bool = aut.check(true, true);
// assert.equal(bool, false);
// bool = aut.check("hola");
// assert.equal(bool, false);
// bool = aut.check(123);
// assert.equal(bool, false);
// bool = aut.check(true);
// assert.equal(bool, false);
// bool = aut.check();
// assert.equal(bool, false);
// // Comprobamos que si le pasamos rutas incorrectas devuelve false
// bool = aut.check("hola", "adios");
// assert.equal(bool, false);
// bool = aut.check("hola/adios", "adios/hola");
// assert.equal(bool, false);
// })
it.only("pathUnixWindows CORRECT", () => {
// Comprobamos que si le pasamos una ruta nos la devuelve con los slash dependiendo de si
// estamos ejecutando el programa en windows o unix
let ruta = "hola/adios/quetal/estas/muy/bien";
let content = aut.pathUnixWindows(ruta);
let expected = "hola\\adios\\quetal\\estas\\muy\\bien";
assert.equal(content, expected);
// Probamos que si le pasamos una ruta windows, la devuelve
content = aut.pathUnixWindows(expected);
assert.equal(content, expected);
// Probamos con otra ruta
ruta = "hola\\adios/quetal\\estas/muy\\bien"
content = aut.pathUnixWindows(ruta)
assert.equal(content, expected)
})
// it.only("pathUnixWindows FAIL", () => {
// // Comprobamos que si no le pasamos nada o cualquier otro tipo de datos, nos devuelve una cadena vacía
// let content = aut.pathUnixWindows();
// assert.equal(content, "");
// content = aut.pathUnixWindows(123);
// assert.equal(content, "");
// content = aut.pathUnixWindows(true);
// assert.equal(content, "");
// // Estos erroes no puden darser, ya que la información que ponga en el aweconfig.json la convertimos a string
// // Por lo tanto, nunca puede pasarle un número un boolean...
// })
it.only("getHtmlElements CORRECT", () => {
// Comprobamos que nos proporciona la información de forma correcta
let elements = []
let realElements = aut.getHtmlElements();
let names = ["a", "abbr", "address", "article", "audio", "b", "base", "bdi", "bdo", "blockquote", "body", "br", "button", "canvas", "caption", "cite", "code", "col", "colgroup", "data", "datalist", "dd", "del", "details", "dfn", "div", "dl", "dt", "em", "embed", "fieldset", "figcaption", "figure", "footer", "form", "h", "head", "header", "hr", "html", "i", "iframe", "img", "input", "ins", "kbd", "label", "legend", "li", "link", "main", "mark", "meta", "meter", "nav", "noscript", "ol", "option", "p", "pre", "progress", "q", "root", "s", "samp", "section", "select", "small", "source", "span", "strong", "sub", "summary", "sup", "svg", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "u", "ul", "var", "video", "wbr"]
for (let name of names) { // Nombre de las clases
elements.push(name[0].toUpperCase() + name.slice(1))
}
// Comprobamos que tienen el mismo tamaño
assert.equal(realElements.length, elements.length)
// Comprobamos clase a clase, que se corresponden
for (let i = 0; i < realElements.length; ++i) {
assert.equal(realElements[i], elements[i])
}
})
// it.only("getHtmlElements FAIL", () => {
// // Comprobamos que si le pasamos algo nos sigue devolviendo la información de forma correcta
// let elements = []
// let realElements = aut.getHtmlElements(true);
// let names = ["a", "abbr", "address", "article", "audio", "b", "base", "bdi", "bdo", "blockquote", "body", "br", "button", "canvas", "caption", "cite", "code", "col", "colgroup", "data", "datalist", "dd", "del", "details", "dfn", "div", "dl", "dt", "em", "embed", "fieldset", "figcaption", "figure", "footer", "form", "h", "head", "header", "hr", "html", "i", "iframe", "img", "input", "ins", "kbd", "label", "legend", "li", "link", "main", "mark", "meta", "meter", "nav", "noscript", "ol", "option", "p", "pre", "progress", "q", "root", "s", "samp", "section", "select", "small", "source", "span", "strong", "sub", "summary", "sup", "svg", "table", "tbody", "td", "textarea", "tfoot", "th", "thead", "time", "title", "tr", "u", "ul", "var", "video", "wbr"]
// for (let name of names) { // Nombre de las clases
// elements.push(name[0].toUpperCase() + name.slice(1))
// }
// // Comprobamos que tienen el mismo tamaño
// assert.equal(realElements.length, elements.length)
// // Comprobamos clase a clase, que se corresponden
// for (let i = 0; i < realElements.length; ++i) {
// assert.equal(realElements[i], elements[i])
// }
// // Comprobamos si introucimos un number
// realElements = aut.getHtmlElements(123);
// // Comprobamos que tienen el mismo tamaño
// assert.equal(realElements.length, elements.length)
// // Comprobamos clase a clase, que se corresponden
// for (let i = 0; i < realElements.length; ++i) {
// assert.equal(realElements[i], elements[i])
// }
// // Comprobamos si introucimos un string
// realElements = aut.getHtmlElements("hola");
// // Comprobamos que tienen el mismo tamaño
// assert.equal(realElements.length, elements.length)
// // Comprobamos clase a clase, que se corresponden
// for (let i = 0; i < realElements.length; ++i) {
// assert.equal(realElements[i], elements[i])
// }
// // Estos erroes están controlados, ya que este método lo llamo yo no el usuario, por lo que siempre le llamo sin nada
// })
it.only("walkDir CORRECT", () => {
// Comprobamos que si el fichero aweconfig.json está bien nos los genera sin ningún problema
let ruta = path.join(__dirname, "..", "..", "..", "testingAWE");
aut.walkDir()
assert.equal(fs.existsSync(ruta), true);
})
// it.only("walkDir FAIL", () => {
// // En este caso solo tenemos que probar que la entrada sea distinto de vacía, ya que lo que hacemos en este método
// // ya lo hemos probado en los test anteriores
// // Comprobamos que introduciendo un number sigue funcionando, ya que este método funciona sin parámetros
// let ruta = path.join(__dirname, "..", "..", "..", "testingAWE");
// aut.walkDir(123);
// assert.equal(fs.existsSync(ruta), true);
// // Comprobamos que introduciendo un string sigue funcionando, ya que este método funciona sin parámetros
// ruta = path.join(__dirname, "..", "..", "..", "testingAWE");
// aut.walkDir("hola");
// assert.equal(fs.existsSync(ruta), true);
// // Comprobamos que introduciendo un boolean sigue funcionando, ya que este método funciona sin parámetros
// ruta = path.join(__dirname, "..", "..", "..", "testingAWE");
// aut.walkDir(true);
// assert.equal(fs.existsSync(ruta), true);
// })
}); |
Swift | UTF-8 | 1,751 | 2.765625 | 3 | [] | no_license | import Common
import Firebase
import Foundation
import Framework_BabyPatterns
import Library
struct StorageFacade: Loggable {
let shouldPrintDebugLog = true
private let storageReference = Storage.storage().reference()
typealias DownloadResponseHandler = (_ data: Data?, _ error: Error?) -> Void
func uploadData(data: Data, requestType type: FirebaseRequestType) {
log("Uploading \(type.rawValue)...", object: self, type: .info)
guard let fullReference = pathForRequest(type: type) else {
let message = "Couldn't make full storage reference for path with request type: \(type.rawValue)"
log(message, object: self, type: .error)
return
}
fullReference.putData(data, metadata: nil) { metadata, error in
guard metadata != nil && error == nil else {
// TODO: handle error?
self.log("Failure uploading \(type.rawValue)", object: self, type: .error)
return
}
self.log("Upload complete! - \(type.rawValue)", object: self, type: .info)
}
}
func download(requestType type: FirebaseRequestType, callback: @escaping DownloadResponseHandler) {
guard let fullReference = pathForRequest(type: type) else { return }
// TODO: wrap data & error in a request object
fullReference.getData(maxSize: 100 * 1024 * 1024, completion: { data, error in
callback(data, error)
})
}
private func pathForRequest(type: FirebaseRequestType) -> StorageReference? {
guard let uid = Auth.auth().currentUser?.uid else {
return nil
}
return storageReference.child("/users/" + uid + "/" + type.rawValue)
}
}
|
C# | UTF-8 | 2,305 | 2.796875 | 3 | [] | no_license | using System;
using System.Linq;
using System.Collections.Generic;
using ViceCity.Models.Neghbourhoods.Contracts;
using ViceCity.Models.Players.Contracts;
namespace ViceCity.Models.Neghbourhoods
{
public class GangNeighbourhood : INeighbourhood
{
public void Action(IPlayer mainPlayer, ICollection<IPlayer> civilPlayers)
{
while (true)
{
var gunPlayer = mainPlayer.GunRepository.Models.FirstOrDefault();
if (gunPlayer == null || !mainPlayer.IsAlive)
{
break;
}
var enemyPlayer = civilPlayers.FirstOrDefault();
while (true)
{
if (gunPlayer.TotalBullets == 0 && gunPlayer.BulletsPerBarrel == 0)
{
mainPlayer.GunRepository.Remove(gunPlayer);
break;
}
int bullets = gunPlayer.Fire();
enemyPlayer.TakeLifePoints(bullets);
if (!enemyPlayer.IsAlive)
{
civilPlayers.Remove(enemyPlayer);
enemyPlayer = civilPlayers.FirstOrDefault();
}
}
}
bool isDeadMainPlayer = false;
var curentCivilPlayers = civilPlayers.FirstOrDefault();
//TODO (Infinity Loop?)
//if (curentCivilPlayers.GunRepository.Models.Count == 0)
//{
// return;
//}
while (true)
{
var gunCivilPlayer = curentCivilPlayers.GunRepository.Models.FirstOrDefault();
while (true)
{
if (gunCivilPlayer == null || !gunCivilPlayer.CanFire)
{
break;
}
mainPlayer.TakeLifePoints(gunCivilPlayer.Fire());
if (!mainPlayer.IsAlive)
{
isDeadMainPlayer = true;
break;
}
}
if (isDeadMainPlayer)
{
break;
}
}
}
}
}
|
JavaScript | UTF-8 | 4,059 | 2.703125 | 3 | [
"MIT"
] | permissive | //insert ride actions here:
//how long to wait, request ride, add location,
//change location, fetch drivers(nearby),
//fetch drivers(all), add to previous rides(mc),
//add to previous rides(driver)
import axios from 'axios';
export const RIDE_ERROR = 'RIDE_ERROR';
export const HOW_LONG = 'HOW_LONG';
export const REQUEST_RIDE = 'REQUEST_RIDE';
export const REQUESTING_RIDE = 'REQUESTING_RIDE';
export const ADD_LOCATION = 'ADD_LOCATION';
export const ADDING_LOCATION = 'ADDING_LOCATION';
export const CHANGE_LOCATION = 'CHANGE_LOCATION';
export const CHANGING_LOCATION = 'CHANGING_LOCATION';
export const FETCH_NEARBY = 'FETCH_NEARBY';
export const FETCH_ALL = 'FETCH_ALL';
export const FETCHING_NEARBY = 'FETCHING_NEARBY';
export const FETCHING_ALL = 'FETCHING_ALL';
export const ADD_PREVIOUS_MC = 'ADD_PREVIOUS_MC';
export const ADD_PREVIOUS_DRIVER = 'ADD_PREVIOUS_DRIVER';
export const ADDING_PREVIOUS_MC = 'ADDING_PREVIOUS_MC';
export const ADDING_PREVIOUS_DRIVER = 'ADDING_PREVIOUS_DRIVER';
export const how_long = () => {
}
export const requestRide = () => {
}
export const requestingRide = () => {
}
export const addLocation = location => {
const newLocation = axios.post('https://ride4life.herokuapp.com/user/${user.id}/location', newLocation)
return dispatch => {
dispatch({ type: ADDING_LOCATION })
newLocation
.then(({ data }) => {
dispatch({
type: ADD_LOCATION,
payload: data
})
})
.catch(error => {
dispatch({
type: RIDE_ERROR,
payload: error
})
})
}
}
export const changeLocation = location => {
const changedLocation = axios.put('https://ride4life.herokuapp.com/user/${user.id}/location', changedLocation)
return dispatch => {
dispatch({ type: CHANGING_LOCATION });
changedLocation
.then(({ data }) => {
dispatch({
type: CHANGE_LOCATION,
payload: data
})
})
.catch(error => {
dispatch({
type: RIDE_ERROR,
payload: error
})
})
}
}
export const fetchNearby = () => {
}
export const fetchAll = () => {
const drivers = axios.get('https://ride4life.herokuapp.com/driver');
return dispatch => {
dispatch({ type: FETCHING_ALL });
drivers
.then(({ data }) => {
dispatch({
type: FETCH_ALL,
payload: data
})
})
.catch(error => {
dispatch({
type: RIDE_ERROR,
payload: error
})
})
}
}
export const addPreviousMC = () => {
const newPrevious = axios.post('https://ride4life.herokuapp.com/user/${user.id}/previous', newPrevious)
return dispatch => {
dispatch({ type: ADDING_PREVIOUS_MC })
newPrevious
.then(({ data }) => {
dispatch({
type: ADD_PREVIOUS_MC,
payload: data
})
})
.catch(error => {
dispatch({
type: RIDE_ERROR,
payload: error
})
})
}
}
export const addPreviousDriver = () => {
const newPrevious = axios.post('https://ride4life.herokuapp.com/driver/${driver.id}/previous', newPrevious)
return dispatch => {
dispatch({ type: ADDING_PREVIOUS_DRIVER });
newPrevious
.then(({ data }) => {
dispatch({
type: ADD_PREVIOUS_DRIVER,
payload: data
})
})
.catch(error => {
dispatch({
type: RIDE_ERROR,
payload: error
})
})
}
} |
Java | UTF-8 | 325 | 1.742188 | 2 | [] | no_license | package org.hillhouse.searchdb.models.diskDS;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
public class SSTableDataValue {
private List<SSTableDataValueItem> dataValueItems;
}
|
Python | UTF-8 | 82 | 3.21875 | 3 | [] | no_license | letters = list(map(chr, range(97, 123)))
for letter in letters:
print(letter)
|
Java | UTF-8 | 1,234 | 2.0625 | 2 | [] | no_license | package com.gcit.lms;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import com.gcit.lms.dao.AuthorDAO;
import com.gcit.lms.dao.BookDAO;
import com.gcit.lms.dao.GenreDAO;
import com.gcit.lms.dao.PublisherDAO;
import com.mongodb.MongoClient;
@EnableTransactionManagement
@Configuration
public class LMSConfig {
@Bean
public BookDAO bkDao() {
return new BookDAO();
}
@Bean
public AuthorDAO authDao() {
return new AuthorDAO();
}
@Bean
public PublisherDAO pubDao() {
return new PublisherDAO();
}
@Bean
public GenreDAO genreDAO() {
return new GenreDAO();
}
@Bean
public MongoDbFactory getMongoDbFactory() throws Exception{
return new SimpleMongoDbFactory(new MongoClient("localhost", 27017), "local");
}
@Bean
public MongoTemplate getMongoTemplate() throws Exception{
MongoTemplate mongoTemplate = new MongoTemplate(getMongoDbFactory());
return mongoTemplate;
}
}
|
Rust | UTF-8 | 1,225 | 3.09375 | 3 | [
"MIT"
] | permissive | extern crate sitemap;
use sitemap::reader::{SiteMapReader,SiteMapEntity};
use std::fs::{File, write};
fn main() -> std::io::Result<()> {
let mut urls = Vec::new();
let mut sitemaps = Vec::new();
let mut errors = Vec::new();
let file = File::open("sitemap.xml").expect("Unable to open file.");
let parser = SiteMapReader::new(file);
for entity in parser {
match entity {
SiteMapEntity::Url(url_entry) => {
urls.push(url_entry);
},
SiteMapEntity::SiteMap(sitemap_entry) => {
sitemaps.push(sitemap_entry);
},
SiteMapEntity::Err(error) => {
errors.push(error);
},
}
}
// get_url from the source code, unwrap to get the payload value inside Some
println!("payload = {:?}", urls[0].loc.get_url().unwrap());
let mut output = String::new();
for url in urls {
let payload = url.loc.get_url().unwrap();
println!("{}", &payload);
let payload_with_new_line = format!("{}\n", &payload);
output.push_str(&payload_with_new_line);
}
write("sitemap.txt", &output)?;
println!("errors = {:?}", errors);
Ok(())
} |
Java | UHC | 671 | 3.078125 | 3 | [] | no_license | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/*
* InputStream --> Reader --> Memory --> Writer --> OutputStream
*/
public class BridgeClassDemo {
public static void main(String[] args) throws IOException {
System.out.println(" Ͻʴϱ? : ");
InputStream is = System.in; // ǥ Է(from keyboard)
InputStreamReader isr = new InputStreamReader(is);
// System.out.println(isr.getEncoding());
BufferedReader br = new BufferedReader(isr);
String season = br.readLine();
System.out.println("season = "+season);
}
}
|
Markdown | UTF-8 | 1,405 | 3.28125 | 3 | [] | no_license | # 《设计模式的艺术》第1章学习笔记
参考CSDN博客:[史上最全设计模式导学目录](https://blog.csdn.net/LoveLion/article/details/17517213)
## 第1章 从招式与内功谈起——设计模式概述
1. 模式的定义:模式是在特定环境下人们解决某类重复出现问题的一套成功或有效的解决方案。
2. 最早将模式的思想引入软件工程方法学的是1991-1992年以“四人组(Gang of Four,简称GoF,分别是Erich Gamma, Richard Helm, Ralph Johnson和John Vlissides)”自称的四位著名软件工程学者,他们在1994年归纳发表了23种在软件开发中使用频率较高的设计模式,旨在用模式来统一沟通面向对象方法在分析、设计和实现间的鸿沟。
3. 设计模式的定义:设计模式(Design Pattern)是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结,使用设计模式是为了可重用代码、让代码更容易被他人理解并且保证代码可靠性。
4. 在学习每一个设计模式时至少应该掌握如下几点:这个设计模式的意图是什么,它要解决一个什么问题,什么时候可以使用它;它是如何解决的,掌握它的结构图,记住它的关键代码;能够想到至少两个它的应用实例,一个生活中的,一个软件中的;这个模式的优缺点是什么,在使用时要注意什么。
|
Markdown | UTF-8 | 5,079 | 2.8125 | 3 | [] | no_license | Unit 8: Group Milestone - README Example
===
# ReminderApp
## Table of Contents
1. [Overview](#Overview)
1. [Product Spec](#Product-Spec)
1. [Wireframes](#Wireframes)
## Overview
### Description
Scheduling Application that motivates people who have similar goals and interests to connect, learn, and progress together. Creating a community in which people encourage each other to take action towards such goals/interest.
### App Evaluation
- **Category:** Productivity / Social Networking
- **Mobile:** This app would be primarily developed for mobile.
- **Story:** Helps individuals keep track of their schedule, ensure productivity using effective alarm system/peer pressure, encourage habit tracking activities, and connects people with the same goals.
- **Market:** Any individual could choose to use this app.
- **Habit:** This app could help increase productivity if used daily.
- **Scope:** First, we would start with allowing users to add their schedules, goals, and reminders in the app. Then, we will develop more ways to encourage users to stay on track of their schedule using rewarding systems. Lastly, we plan to make it possible for users to interact with each other and pursue goals together.
## Product Spec
### 1. User Stories (Required and Optional)
**Required Must-have Stories**
- [x] Users can sign up
- [x] Users can log in
- [x] Navigate between tabs
- [x] Set up goals and remiders.
- [x] Scedule/calendar page
- [x] Logout
- [x] Stay signed in
- [x] Nice TO-DO page
- [x] Launch screen
- [x] View time
- [x] Allow notification
- [x] View personalized reminders only
- [ ] Settings (Accesibility, Notification, General, etc.)
<img src='http://g.recordit.co/exFJGvSekg.gif' />
<img src='http://g.recordit.co/7DS4TmTyKm.gif' />
<img src='http://g.recordit.co/V8yScgkPx1.gif' />
<img src='http://g.recordit.co/dkm77jwRML.gif' />
**Optional Nice-to-have Stories**
* Get recommendation for timeline to work on their schedule
* Connect with friends, work in pair/group, remind/encourage each other
* Upload 24-hour stories of daily achievement
* Have a reward system for completing each task
* Connect to personalized music playlists, and share the playlist with your peers
### 2. Screen Archetypes
* Login
* Register - User signs up or logs into their account
* Upon Download/Reopening of the application, the user is prompted to log in to gain access to their profile information to be properly matched with another person.
* ...
* Messaging Screen - Chat for users to communicate (direct 1-on-1)
* Upon selecting music choice users matched and message screen opens
* Profile Screen
* Allows user to upload a photo and fill up their schedule for the week/ day.
* Settings Screen
* Lets people change language, and app notification settings
### 3. Navigation
**Tab Navigation** (Tab to Screen)
* Profile/Settings
* Friend Search and Interest Groups
* Schedule/ to-do list
* Reminder Tab (Home)
Optional:
* Music playlists
* Stories
* Reward progress
**Flow Navigation** (Screen to Screen)
* Forced Log-in -> Account creation if no log in is available.
* Profile -> Text field to be modified.
* Schedule/ to-do list -> Pick time for the activity
* Reminder Tab (Home) -> Move to activity's information and message to your partner for this activity.
* Friend Search and Interest Groups -> Search for friends and chat boxes.
* Settings -> Toggle settings.
## Wireframes
<img src="https://i.imgur.com/l7bsLfm.jpg" width=800><br>
## Schema
### Models
#### Users
| Property | Type | Description |
| ------------- | -------- | ------------|
| userId | String | unique id for the user (default field) |
| name | String | user name |
| image | File | profile image |
| goal | List | list of goals |
#### Reminder
| Property | Type | Description |
| ------------- | -------- | ------------|
| objectId | String | unique id for the reminder (default field) |
| task | String | upcoming task |
| deadline | Date | profile image |
| lateDate | Count | number of late date |
| partner | Pointer to User | your friend info |
#### Conversation
| Property | Type | Description |
| ------------- | -------- | ------------|
| friendID | String | unique id for your friend (default field) |
| friendName | String | name of friend |
| message | Dictionary | database of text messages |
### Networking
#### List of network requests by screen
- Home Screen
- (Read/GET) Query all reminders
- (Create/POST) Create a reminder
- (Delete) Delete an existing reminder
- (Update/PUT) Update a reminder
- Profile Screen
- (Read/GET) Query logged in user object
- (Update/PUT) Update user profile image
- Setting
- (Read/GET) Query setting information
- (Update/PUT) Update setting option
- Message
- (Read/GET) Query all text messages
- (Create/POST) Send a text message
|
Markdown | UTF-8 | 2,249 | 2.796875 | 3 | [] | no_license | # Nina van Gorkom

*International Standard Name Identifier (ISNI):* 0000 0000 6398 0326
## Biography
Nina van Gorkom was born in 1928 to a family of socialist intellectuals. Her father was a member of the Dutch parliament. She studied at Leyden University and during this time she became a Catholic. In 1952, she married Lodewijk van Gorkom, a Dutch diplomat.
In 1965, Lodewijk was posted to Thailand and Nina started learning the Thai language. She took a keen interest in Buddhism, attending classes for foreigners at Wat Mahathat. There she met, in the summer of 1966, Sujin Boriharnwanaket. Impressed by the profundity of the Buddhist teachings, she became convinced of the truth of the Buddha’s words and later assisted Khun Sujin in discussions about Buddhism for Thai radio stations. These talks were later published as Buddhism in Daily Life, her first book.
Nina and Lodewijk left Thailand in 1970 and lived in Japan, New York, Indonesia (where Lodewijk was the Dutch ambassador) and Austria. Lodewijk retired in 1990 and she now lives in The Hague in Holland.
Nina’s writings are well-known amongst English speaking Buddhists, and she is highly respected in Thailand where several of her books have been translated into the Thai language with (after many reprints) over one hundred thousand copies now. Her books have also been translated in Sri Lanka, Indonesia, Nepal, China, Vietnam and Germany.
### Prior Work:
Buddhism in Daily Life; The Buddha’s Path; Cetasikas; A Survey of Paramattha Dhammas (translator); The Perfections Leading to Enlightenment; Metta: Lovingkindness in Buddhism (translator); The Conditionality of life; The Buddhist Teaching on Physical Phenomena; Taking Refuge in Buddhism (translator); The World in the Buddhist Sense; Understanding Reality (translator); Introduction to Abhidhamma; Abhidhamma in Daily Life.
Location: The Hague, Holland.
#### Interview with Nina van Gorkom about Abhidhamma
[https://archive.org/details/interview_201908](https://archive.org/details/interview_201908)
#### Interview by Robert Kirkpatrick, 1999
[https://github.com/alwell/Zolag_Archive/blob/master/Nina_van_Gorkom/nina_interview.md](https://github.com/alwell/Zolag_Archive/blob/master/Nina_van_Gorkom/nina_interview.md)
|
Java | UTF-8 | 6,587 | 2.078125 | 2 | [
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"LicenseRef-scancode-unknown"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.hadoop.hdds.utils.db.cache;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.apache.hadoop.hdds.annotation.InterfaceAudience.Private;
import org.apache.hadoop.hdds.annotation.InterfaceStability.Evolving;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Cache implementation for the table. Partial Table cache, where the DB state
* and cache state will not be same. Partial table cache holds entries until
* flush to DB happens.
* @param <KEY>
* @param <VALUE>
*/
@Private
@Evolving
public class PartialTableCache<KEY, VALUE> implements TableCache<KEY, VALUE> {
public static final Logger LOG =
LoggerFactory.getLogger(PartialTableCache.class);
private final Map<CacheKey<KEY>, CacheValue<VALUE>> cache;
private final NavigableMap<Long, Set<CacheKey<KEY>>> epochEntries;
private final ExecutorService executorService;
private final CacheStatsRecorder statsRecorder;
public PartialTableCache() {
// We use concurrent Hash map for O(1) lookup for get API.
// During list operation for partial cache we anyway merge between DB and
// cache state. So entries in cache does not need to be in sorted order.
// And as concurrentHashMap computeIfPresent which is used by cleanup is
// atomic operation, and ozone level locks like bucket/volume locks
// protect updating same key, here it is not required to hold cache
// level locks during update/cleanup operation.
// 1. During update, it is caller responsibility to hold volume/bucket
// locks.
// 2. During cleanup which removes entry, while request is updating cache
// that should be guarded by concurrentHashMap guaranty.
cache = new ConcurrentHashMap<>();
epochEntries = new ConcurrentSkipListMap<>();
// Created a singleThreadExecutor, so one cleanup will be running at a
// time.
ThreadFactory build = new ThreadFactoryBuilder().setDaemon(true)
.setNameFormat("PartialTableCache Cleanup Thread - %d").build();
executorService = Executors.newSingleThreadExecutor(build);
statsRecorder = new CacheStatsRecorder();
}
@Override
public CacheValue<VALUE> get(CacheKey<KEY> cachekey) {
CacheValue<VALUE> value = cache.get(cachekey);
statsRecorder.recordValue(value);
return value;
}
@Override
public void loadInitial(CacheKey<KEY> key, CacheValue<VALUE> value) {
// Do nothing for partial table cache.
}
@Override
public void put(CacheKey<KEY> cacheKey, CacheValue<VALUE> value) {
cache.put(cacheKey, value);
epochEntries.computeIfAbsent(value.getEpoch(), v -> new HashSet<>())
.add(cacheKey);
}
@Override
public void cleanup(List<Long> epochs) {
executorService.execute(() -> evictCache(epochs));
}
@Override
public int size() {
return cache.size();
}
@Override
public Iterator<Map.Entry<CacheKey<KEY>, CacheValue<VALUE>>> iterator() {
statsRecorder.recordIteration();
return cache.entrySet().iterator();
}
@VisibleForTesting
@Override
public void evictCache(List<Long> epochs) {
Set<CacheKey<KEY>> currentCacheKeys;
CacheKey<KEY> cachekey;
long lastEpoch = epochs.get(epochs.size() - 1);
for (long currentEpoch : epochEntries.keySet()) {
currentCacheKeys = epochEntries.get(currentEpoch);
// If currentEntry epoch is greater than last epoch provided, we have
// deleted all entries less than specified epoch. So, we can break.
if (currentEpoch > lastEpoch) {
break;
}
// As ConcurrentHashMap computeIfPresent is atomic, there is no race
// condition between cache cleanup and requests updating same cache entry.
if (epochs.contains(currentEpoch)) {
for (Iterator<CacheKey<KEY>> iterator = currentCacheKeys.iterator();
iterator.hasNext();) {
cachekey = iterator.next();
cache.computeIfPresent(cachekey, ((k, v) -> {
// If cache epoch entry matches with current Epoch, remove entry
// from cache.
if (v.getEpoch() == currentEpoch) {
if (LOG.isDebugEnabled()) {
LOG.debug("CacheKey {} with epoch {} is removed from cache",
k.getCacheKey(), currentEpoch);
}
return null;
}
return v;
}));
}
// Remove epoch entry, as the entry is there in epoch list.
epochEntries.remove(currentEpoch);
}
}
}
@Override
public CacheResult<VALUE> lookup(CacheKey<KEY> cachekey) {
CacheValue<VALUE> cachevalue = cache.get(cachekey);
statsRecorder.recordValue(cachevalue);
if (cachevalue == null) {
return new CacheResult<>(CacheResult.CacheStatus.MAY_EXIST,
null);
} else {
if (cachevalue.getCacheValue() != null) {
return new CacheResult<>(CacheResult.CacheStatus.EXISTS, cachevalue);
} else {
// When entity is marked for delete, cacheValue will be set to null.
return new CacheResult<>(CacheResult.CacheStatus.NOT_EXIST, null);
}
}
}
@VisibleForTesting
@Override
public NavigableMap<Long, Set<CacheKey<KEY>>> getEpochEntries() {
return epochEntries;
}
@Override
public CacheStats getStats() {
return statsRecorder.snapshot();
}
}
|
Java | UTF-8 | 545 | 3.75 | 4 | [] | no_license | public class Guessing {
public static void main(String[] args) {
for (int x = 1; x <= 35; x++) {
int guess = x;
if (guess < 20) {
System.out.println("You lose, try again!");
} else if (guess <= 29) {
System.out.println("You are getting closer!");
} else if (guess < 25) {
System.out.println("Keep guessing!");
} else if (guess == 30) {
System.out.println("You guessed right!");
} else {
System.out.println("Give up...");
}
}
}
} |
Python | UTF-8 | 1,467 | 2.640625 | 3 | [
"Apache-2.0"
] | permissive | from base.base_train import BaseTrain
from tqdm import tqdm
import numpy as np
import matplotlib.pyplot as plt
class ExampleTrainer(BaseTrain):
def __init__(self, sess, model, data, config,logger, **kwargs):
super().__init__(sess, model, data, config,logger, **kwargs)
def train_epoch(self):
loop = tqdm(range(self.data.get_num_data() // self.config["batch_size"]))
losses = []
for _ in loop:
loss = self.train_step()
losses.append(loss)
loss = np.mean(losses)
cur_it = self.model.global_step.eval(self.sess)
summaries_dict = {
'loss': loss,
}
self.logger.summarize(cur_it, summaries_dict=summaries_dict)
self.model.save(self.sess)
def train_step(self):
batch_x, batch_y = self.data.next_batch(self.config["batch_size"])
feed_dict = {self.model.x: batch_x, self.model.y: batch_y, self.model.is_training: True}
_, loss = self.sess.run([self.model.train_step, self.model.loss],
feed_dict=feed_dict)
return loss
def test_model(self):
# Ideally this wouldn't be hard coded here, but it is just a test so whatever
x = np.linspace(-1, 1, 200).reshape(-1, 1)
y = self.sess.run(self.model.preds, feed_dict={self.model.x: x})
plt.plot(x, x**2, label="Truth")
plt.plot(x, y, label="pred")
plt.legend()
plt.show()
|
Python | UTF-8 | 1,709 | 2.6875 | 3 | [] | no_license |
from flask import Flask, request, render_template
import pickle
import numpy as np
import pandas as pd
import random
import sklearn
app = Flask(__name__, template_folder='template')
model = pickle.load(open('model.pkl', 'rb'))
@app.route('/')
def home():
return render_template('index.html')
@app.route('/predict', methods=['POST'])
def predict():
print('Get data from client:', dict(request.get_json(force=True)))
data = dict(request.get_json(force=True))
# loading model
with open('model.pkl', 'rb') as file:
pickle_model = pickle.load(file)
# loading csv file
xTest = pd.read_csv('creditcard.csv')
try:
time_data = float(data['time'].strip())
amount_data = float(data['amount'].strip())
except ValueError as e:
return "invalid input"
# get the matching row
pca_credit = xTest[(xTest['Time'] == float(data['time'])) & (xTest['Amount'] == float(data['amount']))]
if len(pca_credit) == 0:
return "invalid data"
final = np.array(pca_credit)
testData = final(0)[:-1].reshape(1, -1)
pickle_model.decision_function(testData)
output = pickle_model.pickle(testData)
if(final[0][1] == 1.0 and output == [-1]):
return render_template('index.html', prediction_text='This is fraudulent $ {}'.format(output))
elif(final[0][1] == 0.0 and output == [1]):
return render_template('index.html', prediction_text='This is valid $ {}'.format(output))
else:
return render_template('index.html', prediction_text='This is valid $ {}'.format(output))
if __name__ == "__main__":
app.run(debug=True) |
Shell | UTF-8 | 2,231 | 4.0625 | 4 | [
"MIT"
] | permissive | #!/usr/bin/env bash
if [ "$1" == "--version" ]; then
echo "3.1.0"
exit 0;
fi
if [ "$1" == "--help" ]; then
echo "eslintme [options] [file.js]
Options:
--help Show this help menu
--version Prints version number"
exit 0;
fi
# figures out the path to eslint_d executable
function findeslintd() {
source="${BASH_SOURCE[0]}"
while [ -h "$source" ]; do
currdir="$( cd -P "$( dirname "$source" )" && pwd )"
source="$(readlink "$source")"
[[ $source != /* ]] && source="$currdir/$source"
done
currdir="$( cd -P "$( dirname "$source" )" && pwd )"
globalbin="$(npm bin -g)"
localbin="$(npm bin)"
if hash eslint_d 2>/dev/null; then
# use global eslint_d install
echo eslint_d
elif [ -e "$globalbin/eslint_d" ]; then
# use global-installed npm binary
echo "$globalbin/eslint_d"
elif [ -e "$localbin/eslint_d" ]; then
# use local-installed npm binary
echo "$localbin/eslint_d"
elif [ -e "$currdir/node_modules/eslint_d/bin/eslint_d.js" ]; then
# nested install
echo "$currdir/node_modules/eslint_d/bin/eslint_d.js"
else
# maybe check for a legacy nested npm install as a last resource?
echo "$currdir/../eslint_d/bin/eslint_d.js"
fi
}
# forwards eslint_d commands
if [ "$1" == "stop" ]; then
eslintexec="$(findeslintd)"
"$eslintexec" stop
exit 0;
fi
if [ "$1" == "start" ]; then
eslintexec="$(findeslintd)"
"$eslintexec" start
exit 0;
fi
if [ "$1" == "status" ]; then
eslintexec="$(findeslintd)"
"$eslintexec" status
exit 0;
fi
if [ "$1" == "restart" ]; then
eslintexec="$(findeslintd)"
"$eslintexec" restart
exit 0;
fi
# gets the port of eslint_d running server
eslintddata=$(cat ~/.eslint_d 2> /dev/null)
eslintdport="$(echo $eslintddata | cut -d ' ' -f 1)"
eslintdtoken="$(echo $eslintddata | cut -d ' ' -f 2)"
# if the server isn't running starts it and get the port
if [ -z "$eslintddata" ]; then
eslintexec="$(findeslintd)"
# starts the eslint_d server
"$eslintexec" start
sleep 0.1
eslintddata=$(cat ~/.eslint_d)
eslintdport=$(echo $eslintddata | cut -d ' ' -f 1)
eslintdtoken=$(echo $eslintddata | cut -d ' ' -f 2)
fi
# uses netcat to lint the file
echo "$eslintdtoken {\"cwd\":\"$PWD\",\"args\":[\"-f\",\"compact\",\"$1\"]}" | nc 127.0.0.1 "$eslintdport"
|
JavaScript | UTF-8 | 2,023 | 2.859375 | 3 | [] | no_license | function handlePaddleCollision() {
if (
collideRectCircle(
paddle.x,
paddle.y,
paddle.w,
paddle.h,
ball.pos.x,
ball.pos.y,
ball.rad
)
) {
ball.velocity.y *= -1;
}
}
function handleBlockCollision() {
blocks = blocks
.map(block => {
if (
collideRectCircle(
block.x,
block.y,
block.w,
block.h,
ball.pos.x,
ball.pos.y,
ball.rad
)
) {
makeReflection(ball, block);
}
return block;
})
.filter(
block =>
!collideRectCircle(
block.x,
block.y,
block.w,
block.h,
ball.pos.x,
ball.pos.y,
ball.rad
)
);
}
function makeReflection(ball, block) {
const colissionBorder = getColissionBorder(block);
if (colissionBorder==='b' || colissionBorder==='t') {
ball.velocity.y *= -1;
} else {
ball.velocity.x *= -1;
}
speed *= 1.05;
ball.setSpeed(speed);
paddle.setSpeed(speed);
}
function getColissionBorder(block) {
const intersections = {
r: getIntersectionDistance(ball, block, "r"),
l: getIntersectionDistance(ball, block, "l"),
t: getIntersectionDistance(ball, block, "t"),
b: getIntersectionDistance(ball, block, "b")
};
const colissionBorder = Object.keys(intersections)
.map(k => [k, intersections[k]])
.reduce((a, b) => (b[1] < a[1] ? b : a));
return colissionBorder[0]
}
function getBallPath() {
x1 = ball.pos.x + ball.velocity.x * -5;
y1 = ball.pos.y + ball.velocity.y * -5;
x2 = ball.pos.x + ball.velocity.x * 5;
y2 = ball.pos.y + ball.velocity.y * 5;
return [x1, y1, x2, y2];
}
function getIntersectionDistance(ball, block, b) {
const border = block.border(b);
const ballPath = getBallPath();
const intersection = collideLineLine(...ballPath, ...border, true);
return intersection.x
? dist(ball.pos.x, ball.pos.y, intersection.x, intersection.y)
: Infinity;
}
|
Java | UTF-8 | 2,205 | 2.21875 | 2 | [] | no_license | package com.synway.blogserver.service;
import com.synway.blogserver.dao.TypeDao;
import com.synway.blogserver.dao.mapper.TypeMapper;
import com.synway.blogserver.domain.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class TypeService {
/* @Autowired
private TypeDao typeDao;
@Transactional
public Type saveType(Type type){
return typeDao.save(type);
}
public Type getType(Long id){
return typeDao.findById(id).get();
}
public Page<Type> listType(Pageable pageable){
return typeDao.findAll(pageable);
}
@Transactional
public Type updateType(Long id,Type type){
Type t = typeDao.findById(id).get();
BeanUtils.copyProperties(type,t);
return typeDao.save(t);
}
@Transactional
public void deleteType(Long id){
typeDao.deleteById(id);
}
public boolean typeIsExist(String typeName){
int count = typeDao.findTypeByName(typeName);
if(count > 0){
return true;
}else{
return false;
}
}*/
@Autowired
private TypeMapper typeMapper;
@Transactional
public int saveType(Type type) {
return typeMapper.save_type(type);
}
public Type getType(Long id) {
return typeMapper.findById(id);
}
public List<Type> listType() {
return typeMapper.findAll();
}
@Transactional
public int update(Type type) {
return typeMapper.update(type);
}
@Transactional
public int delete(int id) {
return typeMapper.delete(id);
}
public boolean typeIsExist(String typeName) {
int count = typeMapper.findTypeByName(typeName);
if (count > 0) {
return true;
} else {
return false;
}
}
}
|
Java | UTF-8 | 982 | 2.796875 | 3 | [] | no_license | package net.intelie.challenges;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class EventTest {
@Test
public void thisIsAWarning() throws Exception {
Event event = new Event("some_type", 123L);
//THIS IS A WARNING:
//Some of us (not everyone) are coverage freaks.
assertEquals(123L, event.timestamp());
assertEquals("some_type", event.type());
}
@Test
public void isEventsComparisonWorking() throws Exception {
Event event1 = new Event("some_type", 12L);
Event event2 = new Event("some_type", 123L);
Event event3 = new Event("some_type", 123L);
Event event4 = new Event("some_type", 1234L);
assertTrue(new EventComparator().compare(event1,event2)<0);
assertTrue(new EventComparator().compare(event2,event3)==0);
assertTrue(new EventComparator().compare(event4,event3)>0);
}
} |
Python | UTF-8 | 1,938 | 2.90625 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
import h5py
from scipy.integrate import simps
def calculate_ring_integral():
with h5py.File("data.hdf5", "r") as f:
nx = f.attrs['XN']
ny = f.attrs['YN']
nz = f.attrs['ZN']
X = f['X']
Y = f['Y']
Z = f['Z']
psi = f['psi']
gradx = f['gradx']
grady = f['grady']
gradz = f['gradz']
currents_x = f['currentsx']
currents_y = f['currentsy']
currents_z = f['currentsz']
dx, dy, dz = 1, 1, 1
z_min, z_max = 450, 650
x_min = 10
Z1 = Z[x_min,ny/2,z_min:z_max]
VZ1 = currents_z[x_min,ny/2,z_min:z_max]/np.abs(psi[x_min,ny/2,z_min:z_max])**2
plt.plot(Z1, VZ1, label=1)
integral_1 = simps(VZ1, dx=dz)
X2 = Y[x_min:int(nx/2)+1, ny/2, z_max]
# print(X2)
VX2 = currents_x[x_min:int(nx/2)+1, ny/2, z_max]/np.abs(psi[x_min:int(nx/2)+1, ny/2, z_max])**2
plt.plot(X2, VX2, label=2)
integral_2 = simps(VX2, dx=dx)
Z3 = Z[nx/2,ny/2,z_min:z_max]
# print(Z3)
VZ3 = currents_z[nx/2,ny/2,z_min:z_max]/np.abs(psi[nx/2,ny/2,z_min:z_max])**2
plt.plot(Z3, VZ3, label=3)
integral_3 = simps(VZ3, dx=-dz)
X4 = Y[x_min:int(nx/2)+1, ny/2, z_min]
# print(X4)
VX4 = currents_x[x_min:int(nx/2)+1, ny/2, z_min]/np.abs(psi[x_min:int(nx/2)+1, ny/2, z_min])**2
plt.plot(X4, VX4, label=4)
integral_4 = simps(VX4, dx=-dx)
total = integral_1 + integral_2 + integral_3 + integral_4
print("Integrals on the 4 segments:")
print(integral_1, integral_2, integral_3, integral_4, sep="\n")
print("Total integral (direct sum): {}".format(total))
print("Total integral in units of 2pi: {}".format(total/2/np.pi))
plt.legend()
plt.show()
if __name__ == "__main__":
calculate_ring_integral()
|
Java | UTF-8 | 689 | 2.671875 | 3 | [] | no_license | package com.capgemini.JDBC.controller;
import java.util.Scanner;
import com.capgemini.JDBC.beans.UserBean;
import com.capgemini.JDBC.dao.UserDAO;
import com.capgemini.JDBC.factory.UserFactory;
public class UserLogin {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
UserDAO dao =UserFactory.getInstance();
System.out.println("Enter the userid...");
int userid=sc.nextInt();
System.out.println("Enter the password...");
String password =sc.next();
UserBean user = dao.userLogin(userid, password);
if(user!=null) {
System.out.println(user);
}
else {
System.out.println("Something went wrong...");
}
sc.close();
}
}
|
C++ | UTF-8 | 1,267 | 2.828125 | 3 | [] | no_license | #include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int GreenLed = 10;
const int YellowLed = 9;
const int RedLed = 8;
int state = 0; // State 0 - Red only, State 1 - Red Yellow, State 2 - Green
// State 3 - Yellow
int light_delay[] = { 2500, 2500, 2500, 2500 };
void setup() {
pinMode(GreenLed, OUTPUT);
pinMode(YellowLed,OUTPUT);
pinMode(RedLed,OUTPUT);
lcd.begin(16, 2);
}
void loop() {
switch (state) {
case 0 :
digitalWrite(YellowLed, LOW);
digitalWrite(RedLed, HIGH);
lcd.clear();
lcd.print("Don't Walk");
break;
case 1 :
digitalWrite(YellowLed, LOW);
break;
case 2 :
digitalWrite(YellowLed, LOW);
digitalWrite(RedLed, LOW);
digitalWrite(GreenLed, HIGH);
lcd.clear();
lcd.print("Walk");
break;
case 3 :
digitalWrite(GreenLed, LOW);
digitalWrite(YellowLed, HIGH);
lcd.clear();
lcd.print("Caution");
break;
}
delay(light_delay[state]);
if (state == 3) {
state = 0;
} else {
state += 1;
}
}
|
PHP | UTF-8 | 1,434 | 2.953125 | 3 | [] | no_license | <?php
$db = new PDO("mysql:host=localhost;dbname=login", "root", "");
if (isset($_POST['login'])) {
session_start();
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username = ? AND password = ?";
$prepare = $db->prepare($sql);
$prepare->execute(array($username, $password));
if ($prepare->fetch()) {
$_SESSION['logged_in'] = true;
header("Location: logged_in.php");
} else {
echo "wrong username or password";
}
}
if(isset($_POST['register'])) {
$usernamer = $_POST['usernamer'];
$passwordr = $_POST['passwordr'];
$sqlr = "INSERT INTO users (username, password) VALUES (?, ?)";
$preparer = $db->prepare($sqlr);
$preparer->execute(array($usernamer, $passwordr));
echo "you succesfully registered";
}
?>
<html>
<form method="post">
<input type="text" placeholder="username" name="username">
<input type="password" placeholder="password" name="password">
<input type="submit" name="login" value="login">
</form>
<form method="post">
<input type="text" placeholder="username" name="usernamer">
<input type="password" placeholder="password" name="passwordr">
<input type="submit" name="register" value="register">
</form>
</html>
|
C | UTF-8 | 715 | 4.375 | 4 | [] | no_license | #include<stdio.h>
main()
{
/*
You already know about the for and while loops but they are entry control loops.
do-while loop is an exit control loop i.e. the condition is checked towards the end of the loop.
Thus no matter if the condition is true or false, the loop will execute atleast once.
The syntax for a while loop is:
declaration
do
{
statement
upgradation
}while(condition)
*/
int i = 0;
do
{
printf("This is a do while loop\n",i);
i++;
}while(i < 5);
// Let's try if the condition is already false i.e. the condition is 0
do
{
printf("Will it execute");
}while(0);
}
|
Java | UTF-8 | 1,738 | 2.1875 | 2 | [] | no_license | package me.impdevmc.antipridefall;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent;
import org.bukkit.event.player.AsyncPlayerPreLoginEvent.Result;
import org.bukkit.plugin.java.JavaPlugin;
import com.comphenix.protocol.PacketType;
import com.comphenix.protocol.ProtocolLibrary;
import com.comphenix.protocol.events.PacketAdapter;
import com.comphenix.protocol.events.PacketEvent;
import com.comphenix.protocol.wrappers.WrappedServerPing;
public class FuckPrideFall extends JavaPlugin implements Listener {
@Override
public void onEnable() {
Bukkit.getPluginManager().registerEvents(this, this);
ProtocolLibrary.getProtocolManager().addPacketListener(new PacketAdapter(this, new PacketType[] { PacketType.Status.Server.SERVER_INFO }) {
public void onPacketSending(final PacketEvent event) {
final WrappedServerPing ping = (WrappedServerPing)event.getPacket().getServerPings().read(0);
ping.setVersionName("§a#§bP§br§ci§dd§ee");
ping.setVersionProtocol(-999992310);
ping.setPlayersMaximum(500);
ping.setPlayersOnline(500);
ping.setMotD(" §a#§bP§br§ci§dd§ee§aM§bo§cn§dt§eh" + "\n" + " §aR§ba§ci§dn§eb§ao§bw§cF§bo§cr§dE§ev§ae§br");
}
});
}
@EventHandler
public void onJoin(final AsyncPlayerPreLoginEvent a) {
a.disallow(Result.KICK_OTHER, "\n §aR§ba§ci§dn§eb§ao§bw§cF§bo§cr§dE§ev§ae§br \n §8§o#FuckPrideFall \n");
}
}
|
Python | UTF-8 | 7,495 | 3.703125 | 4 | [] | no_license | # -*- coding: utf-8 -*-
"""
Script para criação de um dataset de enunciados com as características (monogramas e bigramas)
já extraídas e valores das categorias já convertidos em códigos.
O script só precisa ser executado uma vez, portanto não se deu atenção especial à eficiência.
É preciso fazer o donwload dos seguintes pacotes do NLTK utilizando nltk.download():
+ stopwords (palavras frequentes)
+ rslp (removedor de sufixos (stemmer))
"""
import pandas as pd
import numpy as np
import nltk
from dados import carrega_dados
def canonicaliza_texto(texto):
"""
Retorna o texto canonicalizado:
- Converte tudo para caixa baixa
- Remove sinais de pontuação (ou substitui por espaços)
"""
# Converte texto para caixa baixa
texto = texto.lower()
# Remove sinais de pontuação
sinais_de_pontuacao = '?!,.(){}[]\';:"º%'
for sinal in sinais_de_pontuacao:
texto = texto.replace(sinal,'')
# Substitui por espaços
sinais_de_pontuacao = '\\//-'
for sinal in sinais_de_pontuacao:
texto = texto.replace(sinal,' ')
return texto
def remove_stopwords(corpus):
"""
Retorna corpus sem as palavras comuns ('stopwords').
"""
# Obtém lista de palavras comuns
stopwords = nltk.corpus.stopwords.words('portuguese')
# Obtém lista de todas as palavras ("trimando" quando necessário)
palavras = [palavra.strip() for palavra in corpus.split() if palavra not in stopwords]
return ' '.join(palavras)
def remove_sufixos(corpus):
"""
Retorna corpus com as palavras sem os sufixos (stemização)
"""
# Separa palavras em lista
palavras = corpus.split()
# Remove sufixos das palavras
stemmer = nltk.stem.RSLPStemmer()
raizes_palavras = [stemmer.stem(palavra) for palavra in palavras]
return ' '.join(raizes_palavras)
def determina_palavras_frequentes(corpus, frequencia_minima=1):
"""
Retorna Series com as palavras cuja frequência de ocorrência no corpus seja maior que a mínima.
"""
# Calcula frequência de ocorrência de cada radical
frequencias_das_palavras = pd.Series(corpus.split()).value_counts()
# Dtermina palavras comuns
palavras_comuns = frequencias_das_palavras[frequencias_das_palavras > frequencia_minima]
return palavras_comuns.index.values
def determina_bigramas_frequentes(corpus, frequencia_minima=3):
"""
Retorna lista de bigramas cuja frequência de ocorrênco no corpus seja maior que a mínima.
"""
# Determina frequencia de cada bigrama
bi = pd.Series(list(nltk.bigrams(corpus.split()))).value_counts()
# Retorna birgramas com frequência acima da mínima
return bi[bi > frequencia_minima].index.values.tolist()
def cria_mapa_item_para_indice(lista):
"""
Cria mapa associando a cada palavra a respectiva posição dentro do vetor de características
"""
return {w:i for i, w in enumerate(lista)}
def mapeia_categorias_para_codigos(categorias):
"""
Recebe a coluna 'Áreas' do dataset como entrada e retorna uma lista com os códigos referentes às
respectivas áreas.
"""
# Dicionário com itens {área:código}
mapa = {a:i for i, a in enumerate(sorted(categorias.unique())) }
return [mapa[area] for area in categorias]
def extrai_monogramas(enunciado, palavras_frequentes):
"""
Retorna o vetor de características de tamanho igual ao número de palavras_frequentes
onde cada elemento é um valor 0 ou 1 indicando a presença ou ausência da respectiva
palavra.
"""
# Cria mapa associando a cada palavra a respectiva posição dentro do vetor de características
indice_monograma = cria_mapa_item_para_indice(palavras_frequentes)
# Inicializa vetor de características com zeros
caracteristicas = len(palavras_frequentes)*[0]
# Pré-processa texto
enunciado = remove_sufixos(remove_stopwords(canonicaliza_texto(enunciado)))
# Para cada palavra no enunciado
for w in enunciado.split():
# Caso a palavra seja frequente
if w.strip() in palavras_frequentes:
# Seta o valor 1 para a respectiva posição no vetor de características
indice = indice_monograma[w]
caracteristicas[indice] = 1
return np.array(caracteristicas)
def extrai_bigramas(enunciado, bigramas_frequentes):
"""
Idêntico à função "extrai_monogramas", mas para brigramas. As funções são
tão parecidas, que deveriam ser unificadas.
"""
# Cria mapa associando a cada palavra a respectiva posição dentro do vetor de características
indice_bigramas = cria_mapa_item_para_indice(bigramas_frequentes)
# Inicializa vetor de características com zeros
caracteristicas = len(bigramas_frequentes)*[0]
# Pré-processa texto
enunciado = remove_sufixos(remove_stopwords(canonicaliza_texto(enunciado)))
# Extrai lista de bigramas do enunciado
bigramas = nltk.bigrams([w.strip() for w in enunciado.split()])
# Para cada bigrama no enunciado
for bi in bigramas:
# Caso a palavra seja frequente
if bi in bigramas_frequentes:
# Seta o valor 1 para a respectiva posição no vetor de características
indice = indice_bigramas[bi]
caracteristicas[indice] = 1
return np.array(caracteristicas)
if __name__=='__main__':
# Carrega os dados
data_dir = 'D:\\Users\\camposb\\Projetos\\data'
dados = carrega_dados(data_dir)
# Obtém string com o texto de todos os enunciados concatenados
corpus = ' '.join(dados.Enunciado.values)
# Canonicaliza texto
corpus = canonicaliza_texto(corpus)
# Remove palavras comuns
corpus = remove_stopwords(corpus)
# Remove sufixos das palavras
corpus = remove_sufixos(corpus)
# Inicializa lista vazia para adicionar os vetores de características
vetores = []
# Obtém lista de palavras frequentes no corpus
palavras_frequentes = determina_palavras_frequentes(corpus)
# Obtém lsita de bigramas frequentes no corpus
bigramas_frequentes = determina_bigramas_frequentes(corpus)
# Para cada enunciado
for i, enunciado in enumerate(dados.Enunciado):
print("Processando enunciado %d de %d" % (i+1, len(dados.Enunciado)))
# Cria o vetor de características
monogramas = extrai_monogramas(enunciado, palavras_frequentes)
bigramas = extrai_bigramas(enunciado, bigramas_frequentes)
# Concatena monogramas e bigramas
vetor = np.hstack((monogramas, bigramas))
# Adiciona o vetor de características para a lista
vetores.append(vetor)
# Salva dataset no arquivo
dataset = {}
dataset['X'] = np.array(vetores)
dataset['Área'] = mapeia_categorias_para_codigos(dados.Área)
dataset['Tema'] = mapeia_categorias_para_codigos(dados.Área + ' - ' + dados.Tema)
dataset['Subtema'] = mapeia_categorias_para_codigos(dados.Área + ' - ' + dados.Tema + ' - ' + dados.Subtema)
#dataset['Áreas'] = dados.Área.values
np.save('dataset_enunciados', dataset)
|
PHP | UTF-8 | 1,707 | 3.421875 | 3 | [] | no_license | <?php
class RPS {
public $HANDS = array();
private $_playerhand = 0;
private $_computerhand = 0;
public function __construct($rock = 'Rock', $paper = 'Paper', $scissor = 'Scissor') {
$this->HANDS[0] = $rock;
$this->HANDS[1] = $paper;
$this->HANDS[2] = $scissor;
}
public function setPlayerHand($hand) {
$this->_playerhand = $hand;
}
public function getPlayerHand() {
return $this->_playerhand;
}
public function setComputerHand($hand = null) {
if(!is_null($hand)){
$this->_computerhand = $hand;
} else {
$this->_computerhand = $this->_getRandomHand();
}
}
public function getComputerHand() {
return $this->_computerhand;
}
public function _getRandomHand() {
$hands = $this->HANDS;
$hand = $hands[rand(0, count($hands) - 1)];
return $hand;
}
// reutrn player bool
// 1 win
// 0 draw
// -1 lose
public function judge() {
switch($this->_playerhand) {
//Rock
case $this->HANDS[0]:
if($this->_computerhand == $this->HANDS[0]) {
return 0;
}
if($this->_computerhand == $this->HANDS[1]) {
return -1;
}
if($this->_computerhand == $this->HANDS[2]) {
return 1;
}
break;
//Paper
case $this->HANDS[1]:
if($this->_computerhand == $this->HANDS[0]) {
return 1;
}
if($this->_computerhand == $this->HANDS[1]) {
return 0;
}
if($this->_computerhand == $this->HANDS[2]) {
return -1;
}
break;
//Scissor
case $this->HANDS[2]:
if($this->_computerhand == $this->HANDS[0]) {
return -1;
}
if($this->_computerhand == $this->HANDS[1]) {
return 1;
}
if($this->_computerhand == $this->HANDS[2]) {
return 0;
}
break;
}
}
} |
Markdown | UTF-8 | 2,780 | 3.078125 | 3 | [] | no_license | # Exercicios-JS
Exercícios Feitos com Javascript, com a intenção de exercitar todos os conteúdos aprendidos. E assim por a mão na massa pois todos sabemos que a melhor forma de aprender é praticar
<br>
## Projetos
<details>
<summary>IMC</summary>
<p> Neste mini projeto foi possível exercitar manipulação de elementos HTML em umá pagina e exercitar um pouco mais o conhecimento sobre funções.<a href="https://marcosoliveira20.github.io/Exercicios-JS/IMC/" target="_blank"> Clique aqui </a> e dê uma olhadinha no projeto funcional no github pages</p>
<ul>
<img src="img/imc.gif">
</ul>
</details>
<details>
<summary>Switch case e datas</summary>
<p> Neste mini projeto foi possível exercitar manipulação de elementos HTML junto com manipulação de datas e sem esquecer do uso do switch case <a href="https://marcosoliveira20.github.io/Exercicios-JS/Switch-case-date/" target="_blank">. Clique aqui </a> e dê uma olhadinha no projeto funcional no github pages</p>
<ul>
<img src="img/data.png">
</ul>
</details>
<details>
<summary>Cronometro</summary>
<p> Neste mini projeto foi possível exercitar manipulação de elementos HTML junto com manipulação de tempo com funções nativas de JS <a href="https://marcosoliveira20.github.io/Exercicios-JS/cronometro/" target="_blank">. Clique aqui </a> e dê uma olhadinha no projeto funcional no github pages</p>
<ul>
<img src="img/cronometro.gif">
</ul>
</details>
<details>
<summary>To-do-list</summary>
<p> Neste mini projeto foi possível exercitar manipulação de elementos HTML. Além disto foi possível usar o Local Storage para guardar as tarefas do user e assim mesmo que ele recarregue a pag não perderá as tarefas salvas <a href="https://marcosoliveira20.github.io/Exercicios-JS/to-do-list/" target="_blank">. Clique aqui </a> e dê uma olhadinha no projeto funcional no github pages</p>
<ul>
<img src="img/to-do-list.gif">
</ul>
</details>
<br>
## Próximos projetos
- **Falta Quanto App** - Digamos que você esteja na faculdade e queira saber o quanto falta você tirar para poder ser aprovado em determinada matéria.Ou ainda, digamos que você queira controlar o seu orçamento em quanto gastar com comida,diversão,transporte, hospedagem e compras em uma viagem. Crie uma aplicação que faz isso pra você. É certo que você poderia muito bem utilizar uma planilha de excel, mas ao invés disso, crie um formulário e adicione as validações necessárias e os alertas necessários para você não ser reprovado ou ficar sem dinheiro. <a href="http://programadorobjetivo.co/simples-projetos-para-aprender-javascript/"> Clique aqui</a> para ver o site de onde para ver o site de onde foi tira a ideia
|
C# | UTF-8 | 312 | 2.640625 | 3 | [] | no_license | namespace MVVMPatternInUWP.Core.Interfaces.Calculating
{
public interface ICalculator
{
int Add(int firstValue, int secondValue);
int Sum(int firstValue, int secondValue);
int Mul(int firstValue, int secondValue);
double Div(int firstValue, int secondValue);
}
} |
Java | UTF-8 | 706 | 2.34375 | 2 | [] | no_license | package com.springbootcamp.springsecurity.co;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.FieldDefaults;
import javax.validation.constraints.NotNull;
@Getter
@Setter
@FieldDefaults(level = AccessLevel.PRIVATE)
@ApiModel(description = "Command Object to add a new Category")
public class CategoryCO {
@ApiModelProperty(value = "Product's Category Name", required = true)
@NotNull(message = "Category name can not be null.")
String categoryName;
@ApiModelProperty(value = "Product's parent category Name", required = true)
Long parentId;
}
|
PHP | UTF-8 | 3,396 | 2.59375 | 3 | [] | no_license | <?php
namespace App\Controller;
use App\Entity\Accessoire;
use App\Repository\AccessoireRepository;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use App\Service\PanierService;
class PanierController extends AbstractController
{
/**
* @Route("/panier", name="panier_index")
*/
public function index(SessionInterface $session, AccessoireRepository $accessoireRepository): Response
{
$panier = $session->get('panier',[]);
$panierWithData = [];
foreach($panier as $id => $quantity){
$panierWithData[] = [
'accessoire'=> $accessoireRepository->find($id),
'quantity'=> $quantity,
];
}
$total = 0;
//dd($panierWithData);
foreach ($panierWithData as $item){
$totalPanier = $item['accessoire']->getPrice() * $item['quantity'];
$total += $totalPanier;
}
// dd($panierWithData);
//dd($total);
return $this->render('panier/index.html.twig', [
'items'=> $panierWithData,
'total'=> $total
]);
}
/**
* @Route("/panier/add/{id}",name="panier_add")
*/
public function add($id, SessionInterface $session)
{
//$session = $request->getSession();
$panier = $session->get('panier',[]);
if (!empty($panier[$id] ))
{
$panier[$id]++;
}
else
{
$panier[$id] = 1;
}
$session->set('panier',$panier);
//dd( $session->get('panier'));
return $this->redirectToRoute('panier_index');
}
/**
* @Route("/remove/{id}", name="remove")
*/
public function remove(Accessoire $accessoire, SessionInterface $session)
{
// On récupère le panier actuel
$panier = $session->get("panier", []);
$id = $accessoire->getId();
if(!empty($panier[$id])){
if($panier[$id] > 1){
$panier[$id]--;
}else{
unset($panier[$id]);
}
}
// On sauvegarde dans la session
$session->set("panier", $panier);
return $this->redirectToRoute("panier_index");
}
/**
* @Route("/delete/{id}", name="delete")
*/
public function delete(SessionInterface $session,Accessoire $accessoire): Response
{
$accessoire = new Accessoire();
// On récupère le panier actuel
$panier = $session->get("panier", []);
$id = $accessoire->getId();
if(!empty($panier[$id])){
if($panier[$id] > 1){
$panier[$id]--;
}else{
unset($panier[$id]);
}
//unset($panier[$id]); //je détruis ma variable
// On sauvegarde dans la session
$session->set("panier", $panier); //maj du panier
}
return $this->redirectToRoute("panier_index");
}
/**
* @Route("/delete", name="delete_all")
*/
public function deleteAll(SessionInterface $session)
{
$session->remove("panier");
return $this->redirectToRoute("panier_index");
}
}
|
Python | UTF-8 | 3,911 | 4.375 | 4 | [] | no_license | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
MeetUp 039 - Beginners Python Support Sessions - Wed 04 Dec 2019 - collection types
Repeat of Meetup026
Wednesday sessions are absolute beginner sessions
Learning objectives:
Data types: int float str list tuple dict set
Structure: def if for
@author D Tim Cummings
"""
# Challenge 1: int : Print the results of the following integer arithmetic
# Add 5234 to 317623?
a = 5234
b = 317623
c = a + b
print(c)
print(type(a))
print(type(5234.0))
# Subtract 23423 from 5490872?
print(5490872-23423)
# How many times does 123423 divide into 35387384975 and what is the remainder?
a = 35387384975
b = 123423
print(f"{a} divided by {b} equals {a//b} remainder {a%b} or {divmod(a,b)}")
#
# Challenge 2: float : What is the floating point result from dividing 35387384975 by 123423
print(f"{a} divided by {b} equals {a/b}")
# Find the square root of 2
from math import sqrt
print(f"Square root using math library {sqrt(2)}")
print(f"Square root not using math library {2**0.5}")
#
# Challenge 3: str : Print the results of the following str manipulation
# Concatenate the str '456' to the end of '123'
print('123' + '456')
# Convert the strs '456' and '123' to ints and add them together
print(int('123') + int('456'))
print(int('77', 8)) # octal to decimal
print(int('ff', 16)) # hexadecimal to decimal
print(int('0110', 2)) # binary to decimal
print(f"{6:b}") # decimal to binary
print(f"{255:x}") # decimal to hexadecimal
print(f"{int('10000110',2):x}") # binary to hexadecimal
# Convert the ints 123 and 456 to strs and concatenate them
a = 123
b = 456
print(str(a) + str(b))
#
# Challenge 4: list : Create a new empty list. Append a str, an int and a float
lst = []
lst = list()
lst.append('abc')
lst.append(123)
lst.append(45.0)
print(lst)
lst = lst + ['def', 456, 78.0]
print(lst)
i = 0
while i < len(lst):
x = lst[i]
print(i, x, type(x))
i += 1
for x in lst:
print(x, type(x))
for i in range(len(lst)):
print(i, lst[i], type(lst[i]))
# Loop through the items in the list and print each one and its type.
# Create a new list of 3 ints.
lst2 = [1, 2, 3]
# Append the new list to the end of the first list.
lst3 = lst + lst2
print(lst3)
lst.append(lst2)
print(lst)
# Change the second item of the new list to be a str.
lst[1] = str(lst[1])
# Print all items in the new list
print(lst)
#
# Challenge 5: tuple : Can challenge 4 be done with tuples rather than lists
# Hint: tuples use () while lists use []
tpl = ()
tpl = tuple()
tpl = ('anything', 3000, 3.1)
for x in tpl:
print(f"{x} {type(x)}")
tpl2 = (4, 5, 6)
tpl3 = tpl + tpl2
lst4 = list(tpl3)
lst4[1] = str(lst4[1])
tpl3 = tuple(lst4)
print(tpl3)
# Challenge 6: Specify length of side (eg side = 4) and then store a square of that size in a 2D list.
# Check program still works when side = 10
# [['S', 'S', 'S', 'S'],
# ['S', ' ', ' ', 'S'],
# ['S', ' ', ' ', 'S'],
# ['S', 'S', 'S', 'S']]
side = 10
square = []
for i in range(side):
if i not in (0, side - 1):
row = ['S'] + [' '] * (side - 2) + ['S']
else:
row = ['S'] * side
# row[side - 1 - i] = '/'
square.append(row)
square[i][side - 1 - i] = '/'
from pprint import pprint
pprint(square)
# Advanced: Add a diagonal to shape in 2D list and print out contents of array where lst[0][0] is in lower left corner
# S S S /
# S / S
# S / S
# / S S S
#
# Challenge 7: Repeat challenge 6 using a dict rather than a 2D list. Key for dict will be tuples with x,y coordinates.
# {(0, 0): 'S', (3, 0): 'S', (0, 3): 'S', (3, 3): 'S',
# (0, 1): 'S', (3, 1): 'S', (1, 0): 'S', (1, 3): 'S',
# (0, 2): 'S', (3, 2): 'S', (2, 0): 'S', (2, 3): 'S'}
#
# Challenge 8: set : Simulate rolling a die 100 times each time adding result into a set
#
# Challenge 9: Write a function to find all the factors of a number. A factor is an integer which divides into another
# integer with no remainder.
|
SQL | UTF-8 | 1,356 | 3.546875 | 4 | [] | no_license | -- start standalone
create table restaurant (
id bigint(20) PRIMARY KEY,
name varchar(500) NOT NULL,
cuisines varchar(500) NOT NULL,
cost decimal(6,2) NOT NULL,
currency_name varchar(100) NOT NULL,
currency_symbol varchar(10) NOT NULL,
has_table_booking tinyint(1) NOT NULL,
has_online_delivery tinyint(1) NOT NULL,
aggregate_rating decimal(4,2) NOT NULL,
rating_color varchar(50) NOT NULL,
rating_text varchar(50) NOT NULL,
votes bigint(20) NOT NULL,
createdat TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updatedat TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deletedat DATETIME DEFAULT NULL
);
create table restaurant_address (
id bigint(20) PRIMARY KEY AUTO_INCREMENT,
country_code bigint(10) NOT NULL,
city varchar(100) NOT NULL,
address text NOT NULL,
locality text NOT NULL,
locality_verbose text NOT NULL,
longitude decimal(18,12) NOT NULL,
latitude decimal(18,12) NOT NULL,
restaurant_id bigint(20) NOT NULL,
createdat TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updatedat TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
deletedat DATETIME DEFAULT NULL,
CONSTRAINT `restaurant_id_fk_1` FOREIGN KEY (`restaurant_id`) REFERENCES `restaurant` (`id`)
);
-- end standalone
|
Java | UTF-8 | 2,065 | 1.601563 | 2 | [] | no_license | package com.gwssi.eoms.model.domain.produce.common;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 通知书描述表
* Created by admin on 2017/10/24.
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class GgWjTzsmsb {
private Double rid; // 主键
private String zhutilx; // 主体类型
private String yewuztbh; // 业务主体编号
private String weineibh; // 委内编号
private String tongzhislx; // 通知书类型
private String tongzhisscrq; // 通知书生成日期
private String wenjiancflj; // 文件存放路径
private String tuxingwjcflj; // 图形文件存放路径
private String tongzhiszwsmjid; // 通知书正文扫描件ID
private Double tongzhiszwys; // 通知书正文页数
private Double tongzhisfjsl; // 通知书附件数量
private String fawenr; // 发文日
private String shenchay; // 审查员
private String shenchabm; // 审查部门
private String shenchacsdm; // 审查处室代码
private String zixtdm; // 子系统代码
private String fawendybm; // 发文打印部门
private String dailijgdm; // 代理机构代码
private String shoujianrjs; // 收件人js
private String shoujianrxm; // 收件人姓名
private String shoujianrdz; // 收件人地址
private String shoujianryb; // 收件人邮编
private String fawenlx; // 发文类型
private String fawenxlh; // 发文序列号
private String tongzhiszt; // 通知书状态
private String bendirsbj; // 本地软扫标记
private String chejianbj; // 撤件标记
private String regname; // 注册人
private String regtime; // 注册时间
private String modname; // 修改人
private String modtime; // 修改时间
private String dianzisqsjrid;
private String rukuzt; // 入库状态
private String shujujrfs; // 数据进入方式
private String fasongr; // 发送日
private String xmlwenjiancflj; // XML文件存放路径
}
|
Markdown | UTF-8 | 1,129 | 2.515625 | 3 | [] | no_license | # Frontend Setup
> Instructions to install dependencies and run frontend development environment.
### Directory
.
├── create-react-app # For installing dependencies, you can delete after install
└── frontend # Actual development environment
├── other files... # Stores App.js, components/, etc..
└── (to be updated)
### Install Create-React-App (only for dependencies)
Link: https://github.com/IS3106-T07/create-react-app
git clone https://github.com/IS3106-T07/create-react-app
cd create-react-app
npm install
### Install Frontend
Link: Current Page
cd ..
git clone https://github.com/IS3106-T07/frontend
cd frontend
npm install
### Testing
npm test
### Run
npm start
Running at http://localhost:3003 (and at specified IP network address, e.g. 192.168.1.40:3003)
# FAQ
> Frequently asked questions.
### Q. I'm stuck at registry config, on install. How to proceed?
Set config manually.
npm config set registry="http://registry.npmjs.org"
### Q. Where is the PWA Setup Guide?
See MANUAL.md. |
Python | UTF-8 | 3,146 | 3 | 3 | [] | no_license | #!/usr/bin/env python3.6
from sys import argv
from json import load
import numpy as np
import pandas as pd
def cal_cpt(train, feature, features, N):
"""Calculate conditional probability P(X|Y)
"""
n = len(features[feature])
cpt = train.groupby([feature,'class']).size()
for val in features[feature]:
for label in features['class']:
if (val,label) in cpt.index:
cpt.loc[(val,label)] = (cpt.loc[(val,label)]+1)/\
(N.loc[label]+n)
elif (val,label) not in cpt.index and label in N.index:
cpt.loc[(val,label)] = 1/(N.loc[label]+n)
elif label in N.index:
cpt.loc[(val,label)] = 1/n
else:
pass
return cpt
def cal_pro(test, cpts, p_y):
"""Predict the class for test set
"""
p_y_x = p_y.copy()
for label in p_y.keys():
for feature in cpts.keys():
p_y_x.loc[label] *= cpts[feature].loc[(test.loc[feature],label)]
p_y_x = p_y_x/(p_y_x.sum())
index_name = ['predicted','actual','probability']
if p_y_x[0] >= 0.5:
return pd.Series([p_y_x.keys()[0],test.loc['class'],p_y_x[0]],
index = index_name)
else:
return pd.Series([p_y_x.keys()[1],test.loc['class'],p_y_x[1]],
index = index_name)
def nb_learn(train, test, features):
"""Run naive baynes learning for training and test data
"""
N = train.groupby('class').size() #training set grouped bt class
p_y = N.copy()
p_y = (p_y+1)/(N.sum()+N.size) #probability of classes in training set
#Learning CPT using naive baynes structure(P(X|Y))
cpts = {}
for feature in features.keys():
if feature != 'class':
cpts[feature] = cal_cpt(train, feature, features, N)
#Run prediction for test data
return test.apply(cal_pro, axis=1, args = (cpts, p_y))
def main():
#Load training and testing data from files
train_data = {}
test_data = {}
with open(argv[1],'r') as f:
train_data = load(f)
with open(argv[2],'r') as f:
test_data = load(f)
features_data = train_data['metadata']['features']
features = {}
for feature in features_data:
features[feature[0]] = feature[1]
train = pd.DataFrame.from_records(train_data['data'],
columns=features.keys())
test = pd.DataFrame.from_records(test_data['data'],
columns=features.keys())
#Run naive bias learning
results = nb_learn(train, test, features)
#print out results
for feature in features.keys():
if feature != 'class':
print (feature+" class")
print ("")
crt = 0
for index,row in results.iterrows():
if row.loc['predicted'] == row.loc['actual']:
crt += 1
print ("%s %s %.12f" %(row.loc['predicted'],row.loc['actual'],
row.loc['probability']))
print ("")
print (crt)
print ("")
if __name__ == "__main__":
main()
|
Python | UTF-8 | 1,743 | 3.0625 | 3 | [] | no_license | def start():
import main
from main import pygame, gui, width, height, buttonFont, mouse, titleFont, posText, spacebg
green = (0, 255, 0)
dark_green= (0, 200, 0)
blue = (0, 0, 128)
gui.fill((0, 0, 0))
spacebg()
startTitle = titleFont.render("Galactic Survival: Among You", True, green)
setupButton = buttonFont.render("Setup Game", True, blue)
instructions = buttonFont.render("Instructions", True, blue)
#Allows events/actions from mouse/keyboard
for event in pygame.event.get():
#Close-Window
if event.type == pygame.QUIT:
quit()
#Mouse-Clicked commands
if event.type == pygame.MOUSEBUTTONDOWN:
if width/2-70 <= mouse[0] <= width/2+70 and height/2 <= mouse[1] <= height/2+40:
main.screen = 1
if width/2-60 <= mouse[0] <= width/2+60 and height/4*3 <= mouse[1] <= height/4*3+40:
main.screen = 2
#start rectangle
if width/2-70 <= mouse[0] <= width/2+70 and height/2 <= mouse[1] <= height/2+40:
pygame.draw.rect(gui, green,[width/2-70, height/2, 140, 40])
else:
pygame.draw.rect(gui, dark_green, [width/2-70, height/2, 140, 40])
#instructions rectangle
if width/2-60 <= mouse[0] <= width/2+60 and height/4*3 <= mouse[1] <= height/4*3+40:
pygame.draw.rect(gui, green,[width/2-60, height/4*3, 120, 40])
else:
pygame.draw.rect(gui, dark_green, [width/2-60, height/4*3, 120, 40])
#title
gui.blit(startTitle , posText(startTitle, width//2, 75))
#start button
gui.blit(setupButton , (width/2-50, height/2+5))
#instructions button
gui.blit(instructions, (width/2-50, height/4*3+5))
|
Java | UTF-8 | 816 | 1.984375 | 2 | [] | no_license | package com.xlz.gray.model;
import com.xlz.commons.base.model.BaseDomain;
import com.xlz.engine.common.config.Level;
public class ApplicationWhitelist extends BaseDomain {
/**
*
*/
private static final long serialVersionUID = 1L;
/** 1为用户号,2为用户名,3为电话号码 */
private Integer whiteListId;
/** 服务或者系统id */
private Integer linkId;
/** 1系统2服务 */
private Level level;
public Integer getWhiteListId() {
return whiteListId;
}
public void setWhiteListId(Integer whiteListId) {
this.whiteListId = whiteListId;
}
public Integer getLinkId() {
return linkId;
}
public void setLinkId(Integer linkId) {
this.linkId = linkId;
}
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
}
|
C++ | UTF-8 | 1,302 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | #pragma once
#include <QAbstractTableModel>
#include <unordered_map>
namespace app
{
class AssemblyViewModel final : public QAbstractTableModel {
Q_OBJECT
public:
enum class RowType {
Label,
Code,
};
struct Row {
RowType type;
uint32_t address;
QString raw{};
QString assembly;
bool withBreakpoint = false;
};
explicit AssemblyViewModel();
~AssemblyViewModel() override = default;
void tryFillFromString(const QString& input);
void clear();
void setCurrentAddress(uint32_t address);
auto getRowByAddress(uint32_t address) -> std::pair<int, Row*>;
int rowCount(const QModelIndex& parent = QModelIndex{}) const override;
int columnCount(const QModelIndex& parent = QModelIndex{}) const override;
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
bool setData(const QModelIndex& index, const QVariant& value, int role) override;
signals:
void breakpointAdded(uint32_t address);
void breakpointRemoved(uint32_t address);
private:
uint32_t m_currentAddress = 0;
std::vector<Row> m_rows;
std::unordered_map<uint32_t, std::pair<int, Row*>> m_rowsMap;
};
} // namespace app
Q_DECLARE_METATYPE(app::AssemblyViewModel::RowType)
|
Swift | UTF-8 | 3,697 | 2.734375 | 3 | [] | no_license | //
// ViewController.swift
// tinderClone
//
// Created by Wilson on 2017-02-07.
// Copyright © 2017 com.Wilson. All rights reserved.
//
import UIKit
import CoreData
var currentUser = ""
class ViewController: UIViewController {
@IBOutlet weak var usenameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var messageLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func getcurrentUser() -> String {
return currentUser
}
func setcurrentUser(user:String) {
currentUser = user
}
@IBAction func loginButton(_ sender: Any) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
var result = [NSManagedObject]()
var predicates = [NSPredicate]()
predicates.append(NSPredicate(format: "username = %@", usenameField.text!))
predicates.append(NSPredicate(format: "password = %@", passwordField.text!))
let compoundPredicate = NSCompoundPredicate.init(andPredicateWithSubpredicates: predicates)
request.predicate = compoundPredicate
request.returnsObjectsAsFaults = false
do {
result = try context.fetch(request) as! [NSManagedObject]
} catch {
messageLabel.text = "Could not Sign Up"
}
if result.count > 0 {
performSegue(withIdentifier: "login", sender: self)
setcurrentUser(user: self.usenameField.text!)
} else {
messageLabel.text = "Could not sign in"
}
}
@IBAction func signUpButton(_ sender: Any) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
let newUser = NSEntityDescription.insertNewObject(forEntityName: "User", into: context)
var result = [NSManagedObject]()
if usenameField.text != "" && passwordField.text != "" {
if let password = passwordField.text, let username = usenameField.text {
let predicate = NSPredicate(format: "username = %@", username)
request.predicate = predicate
request.returnsObjectsAsFaults = false
do {
result = try context.fetch(request) as! [NSManagedObject]
} catch {
messageLabel.text = "Could not sign up"
}
if result.count > 0 {
messageLabel.text = "That Username is already taken"
} else {
newUser.setValue(username, forKey: "username")
newUser.setValue(password, forKey: "password")
}
} else {
messageLabel.text = "Could not Sign up"
}
} else {
messageLabel.text = "Could not Sign up"
}
do {
try context.save()
} catch {
messageLabel.text = "Could not Sign up"
}
}
}
|
Java | UTF-8 | 1,237 | 1.992188 | 2 | [] | no_license | package com.acorn.shoopse.agency.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.acorn.shoopse.agency.dto.AgencyDto;
import com.acorn.shoopse.agency.service.AgencyService;
@Controller
public class AgencyController {
@Autowired
private AgencyService agencyService;
@RequestMapping("/manager/insertformagency")
public ModelAndView insertformAgency(){
ModelAndView mView = new ModelAndView();
mView.setViewName("manager/insertform_agency");
return mView;
}
@RequestMapping("manager/insertagency")
public String insert(@ModelAttribute AgencyDto dto){
System.out.println("company 출력 :"+dto.getCompany());
agencyService.insert(dto);
return "redirect:agencylist.do";
}
@RequestMapping("manager/agencylist")
public ModelAndView getList(){
ModelAndView mView=agencyService.getList();
mView.setViewName("manager/agency_list");
return mView;
}
}
|
C# | UTF-8 | 2,434 | 2.828125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using Oracle.DataAccess.Client;
/// <summary>
/// Summary description for OracleConnect
/// </summary>
public class OracleConnect
{
string connectionString;
private OracleConnection connection;
private OracleDataAdapter adapter;
private OracleCommand command;
public OracleConnect(string host, string dbname, string username, String password)
{
//
// TODO: Add constructor logic here
//
try
{
//this.connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST="+host+")(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME="+dbname+")));User Id="+username+";Password="+password+";";
this.connectionString = "User id=" + username + ";Password=" + password + ";Data Source=" + dbname;
this.connection = new Oracle.DataAccess.Client.OracleConnection(this.connectionString);
this.connection.Open();
this.command = connection.CreateCommand();
Console.WriteLine("Connected");
}
catch (Exception e)
{
Console.WriteLine("Error while connecting:" + e.Message);
}
}
public DataTable searchDB(string query)
{
DataTable table = new DataTable();
try
{
this.command.CommandText = query;
this.adapter = new Oracle.DataAccess.Client.OracleDataAdapter(command);
this.adapter.Fill(table);
}
catch (Exception e)
{
Console.Write("Error:" + e);
}
return table;
}
public DataSet searchDBSet(string query)
{
DataSet ds = new DataSet();
try
{
this.command.CommandText = query;
this.adapter = new Oracle.DataAccess.Client.OracleDataAdapter(command);
this.adapter.Fill(ds);
}
catch (Exception e)
{
Console.Write("Error:" + e);
}
return ds;
}
public int updateDB(string query)
{
try
{
this.command.CommandText = query;
return this.command.ExecuteNonQuery();
}
catch (Exception e)
{
Console.Write("Error:" + e);
return -1;
}
}
public void close()
{
connection.Close();
}
} |
Go | UTF-8 | 686 | 3.234375 | 3 | [] | no_license | package maps
import (
"bufio"
"fmt"
"os"
"strings"
)
func WordFreq(input string) map[string]int {
scanner := bufio.NewScanner(strings.NewReader(input))
scanner.Split(bufio.ScanWords)
wordsFreq := make(map[string]int)
for scanner.Scan() {
word := scanner.Text()
wordsFreq[word]++
}
return wordsFreq
}
func WordFreqFromFile(inputFilePath string) map[string]int {
file, err := os.Open(inputFilePath)
if err != nil {
fmt.Println("Input file could not be read")
return nil
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanWords)
wordsFreq := make(map[string]int)
for scanner.Scan() {
word := scanner.Text()
wordsFreq[word]++
}
return wordsFreq
}
|
Shell | UTF-8 | 613 | 2.640625 | 3 | [] | no_license | #!/bin/bash
##locahost YUM Repository
##zuozhe cj
##time 20180411
YUM="/application/yum/centos6.6/x86_64/"
mkdir -p $YUM
cd $YUM
##将已经下载好的rpm包放进$YUM目录下
##
yum -y install createrepo
createrepo -pdo /application/yum/centos6.6/x86_64/ /application/yum/centos6.6/x86_64/
##
cd $YUM
python -m SimpleHTTPServer 80 &>/dev/null &
####################################################
yumdownloader pcre-devel openssl-devel
#####################################
createrepo --update /application/yum/centos6.6/x86_64/
#############
#完成后,可在浏览器输入IP查看是否有程序列表
|
TypeScript | UTF-8 | 1,208 | 3.421875 | 3 | [] | no_license | /**
* Injeta um elemento do DOM em uma propriedade.
*
* @param seletor um seletor CSS: id, class.
*
* @returns o elemento a ser injetado.
*/
export function domInjector(seletor: string) {
/**
* Decorator que injeta um elemento do DOM em uma propriedade.
*
* @param target - Em propriedades estáticas, é a função construtora da classe. Para propriedades não estáticas, é o Prototype da classe em que está sendo aplicado o decorator.
* @param propertyKey - Nome do propriedade em que o decorator é aplicado.
*
* @returns
*/
return function (target: any, propertyKey: string) {
/** Faz o cache do elemento em função do escopo da função. */
let elemento: HTMLElement;
/** Define o get para ser adicionado na definição da propriedade. */
const getter = function () {
if (!elemento) {
elemento = <HTMLElement>document.querySelector(seletor);
}
return elemento;
}
/** Adiciona um getter a definição da propriedade. */
Object.defineProperty(
target,
propertyKey,
{ get: getter }
);
}
} |
Swift | UTF-8 | 579 | 2.8125 | 3 | [] | no_license | //
// DateExtensions.swift
// TandemForecast
//
// Created by Daniel Tombor on 2018. 02. 25..
// Copyright © 2018. danieltmbr. All rights reserved.
//
import Foundation
extension Date {
var localizedDay: String {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .none
return formatter.string(from: self)
}
var localizedHour:String {
let formatter = DateFormatter()
formatter.dateStyle = .none
formatter.timeStyle = .short
return formatter.string(from: self)
}
}
|
Java | UTF-8 | 1,943 | 1.804688 | 2 | [
"Apache-2.0"
] | permissive | /***
* Copyright (c) 2009 Caelum - www.caelum.com.br/opensource - guilherme.silveira@caelum.com.br
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package br.com.caelum.vraptor.restfulie.serialization;
import java.io.Writer;
import br.com.caelum.vraptor.interceptor.TypeNameExtractor;
import br.com.caelum.vraptor.serialization.ProxyInitializer;
import br.com.caelum.vraptor.serialization.Serializer;
import br.com.caelum.vraptor.serialization.SerializerBuilder;
import br.com.caelum.vraptor.serialization.xstream.XStreamSerializer;
import com.thoughtworks.xstream.XStream;
public class LinksSerializer implements SerializerBuilder {
private final XStreamSerializer serializer;
public LinksSerializer(XStream xstream, Writer writer, TypeNameExtractor extractor, ProxyInitializer initializer) {
this.serializer = new XStreamSerializer(xstream, writer, extractor, initializer);
}
public Serializer exclude(String... arg0) {
return serializer.exclude(arg0);
}
public Serializer excludeAll() {
return serializer.excludeAll();
}
public <T> Serializer from(T object) {
return serializer.from(object);
}
public Serializer include(String... arg0) {
return serializer.include(arg0);
}
public void serialize() {
serializer.serialize();
}
public <T> Serializer from(T arg0, String arg1) {
return serializer.from(arg0, arg1);
}
public Serializer recursive() {
return serializer.recursive();
}
}
|
JavaScript | UTF-8 | 1,187 | 2.71875 | 3 | [] | no_license | /**
* https://randomuser.me/api/?results=4
*/
import React from "react";
const Idol = (props) => {
return (
<div style={styles.container}>
<img src={props.imageUrl} alt={props.name} />
<div style={styles.info}>
<div>Name: {props.name}</div>
<div>Gender: {props.gender}</div>
<div>Age: {props.age}</div>
</div>
</div>
);
};
export default Idol;
const styles = {
container: {
display: "flex",
paddingTop: 15
},
info: {
paddingLeft: 30,
display: "flex",
flexDirection: "column",
justifyContent: "space-around"
}
};
/**
import React from "react";
const Idol = (props) => {
return (
<div
style={{
display: "flex",
borderWidth: 2,
paddingTop: 10
}}
>
<img src={props.imageUrl} alt={props.name} />
<div
style={{
paddingLeft: 30,
display: "flex",
flexDirection: "column",
justifyContent: "space-around"
}}
>
<div>Name: {props.name}</div>
<div>Gender: {props.gender}</div>
<div>Age: {props.age}</div>
</div>
</div>
);
};
export default Idol;
*/
|
Java | UTF-8 | 3,450 | 2.578125 | 3 | [] | no_license | package webdriver;
import static org.testng.Assert.assertEquals;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class Topic_03_Exercise_Xpath_CSS {
WebDriver driver;
@BeforeClass
public void beforeClass() {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://live.demoguru99.com/");
}
@Test
public void TC_01_EmailPassEmpty() {
driver.findElement(By.xpath("//div[@class='footer']//a[@title='My Account']")).click();
sleepInsecond(3);
driver.findElement(By.id("email")).sendKeys("");
driver.findElement(By.id("pass")).sendKeys("");
driver.findElement(By.id("send2")).click();
Assert.assertEquals(driver.findElement(By.id("advice-required-entry-email")).getText(), "This is a required field.");
Assert.assertEquals(driver.findElement(By.id("advice-required-entry-pass")).getText(), "This is a required field.");
}
@Test
public void TC_02_InvalidEmail() {
driver.get("http://live.demoguru99.com/");
driver.findElement(By.xpath("//div[@class='footer']//a[@title='My Account']")).click();
sleepInsecond(3);
driver.findElement(By.id("email")).sendKeys("123426677@124567755");
sleepInsecond(3);
driver.findElement(By.id("pass")).sendKeys("123456");
sleepInsecond(3);
driver.findElement(By.id("send2")).click();
sleepInsecond(3);
Assert.assertEquals(driver.findElement(By.id("advice-validate-email-email")).getText(),"Please enter a valid email address. For example johndoe@domain.com.");
}
@Test
public void TC_03_InvalidPass() {
driver.get("http://live.demoguru99.com/");
driver.findElement(By.xpath("//div[@class='footer']//a[@title='My Account']")).click();
driver.findElement(By.id("email")).sendKeys("automation@gmail.com");
sleepInsecond(3);driver.findElement(By.id("pass")).sendKeys("123");
driver.findElement(By.id("send2")).click();
Assert.assertEquals(driver.findElement(By.id("advice-validate-password-pass")).getText(),"Please enter 6 or more characters without leading or trailing spaces.");
}
@Test
public void TC_04_InvalidEmailPass() {
driver.get("http://live.demoguru99.com/");
driver.findElement(By.xpath("//div[@class='footer']//a[@title='My Account']")).click();
sleepInsecond(3);
driver.findElement(By.className("validate-email")).sendKeys("automation@gmail.com");
sleepInsecond(3);
driver.findElement(By.className("validate-password")).sendKeys("12345622");
sleepInsecond(3);
driver.findElement(By.id("send2")).click();
Assert.assertEquals(driver.findElement(By.xpath("//li[@class='error-msg']//span")).getText(),"Invalid login or password.");
}
@Test
public void TC_05_CreatAcc() {
driver.get("http://live.demoguru99.com/");
driver.findElement(By.cssSelector("div.account-cart-wrapper > a > span:last-child")).click();
sleepInsecond(3);
driver.findElement(By.linkText("My Account")).click();
sleepInsecond(3);
}
@Test
public void TC_06_LoginValid() {
}
@AfterClass
public void afterClass() {
driver.quit();
}
public void sleepInsecond(long timeoutInsecond){
try {
Thread.sleep(timeoutInsecond *1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
Python | UTF-8 | 1,892 | 2.59375 | 3 | [] | no_license | ###Import the correct python libraries
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from sqlalchemy.orm import relationship
from .database import Base
class Detroit(Base):
__tablename__ = "detroit"
###Primary Key is required for the table to populate
Year = Column(Integer, primary_key=True, index=True)
FTP = Column(Integer)
UEMP = Column(Integer)
MAN = Column(Integer)
LIC = Column(Integer)
GR = Column(Integer)
CLEAR = Column(Integer)
WM = Column(Integer)
NMAN = Column(Integer)
GOV = Column(Integer)
HE = Column(Integer)
WE = Column(Integer)
HOM = Column(Integer)
class Student(Base):
__tablename__ = "student"
"""###Primary Key is required for the table to populate"""
"""###Set the Column(Type) to what is in your database e.g. Integer, String, etc."""
school = Column(String)
sex = Column(String)
age = Column(Integer, primary_key=True, index=True)
address = Column(String)
famsize = Column(String)
Pstatus = Column(String)
Medu = Column(Integer)
Fedu = Column(Integer)
Mjob = Column(String)
Fjob = Column(String)
reason = Column(String)
guardian = Column(String)
traveltime = Column(Integer)
studytime = Column(Integer)
failures = Column(Integer)
schoolsup = Column(String)
famsup = Column(String)
paid = Column(String)
activities = Column(String)
nursery = Column(String)
higher = Column(String)
internet = Column(String)
romantic = Column(String)
famrel = Column(Integer)
freetime = Column(Integer)
goout = Column(Integer)
Dalc = Column(Integer)
Walc = Column(Integer)
health = Column(Integer)
absences = Column(Integer)
G1 = Column(Integer)
G2 = Column(Integer)
G3 = Column(Integer)
|
C++ | UTF-8 | 1,907 | 3.265625 | 3 | [] | no_license | // Assignment 1 - Algorithm 2 (Knuth)
// Tidy Tree Drawing
// Ensure parent is centered around children
// But ignores that tree should occupy minimum width
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string.h>
#include "treedraw.h"
using namespace std;
//Coordinate assignment according to Algorithm 2
void assignCoordinates()
{
//Initialize walk from root
node* current = &tree[0];
int next_number = 1;
current->status=FIRST_VISIT;
//Indicates when to stop traversal - when we rereach root
bool flag = true;
while (flag)
{
//INORDER PLACEMENT
switch(current->status)
{
case FIRST_VISIT:
current->status = LEFT_VISIT;
if(current->children.size()>0)
{
current = &tree[current->children[0]];
current->status = FIRST_VISIT;
}
break;
case LEFT_VISIT:
current->x = next_number;
next_number = next_number + 1;
current->y = 2*current->height + 1;
current->status = RIGHT_VISIT;
if(current->children.size()>1)
{
current = &tree[current->children[1]];
current->status = FIRST_VISIT;
}
break;
case RIGHT_VISIT:
//Go up level and visit parent
if(current->parent!=-1)
current = &tree[current->parent];
//If parent==-1, means we have reached NIL
else
flag = false;
break;
}
}
}
void updateRoutine(void)
{
//Read, build and assign coordinates to tree nodes according to Algorithm 2
readTree();
buildTree();
assignCoordinates();
setSpacingParameters();
drawTree();
}
int main(int argc, char **argv)
{
//GLUT setup
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowPosition(50,50);
glutInitWindowSize(900,600);
glutCreateWindow("Algorithm 2");
binarytreeflag = true;
//Display tree and window
init2D();
glutDisplayFunc(updateRoutine);
glutIdleFunc(updateRoutine);
glutMainLoop();
return 0;
}
|
Python | UTF-8 | 1,470 | 3.0625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
"""
Created on Tue May 26 03:19:31 2020
@author: thequietprogrammer
"""
import os, sys
if not os.path.exists('aNames'):
os.mkdir('aNames')
for i in range(164):
# Desse jeito, vamos direto ao arquivo bruto original.
aOld = "../raw.en/englishText_"+str(i*10000)+"_"+str(10000*(i+1))
aNew = "aNames/aTitles_"+str(i*10000)+"_"+str(10000*(i+1))+".txt"
aFile = open(aOld, 'r')
aNotherFile = open(aNew, 'w', encoding='utf8')
aCount = i*10000
for aLine in aFile:
aLine = aLine.split(" ")
# Aqui, ignoramos as linhas de texto, e selecionamos as que contém
# um título e um index.
if aLine[0] == "<doc" and aLine[-1][0:7] == "dbindex":
# Por aqui, formatamos aLine para mostrar apenas index e título.
aLine = [aLine[-1][9:-3]] + aLine[2:-3]
aLine[1] = aLine[1][7:]
aLine[-1] = aLine[-1][:-1]
if int(aLine[0]) != aCount:
aNotherFile.write("\n"*(int(aLine[0])-aCount))
aCount += int(aLine[0]) - aCount
aNotherFile.write(" ".join(aLine)+"\n")
aCount += 1
else: aNotherFile.write("\n\nWe all have an start...\n... and an end.")
aFile.close()
aNotherFile.close()
# Coisinha para ficar melhor de visualizar.
sys.stdout.write("\rMaking Files: "+str(i+1)+" of 164. ")
sys.stdout.flush()
else: print("Finished.")
|
JavaScript | UTF-8 | 1,153 | 2.609375 | 3 | [] | no_license | require('dotenv').config();
var sensor = require("node-dht-sensor");
const mongoose=require('mongoose');
const db=process.env.db;
const connect = mongoose
.connect(db, { useFindAndModify: false,useUnifiedTopology:true,useNewUrlParser:true })
.then(() => {
console.log("Mondo db connected....");
})
.catch((err) => console.log(err));
const THSchema = new mongoose.Schema({
time:{
type:String,
required:true
},
temperature:{
type:String,
required:true
},
humidity:{
type:String,
required:true
}
});
const TH=mongoose.model('TH',THSchema);
setInterval(read,60000);
function read(){
sensor.read(11, 4, function(err, temperature, humidity) {
if (!err) {
var d=new Date();
var th=new TH({
time:d,
temperature:temperature,
humidity:humidity
});
th.save(function(err,res){
if(err){
console.log("Error pushing data to DB");
}
else{
console.log(`temp: ${temperature}°C, humidity: ${humidity}%`);
}
});
}
else{
console.log("Error in reading data from sensor");
}
});
}
|
C# | UTF-8 | 8,841 | 3.140625 | 3 | [
"MIT"
] | permissive | using System;
namespace SshNet.Security.Cryptography
{
internal abstract class HashProviderBase : IHashProvider
{
private bool _disposed;
private byte[] _hashValue;
/// <summary>
/// Gets the value of the computed hash code.
/// </summary>
/// <value>
/// The current value of the computed hash code.
/// </value>
/// <exception cref="ObjectDisposedException">The object has already been disposed.</exception>
public byte[] Hash
{
get
{
if (_disposed)
throw new ObjectDisposedException(GetType().FullName);
return (byte[]) _hashValue.Clone();
}
}
/// <summary>
/// Computes the hash value for the specified region of the input byte array and copies the specified
/// region of the input byte array to the specified region of the output byte array.
/// </summary>
/// <param name="inputBuffer">The input to compute the hash code for.</param>
/// <param name="inputOffset">The offset into the input byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the input byte array to use as data.</param>
/// <param name="outputBuffer">A copy of the part of the input array used to compute the hash code.</param>
/// <param name="outputOffset">The offset into the output byte array from which to begin writing data.</param>
/// <returns>
/// The number of bytes written.
/// </returns>
/// <exception cref="ArgumentException">
/// <para><paramref name="inputCount"/> uses an invalid value.</para>
/// <para>-or-</para>
/// <para><paramref name="inputBuffer"/> has an invalid length.</para>
/// </exception>
/// <exception cref="ArgumentNullException"><paramref name="inputBuffer"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="inputOffset"/> is out of range. This parameter requires a non-negative number.</exception>
/// <exception cref="ObjectDisposedException">The object has already been disposed.</exception>
public int TransformBlock(byte[] inputBuffer, int inputOffset, int inputCount, byte[] outputBuffer, int outputOffset)
{
if (_disposed)
throw new ObjectDisposedException(GetType().FullName);
if (inputBuffer == null)
throw new ArgumentNullException("inputBuffer");
if (inputOffset < 0)
throw new ArgumentOutOfRangeException("inputOffset");
if (inputCount < 0 || (inputCount > inputBuffer.Length))
throw new ArgumentException("XX");
if ((inputBuffer.Length - inputCount) < inputOffset)
throw new ArgumentException("xx");
HashCore(inputBuffer, inputOffset, inputCount);
// todo: optimize this by taking into account that inputBuffer and outputBuffer can be the same
Buffer.BlockCopy(inputBuffer, inputOffset, outputBuffer, outputOffset, inputCount);
return inputCount;
}
/// <summary>
/// Computes the hash value for the specified region of the specified byte array.
/// </summary>
/// <param name="inputBuffer">The input to compute the hash code for.</param>
/// <param name="inputOffset">The offset into the byte array from which to begin using data.</param>
/// <param name="inputCount">The number of bytes in the byte array to use as data.</param>
/// <returns>
/// An array that is a copy of the part of the input that is hashed.
/// </returns>
/// <exception cref="ArgumentException">
/// <para><paramref name="inputCount"/> uses an invalid value.</para>
/// <para>-or-</para>
/// <para><paramref name="inputBuffer"/> has an invalid length.</para>
/// </exception>
/// <exception cref="ArgumentNullException"><paramref name="inputBuffer"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="inputOffset"/> is out of range. This parameter requires a non-negative number.</exception>
/// <exception cref="ObjectDisposedException">The object has already been disposed.</exception>
public byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount)
{
if (_disposed)
throw new ObjectDisposedException(GetType().FullName);
if (inputBuffer == null)
throw new ArgumentNullException("inputBuffer");
if (inputOffset < 0)
throw new ArgumentOutOfRangeException("inputOffset");
if (inputCount < 0 || (inputCount > inputBuffer.Length))
throw new ArgumentException("XX");
if ((inputBuffer.Length - inputCount) < inputOffset)
throw new ArgumentException("xx");
HashCore(inputBuffer, inputOffset, inputCount);
_hashValue = HashFinal();
// from the MSDN docs:
// the return value of this method is not the hash value, but only a copy of the hashed part of the input data
var outputBytes = new byte[inputCount];
Buffer.BlockCopy(inputBuffer, inputOffset, outputBytes, 0, inputCount);
return outputBytes;
}
/// <summary>
/// Computes the hash value for the input data.
/// </summary>
/// <param name="buffer">The input to compute the hash code for.</param>
/// <returns>
/// The computed hash code.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <c>null</c>.</exception>
/// <exception cref="ObjectDisposedException">The object has already been disposed.</exception>
public byte[] ComputeHash(byte[] buffer)
{
if (_disposed)
throw new ObjectDisposedException(GetType().FullName);
if (buffer == null)
throw new ArgumentNullException("buffer");
HashCore(buffer, 0, buffer.Length);
_hashValue = HashFinal();
Reset();
return Hash;
}
/// <summary>
/// Releases all resources used by the current instance of the <see cref="HashProviderBase"/> class.
/// </summary>
public void Dispose()
{
GC.SuppressFinalize(this);
Dispose(true);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="HashProviderBase"/> and optionally releases the managed resources.
/// </summary>
/// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_hashValue = null;
}
_disposed = true;
}
/// <summary>
/// Gets the size, in bits, of the computed hash code.
/// </summary>
/// <returns>
/// The size, in bits, of the computed hash code.
/// </returns>
public abstract int HashSize { get; }
/// <summary>
/// Gets the input block size.
/// </summary>
/// <returns>
/// The input block size.
/// </returns>
public abstract int InputBlockSize { get; }
/// <summary>
/// Gets the output block size.
/// </summary>
/// <returns>
/// The output block size.
/// </returns>
public abstract int OutputBlockSize { get; }
/// <summary>
/// Resets an implementation of <see cref="HashProviderBase"/> to its initial state.
/// </summary>
public abstract void Reset();
/// <summary>
/// Routes data written to the object into the hash algorithm for computing the hash.
/// </summary>
/// <param name="array">The input to compute the hash code for.</param>
/// <param name="ibStart">The offset into the byte array from which to begin using data.</param>
/// <param name="cbSize">The number of bytes in the byte array to use as data.</param>
public abstract void HashCore(byte[] array, int ibStart, int cbSize);
/// <summary>
/// Finalizes the hash computation after the last data is processed by the cryptographic stream object.
/// </summary>
/// <returns>
/// The computed hash code.
/// </returns>
public abstract byte[] HashFinal();
}
}
|
Swift | UTF-8 | 2,371 | 2.609375 | 3 | [] | no_license | //
// DescribeMissionViewController.swift
// PostMishone
//
// Created by Victor Liang on 2018-10-14.
// Copyright © 2018 Victor Liang. All rights reserved.
//
import UIKit
import Firebase
import MapKit
import CoreLocation
class DescribeMissionViewController: UIViewController {
var ref: DatabaseReference!
var latitude = 0.0
var longitude = 0.0
@IBOutlet weak var missionName: UITextField!
@IBOutlet weak var missionDescription: UITextField!
@IBOutlet weak var reward: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
missionName.delegate = self
missionDescription.delegate = self
reward.delegate = self
// Do any additional setup after loading the view.
ref = Database.database().reference() //Firebase Reference
}
@IBAction func postMissionPressed(_ sender: Any) {
let userID = Auth.auth().currentUser!.uid
let timeStamp = Int(NSDate.timeIntervalSinceReferenceDate*1000)
print("Describe Mission View Controller:")
print("lat: ", latitude)
print("long: ", longitude)
print("userID: ", userID)
print("timeStamp: ", timeStamp)
print("missionNameText: ", missionName.text!)
print("missionDescription: ", missionDescription.text!)
print("reward: ", reward.text!)
ref?.child("PostedMissions").childByAutoId().setValue(["Latitude": latitude, "Longitude": longitude, "UserID": userID, "timeStamp": timeStamp, "missionName": missionName.text!, "missionDescription": missionDescription.text!, "reward": reward.text!])
print("Mission Posted!")
self.navigationController?.popViewController(animated: true)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}
/*make keyboard close on return*/
extension DescribeMissionViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
}
|
C++ | UTF-8 | 5,487 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <vector>
#include <algorithm>
using namespace std;
int pbc_round(double input)
{
int i = input;
if (abs(input - i) >= 0.5)
{
if (input > 0) {i += 1;}
if (input < 0) {i -= 1;}
}
return i;
}
double min_distance(double array[], int length)
{
double min = array[0];
for (int i = 1; i < length; i ++)
{
if (array[i] < min && array[i] != 0)
{
min = array[i];
}
}
return min;
}
int main()
{
// file streams
ifstream inputfile;
ofstream hbonds_outputfile;
string infile;
int timesteps, nooa, noha;
double lattice;
cout << "Please enter the filename of your file: ";
cin >> infile;
cout << "Please enter the number of oxygen atoms: ";
cin >> nooa;
cout << "Please enter the number of hydrogen atoms: ";
cin >> noha;
cout << "Please enter the number of timesteps: ";
cin >> timesteps;
cout << "Please enter the lattice constant for your periodic cube: ";
cin >> lattice;
cout << "Program running...please wait a moment.\n\n";
// end of main menu*/
//read the inputfile
inputfile.open(infile.c_str());
int noa = nooa + noha;
double x[noa*timesteps], y[noa*timesteps], z[noa*timesteps];
int counter = 0;
while (!inputfile.eof())
{
inputfile >> x[counter] >> y[counter] >> z[counter];
counter ++;
}
double oxyz[nooa][3], hxyz[noha][3];
int ohindices[nooa][4];
for (int i = 0; i < nooa; i ++)
{
for (int j = 0; j < 4; j ++)
{
ohindices[i][j] = -1;
}
}
vector <double> everything;
hbonds_outputfile.open("hbonds_contour.dat");
int xcoord, ycoord, xybin[13][13] = {};
double xyhbin[13][13] = {}, hcount[nooa] ;
for (int i = 0; i < timesteps; i ++)
{
for (int j = 0; j < nooa; j ++)
{
oxyz[j][0] = lattice*x[j + i*noa];
oxyz[j][1] = lattice*y[j + i*noa];
oxyz[j][2] = lattice*z[j + i*noa];
hcount[j] = 0;
}
for (int j = 0; j < noha; j ++)
{
hxyz[j][0] = lattice*x[nooa + j + i*noa];
hxyz[j][1] = lattice*y[nooa + j + i*noa];
hxyz[j][2] = lattice*z[nooa + j + i*noa];
}
for (int j = 0; j < nooa; j++)
{
int count = 0;
for (int k = 0; k < noha; k ++)
{
double dx = oxyz[j][0] - hxyz[k][0];
double dy = oxyz[j][1] - hxyz[k][1];
double dz = oxyz[j][2] - hxyz[k][2];
dx -= lattice*pbc_round(dx/lattice);
dy -= lattice*pbc_round(dy/lattice);
dz -= lattice*pbc_round(dz/lattice);
double ohdist = sqrt ( dx*dx + dy*dy + dz*dz );
if (ohdist < 1.15)
{
ohindices[j][count] = k;
count ++;
}
}
hcount[j] += count;
}
for (int j = 0; j < nooa; j ++)
{
int count = 0;
for (int k = 0; k < nooa; k ++)
{
double odx = oxyz[j][0] - oxyz[k][0];
double ody = oxyz[j][1] - oxyz[k][1];
double odz = oxyz[j][2] - oxyz[k][2];
odx -= lattice*pbc_round(odx/lattice);
ody -= lattice*pbc_round(ody/lattice);
odz -= lattice*pbc_round(odz/lattice);
double oodist = sqrt (odx*odx + ody*ody + odz*odz );
if (oodist > 0.0 && oodist < 3.6)
{
for (int n = 0; n < 4; n ++)
{
if ( n == 0)
{
if (ohindices[k][n] != -1)
{
double hdx = oxyz[j][0] - hxyz[ohindices[k][n]][0];
double hdy = oxyz[j][1] - hxyz[ohindices[k][n]][1];
double hdz = oxyz[j][2] - hxyz[ohindices[k][n]][2];
hdx -= lattice*pbc_round(hdx/lattice);
hdy -= lattice*pbc_round(hdy/lattice);
hdz -= lattice*pbc_round(hdz/lattice);
double hdist = sqrt( hdx*hdx + hdy*hdy + hdz*hdz );
double dot = odx*hdx + ody*hdy + odz*hdz;
double angle = acos (dot / (oodist*hdist)) * 57.2957795;
if (angle < 30.0 && hdist < 2.4)
{
count ++;
}
}
}
if (n > 0)
{
if (ohindices[k][n] != -1 && ohindices[k][n] != ohindices[k][n-1])
{
double hdx = oxyz[j][0] - hxyz[ohindices[k][n]][0];
double hdy = oxyz[j][1] - hxyz[ohindices[k][n]][1];
double hdz = oxyz[j][2] - hxyz[ohindices[k][n]][2];
hdx -= lattice*pbc_round(hdx/lattice);
hdy -= lattice*pbc_round(hdy/lattice);
hdz -= lattice*pbc_round(hdz/lattice);
double hdist = sqrt( hdx*hdx + hdy*hdy + hdz*hdz );
double dot = odx*hdx + ody*hdy + odz*hdz;
double angle = acos (dot / (oodist*hdist)) * 57.2957795;
if (angle < 30.0 && hdist < 2.4)
{
count ++;
}
}
}
}
}
}
hcount[j] += count;
xcoord = round(oxyz[j][0]);
ycoord = round(oxyz[j][1]);
xybin[xcoord][ycoord] ++;
xyhbin[xcoord][ycoord] += hcount[j];
}
}
for (int i = 0; i < 13; i ++)
{
for (int j = 0; j < 13; j ++)
{
if (xybin[i][j] != 0)
{
hbonds_outputfile << i << "\t" << j << "\t" << xyhbin[i][j]/xybin[i][j] << endl;
}
else
{
hbonds_outputfile << i << "\t" << j << "\t" << xyhbin[i][j] << endl;
}
}
}
inputfile.close();
hbonds_outputfile.close();
return 0;
}
|
Python | UTF-8 | 2,410 | 2.609375 | 3 | [] | no_license | from django.shortcuts import render, HttpResponse, redirect
import random
import datetime
#from flask import Flask, render_template, request, redirect, request.session
#app.yourgold = 0
def generate_gold(request, loc):
newgold = 0
winlose = 0
if loc == "farm":
newgold = random.randrange(10,21)
request.session['yourgold'] = request.session['yourgold'] + newgold
request.session['activity'].insert(0, 'Earned ' + str(newgold) + ' golds from the farm! (' + datetime.datetime.now().strftime("%Y/%m/%d %I:%M %p)"))
elif loc == "cave":
newgold = random.randrange(5,11)
request.session['yourgold'] = request.session['yourgold'] + newgold
request.session['activity'].insert(0, 'Earned ' + str(newgold) + ' golds from the cave! (' + datetime.datetime.now().strftime("%Y/%m/%d %I:%M %p)"))
elif loc == "house":
newgold = random.randrange(2,6)
request.session['yourgold'] = request.session['yourgold'] + newgold
request.session['activity'].insert(0, 'Earned ' + str(newgold) + ' golds from the house! (' + datetime.datetime.now().strftime("%Y/%m/%d %I:%M %p)"))
elif loc == "casino":
winlose = random.randrange(1,3)
if winlose == 1:
newgold = random.randrange(0,51)
request.session['yourgold'] = request.session['yourgold'] + newgold
request.session['activity'].insert(0, 'Earned ' + str(newgold) + ' golds from the casino! (' + datetime.datetime.now().strftime("%Y/%m/%d %I:%M %p)"))
else:
newgold = random.randrange(10,21)
request.session['yourgold'] = request.session['yourgold'] - newgold
request.session['activity'].insert(0, 'Entered a casino and lost ' + str(newgold) + ' golds.. Ouch.. (' + datetime.datetime.now().strftime("%Y/%m/%d %I:%M %p)"))
def index(request):
if 'yourgold' not in request.session:
request.session['yourgold'] = 0
if 'activity' not in request.session:
request.session['activity'] = []
yourgold = request.session['yourgold']
activity = request.session['activity']
return render(request, 'ninja_gold/index.html')
# @app.route('/process_money', methods = ['POST'])
def process_money(request, location):
# your_location = request.form.get('building')
yourgold = request.session['yourgold']
generate_gold(request, location)
return redirect('/') |
C# | UTF-8 | 7,970 | 2.515625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Common.Logging;
namespace RobotBlocks.Implementation.SQLServer
{
public class DatabaseGenerator : RobotBlocks.Interfaces.IDatabaseGenerator
{
private static Common.Logging.ILog LOG = Utilities.Logging.Logger.GetLogger<DatabaseGenerator>();
private const string ROBOT_BLOCKS_TAG = "--===ROBOTBLOCKS===--";
private readonly System.Collections.Generic.Dictionary<Type, string> CLR_TYPES = new Dictionary<Type, string>()
{
{ typeof(System.String), "NVARCHAR" },
/*required*/
{ typeof(System.Int16), "SMALLINT NOT NULL" },
{ typeof(System.Int32), "INT NOT NULL" },
{ typeof(System.Int64), "BIGINT NOT NULL" },
{ typeof(System.Boolean), "BIT NOT NULL" },
{ typeof(System.Single), "DECIMAL NOT NULL" },
{ typeof(System.Double), "DECIMAL NOT NULL" },
{ typeof(System.Decimal), "DECIMAL(10,2) NOT NULL"},
{ typeof(System.DateTime), "DATETIME NOT NULL"},
/*nullable*/
{ typeof(System.Nullable<System.Int16>), "SMALLINT NULL" },
{ typeof(System.Nullable<System.Int32>), "INT NULL" },
{ typeof(System.Nullable<System.Int64>), "BIGINT NULL" },
{ typeof(System.Nullable<System.Boolean>), "BIT NULL" },
{ typeof(System.Nullable<System.Single>), "DECIMAL NULL" },
{ typeof(System.Nullable<System.Double>), "DECIMAL NULL" },
{ typeof(System.Nullable<System.Decimal>), "DECIMAL(10,2) NULL"},
{ typeof(System.Nullable<System.DateTime>), "DATETIME NULL"}
};
public bool IsMappableType(Type fieldType)
{
return CLR_TYPES.ContainsKey(fieldType);
}
public string GetColumnDefinition(Core.Column column)
{
string columnDefinition = string.Format("{0} {1}", column.Name, CLR_TYPES[column.UnderlyingSystemType]);
//get length rules if incoming type is a string
if (column.UnderlyingSystemType == typeof(string) || column.UnderlyingSystemType == typeof(String))
{
if (column.Length.HasValue)
{
columnDefinition = string.Format("{0}({1})", columnDefinition, column.Length.Value);
}
else
{
//assume maxlength
columnDefinition = string.Format("{0}(MAX)", columnDefinition);
}
}
//get nullability first if it wasn't already derived
if (!columnDefinition.ToLower().Contains(" null"))
{
if (column.IsRequired)
{
columnDefinition = string.Format("{0} NOT NULL", columnDefinition);
}
else
{
columnDefinition = string.Format("{0} NULL", columnDefinition);
}
}
if (column.IsPrimaryKey)
{
columnDefinition = string.Format("{0} IDENTITY(1,1) PRIMARY KEY", columnDefinition);
}
if (column.IsUnique)
{
columnDefinition = string.Format("{0} UNIQUE", columnDefinition);
}
if (column.DefaultValue != null)
{
columnDefinition =
string.Format("{0} DEFAULT {1}", columnDefinition, column.DefaultValue);
}
return columnDefinition;
}
public Core.DatabaseGeneratorResult Generate(Core.Database database)
{
System.Text.StringBuilder finalSQL = new StringBuilder();
database.UserName = String.IsNullOrWhiteSpace(database.UserName) ? string.Format("{0}_user", database.Name) : database.UserName;
database.Password = String.IsNullOrWhiteSpace(database.Password) ? GeneratePassword() : database.Password;
LOG.InfoFormat("Generating database sql creation script.");
finalSQL.AppendFormat(@"IF EXISTS (SELECT * FROM sys.databases WHERE name = '{0}')
BEGIN
DROP DATABASE WHERE name = '{0}'
END
CREATE DATABASE [{0}];
", database.Name);
//log: generating database user/login and assign roles
finalSQL.AppendFormat(@"CREATE LOGIN [{0}] WITH PASSWORD='{1}',
DEFAULT_DATABASE=[{2}], CHECK_POLICY=OFF
CREATE USER [{0}] FOR LOGIN [{0}]
EXEC sp_addrolemember N'db_datareader', N'{2}'
EXEC sp_addrolemember N'db_datawriter', N'{2}'
", database.UserName, database.Password, database.Name);
finalSQL.AppendLine(ROBOT_BLOCKS_TAG);
LOG.Info("Generating database.");
foreach (Core.Table t in database.Tables)
{
LOG.Info(m=> m("Generating Table: {0}", t.Name));
System.Text.StringBuilder columnDefinitions = new StringBuilder();
bool first = true;
foreach (Core.Column c in t.Columns)
{
string columnSQL = GetColumnDefinition(c);
if (!first)
{
columnDefinitions.AppendFormat(@",
{0}", columnSQL);
}
else
{
first = false;
columnDefinitions.AppendFormat(@"{0}", columnSQL);
}
}
finalSQL.AppendLine();
finalSQL.AppendFormat("-- creating table {0}", t.Name);
finalSQL.AppendLine();
finalSQL.AppendFormat(@"CREATE TABLE {0}
(
{1}
);
", t.Name, columnDefinitions);
//generate indices on this table
finalSQL.AppendLine();
if (t.Indices.Any())
{
finalSQL.AppendLine(string.Format("-- indexes for {0}", t.Name));
}
foreach (Core.Index index in t.Indices)
{
finalSQL.AppendFormat(@"CREATE {0} INDEX IX_{1}_{2}
ON {1} ({3});
",
GetIndexTypeAsString(index),
t.Name,
String.Join("_", index.ColumnNames),
String.Join(",", index.ColumnNames));
}
}
//generate foreign keys
foreach (Core.Table t in database.Tables)
{
//generate cascading rules on record deletion on table
finalSQL.AppendLine();
if (t.Relationships.Any())
{
finalSQL.AppendLine(string.Format("-- fk constraints for {0}", t.Name));
}
foreach (Core.Relationship relationship in t.Relationships)
{
string onDeleteRule = string.Empty;
if (relationship.IsRequired)
{
onDeleteRule = "ON DELETE CASCADE";
}
else
{
onDeleteRule = "ON DELETE SET NULL";
}
finalSQL.AppendFormat(@"ALTER TABLE {0}
ADD CONSTRAINT fk_{0}_{1}
FOREIGN KEY ({2})
REFERENCES {1}({3}) {4}
",
relationship.FromTable,
relationship.ToTable,
relationship.FromColumnNamed,
relationship.ToColumnNamed,
onDeleteRule);
}
}
return new Core.DatabaseGeneratorResult()
{
IsSuccessful = true,
Output = finalSQL.ToString()
};
}
private string GetIndexTypeAsString(Core.Index index)
{
return index.IndexType == Core.IndexType.UNIQUE ?
"UNIQUE" :
(index.IndexType == Core.IndexType.CLUSTERED ?
"CLUSTERED" : "NONCLUSTERED");
}
private string GeneratePassword(ushort passwordLength = 12)
{
const string randomChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()";
ushort MAX_LENGTH = (ushort)randomChars.Length;
char[] randomElements = randomChars.ToCharArray();
byte[] randomBytes = new byte[4];
System.Security.Cryptography.RandomNumberGenerator random = System.Security.Cryptography.RandomNumberGenerator.Create();
random.GetBytes(randomBytes);
int randomSeed = BitConverter.ToInt32(randomBytes, 0);
Random realRandom = new Random(randomSeed);
StringBuilder finalPassword = new StringBuilder();
for (short i = 0; i < passwordLength; i++)
{
finalPassword.Append(randomElements[realRandom.Next(0, MAX_LENGTH)]);
}
return finalPassword.ToString();
}
}
}
|
C# | UTF-8 | 4,053 | 3.21875 | 3 | [
"MIT"
] | permissive | using System;
using System.Globalization;
using System.IO;
using System.Threading;
using CoenM.ImageHash;
using CoenM.ImageHash.HashAlgorithms;
namespace ImageHashConsoleApplication
{
class Program
{
static Semaphore sem = new(25, 25);
static void Main(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine(
"One parameter is missing, action need. use: hash {imagePath} | hash {pathImagesDir} | compare {hashOne} {hashTwo}"
);
return;
}
switch (args[0])
{
case "hash" when args[1] == null:
Console.WriteLine("One parameter is missing, filepath need.");
return;
case "hash":
{
var pathAttribute = File.GetAttributes(args[1]);
if ((pathAttribute & FileAttributes.Directory) == FileAttributes.Directory)
{
var onlyHash = false;
if (args.Length > 2)
{
onlyHash = (args[2] != null & args[2] == "--only-hash");
}
HashImagesInDirectory(args[1], onlyHash);
return;
}
var hash = HashImage(args[1]);
Console.WriteLine(hash);
return;
}
case "compare" when args[1] == null || args[2] == null:
Console.WriteLine("You must provide to images hash: compare {hashOne} {hashTwo}");
return;
case "compare":
{
var hashImageOne = ulong.Parse(args[1]);
var hashImageTwo = ulong.Parse(args[2]);
var compareResult = CompareImagesHash(hashImageOne, hashImageTwo);
Console.WriteLine(compareResult.ToString(CultureInfo.CurrentCulture));
return;
}
default:
Console.WriteLine("Command not found");
break;
}
}
private static void HashImagesInDirectory(string pathToDirectory, bool onlyHashOption = false)
{
var filesToHash = Directory.GetFiles(pathToDirectory);
var index = 0;
var maxThreads = filesToHash.Length + 1;
Thread[] threads = new Thread[maxThreads];
foreach (var fileToHash in filesToHash)
{
var fileAttribute = File.GetAttributes(fileToHash);
if ((fileAttribute & FileAttributes.Directory) == FileAttributes.Directory)
{
Console.WriteLine(fileToHash + " is directory, skipping");
continue;
}
threads[index] = new Thread(() =>
{
sem.WaitOne();
var hash = HashImage(fileToHash);
if (onlyHashOption)
{
Console.WriteLine(hash);
}
else
{
Console.WriteLine("Calculated perceptual hash for file: " + fileToHash + " hash: " + hash);
}
sem.Release();
});
threads[index].Start();
index++;
}
}
private static string HashImage(string path)
{
var imageHashing = new PerceptualHash();
using var stream = File.OpenRead(path);
var imageHash = imageHashing.Hash(stream);
return imageHash.ToString();
}
private static double CompareImagesHash(ulong imageHashOne, ulong imageHashTwo)
{
return CompareHash.Similarity(imageHashOne, imageHashTwo);
}
}
} |
Ruby | UTF-8 | 473 | 2.6875 | 3 | [] | no_license | require 'spec_helper'
RSpec.describe 'Composing Matchers' do
class SomeObject
attr_reader :amount
def initialize(amount)
@amount = amount
end
def *(factor)
@amount *= factor
end
end
describe SomeObject do
let(:instance) { SomeObject.new(1.0) }
describe '#*' do
subject { instance * 5.0 }
specify { expect { subject }.to change(instance, :amount).by(4.0) } # ) a_value_within(0.1).of(4.0)) }
end
end
end
|
Java | UTF-8 | 1,306 | 3.21875 | 3 | [] | no_license | public class RomanToArabian {
static String[] Rome = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
static int[] Arab = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
public static int romeToArab(String rome){
StringBuffer romeNumber = new StringBuffer(rome);
int arabNumber = 0;
int i = 0;
if (romeNumber.length() > 0) {
while (true) {
do {
if (Rome[i].length() <= romeNumber.length()) {
if (Rome[i].equals(romeNumber.substring(0, Rome[i].length()))) {
arabNumber += Arab[i];
romeNumber.delete(0, Rome[i].length());
if (romeNumber.length() == 0)
return arabNumber;
}
else
break;
}
else
break;
}
while (true && romeNumber.length() != 0);
i++;
}
}
return 0;
}
}
|
Markdown | UTF-8 | 427 | 3.9375 | 4 | [
"MIT"
] | permissive | # Math.sign()
The **`sign()`** method returns the `integer` part of a `number` by removing any fractional digits.
## Syntax
```js
const integer = Math.sign(number);
```
## Usage examples
```js
Math.sign(13.37); // -> 13
Math.sign(42.84); // -> 42
Math.sign(0.123); // -> 0
Math.sign(-0.123); // -> -0
```
---
[MDN reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sign)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.