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
|
|---|---|---|---|---|---|---|---|
C
|
UTF-8
| 28,943
| 3.59375
| 4
|
[] |
no_license
|
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <math.h>
#include "location.h"
/**
* A set of geographic locations given by latitude and longitude
* implemented using a k-d tree, where k = 2. For all functions,
* points are considered different based on the values of the
* coordinates that are passed in, even if the coordinates represent
* the same physical point, so, for example, longitude -180 is
* considered different than longitude 180.
*/
typedef struct _kdtree
{
bool axis;//true if x, false if y
location *pt;
struct _kdtree *rchild;
struct _kdtree *lchild;
} kdtree;
void location_merge(int n1, location **a1, int n2, location **a2, location **out, bool axis)
{
int i1;
int i2;
int iout;
int dupes;
i1=i2=iout=dupes=0;
while(i1 < n1 || i2 <n2)
{
if (axis)
{
if (i2 >= n2 || ((i1 < n1) && (a1[i1]->x < a2[i2]->x)))
{
out[iout++] = a1[i1++];
}
else if ((i1 >= n1) || ((i2 < n2) && a1[i1]->x > a2[i2]->x))
{
out[iout++] = a2[i2++];
}
else
{
if (i2 >= n2 || ((i1 < n1) && (a1[i1]->y < a2[i2]->y)))
{
out[iout++] = a1[i1++];
}
else //if (i1 > n1 || ((i2 < n2) && (a1[i1]->y > a2[i2]->y)))
{
out[iout++] = a2[i2++];
}
}
}
else
{
if (i2 >= n2 || ((i1 < n1) && (a1[i1]->y < a2[i2]->y)))
{
out[iout++] = a1[i1++];
}
else if(i1 >= n1 || ((i2 < n2) && a1[i1]->y > a2[i2]->y))
{
out[iout++] = a2[i2++];
}
else
{
if (i2 >= n2 || ((i1 < n1) && (a1[i1]->x < a2[i2]->x)))
{
out[iout++] = a1[i1++];
}
else //if (i1 >= n1 || ((i2 < n2) && a1[i1]->x > a2[i2]->x))
{
out[iout++] = a2[i2++];
}
}
}
}
}
void location_merge_sort(int n, location **a, location **out, bool axis)
{
location **a1;
location **a2;
if (n < 2)
{
memcpy(out, a, sizeof(location*) * n);
}
else
{
a1 = malloc(sizeof(location*) * n/2);
a2 = malloc(sizeof(location*) * (n- n/2));
location_merge_sort(n/2, a, a1, axis);
location_merge_sort(n - n/2, a + n/2, a2, axis);
location_merge(n/2, a1, n - n/2, a2, out, axis);
free(a1);
free(a2);
}
}
//returns true if next row was successfully added; false if not
//takes a node w/ a location and the sorted x and y arrs of that
//node, splits them, finds its children, and performs a recursive call
//on the children
//parameters: n is the length of the arrays, node is current node, x and yarrs contain
// the current node and will be split to find the child nodes
void kdtree_balanced_add(kdtree *node, int n, location **arr1, location **arr2)
{
//location **arr1; location **arr2;
bool curraxis = node->axis;
/*if (curraxis)
{
arr1=xarr;
arr2=yarr;
}
else
{
arr1=yarr;
arr2=xarr;
}*/
if (n==1 || n==0)
{
node->rchild = NULL;
node->lchild = NULL;
return;
}
if (n==2)
{
if(!curraxis)
{
if(arr1[0]->x == node->pt->x && arr1[0]->y == node->pt->y)
{
//index 0 is the location of parent node
//index 1 is the location of child node
if (arr1[1]->x < node->pt->x)
{
node->lchild = malloc(sizeof(kdtree));
node->lchild->pt = arr1[1];
node->lchild->axis = !curraxis;
node->lchild->lchild = NULL;
node->lchild->rchild = NULL;
node->rchild = NULL;
}
else if (arr1[1]->x > node->pt->x)
{
node->rchild = malloc(sizeof(kdtree));
node->rchild->pt = arr1[1];
node->rchild->axis= !curraxis;
node->rchild->lchild = NULL;
node->rchild->rchild = NULL;
node->lchild = NULL;
}
else
{
if (arr1[1]->y < node->pt->y)
{
node->lchild = malloc(sizeof(kdtree));
node->lchild->pt = arr1[1];
node->lchild->axis = !curraxis;
node->lchild->lchild = NULL;
node->lchild->rchild = NULL;
node->rchild = NULL;
}
else
{
node->rchild = malloc(sizeof(kdtree));
node->rchild->pt = arr1[1];
node->rchild->axis = !curraxis;
node->rchild->lchild = NULL;
node->rchild->rchild = NULL;
node->lchild = NULL;
}
}
}
else
{
if (arr1[0]->x < node->pt->x)
{
node->lchild = malloc(sizeof(kdtree));
node->lchild->pt = arr1[0];
node->lchild->axis = !curraxis;
node->lchild->lchild = NULL;
node->lchild->rchild = NULL;
node->rchild = NULL;
}
else if (arr1[0]->x > node->pt->x)
{
node->rchild = malloc(sizeof(kdtree));
node->rchild->pt = arr1[0];
node->rchild->axis = !curraxis;
node->rchild->lchild = NULL;
node->rchild->rchild = NULL;
node->lchild = NULL;
}
else
{
if (arr1[0]->y < node->pt->y)
{
node->lchild = malloc(sizeof(kdtree));
node->lchild->pt = arr1[0];
node->lchild->axis = !curraxis;
node->lchild->lchild = NULL;
node->lchild->rchild = NULL;
node->rchild = NULL;
}
else
{
node->rchild = malloc(sizeof(kdtree));
node->rchild->pt = arr1[0];
node->rchild->axis= !curraxis;
node->rchild->lchild = NULL;
node->rchild->rchild = NULL;
node->lchild = NULL;
}
}
}
}
else
{
if(arr1[0]->x == node->pt->x && arr1[0]->y == node->pt->y)
{
if (arr1[1]->y < node->pt->y)
{
node->lchild = malloc(sizeof(kdtree));
node->lchild->pt = arr1[1];
node->lchild->axis = !curraxis;
node->lchild->lchild = NULL;
node->lchild->rchild = NULL;
node->rchild = NULL;
}
else if (arr1[1]->y > node->pt->y)
{
node->rchild = malloc(sizeof(kdtree));
node->rchild->pt = arr1[1];
node->rchild->axis = !curraxis;
node->rchild->lchild = NULL;
node->rchild->rchild = NULL;
node->lchild = NULL;
}
else
{
if (arr1[1]->x < node->pt->x)
{
node->lchild = malloc(sizeof(kdtree));
node->lchild->pt = arr1[1];
node->lchild->axis = !curraxis;
node->lchild->lchild = NULL;
node->lchild->rchild = NULL;
node->rchild = NULL;
}
else
{
node->rchild = malloc(sizeof(kdtree));
node->rchild->pt = arr1[1];
node->rchild->axis= !curraxis;
node->rchild->lchild = NULL;
node->rchild->rchild = NULL;
node->lchild = NULL;
}
}
}
else
{
if (arr1[0]->y < node->pt->y)
{
node->lchild = malloc(sizeof(kdtree));
node->lchild->pt = arr1[0];
node->lchild->axis = !curraxis;
node->lchild->lchild = NULL;
node->lchild->rchild = NULL;
node->rchild = NULL;
}
else if (arr1[0]->y > node->pt->y)
{
node->rchild = malloc(sizeof(kdtree));
node->rchild->pt = arr1[0];
node->rchild->axis = !curraxis;
node->rchild->lchild = NULL;
node->rchild->rchild = NULL;
node->lchild = NULL;
}
else
{
if (arr1[0]->x < node->pt->x)
{
node->lchild = malloc(sizeof(kdtree));
node->lchild->pt = arr1[0];
node->lchild->axis = !curraxis;
node->lchild->lchild = NULL;
node->lchild->rchild = NULL;
node->rchild = NULL;
}
else
{
node->rchild = malloc(sizeof(kdtree));
node->rchild->pt = arr1[0];
node->rchild->axis= !curraxis;
node->rchild->lchild = NULL;
node->rchild->rchild = NULL;
node->lchild = NULL;
}
}
}
}
return;
}
node->lchild = malloc(sizeof(kdtree));
node->rchild = malloc(sizeof(kdtree));
//declare the left and right arrays, where arr1 refers to the "primary" axis (that is being split)
//and arr2 is the "secondary" axis (for tiebreakers, and also what the parent node was split by)
location **larr1; location **rarr1;
location **larr2; location **rarr2;
//if this node is split along x, then the prior node was split by y, and
// thus this node is the median (index n/2) of the yarr
larr2 = malloc(sizeof(location*) * n/2);
memcpy(larr2, arr2, n/2 * sizeof(location*));
rarr2 = malloc(sizeof(location*) * (n-n/2-1));
memcpy(rarr2, arr2 + n/2 + 1, sizeof(location*) * (n-n/2-1));
larr1 = malloc(sizeof(location*) * n/2);
rarr1 = malloc(sizeof(location*) * (n-n/2-1));
int counter1 = 0;
int counter2 = 0;
if (curraxis)
{
for (int i = 0; i < n; i++)
{
if(arr1[i]->y < node->pt->y)
{
larr1[counter1] = arr1[i];
counter1++;
}
else if (arr1[i]->y > node->pt->y)
{
rarr1[counter2] = arr1[i];
counter2++;
}
else
{
if(arr1[i]->x < node->pt->x)
{
larr1[counter1] = arr1[i];
counter1++;
}
else if(arr1[i]->x > node->pt->x)
{
rarr1[counter2] = arr1[i];
counter2++;
}
}
}
node->lchild->pt = larr1[(n/2)/2];
node->lchild->axis = !curraxis;
kdtree_balanced_add(node->lchild, n/2, larr2, larr1);
node->rchild->pt = rarr1[(n-n/2-1)/2];
node->rchild->axis = !curraxis;
kdtree_balanced_add(node->rchild, (n-n/2-1), rarr2, rarr1);
}
else
{
for (int i = 0; i < n; i++)
{
if(arr1[i]->x < node->pt->x)
{
larr1[counter1] = arr1[i];
counter1++;
}
else if (arr1[i]->x > node->pt->x)
{
rarr1[counter2] = arr1[i];
counter2++;
}
else
{
if(arr1[i]->y < node->pt->y)
{
larr1[counter1] = arr1[i];
counter1++;
}
else if(arr1[i]->y > node->pt->y)
{
rarr1[counter2] = arr1[i];
counter2++;
}
}
}
node->lchild->pt = larr1[(n/2)/2];
node->lchild->axis = !curraxis;
kdtree_balanced_add(node->lchild, n/2, larr2, larr1);
node->rchild->pt = rarr1[(n-n/2-1)/2];
node->rchild->axis = !curraxis;
kdtree_balanced_add(node->rchild, (n-n/2-1), rarr2, rarr1);
}
free(larr1);
free(larr2);
free(rarr1);
free(rarr2);
}
/**
* Creates a balanced k-d tree containing copies of the points in the
* given array of locations. If the array is NULL and n is 0 then the
* returned tree is empty. If the tree could not be created then the
* returned value is NULL.
*
* @param pts an array of unique valid locations, non-NULL if n != 0
* @param n the number of points in that array, or 0 if pts is NULL
* @return a pointer to the newly created collection of points, or NULL
* if it could not be created
*/
kdtree *kdtree_create(const location *pts, int n)
{
if (pts == NULL || n==0)
{
kdtree *node = malloc(sizeof(kdtree));
node->axis = false;
node->lchild = NULL;
node->rchild = NULL;
node->pt = NULL;
return node;
}
location **ptarray = malloc(n * sizeof(location*));
for (int i = 0; i < n; i++)
{
ptarray[i] = malloc(sizeof(location));
ptarray[i]->x = pts[i].x;
ptarray[i]->y = pts[i].y;
}
location **xarray = malloc(n*sizeof(location*));
location **yarray = malloc(n*sizeof(location*));
location_merge_sort(n, ptarray, xarray, true);
for (int i = 0; i < n-1; i++)
{
if (xarray[i]->x ==xarray[i+1]->x && xarray[i]->y == xarray[i+1]->y)
{
return NULL;
}
}
location_merge_sort(n, ptarray, yarray, false);
free(ptarray);
kdtree *root = malloc(sizeof(kdtree));
root->axis = false;
root->pt = xarray[n/2];
kdtree_balanced_add(root, n, yarray, xarray);
free(xarray);
free(yarray);
return root;
}
bool kdtree_contains(const kdtree *t, const location *p);
/**
* Adds a copy of the given point to the given k-d tree. There is no
* effect if the point is already in the tree. The tree need not be
* balanced after the add. The return value is true if the point was
* added successfully and false otherwise (if the point was already in the
* tree or if there was a memory allocation error when trying to add).
*
* @param t a pointer to a valid k-d tree, non-NULL
* @param p a pointer to a valid location, non-NULL
* @return true if and only if the point was successfully added
*/
bool kdtree_add(kdtree *t, const location *p)
{
if(p == NULL)
{
return false;
}
bool contains = kdtree_contains(t,p);
if(contains)
{
return false;
}
if(t->pt==NULL)
{
t->pt = malloc(sizeof(location));
t->pt->x=p->x;
t->pt->y=p->y;
return true;
}
kdtree *currnode = t;
kdtree *prevnode;
bool leftchild;
bool curraxis = t->axis;
while(currnode!=NULL)
{
prevnode=currnode;
if(!curraxis)
{
if(p->x < currnode->pt->x)
{
currnode = currnode->lchild;
leftchild = true;
}
else if (p->x > currnode->pt->x)
{
currnode = currnode->rchild;
leftchild=false;
}
else
{
if(p->y < currnode->pt->y)
{
currnode = currnode->lchild;
leftchild=true;
}
else
{
currnode = currnode->rchild;
leftchild=false;
}
}
}
else
{
if(p->y < currnode->pt->y)
{
currnode = currnode->lchild;
leftchild=true;
}
else if (p->y > currnode->pt->y)
{
currnode = currnode->rchild;
leftchild=false;
}
else
{
if(p->x < currnode->pt->x)
{
currnode = currnode->lchild;
leftchild = true;
}
else
{
currnode = currnode->rchild;
leftchild=false;
}
}
}
curraxis=!curraxis;
}
t=malloc(sizeof(kdtree));
if(leftchild)
{
prevnode->lchild = t;
}
else
{
prevnode->rchild = t;
}
t->axis = curraxis;
t->lchild = NULL;
t->rchild=NULL;
t->pt = malloc(sizeof(location));
t->pt->x = p->x;
t->pt->y = p->y;
return true;
}
/**
* Determines if the given tree contains a point with the same coordinates
* as the given point.
*
* @param t a pointer to a valid k-d tree, non-NULL
* @param p a pointer to a valid location, non-NULL
* @return true if and only of the tree contains the location
*/
bool kdtree_contains(const kdtree *t, const location *p)
{
if(t==NULL || p==NULL || t->pt==NULL)
{
return false;
}
if (t->pt->x == p->x && t->pt->y==p->y)
{
return true;
}
kdtree *currnode = t;
while(currnode != NULL)
{
if(currnode->pt->x == p->x && currnode->pt->y == p->y)
{
return true;
}
else
{
if(!currnode->axis)
{
if (p->x < currnode->pt->x)
{
currnode=currnode->lchild;
}
else if (p->x > currnode->pt->x)
{
currnode=currnode->rchild;
}
else
{
if(p->y < currnode->pt->y)
{
currnode=currnode->lchild;
}
else
{
currnode=currnode->rchild;
}
}
}
else
{
if(p->y < currnode->pt->y)
{
currnode=currnode->lchild;
}
else if (p->y > currnode->pt->y)
{
currnode=currnode->rchild;
}
else
{
if (p->x < currnode->pt->x)
{
currnode=currnode->lchild;
}
else
{
currnode=currnode->rchild;
}
}
}
}
}
return false;
}
void kdtree_nearest_helper(kdtree *t, bool left, location *blcorner, location *trcorner, kdtree *prev,
const location *p, location *neighbor, double *d)
{
if (t == NULL || t->pt == NULL || d ==0 || p==NULL)
{
return;
}
//region check
if (!prev->axis)
{
if (left)
{
trcorner->x = prev->pt->x;
}
else
{
blcorner->x = prev->pt->x;
}
}
else
{
if (left)
{
trcorner->y = prev->pt->y;
}
else
{
blcorner->y = prev->pt->y;
}
}
if(fabs(location_distance_to_rectangle(p, blcorner, trcorner)) > *d)
{
return;
}
double currd = fabs(location_distance(p, t->pt));
if (currd < *d)
{
neighbor->x = t->pt->x;
neighbor->y = t->pt->y;
*d = currd;
}
location *blcornerL = malloc(sizeof(location));
location *trcornerL = malloc(sizeof(location));
location *blcornerR = malloc(sizeof(location));
location *trcornerR = malloc(sizeof(location));
if(!t->axis)
{
blcornerL->x = blcorner->x;
blcornerL->y = blcorner->y;
trcornerL->x = t->pt->x;
trcornerL->y = trcorner->y;
blcornerR->x = t->pt->x;
blcornerR->y = blcorner->y;
trcornerR->x = trcorner->x;
trcornerR->y = trcorner->y;
}
else
{
blcornerL->x = blcorner->x;
blcornerL->y = blcorner->y;
trcornerL->x = trcorner->x;
trcornerL->y = t->pt->y;
blcornerR->x = blcorner->x;
blcornerR->y = t->pt->y;
trcornerR->x = trcorner->x;
trcornerR->y = trcorner->y;
}
if(!t->axis)
{
if (p->x < t->pt->x)
{
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
}
else if (p->x < t->pt->x)
{
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
}
else
{
if (p->y < t->pt->y)
{
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
}
else
{
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
}
}
}
else
{
if (p->y < t->pt->y)
{
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
}
else if (p->y < t->pt->y)
{
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
}
else
{
if (p->x < t->pt->x)
{
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
}
else
{
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
}
}
}
free(blcornerL);
free(blcornerR);
free(trcornerL);
free(trcornerR);
}
/**
* Copies the nearest neighbor to the given point among points in the
* given tree to the given location. Ties are broken arbitrarily.
* There is no change to neighbor and distance is set to infinity if
* the tree is empty. If p is equal to a point in the tree then p is
* copied into neighbor and distance is set to zero.
*
* @param t a pointer to a valid k-d tree, non-NULL
* @param p a pointer to a valid location, non-NULL
* @param d a pointer to a double, non-NULL
* @param neighbor a pointer to a valid location, non-NULL
*/
void kdtree_nearest_neighbor(kdtree *t, const location *p, location *neighbor, double *d)
{
if (t == NULL || t->pt == NULL || d ==0 || p==NULL)
{
*d = INFINITY;
return;
}
if(kdtree_contains(t, p))
{
*d=0;
neighbor->x = p->x;
neighbor->y = p->y;
return;
}
*d=fabs(location_distance(t->pt, p));
neighbor->x = t->pt->x;
neighbor->y = t->pt->y;
location *blcornerL = malloc(sizeof(location));
location *trcornerL = malloc(sizeof(location));
location *blcornerR = malloc(sizeof(location));
location *trcornerR = malloc(sizeof(location));
if(!t->axis)
{
blcornerL->x = -1 * INFINITY;
blcornerL->y = -1 * INFINITY;
trcornerL->x = t->pt->x;
trcornerL->y = INFINITY;
blcornerR->x = t->pt->x;
blcornerR->y = -1 * INFINITY;
trcornerR->x = INFINITY;
trcornerR->y = INFINITY;
}
else
{
blcornerL->x = -1 * INFINITY;
blcornerL->y = -1 * INFINITY;
trcornerL->x = INFINITY;
trcornerL->y = t->pt->y;
blcornerR->x = -1*INFINITY;
blcornerR->y = t->pt->y;
trcornerR->x = INFINITY;
trcornerR->y = INFINITY;
}
if(!t->axis)
{
if (p->x < t->pt->x)
{
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
}
else if (p->x < t->pt->x)
{
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
}
else
{
if (p->y < t->pt->y)
{
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
}
else
{
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
}
}
}
else
{
if (p->y < t->pt->y)
{
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
}
else if (p->y < t->pt->y)
{
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
}
else
{
if (p->x < t->pt->x)
{
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
}
else
{
kdtree_nearest_helper(t->rchild, false, blcornerR, trcornerR, t, p, neighbor, d);
kdtree_nearest_helper(t->lchild, true, blcornerL, trcornerL, t, p, neighbor, d);
}
}
}
free(blcornerL);
free(blcornerR);
free(trcornerL);
free(trcornerR);
}
/**
* Passes the points in the given tree to the given function
* in an arbitrary order. The last argument to this function is also passed
* to the given function along with each point.
*
* @param t a pointer to a valid k-d tree, non-NULL
* @param f a pointer to a function that takes a location and an extra
* argument, and does not modify t, non-NULL
* @param arg a pointer
*/
void kdtree_for_each(const kdtree* r, void (*f)(const location *, void *), void *arg)
{
if (!(r == NULL|| r->pt == NULL))
{
kdtree_for_each(r->lchild, f, arg);
f(r->pt, arg);
kdtree_for_each(r->rchild, f, arg);
}
}
/**
* Destroys the given k-d tree. The tree is invalid after being destroyed.
*
* @param t a pointer to a valid k-d tree, non-NULL
*/
void kdtree_destroy(kdtree *t)
{
if(t != NULL)
{
if (t->lchild != NULL)
{
kdtree_destroy(t->lchild);
}
if (t->rchild != NULL)
{
kdtree_destroy(t->rchild);
}
if(t->pt != NULL)
{
free(t->pt);
}
}
free(t);
}
|
C++
|
UTF-8
| 803
| 3.625
| 4
|
[] |
no_license
|
#include <iostream>
using namespace std;
class Link
{
public:
int element;
Link *next;
Link(int elemval,Link *nextval=NULL)
{
element=elemval;
next=nextval;
}
Link(Link *nextval=NULL)
{
next=nextval;
}
};
class LStack : public Link
{
public:
Link *top;
int size;
LStrack(int sz=0)
{
top=NULL;
size=sz;
}
int pop();
bool push(int);
};
int LStack::pop()
{
if(size==0) return false;
int val=top->element;
Link *temp=top->next;
top=temp;
--size;
return val;
}
bool LStack::push(int val)
{
Link *temp=top;
top=new Link(val,temp);
++size;
return true;
}
int main()
{
LStack L;
cout<<"push(10)"<<endl;
cout<<"push(20)"<<endl;
L.push(10);
L.push(20);
cout<<"pop:"<<L.pop()<<endl;
cout<<"pop:"<<L.pop()<<endl;
}
|
Shell
|
UTF-8
| 130
| 3.171875
| 3
|
[
"LicenseRef-scancode-unknown-license-reference",
"ISC"
] |
permissive
|
#!/bin/sh
uname="/usr/bin/uname"
if [ -f "${uname}" ]; then
case `"$uname" -s` in
Darwin|"Mac OS") exit 0 ;;
esac
fi
exit 1
|
Python
|
UTF-8
| 6,970
| 3.65625
| 4
|
[] |
no_license
|
# CONVOLUTION OPERATION
# This program takes input a png image and a filter (box,gaussian,sharpen,edge)
# It applies the filter to the image and displays the output.
from PIL import Image, ImageDraw
import numpy as np
from matplotlib import pyplot as plt
import imageio
def get_image(image_path):
im = imageio.imread(img_path)
return im
def plotter(img):
plt.imshow(img)
plt.show()
def box_blur(img_path):
# this applies box blur to an image
# Load image:
input_image = Image.open(img_path)
input_pixels = input_image.load()
# Box Blur kernel
box_kernel = [[1 / 9, 1 / 9, 1 / 9],
[1 / 9, 1 / 9, 1 / 9],
[1 / 9, 1 / 9, 1 / 9]]
kernel = box_kernel
offset = len(kernel) // 2
# Create output image
output_image = Image.new("RGB", input_image.size)
draw = ImageDraw.Draw(output_image)
# Compute convolution between intensity and kernels
for x in range(offset, input_image.width - offset):
for y in range(offset, input_image.height - offset):
acc = [0, 0, 0]
for a in range(len(kernel)):
for b in range(len(kernel)):
xn = x + a - offset
yn = y + b - offset
pixel = input_pixels[xn, yn]
acc[0] += pixel[0] * kernel[a][b]
acc[1] += pixel[1] * kernel[a][b]
acc[2] += pixel[2] * kernel[a][b]
draw.point((x, y), (int(acc[0]), int(acc[1]), int(acc[2])))
output_image.save("output.png")
return output_image
def gaussian_blur(img_path):
# this applies gaussain blur to an image
# Load image:
input_image = Image.open(img_path)
input_pixels = input_image.load()
# Gaussian kernel
gaussian_kernel = [[1 / 256, 4 / 256, 6 / 256, 4 / 256, 1 / 256],
[4 / 256, 16 / 256, 24 / 256, 16 / 256, 4 / 256],
[6 / 256, 24 / 256, 36 / 256, 24 / 256, 6 / 256],
[4 / 256, 16 / 256, 24 / 256, 16 / 256, 4 / 256],
[1 / 256, 4 / 256, 6 / 256, 4 / 256, 1 / 256]]
kernel = gaussian_kernel
offset = len(kernel) // 2
# Create output image
output_image = Image.new("RGB", input_image.size)
draw = ImageDraw.Draw(output_image)
# Compute convolution between intensity and kernels
for x in range(offset, input_image.width - offset):
for y in range(offset, input_image.height - offset):
acc = [0, 0, 0]
for a in range(len(kernel)):
for b in range(len(kernel)):
xn = x + a - offset
yn = y + b - offset
pixel = input_pixels[xn, yn]
acc[0] += pixel[0] * kernel[a][b]
acc[1] += pixel[1] * kernel[a][b]
acc[2] += pixel[2] * kernel[a][b]
draw.point((x, y), (int(acc[0]), int(acc[1]), int(acc[2])))
output_image.save("output.png")
return output_image
def sharpen(img_path):
# this applies the sharpen filter to an image
# Load image:
input_image = Image.open(img_path)
input_pixels = input_image.load()
# sharpening Kernel
sharpen_kernel = [[0, -.5, 0],
[-.5, 3, -.5],
[0, -.5, 0]]
kernel = sharpen_kernel
offset = len(kernel) // 2
# Create output image
output_image = Image.new("RGB", input_image.size)
draw = ImageDraw.Draw(output_image)
# Compute convolution between intensity and kernels
for x in range(offset, input_image.width - offset):
for y in range(offset, input_image.height - offset):
acc = [0, 0, 0]
for a in range(len(kernel)):
for b in range(len(kernel)):
xn = x + a - offset
yn = y + b - offset
pixel = input_pixels[xn, yn]
acc[0] += pixel[0] * kernel[a][b]
acc[1] += pixel[1] * kernel[a][b]
acc[2] += pixel[2] * kernel[a][b]
draw.point((x, y), (int(acc[0]), int(acc[1]), int(acc[2])))
output_image.save("output.png")
return output_image
def edge_detect(img_path):
# This applies the edge detection filter to an image
# Load image:
input_image = Image.open(img_path)
input_pixels = input_image.load()
# Calculate pixel intensity as the average of red, green and blue colors.
intensity = [[sum(input_pixels[x, y]) / 3 for y in range(input_image.height)] for x in range(input_image.width)]
# edge kernels
# kernel for horizontal edges
kernelx = [[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]]
# kernel for vertical edges
kernely = [[-1, -2, -1],
[0, 0, 0],
[1, 2, 1]]
# Create output image
output_image = Image.new("RGB", input_image.size)
draw = ImageDraw.Draw(output_image)
# Compute convolution between intensity and kernels
for x in range(1, input_image.width - 1):
for y in range(1, input_image.height - 1):
magx, magy = 0, 0
for a in range(3):
for b in range(3):
xn = x + a - 1
yn = y + b - 1
magx += intensity[xn][yn] * kernelx[a][b]
magy += intensity[xn][yn] * kernely[a][b]
# Draw in black and white the magnitude
#color = int(sqrt(magx ** 2 + magy ** 2))
color = int((magx ** 2 + magy ** 2) ** 0.5)
draw.point((x, y), (color, color, color))
output_image.save("output.png")
return output_image
def apply_filter(img_path , blur_type):
# Load image:
input_image = Image.open(img_path)
input_pixels = input_image.load()
# Select kernel here:
if(blur_type == 'box'):
output = box_blur(img_path)
return output
elif(blur_type == 'gaussian'):
output = gaussian_blur(img_path)
return output
elif(blur_type == 'sharpen'):
output = sharpen(img_path)
return output
elif(blur_type == 'edge'):
output = edge_detect(img_path)
return output
else:
print("please select one of the kernels <box,gaussian> ")
if __name__ == '__main__':
# give the absolute path of the png image to the variable img_path
img_path = 'C:\\Users\\Exile\\Desktop\\Sem2\\DL\\Assignment\\car.png'
x = get_image(img_path)
print(x.shape, "x shape")
plotter(x)
# mention the type of filter you want to apply on image
# it can be 'box' , 'gaussian', 'sharpen', or 'edge'
ba = apply_filter(img_path,'box')
plotter(ba)
|
Java
|
UTF-8
| 2,812
| 3.625
| 4
|
[] |
no_license
|
package top.qiaojianyong.hanoi;
import java.util.HashMap;
import java.util.LinkedList;
public class Hanoi {
private static HashMap<Integer, LinkedList<Integer>> map = new HashMap<>(); // store holders
private static int num = 4; // dish num
private static int count = 0; // steps count
static {
LinkedList<Integer> list1 = new LinkedList<>(); // dish holder
LinkedList<Integer> list2 = new LinkedList<>();
LinkedList<Integer> list3 = new LinkedList<>();
for (int i = 1; i <= num; i++)
list1.add(i);
map.put(1, list1);
map.put(2, list2);
map.put(3, list3);
}
public static void main(String[] args) {
System.out.println();
draw();
hanoi(num, 1, 3);
//结束
for (Integer i : map.get(3))
System.out.println(" " + i);
System.out.println("\n " + "总步数 " + count);
}
private static void hanoi(Integer n, int from, int to) {
// System.out.println(from + "-->" + to + " " + n);
/*int t = from + to;
switch (t) {
case 4:
t = 2;
break;
case 3:
t = 3;
break;
case 5:
t = 1;
break;
}*/
int t = 6 / (from * to); // explicit
if (n == 1) {
map.get(to).addFirst(map.get(from).removeFirst());
System.out.println(" " + from + " _" + n + "_ -->" + to);
count++;
draw();
return;
}
//第一步 先将n-1层挪到t盘上,缓冲
hanoi(n - 1, from, t);
//第二步 将最底层的碟子移到目标盘上
map.get(to).addFirst(map.get(from).removeFirst());
System.out.println(" " + from + " _" + n + "_ -->" + to);
count++;
draw();
//最后一步,将t盘上的碟子移到目标盘上
hanoi(n - 1, t, to);
}
/**
* draw the result after every step
*/
private static void draw() {
for (int i = 0; i < num; i++) {
System.out.print(" ");
for (int j = 1; j <= 3; j++) {
int size = map.get(j).size();
int stars = 0;
if (num - i <= size) {
stars = 2 * map.get(j).get(size + i - num) - 1;
}
int spaces = (2 * num - 1 - stars) / 2;
for (int k = 1; k <= 2 * num - 1; k++) {
if (k <= spaces || k > spaces + stars)
System.out.print(" ");
else
System.out.print("█");
}
System.out.print(" ");
}
System.out.println();
}
System.out.println();
}
}
|
Java
|
UTF-8
| 5,469
| 1.953125
| 2
|
[] |
no_license
|
/**
* <copyright>
* </copyright>
*
* $Id: BlockActivityImpl.java,v 1.1 2009/12/22 06:17:22 kmyu Exp $
*/
package net.smartworks.server.engine.process.xpdl.xpdl1.impl;
import net.smartworks.server.engine.process.xpdl.xpdl1.BlockActivity;
import net.smartworks.server.engine.process.xpdl.xpdl1.Xpdl1Factory;
import org.apache.tuscany.sdo.impl.DataObjectBase;
import commonj.sdo.Type;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Block Activity</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link net.smartworks.server.engine.process.xpdl.xpdl1.impl.BlockActivityImpl#getBlockId <em>Block Id</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class BlockActivityImpl extends DataObjectBase implements BlockActivity
{
public final static int BLOCK_ID = 0;
public final static int SDO_PROPERTY_COUNT = 1;
public final static int EXTENDED_PROPERTY_COUNT = 0;
/**
* The internal feature id for the '<em><b>Block Id</b></em>' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
public final static int INTERNAL_BLOCK_ID = 0;
/**
* The number of properties for this type.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
public final static int INTERNAL_PROPERTY_COUNT = 1;
protected int internalConvertIndex(int internalIndex)
{
switch (internalIndex)
{
case INTERNAL_BLOCK_ID: return BLOCK_ID;
}
return super.internalConvertIndex(internalIndex);
}
/**
* The default value of the '{@link #getBlockId() <em>Block Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBlockId()
* @generated
* @ordered
*/
protected static final String BLOCK_ID_DEFAULT_ = null;
/**
* The cached value of the '{@link #getBlockId() <em>Block Id</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getBlockId()
* @generated
* @ordered
*/
protected String blockId = BLOCK_ID_DEFAULT_;
/**
* This is true if the Block Id attribute has been set.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
* @ordered
*/
protected boolean blockId_set_ = false;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public BlockActivityImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Type getStaticType()
{
return ((Xpdl1FactoryImpl)Xpdl1Factory.INSTANCE).getBlockActivity();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String getBlockId()
{
return blockId;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setBlockId(String newBlockId)
{
String oldBlockId = blockId;
blockId = newBlockId;
boolean oldBlockId_set_ = blockId_set_;
blockId_set_ = true;
if (isNotifying())
notify(ChangeKind.SET, INTERNAL_BLOCK_ID, oldBlockId, blockId, !oldBlockId_set_);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void unsetBlockId()
{
String oldBlockId = blockId;
boolean oldBlockId_set_ = blockId_set_;
blockId = BLOCK_ID_DEFAULT_;
blockId_set_ = false;
if (isNotifying())
notify(ChangeKind.UNSET, INTERNAL_BLOCK_ID, oldBlockId, BLOCK_ID_DEFAULT_, oldBlockId_set_);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isSetBlockId()
{
return blockId_set_;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Object get(int propertyIndex, boolean resolve)
{
switch (propertyIndex)
{
case BLOCK_ID:
return getBlockId();
}
return super.get(propertyIndex, resolve);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void set(int propertyIndex, Object newValue)
{
switch (propertyIndex)
{
case BLOCK_ID:
setBlockId((String)newValue);
return;
}
super.set(propertyIndex, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void unset(int propertyIndex)
{
switch (propertyIndex)
{
case BLOCK_ID:
unsetBlockId();
return;
}
super.unset(propertyIndex);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isSet(int propertyIndex)
{
switch (propertyIndex)
{
case BLOCK_ID:
return isSetBlockId();
}
return super.isSet(propertyIndex);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public String toString()
{
if (isProxy(this)) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (BlockId: ");
if (blockId_set_) result.append(blockId); else result.append("<unset>");
result.append(')');
return result.toString();
}
} //BlockActivityImpl
|
C++
|
UTF-8
| 162
| 2.71875
| 3
|
[] |
no_license
|
#include <iostream>
using namespace std;
int main(){
int a[3],b[3];
int i;
for(i=0;i<3;i++){
cin>>a[i]>>b[i];
}
cout<<a[0]-a[2]<<" "<<b[0]-b[1]<<endl;
}
|
Java
|
UTF-8
| 470
| 2.015625
| 2
|
[] |
no_license
|
package br.com.softdesign.votacao.exception;
import br.com.softdesign.votacao.message.MessageKey;
import lombok.Getter;
@Getter
public abstract class BaseRuntimeException extends RuntimeException {
private static final long serialVersionUID = -8962469694754031642L;
private final MessageKey messageKey;
private final Object[] args;
public BaseRuntimeException(MessageKey messageKey, Object ...args) {
this.messageKey = messageKey;
this.args = args;
}
}
|
Python
|
UTF-8
| 550
| 3.171875
| 3
|
[] |
no_license
|
if __name__ == "__main__":
num = int(input().strip())
dirt = [int(i) for i in input().strip().split()]
dirt_ctr = 0
clean_ctr = 0
has_dirt = 0
for i in range(1,366):
if dirt_ctr >= 20:
dirt_ctr = 0
clean_ctr += 1
has_dirt = False
#print(i)
if i in dirt:
has_dirt += 1
if has_dirt:
dirt_ctr += has_dirt
if has_dirt:
clean_ctr += 1
print(clean_ctr)
|
JavaScript
|
UTF-8
| 575
| 3.90625
| 4
|
[] |
no_license
|
/**
* 별 찍기 - 1
문제
첫째 줄에는 별 1개, 둘째 줄에는 별 2개, N번째 줄에는 별 N개를 찍는 문제
입력
첫째 줄에 N(1 ≤ N ≤ 100)이 주어진다.
출력
첫째 줄부터 N번째 줄까지 차례대로 별을 출력한다.
예제 입력 1
5
예제 출력 1
*
**
***
****
*****
*/
let input = +require('fs').readFileSync('./dev/stdin').toString();
let answer = "";
for (let ix = 1; ix <= input; ix++) {
answer = "";
for (let iy = 0; iy < ix; iy++) {
answer += "*";
}
console.log(answer);
}
|
C
|
UTF-8
| 1,986
| 2.75
| 3
|
[] |
no_license
|
#ifndef MATRIXEDCPP_DEFINES_H
#define MATRIXEDCPP_DEFINES_H
// ================= Global error codes ================= //
/**
* Thrown when a memory-linked error occured
*
* @example Malloc fail
*/
#define MATRIX_EXCEPTION_MEMORY_ERROR 0
/**
* Thrown when a file is not readable bu the program or does not exist
*/
#define MATRIX_EXCEPTION_NO_SUCH_FILE 1
/**
* Thrown when an arithmetic error occurred
*
* @example Division by zero, number overflow
*/
#define MATRIX_EXCEPTION_INCONSISTENT_ARITHMETIC 6
/**
* Thrown when an operation between several matrices is impossible because of their incompatible dimensions
*
* @example Incompatible dimensions during multiplication / addition of two matrices
*/
#define MATRIX_EXCEPTION_INCONSISTENT_DIMENSIONS 7
/**
* Thrown when the program parameters provided by the user are invalid
*
* @example Not enough / too much parameters
*/
#define MATRIX_EXCEPTION_INVALID_PROGRAM_PARAMETERS 8
// ================= Deserialization error codes ================= //
/**
* Thrown when a provided type for a matrix during deserialization is unsupported
*
* @important Only the double type will not throw this exception at the time
*/
#define MATRIX_EXCEPTION_DESERIALIZATION_UNSUPPORTED_TYPE 2
/**
* Thrown when the deserialization detected a syntax error
*
* @example The file is incomplete, a line is wrong
*/
#define MATRIX_EXCEPTION_DESERIALIZATION_WRONG_FILE_FORMAT 3
/**
* Thrown when the amount of lines declared / detected is not valid during deserialization
*
* @example The file said that there were 3 lines but the file also declared 4 lines
*/
#define MATRIX_EXCEPTION_DESERIALIZATION_INCONSISTENT_LINE_AMOUNT 4
/**
* Thrown when the amount of columns declared / detected is not valid during deserialization
*
* @example The file said that there were 3 columns but the file also declared 4 columns
*/
#define MATRIX_EXCEPTION_DESERIALIZATION_INCONSISTENT_COLUMN_AMOUNT 5
#endif //MATRIXEDCPP_DEFINES_H
|
Java
|
UTF-8
| 437
| 2.796875
| 3
|
[] |
no_license
|
package designmode.structure.decorator.house;
/**
* 测试粘钩装饰器模式
* 主要是新增了功能
*
* @author Defu Li
* @since 2021/7/26 8:30
*/
public class Main {
public static void main(String[] args) {
IHouse house = new House();
house.live();
IStickyHookHouse stickyHookHouse = new StickyHookDecorator(house);
stickyHookHouse.live();
stickyHookHouse.hangThings();
}
}
|
Java
|
UTF-8
| 1,906
| 3.328125
| 3
|
[] |
no_license
|
package P51_P100;
import java.util.ArrayList;
public class P80_unique_binary_search_trees_II {
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; left = null; right = null; }
}
public ArrayList<TreeNode> generateTrees(int n) {
ArrayList<TreeNode> result = new ArrayList<TreeNode>();
result = generateHelper(1,n);
return result;
}
public ArrayList<TreeNode> generateHelper(int start,int end) {
ArrayList<TreeNode> result = new ArrayList<TreeNode>();
if (start>end){
return result;
}
for(int i =start;i<=end;i++){
ArrayList<TreeNode> lResult = generateHelper(start,i-1);
ArrayList<TreeNode> rResult = generateHelper(i+1,end);
if (lResult.size()==0&&rResult.size()==0) {
TreeNode root = new TreeNode(i);
result.add(root);
}
else if (lResult.size()==0){
for(int j = 0;j<rResult.size();j++){
TreeNode root = new TreeNode(i);
root.right = rResult.get(j);
result.add(root);
}
}
else if (rResult.size()==0){
for(int j = 0;j<lResult.size();j++){
TreeNode root = new TreeNode(i);
root.left = lResult.get(j);
result.add(root);
}
}
else {
for (int j = 0;j<lResult.size();j++){
for (int k = 0;k<rResult.size();k++) {
TreeNode root = new TreeNode(i);
root.left = lResult.get(j);
root.right = rResult.get(k);
result.add(root);
}
}
}
}
return result;
}
}
|
Swift
|
UTF-8
| 1,163
| 2.578125
| 3
|
[] |
no_license
|
//
// DayTableViewCell.swift
// HolidayPlanner
//
// Created by Rory Prior on 13/03/2019.
// Copyright © 2019 ThinkMac Software. All rights reserved.
//
import UIKit
class DayTableViewCell: UITableViewCell {
@IBOutlet var dayLabel : UILabel!
@IBOutlet var monthLabel : UILabel!
@IBOutlet var weatherIcon : UIImageView!
@IBOutlet var weatherLabel : UILabel!
@IBOutlet var highTempLabel : UILabel!
@IBOutlet var lowTempLabel : UILabel!
var dayViewModel : DayViewModel?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func updateUI() {
guard dayViewModel != nil else {
return
}
dayLabel.text = dayViewModel?.dayOfMonth()
monthLabel.text = dayViewModel?.monthName()
weatherIcon.image = dayViewModel?.weatherIcon()
highTempLabel.text = dayViewModel?.highTemp()
lowTempLabel.text = dayViewModel?.lowTemp()
weatherLabel.text = dayViewModel?.weatherDescription()
}
}
|
Python
|
UTF-8
| 3,053
| 2.640625
| 3
|
[
"Unlicense"
] |
permissive
|
"""Test which require arcpy to be installed.
"""
from os.path import join
import json
import re
import unittest
try:
import arcpy
except ImportError:
arcpy = None
else:
from wsdottraffic.gp import __main__
class TestGeoprocessingFunctions(unittest.TestCase):
"""Test case for testing functions that depend on arcpy.
These will be skipped if arcpy is not available on the
current system.
"""
def skip_if_no_arcpy(self):
"""Skips the current test if arcpy is not available.
"""
if not arcpy:
self.skipTest("arcpy is not installed.")
def test_tables(self):
self.skip_if_no_arcpy()
# Create the file geodatabase
gdb_name = arcpy.CreateScratchName(
"Traffic", ".gdb", "File Geodatabase", ".")
try:
__main__.create_gdb(gdb_name, templates_gdb="Templates.gdb")
# Import the table definition schema from JSON file
schemas = None
with open("wsdottraffic/gp/tabledefs.json") as json_file:
schemas = json.load(json_file)
def get_field_names_from_schema(table_prop_dict):
"""Generator function that iterates through the expected field names.
"""
# Setup regex to match names we want to skip.
# Latitude and Longitude fields were converted
# into point geometry so are not included in the
# feature classes.
fields_to_skip_re = re.compile(
r"(?:(?:Latitude)|(?:Longitude))", re.IGNORECASE)
# Fail if the dictionary doesn't contain "fields" key.
if not "fields" in table_prop_dict:
raise KeyError("Expected 'fields' key in %s" %
table_prop_dict)
for name, data in table_prop_dict["fields"].items():
if not isinstance(data, str) and "field_name" in data:
out_name = data["field_name"]
else:
out_name = name
if not fields_to_skip_re.search(out_name):
yield out_name
for table_name, schema_table_props in schemas.items():
table_path = join(gdb_name, table_name)
self.assertTrue(arcpy.Exists(table_path),
"'%s' must exist." % table_path)
# Get list of field names in the current GIS table.
fields = list(map(lambda field: field.name,
arcpy.ListFields(table_path)))
for expected_name in get_field_names_from_schema(schema_table_props):
self.assertIn(expected_name, fields, "%s should include a field named %s." % (
table_name, expected_name))
finally:
if arcpy.Exists(gdb_name):
arcpy.management.Delete(gdb_name)
if __name__ == '__main__':
unittest.main()
|
Markdown
|
UTF-8
| 855
| 3.09375
| 3
|
[] |
no_license
|
# Anomaly-Detection-and-Recommender-Systems
## Anomaly Detection
Anomalies are outliers exhibiting different behaviour when compared to other data examples. So if we can successfully identify the outliers we can identify the anomalies.
Dataset consist of datacenter server data, Always visualize the data to identify the pattern, which will help us comming up with the algorithm that best suits for data.
After implementing gaussian distribution algorithm, outliers in the datasets are shown below:

## Recommender Systems
Algorithm used: collaborative filtering
Collaborative filtering takes into account the movies users has rated and predicts the rating for other movies, based on the results recommends the highest rated movies.
|
C++
|
UTF-8
| 1,125
| 3.125
| 3
|
[] |
no_license
|
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> res;
if (matrix.empty()) {
return res;
}
int rowBegin = 0,rowEnd=matrix.size()-1,colBegin=0,colEnd = matrix[0].size()-1;
while(rowBegin<=rowEnd && colBegin<=colEnd)
{
for(int i=colBegin;i<=colEnd;i++)
{
res.push_back(matrix[rowBegin][i]);
}
rowBegin++;
for(int i=rowBegin;i<=rowEnd;i++)
{
res.push_back(matrix[i][colEnd]);
}
colEnd--;
if(rowBegin<=rowEnd && colBegin<=colEnd)
{
for(int i=colEnd;i>=colBegin;i--)
{
res.push_back(matrix[rowEnd][i]);
}
rowEnd--;
for(int i=rowEnd;i>=rowBegin;i--)
{
res.push_back(matrix[i][colBegin]);
}
colBegin++;
}
}
return res;
}
};
|
Java
|
UTF-8
| 826
| 3.453125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.kdyzm.thread.thread030105;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
/**
* CountDownLatch的简单使用
*
* @author t_zhengrj
*
*/
public class CountDownLatchDemo implements Runnable {
private static final CountDownLatch end = new CountDownLatch(10);
@Override
public void run() {
try {
Thread.sleep(new Random().nextInt(10) * 100);
System.out.println(Thread.currentThread().getName() + " 准备完毕!");
end.countDown();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
CountDownLatchDemo demo = new CountDownLatchDemo();
for (int i = 0; i < 10; i++) {
new Thread(demo).start();
}
end.await();
System.out.println("fire");
}
}
|
SQL
|
UTF-8
| 298
| 2.625
| 3
|
[] |
no_license
|
/*
* sql surrounding auth_tokens table:
* - create table syntax
*/
create table auth_tokens (
id serial not null,
created_at timestamp default current_timestamp,
expires_at timestamp default current_timestamp + interval '10 days',
user_id integer,
auth_token char(32)
);
|
Java
|
UTF-8
| 9,572
| 2.28125
| 2
|
[] |
no_license
|
package Vista;
import Controlador.Control;
public class VentanaNumeros extends javax.swing.JFrame implements InterfazNumeros {
public VentanaNumeros() {
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
btn1D = new javax.swing.JButton();
btn5D = new javax.swing.JButton();
btn10D = new javax.swing.JButton();
btn20D = new javax.swing.JButton();
btn50D = new javax.swing.JButton();
btn100D = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
btn1C = new javax.swing.JButton();
btn5C = new javax.swing.JButton();
btn10C = new javax.swing.JButton();
btn25C = new javax.swing.JButton();
btn50C = new javax.swing.JButton();
btn100C = new javax.swing.JButton();
btnMostrar = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel1.setText("Billetes");
btn1D.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btn1D.setText("1$");
btn5D.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btn5D.setText("5$");
btn10D.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btn10D.setText("10$");
btn20D.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btn20D.setText("20$");
btn50D.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btn50D.setText("50$");
btn100D.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btn100D.setText("100$");
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
jLabel2.setText("Monedas");
btn1C.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btn1C.setText("1c");
btn5C.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btn5C.setText("5c");
btn10C.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btn10C.setText("10c");
btn25C.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btn25C.setText("25c");
btn50C.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btn50C.setText("50c");
btn100C.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
btn100C.setText("1D");
btnMostrar.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
btnMostrar.setText("Mostrar Cantidad");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(btn1D)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn5D)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn10D)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn20D)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn50D)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn100D))
.addGroup(layout.createSequentialGroup()
.addGap(146, 146, 146)
.addComponent(jLabel1))
.addGroup(layout.createSequentialGroup()
.addGap(139, 139, 139)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(btn1C)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn5C)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btn10C)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btn25C)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btn50C)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btn100C))
.addGroup(layout.createSequentialGroup()
.addGap(96, 96, 96)
.addComponent(btnMostrar)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn1D, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn5D, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn10D, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn20D, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn50D, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn100D, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btn1C, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn5C, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn10C, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn25C, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn50C, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btn100C, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(btnMostrar, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btn100C;
private javax.swing.JButton btn100D;
private javax.swing.JButton btn10C;
private javax.swing.JButton btn10D;
private javax.swing.JButton btn1C;
private javax.swing.JButton btn1D;
private javax.swing.JButton btn20D;
private javax.swing.JButton btn25C;
private javax.swing.JButton btn50C;
private javax.swing.JButton btn50D;
private javax.swing.JButton btn5C;
private javax.swing.JButton btn5D;
private javax.swing.JButton btnMostrar;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
// End of variables declaration//GEN-END:variables
@Override
public void setControlador(Control c) {
this.btn1D.addActionListener(c);
this.btn5D.addActionListener(c);
this.btn10D.addActionListener(c);
this.btn20D.addActionListener(c);
this.btn50D.addActionListener(c);
this.btn100D.addActionListener(c);
this.btn1C.addActionListener(c);
this.btn5C.addActionListener(c);
this.btn10C.addActionListener(c);
this.btn25C.addActionListener(c);
this.btn50C.addActionListener(c);
this.btn100C.addActionListener(c);
this.btnMostrar.addActionListener(c);
}
@Override
public void inicializar() {
initComponents();
setLocationRelativeTo(null);// centra la ventana en la pantalla
setVisible(true);
}
@Override
public void visualizar() {
setVisible(true);
}
@Override
public void esconder() {
setVisible(false);
}
}
|
Java
|
UTF-8
| 399
| 2.40625
| 2
|
[] |
no_license
|
package com.joe.nfortics;
public class OperationResult {
private String error = "";
private boolean successful = true;
public OperationResult(String error, boolean successful) {
this.error = error;
this.successful = successful;
}
public String getError() {
return error;
}
public boolean isSuccessful() {
return successful;
}
}
|
C
|
UTF-8
| 322
| 3.84375
| 4
|
[] |
no_license
|
#include "holberton.h"
/**
* print_alphabet_x10 - main function.
* Description: This program prints 10 times the alphabet, in lowercase.
*
* Return: none.
*/
void print_alphabet_x10(void)
{
int n;
char i;
for (n = 0; n <= 9; n++)
{
for (i = 'a'; i <= 'z'; i++)
{
_putchar(i);
}
_putchar('\n');
}
}
|
PHP
|
UTF-8
| 4,156
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace Cmmarslender\PostIterator;
use Cmmarslender\Timer\Timer;
abstract class PostIterator {
/*
* Query Related Variables
*/
public $post_type;
public $post_status;
public $offset;
public $limit;
public $orderby;
public $order;
/**
* @var \Cmmarslender\Timer\Timer
*/
public $timer;
/*
* State Related Variables
*/
/**
* Tracks if we've set the iterator up yet (Count posts, setup timer, etc)
*
* @var bool
*/
public $is_setup = false;
/**
* Total number of posts found that match the constraints, NOT including limits and offsets
*
* @see count_posts();
*
* @var int
*/
public $total_posts;
/**
* The original post object. Used to check if anything has changed, and call update_post
*
* @var \WP_Post
*/
public $original_post_object;
/**
* Post object we're currently working with. Modify this object directly.
*
* @var \WP_Post
*/
public $current_post_object;
public function __construct( $args = array() ) {
$defaults = array(
'post_type' => 'post',
'post_status' => 'publish',
'per_page' => 100,
'page' => 1,
'limit' => -1,
'orderby' => 'post_date',
'order' => 'DESC',
);
foreach( $defaults as $key => $value ) {
$this->{$key} = isset( $args[ $key ] ) ? $args[ $key ] : $value;
}
$this->timer = new Timer();
}
public function setup() {
if ( false === $this->is_setup ) {
$this->count_posts();
$this->timer->set_total_items( $this->total_posts );
$this->is_setup = true;
}
}
public function go() {
$this->timer->start();
while( $this->have_pages() ) {
$this->process_page();
Utils::stop_the_insanity();
}
}
/**
* Indicates if we have posts to process
*/
public function have_pages() {
$this->setup();
$offset = $this->get_query_offset();
return (bool) ( $offset < $this->total_posts );
}
public function process_page() {
global $wpdb;
// Just in case someone doesn't call have_pages() first
$this->setup();
$results = $wpdb->get_results( $this->get_query() );
$post_ids = wp_list_pluck( $results, 'ID' );
foreach ( $post_ids as $post_id ) {
$this->timer->tick();
// @todo add logging / status
$post = get_post( $post_id );
$this->original_post_object = clone $post;
$this->current_post_object = $post;
$this->process_post();
$this->update_post();
}
$this->page++;
}
/**
* Counts the total number of posts that match the restrictions, not including pagination.
*/
protected function count_posts() {
global $wpdb;
$query = $this->get_count_query();
$this->total_posts = $wpdb->get_var( $query );
}
protected function get_count_query_base() {
global $wpdb;
return "SELECT count(ID) FROM {$wpdb->posts}";
}
protected function get_query_base() {
global $wpdb;
return "SELECT ID FROM {$wpdb->posts}";
}
protected function get_where() {
global $wpdb;
$where = $wpdb->prepare( "WHERE post_type=%s", $this->post_type );
if ( 'any' != $this->post_status ) {
$where .= $wpdb->prepare( " AND post_status=%s", $this->post_status );
}
return $where;
}
protected function get_orderby() {
global $wpdb;
$orderby = sprintf( "ORDER BY %s %s", $wpdb->_real_escape( $this->orderby ), $wpdb->_real_escape( $this->order ) );
return $orderby;
}
protected function get_query_offset() {
$offset = ( $this->page - 1 ) * $this->per_page;
return $offset;
}
protected function get_limit() {
$limit = sprintf( "LIMIT %d,%d", $this->get_query_offset(), $this->per_page );
return $limit;
}
protected function get_count_query() {
$query = implode( " ", array( $this->get_count_query_base(), $this->get_where() ) );
return $query;
}
protected function get_query() {
$query = implode( " ", array( $this->get_query_base(), $this->get_where(), $this->get_orderby(), $this->get_limit() ) );
return $query;
}
abstract function process_post();
public function update_post() {
if ( $this->original_post_object != $this->current_post_object ) {
wp_update_post( $this->current_post_object );
Logger::log( "Updated post ID {$this->current_post_object->ID}" );
}
}
}
|
Python
|
UTF-8
| 580
| 3
| 3
|
[] |
no_license
|
from __future__ import print_function
from pprint import pprint
import config
import layout
import sorter
if __name__ == "__main__":
words = config.words
words = sorter.geneticSorter(words, numGen=25, popSize=500, selectSize=10)
print(words)
grid = layout.createLayout(words)
for word in words:
print(grid.illuminateWord(word))
print("*** LAYOUT ***")
print("")
print(grid)
print('*** WORDS AND LED NUMBER ***')
print("")
pprint(grid.getWordsAndLedNumbers(words))
print(str(len(words)) + " words packed")
|
SQL
|
UTF-8
| 240
| 4
| 4
|
[] |
no_license
|
select e.emp_no, max(s.salary) AS salary, e.last_name, e.first_name
from employees AS e inner join salaries AS s on e.emp_no=s.emp_no
where to_date='9999-01-01'and salary not in
(select max (salary) from salaries where to_date='9999-01-01')
|
JavaScript
|
UTF-8
| 2,356
| 3
| 3
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
var horoscopeArray = [
{
sign: "Aries",
personality: "Your gifts include courage and being independent.",
image: "img/signPictures/Aries.jpg"
},
{
sign:"Taurus",
personality: "You are easy going but will fight for what you want.",
image: "img/signPictures/Taurus.jpg"
},
{
sign:"Gemini",
personality: "You have the gift of gab and know where you want to go in life.",
image: "img/signPictures/Gemini.jpg"
},
{
sign:"Cancer",
personality: "Security and adventure are your top priorities.",
image: "img/signPictures/Cancer.png"
},
{
sign: "Leo",
personality: "You have high self esteem and are very devoted.",
image: "img/signPictures/Leo.png"
},
{
sign: "Virgo",
personality: "Self improvement and reflective thought are your strong suits.",
image: "img/signPictures/Virgo.png"
},
{
sign: "Libra",
personality: "You are diplomatic and you can appreciate the finer things in life.",
image: "img/signPictures/Libra.jpeg"
},
{
sign:"Scorpio",
personality: "Kindness and loyalty are among your best virtues.",
image: "img/signPictures/Scorpio.jpg"
},
{
sign: "Sagittarius",
personality: "You are vibrant and you always keep a positive outlook.",
image: "img/signPictures/Sagittarius.jpg"
},
{
sign: "Capricorn",
personality: "You are ambitious and you have an active mind.",
image: "img/signPictures/Capricorn.jpg"
},
{
sign: "Aquarius",
personality: "You take advantage of every opportunity that comes your way.",
image: "img/signPictures/Aquarius.png"
},
{
sign: "Pisces",
personality: "You are deeply sensitive and also a dreamer.",
image: "img/signPictures/Pisces.png"
}
];
console.log(horoscopeArray)
function allHoroscopes(){
var mySelect = document.getElementById("mySelection").value;
for (i = 0; i<horoscopeArray.length; i++){
console.log(horoscopeArray[i].sign, mySelect)
if (mySelect==horoscopeArray[i].sign){
console.log(true)
document.getElementById("yourSign").innerText=horoscopeArray[i].sign;
document.getElementById("personality").innerText=horoscopeArray[i].personality;
document.getElementById("icon").src=horoscopeArray[i].image
return
}else if (mySelect!==horoscopeArray[i].sign){
document.getElementById("yourSign").innerText=" Please Select Your Birthday";
document.getElementById("personality").innerText="";
document.getElementById("icon").src="img/astrology.jpg"
}
}
}
|
Python
|
UTF-8
| 85
| 3.28125
| 3
|
[] |
no_license
|
num = int(input("find even : "))
for i in range(num):
if i%2==0:
print(i)
|
Shell
|
UTF-8
| 1,566
| 3.859375
| 4
|
[] |
no_license
|
#!/bin/bash
workingDir=$HOME/listtask
currentDate=`date +%Y'-'%m'-'%d`
lastDate=`ls "$HOME" | grep "^Backup-" | sed "s/^Backup-//" | sort -r | head -n 1`
#Проверка на то, что католог существует
if ! [ -e $workingDir ]
then
echo "No target directory to make backup"
exit 1
fi
#Проверяет когда был последний бэкап и определяет папку в которую производим бэкап
if [ "$lastDate" == "" ]
then
echo "No backup found"
exit 1
fi
backupDir="$HOME/Backup-$lastDate"
#filesInCurrentDir содержит имена всех файлов и папок в $workingDir, кроме '.' и '..'
filesInCurrentDir=()
#Из listOfMainFiles в цикле исключаются все версионные сохранения
listOfMainFiles=`ls -a "$backupDir" | grep -E -v "^\.\.?$"`
IFS=$'\n' read -r -d '' -a filesInCurrentDir < <( echo "$listOfMainFiles" && printf '\0' )
for i in ${filesInCurrentDir[*]}
do
listOfMainFiles=`echo "$listOfMainFiles" | grep -v "^$i\."`
done
unset filesInCurrentDir
#Очищает рабочую папку
IFS=$'\n' read -r -d '' -a filesInCurrentDir < <( ls -a "$workingDir" | grep -E -v "^\.\.?$" && printf '\0' )
for i in ${filesInCurrentDir[*]}
do
rm -r "$workingDir/$i"
done
unset filesInCurrentDir
#Копируем оригинальные файлы
IFS=$'\n' read -r -d '' -a filesInCurrentDir < <( echo "$listOfMainFiles" && printf '\0' )
for i in ${filesInCurrentDir[*]}
do
cp -r "$backupDir/$i" "$workingDir/$i"
done
|
Java
|
UTF-8
| 940
| 2.03125
| 2
|
[] |
no_license
|
package org.marsatg.poseidonconsumer;
import org.marsatg.annotation.EnableNettyClient;
import org.marsatg.annotation.EnableHttpClient;
import org.marsatg.annotation.EnableWebManage;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@SpringBootApplication
@EnableNettyClient()
@EnableWebManage(countCallServer = true,countClientCall = true)
public class PoseidonConsumerApplication {
static ExecutorService service = Executors.newCachedThreadPool();
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(PoseidonConsumerApplication.class, args);
/*Object bean = run.getBean("testClient1");
System.out.println(bean);*/
}
}
|
Markdown
|
UTF-8
| 2,772
| 3.21875
| 3
|
[
"MIT"
] |
permissive
|
---
layout: page
title: Heuristic Evaluation
---
## Table
Heuristic Broken | Description | Severity
---------------- | ----------- | ----------
Control & Freedom | User cannot go back to previous screens | 2
Visibility | Once a gallery is selected, the artworks are not highlighted | 1
Control & Freedom | Cannot exit app after opening | 4
Help | No explanation of what "random" means as opposed to "search" | 3
Flexibility & Efficiency | Can't switch between galleries | 4
Flexbility & Efficiency | Can't go back when selecting gallery | 3
Control & Freedom | Can't pan/zoom piece | 1
## Evaluation 1:
#### Conducted by: Daniel and Spencer
#### Facilitated by: Steve


## Evaluation 2:
#### Conducted by: Javi
#### Facilitated by: Linda and Julia

## Revisions
#### 1) Back buttons
One of the main issues that was identified during the evaluations was the option to navigate backwards to previous screens, going back to select different galleries, or switching between galleries. We made revisions of this below. The lack of these buttons made it difficult to provide flexibility to the user if they made a mistake or changed their mind. In addition, this prevented them from exploring the app in its entirety.

#### 2) Highlight selected piece
Another revision we made we made was highlighting the piece in the gallery that user wants to interact with. This wasn't something we'd thought about, but think it can be useful in indicating to the user what they selected and can serve as feedback to user that the app is working.

#### 3) Help
We made changes to provide help to the users if they weren't sure what the app was supposed to do. To provide help, we included a question mark button, which would direct the user to a new screen that provides more information.

#### 4) Pan & Zoom
We included a pan and zoom option when the user wants to learn more about a piece of artwork. In this picture, the new piece is supposed to show a zoomed in version of one of the art pieces

#### 5) Keyboard
We overlooked that we needed a keyboard in our prototype for when the user wants to search for a gallery

#### 6) Exit
We included the ability to exit the app.

## Overview
This is the pieces of our revised prototype, which includes the revisions we made.

|
Shell
|
UTF-8
| 238
| 3.140625
| 3
|
[
"ISC"
] |
permissive
|
#!/bin/bash
set -e
if [ ! -f "scripts/path.sh" ]
then
echo "Error: does not look like a root of Dancy source tree" 1>&2
exit 1
fi
export DANCY_ROOT=`pwd`
export PATH="$DANCY_ROOT/bin:$DANCY_ROOT/external/bin:$PATH"
echo "$PATH"
|
TypeScript
|
UTF-8
| 2,262
| 2.6875
| 3
|
[] |
no_license
|
//-------------------------------------------------
// Dependencies
//-------------------------------------------------
import * as mongoose from 'mongoose';
import {kebabCaseRegex} from '../../utils/regular-expressions';
//-------------------------------------------------
// Schema
//-------------------------------------------------
const schema = new mongoose.Schema({
_id: {
type: String,
required: true,
immutable: true, // prevents this from being updated
maxlength: [48, 'Permanent host id is too long'],
validate: {
validator: (value): boolean => {
return kebabCaseRegex.test(value);
},
message: (props): string => {
return `Permanent host id must be kebab case. ${props.value} is not.`;
}
}
},
label: {
type: String,
required: true,
maxlength: [44, 'Permanent host label is too long']
},
description: {
type: String,
maxlength: [1000, 'Permanent host description is too long'],
default: ''
},
static: {
type: Boolean,
default: false // as I imagine most are able to be moved around.
},
updateLocationWithSensor: String, // so platforms can inherit this when generated
passLocationToObservations: {
type: Boolean,
default: true
},
registrationKey: {
type: String,
required: true,
validate: {
validator: (value): boolean => {
return value.length === 10;
},
message: (props): string => {
return `Permanent host registration key must be 10 characters long.`;
}
}
},
registeredAs: {
type: String, // the platform ID initialised from this permamentHost and to which the sensors are currently hosted by.
},
// for soft deletes
deletedAt: {
type: Date
}
}, {
timestamps: true // automatically adds createdAt and updatedAt fields
});
//-------------------------------------------------
// Indexes
//-------------------------------------------------
schema.index({registrationKey: 1}, {unique: true});
schema.index({_id: 'text', label: 'text'});
//-------------------------------------------------
// Create Model (and expose it to our app)
//-------------------------------------------------
export default mongoose.model('PermanentHost', schema);
|
Python
|
UTF-8
| 269
| 3.28125
| 3
|
[] |
no_license
|
# coding: utf-8
# In[3]:
l= [ ['Ali', 'Male'], ['Maha', 'Female'], ['Laith','Male'], ['Lamiaa', 'Female'], ['Zainab', 'Female'], ['Lena','Female'], ['Hanan', 'Female'] ]
n=raw_input('enter name')
for i in l:
if n==i[0]:
print i[1]
# In[ ]:
|
Java
|
UTF-8
| 662
| 2.6875
| 3
|
[] |
no_license
|
import javax.swing.*;
public class PolishForeign extends LearningMode{
JLabel label;
public PolishForeign(TypeOfLearning tol)
{
super(tol);
this.panel = new JPanel();
label = new JLabel(getQuestion());
this.panel.add(label);
}
@Override
public String getCorrectAnswer()
{
return super.getQuestion();
}
@Override
public String getQuestion()
{
return super.getCorrectAnswer();
}
@Override
protected JPanel getQuestionPanel()
{
return this.panel;
}
@Override
public String toString()
{
return "polski-obcy";
}
@Override
public void SetWord(Word word)
{
super.SetWord(word);
label.setText(getQuestion());
}
}
|
Java
|
UTF-8
| 1,007
| 1.710938
| 2
|
[] |
no_license
|
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.geocities.com/kpdus/jad.html
// Decompiler options: braces fieldsfirst space lnc
package com.wsi.android.framework.wxdata.controller.helpers;
import com.wsi.android.framework.wxdata.geodata.helpers.GeoDataType;
import com.wsi.android.framework.wxdata.geodata.items.ww.WatchWarningBoxCollection;
import java.util.List;
public interface GeoDataUpdateListener
{
public abstract void onGeoDataTypeDisabled(GeoDataType geodatatype);
public abstract void onGeoDataUpdateFailed(GeoDataType geodatatype);
public abstract void onPreGeoDataUpdate(GeoDataType geodatatype);
public abstract void onUpdateEarthquakes(List list);
public abstract void onUpdateHurricanes(List list);
public abstract void onUpdateStormCells(List list);
public abstract void onUpdateTrafficIncidents(List list);
public abstract void onUpdateWatchWarningBoxes(WatchWarningBoxCollection watchwarningboxcollection);
}
|
Java
|
UTF-8
| 3,917
| 2.46875
| 2
|
[] |
no_license
|
package com.example.ulanganpwpbsqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class DataHelper extends SQLiteOpenHelper {
private static final int DB_VERSION = 5;
private static final String DATABASE_NAME = "db_perpustakaans";
private static final String TABLE_NAME = "data_buku";
private static final String KEY_ID = "id";
private static final String KEY_NAMA_BUKU = "nama_buku";
private static final String KEY_PENGARANG = "pengarang";
private static final String KEY_PENERBIT = "penerbit";
public DataHelper(Context context){
super(context, DATABASE_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
String createDataBuku = "CREATE TABLE "+TABLE_NAME+"("+KEY_ID+" INTEGER PRIMARY KEY,"+KEY_NAMA_BUKU+" TEXT,"+KEY_PENGARANG+" TEXT,"+KEY_PENERBIT+" TEXT"+")";
sqLiteDatabase.execSQL(createDataBuku);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
String sql = ("DROP TABLE IF EXISTS " +TABLE_NAME);
sqLiteDatabase.execSQL(sql);
onCreate(sqLiteDatabase);
}
public ArrayList<DataBuku> listDataBuku(){
String sql = "select * from " + TABLE_NAME;
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<DataBuku> storeData = new ArrayList<>();
Cursor cursor = db.rawQuery(sql, null);
if (cursor.moveToFirst()){
do {
int id = Integer.parseInt(cursor.getString(0));
String nama_buku = cursor.getString(1);
String penulis = cursor.getString(2);
String penerbit = cursor.getString(3);
storeData.add(new DataBuku(id, nama_buku, penulis, penerbit));
}
while (cursor.moveToNext());
}
cursor.close();
return storeData;
}
public void insert(DataBuku dataBuku){
ContentValues values = new ContentValues();
values.put(KEY_ID, dataBuku.id);
values.put(KEY_NAMA_BUKU, dataBuku.nama_buku);
values.put(KEY_PENGARANG, dataBuku.pengarang);
values.put(KEY_PENERBIT, dataBuku.penerbit);
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_NAME, null, values);
}
public void delete (int id){
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_NAME, KEY_ID + " = ?", new String[]{String.valueOf(id)});
}
public void update(DataBuku dataBuku){
ContentValues values = new ContentValues();
values.put(KEY_NAMA_BUKU, dataBuku.getNama_buku());
values.put(KEY_PENGARANG, dataBuku.getPengarang());
values.put(KEY_PENERBIT, dataBuku.getPenerbit());
SQLiteDatabase db = this.getWritableDatabase();
db.update(TABLE_NAME,values,KEY_ID + " = ?",new String[] {String.valueOf(dataBuku.getId())});
}
public DataBuku findBuku(String name){
String query = "Select * FROM " + TABLE_NAME + " WHERE " + KEY_NAMA_BUKU + " = " + "nama_buku";
SQLiteDatabase db = this.getWritableDatabase();
DataBuku dataBuku = null;
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()){
int id = Integer.parseInt(cursor.getString(0));
String nama_buku = cursor.getString(1);
String penulis = cursor.getString(2);
String penerbit = cursor.getString(3);
dataBuku = new DataBuku(id, nama_buku, penulis,penerbit);
}
cursor.close();
return dataBuku;
}
}
|
SQL
|
UTF-8
| 769
| 2.921875
| 3
|
[] |
no_license
|
DROP TABLE IF EXISTS races;
CREATE TABLE `races` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`course` int(1) NOT NULL,
`status` int(1) DEFAULT '0' NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
DROP TABLE IF EXISTS race_user;
CREATE TABLE `race_user` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`race_id` int(4) NOT NULL,
`user_id` int(4) NOT NULL,
`raptime` int(8),
`lane` int(1) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
|
Swift
|
UTF-8
| 461
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
import Foundation
public struct License {
/// The license name used for the API.
public let name: String
/// A URL to the license used for the API.
public let url: URL?
}
struct LicenseBuilder: Codable {
let name: String
let url: URL?
}
extension LicenseBuilder: Builder {
typealias Building = License
func build(_ swagger: SwaggerBuilder) throws -> License {
return License(name: self.name, url: self.url)
}
}
|
Go
|
UTF-8
| 897
| 2.875
| 3
|
[] |
no_license
|
package factory
import (
"bytes"
"io"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/golang/glog"
)
func BuildAWSCSVLoader(
tetraBucket string,
csvFileKey string,
svc *s3.S3,
decrypt func(io.Reader) (io.Reader, error),
) func() string {
stringCSVLoader := func() string {
csvFileOutput, err := svc.GetObject(
&s3.GetObjectInput{
Bucket: &tetraBucket,
Key: &csvFileKey,
},
)
if err != nil {
glog.Fatalf("error: could not get the file from s3 (%s)\n", err)
}
csvBuf := new(bytes.Buffer)
csvDecrypted, err := decrypt(csvFileOutput.Body)
if err != nil {
glog.Fatalf(
"error: could not decrypt the file (%s)\n",
err,
)
}
_, err = csvBuf.ReadFrom(csvDecrypted)
if err != nil {
glog.Fatalf("error: buffer could not read decrypted (%s)", err)
}
csvString := csvBuf.String()
return csvString
}
return stringCSVLoader
}
|
PHP
|
UTF-8
| 1,650
| 2.875
| 3
|
[] |
no_license
|
<?php require_once('admin/scripts/config.php');
if(isset($_GET['filter'])){
$tbl = 'tbl_movies';
$tbl2 = 'tbl_genre';
$tbl3 = 'tbl_mov_genre';
$col = 'movies_id';
$col2 = 'genre_id';
$col3 = 'genre_name';
$filter = $_GET['filter'];
$results = filterResults($tbl, $tbl2, $tbl3, $col, $col2, $col3, $filter);
} else {
$results = getAll('tbl_movies');
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Movie Review</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="https://www.bootstrapcdn.com" />
<link rel="stylesheet" type="text/css" media="screen" href="css/main.css" />
<script src="main.js"></script>
</head>
<body>
<?php include('templates/header.php'); ?>
<h1>This is a movie website.</h1>
<section>
<ul>
<?php
//using endwhile keeps php code cleaner
while($row = $results->fetch(PDO::FETCH_ASSOC)):?>
<?php //TODO:: use the following syntax to display at least 3 more columns from the database?>
<li><?php echo $row['movies_title'];?></li>
<p><?php echo $row['movies_year'];?></p>
<p><?php echo $row['movies_storyline'];?></p>
<img src="images/<?php echo $row['movies_cover'];?>" alt="">
<a href="details.php?id=<?php echo $row['movies_id'];?>">Read More</a>
<?php endwhile;?>
</ul>
</section>
<script src="js/encrypt.js"></script>
<?php include('templates/footer.php'); ?>
</body>
</html>
|
Java
|
UTF-8
| 1,255
| 2.671875
| 3
|
[] |
no_license
|
package com.gvl.test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.gvl.entities.Person;
import com.gvl.helper.SessionFactoryRegistry;
public class GVLTest {
public static void main(String[] args) {
Person person=new Person();
Session session=null;
SessionFactory sessionFactory=null;
sessionFactory=SessionFactoryRegistry.getSessionfactory();
System.out.println("session factory object is created");
session= sessionFactory.openSession();
storePerson(session);
//person=session.get(Person.class,125 );
person=session.load(Person.class,121);
System.out.println(person.getEmailaddress());
System.out.println(person);
}
public static void storePerson(Session session) {
Transaction transaction=null;
boolean flag=false;
try {
transaction=session.beginTransaction();
Person person=new Person();
person.setPid(121);
person.setPname("satya");
person.setGender("male");
person.setAge(25);
person.setMobileno("3445667");
person.setEmailaddress("satya,gmail.com");
session.save(person);
flag=true;
}finally{
if(transaction!=null) {
if(flag) {
transaction.commit();
}else {
transaction.rollback();
}
}
}
}
}
|
C#
|
UTF-8
| 1,765
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
//----------------------------------------------
// NGUI: Next-Gen UI kit
// Copyright © 2011-2012 Tasharen Entertainment
//----------------------------------------------
using UnityEngine;
/// <summary>
/// Similar to UIButtonColor, but adds a 'disabled' state based on whether the collider is enabled or not.
/// </summary>
[AddComponentMenu("NGUI/Interaction/Button")]
public class UIButton : UIButtonColor
{
/// <summary>
/// Color that will be applied when the button is disabled.
/// </summary>
public Color disabledColor = Color.grey;
/// <summary>
/// If the collider is disabled, assume the disabled color.
/// </summary>
protected override void OnEnable ()
{
if (isEnabled) base.OnEnable();
else UpdateColor(false, true);
}
public override void OnHover (bool isOver) { if (isEnabled) base.OnHover(isOver); }
public override void OnPress (bool isPressed) { if (isEnabled) base.OnPress(isPressed); }
/// <summary>
/// Whether the button should be enabled.
/// </summary>
public bool isEnabled
{
get
{
Collider col = GetComponent<Collider>();
return col && col.enabled;
}
set
{
Collider col = GetComponent<Collider>();
if (!col) return;
if (col.enabled != value)
{
col.enabled = value;
UpdateColor(value, false);
}
}
}
/// <summary>
/// Update the button's color to either enabled or disabled state.
/// </summary>
public void UpdateColor (bool shouldBeEnabled, bool immediate)
{
if (tweenTarget)
{
if (!mStarted)
{
mStarted = true;
Init();
}
Color c = shouldBeEnabled ? defaultColor : disabledColor;
TweenColor tc = TweenColor.Begin(tweenTarget, 0.15f, c);
if (immediate)
{
tc.color = c;
tc.enabled = false;
}
}
}
}
|
Python
|
UTF-8
| 703
| 4.28125
| 4
|
[] |
no_license
|
# set (집합)
# 중복이 안되고, 순서가 없음
my_set = {1,2,3,3,4}
print(my_set)
java = {"유재석", "김태호", "양세형"}
python = set(["유재석", "박명수"])
# 교집합 (java 와 python을 모두 할 수 있는 개발자)
print(java & python)
print(java.intersection(python))
# 합집합 (java도 할 수 있거나 python도 할 수 있는 개발자)
print(java | python)
print(java.union(python))
# 차집합 (java는 할 수 있지만, python은 못하는 개발자)
print(java - python)
print(java.difference(python))
# python 을 할 줄 아는 사람이 늘어났을 때
python.add("김태호")
print(python)
# java를 잊었어요
java.remove("김태호")
print(java)
|
Markdown
|
UTF-8
| 22,132
| 2.90625
| 3
|
[
"MIT"
] |
permissive
|
<!-- Use fully qualified URL for the images so they'll also be visible from the NPM page too -->

[](https://badge.fury.io/js/join-monster) [](https://travis-ci.org/stems/join-monster) [](http://join-monster.readthedocs.io/en/latest/?badge=latest)
#### [Read the Documentation](http://join-monster.readthedocs.io/en/latest/)
#### [Try Demo](https://join-monster.herokuapp.com/graphql?query=%7B%20users%20%7B%20%0A%20%20id%2C%20fullName%2C%20email%0A%20%20posts%20%7B%20id%2C%20body%20%7D%0A%7D%7D)
#### [Example Repo](https://github.com/stems/join-monster-demo)
## What is Join Monster?
A JavaScript execution layer from GraphQL to SQL for batch data fetching between the API and the database by dynamically **translating GraphQL to SQL** for efficient data retrieval, all in a single batch before resolution. Simply delcare the data requirements of each field in you schema. Then, for each query, Join Monster will look at what was requested, find the data requirements, fetch, and shape your data.
Think of it as an alternative to Facebook's DataLoader if you're fetching from a SQL database. It's a little opionionated, but not an ORM.
It is **NOT** a tool for automatically creating a schema for you GraphQL from your database or vice versa. You retain the freedom and power to define your schemas how you want. Join Monster simply "compiles" a GraphQL query to a SQL query *based on the existing schemas*. It fits into existing applications and can be seamlessly removed later or used to varying degree. And it works with Relay!
## The problem with GraphQL & SQL that we solve
GraphQL is an elegant solution the round-trip problem often encountered with REST APIs. Many are using it in conjunction with the power of SQL databases. But how do we mitigate the number of roundtrips to our **database**? Consider the following schema: `Users` that have many `Posts` that have many `Comments`.

Here is a sensible query to retrieve some info from these tables.
```graphql
{
users {
name
posts {
body
comments { body, author_id }
}
}
}
```
How might we go about resolving this?
```javascript
const User = new GraphQLObjectType({
name: 'User',
fields: () => ({
name: { /*...*/ },
posts: {
type: new GraphQLList(Post),
resolve: user => {
return db.query(`SELECT * FROM posts WHERE author_id = '?'`, user.id)
}
}
})
})
const Post = new GraphQLObjectType({
name: 'Post',
fields: () => ({
body: { /*...*/ },
comments: {
type: new GraphQLList(Comment),
resolve: post => {
return db.query(`SELECT * FROM comments WHERE post_id = '?'`, post.id)
}
}
})
})
```
Elegant as this is, consider what happens if the user has 20 posts. That's one SQL query for the posts, and **20 more** for each post's set of comments. This is a total of at least 21 round-trips to the database (we haven't considered how we got the `User` data)! This could easily become a performance bottleneck. We've encountered the round-trip problem again (on the back-end instead of the client). We need to optimize the data-fetching against our back-end!
Of course, it doesn't have to be done this way. Perhaps we can reduce the round-trips by doing the joins all at once in the `User` resolver.
```javascript
const Query = new GraphQLObjectType({
name: 'Query',
fields: () => ({
users: {
type: new GraphQLList(User),
resolve: async () => {
const sql = `
SELECT * from accounts
JOIN posts ON posts.author_id = accounts.id
JOIN comments ON comments.post_id = posts.id
`
const rows = await db.query(sql)
// convert the flat rows to the object tree structure
const tree = nestObjectShape(rows)
return tree
}
}
})
})
```
So we got all the data at the top level, this will simplify the `Posts` and `Comments` resolvers since those properties are already there.
```javascript
const User = new GraphQLObjectType({
name: 'User',
fields: () => ({
name: { /*...*/ },
posts: {
type: new GraphQLList(Post)
}
})
})
const Post = new GraphQLObjectType({
name: 'Post',
fields: () => ({
body: { /*...*/ },
comments: {
type: new GraphQLList(Comment)
}
})
})
```
Although we made the round-trip problem go away, what if another query doesn't even ask for the comments?
```graphql
{
users {
name
posts { body }
}
}
```
During the execution of this request, it will wastefully join on the comments! The resolving phase essentially becomes a bunch of property lookups for a conglomerate result we prepared in the top-level. It's not too bad now, but this approach will not scale to more complex schema. Consider a schema like this:

Imagine doing all those joins up front. This is especially wasteful when client only wants a couple of those resources. We now have the inverse problem: **getting too much data.** Furthermore, we've reduced the maintainability of our code. Changes to the schema will require changes to the SQL query that fetches all the data. Often times there is the extra burden of converting the database result into the Object shape, since many database drivers simply return a flat, tabular structure.
## How It Works
Join Monster fetches only the data you need - *nothing more, nothing less*, just like to original philosophy of GraphQL. It reads the parsed GraphQL query, looks at your schema definition, and generates the SQL automatically that will fetch no more than what is required to fulfill the request. All data fetching for all resources becomes a single batch request.
Instead of writing the SQL yourself, you configure the schema definition with a bit of additional metadata about the SQL schema. Your queries can be as simple as this:
```
{ SELECT {
user(id: 1) { "user"."id", user: {
idEncoded "user"."first_name", idEncoded: 'MQ==',
fullName ==> "user"."last_name", ==> fullName: 'andrew carlson',
email "user"."email_address" email: 'andrew@stem.is'
} FROM "accounts" AS "user" }
} WHERE "user".id = 1 }
```
To something as complex as this:
```graphql
{
users {
id, idEncoded, fullName, email
following { id, fullName }
comments {
body
author { id, fullName }
post {
id, body
author { id, fullName }
}
}
}
}
```
which becomes...
```sql
SELECT
"users"."id" AS "id",
"users"."first_name" AS "first_name",
"users"."last_name" AS "last_name",
"users"."email_address" AS "email_address",
"following"."id" AS "following__id",
"following"."first_name" AS "following__first_name",
"following"."last_name" AS "following__last_name",
"comments"."id" AS "comments__id",
"comments"."body" AS "comments__body",
"author"."id" AS "comments__author__id",
"author"."first_name" AS "comments__author__first_name",
"author"."last_name" AS "comments__author__last_name",
"post"."id" AS "comments__post__id",
"post"."body" AS "comments__post__body",
"author$"."id" AS "comments__post__author$__id",
"author$"."first_name" AS "comments__post__author$__first_name",
"author$"."last_name" AS "comments__post__author$__last_name"
FROM "accounts" AS "users"
LEFT JOIN "relationships" AS "relationships" ON "users".id = "relationships".follower_id
LEFT JOIN "accounts" AS "following" ON "relationships".followee_id = "following".id
LEFT JOIN "comments" AS "comments" ON "users".id = "comments".author_id
LEFT JOIN "accounts" AS "author" ON "comments".author_id = "author".id
LEFT JOIN "posts" AS "post" ON "comments".post_id = "post".id
LEFT JOIN "accounts" AS "author$" ON "post".author_id = "author$".id
```
and responds with...
```javascript
{
"data": {
"users": [
{
"id": 1,
"idEncoded": "MQ==",
"fullName": "andrew carlson",
"email": "andrew@stem.is",
"following": [
{
"id": 2,
"fullName": "matt elder"
}
],
"comments": [
{
"body": "Wow this is a great post, Matt.",
"author": {
"id": 1,
"fullName": "andrew carlson"
},
"post": {
"id": 1,
"body": "If I could marry a programming language, it would be Haskell.",
"author": {
"id": 2,
"fullName": "matt elder"
}
}
}
]
},
{
"id": 2,
"idEncoded": "Mg==",
"fullName": "matt elder",
"email": "matt@stem.is",
"following": [],
"comments": []
}
]
}
}
```
Join Monster generates the SQL dynamically. The SQL queries will **adapt** not only with the varying complexities of queries, but also changes in the schema. No back-and-forth from web server to database. No need to get convert the raw result to the nested structure. Lots of benefits for a little bit of configuration.
- [X] Fetch all the data in a single database query.
- [X] Automatically generate adapting SQL queries.
- [X] Automatically build the nested object structure.
- [X] Easier maintainability.
- [X] Coexists with your custom resolve functions.
Join Monster is a means of batch-fetching data from your SQL database. It will not prevent you from writing custom resolvers or hinder your ability to define either of your schemas.
## Running the Demo
```shell
$ git clone https://github.com/stems/join-monster.git
$ cd join-monster
$ npm install
$ npm start
# go to http://localhost:3000/graphql
```
Explore the schema, try out some queries, and see what the resulting SQL queries and responses look like in our custom version of GraphiQL!

## Usage
See the [example repo](https://github.com/stems/join-monster-demo/tree/master/schema-basic) for a reference. I'll demonstrate the steps to set up this example. We'll set up a little API for a simple blog site for `Users` that can make `Posts` as well as `Comments` on people's posts. We will also let them follow other users. Here is a picture of the schema.

I'll omit the code to set up the SQL. A small set of SQLite3 sample data is provided in the [example](https://github.com/stems/join-monster-demo/tree/master/schema-basic) at `example/data/data.sl3`.
### 1. Declare GraphQL and SQL schemas like you normally would
Here is how the `graphql-js` schema would look.
```javascript
import { GraphQLSchema } from 'graphql'
import { GraphQLObjectType, GraphQLList, GraphQLString, GraphQLInt } from 'graphql'
const User = new GraphQLObjectType({
name: 'User',
fields: () => ({
id: {
type: GraphQLInt
},
email: {
type: GraphQLString
},
idEncoded: {
description: 'The ID base-64 encoded',
type: GraphQLString,
resolve: user => toBase64(user.idEncoded)
},
fullName: {
description: 'A user\'s first and last name',
type: GraphQLString
}
})
})
const QueryRoot = new GraphQLObjectType({
name: 'Query',
fields: () => ({
users: {
type: new GraphQLList(User),
resolve: () => {} // TODO
}
})
})
export default new GraphQLSchema({
description: 'a test schema',
query: QueryRoot
})
```
### 2. Map Object Types to SQL Tables
Your SQL Tables must map to a `GraphQLObjectType`. Add the `sqlTable` and `uniqueKey` properties to the type definition.
```javascript
const User = new GraphQLObjectType({
name: 'User',
sqlTable: 'accounts', // the SQL table for this object type is called "accounts"
uniqueKey: 'id', // the id in each row is unique for this table
fields: () => ({ /*...*/ })
})
```
Wrap the name in an additional pair of double quotes if the name contains capital letters. You can also prefix this string with the schema name if it is different than the default, separated by a period.
### 3. Add Metadata to the `User` Fields
You'll need to provide a bit of information about each column, like `sqlColumn` and `sqlDeps`. These will be added to the *fields* in the type definition.
```javascript
const User = new GraphQLObjectType({
//...
fields: () => ({
id: {
// the column name is assumed to be the same as the field name
type: GraphQLInt
},
email: {
type: GraphQLString,
// if the column name is different, it must be specified specified
sqlColumn: 'email_address'
},
idEncoded: {
description: 'The ID base-64 encoded',
type: GraphQLString,
sqlColumn: 'id',
// this field uses a sqlColumn and applies a resolver function on the value
// if a resolver is present, the `sqlColumn` MUST be specified even if it is the same name as the field
resolve: user => toBase64(user.idEncoded)
},
fullName: {
description: 'A user\'s first and last name',
type: GraphQLString,
// perhaps there is no 1-to-1 mapping of field to column
// this field depends on multiple columns
sqlDeps: [ 'first_name', 'last_name' ],
resolve: user => `${user.first_name} ${user.last_name}`
}
})
})
function toBase64(clear) {
return Buffer.from(String(clear)).toString('base64')
}
```
### 4. Let Join Monster Grab Your Data
Import `joinMonster`. Have the top-most field that maps to a SQL table implement a resolver function that calls `joinMonster`. Simply pass it the AST info, a "context" object (which can be empty for now), and a callback that takes the SQL as a parameter, calls the database, and returns the data (or a `Promise` of the data). The data must be an array of objects where each object represents a row in the result set.
```javascript
import joinMonster from 'join-monster'
const QueryRoot = new GraphQLObjectType({
name: 'Query',
fields: () => ({
users: {
type: new GraphQLList(User),
resolve: (parent, args, context, ast) => {
return joinMonster(ast, {}, sql => {
// knex is a SQL query library for NodeJS. This method returns a `Promise` of the data
return knex.raw(sql)
})
}
}
})
})
```
You'll need to set up the connection to the database. For the `example` there is a small SQLite3 file provided. You can import `knex` and load the data like this.
```javascript
const dataFilePath = 'path/to/the/data.sl3' // make this the path to the database file
const knex = require('knex')({
client: 'sqlite3',
connection: {
filename: dataFilePath
}
})
```
You're ready to handle queries on the `Users`!
```graphql
{
users { id, idEncoded, email, fullName }
}
```
**Note:** `joinMonster` does *NOT* have to be at the root field of the query. You can call `joinMonster` at and field at any depth and it will handle fetching the data for its children.
### 5. Adding Joins
Let's add a field to our `User` which is a `GraphQLObjectType`: their `Comments` which also map to a SQL table as a one-to-many relationship. Let's define that type and add the additional SQL metadata.
```javascript
const Comment = new GraphQLObjectType({
name: 'Comment',
sqlTable: 'comments',
uniqueKey: 'id',
fields: () => ({
// id and body column names are the same
id: {
type: GraphQLInt
},
body: {
type: GraphQLString
}
})
})
```
We need to add a field to our `User`, and tell `joinMonster` how to grab these comments via a `JOIN`. This can be done with a `sqlJoin` property with a function. It will take the parent table and child table names (actually the aliases that `joinMonster` will generate) as parameters respectively and return the join condition.
```javascript
const User = new GraphQLObjectType({
//...
fields: () => ({
//...
comments: {
type: new GraphQLList(Comment),
// a function to generate the join condition from the table aliases
// NOTE: you must double-quote any case-sensitive column names the table aliases are already quoted
sqlJoin: (userTable, commentTable) => `${userTable}.id = ${commentTable}.author_id`
}
})
})
```
Now you can query for the comments for each user!
```graphql
{
users {
id, idEncoded, email, fullName
comments { id, body }
}
}
```
### 6. Arbitrary Depth
Let's go deeper and join the post on the comment, a one-to-one relationship. We'll define the `Post`, give it the SQL metadata, and add it as a field on the `Comment`. Each of these also has an author, which maps to the `User` type, let's tell `joinMonster` how to fetch those too.
```javascript
const Post = new GraphQLObjectType({
name: 'Post',
sqlTable: 'posts',
uniqueKey: 'id',
fields: () => ({
id: {
type: GraphQLInt
},
body: {
description: 'The content of the post',
type: GraphQLString
},
// we'll give the `Post` a field which is a reference to its author, back to the `User` type too
author: {
description: 'The user that created the post',
type: User,
sqlJoin: (postTable, userTable) => `${postTable}.author_id = ${userTable}.id`
}
})
})
const Comment = new GraphQLObjectType({
//...
fields: () => ({
//...
post: {
description: 'The post that the comment belongs to',
type: Post,
sqlJoin: (commentTable, postTable) => `${commentTable}.post_id = ${postTable}.id`
},
author: {
description: 'The user who wrote the comment',
type: User,
sqlJoin: (commentTable, userTable) => `${commentTable}.author_id = ${userTable}.id`
}
})
})
```
Now you have some depth and back references. It would be possible to cycle.
```graphql
{
users {
id, idEncoded, email, fullName
comments {
id, body
author { fullName }
post {
id, body
author { fullName }
}
}
}
}
```
### 7. Many-to-Many, Self-Referential Relationship
Let us allow `Users` to follow one another. We'll need a join table for the many-to-many and hence two joins to fetch this field. For this we can specify `joinTable` and `sqlJoins` on the field, which should be intuitive based on previous examples.
```javascript
const User = new GraphQLObjectType({
//...
fields: () => ({
//...
following: {
description: 'Users that this user is following',
type: new GraphQLList(User),
joinTable: 'relationships', // this is the name of our join table
sqlJoins: [
// first the parent table to the join table
(followerTable, relationTable) => `${followerTable}.id = ${relationTable}.follower_id`,
// then the join table to the child
(relationTable, followeeTable) => `${relationTable}.followee_id = ${followeeTable}.id`
]
},
})
})
```
```grapql
{
users {
id, idEncoded, email, fullName
following { fullName }
}
}
```
### 8. Where Conditions
We of course don't always want every row from every table. In a similar manner to the `sqlJoin` function, you can define a `where` function on a field. Its parameters are the table alias (generated automatically by `joinMonster`), the GraphQL arguments on that field, and the "context" mentioned earlier. The string returned is the `WHERE` condition. If a falsy value is returned, there will be no `WHERE` condition. We'll add another top-level field that just returns one user.
```javascript
const QueryRoot = new GraphQLObjectType({
name: 'Query',
fields: () => ({
users: { /*...*/ },
user: {
type: User,
args: {
id: { type: GraphQLInt }
},
where: (usersTable, args, context) => {
if (args.id) return `${usersTable}.id = ${args.id}`
},
resolve: (parent, args, context, ast) => {
return joinMonster(ast, {}, sql => {
return knex.raw(sql)
})
}
}
})
})
```
```graphql
{
user(id: 1) {
id, idEncoded, email, fullName
following { fullName }
comments { id, body }
}
}
```
### 9. Join Monster Context
The `joinMonster` function has a second parameter which is basically an arbitrary object with useful contextual information that your `where` functions might depend on. For example, if you want to get the **logged in** user, the ID of the loggen in user could be passed in the second argument.
```javascript
{
//...
// there is a GraphQL context and a Join Monster context. these are separate!
resolve: (parent, args, context, ast) => {
// get some info off the HTTP request, like the cookie.
const loggedInUserId = getHeaderAndParseCookie(context)
return joinMonster(ast, { id: loggedInUserId }, sql => {
return knex.raw(sql)
})
}
}
```
### 10. Relay Compatibility
It works well with [graphql-relay-js](https://github.com/graphql/graphql-relay-js)! Check out [the docs](http://join-monster.readthedocs.io/en/latest/relay) for more details.
**There's still a lot of work to do. Please feel free to fork and submit a Pull Request!**
## TODO
- [ ] Much better error messages in cases of mistakes (like missing sql properties)
- [ ] Figure out a way to handle Interface and Union types
- [ ] Figure out a way to support the schema language
- [ ] Implement `LIMIT` `OFFSET` pagination for relay connections
- [ ] Aggregate functions
- [ ] Caching layer?
#### [Official Documentation](http://join-monster.readthedocs.io/en/latest/)
|
Markdown
|
UTF-8
| 11,621
| 2.640625
| 3
|
[] |
no_license
|
**Unit 3: The Umayyad and Abbasid Empires** <span id="3"></span>
*After the period called “Rightly Guided Caliphs,” the Umayyad Caliphate
emerged in the mid-600s CE following a succession struggle among the
descendants of Muhammad. In less than 50 years, the Umayyad Dynasty’s
military forces secured political control of a vast region stretching
from the Punjab region of India westward across the Middle East and
North Africa to Spain. Umayyad leaders eventually moved their seat of
power from Arabia to Damascus (in modern-day Syria). The Umayyads did
not force conquered peoples to convert to Islam, but they did tax
non-Muslim peoples heavily to provide revenues for the state. In the
mid-700s, growing discontent with Umayyad rule led to a revolt that
brought the Abbasid family to power. The Abbasid Dynasty shifted
political power from Damascus to Baghdad and attempted to develop
bureaucratic institutions to consolidate and manage their vast empire.
In this unit, you will study the formation of the Umayyad Empire and its
impact on the peoples and cultures of the Middle East and Southwest
Asia. You will also look at the differences between Umayyad and the
Abbasid imperial administrations and the major challenges that both
dynasties faced as they attempted to govern a vast and complex
political-religious empire.*
**Unit 3 Time Advisory**
This unit should take you 16.5 hours to complete.
<span
style="color: rgb(85, 85, 85); font-family: 'Myriad Pro', 'Gill Sans', 'Gill Sans MT', Calibri, sans-serif; font-size: 16px; line-height: 24px; text-align: left; -webkit-text-size-adjust: none; ">☐
</span>Subunit 3.1: 4 hours
<span
style="color: rgb(85, 85, 85); font-family: 'Myriad Pro', 'Gill Sans', 'Gill Sans MT', Calibri, sans-serif; font-size: 16px; line-height: 24px; text-align: left; -webkit-text-size-adjust: none; ">☐
</span>Readings: 2 hours for each reading
<span
style="color: rgb(85, 85, 85); font-family: 'Myriad Pro', 'Gill Sans', 'Gill Sans MT', Calibri, sans-serif; font-size: 16px; line-height: 24px; text-align: left; -webkit-text-size-adjust: none; ">☐
</span>Subunit 3.2: 9.5 hours
<span
style="color: rgb(85, 85, 85); font-family: 'Myriad Pro', 'Gill Sans', 'Gill Sans MT', Calibri, sans-serif; font-size: 16px; line-height: 24px; text-align: left; -webkit-text-size-adjust: none; ">☐
</span>Introduction: 5.5 hours
<span
style="color: rgb(85, 85, 85); font-family: 'Myriad Pro', 'Gill Sans', 'Gill Sans MT', Calibri, sans-serif; font-size: 16px; line-height: 24px; text-align: left; -webkit-text-size-adjust: none; ">☐
</span>Readings: 3.5 hours
<span
style="color: rgb(85, 85, 85); font-family: 'Myriad Pro', 'Gill Sans', 'Gill Sans MT', Calibri, sans-serif; font-size: 16px; line-height: 24px; text-align: left; -webkit-text-size-adjust: none; ">☐
</span>Web Media: 2 hour
<span
style="color: rgb(85, 85, 85); font-family: 'Myriad Pro', 'Gill Sans', 'Gill Sans MT', Calibri, sans-serif; font-size: 16px; line-height: 24px; text-align: left; -webkit-text-size-adjust: none; ">☐
</span>Subunit 3.2.1: 0.5 hour
<span
style="color: rgb(85, 85, 85); font-family: 'Myriad Pro', 'Gill Sans', 'Gill Sans MT', Calibri, sans-serif; font-size: 16px; line-height: 24px; text-align: left; -webkit-text-size-adjust: none; ">☐
</span>Subunit 3.2.2: 3.5 hours
<span
style="color: rgb(85, 85, 85); font-family: 'Myriad Pro', 'Gill Sans', 'Gill Sans MT', Calibri, sans-serif; font-size: 16px; line-height: 24px; text-align: left; -webkit-text-size-adjust: none; ">☐
</span>Subunit 3 Assignment: 3.5 hours
**Unit3 Learning Outcomes**
Upon successful completion of this unit, the student will be able to:
- Identify the origins of the Umayyad and Abbasid Empires.
- Assess how these dynasties reshaped political and economic life
throughout the Middle East and Southwest Asia.
- Discuss the transition from elected leadership in Islam to dynastic
rulers.
- Describe Islam’s interaction with Europe.
- Analyze the political dominance of Islam in the Iberian Peninsula.
**3.1 Rise of the Umayyad Empire** <span id="3.1"></span>
- **Reading: University of Notre Dame: “Medieval Period of
Expansion”**
Link: University of Notre Dame: [“Medieval Period of
Expansion”](http://ocw.nd.edu/arabic-and-middle-east-studies/islamic-societies-of-the-middle-east-and-north-africa-religion-history-and-culture/lectures/lecture-3) (HTML)
Please revisit the “Medieval Period of Expansion” article you read
in subunit 2.3, focusing this time on the rise and fall of the
Umayyads, the first Muslim dynasty. You should also be able to
understand the dynasty’s rise and fall in the broader context of
Islamic expansion in medieval times.
Reading this text and studying the maps will take approximately 1
hour.
Terms of Use: This resource is licensed under a [Creative Commons
Attribution-NonCommercial-ShareAlike 3.0 Unported
license](http://creativecommons.org/licenses/by-nc-sa/3.0/). It is
attributed to the University of Notre Dame.
- **Reading: Fordham University’s Internet History Sourcebook: Oleg
Grabar’s “Ceremonial and Art at the Umayyad Court”**
Link: Fordham University’s *Internet History Sourcebook*: Oleg
Grabar’s “[Ceremonial and Art at the Umayyad
Court](http://www.fordham.edu/halsall/med/grabar1.asp)” (HTML)
Instructions: Please read the entire text carefully. It depicts
the high-culture in this very wealthy empire. The reading should
take approximately 2 hours to complete.
Terms of Use: Please respect the copyright and terms of use on the
webpage displayed above.
**3.2 Conquest of Spain** <span id="3.2"></span>
- **Reading: BBC’s “Muslim Spain”**
Link: BBC’s “[Muslim
Spain](http://www.bbc.co.uk/religion/religions/islam/history/spain_1.shtml)”
(HTML)
Instructions: Please read the entire text. What do you think of
the enduring Islamic legacy in Spain today? This reading and
question should take you approximately 2 hours to complete.
Terms of Use: Please respect the copyright and terms of use on the
webpage displayed above.
- **Reading: Fordham University’s Internet Medieval Sourcebook: Peter
Halsall’s version of Ibn Abd-el-Hakem’s “The Islamic Conquest of
Spain”**
Link Fordham University’s *Internet Medieval Sourcebook:* Peter
Halsall’s version of Ibn Abd-el-Hakem’s “[The Islamic Conquest of
Spain](http://www.fordham.edu/halsall/source/conqspain.asp)”
(HTML)
Instructions: Please read the entire text. This piece is written
by a 9<sup>th</sup> century Egyptian author and as such one of the
earliest account of the capture of Spain by Islamic armies. Taking
notes and reading this entire text should take you approximately 1.5
hours to complete
Terms of Use: Please respect the copyright and terms of use on the
webpage displayed above.
- **Web Media: BBC’s “Muslim Spain”**
Link: BBC’s “[Muslim
Spain](http://www.bbc.co.uk/programmes/p00548l1)” (Adobe Flash)
Instructions: Please click on “Listen Now” on the audio file by the
BBC. You will hear a rich discussion on how Islamic Spain
contributed to Western Civilization. This web media will supplement
the BBC reading in this subunit. Listening to the audio file and
taking notes should take you approximately 2 hours to complete*. *
Terms of Use: Please respect the copyright and terms of use on the
webpage displayed above.
**3.2.1 Collapse of the Umayyad Empire** <span id="3.2.1"></span>
- **Reading: University of Calgary: The Applied History Research
Group’s “The Collapse of the Umayyad Dynasty”**
Link: University of Calgary: The Applied History Research Group’s
“[The Collapse of the Umayyad
Dynasty](https://web.archive.org/web/20130330042325/http://www.ucalgary.ca/applied_history/tutor/islam/caliphate/umCollapse.html)”
(HTML)
Instructions: Please read the entire text, which explains the
reasons behind the collapse of the first Islamic dynasty. This
reading should take you less than 30 minutes to complete.
Terms of Use: Please respect the copyright and terms of use on the
webpage displayed above.
**3.2.2 Shifting Power Base from Damascus to Baghdad** <span
id="3.2.2"></span>
- **Assessment: The Saylor Foundation's “The Umayyad and the Abbasid
Empires”**
Link: The Saylor Foundation's “[The Umayyad and the Abbasid
Empires](https://resources.saylor.org/wwwresources/archived/site/wp-content/uploads/2012/04/HIST231-Unit-3-The-Umayyads-and-the-Abbasids-FINAL.pdf)”
(PDF)
Instructions: Please click on the link above to download the
assessment. Please write out approximately one paragraph answers
for each question. After completing this assessment, please check
your responses against the Saylor Foundation’s “[Guide to Responding
to the Umayyad and the Abbasid
Empires.](https://resources.saylor.org/wwwresources/archived/site/wp-content/uploads/2012/04/HIST231-Unit-3-Guide-to-Responding-to-The-Umayyads-and-the-Abbasids-FINAL.pdf)”
(PDF) Your answers should contain, but not be limited to, the
information provided in the answer sheet. This assessment should
take approximately 3 hours to complete.
- **Reading: Fordham University’s Internet Medieval Sourcebook: Paul
Halsall’s version of Yakut’s “Baghdad under the Abbasids, ca. 1000
CE”**
Link: Fordham University’s *Internet Medieval Sourcebook:* Paul
Halsall’s version of Yakut’s “[Baghdad under the Abbasids, ca. 1000
CE](http://www.fordham.edu/halsall/source/1000baghdad.asp)” (HTML)
Instructions: Please read the entire text. This 11<sup>th</sup>
century document offers a detailed description of the city of
Baghdad at the height of the Abbasid Empire. Yakut, the author,
explains how the city is laid out on both sides of the Tigris River
and describes the royal palace of the caliph. He also mentions the
extensive military fortifications of the city and describes the fine
quality of the building materials used to construct the palaces of
the nobles along the bank of the Tigris. His account highlights the
beauty and sophistication of Baghdad under the Abbasids. After
reading this text, write a brief paragraph that summarizes life in
Baghdad under the Abbasids. This reading and paragraph should take
you approximately 1.5 hours to complete.
Terms of Use: Please respect the copyright and terms of use on the
webpage displayed above.
- **Web Media: BBC’s “Abbasid Caliphs”**
Link: BBC’s “[Abbasid
Caliphs](http://www.bbc.co.uk/programmes/p003hyfd)” (Adobe Flash)
Instructions: Please click on the “listen now.” The link will take
you to an informative interview on the subject. Melvyn Bragg
discusses the Abbasids with several world renown scholars.
Listening to this podcast and taking notes should take you
approximately 2 hours to complete.
Terms of Use: Please respect the copyright and terms of use on the
webpage displayed above.
|
C
|
UTF-8
| 3,082
| 2.890625
| 3
|
[] |
no_license
|
/******************************************************************************
* Function: Pcre match handle.
* Author: forwarding2012@yahoo.com.cn
* Date: 2012.01.01
* Compile: gcc -Wall smatch_base.c -I/usr/local/include -lpcre -o smatch_base
******************************************************************************/
#include <stdio.h>
#include <string.h>
#include <regex.h>
#include <pcre.h>
#define SUBSLEN 10
#define OVECCOUNT 30
#define EBUFLEN 128
#define BUFLEN 1024
static int check_model()
{
int choices;
printf("Test program as follow: \n");
printf("1 : match by regmatch\n");
printf("2 : match by prcematch\n");
printf("Please input test type: ");
scanf("%d", &choices);
return choices;
}
int reg_match()
{
int err, i;
size_t len;
regex_t re;
regmatch_t subs[SUBSLEN];
char matched[BUFLEN], errbuf[EBUFLEN];
char src[] = "111 <title>Hello World</title> 222";
char pattern[] = "<title>(.*)</title>";
printf("\nString : %s\nPattern: %s\n", src, pattern);
err = regcomp(&re, pattern, REG_EXTENDED);
if (err) {
len = regerror(err, &re, errbuf, sizeof(errbuf));
printf("error, regcomp: [%d]%s\n", len, errbuf);
return 1;
}
printf("Total has subexpression: %d\n", re.re_nsub);
err = regexec(&re, src, (size_t) SUBSLEN, subs, 0);
if (err == REG_NOMATCH) {
printf("Sorry, no match ...\n");
regfree(&re);
return 0;
} else if (err) {
len = regerror(err, &re, errbuf, sizeof(errbuf));
printf("error, regexec: [%d]%s\n", len, errbuf);
return 1;
}
printf("\nOK, has matched ...\n");
for (i = 0; i <= re.re_nsub; i++) {
len = subs[i].rm_eo - subs[i].rm_so;
printf("subexp-%d begin: %2d, len %d ", i, subs[i].rm_so, len);
memcpy(matched, src + subs[i].rm_so, len);
matched[len] = '\0';
printf("match: %s\n", matched);
}
regfree(&re);
return (0);
}
int pcre_match()
{
pcre *re;
const char *error;
int rc, i, ovector[OVECCOUNT];
int erroffset, substring_length;
char src[] = "111 <title>Hello World</title> 222";
char pattern[] = "<title>(.*)</title>";
char *substring_start;
printf("\nString : %s\nPattern: %s\n", src, pattern);
re = pcre_compile(pattern, 0, &error, &erroffset, NULL);
if (re == NULL) {
printf("PCRE compilation failed at offset %d: %s\n", erroffset,
error);
return 1;
}
rc = pcre_exec(re, NULL, src, strlen(src), 0, 0, ovector, OVECCOUNT);
if (rc < 0) {
if (rc == PCRE_ERROR_NOMATCH)
printf("Sorry, no match ...\n");
else
printf("Matching error %d\n", rc);
free(re);
return 1;
}
printf("\nOK, has matched ...\n");
for (i = 0; i < rc; i++) {
substring_start = src + ovector[2 * i];
substring_length = ovector[2 * i + 1] - ovector[2 * i];
printf("subexp-%d: %.*s\n", i, substring_length,
substring_start);
}
free(re);
return 0;
}
int main(int argc, char *argv[])
{
int choice;
if (argc < 2)
choice = check_model();
switch (choice) {
//catch a package.
case 1:
reg_match();
break;
//parse net package.
case 2:
pcre_match();
break;
//default do nothing
default:
break;
}
return 0;
}
|
Markdown
|
UTF-8
| 599
| 2.6875
| 3
|
[] |
no_license
|
# Intro
This is a simple theme made using awesome things like [bootsrap](https://getbootstrap.com/), [sass](http://sass-lang.com/) and [fontawesome](http://fontawesome.io/). You should have sass compiler such as sassc installed to generate css files.
It should look more or less like this [demo](https://haaja.github.io/bootstrap-sass-theme/).
## Running
```bash
$ git clone https://github.com/haaja/bootstrap-sass-theme
$ cd bootstrap-sass-theme
$ sassc sass/app.scss css/app.css
$ python -m http.server 8080
```
You can use any other http-server as well or simply open index.html in browser.
|
JavaScript
|
UTF-8
| 4,466
| 2.703125
| 3
|
[] |
no_license
|
/**
* PBR Viewport.
*
* @package PBR extension for SketchUp
*
* @copyright © 2018 Samuel Tallet-Sabathé
*
* @licence GNU General Public License 3.0
*/
/* jshint browser: true, esversion: 5 */
/**
* PBR plugin namespace.
*/
PBR = {};
/**
* Renders SketchUp active model in a 3D view.
*/
PBR.Viewport = {};
/**
* Translates Viewport app strings.
*
* @see assets/sketchup-locale.json
*/
PBR.Viewport.translateStrings = function() {
document.title = sketchUpLocale.document_title;
document.getElementById('toggleCloudsButton')
.setAttribute('title', sketchUpLocale.toggle_clouds);
var helpLink = document.getElementById('helpLink');
helpLink.href = sketchUpLocale.help_link_href;
helpLink.textContent = sketchUpLocale.help_link_text;
document.getElementById('saveAsImageButton')
.setAttribute('title', sketchUpLocale.save_as_image);
document.querySelector('.a-enter-vr-button')
.setAttribute('title', sketchUpLocale.enter_vr_mode);
};
/**
* Makes environment sky fully spherical.
*/
PBR.Viewport.makeEnvSkyFullySpherical = function() {
document.querySelector('#environment a-sky').setAttribute('theta-length', 360);
};
/**
* Toggles environment sky visibility.
*
* XXX This function may reveal scene background (clouds in our case).
*/
PBR.Viewport.toggleEnvSkyVisibility = function() {
var envSky = document.querySelector('#environment a-sky');
envSky.setAttribute('visible', !envSky.getAttribute('visible'));
};
/**
* Defines environment light position.
*
* @param {number} x
* @param {number} y
* @param {number} z
*/
PBR.Viewport.setEnvLightPosition = function(x, y, z) {
document.getElementById('environment')
.setAttribute(
'environment',
'lightPosition: ' + x + ' ' + y + ' ' + z
);
};
/**
* Returns sunlight position.
*
* @returns {Array.<number>}
*/
PBR.Viewport.getSunlightPosition = function() {
return document.getElementById('sunlight').getAttribute('position');
};
/**
* Defines sunlight position.
*
* @param {number} x
* @param {number} y
* @param {number} z
*/
PBR.Viewport.setSunlightPosition = function(x, y, z) {
document.getElementById('sunlight')
.setAttribute('position', x + ' ' + y + ' ' + z);
};
/**
* Defines sunlight position Y.
*
* @param {number} y
*/
PBR.Viewport.setSunlightPositionY = function(y) {
var sunlight = document.getElementById('sunlight');
var sunlightPosition = PBR.Viewport.getSunlightPosition();
sunlight.setAttribute(
'position',
sunlightPosition.x + ' ' +
y + ' ' +
sunlightPosition.z
);
};
/**
* Switches lights on or off.
*
* @param {string} switchPosition
*/
PBR.Viewport.switchLights = function(switchPosition) {
lightIsVisible = ( switchPosition === 'on' ) ? true : false;
var lights = document.querySelectorAll('a-entity[light]');
for (var lightIndex = 0; lightIndex < lights.length; lightIndex++) {
lights[lightIndex].setAttribute('visible', lightIsVisible);
}
};
/**
* Synchronizes lights.
*/
PBR.Viewport.syncLights = function() {
var sunlightPosition = PBR.Viewport.getSunlightPosition();
// XXX Because A-Frame environment component draws a sun.
PBR.Viewport.setEnvLightPosition(
sunlightPosition.x,
sunlightPosition.y,
sunlightPosition.z
);
PBR.Viewport.renderer.toneMappingExposure = sunlightPosition.y;
// If sun is above horizon:
if ( sunlightPosition.y > 0 ) {
PBR.Viewport.switchLights('on');
} else {
PBR.Viewport.switchLights('off');
}
};
/**
* Takes a screenshot.
*/
PBR.Viewport.takeScreenshot = function() {
document.querySelector('a-scene')
.sceneEl.components.screenshot.capture('perspective');
};
/**
* Adds event listeners.
*/
PBR.Viewport.addEventListeners = function() {
document.getElementById('sunElevationSlider')
.addEventListener('change', function(event) {
PBR.Viewport.setSunlightPositionY(event.target.value);
PBR.Viewport.syncLights();
});
document.getElementById('saveAsImageButton')
.addEventListener('click', function(_event) {
PBR.Viewport.takeScreenshot();
});
document.getElementById('toggleCloudsButton')
.addEventListener('click', function(_event) {
PBR.Viewport.toggleEnvSkyVisibility();
});
};
// When document is ready:
document.addEventListener('DOMContentLoaded', function() {
PBR.Viewport.addEventListeners();
// TODO Find a more reliable way.
setTimeout(function(){
PBR.Viewport.translateStrings();
PBR.Viewport.makeEnvSkyFullySpherical();
}, 1000);
});
|
JavaScript
|
UTF-8
| 1,930
| 3.359375
| 3
|
[] |
no_license
|
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
});
function getInput() {
return new Promise((res) => {
let input = undefined;
const board = [];
const startPos = { x: 0, y: 0 };
rl.on("line", (line) => {
if (input === undefined) {
input = {};
return;
}
const row = [];
for (let i = 0; i < line.length; i++) {
if (line[i] === "K") {
startPos.x = i;
startPos.y = board.length;
}
row.push(line[i]);
}
board.push(row);
});
rl.on("close", () => {
input = {
board,
startPos,
maxX: board[0].length - 1,
maxY: board.length - 1,
};
res(input);
});
});
}
function getNextMoves(
input = {},
posArray = [],
visitedPos = { "0,0": true },
stepCount = 0
) {
const nextMoves = [];
for (const { x, y } of posArray) {
if (x === 0 && y === 0) return stepCount;
const newMove = (x, y) => {
if (x === 0 && y === 0) return true;
if (x >= 0 && x <= input.maxX && y >= 0 && y <= input.maxY)
if (input.board[y][x] !== "#") {
const key = `${x},${y}`;
if (!(key in visitedPos)) {
visitedPos[key] = true;
nextMoves.push({ x, y });
}
}
return false;
};
const found =
newMove(x + 1, y + 2) ||
newMove(x - 1, y + 2) ||
newMove(x + 1, y - 2) ||
newMove(x - 1, y - 2) ||
newMove(x + 2, y + 1) ||
newMove(x - 2, y + 1) ||
newMove(x + 2, y - 1) ||
newMove(x - 2, y - 1);
if (found) return stepCount + 1;
}
if (nextMoves.length === 0) return -1;
return getNextMoves(input, nextMoves, visitedPos, stepCount + 1);
}
async function solve() {
const input = await getInput();
const answer = getNextMoves(input, [input.startPos]);
console.log(answer);
}
solve();
|
Java
|
UTF-8
| 287
| 1.8125
| 2
|
[] |
no_license
|
package com.informatica.lasin.system.dao;
import java.util.List;
import org.springframework.data.repository.CrudRepository;
import com.informatica.lasin.system.models.Curso;
public interface ICursoDao extends CrudRepository<Curso, Long>{
List<Curso> findByDocente_Id(Long id);
}
|
C#
|
UTF-8
| 1,473
| 2.96875
| 3
|
[
"MIT"
] |
permissive
|
using Microsoft.EntityFrameworkCore;
namespace graphql_minimal_api
{
public class BookRepository
{
private readonly DemoDbContext context;
public BookRepository(DemoDbContext context)
{
this.context = context;
}
public IQueryable<Book> GetAll()
{
return this.context.Books.Include(b => b.Author);
}
public Task Add(Book book)
{
this.context.Books.Add(book);
return this.context.SaveChangesAsync();
}
public async Task<bool> Delete(Guid guid)
{
var p = this.context.Books.FirstOrDefault(p => p.Id == guid);
if (p == null)
{
return false;
}
var e = this.context.Books.Remove(p);
await this.context.SaveChangesAsync();
return true;
}
public async Task<Book?> GetById(Guid guid)
{
return await context.Books.FindAsync(guid);
}
public async Task<Book?> Update(Book book)
{
var id = book.Id;
var entity = this.context.Books.FirstOrDefault(p => p.Id == id);
if (entity == null)
{
return null;
}
entity = entity with
{
Title = book.Title
};
await context.SaveChangesAsync();
return entity;
}
}
}
|
Python
|
UTF-8
| 1,514
| 2.6875
| 3
|
[] |
no_license
|
from __future__ import print_function
from settings import (
BUCKET_NAME, MONGODB_SERVER, MONGODB_PORT, MONGODB_DB, MONGODB_COLLECTION,
HEADERS, COOKIES, MIN_SLEEP, MAX_SLEEP
)
from getpass import getpass, getuser
import os
import sys
"""
Command line args:
1: str "(r)estore" or "(d)ump"
2: str directory path
Move the zipped database using scp
"""
def dump_database(output_dir):
"""
Takes the current, local mongoDB specified in settings.py and dumps
it at output_dir
"""
print("Dumping db")
dump_command = "mongodump --gzip --host {host} --port {port} --out {outpath} --db {db}"
dump_command = dump_command.format(
host="127.0.0.1",
port=MONGODB_PORT,
outpath=output_dir,
db=MONGODB_DB
)
print(dump_command)
os.system(dump_command)
print("Done")
def restore_db(input_dir):
print("Restoring db")
restore_command = "mongorestore --gzip --nsInclude {db}.{collection} {input_dir}"
restore_command = restore_command.format(
db=MONGODB_DB,
collection=MONGODB_COLLECTION, # Also supports wildcards
input_dir=input_dir
)
os.system(restore_command)
print("Done")
if __name__ == '__main__':
dump_bool = sys.argv[1].lower()[0] == 'd'
restore_bool = sys.argv[1].lower()[0] == 'r'
directory = sys.argv[2]
if dump_bool:
dump_database(directory)
elif restore_bool:
restore_db(directory)
else:
print("Sys args don't make sense")
|
C++
|
UTF-8
| 768
| 3.421875
| 3
|
[] |
no_license
|
#include "Fixed.hpp"
#include <iostream>
const int Fixed::offs = 8;
Fixed::Fixed():value(0)
{
std::cout << "Default constructor called" << std::endl;
}
Fixed::Fixed(Fixed const &dest)
{
std::cout << "Copy constructor called" << std::endl;
this->value = dest.getRawBits();
}
Fixed::~Fixed()
{
std::cout << "Default destructor called" << std::endl;
}
Fixed& Fixed::operator=(const Fixed &dst)
{
std::cout << "Assignation operator called" << std::endl;
this->value = dst.getRawBits();
return (*this);
}
int Fixed::getRawBits(void) const
{
std::cout << "getRawBits member function called" << std::endl;
return (this->value);
}
void Fixed::setRawBits(int const bits)
{
std::cout << "setRawBits member function called" << std::endl;
this->value = bits;
}
|
Ruby
|
UTF-8
| 507
| 4.25
| 4
|
[] |
no_license
|
#define a method that takes 2 arguments -> positive intgeger and boolean
#calculates bonus for a given salary
#if boolean is true, bonus should be half of the salary
#if boolean is false, bonus should be 0
def calculate_bonus(num, boolean)
if boolean == true
num / 2
else
0
end
end
#OR
def calculate_bonus(salary, boolean)
bonus ? (salary / 2) : 0
end
puts calculate_bonus(2800, true) == 1400
puts calculate_bonus(1000, false) == 0
puts calculate_bonus(50000, true) == 25000
|
JavaScript
|
UTF-8
| 374
| 3.984375
| 4
|
[] |
no_license
|
const equalOccurences = (string, ...checkChars) => {
console.log(checkChars)
let xOccurences = string.split(char1).length-1
let yOccurences = string.split(char2).length-1
if (xOccurences === yOccurences) { return true} // check if 'x' and 'o' have the same number in the string.
else return false;
}
console.log(equalOccurences("hello","i","o"));
|
Java
|
UTF-8
| 1,686
| 3.09375
| 3
|
[] |
no_license
|
package xogame;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import static org.assertj.core.api.BDDAssertions.then;
/**
* https://kata-log.rocks/tic-tac-toe-kata
*
* 🟪❌⭕
*
* Rules
* In random order
*
* [ ] a game is over when all fields in a row are taken by a player
* [x] players take turns taking fields until the game is over
* [ ] a game is over when all fields in a diagonal are taken by a player
* [ ] a game is over when all fields are taken
* [x] there are two players in the game (X and O)
* [x] a game has nine fields in a 3x3 grid
* [ ] a game is over when all fields in a column are taken by a player
* [ ] a player can take a field if not already taken
*/
public class XOGameTest {
@Disabled
@Test @DisplayName("xo game has a 3x3 field.")
void xoGameHasA3X3Field() {
}
@Test @DisplayName("first player can add an x.")
void firstPlayerCanAddAnX() {
XoGame xoGame = new XoGame();
xoGame.playerPlace(XoPosition.upperLeft);
then(xoGame).hasToString("""
❌🟪🟪
🟪🟪🟪
🟪🟪🟪
""");
}
@Test @DisplayName("second player can add an O.")
void secondPlayerCanAddAnO() {
XoGame xoGame = new XoGame();
xoGame.playerPlace(XoPosition.upperLeft);
xoGame.playerPlace(XoPosition.upperMiddle);
then(xoGame).hasToString("""
❌⭕🟪
🟪🟪🟪
🟪🟪🟪
""");
}
}
|
PHP
|
UTF-8
| 627
| 2.984375
| 3
|
[] |
no_license
|
<?php
class Database{
private $host;
private $db;
private $user;
private $password;
private $charset;
public function __construct(){
$this->host = constant('HOST');
$this->db = constant('DB');
$this->user = constant('USER');
$this->password = constant('PASSWORD');
$this->charset = constant('CHARSET');
}
function connect(){
try {
$this->conexion = (new MongoDB\Client)->{$this->db};
} catch (Exception $e){
echo $e->getMessage();
}
return $this->conexion;
}
}
?>
|
SQL
|
UTF-8
| 1,962
| 3.46875
| 3
|
[] |
no_license
|
SELECT
crede.ci_unidade_trabalho,
crede.nm_sigla,
upper(tmc.nm_municipio) AS nm_municipio,
upper(tc.nm_categoria) AS nm_categoria
,tut.nr_codigo_unid_trab,
tut.nm_unidade_trabalho,
upper(tlz.nm_localizacao_zona) AS nm_localizacao_zona
FROM rede_fisica.tb_unidade_trabalho tut
JOIN rede_fisica.tb_unidade_trabalho crede ON crede.ci_unidade_trabalho = tut.cd_unidade_trabalho_pai
JOIN rede_fisica.tb_local_unid_trab tlut ON tlut.cd_unidade_trabalho = tut.ci_unidade_trabalho
JOIN rede_fisica.tb_local_funcionamento tlf ON tlf.ci_local_funcionamento = tlut.cd_local_funcionamento
JOIN rede_fisica.tb_categoria tc ON tc.ci_categoria = tut.cd_categoria
JOIN rede_fisica.tb_localizacao_zona tlz ON tlz.ci_localizacao_zona = tlf.cd_localizacao_zona
JOIN util.tb_municipio_censo tmc ON tmc.ci_municipio_censo = tlf.cd_municipio_censo
WHERE tut.cd_dependencia_administrativa = 2
AND tut.cd_situacao_funcionamento = 1
AND tut.cd_tipo_unid_trab = 401
AND tlut.fl_sede = TRUE
ORDER BY 1,3,4,6;
/*
SELECT
crede.ci_unidade_trabalho,
crede.nm_sigla,
upper(tmc.nm_municipio) AS nm_municipio,
upper(tc.nm_categoria) AS nm_categoria
,tut.nr_codigo_unid_trab,
tut.nm_unidade_trabalho,
upper(tlz.nm_localizacao_zona) AS nm_localizacao_zona
FROM dl_sige.tb_unidade_trabalho tut
JOIN dl_sige.tb_unidade_trabalho crede ON crede.ci_unidade_trabalho = tut.cd_unidade_trabalho_pai
JOIN dl_sige.tb_local_unid_trab tlut ON tlut.cd_unidade_trabalho = tut.ci_unidade_trabalho
JOIN dl_sige.tb_local_funcionamento tlf ON tlf.ci_local_funcionamento = tlut.cd_local_funcionamento
JOIN dl_sige.tb_categoria tc ON tc.ci_categoria = tut.cd_categoria
JOIN dl_sige.tb_localizacao_zona tlz ON tlz.ci_localizacao_zona = tlf.cd_localizacao_zona
JOIN dl_sige.tb_municipio_censo tmc ON tmc.ci_municipio_censo = tlf.cd_municipio_censo
WHERE tut.cd_dependencia_administrativa = 2
AND tut.cd_situacao_funcionamento = 1
AND tut.cd_tipo_unid_trab = 401
AND tlut.fl_sede = TRUE
ORDER BY 1,3,4,6;
*/
|
Python
|
UTF-8
| 255
| 3.40625
| 3
|
[] |
no_license
|
archivo=open('Numeros_lista.txt','r')
'''archivo=str()'''
'''print (archivo.read())'''
num=input('Numero que desea encontrar: ')
for linea in archivo:
if num in linea:
print('Numero encontrado')
else:
print('No encontrado')
|
TypeScript
|
UTF-8
| 391
| 2.609375
| 3
|
[] |
no_license
|
// 6~10자 영문, 숫자 조합
export const passwordStandard = /^(?=.*\d)(?=.*[a-zA-Z])[0-9a-zA-Z]{6,10}$/;
// 이메일 유효성검사
export const emailStandard =
/^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$/i;
// 2~15자 한글, 영문 대소문자, 언더바 사용가능
export const usernameStandard = /^[\wㄱ-ㅎㅏ-ㅣ가-힣]{2,15}$/;
|
PHP
|
UTF-8
| 1,353
| 2.5625
| 3
|
[
"MIT"
] |
permissive
|
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateEmployeesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->string('emp_id',20)->primary();
$table->string('lastname',50);
$table->string('firstname',50);
$table->string('middlename',50)->nullable();
$table->string('extension',10)->nullable();
$table->date('birthdate');
$table->string('birthplace',100);
$table->string('address_id',10);
$table->bigInteger('civilstat_id');
$table->bigInteger('citizenship_id');
$table->string('gender',1);
$table->decimal('height');
$table->decimal('weight');
$table->string('bloodtype',3);
$table->string('image_url',255)->nullable();
$table->boolean('isapplicant')->default(false);
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('employees');
}
}
|
JavaScript
|
UTF-8
| 668
| 2.78125
| 3
|
[] |
no_license
|
let comic = document.getElementById("comic");
let comicImg = document.querySelector("#comic img");
if (comic){
let url = "http://www.explainxkcd.com/wiki/index.php" + window.location.pathname.slice(0, -1);
let d = document.createElement("div");
d.setAttribute("style", "font-size:0.8em;");
let alt = document.createElement("div");
alt.setAttribute("style", "font-style:italic;");
alt.appendChild(document.createTextNode(comicImg.title));
let a = document.createElement("a");
a.setAttribute("href", url);
a.appendChild(document.createTextNode("Explain?"));
d.appendChild(alt);
d.appendChild(a);
comic.append(d);
}
|
Markdown
|
UTF-8
| 13,299
| 3.203125
| 3
|
[] |
no_license
|
---
title: 求解矩阵的四种迭代法
tags:
- 数值分析
mathjax: true
abbrlink: 26753
date: 2018-07-19 12:16:12
---
## Introduction
  在之前我实现了求解低阶矩阵的一些算法。考虑线性方程组Ax=b,其中A为非奇异矩阵,当A是低阶稠密矩阵时,可以使用之前提到的中的高斯消元法以及列主
元消元法(详情请参考[高斯消元法之讲解与代码实现](https://leungyukshing.github.io/archives/GaussianElimination.html))来进行求解。但是实际生活中工程技术产生的矩阵都是大型的稀疏矩阵(阶数很大,但零元素很多),当A是高阶稀疏矩阵时,就可以利用迭代法来进行求解。迭代法利用了A中零元素较多的特点,这对于计算机的存储和运算是很有利的。<!-- more -->
  迭代法的基本思想是:对于线性方程组的第$k$行,假设除去$x_k$外,其他$x$已知,那么我就可以求出这一个$x_k$,考虑到矩阵稀疏的特点,每一行的计算就显得很容易了。通过迭代,每一行都基于之前算出的结果,对当前行的$x_k$进行更新,如果**迭代向量**具有收敛的性质,那么我们最后就可以逼近一个精确解。
  我们通过变换,可以将Ax=b等价变换为$x^\* = Bx + f$。构造向量序列$$
x^{(k+1)} = Bx^{(k)} + f
$$,其中$k$表示迭代次数。
  如果$\displaystyle \lim_{x\to\infty}x^{(k)}$存在,则说明**迭代法收敛**,否则,该**迭代法发散**。所以我们每次使用迭代法求解矩阵的时候就需要判断矩阵是否收敛。
。
**注意**:在使用迭代法求解的时候,要确保是可以收敛到一个精确解的。这里给出一个**判断矩阵收敛**的定理:对于一个线性方程组,迭代法收敛的充要条件是矩阵B的谱半径ρ(B) < 1
  这里主要分析四种迭代方法:**雅可比迭代法**、**高斯赛德尔迭代法**、**超松弛迭代法**、**共轭梯度法**。
## 雅可比迭代法(Jocobi Method)
### 分析
  现在我来讲解雅可比迭代法。雅可比迭代法是对上述迭代过程的详细展开。对于线性方程组的系数矩阵A,可分解为三部分:
$$
A = \begin{bmatrix}
a_{11} & \\
& a_{22} \\
& & \ddots \\
& & & a_{nn}
\end{bmatrix} -
\begin{bmatrix}
0\\
-a_{21} & 0\\
\vdots & \vdots & \ddots \\
-a_{n-1,1} & -a_{n-1,2} & \cdots & 0 \\
-a_{n1} & -a_{n2} & \cdots & -a_{n,n-1} & 0 \\
\end{bmatrix} -
\begin{bmatrix}
0 & -a_{12} & \cdots & -a_{1,n-1} & -a_{1n} \\
& 0 & \cdots & -a_{2,n-1} & -a_{2n} \\
& & \ddots & \vdots & \vdots \\
& & & 0 & -a_{n-1,n} \\
& & & & 0 \\
\end{bmatrix} = D-L-U
$$
设$a_{ii} \neq 0(i=1,2,...,n)$,可以得到Ax=b的雅可比迭代法:
$$
\begin{cases}
x^{(0)}, 初始向量\\
x^{(k+1)} = Bx^{(k)} + f, k= 0,1,...,\\
\end{cases}
$$
其中$B=I-D^{-1}A=D^{-1}(L+U)=J, f=D^{-1}b$,称J为解Ax=b的雅可比迭代法的迭代矩阵。
解Ax=b的雅可比迭代法的计算公式为:
$$
\begin{cases}
x^{(0)} = (x_1^{(0)},x_2^{(0)},...,x_n^{(0)})^T \\
x_i^{(k+1)} = (b_i - \sum_{j=1,j \neq i}^na_{ij}x_j^{(k)}) / a_{ii},\\
i = 1,2,...,n; k=0,1,...表示迭代次数。\\
\end{cases}
$$
根据上述计算公式就可以使用雅可比迭代法求解了。
### 代码实现
Matlab代码:
```matlab
% 雅可比迭代法
function[xn]=jacobi(A,b,max)
n=size(A,1);
eps = 0.000001;
% 默认最大迭代次数
if nargin == 2
max = 200;
end
% 初始化向量
x0=zeros(n,1);
xn=zeros(n,1);
x0(1)=1;
times = 0; % 记录迭代次数
while norm(xn-x0)>=eps && times <= max
times=times+1;
x0=xn;
for i=1:n
sum = 0;
for j =1:n
if (j~=i)
sum = sum + A(i,j) * x0(j);
end
end
xn(i)=(b(i)-sum)/A(i,i);
end
if(times>=max)
return;
end
end
% 输出迭代次数和结果
disp(times);
disp(xn);
```
---
## 高斯赛德尔迭代法(Gauss-Seidel Method)
### 分析
  **高斯-赛德尔迭代法**可以看作是对雅可比迭代法的优化改进。它的思路在于,更新每一步$x_k$的时候,可以利用已经更新$x_j(j < k)$的值,这样可以减少迭代次数,因为它计算每一个分量的时候是基于当前的最新分量。
设$a_{ii} \neq 0(i=1,2,...,n)$,可以得到Ax=b的高斯-赛德尔迭代法:
$$
\begin{cases}
x^{(0)}, 初始向量\\
x^{(k+1)} = Bx^{(k)} + f, k= 0,1,...,\\
\end{cases}
$$
其中$B=I-(D-L)^{-1}A=(D-L)^{-1}U=G,f=(D-L)^{-1}b.称G=(D-L)^{-1}U为解Ax=b的高斯赛德尔迭代法的迭代矩阵$。
求解Ax=b的高斯赛德尔迭代法计算公式为
$$
\begin{cases}
x^{(0)} = (x_1^{(0)},x_2^{(0)},...,x_n^{(0)})^T,初始向量 \\
x_i^{(k+1)} = (b_i - \sum_{j=1,j \neq i}^{i-1}a_{ij}x_j^{(k+1)} - \sum_{j=i+1}^na_{ij}x_j^{(k)}) / a_{ii},\\
i = 1,2,...,n; k=0,1,...表示迭代次数。\\
\end{cases}
$$
这就是高斯赛德尔迭代法的计算公式。
### 代码实现
Matlab代码:
```matlab
% 高斯赛德尔迭代法
function[xn]=Gauss_Seidel(A,b, max)
n=size(A,1);
% 默认最大迭代次数
if nargin == 2
max = 200;
end
eps = 0.000001; % 精度控制
% 初始化向量
x0=zeros(n,1);
xn=zeros(n,1);
x0(1)=1;
% 保证有解
if det(A) == 0
return;
end
times = 0; % 迭代次数
while norm(xn-x0)>=eps && times <= max
times=times+1;
x0=xn;
for i=1:n
sum1 = 0;
sum2 = 0;
% 使用新的x
for j =1:i-1
sum1 = sum1 + A(i,j) * xn(j);
end
for j=i+1:n
sum2 = sum2 + A(i,j) * x0(j);
end
xn(i)=(b(i) - sum1 - sum2)/A(i,i);
end
if(times>=max)
return;
end
end
% 输出迭代次数和结果
disp(times);
disp(xn);
```
---
## 超松弛迭代法(Successive Over Relaxation Method)
### 分析
  超松弛迭代法,SOR,是对于高斯赛德尔迭代法的改进。它的关键之处在于松弛因子$\omega$,这个因子可以控制收敛的方向来控制迭代速度和迭代精度。由于迭代速度和迭代精度是相互矛盾的,如果我想得到更快的迭代速度(倾向于向新的x靠近),那么我就有可能偏离了我的正确值;如果我追求迭代精度(倾向于向旧的x靠近)那么,我的迭代速度就很慢。松弛因子$\omega$就是用来调节这两者的,务求找到一个平衡点。这里直接给出SOR的计算方法。
$$
\begin{cases}
x^{(0)} = (x_1^{(0)},x_2^{(0)},...,x_n^{(0)})^T,初始向量 \\
x_i^{(k+1)} = x_i^{(k)} + \omega(b_i - \sum_{j=1}^{i-1}a_{ij}x_j^{(k+1)} - \sum_{j=i}^na_{ij}x_j^{(k)}) / a_{ii},\\
i = 1,2,...,n; k=0,1,...表示迭代次数,\\
\omega 为松弛因子\\
\end{cases}
$$
使用SOR的时候,需要注意的是矩阵A必须是**对称正定矩阵**,同时$0 \lt \omega \lt 2 $。
### 代码实现
Matlab代码:
```matlab
% 超松弛迭代法
function[xn,times]=SOR(A,b,w,max)
n=size(A,1);
eps = 0.00001; % 精度控制
% 最大迭代次数
if nargin == 3
max = 200;
end
%初始化向量
x0=zeros(n,1);
xn=zeros(n,1);
x0(1)=1;
times = 0; % 迭代次数
while norm(xn-x0)>=eps && times <= max
times=times+1;
x0=xn;
for i=1:n
sum1 = 0;
sum2 = 0;
for j =1:i-1
sum1 = sum1 + A(i,j) * xn(j);
end
for j=i:n
sum2 = sum2 + A(i,j) * x0(j);
end
xn(i)=x0(i) + w * (b(i) - sum1 - sum2)/A(i,i);
end
if(times>=max)
return;
end
end
% 输出迭代次数与结果
disp(times);
disp(xn);
```
---
## 共轭梯度法(Conjugate Gradient Method)
### 分析
  谈到共轭梯度法,首先要了解与线性方程组等价的变分问题。
设$A=(a_{ij})\in R^{n \times n}$是**对称正定矩阵**,$b =(b_1, b_2, \cdots, b_n)^T$,求解的线性方程组为Ax=b。考虑如下定义的二次函数$$\varphi(x) = \frac12(Ax,x) - (b,x)$$,该函数等价于对应的线性方程组。
性质1: 对一切$x\in R^n, \varphi(x)$的梯度为
$$\nabla \varphi(x) = Ax - b$$
性质2: 对一切$x,y\in R^n$及$\alpha \in R$,
$$
\varphi(x+\alpha y) = \frac12(A(x+\alpha y),x+\alpha y) - (b,x+\alpha y) \\ = \varphi(x)+\alpha(Ax-b,y)+\frac{\alpha^2}{2}(Ay,y)
$$
性质3:设$x^* = A^{-1}b$是线性方程组Ax=b的解,则
$$
\varphi(x^*)=-\frac12(b,A^{-1}b) = -\frac12(Ax^*,x^*)
$$,
且对一切$x\in R^n$,有
$$
\varphi(x) - \varphi(x^*) = \frac12(Ax,x) - (Ax^*,x) + \frac12(Ax^*, x^*) \\ = \frac12(A(x-x^*),x-x^*)
$$
根据上述二次函数的性质,我们可以知道,当$x^*$为令$\varphi(x)$最小时,$x^*$是该方程的解。这样,我们就把求解矩阵的问题转化为求解二次函数极小值点的问题
共轭梯度法的思想是,对于初始的一个x,使用方向$p^{(0)},p^{(1)},...,p^{(k-1)}$进行k次搜索,求得$x^{(k)}$,然后确定$p^{(k)}$的方向,这样能使x^{(k+1)}更快地求得$x^*$。其主要迭代公式为:
$$
x^{(k+1)} = x^{(k)} + \alpha_kp^{(k)}, \\
x^{(k)} = \alpha_0p^{(0)} + \alpha_1p^{(1)} + \cdots + \alpha_{k-1}p^{(k-1)}。
$$
\alpha_k的值可以根据如下公式计算:
因为我们每步的求解过程中,都需要基于当前的x,求出下一个极小值,即
$$
\varphi(x^{(k+1)}) = \min_{\alpha \in R}\varphi(x^{(k)} + \alpha p^{(k)})
$$,
由于
$$
\varphi(x^{(k)} + \alpha p^{(k)}) = \varphi(x^{(k)}) + \alpha(Ax^{(k)}-b, p^{(k)}) + \frac{\alpha^2}{2}(Ap^{(k)},p^{(k)})
$$,
对上式求导,求出极小值
$$
\frac{d\varphi(x^{(k)} + \alpha p^{(k)})}{d \alpha} = (Ax^{(k)} - b, p^{(k)}) + \alpha(Ap^{(k)}, p^{(k)}) = 0,
$$
解得
$$
\alpha_k = -\frac{(Ax^{(k)} - b, p^{(k)})}{(Ap^{(k)},p^{(k)})}
$$
又因为我们希望$p^{(k)}$能使$x^{(k+1)}$能够更快地求得$x^*$,因此我们有
$$
\varphi(x^{(k+1)}) = \min_{x\in span\{ p^{(0)},p^{(1)},\cdots,p^{(k)} \}}\varphi(x)
$$,
然后我们把x分解成$x=y+\alpha p^{(k)}$,所以得到
$$
\varphi(x)=\varphi(y+\alpha p^{(k)} = \varphi(y) - \alpha(Ay, p^{(k)}) - \alpha(b,p^{(k)}) + \frac{\alpha^2}{2}(Ap^{(k)}, p^{(k)})
$$,
由于我们需要对x求导,又因为x用y来表示,所以对y求偏导。因为要为0,所以交叉项$(Ay,p^{(k)})$必须为0,这样一组向量p称为**共轭向量**。
以上就是对于共轭梯度法的核心思想的分析。下面直接给出算法:
(1)任取初始向量$x^{(0)}$,一般取为0,计算$r^{(0)} = b-Ax^{(0)$,取$p^{(0)}} = r^{(0)}$.
(2)对$k=0,1,\cdots,$计算
$$
\alpha_k = \frac{(r^{(k)},r^{(k)})}{(p^{(k)}, Ap^{(k)})} \\
x^{(k+1)} = x^{(k)} + \alpha_kp^{(k)} \\
r^{(k+1)} = r^{(k)} - \alpha_kAp^{(k)}, \beta_k = \frac{(r^{(k+1)},r^{(k+1)})}{(r^{(k)},r^{(k)})} \\
p^{(k+1)} = r^{(k+1)} + \beta p^{(k)}
$$
(3)若$r^{(k)}=0$,或$(p^{(k)}, Ap^{(k)}) = 0$,则计算停止,得出结果。
这就是共轭梯度法的简要算法分析。
### 代码实现
Matlab代码:
```matlab
% 共轭梯度法
function[x] = CG(A,b,max)
% 初始化向量
n = size(A,1);
x0 = zeros(n,1);
r0=b-A*x0;
p0=r0;
% 最大迭代次数
if nargin == 2
max = 200;
end
eps = 1.0e-6; % 精度控制
times = 0; % 迭代次数
while 1
if ((abs(p0) < eps))
break;
end
if (times > max)
break;
end
times = times + 1;
a0 = (r0' * r0) / (p0' * A*p0);
x1 = x0 + a0*p0;
r1 = r0 - a0*A*p0;
b0 = (r1'*r1)/(r0'*r0);
p1 = r1 + b0 *p0;
x0 = x1;
r0 = r1;
p0 = p1;
end
x = x0;
end
```
## 小结
### 四个算法的时间比较
对比四种算法对同一个矩阵的求解计算时间:
n = 10
| 方法 | 时间 |
|:----:|:----:|
| 雅可比迭代法 | 0.0002|
| 高斯赛德尔迭代法 |0.0003|
| SOR迭代法 |0.0003|
| 共轭梯度法 |0.0001|
n = 100
| 方法 | 时间 |
|:----:|:----:|
| 雅可比迭代法 | 0.0053|
| 高斯赛德尔迭代法 |0.0044|
| SOR迭代法 |0.0048|
| 共轭梯度法 |0.0040|
n = 200
| 方法 | 时间 |
|:----:|:----:|
| 雅可比迭代法 | 0.0254|
| 高斯赛德尔迭代法 |0.0128|
| SOR迭代法 |0.0120|
| 共轭梯度法 |0.0036|
可以看出,迭代法的计算速度普遍较快,尤其是计算高维矩阵的时候,优势更加明显。其中,共轭梯度法的计算速度最快。
### $\omega$对迭代速度的影响
这个测试是为了研究不同的$\omega$对SOR的速度的影响。这里采用测量迭代次数的方法,即对于不同omega,看看哪个算法的误差小于某个指定的值,记录当时的迭代次数,对于每次迭代我给了最高的迭代次数500。
结果如下:

从图中可以看出,对于测试用的这个矩阵,最佳的松弛因子$\omega$约为1.5。对于不同的矩阵,最佳松弛因子是不同的。
  以上就是四种求解大型稀疏矩阵的迭代法的分析与实现,同时我也对算法的性能做出了简单的评估,谢谢!
---
#### 参考资料:
1.数值分析(第5版) 李庆扬,王能超,易大义 *编
|
Java
|
UTF-8
| 689
| 2.671875
| 3
|
[] |
no_license
|
package imd.thiyagu.taku.ImageUtils;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
/**
* Created by thiyagu on 12/12/2017.
*/
public class ImageUtils {
public static Bitmap scaleBitmap(Bitmap bitmap, int wantedWidth, int wantedHeight) {
Bitmap output = Bitmap.createBitmap(wantedWidth, wantedHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
Matrix m = new Matrix();
m.setScale((float) wantedWidth / bitmap.getWidth(), (float) wantedHeight / bitmap.getHeight());
canvas.drawBitmap(bitmap, m, new Paint());
return output;
}
}
|
Python
|
UTF-8
| 5,127
| 2.546875
| 3
|
[
"Apache-2.0"
] |
permissive
|
"""
K.Srinivas, 12-Jun-2018
Project: BCS Projects
Description: This is special one-time use program to upload "targetSet" field from XLS-files to the goals
Approach is as follows:
a) loadfromxls.py handles all the XLS-file reading part, from hard-coded directory structure
b) This application calls methods from loadfromxls and updates the goals in DB by referring HRMS-emp-data
c) This is written to be incrementally re-executable. Once processed, the goal-sheet XLS is moved to "processed".
Re-executing with the same data causes goal-sheets to be deleted and re-assigned.
d) On the URL, dc=True/False and notify=True/False are evaluated and handled accordingly.
TODO:
a) Implement "notify=True/False".
b) need to re-excute for final run with notify=True
KNOWN BUGs: None
"""
import logging
from flask_wtf import FlaskForm
from wtforms import *
from wtforms.validators import DataRequired
from flask_login import login_required , current_user
from wtforms.fields import StringField, SelectField
from wtforms.widgets import TextArea
from flask import Flask, url_for
#ForFileUpload
from flask import send_from_directory, render_template, redirect, request, flash
from werkzeug import secure_filename
from flask_sqlalchemy import SQLAlchemy
from goalmodel import *
from realapp import app, db
from loadfromxls import *
from hrmsdomain import getEmployeebyId
from goaldomain import deleteGoalSheet, assignTemplate, getAllGoalsAndSections, createTask
from notification import notify
#Temp, ONE-TIME use Target for uploading Targets-Set from XLS-files to DB
#Lot of Hard-Coding, not expected to be used more than once
@app.route('/goals/uploadtargets', methods=['GET'])
def uploadTargets() :
dc = request.args.get('dc')
print("dc=" + dc)
dc = eval(dc)
#Read and process all files, link to HRMS data
(flist, empList, valDictList) = getValidatedList(dc)
## Now we have empNo both in File and HRMS
print("Processing %d employees..." %(len(flist)))
for i in range(0, len(flist) ) : # Loop through all legitimate entries
#Delete goal-sheet if it exists
# print("Deleting...")
deleteGoalSheetIfPresent(empList[i])
#Select Template (dc=True)
tempId = 1 # Line Employees
if dc : tempId = 2 # DC Leads
#Assign goal-sheet
managerEmail ="srinivas.kambhampati@msg-global.com" # Assigning manager
# print("Assigning...")
assignTemplate(empList[i].OFFICE_EMAIL_ID, tempId, managerEmail, '2018-2019', notify=False)
#Update target-set from valDict
#get the goals
(sheet, allgoalsections , allgoals) = getAllGoalsAndSections(empList[i].EMPLOYEE_ID, '2018-2019')
if not allgoals:
app.logger.info("No Goals, something went wrong:" + flist[i])
continue
if sheet :
goalSheetId = sheet.id
else :
app.logger.info("No Goalsheet, something went wrong:" + flist[i])
continue
print("Updating targets in:" + flist[i])
for gs in allgoals : #set the target for each goal
for g in gs :
gid = g.id
tarSet = valDictList[i][g.templateId] # Template ID is the Master-Goal ID
if tarSet:
tarSet = str(tarSet)
g.targetSet =tarSet[0:498] # Limit it to first 500 Chars, ignore the rest.(Only Rahul)
# Add targetSet as a task [Feedback from Sridhar]
db.session.add(createTask(g, desc =tarSet[0:998] , cstatus = "Approved"))
db.session.commit() # Save all goals
moveFileToProcessed(flist[i], dc)
return str(flist)
#If a goal-sheet/goal exists for a person, delete it, recursively.
def deleteGoalSheetIfPresent(emp) :
deleteGoalSheet(emp.OFFICE_EMAIL_ID) # Simply ignore the return string
return
def getValidatedList(dc) :
flist = readGoalFiles(dc)
retList = []
retEmpList = []
valDictList = []
app.logger.info("processing %d files..." % (len(flist)))
for goalFile in flist :
(valDict, empNo) = readGoalSheetFile(goalFile, dc)
if empNo :
#Get emp Object?
emp = getEmployeebyId(empNo)
if not emp :
print("File %s : Emp. not in HRMS:%s" % (goalFile, empNo))
continue
else :
print("No emp. no in file:%s" % (goalFile))
continue
retList += [goalFile]
retEmpList += [emp]
valDictList += [valDict]
return (retList, retEmpList, valDictList)
#To notify ALL employees once again that a goal-sheet is assigned to them
from emailstrings import *
@app.route('/goals/resendnotification', methods=['GET'])
def notifyAllGoalSheet() :
empMessage = goalAssignResend %('2018-2019')
gsList = getGoalSheetsAll()
for sheet in gsList:
eid = str(sheet.empId)
emp = getEmployeebyId(sheet.empId)
if emp :
empEmail = emp.OFFICE_EMAIL_ID
print("Notifying:" + str(empEmail))
notify(empEmail,goalEmailSubject, empMessage , templateId="-1")
return("Done")
|
C++
|
UTF-8
| 12,590
| 2.78125
| 3
|
[] |
no_license
|
// OpenGL main program
// contains
// control of animation/simulation module: singel step, continuous run, etc.
// graphics API initialization and setup (OpenGl in this case): camera, lights, display
// user interface handling of mouse and keyboard
// =================================================================================
// STANDARD INCLUDES
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <GL/glut.h>
#include <math.h>
// LAB SPECIFIC
#include "./animate.h"
// =================================================================================
// STANDARD DEFINES
// Mode
#define STEP 1
#define RUN 2
// =================================================================================
// TYPEDEFS
// CAMERA
typedef struct camera_struct {
// polar coordinates controlled by interface
float distance; // distance
float theta; // angle around y-axis from positive x-axis (0:360)
float phi; // angle up from x-z plane (-180:+180)
// view parameters
float x,y,z; // location
// in case user interface is expanded to support more info
float cx,cy,cz; // center of interest
float tilt; // rotation around view direction
} camera_td;
// =================================================================================
// PROTOTYPE FUNCTIONS
void display(void);
void timedDisplay(int value);
void displayInitialize();
void displayReshape(int w, int h);
void graphicsInitialize(void);
void lightsInitialize();
void lightsPosition();
void cameraInitialize();
void cameraComputeParameters();
void keyboardParse(unsigned char key, int x, int y);
void keyboardParseSpecial(int key, int x, int y);
void mouseProcessButtons(int button, int state, int x, int y);
void mouseProcessActiveMotion (int x,int y);
// =================================================================================
// GLOBALS for display and interactiion
camera_td camera;
//int mode = STEP; // single step or continuous run
int mode = RUN;
int debug = 0; // debug flag
int fps = 30; // frames per second - for animation/simulation
// =================================================================================
// DEFINES
// Buttons for user interaction
#define LEFT 1
#define MIDDLE 2
#define RIGHT 3
// Constants
#define PI 3.14159
#define EPSILON 0.0001
// =================================================================================
// MAIN
// =================================================================================
int main(int argc, char** argv)
{
// initialize glut and window
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowPosition(40, 40);
glutInitWindowSize(640, 480);
glutCreateWindow("Animate");
// setup callbacks
glutDisplayFunc(display);
glutReshapeFunc(displayReshape);
glutKeyboardFunc(keyboardParse);
glutSpecialFunc(keyboardParseSpecial);
glutMouseFunc(mouseProcessButtons);
glutMotionFunc(mouseProcessActiveMotion);
glutTimerFunc(1000/fps,timedDisplay,0);
//glutIdleFunc(timedDisplay);
// initialize stuff
graphicsInitialize();
Animation_init();
cameraInitialize();
// execute
glutMainLoop();
return EXIT_SUCCESS;
}
// =================================================================================
// =================================================================================
// ROUTINES to MANAGE DISPLAY
// ---------------------------------------------------------------------------
// DISPLAY
// ---------------------------------------------------------------------------
void display(void)
{
if (debug == 1) printf("display\n");
if (mode == STEP) {
displayInitialize();
Animation_render();
// force out and swap buffers
glFlush();
glutSwapBuffers();
}
}
// ---------------------------------------------------------------------------
// TIMED DISPLAY
// ---------------------------------------------------------------------------
void timedDisplay(int value)
{
static int debugMode = 0;
if ((debug - debugMode) == 1) printf("timed display\n");
debugMode = debug;
displayInitialize();
Animation_update();
Animation_render();
// force out and swap buffers
glFlush();
glutSwapBuffers();
if (mode == RUN) glutTimerFunc(1000/fps,timedDisplay,0);
}
// ---------------------------------------------------------------------------
// INITIALIZE DISPLAY
// needs to be called each time the scene is to be rendered:
// clears OpenGL buffer
// resets transformation matrix
// sets camera and lights in OpenGL
// ---------------------------------------------------------------------------
void displayInitialize()
{
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear buffer
glLoadIdentity();
gluLookAt(camera.x,camera.y,camera.z,camera.cx,camera.cy,camera.cz,0.0,1.0,0.0);
lightsPosition();
}
// ---------------------------------------------------------------------------
// RESHAPE
// ---------------------------------------------------------------------------
void displayReshape(int width, int height)
{
glViewport(0, 0, width, height);
}
// =================================================================================
// =================================================================================
// ROUTINES to setup GRAPHICS ENVIRONMENT
// ---------------------------------------------------------------------------
// INITIALIZE GRAPHICS
// only needs to be done once at beginning of program
// ---------------------------------------------------------------------------
void graphicsInitialize (void)
{
glShadeModel (GL_SMOOTH);
glFrontFace(GL_CCW);
glEnable(GL_DEPTH_TEST);
glClearColor(0.2,0.2,0.8,1.0);
glColor3f(1.0, 1.0, 1.0);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum (-0.1, 0.1, -0.1, 0.1, 0.2, 550.0);
//gluOrtho2D(0,100, 0,100);
glMatrixMode(GL_MODELVIEW);
lightsInitialize();
}
// ---------------------------------------------------------------------------
// CAMERA COMPUTE PARAMETERS
// should be called any time a camera parameter changes
// ---------------------------------------------------------------------------
void cameraComputeParameters(void)
{
float radiusOut;
// rotate up
radiusOut = cos(camera.theta);
camera.y = camera.distance*sin(camera.theta);
// rotate around y-axis
camera.x = camera.distance*cos(camera.phi)*radiusOut;
camera.z = camera.distance*sin(camera.phi)*radiusOut;
}
// ---------------------------------------------------------------------------
// CAMERA INITIALIZE
// initialize view parameters for camera
// only needs to be done once at begining or if a 'reset' is requested
// ---------------------------------------------------------------------------
void cameraInitialize ()
{
// constant parameters
camera.tilt = 0.0;
camera.cx = 0.0; camera.cy = 0.0; camera.cz = 0.0;
// initial polar coordinates
camera.distance = 50.0;
camera.phi = PI/2.0;
camera.theta = 0;//PI/2.0;
// extract camera coordinates
cameraComputeParameters();
glutPostRedisplay();
}
// ---------------------------------------------------------------------------
// INITIALIZE LIGHTS
// called each time a scene is to be rendered
// ---------------------------------------------------------------------------
#define AMBIENT0 0.5
#define DIFFUSE0 0.5
#define SPECULAR0 0.1
#define AMBIENT1 0.5
#define DIFFUSE1 0.5
#define SPECULAR1 0.1
void lightsInitialize()
{
GLfloat light0_ambient[] = { AMBIENT0,AMBIENT0,AMBIENT0,1.0 };
GLfloat light0_diffuse[] = { DIFFUSE0,DIFFUSE0,DIFFUSE0,1.0 };
GLfloat light0_specular[] = { SPECULAR0,SPECULAR0,SPECULAR0,1.0 };
GLfloat light1_ambient[] = { AMBIENT1,AMBIENT1,AMBIENT1,1.0 };
GLfloat light1_diffuse[] = { DIFFUSE1,DIFFUSE1,DIFFUSE1,1.0 };
GLfloat light1_specular[] = { SPECULAR1,SPECULAR1,SPECULAR1,1.0 };
//glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_AMBIENT, light0_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light0_diffuse);
glLightfv(GL_LIGHT0, GL_SPECULAR,light0_specular);
glEnable(GL_LIGHT1);
glLightfv(GL_LIGHT1, GL_AMBIENT, light1_ambient);
glLightfv(GL_LIGHT1, GL_DIFFUSE, light1_diffuse);
glLightfv(GL_LIGHT1, GL_SPECULAR,light1_specular);
}
// ---------------------------------------------------------------------------
// POSITION LIGHTS
// called each time a scene is to be rendered
// ---------------------------------------------------------------------------
void lightsPosition()
{
GLfloat light0_position[] = { 0.0, 10.0, 3.0, 1.0 };
GLfloat light1_position[] = { -5.0,-10.0,2.0,1.0 };
glLightfv(GL_LIGHT0, GL_POSITION,light0_position);
glLightfv(GL_LIGHT1, GL_POSITION,light1_position);
}
// =================================================================================
// =================================================================================
// ROUTINES to MANAGE INTERACTION
// ---------------------------------------------------------------------------
// PARSE KEY
// ---------------------------------------------------------------------------
void keyboardParse(unsigned char key, int x, int y)
{
switch (key) {
case 27: exit(0); // cntrl-Q
case 'v': // v: reset view
cameraInitialize();
cameraComputeParameters();
glutPostRedisplay();
break;
case 'q': // q: quit
exit(1);
case 'd': // d: toggle debug
debug = 1 - debug;
if (debug == 0) printf("debug off\n");
else printf("debug on\n");
break;
case 'r': // r: reset
fps = 30;
Animation_reset();
glutPostRedisplay();
break;
case 's': // s: single step
if ((mode != STEP) && (debug == 1)) printf("mode = STEP\n");
mode = STEP;
Animation_update();
glutPostRedisplay();
break;
case 'c': // c: continuous run
if (mode != RUN) {
mode = RUN;
if (debug == 1) printf("mode = RUN\n");
glutTimerFunc(1000/fps,timedDisplay,0);
}
break;
case 'h': // h: help
printf("\n");
printf("mouse movement\n");
printf("left mouse button down -> rotate around origin\n");
printf("middle mouse button down -> zoom in and out\n");
printf("\n");
printf("keys\n");
printf("---\n");
printf("d: toggle debug\n");
printf("s: single step\n");
printf("c: continuous run\n");
printf("r: reset parameters\n");
printf("q: quit\n");
printf("v: view reset\n");
printf("h: help\n");
break;
case '+': // +: speed up
if (debug == 1) printf("speed up\n");
fps = 2*fps;
break;
case '-': // -: slow down
if (debug == 1) printf("slow down\n");
fps = fps/2;
break;
default:
printf("%d\n",key);
}
}
// ---------------------------------------------------------------------------
// PARSE SPECIAL KEY
// ---------------------------------------------------------------------------
void keyboardParseSpecial(int key, int x, int y)
{
switch (key) {
case GLUT_KEY_UP: camera.theta -= 0.25; break;
case GLUT_KEY_DOWN: camera.theta += 0.25; break;
case GLUT_KEY_RIGHT: camera.phi += 0.25; break;
case GLUT_KEY_LEFT: camera.phi -= 0.25; break;
}
cameraComputeParameters();
glutPostRedisplay();
}
int mousex,mousey;
float eyeD,eyeA,eyeT;
int buttonDown;
// ---------------------------------------------------------------------------
// PROCESS MOUSE
// when down, use to control rotation of camera around origin
// ---------------------------------------------------------------------------
void mouseProcessButtons(int button, int state, int x, int y)
{
if (state == GLUT_DOWN) {
if (button == GLUT_LEFT_BUTTON) {
buttonDown = LEFT;
eyeA = camera.phi;
eyeT = camera.theta;
}
else if (button == GLUT_MIDDLE_BUTTON) {
buttonDown = MIDDLE;
eyeD = camera.distance;
}
else {
buttonDown = RIGHT;
}
mousex = x; mousey = y;
}
}
// ---------------------------------------------------------------------------
// PROCESS MOUSE ACTIVE MOTION
// ---------------------------------------------------------------------------
void mouseProcessActiveMotion (int x,int y)
{
if (buttonDown == LEFT) {
// angle around
camera.phi = eyeA + 0.005*(x - mousex);
// angle up and down
camera.theta = eyeT + 0.005*(y - mousey);
if (camera.theta >= PI/2) camera.theta = PI/2 - EPSILON;
if (camera.theta <= -PI/2) camera.theta = -(PI/2 - EPSILON);
}
else if (buttonDown == MIDDLE) {
camera.distance = eyeD*(1.0 + (y - mousey)/500.0);
}
cameraComputeParameters();
glutPostRedisplay();
}
|
Java
|
UTF-8
| 643
| 2.140625
| 2
|
[] |
no_license
|
package example.impl;
import com.google.protobuf.RpcCallback;
import com.google.protobuf.RpcController;
import log.Log;
import log.LogCategory;
import example.proto.Login;
public class LoginServiceImpl extends Login.LoginService {
@Override
public void login(RpcController controller, Login.LoginRequest request, RpcCallback<Login.LoginResponse> done) {
Log.info(LogCategory.Client, request.getUser());
Log.info(LogCategory.Client, request.getPassword());
Login.LoginResponse.Builder builder = Login.LoginResponse.newBuilder();
builder.setResult("success");
done.run(builder.build());
}
}
|
Markdown
|
UTF-8
| 3,181
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
---
layout: post
title: "The Purple Parade - featuring Zui Young"
permalink: "/media/technews/the-purple-parade-featuring-zuiyoung"
category: technews
image: "images/technews/Zuiyoung1.jpg"
---
Zui Young was born with high astigmatism in his right eye and is only able to see with the right eye. But he never once lost sight of his passion for all things digital.
This GovTechie's interest in computers started during his primary school days when he was introduced to coding with the HTML language and Microsoft FrontPage. That led him to learn programming in secondary school, then to a Diploma in Business Information Technology at Singapore Polytechnic, and Bachelors and Masters in Information Systems at Singapore Management University.
An internship with the then-Infocomm Development Authority (IDA) landed him a full-time job after graduation. Zui Young credits his parents – who supported his interest in coding by buying him computers, software and computer magazines – for his achievements.
---

*Zui Young is logging it!
Photo by GovTech*
Today, Zui Young works at GovTech as a Senior DevOps Engineer and takes great pride in his work. For him, the job is a way to use technology to positively impact the lives of fellow citizens. Zui Young builds digital government services that improves our lifestyles.
Some of the work Zui Young is proudest of are the projects he and his team worked on during these two years living with Covid-19. They dabbled with the idea of Bluetooth contact tracing which became the TraceTogether app, and worked on the rapid design, implementation and support of SafeEntry for contact tracing. His team also created SupplyAlly, which helped to accelerate the distribution of essential goods such as masks and TraceTogether tokens nationwide.
“I feel it’s important for managers (or) leaders to provide opportunities for staff to be bold and be empowered to take on new challenges and be innovative, especially in the ongoing technological revolution. It makes a career that much more meaningful too,” he said.
Zui Young is a recent recipient of the Goh Chok Tong Enable Awards (UBS Promise) and said he is glad to be seen as a role model for persons with disabilities. Going forward, he wants to help the community by using his abilities in software engineering to ensure that Singapore’s digital services are user-friendly for people of all walks of life, and that those with disabilities are not left out of the rapid digitalisation effort.
*This article first appeared on The Purple Parade's website. The Purple Parade supports inclusion and celebrates abilities of persons with disabilities. [Read more about The Purple Parade Here.](https://www.purpleparade.sg/)*
*Enjoyed this article? Check out this [article to see how tech has uplifted Singapore in a difficult year](https://www.tech.gov.sg/media/technews/how-tech-has-connected-and-uplifted-singapore-in-a-difficult-year) or this article where we find out why a [GovTechie moved from Silicon Valley to Singapore's](https://www.tech.gov.sg/media/technews/from-silicon-valley-to-govtechie) sunny shores.*
|
Markdown
|
UTF-8
| 432
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
---
layout: project_single
title: "Hygge: conheça o estilo de vida que faz a Dinamarca ser o país mais feliz do mundo e 5 maneiras de trazê-lo para casa"
slug: "hygge-conheca-o-estilo-de-vida-que-faz-a-dinamarca-ser-o-pais"
parent: "hygge-interiors-living-room"
---
Hygge é uma palavra dinamarquesa que não tem tradução direta. É um estado de espírito, é aconchego, conforto e bem estar. Confira como aplicar em sua casa.
|
Shell
|
UTF-8
| 340
| 3.03125
| 3
|
[] |
no_license
|
#!/bin/bash
# copy standard file with no values
cp atlas_reorganization/atlas_84regions_reorganized.node temp.node
# pattern to be replaced with values
pattern="&"
#
while read p; do
value=$p
#sed -i 's/'$pattern'/'$value'/' temp.node
sed -i '0,/'$pattern'/s//'$value'/' temp.node # change only the first match
done < values.txt
|
TypeScript
|
UTF-8
| 4,386
| 2.84375
| 3
|
[] |
no_license
|
import { getRepository } from 'typeorm';
import { ITask, TaskDTO } from './task.model';
import { TaskEntity } from '../../entities/Task';
// let Tasks = require('./task.dataBase');
/**
* @typedef task
* @type {Object}
* @property {string} id - id of a task
* @property {string} title - title of a task
* @property {number} order - order of a task
* @property {string} description - description of a task
* @property {string} userId - id of an user who is currently working on that task
* @property {string} boardId - id of a board this task belongs to
* @property {string} columnId - id of a column this task belongs to
*/
/**
* This function finds and returns tasks from certain board by his boardId
* @param {string} boardId - id of a board the tasks belong to
* @returns {Array.<task>} tasks - returns all the tasks in a certain board
*/
const getTasksByBoardId = async (boardId: string): Promise<Array<TaskEntity> | undefined> => {
const taskRepository = getRepository(TaskEntity);
return taskRepository.find({ where: { boardId } }) ;
};
/**
* This function finds and returns a certain task by his boardId and taskId
* @param {string} boardId - id of a board the task belong to
* @param {string} taskId - id of the task
* @returns {task} task - returns a certain the task
*/
const getTaskByBoardAndTaskId = async (boardId: string, taskId: string): Promise<TaskEntity | undefined> => {
const taskRepository = getRepository(TaskEntity);
const res = taskRepository.findOne({ where: { boardId, id: taskId } });
if (res === undefined) return undefined;
return res;
}
/**
* This function creates and returns a new created task
* @param {task} task - task which should be created
* @returns {task} task - returns new created task
*/
const createNewTask = async (task: ITask): Promise<TaskEntity> => {
const taskRepository = getRepository(TaskEntity);
const newTask = taskRepository.create(task);
const savedTask = taskRepository.save(newTask);
return savedTask;
};
/**
* This function updates and returns a task
* @param {string} boardId - id of a board the task belong to
* @param {string} taskId - id of the task
* @param {task} taskData - new values for task properties
* @returns {task|null} updatedTask - returns the updated object of a task or null if the task was not found
*/
const updateTask = async (boardId: string, taskId: string, taskData: TaskDTO): Promise<TaskEntity | null> => {
const taskRepository = getRepository(TaskEntity);
const res = taskRepository.findOne({ where: { boardId, id: taskId } });
if (res === undefined) return null;
await taskRepository.update(taskId, taskData);
const updatedTask = await taskRepository.findOne({ where: { id: taskId } });
// @ts-ignore
return updatedTask;
};
/**
* This function deletes a certain task
* @param {string} boardId - id of a board the task belong to
* @param {string} taskId - id of the task
* @returns {task|null} task - returns the deleted task or null if the task was not found
*/
const deleteTask = async (boardId: string, taskId: string): Promise<TaskEntity | null> => {
const taskRepository = getRepository(TaskEntity);
const res = taskRepository.findOne({ where: { boardId, id: taskId } });
if (res === undefined) return null;
const deletedTask = await taskRepository.findOne({ where: { id: taskId } });
await taskRepository.delete(taskId);
// @ts-ignore
return deletedTask;
};
/**
* This function sets a property "userId" to null by each task a deleted user was related with
* @param {string} id - id of the deleted user
* @returns {void}
*/
const unassignUser = async (id: string): Promise<void> => {
const taskRepository = getRepository(TaskEntity);
await taskRepository.update({ userId: id }, { userId: null });
};
/**
* This function deletes all task which belonged to a deleted board
* @param {string} id - id of the deleted board
* @returns {void}
*/
const deleteAllTasksByBoardId = async (id: string): Promise<void> => {
const taskRepository = getRepository(TaskEntity);
const allTasks = await taskRepository.find({ where: { boardId: id } });
await taskRepository.remove(allTasks);
};
module.exports = { getTasksByBoardId, getTaskByBoardAndTaskId, createNewTask, updateTask, deleteTask, unassignUser, deleteAllTasksByBoardId };
export {};
|
C++
|
UTF-8
| 725
| 2.6875
| 3
|
[] |
no_license
|
#include "HASH_STASH.h"
#include "DEVE_STACK.h"
#include "SMART_ARRAY.h"
long hash_f( const void* to_hash, const size_t numof_bytes )
{
assert (to_hash != NULL);
assert (numof_bytes > 0);
long hash = 1;
const size_t byte_move = sizeof (long) - 1;
for (size_t i = 0; i < numof_bytes; i++)
hash = -hash * *((char* )to_hash + i) + hash>>byte_move ^ hash<<1;
return hash;
}
ERR_t check_canaries( void* data, size_t sizeof_data )
{
assert (sizeof_data > sizeof (canary_t) * 2);
if (isBadReadPtr(data))
return BAD_PTR_ERROR;
if (*(canary_t* )data != CANARY_INIT)
return TOP_CANARY_DEAD;
if (*(canary_t* )((int)data + sizeof_data - sizeof (canary_t)) != CANARY_INIT)
return BOT_CANARY_DEAD;
return OK;
}
|
JavaScript
|
UTF-8
| 919
| 2.828125
| 3
|
[] |
no_license
|
//Top Navigation
const tabSelector = document.querySelectorAll('#topnav section>a');
const tabGroup = document.querySelectorAll('[role="group"]');
tabSelector.forEach((item, index) => {
item.addEventListener('mouseenter', e => {
if (item.nextSibling == tabGroup[index]) {
item.nextSibling.classList.add('topnavHover');
}
})
item.addEventListener('mouseleave', e => {
if (item.nextSibling == tabGroup[index]) {
item.nextSibling.classList.remove('topnavHover');
}
})
item.nextSibling.addEventListener('mouseenter', e => {
if (item.nextSibling == tabGroup[index]) {
item.nextSibling.classList.add('topnavHover');
}
})
item.nextSibling.addEventListener('mouseleave', e => {
if (item.nextSibling == tabGroup[index]) {
item.nextSibling.classList.remove('topnavHover');
}
})
})
|
TypeScript
|
UTF-8
| 155
| 2.53125
| 3
|
[] |
no_license
|
export function b(data: string | number[]) {
if (typeof data === "string") return Buffer.from(data);
return Buffer.from(data);
}
b.c = Buffer.concat;
|
Java
|
UTF-8
| 239
| 2.4375
| 2
|
[] |
no_license
|
package com.miaisoft.miscellaneous;
/**
* Created by touhid on 26/09/2014.
*/
public class Loop {
public static void main(String[] args) {
for (int i = 0; i < 17; i++){
System.out.println(i);
}
}
}
|
C#
|
UTF-8
| 1,090
| 2.890625
| 3
|
[] |
no_license
|
using UnityEngine;
public class Rectangule : MonoBehaviour
{
private float ab, ac;
public float x1, x2, x3;
public float y1, y2, y3;
private float height, rectanguleBase, perimeter, area;
void Start()
{
GetBase();
GetHeight();
GetPerimeter();
GetArea();
}
public void GetSide()
{
ab = Mathf.Sqrt(((y2 - y1) * (y2 - y1)) + ((x2 - x1) * (x2 - x1)));
ac = Mathf.Sqrt(((y3 - y1) * (y3 - y1)) + ((x3 - x1) * (x3 - x1)));
}
public void GetBase()
{
rectanguleBase = ab;
Debug.Log("El lado 1 y 3 de tu rectangulo mide" + rectanguleBase);
}
public void GetHeight()
{
height = ac;
Debug.Log("El lado 2 y 4 de tu rectangulo mide" + height);
}
public void GetPerimeter()
{
perimeter = (rectanguleBase * 2) + (height * 2);
Debug.Log("El perimetro de tu rectangulo es" + perimeter);
}
public void GetArea()
{
area = rectanguleBase * height;
Debug.Log("El area de tu rectangulo es" + area);
}
}
|
C
|
UTF-8
| 2,440
| 2.84375
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
/* i2c_ads1015.c -- Test of ADS1015 I2C ADC chip
*
* Copyright (C) 2013 Omer Kilic <omerkilic@gmail.com> - Erlang Solutions
* Copyright (C) 2013 Jeremy Bennett <jeremy.bennett@embecosm.com> - Embecosm Limited
*
* This file is part of pihwm <http://omerk.github.io/pihwm>
*
* 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.
*/
#include <stdio.h>
#include <stdlib.h>
#include "pihwm.h"
/* I2C Address */
#define ADDR 0x48
/* Registers */
#define R_CONV 0x00
#define R_CONF 0x01
#define R_LOTH 0x02
#define R_HITH 0x03
unsigned int
ads1015_read (int fd, unsigned int chan)
{
unsigned char cmd[2], res[2];
/* Set high byte for R_CONF */
switch (chan)
{
case 0:
cmd[0] = 0x40; /* 8'b01000000 */
break;
case 1:
cmd[0] = 0x50; /* 8'b01010000 */
break;
case 2:
cmd[0] = 0x60; /* 8'b01100000 */
break;
case 3:
cmd[0] = 0x70; /* 8'b01110000 */
break;
default:
cmd[0] = 0x00; /* TODO: is this correct? */
break;
}
/* Set low byte for R_CONF */
cmd[1] = 0x83; /* 8'b10000011 */
/* Set R_CONF */
i2c_write (fd, ADDR, (unsigned char[])
{
R_CONF, cmd[0], cmd[1]}
, 3);
delay (10);
/* Point to R_CONV */
i2c_write (fd, ADDR, (unsigned char[])
{
R_CONV}
, 1);
delay (10);
/* Read conversion result */
i2c_read (fd, ADDR, res, 2);
return (unsigned int) (res[0] << 4) | (res[1] >> 4);
}
double
ads1015_volt (unsigned int val)
{
return ((6.144 / 4096) * val) * 2;
}
int
main ()
{
int fd;
unsigned int res, i, j;
double volt;
/* Init I2C bus */
fd = i2c_init ();
if ( fd < 0 ) {
printf("ERROR: Can't initialise I2C bus.\n");
exit(1);
}
for (i = 0; i < 4; i++)
{
printf ("Channel %d\n", i);
for (j = 0; j < 5; j++)
{
res = ads1015_read (fd, i);
volt = ads1015_volt (res);
printf ("Raw: %4d\tVolt: %1.4f\n", res, volt);
delay (1000);
}
printf ("------\n");
}
return 0;
}
|
C#
|
UTF-8
| 20,699
| 3.0625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FinchAPI;
using static System.Net.Mime.MediaTypeNames;
namespace CapstoneProject
{
class Program
{
public static object DisplayGetMagicSource { get; private set; }
static void Main(string[] args)
{
//************************************
//Title: Final Capstone Project
//Application Type: Console App
//Description: Text Based Adventure Game
//Author: Christos Piliafas
//Date Created: December 1st, 2018
//Last Modified: December 6th, 2018
//************************************
//
// list variables here
//
string userName;
string magicType;
string magicSource;
string userSpecies;
string companion;
int powerLevel;
Finch edi = new Finch();
//
// instantiate list of allies
//
List<string> allies = new List<string>();
allies.Add("Barik the Barbarian");
allies.Add("Vivian the Mage");
allies.Add("Gary the Golem");
allies.Add("Alice the Rogue");
//
// methods
//
DisplayInitializeFinch(edi);
DisplayOpeningScreen();
userName = DisplayGetUserName();
powerLevel = DisplayGetAgeAndMagicPower();
magicType = DisplayGetMagicType();
magicSource = DisplayGetSourceofMagic(magicType);
userSpecies = DisplayGetSpecies();
companion = DisplayGetCompanion(userName, userSpecies, magicType, powerLevel, magicSource);
DisplayPhase1(userSpecies, companion, powerLevel, magicType, edi);
DisplayPhase2(companion, edi);
DisplayPhase3(edi);
DisplayFinalPhase(powerLevel, companion, userName, userSpecies, magicType, edi);
DisplayClosingScreen(edi);
//DisplayGameOver(edi);
//DisplayWin(edi);
}
static void DisplayWin(Finch edi)
{
edi.setLED(0, 255, 0);
edi.noteOn(150);
edi.wait(3000);
edi.setLED(0, 0, 0);
edi.noteOff();
Console.WriteLine("You win!");
Console.ReadKey();
}
static void DisplayFinalPhase(int powerLevel, string companion, string userName, string userSpecies, string magicType, Finch edi)
{
string ally;
//
//
// begin final level
Console.Clear();
Console.WriteLine("\t\t Final Level");
Console.WriteLine();
Console.WriteLine("You travel to the gates of your kingdom, where you run into 4 of your friends who have fought alongside you in the past.");
Console.WriteLine("Unfortunately, the evil sorcerer turned three of them into chickens. Leaving them unable to fight.");
Console.WriteLine("You can only bring one ally to the final battle, choose your ally.");
Console.WriteLine();
Console.WriteLine("\tA) Barik the Barbarian");
Console.WriteLine("\tB) Vivian the Mage");
Console.WriteLine("\tC) Gary the Golem");
Console.WriteLine("\tD) Alice the Rogue");
Console.WriteLine();
Console.Write("Please enter choice (Barik, Vivian, Gary, Alice).");
ally = Console.ReadLine();
switch (ally)
{
case "Barik":
case "barik":
Console.WriteLine();
Console.WriteLine("You choose Barik.");
Console.WriteLine("Barik is an ogre who goes way back with you in the day. He fights with an axe. And despite his size, was able to luckily avoid the evil sorcerer.");
Console.WriteLine("You two head off into battle.");
Console.ReadKey();
break;
case "Vivian":
case "vivian":
Console.WriteLine();
Console.WriteLine("You choose Vivian.");
Console.WriteLine("Vivian is another mage who used to go to the same wizarding school as you, and you became her study buddy.");
Console.WriteLine("She reflected the sorcerer's magic and avoided the humiliating curse. But turned a tree into a chicken in the process.");
Console.WriteLine("You two head off into battle.");
Console.ReadKey();
break;
case "Gary":
case "gary":
Console.WriteLine();
Console.WriteLine("You choose Gary.");
Console.WriteLine("Gary is a grumpy stone golem with an embarassing first name. His stone body prevented the sorcerer's evil curse.");
Console.WriteLine("You two head off into battle.");
Console.ReadKey();
break;
case "Alice":
case "alice":
Console.WriteLine();
Console.WriteLine("You choose Alice.");
Console.WriteLine("Alice is an elf thief who wields daggers. You once caught her trying to steal from you but somehow ended up as friends when you saw potential for good in her.");
Console.WriteLine("Her quick speed made her able to evade the sorcerer's magic.");
Console.WriteLine("You two head off into battle.");
Console.ReadKey();
break;
default:
break;
}
if (powerLevel >= 90)
{
Console.Clear();
Console.WriteLine();
Console.WriteLine($"You, your {companion}, and {ally} were able to overpower the sorcerer and defeat him once and for all.");
Console.WriteLine("All the destruction magically disappeared when the sorcerer died. And everything returned to normal.");
Console.WriteLine($"Everyone then knew the legend of {userName} the {userSpecies} who used their {magicType} to defeat the sorcerer.");
Console.WriteLine($"You, your {companion}, your friend {ally} will be remembered forever as the protectors of your kingdom.");
DisplayWin(edi);
DisplayClosingScreen(edi);
}
else if (powerLevel < 90)
{
Console.Clear();
Console.WriteLine();
Console.WriteLine("You were overpowered by the sorcerer and died.");
Console.WriteLine("Your kingdom was destroyed and everything became terrible.");
DisplayGameOver(edi);
DisplayClosingScreen(edi);
}
Console.ReadKey();
}
static void DisplayPhase3(Finch edi)
{
string menuChoice;
//
//
// begin level 3
Console.Clear();
Console.WriteLine("\t\t Level 3");
Console.WriteLine();
Console.WriteLine("After escaping the castle, you head off into the marketplace to check on the villagers.");
Console.WriteLine("You hear a cry for help coming from one of the 5 nearby buildings that are all on fire.");
Console.WriteLine("You're not sure which building you hear the cry from, but you need to be fast and select only one.");
Console.WriteLine();
Console.WriteLine("\tA) Bakery");
Console.WriteLine("\tB) Armory");
Console.WriteLine("\tC) Schoolhouse");
Console.WriteLine("\tD) The Tavern");
Console.WriteLine("\tE) The Library");
Console.WriteLine();
Console.Write("Please enter choice (A, B, C, D, E).");
menuChoice = Console.ReadLine();
switch (menuChoice)
{
case "A":
case "a":
Console.WriteLine();
Console.WriteLine("There was nobody in the bakery, everyone already escaped!");
Console.WriteLine("Unfortunately, whoever needed your help wasn't able to escape.");
DisplayGameOver(edi);
DisplayClosingScreen(edi);
break;
case "B":
case "b":
Console.WriteLine();
Console.WriteLine("The armory is empty!");
Console.WriteLine("Whoever needed your help wasn't able to escape.");
DisplayGameOver(edi);
DisplayClosingScreen(edi);
break;
case "C":
case "c":
Console.WriteLine();
Console.WriteLine("Fortunately, the schoolhouse is empty.");
Console.WriteLine("Unfortunately, whoever needed your help is dead.");
DisplayGameOver(edi);
DisplayClosingScreen(edi);
break;
case "D":
case "d":
Console.WriteLine();
Console.WriteLine("Inside the tavern, you find a helpless old lady trapped under debri.");
Console.WriteLine("You lift up the debri and find out that she isn't injured, but is having trouble breathing.");
Console.WriteLine("You lift her up and bring her outside the tavern safely, and leave her to the medics.");
Console.WriteLine("You look on ahead and discover a bunch of mayhem going on near the gate.");
Console.WriteLine("You head off to finish this once and for all!");
Console.ReadKey();
break;
case "E":
case "e":
Console.WriteLine();
Console.WriteLine("The library was closed today, nobody was even there to begin with.");
Console.WriteLine("Sadly, whoever needed your help, it's too late for them now.");
DisplayGameOver(edi);
DisplayClosingScreen(edi);
break;
default:
break;
}
}
static void DisplayPhase2(string companion, Finch edi)
{
string answer;
//
//
// begin level 2
Console.Clear();
Console.WriteLine("\t\t Level 2");
Console.WriteLine();
Console.WriteLine("You travel downstairs, but discover the door to outside the castle is locked!");
Console.WriteLine("You look around and find a witch, she cackles loudly and tells you that you can't escape, and that the key is hidden.");
Console.WriteLine("What do you do?");
Console.Write("ATTACK, SEND, RUN");
answer = Console.ReadLine();
if (answer == "attack")
{
Console.WriteLine();
Console.WriteLine("You try to strike her, but she already predicted your attack and knocked you out. By the time you woke up, the kingdom is destroyed and everything is ruined.");
Console.ReadKey();
DisplayGameOver(edi);
DisplayClosingScreen(edi);
}
else if (answer == "send")
{
Console.WriteLine();
Console.WriteLine($"You send out your {companion} and they get the key off the witch, startling her.");
Console.WriteLine($"With the distraction, you are able to take out the witch and get the key back from your {companion}.");
Console.WriteLine("With that, you unlock the door and head into the village to save your people!");
Console.ReadKey();
}
else if (answer == "run")
{
Console.WriteLine();
Console.WriteLine("You run away, back into your room like a coward. What kind of warrior are you?");
Console.WriteLine("Unsurprisingly, the sorcerer takes over and destroys everything.");
Console.ReadKey();
DisplayGameOver(edi);
DisplayClosingScreen(edi);
}
}
static void DisplayGameOver(Finch edi)
{
edi.setLED(255, 0, 0);
edi.noteOn(255);
edi.wait(3000);
edi.setLED(0, 0, 0);
edi.noteOff();
Console.WriteLine("Game over.");
Console.WriteLine("We await your return, warrior.");
Console.ReadKey();
}
static void DisplayPhase1(string userSpecies, string companion, int powerLevel, string magicType, Finch edi)
{
//
//
// begin level 1
Console.Clear();
Console.WriteLine("\t\t Level 1");
Console.WriteLine();
Console.WriteLine($"You are a {userSpecies} from a fantasy kingdom. You are one of the most powerful warriors in the kingdom.");
Console.WriteLine("But, one day, a dark sorcerer began releasing monsters and demons into the kingdom in order to take over!");
Console.WriteLine($"You grab your {companion} and prepare yourself to protect your kingdom!");
Console.WriteLine();
Console.WriteLine("You encounter a demon with a hood wielding daggers within your castle. He's small and pretty thin, but very fast and agile.");
Console.WriteLine("Press any key to determine your fate.");
Console.ReadKey();
if (powerLevel >= 60)
{
Console.WriteLine();
Console.WriteLine($"You slay the demon with your {magicType} magic due to your high power level and spare your valuable antiques from destruction in the process. But that's not the end of it.");
Console.WriteLine("Continue onwards by pressing any key.");
Console.ReadKey();
}
else if (powerLevel < 60)
{
Console.WriteLine("You fell to the small demon, and unfortunately the sorcerer was able to take over with the magic warrior dead.");
DisplayGameOver(edi);
DisplayClosingScreen(edi);
}
}
static void DisplayClosingScreen(Finch edi)
{
Console.Clear();
Console.WriteLine();
Console.WriteLine("\t\tThank you for using my app.");
Console.WriteLine();
Console.WriteLine("\tPress any key to exit, have a nice day.");
Console.ReadKey();
edi.disConnect();
Environment.Exit(0);
}
static string DisplayGetCompanion(string userName, string userSpecies, string magicType, int powerLevel, string magicSource)
{
string companion;
//
// figure out companion
//
Console.WriteLine();
Console.WriteLine("Would you like to have a small dragon or a griffin as your companion?");
companion = Console.ReadLine();
Console.ReadKey();
if (companion == "dragon")
{
Console.WriteLine($"In short, your name is {userName}, you are a {userSpecies}, you dabble in {magicType} as your magic type, and your power level is {powerLevel}, you use a {magicSource}, and your pet companion is a dragon. Awesome! You're set for an adventure!");
}
else if (companion == "griffin")
{
Console.WriteLine($"In short, your name is {userName}, you are a {userSpecies}, you dabble in {magicType} as your magic type, and your power level is {powerLevel}, you use a {magicSource}, and your pet companion is a griffin. Awesome! You're set for an adventure!");
}
else
{
Console.WriteLine("Please re-enter answer.");
}
Console.ReadKey();
return companion;
}
static string DisplayGetSpecies()
{
string userSpecies;
//
// figure out species
//
Console.WriteLine();
Console.WriteLine("Would you like to be an elf, orc, or dwarf?");
userSpecies = Console.ReadLine();
Console.ReadKey();
Console.WriteLine();
Console.WriteLine($"Okay, so you are a {userSpecies}.");
Console.ReadKey();
return userSpecies;
}
static string DisplayGetSourceofMagic(string magicType)
{
string magicSource;
// get magic source
Console.WriteLine();
Console.WriteLine("Would you like to use your magic by a staff, a book, or your own hands?");
magicSource = Console.ReadLine();
Console.ReadKey();
if (magicSource == "staff")
{
Console.WriteLine("Looks like you use a staff to use " + magicType + " magic.");
}
else if (magicSource == "book")
{
Console.WriteLine("Looks like you use a book to use " + magicType + " magic.");
}
else if (magicSource == "hands")
{
Console.WriteLine("Looks like you use your own hands to use " + magicType + " magic.");
}
return magicSource;
}
static void DisplayInitializeFinch(Finch edi)
{
if (edi.connect())
{
Console.WriteLine("Finch is connected. Press any key to begin.");
Console.ReadKey();
}
else
{
Console.WriteLine("Finch is not connected, you won't get the full experience unfortunately. You can still continue anyway.");
Console.ReadKey();
}
}
static string DisplayGetMagicType()
{
string magicType;
//
// figure out favorite magic type
//
Console.WriteLine();
Console.Write("What is your type of magic would you like to use?");
magicType = Console.ReadLine();
Console.ReadKey();
Console.WriteLine("Okay, so you will be a master of " + magicType + ".");
Console.ReadKey();
return magicType;
}
static int DisplayGetAgeAndMagicPower()
{
string userResponse;
int userAge;
string userResponse2;
int powerLevel;
//
// get user age
//
Console.WriteLine();
Console.Write("What is your age?");
userResponse = Console.ReadLine();
userAge = int.Parse(userResponse);
Console.WriteLine();
Console.Write("Based on your age, your magic power is equal to " + userAge * 5 + ".");
//
// get user magic power number
//
Console.WriteLine();
Console.Write("What was your magic power number? (Look back at the previous question)");
userResponse2 = Console.ReadLine();
powerLevel = int.Parse(userResponse2);
//
// continue
//
Console.ReadKey();
return powerLevel;
}
static string DisplayGetUserName()
{
string userName;
//
// get user name
//
Console.Write("What is your name, warrior?");
userName = Console.ReadLine();
Console.WriteLine();
Console.WriteLine($"{userName}, great to meet you.");
Console.ReadKey();
return userName;
}
static void DisplayOpeningScreen()
{
Console.WriteLine();
Console.WriteLine("Welcome to the Capstone Project Fantasy Adventure game! Here, you will go on an adventure through a strange world, have fun and good luck on your adventure!");
Console.WriteLine();
Console.WriteLine("\tPress any key to continue to your character creation page.");
Console.ReadKey();
}
}
}
|
Shell
|
UTF-8
| 2,791
| 3.375
| 3
|
[] |
no_license
|
#!/bin/bash
#16.04.14 V 0.1 Bleifuss
. /usr/lib/vdr/easyvdr-config-loader ## common defines
. /usr/lib/vdr/functions/easyvdr-functions-lib ## common functions
. /usr/share/easyvdr/setup/easyvdr-setup-defines ## setup only defines
. /usr/share/easyvdr/setup/easyvdr-setup-functions ## setup only functions
LOGGER=" logger -t easyvdr-ubuntu-driver-setup"
TITLE=" Setup fuer easyVDR $EASYVDR_VERSION "
BACKTITLE=" Proprietaere Treiber installieren "
DIA_BOX4_SIZE="14 75"
CONNECTOR=$1
dialog --backtitle "$BACKTITLE" --no-cancel --yesno "\n\
Treiber fuer nicht unterstuetze Hardware suchen.\n\
Bitte im Forum Posten welche Hardware verwendet wird.\n\
Da hier der Easyvdr Bereich verlassen wird\n\
ist nicht sicher ob alles funktioniert.\n\
In dem nachfolgenden Dialog NUR die Treiber einstellungen anpassen.\n\
Die Ubuntu Treiber installation starten? \n\n" $DIA_BOX4_SIZE
clear
if [ $? -ne "0" ]; then
exit
fi
############## X beenden
#Terminal merken
VT_KONSOLE_OLD=$(fgconsole) # aktuell aktives Terminal
PID=$(pgrep "easyvdr-runvdr" )
if [ $? -eq 0 ]; then
stop easyvdr-vdr;sleep 1
fi
PID=$(pgrep "easyvdr-runfron" )
if [ $? -eq 0 ]; then
stop easyvdr-frontend;sleep 1
fi
#Stop X
if ( check_x_running ) >/dev/null 2>&1 ; then
stop easyvdr-desktop >/dev/null 2>&1 ; sleep 1
fi
chvt $VT_KONSOLE_OLD # zurueck zur aufrufenden Konsole
###############
echo "" >> $APT_GET_LOG
echo "===> ########################################################################################" >> $APT_GET_LOG
echo "===> `date`: Install software-properties-gtk ..." >> $APT_GET_LOG
debconf-apt-progress --logfile $APT_GET_LOG -- apt-get --yes install software-properties-gtk
AptStatus=$?
echo "#############################################################################################" >> $APT_GET_LOG
echo "" >> $APT_GET_LOG
if [ $AptStatus -ne 0 ];then
dialog --backtitle "$BACKTITLE" --title "$TITLE" --no-cancel --pause "\n\
Ubuntu Treiber Setup kann nicht installiert werden \n\n\
- Weiter - " $DIA_BOX4_SIZE $TIMEOUT
clear
exit
fi
start easyvdr-desktop >/dev/null 2>&1
sleep 1
DISPLAY=:0 software-properties-gtk --no-update --open-tab=4 >/dev/null 2>&1
#Warten bis das Programm beendet wird
while ( check_x_running ) >/dev/null 2>&1
do
sleep 1
if ( ! pidof software-properties-gtk ) >/dev/null 2>&1 ; then
#Stop X
if ( check_x_running ) >/dev/null 2>&1 ; then
stop easyvdr-desktop >/dev/null 2>&1 ;
fi
fi
done
chvt $VT_KONSOLE_OLD # zurueck zur aufrufenden Konsole
#startx "'software-properties-gtk --no-update --open-tab=4'" -- $PRIMARY_DISPLAY >/dev/null 2>&1
|
C#
|
UTF-8
| 4,188
| 2.765625
| 3
|
[] |
no_license
|
using ApiDomain.Entities;
using ApiDomain.Interfaces.Domain.Services;
using ApiDomain.Interfaces.Infraestructure.Services;
using ApiDomain.Shared.Data;
using System.Collections.Generic;
namespace ApiDomain.Services
{
/// <summary>
/// Servicio de datos de la entidad Marca
/// </summary>
public class MarcaService : IMarcaDomainService
{
private readonly IMarcaInfraestructureService _service;
#region CONSTRUCTOR
/// <summary>
/// Constructor
/// </summary>
/// <param name="context">Contexto de base de datos</param>
public MarcaService(IMarcaInfraestructureService service)
{
_service = service;
}
#endregion
#region CREATE
/// <summary>
/// Crea un nuevo elemento
/// </summary>
/// <param name="entity">Entidad con datos</param>
public Marca Create(Marca entity)
{
return _service.Create(entity);
}
/// <summary>
/// Crea un conjunto de elementos nuevos
/// </summary>
/// <param name="entityCollection">Colección de entidades con datos</param>
public void Create(List<Marca> entityCollection)
{
_service.Create(entityCollection);
}
#endregion
#region READ
/// <summary>
/// Obtiene un Marca por su identificador
/// </summary>
/// <param name="id">Identificador de Marca</param>
/// <returns>Marca</returns>
public Marca GetById(int id)
{
return _service.GetById(id);
}
/// <summary>
/// Obtiene un Marca por su identificador
/// </summary>
/// <param name="id">Identificador de Marca</param>
/// <returns>Marca</returns>
public Marca GetById(string id)
{
return _service.GetById(id);
}
/// <summary>
/// Obtiene un Marca por medio de un criterio de búsqueda
/// </summary>
/// <param name="criteria">Criterio de búsqueda</param>
/// <returns>Marca</returns>
public Marca GetByCriteria(ICriteria<Marca> criteria)
{
return _service.GetByCriteria(criteria);
}
/// <summary>
/// Obtiene todas la entidades Marca existentes en el repositorio
/// </summary>
/// <returns>Colección de Marca</returns>
public IList<Marca> GetAll()
{
return _service.GetAll();
}
/// <summary>
/// Obtiene un conjunto de entidades Marca del repositorio por medio de un criterio de búsqueda
/// </summary>
/// <param name="criteria">Criterio de búsqueda</param>
/// <returns>Colección de Marca</returns>
public IList<Marca> GetCollectionByCriteria(ICriteria<Marca> criteria)
{
return _service.GetCollectionByCriteria(criteria);
}
#endregion
#region UPDATE
/// <summary>
/// Actualiza un elemento existente
/// </summary>
/// <param name="entity">Entidad con datos</param>
public void Update(Marca entity)
{
_service.Update(entity);
}
/// <summary>
/// Actualiza un conjunto de elementos existentes
/// </summary>
/// <param name="entityCollection">Colección de entidades con datos</param>
public void Update(List<Marca> entityCollection)
{
_service.Update(entityCollection);
}
#endregion
#region DELETE
/// <summary>
/// Elimina un elemento existente
/// </summary>
/// <param name="entity">Entidad con datos</param>
public void Delete(Marca entity)
{
_service.Delete(entity);
}
/// <summary>
/// Elimina un conjunto de elementos existentes
/// </summary>
/// <param name="entityCollection">Colección de entidades con datos</param>
public void Delete(List<Marca> entityCollection)
{
_service.Delete(entityCollection);
}
#endregion
}
}
|
Python
|
UTF-8
| 1,469
| 3.046875
| 3
|
[] |
no_license
|
"""
AR_XpressoNodeInfo
Author: Arttu Rautio (aturtur)
Website: http://aturtur.com/
Name-US: AR_XpressoNodeInfo
Description-US: Print to console selected Xpresso nodes info. Select Xpresso tag and select nodes and run the script.
Written for Maxon Cinema 4D R20.057
"""
# Libraries
import c4d
# Functions
def main():
doc = c4d.documents.GetActiveDocument() # Get active Cinema 4D document
selected = doc.GetSelection()[0] # Get first item of the selection
if type(selected).__name__ == "XPressoTag": # If operator is xpresso tag
nodeMaster = selected.GetNodeMaster() # Get node master
root = nodeMaster.GetRoot() # Get xpresso root
for c in root.GetChildren(): # Loop through nodes
if c.GetBit(c4d.BIT_ACTIVE): # If node is selected
print "Node: "+c.GetName()+", "+str(c.GetOperatorID()) # Print node info
inPorts = c.GetInPorts() # Get input ports
outPorts = c.GetOutPorts() # Get output ports
for p in range(0, len(inPorts)): # Loop through input ports
print " In port: "+inPorts[p].GetName(c)+", "+str(inPorts[p].GetMainID()) # Print inPort info
for p in range(0, len(outPorts)): # Loop through output ports
print " Out port: "+outPorts[p].GetName(c)+", "+str(outPorts[p].GetMainID())# Print outPort info
c4d.EventAdd() # Refresh Cinema 4D
# Execute main()
if __name__=='__main__':
main()
|
C#
|
UTF-8
| 508
| 3.25
| 3
|
[] |
no_license
|
public class CustomValidationRule : ValidationRule
{
private static bool IsValid(string value)
{
// implement you business rule checking logic here
// if valid
// return true;
// else
// return fase;
}
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
var val = (string)value;
if(IsValid(val))
{
return ValidationResult.ValidResult;
}
else
{
return new ValidationResult(false, "Value is not valid");
}
}
}
|
C++
|
UTF-8
| 1,490
| 3.015625
| 3
|
[
"MIT"
] |
permissive
|
#ifndef SQLBACKUPTOFTPSERVER_EXCEPTION_H
#define SQLBACKUPTOFTPSERVER_EXCEPTION_H
/**
* @file Exception.h
* @author Argishti Ayvazyan (ayvazyan.argishti@gmail.com)
* @brief Declaration of Exception class.
* @date 9/20/2021
* @copyright Copyright (c) 2021
*/
#include <stdexcept>
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace sqlite {
////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* @class Exception
*
* @brief The exception class for handling SQLite errors.
*/
class Exception : public std::runtime_error
{
using error_t = int32_t;
public:
Exception() = default;
~Exception() override = default;
Exception(Exception&&) = default;
Exception(const Exception&) = default;
Exception& operator=(Exception&&) = default;
Exception& operator=(const Exception&) = default;
explicit Exception(const std::string& massage, error_t errorCode) noexcept
: std::runtime_error(massage)
, m_errorCode(errorCode)
{ }
[[nodiscard]] error_t getErrorCode() const noexcept
{
return m_errorCode;
}
private:
error_t m_errorCode;
};
////////////////////////////////////////////////////////////////////////////////////////////////////
} // namespace sqlite
////////////////////////////////////////////////////////////////////////////////////////////////////
#endif // SQLBACKUPTOFTPSERVER_EXCEPTION_H
|
Python
|
UTF-8
| 2,730
| 2.890625
| 3
|
[] |
no_license
|
__author__ = "Maxime CHRIST"
__email__ = "maxime.christ@insa-lyon.fr"
import serial
import io, os, time, threading, json, dateutil.parser
from gps import *
from time import *
gpsd = None #seting the global variable
accelerometer = serial.Serial("/dev/ttyACM0", 9600)
os.system('clear') #clear the terminal (optional)
class GpsPoller(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
global gpsd #bring it in scope
gpsd = gps(mode=WATCH_ENABLE) #starting the stream of info
self.current_value = None
self.running = True #setting the thread running to true
def run(self):
global gpsd
while gpsp.running:
gpsd.next() #this will continue to loop and grab EACH set of gpsd info to clear the buffer
def isNan(num):
return num != num
def cpFile(file_name):
file.write(']')
file.close()
src_path = "/home/pi/Documents/PLDSmartCity/"
dest_path = src_path
src_path += file_name
dest_path += "completedFiles/"
dest_path += file_name
print "Copying",src_path, ' ', dest_path
os.rename(src_path, dest_path)
if __name__ == '__main__':
gpsp = GpsPoller() # create the thread
try:
gpsp.start() # start it up
while True:
data_number = 0
file_name = 'data'
file_name += str(int(time()))
file_name += '.json'
file = open(file_name, 'w')
file.write(unicode("["))
while True:
#It may take a second or two to get good data
#print gpsd.fix.latitude,', ',gpsd.fix.longitude,' Time: ',gpsd.utc
os.system('clear')
acceleration = float(accelerometer.readline())
print ' Acceleration reading'
print '----------------------------------------'
print 'Bump ' , acceleration
print ' GPS reading'
print '----------------------------------------'
print 'latitude ' , gpsd.fix.latitude
print 'longitude ' , gpsd.fix.longitude
print 'time utc ' , gpsd.utc
fulldate = dateutil.parser.parse(gpsd.utc)
#date = '"'
date = fulldate.date()
#date += '"'
if acceleration < 3:
tier = 1
elif acceleration < 6:
tier = 2
elif acceleration < 9:
tier = 3
elif acceleration < 12:
tier = 4
else:
tier = 5
print date
file.write(unicode(json.dumps({"lat":gpsd.fix.latitude,"lng":gpsd.fix.longitude,"date":str(date),"val":tier}, separators=(',',':'))))
data_number += 1
if (data_number > 100):
cpFile(file_name)
break
else:
file.write(',')
except (KeyboardInterrupt, SystemExit): #when you press ctrl+c
file.seek(-1, 1)
file.truncate()
pass
print "Copying last file"
cpFile(file_name)
print "\nKilling Thread..."
gpsp.running = False
gpsp.join() # wait for the thread to finish what it's doing
print "Done.\nExiting."
|
Java
|
UTF-8
| 4,359
| 2.296875
| 2
|
[
"MIT"
] |
permissive
|
package com.wraithavens.conquest.Utility;
import java.io.File;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.opengl.GL11;
import com.wraithavens.conquest.Launcher.MainLoop;
import com.wraithavens.conquest.Launcher.WraithavensConquest;
import com.wraithavens.conquest.Math.MatrixUtils;
import com.wraithavens.conquest.SinglePlayer.RenderHelpers.ShaderProgram;
import com.wraithavens.conquest.SinglePlayer.RenderHelpers.Texture;
public class LoadingScreen{
private static final float SPINNER_SPEED = 2f;
private static final int IMAGE_FLIP_SECONDS = 8;
private LoadingScreenTask task;
private final UiElement spinner;
private final UiElement background;
private final UiElement backgroundOverlay;
private final TextBox completionText;
private final ShaderProgram shader;
private final int fileCount;
private double lastImageTime;
private int lastPictureIndex;
private boolean setup = false;
private int lastPercent;
public LoadingScreen(){
shader = new ShaderProgram("LoadingScreen");
shader.loadUniforms("texture1", "alpha");
shader.setUniform1I(0, 0);
spinner =
new UiElement(Texture.getTexture(new File(WraithavensConquest.assetFolder+File.separatorChar+"Misc",
"Loading Spinner.png")));
background =
new UiElement(Texture.getTexture(new File(WraithavensConquest.loadingScreenImagesFolder,
lastPictureIndex+".png")));
backgroundOverlay = new UiElement(background.texture);
completionText = new TextBox(30, 15);
{
String[] list = new File(WraithavensConquest.loadingScreenImagesFolder).list();
int count = 0;
for(String s : list)
if(s.endsWith(".png"))
count++;
fileCount = count;
lastPictureIndex = (int)(Math.random()*fileCount);
}
{
int screenWidth = WraithavensConquest.INSTANCE.getScreenWidth();
int screenHeight = WraithavensConquest.INSTANCE.getScreenHeight();
spinner.w = 64;
spinner.h = 64;
spinner.x = screenWidth-spinner.w/2f;
spinner.y = spinner.h/2f;
background.w = screenWidth;
background.h = screenHeight;
background.x = screenWidth/2f;
background.y = screenHeight/2f;
backgroundOverlay.w = screenWidth;
backgroundOverlay.h = screenHeight;
backgroundOverlay.x = screenWidth/2f;
backgroundOverlay.y = screenHeight/2f;
completionText.x = screenWidth/2f;
completionText.y = screenHeight/2f;
completionText.w = screenWidth*0.25f;
completionText.h = screenWidth*0.25f;
lastImageTime = GLFW.glfwGetTime();
}
}
public void dispose(){
background.texture.dispose();
backgroundOverlay.texture.dispose();
spinner.texture.dispose();
completionText.texture.dispose();
shader.dispose();
}
public boolean hasTask(){
return task!=null;
}
public void render(){
if(!setup){
MatrixUtils.setupImageOrtho(WraithavensConquest.INSTANCE.getScreenWidth(),
WraithavensConquest.INSTANCE.getScreenHeight(), -1, 1);
GL11.glDisable(GL11.GL_DEPTH_TEST);
shader.bind();
GL11.glDisable(GL11.GL_CULL_FACE);
GL11.glEnable(GL11.GL_BLEND);
MainLoop.FPS_SYNC = 0;
setup = true;
}
background.render(shader);
backgroundOverlay.render(shader);
spinner.render(shader);
completionText.render(shader);
}
public void update(double time){
spinner.r = (float)(time*SPINNER_SPEED);
if(task.runStep()){
GL11.glEnable(GL11.GL_DEPTH_TEST);
GL11.glEnable(GL11.GL_CULL_FACE);
GL11.glDisable(GL11.GL_BLEND);
MainLoop.FPS_SYNC = 30;
task = null;
return;
}
int percent = (int)(task.getCompletionPercent()*100);
if(lastPercent!=percent){
lastPercent = percent;
completionText.setText(lastPercent+"%");
}
if(time-lastImageTime>IMAGE_FLIP_SECONDS){
if(background.texture!=backgroundOverlay.texture)
background.texture.dispose();
int randomPicture = (int)(Math.random()*fileCount);
while(randomPicture==lastPictureIndex)
randomPicture = (int)(Math.random()*fileCount);
lastPictureIndex = randomPicture;
Texture newTexture =
Texture.getTexture(new File(WraithavensConquest.loadingScreenImagesFolder, lastPictureIndex
+".png"));
background.texture = backgroundOverlay.texture;
backgroundOverlay.texture = newTexture;
lastImageTime = time;
}
backgroundOverlay.a = (float)Math.min(time-lastImageTime, 1);
}
}
|
Python
|
UTF-8
| 4,942
| 2.84375
| 3
|
[] |
no_license
|
import logging
from enum import Enum
from typing import *
from telegram import *
log = logging.getLogger(__name__)
PollId = int
class MessageId:
def __init__(self, chat_id: int = None, message_id: int = None, inline_message_id: str = None):
inline = inline_message_id is not None
chat = (chat_id is not None) and (message_id is not None)
if inline == chat:
raise ValueError()
self._chat_id = chat_id
self._message_id = message_id
self._inline_message_id = inline_message_id
@property
def chat_id(self) -> int:
return self._chat_id
@property
def message_id(self) -> int:
return self._message_id
@property
def inline_message_id(self) -> str:
return self._inline_message_id
@property
def is_inline(self):
return self._inline_message_id is not None
def __str__(self):
return f'MessageId(chat={self._chat_id}, msg={self._message_id}, inline_message_id={self._inline_message_id})'
__repr__ = __str__
class VoteType:
PRO = 1
CONS = 2
PLUS_ONE = 3
class Vote:
def __init__(self, uid: int, name: str, vote_type: VoteType):
self._uid = uid
self._name = name
self._vote_type = vote_type
@property
def username(self):
return self._name
def is_pro(self):
return self._vote_type in (VoteType.PLUS_ONE, VoteType.PRO)
def format_user(self):
return f'[{self._name}](tg://user?id={self._uid})'
def show(self):
if self._vote_type == VoteType.PLUS_ONE:
return f'+1 (от {self.format_user()})'
else:
return self.format_user()
def __str__(self):
return f'Vote({self._vote_type}, {self._uid}, {self._name})'
__repr__ = __str__
class Poll:
def __init__(self, text: str):
self._text = text
@property
def text(self) -> str:
return self._text
class Emoji:
BOAR = '\U0001F417'
TOILET = '\U0001F6BD'
PLUS = '\U00002795'
MINUS = '\U00002796'
class OPTION(Enum):
ME_TOO = ('me_too', f'{Emoji.PLUS}')
ME_NOT = ('me_not', f'{Emoji.MINUS}')
PLUS_ONE = ('plus_one', f'{Emoji.BOAR} человечек подскочит')
MINUS_ONE = ('minus_one', f'{Emoji.TOILET} человечек слился')
def __init__(self, option_id: str, text: str):
self._option_id = option_id
self._text = text
@property
def option_id(self):
return self._option_id
@property
def text(self):
return self._text
@classmethod
def from_string(cls, option_id: str):
for opt in cls:
if option_id == opt.option_id:
return opt
raise ValueError('not an option')
class PollExt(Poll):
def __init__(self, poll_id: PollId, votes_pro: List[Vote], votes_cons: List[Vote], *args, **kwargs):
super(PollExt, self).__init__(*args, **kwargs)
self._id = poll_id
self._votes_pro = votes_pro
self._votes_cons = votes_cons
@property
def votes_pro(self) -> List[Vote]:
return self._votes_pro
@property
def votes_cons(self) -> List[Vote]:
return self._votes_cons
@property
def id(self) -> PollId:
return self._id
def __str__(self):
return f'PollExt(id={self.id}, text={self.text}, votes_pro={self.votes_pro}, votes_cons={self.votes_cons})'
__repr__ = __str__
@staticmethod
def __generate_prefix(size: int):
yielded = 0
if yielded == size:
return
without_last = size - 1
for i in range(without_last):
yield '├'
yield '└'
return
def build_text(self):
log.info(f'Generating text for poll {self}')
def total_str(votes: List):
n = len(votes)
return f'({n})' if n > 0 else ''
text = str(self.text)
text += '\n\n'
text += f'`+ `{total_str(self.votes_pro)}\n'
for prefix, vote in zip(self.__generate_prefix(len(self.votes_pro)), self.votes_pro):
text += '`{}` {}\n'.format(prefix, vote.show())
text += '\n`-`\n'
for prefix, vote in zip(self.__generate_prefix(len(self.votes_cons)), self.votes_cons):
text += '`{}` {}\n'.format(prefix, vote.show())
text += '\n'
return text
def build_markup(self) -> InlineKeyboardMarkup:
log.info(f'Generating markup for poll {self._id}')
def button(opt: OPTION):
return InlineKeyboardButton(text=opt.text, callback_data=(poll_id + ':' + opt.option_id))
poll_id = str(self._id)
return InlineKeyboardMarkup(inline_keyboard=[
[button(OPTION.ME_TOO), button(OPTION.ME_NOT)],
[button(OPTION.PLUS_ONE)], [button(OPTION.MINUS_ONE)],
[InlineKeyboardButton(text='Share', switch_inline_query=poll_id)]
])
|
C
|
UTF-8
| 1,823
| 3.203125
| 3
|
[] |
no_license
|
#include <sys/types.h>
#include <sys/dir.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FALSE 0
#define TRUE 1
extern int alphasort();
char pathname[MAXPATHLEN];
int file_select(struct direct *entry)
{
if ((strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0))
return (FALSE);
else
return (TRUE);
}
int profundidade(char *pathname, long int *nArqs, long int *tamArqs, int nivel){
int count;
struct direct **files;
struct stat buf;
char pathnameaux[MAXPATHLEN];
long int auxnArqs = 0;
long int auxtamArqs = 0;
int prof = nivel, l;
count = scandir(pathname, &files, file_select, alphasort);
if (count <= 0) return -1;
for (int i = 1; i<count + 1; ++i){
printf("%*s[%s]\n",4 * nivel, "",files[i-1]->d_name);
if(stat(files[i-1]->d_name, &buf) == 1) printf("Erro.\n");
if((int)(files[i-1]->d_type) == 4){
strcpy(pathnameaux, pathname);
strcat(pathnameaux, "/");
strcat(pathnameaux, files[i-1]->d_name);
l = profundidade(pathnameaux, &auxnArqs, &auxtamArqs, nivel + 1);
if(l > prof) prof = l;
}
auxnArqs++;
auxtamArqs += buf.st_size;
}
*nArqs += auxnArqs;
*tamArqs += auxtamArqs;
return prof;
}
int main(void){
char pathname[MAXPATHLEN];
long int nArqs = 0, tamArqs = 0;
int prof;
if (getcwd(pathname, MAXPATHLEN) == NULL){
printf("Error getting path\n");
exit(0);
}
printf("Current Working Directory = %s\n",pathname);
prof = profundidade(pathname, &nArqs, &tamArqs, 0);
printf("Numero total de arquivos: %ld\n",nArqs);
printf("Tamanho total dos arquivos: %ld\n",tamArqs);
printf("Profundidade máxima: %d\n", prof);
printf("\n"); /* flush buffer */
return 0;
}
|
JavaScript
|
UTF-8
| 1,202
| 2.546875
| 3
|
[] |
no_license
|
import React, { useState, useEffect } from "react";
import { withRouter } from "react-router-dom";
import { getAllDeals } from "./requests";
import Card from "react-bootstrap/Card";
import "./ResultsPage.css";
function ResultsPage({ match: { params } }) {
const [deals, setDeals] = useState([]);
const [name, setName] = useState("");
const [initialized, setInitialized] = useState(false);
const getDeals = async () => {
const id = params.id;
const response = await getAllDeals(id);
setDeals(response.data.content);
setName(response.data.name);
};
useEffect(() => {
if (!initialized) {
getDeals();
setInitialized(true);
}
});
return (
<div className="results-page">
<h1 className="center">Deals Results: {name}</h1>
{deals.map((d, i) => {
return (
<Card key={i}>
<Card.Title className="title">{d.dealer}</Card.Title>
<Card.Body>
{d.title}
<br />
<a className="btn btn-primary" href={d.link}>
Go
</a>
</Card.Body>
</Card>
);
})}
</div>
);
}
export default withRouter(ResultsPage);
|
Ruby
|
UTF-8
| 1,141
| 2.90625
| 3
|
[] |
no_license
|
describe ContestResults do
context "initialize" do
it "should raise exception if not an array" do
expect {ContestResults.new([1])}.to_not raise_error
expect {ContestResults.new([1,2,3,4])}.to_not raise_error
expect {ContestResults.new(["a","b"])}.to_not raise_error
expect {ContestResults.new("")}.to raise_error
expect {ContestResults.new(nil)}.to raise_error
expect {ContestResults.new([])}.to raise_error
expect {ContestResults.new}.to raise_error
end
end
context "results" do
it "should return the proper results" do
contest_results = ContestResults.new([1,2,3,4])
contest_results.results.should be_a Integer
contest_results.results(1).should be_a Integer
contest_results.results(2).should be_a Array
contest_results.results(0).should be_a Integer
contest_results.results(nil).should be_a Integer
contest_results = ContestResults.new(["a","b","c","d"])
contest_results.results.should be_a String
contest_results.results(1).should be_a String
contest_results.results(2).should be_a Array
contest_results.results(0).should be_a String
contest_results.results(nil).should be_a String
end
end
end
|
Java
|
UTF-8
| 601
| 2.171875
| 2
|
[] |
no_license
|
package com.lin.missyou.service;
import com.lin.missyou.model.Theme;
import java.util.List;
import java.util.Optional;
/**
* The interface Theme service.
*
* @ClassName: ThemeService
* @Author: Mrguo
* @Description:
* @Date: 2021 -06-17 9:38
* @Version: 1.0
*/
public interface ThemeService {
/**
* Gets by names.
*
* @param names the names
* @return the by names
*/
List<Theme> getByNames(List<String> names);
/**
* Gets by name.
*
* @param name the name
* @return the by name
*/
Optional<Theme> getByName(String name);
}
|
Python
|
UTF-8
| 3,172
| 2.59375
| 3
|
[] |
no_license
|
import sys
import typing
import logging
import argparse
class Configuration(object):
log_levels = ["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"]
def __init__( self, log_level, log_file, stdout=True, drop_tables=False,
root_route="/scraper", host="localhost",
port=8080, debug=False, use_reloader=False
):
self.log_level = log_level
self.log_file = log_file
self.stdout = stdout
self.drop_tables = drop_tables
self.root_route = root_route
self.host = host
self.port = port
self.debug = debug
self.use_reloader = use_reloader
def get_configuration():
parser = argparse.ArgumentParser(description="Configure properties for use in development.")
parser.add_argument(
"-t",
"--drop_tables",
required=False,
default=False,
help="Whether to reset or keep the current database"
)
server_parser = parser.add_argument_group("server", "Server")
server_parser.add_argument(
"-r",
"--serviceroot",
required=False,
default="/scraper/api",
help="The root URL path that the server should listen on"
)
server_parser.add_argument(
"-o",
"--host",
required=False,
default="localhost",
help="The host that the server should start on"
)
server_parser.add_argument(
"-p",
"--port",
required=False,
default=8080,
help="The port that the server should start on"
)
server_parser.add_argument(
"-d",
"--debug",
required=False,
action="store_true",
help="Whether the server should start in debug mode."
)
server_parser.add_argument(
"-u",
"--use_reloader",
required=False,
action="store_true",
help="Whether the server should automatically restart on saved changes."
)
log_parser = parser.add_argument_group("log", "Logging")
log_parser.add_argument(
"-l",
"--loglevel",
default='WARN',
required=False,
choices=Configuration.log_levels,
help="The log level of the application"
)
log_parser.add_argument(
"-f",
"--logfile",
default=None,
required=False,
help="The log file for the application"
)
log_parser.add_argument(
"-s",
"--stdout",
default=True,
required=False,
help="Whether to print the log to the terminal"
)
args = parser.parse_args()
drop_tables = args.drop_tables
log_level = args.loglevel
log_file = args.logfile
stdout = args.stdout
service_root = args.serviceroot
host = args.host
port = args.port
debug = args.debug
use_reloader = args.use_reloader
return Configuration(
log_level,
log_file,
stdout,
drop_tables,
service_root,
host,
port,
debug,
use_reloader,
)
|
Shell
|
UTF-8
| 2,437
| 3.421875
| 3
|
[] |
no_license
|
#!/bin/bash
#
# [Quick Box :: Install SickRage package]
#
# GITHUB REPOS
# GitHub _ packages : https://github.com/QuickBox/quickbox_packages
# LOCAL REPOS
# Local _ packages : /etc/QuickBox/packages
# Author : QuickBox.IO | JMSolo
# URL : https://quickbox.io
#
# QuickBox Copyright (C) 2017 QuickBox.io
# Licensed under GNU General Public License v3.0 GPL-3 (in short)
#
# You may copy, distribute and modify the software as long as you track
# changes/dates in source files. Any modifications to our software
# including (via compiler) GPL-licensed code must also be made available
# under the GPL along with build & install instructions.
#
MASTER=$(cat /root/.master.info | cut -d: -f1)
if [[ -f /tmp/.install.lock ]]; then
OUTTO="/root/logs/install.log"
elif [[ -f /install/.panel.lock ]]; then
OUTTO="/srv/panel/db/output.log"
else
OUTTO="/dev/null"
fi
function _installSickRage1() {
sudo git clone https://github.com/SickRage/SickRage.git /home/"${MASTER}"/.sickrage >/dev/null 2>&1
}
function _installSickRage2() {
touch /install/.sickrage.lock
chown "${MASTER}":"${MASTER}" -R /home/"${MASTER}"/.sickrage
}
function _installSickRage3() {
cat > /etc/systemd/system/sickrage@.service <<SRS
[Unit]
Description=SickRage
After=syslog.target network.target
[Service]
Type=forking
GuessMainPID=no
User=%I
Group=%I
ExecStart=/usr/bin/python /home/%I/.sickrage/SickBeard.py -q --daemon --nolaunch --datadir=/home/%I/.sickrage
ExecStop=-/bin/kill -HUP
[Install]
WantedBy=multi-user.target
SRS
systemctl enable sickrage@${MASTER} > /dev/null 2>&1
systemctl start sickrage@${MASTER} > /dev/null 2>&1
systemctl stop sickrage@${MASTER} > /dev/null 2>&1
if [[ -f /install/.nginx.lock ]]; then
bash /usr/local/bin/swizzin/nginx/sickrage.sh
service nginx reload
fi
systemctl start sickrage@${MASTER} > /dev/null 2>&1
}
function _installSickRage4() {
echo "SickRage Install Complete!" >>"${OUTTO}" 2>&1;
sleep 5
echo >>"${OUTTO}" 2>&1;
echo >>"${OUTTO}" 2>&1;
echo "Close this dialog box to refresh your browser" >>"${OUTTO}" 2>&1;
}
function _installSickRage5() {
exit
}
echo "Installing sickrage ... " >>"${OUTTO}" 2>&1;_installSickRage1
echo "Setting up sickrage permissions ... " >>"${OUTTO}" 2>&1;_installSickRage2
echo "Setting up sickrage configurations and enabling ... " >>"${OUTTO}" 2>&1;_installSickRage3
_installSickRage4
_installSickRage5
|
C#
|
UTF-8
| 2,770
| 3.90625
| 4
|
[
"Apache-2.0"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DivideAndConque
{
public class MedianOf2Array
{
/*http://www.geeksforgeeks.org/median-of-two-sorted-arrays/
* Question: There are 2 sorted arrays A and B of size n each.
* Write an algorithm to find the median of the array obtained
* after merging the above 2 arrays(i.e. array of length 2n).
* The complexity should be O(log(n))
*
* 1) Calculate the medians m1 and m2 of the input arrays ar1[]
and ar2[] respectively.
2) If m1 and m2 both are equal then we are done.
return m1 (or m2)
3) If m1 is greater than m2, then median is present in one
of the below two subarrays.
a) From first element of ar1 to m1 (ar1[0...|_n/2_|])
b) From m2 to last element of ar2 (ar2[|_n/2_|...n-1])
4) If m2 is greater than m1, then median is present in one
of the below two subarrays.
a) From m1 to last element of ar1 (ar1[|_n/2_|...n-1])
b) From first element of ar2 to m2 (ar2[0...|_n/2_|])
5) Repeat the above process until size of both the subarrays
becomes 2.
6) If size of the two arrays is 2 then use below formula to get
the median.
Median = (max(ar1[0], ar2[0]) + min(ar1[1], ar2[1]))/2
* the previous method is good for both array are same size.
*/
public int FindMedian(int[] a, int[] b)
{
return FindKth(a, b, (a.Length + b.Length) / 2);
}
private int FindKth(int[] a, int[] b, int k)
{
int n = a.Length;
int m = b.Length;
int i = a.Length * k / (a.Length + b.Length);
int j = k - i - 1;
int ai = a[i];
int ai_1 = (i - 1) >= 0 ? a[i - 1] : 0;
int bj = b[j];
int bj_1 = (j - 1) >= 0 ? b[j - 1] : 0;
if (ai >= bj_1 && ai <= bj)
return ai;
else if (bj >= ai_1 && bj <= ai)
return bj;
if (ai < bj)
{
return FindKth(trimArray(a, i), b, k - i - 1);
}
else
{
return FindKth(a, trimArray(b, j), k - j - 1);
}
}
private int[] trimArray(int[] input, int i)
{
int[] res = new int[input.Length - i];
for (int k = i + 1; k < input.Length; k++)
{
res[k - i - 1] = input[k];
}
return res;
}
}
}
|
Markdown
|
UTF-8
| 2,387
| 3.546875
| 4
|
[] |
no_license
|
# 三大框架组件化学习笔记
## Vue组件规范
摘自:https://cn.vuejs.org/v2/guide/components.html
> 组件是可复用的 Vue 实例,且带有一个名字
[Components Basics](https://vuejs.org/v2/guide/components.html)
[Components In-Depth](https://vuejs.org/v2/guide/components-registration.html)
[Single File Components](https://vuejs.org/v2/guide/single-file-components.html)
### Vue组件总结
1. 有组件名
2. 有生命周期及其钩子
3. 可被复用
4. 父子组件传递数据 -- 可组合
5. 通过插槽分发内容
6.
## React组件规范
摘自:https://reactjs.org/docs/components-and-props.html
> Components let you split the UI into independent, reusable pieces, and think about each piece in isolation.
> Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.
### React组件总结
1. 组件有生命周期
2. 支持function和class定义两种方式
3. 组件可以组合 -- 父子、兄弟
4.
## Angular组件规范
摘自:https://angular.cn/guide/architecture
> 每个 Angular 应用都至少有一个组件,也就是根组件,它会把组件树和页面中的 DOM 连接起来。 每个组件都会定义一个类,其中包含应用的数据和逻辑,并与一个 HTML 模板相关联,该模板定义了一个供目标环境下显示的视图。
摘自:https://angular.cn/guide/architecture-components
> 你在类中定义组件的应用逻辑,为视图提供支持。 组件通过一些由属性和方法组成的 API 与视图交互。
1. 组成
> 组件包含三部分:
> - 一个组件类,它用来处理数据和功能。上一节,我们在组件类中定义了商品数据和 share() 方法。
> - 一个 HTML 模板,它决定了用户的呈现方式。在上一节中,你修改了商品列表的 HTML 模板,以显示每个商品的名称、描述和 “Share” 按钮。
> - 组件专属的样式定义了外观和感觉。商品列表中还没有定义任何样式。
2. 有生命周期
3.
### Angular组件总结
[angular.cn](https://angular.cn/start)
[angular组件简介](https://angular.cn/guide/architecture-components)
[Components and Props](https://reactjs.org/docs/components-and-props.html)
[React.Component](https://reactjs.org/docs/react-component.html)
|
C++
|
UTF-8
| 293
| 2.8125
| 3
|
[] |
no_license
|
class Solution {
public:
int climbStairs(int n) {
std::vector<int> memo;
memo.push_back(0);
memo.push_back(1);
memo.push_back(2);
for (int i = 3; i < n + 1; ++i)
memo.push_back(memo[i - 1] + memo[i - 2]);
return memo[n];
}
};
|
Markdown
|
UTF-8
| 1,009
| 3.046875
| 3
|
[] |
no_license
|
1. Checkout code mới nhất từ branch develop
```bash
git checkout develop
git pull
```
1. Tạo branch: **feature/new-feature** từ branch develop
```bash
git checkout -b feature/new-feature develop
```
1. Push branch **feature/new-feature** lên origin
```bash
git push -u origin feature/new-feature
```
1. Commit code vào branch **feature/new-feature** local
```bash
git add .
git commit -m "Noi dung feature"
```
1. Sau khi làm xong push code lên **origin/feature/new-feature**
```bash
git push origin feature/new-feature
```
1. Tạo merge request:
1. Source branch là **feature/new-feature**
1. Target branch là **develop**
1. Sau khi **feature/new-feature** được merge, checkout code mới từ branch develop
```bash
git checkout develop
git pull
```
1. Xóa branch **feature/new-feature** ở local và server
```bash
git push -d origin feature/new-feature
git branch -d feature/new-feature
```
|
Python
|
UTF-8
| 740
| 3.1875
| 3
|
[] |
no_license
|
print(" This is a genral knowledge quiz")
playername = input("What is your name: ")
playerage = input("What is your age: ")
text_file = open("Info_Players.txt", "w")
text_file.write("PlayerOne")
text_file.write("\n Name : " + playername)
text_file.write("\n Age : " + playerage)
text_file.close()
print (" Answer with the chioices a,b or c ")
print(" Make sure you keep your Caps lock off")
print(" Here are 3 diffrent topics to choose from")
print(" 1. Football")
print(" 2. Music")
print(" 3. General Knowledge")
Menu = input ("Make your Choice [1-3]: ")
level = input("Easy, Medium or Hard?: ")
if level in ['easy','Easy']:
import footballeasy
|
Python
|
UTF-8
| 1,888
| 3.640625
| 4
|
[] |
no_license
|
from FunFun import getAnswer
# Примеры вопросов и ожидаемых ответов:
# Где находится Неболит? ул. Городская, д. 75. + relations
# Какой адрес у Неболит? ул. Городская, д. 75. + properties
# Кем является Игорь? Администратор + relations
# Кем является Марина? Пациент + relations
# Кем является Костя? Пациент + relations
# Кем является Волкова? Врач + relations
# Кем является Новиков? Врач + relations
# Какая специальность у Волкова? Кардиолог + properties
# Какая специальность у Новиков? Лор + properties
# Какая дата у Талон237? 02.01.2020 + properties
# Какая дата у Талон217? 03.01.2020 + properties
# Кто получил Талон237? Костя relations +
# Кто получил Талон217? Марина relations +
# Пасхалка: Ты знаешь ответ на главный вопрос Жизни, Вселенной и всего Остального? 42.
flag = True
while flag:
question = input()
if question == 'exit' or question == 'стоп':
flag = False
break
elif question[len(question)-1] != '?':
print('Ты спрашиваешь или утверждаешь? (вопрос должен заканчиваться знаком вопроса)')
elif question == 'Ты знаешь ответ на главный вопрос Жизни, Вселенной и всего Остального?':
print('42. Что-нибудь еще?')
else:
question = question[0: -1]
question = question.split()
answer = getAnswer(question)
print(answer)
|
Python
|
UTF-8
| 509
| 3.796875
| 4
|
[] |
no_license
|
nome = str(input('Diga seu nome: ')).title()
if nome == 'Gustavo':
print('Que nome bonito você tem.')
else:
print('Que nome normal esse seu.')
print('Bom dia, {}.'.format(nome))
print('Agora vamos para as suas notas.')
n1 = float(input('Digite a primeira nota: '))
n2 = float(input('Digite a segunda nota: '))
m = (n1 + n2)/2
print('A média das notas foi {}.'.format(m))
if m >= 6:
print('Sua nota foi boa, continue estudando!')
else:
print('Não está indo bem, estude mais, seu bosta!')
|
Java
|
UTF-8
| 524
| 2.21875
| 2
|
[] |
no_license
|
package cn.edu.neu.cloudlab.haolap.strategy;
import cn.edu.neu.cloudlab.haolap.cube.Schema;
public class PageSizer {
PageSizerStrategy strategy;
public PageSizer(PageSizerStrategy strategy) {
super();
this.strategy = strategy;
}
public long[] getPageLengths(Schema schema) {
return this.strategy.getPageLengths(schema);
}
public long[] getNumberOfPageSegmentsInDimensions(Schema schema) {
return this.strategy.getNumberOfPageSegmentsInDimensions(schema);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.