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 |
|---|---|---|---|---|---|---|---|
Java | UTF-8 | 93 | 1.625 | 2 | [] | no_license | package org.leanpoker.player;
/**
* ...
*/
enum Suit {
clubs,spades,hearts,diamonds
}
|
C++ | UTF-8 | 2,043 | 2.9375 | 3 | [] | no_license | //
// Created by sahar on 12/4/17.
//
#ifndef REVERSI_CLIENT_H
#define REVERSI_CLIENT_H
#include <string>
#include "PlayerHuman.h"
const int length = 50;
/**
* This object inherits from PlayerType (an abstract class) and iד responsible for managing the AI player's
* members and implementation of PlayerType.
*/
class PlayerClient: public PlayerHuman {
//#ifndef REVERSI_CLIENT_H
//#define REVERSI_CLIENT_H
public:
/**
* The player clients constructor
* @param serverIP the server's IP
* @param serverPort the server's port
* @param sym the player's symbol
*/
PlayerClient(const char *serverIP, int serverPort, DiscSymbol sym);
/**
* creating the socket and connecting to the server.
*/
void connectToServer();
/**
* @return the playerClient's socket
*/
int getClientSocket();
/**
* setting the socket member of the playerClient
* @param socket - the socket to be set
*/
void setClientSocket(int socket);
/**
* @return the player's number
*/
int getPlayerNum();
/**
* set the player's number
* @param num the player' number
*/
void setPlayerNum(int num);
/*
* receives, checks and asks the server for pre game commands given by the player (such as start, join
* and asking for a list of games with one player)
*/
void writeCommande();
/**
* A virtual function that returns the move a player would like to make (AI, console or remote)
* @param bl the current game's BoardLogic object.
* @return the move a player decided on.
*/
virtual coordinates makeMove(BoardLogic *bl) const;
/**
* Converts a char to string
* @param some a char array
* @return a string with the content of the char array.
*/
string convertCharToString (char some[length]);
private:
const char *serverIP;
int serverPort;
int clientSocket;
int playernumber;
};
#endif //ROOT_PLAYERCLIENT_H
|
Markdown | UTF-8 | 5,417 | 3.203125 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: What’s New in RxJS 7: Small Bundles and Big Changes to share
image: rxjs-logo.png
---
RxJS 7 has shipped! For us Angular developers, it unfortunately did not ship in time for Angular 12.
I've summarized key takeaways from Ben Lesh’s talk from RxJS Live Asia and his slides below. Lesh is a member of the RxJS core team and formerly worked at Google on the Angular team.
## Big Feature: Smaller Bundle Sizes
Lesh said while RxJS 7 was "a bit faster," the big improvement for the new version is its bundle size. RxJS 7 is 53% the size of RxJS 6. If your app used every operator in version 6, that would require 52 KB, but the same thing in RxJS 7 requires just 19 KB.
"This was done via a refactor, a hundred-point improvement of going around and individually moving around code, keeping the same tests, keeping the same code, and moving things around slowly but surely until we got to a place where we could see daylight and we were able to refactor larger portions of the code," Lesh said in his talk.
See this chart of operator sizes in RxJS 6:

And this chart of the same operator sizes in RxJS 7:

## Consolidating Sharing operators
Lesh's talk includes a long discussion about how many ways RxJS lets you share a stream (`multicast`, `shareReplay`, `refCount`, etc).
RxJS 7 deprecates `multicast`, `publish`, `publishReplay`, `publishLast`, and `refCount`. `shareReplay` was too popular to deprecate in 7, but Lesh said it's next because it is "full of footguns." Long term, the only sharing operators will be `share`, `connect` and `connectable`. He recommends moving to `share` now.
`share` is picking up some new features as the single solution operator. It takes an optional config object as a parameter, where you can define custom behavior for the stream.
```typescript
share({
connector: () => new ReplaySubject(),
resetOnRefCountZero: true,
resetOnComplete: true,
resetOnError: true
})
```
## Better TypeScript Typings
RxJS 7 [requires TypeScript 4.2](https://github.com/ReactiveX/rxjs/blob/6bd1c5f3cf0e387973b44698c48bc933e8c528aa/package.json#L9), Lesh said, because it contains features that enable more accurate, stricter types. One example he gave in his slides involved `Subject`:
```typescript
// allowed in RxJS 6, errors in 7 because next() must be called with a number
const subject = new Subject<number>()
subject.next()
```
For teams that are unable to upgrade to TypeScript 4.2, Lesh recommended staying on RxJS 6, which the RxJS team will continue to support.
### `toPromise()` Deprecated
The problem with `toPromise()`, Lesh explained, was that it didn't make sense with Observables. Should a promise created by `toPromise()` resolve with the first or last value emitted from the source Observable?
So, `toPromise()` is deprecated in favor of `lastValueFrom()` and `firstValueFrom()`. These new functions still convert Observables to Promises, but in a way that clarifies that value the Promise will resolve with.
```typescript
const source = from([1, 2])
const firstVal = await firstValueFrom(source)
console.log(firstVal) // 1
const lastVal = await lastValueFrom(source)
console.log(lastVal) // 2
```
If an Observable completes without emitting a value, the Promise created by `lastValueFrom` or `firstValueFromrejects`. If that is not desired behavior, you can configure the new Promise to resolve with a defaultValue.
```typescript
const emptyVal = await firstValueFrom(source, { defaultValue: 'empty' })
console.log(emptyVal) // 'empty'
```
## AsyncIterable support
Anywhere you can pass an Observable, RxJS 7 also lets you pass an AsyncIterable.
```typescript
async function* ticket(delay: number) {
let n = 0;
while (true) {
await sleep(delay);
yield n;
}
}
```
## Other Updates
- `finalize()` operators now run in the order in which they are written in `pipe()`. In contrast, RxJS 6 ran them in reverse.
- `subscription.add(someSubscription)` now returns void so people will stop writing `add()` chains, which Lesh says never worked.
```typescript
// add() returns void, cannot be chained
subscription
.add(subOne)
.add(subTwo) // errors
```
- `animationFrames()` creates Observables to do animation logic reactively
- `switchScan()` operator, aka `switchMap` with an accumulator
- `throwError()` requires a callback, not an error, as the error captures the current stack at the moment of its creation
### Your `with` Is My Command
- `combineLatest` operator renamed to `combineLatestWith`
- `merge` operator renamed to `mergeWith`
- `zip` operator renamed to `zipWith`
- `race` operator renamed to `raceWith`
- `concat` operator renamed to `concatWith`
## Bitovi Recommendations for Migrating to RxJS 7
If your project can be upgraded to RxJS 7, we would recommend doing so. The speed and bundle size improvements offer tangible, immediate benefits to end users.
Important points to remember:
- Replace your `toPromise` calls with `firstValueFrom` and `lastValueFrom`
- Replace your `shareReplay` calls with `share`
- Stop using `.add` chains to manage your subscriptions. Lesh [recommends `takeUntil`](https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87) |
Python | UTF-8 | 877 | 3.015625 | 3 | [] | no_license | import pprint
N = int(input())
list = []
for i in range(N-1):
list.append(str(input()))
vertexes = set()
def graph_from_input():
graph = {}
for element in list:
a, b = element.split()
vertexes.add(a)
vertexes.add(b)
if a not in graph:
graph[a] = b
for v in vertexes:
if v not in graph:
graph[v] = None
return graph
parents = graph_from_input()
#pprint.pprint(g)
g = {}
for element in list:
line = element.split()
try:
g[line[1]].add(line[0])
except KeyError:
g[line[1]] = set()
g[line[1]].add(line[0])
try:
if len(g[line[0]]) != 0:
g[line[0]] = g[line[0]]
except Exception:
g[line[0]] = set()
root = None
for key in parents:
if parents[key] == None:
root = key
print =(root, parents, g)
pprint.pprint(print) |
Java | UTF-8 | 317 | 1.585938 | 2 | [] | no_license | package com.haulmont.screenapidemos.web.airport;
import com.haulmont.cuba.gui.screen.*;
import com.haulmont.screenapidemos.entity.airport.Airport;
@UiController("sad_Airport.browse")
@UiDescriptor("airport-browse.xml")
@LookupComponent("airportsTable")
public class AirportBrowse extends StandardLookup<Airport> {
} |
C# | UTF-8 | 4,379 | 3.03125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace db_SmartMovers
{
public class Customerdetails
{
public string C_Id;
public string C_Type_Id;
public string C_Name;
public string C_Address;
public string C_Email;
public string C_Password;
}
public class Product
{
public string P_Id;
public string P_Type_Id;
public string P_Name;
public string P_Description;
public string P_Cost;
}
public class LoadType
{
public string L_Type_Id;
public string L_Type_Name;
public string L_Type_Cost;
}
class Common
{
SqlConnection m_con = new DatabaseConnection().getConnection();
public Customerdetails GetCustomerRowById(String C_Id)
{
try
{
string sql = "select * from Customer where C_Id ='" + C_Id + "' ";
SqlCommand cmd = new SqlCommand(sql, m_con);
m_con.Open();
SqlDataReader dreader = cmd.ExecuteReader();
// We are going to store Customer data in this variable (Customer)
Customerdetails cus = new Customerdetails();
if (dreader.Read())
{
cus.C_Id = dreader[0].ToString();
cus.C_Type_Id = dreader[1].ToString();
cus.C_Name = dreader[2].ToString();
cus.C_Address = dreader[3].ToString();
cus.C_Email = dreader[4].ToString();
cus.C_Password = dreader[5].ToString();
dreader.Close();
return cus;
}
else
{
return null;
}
}
catch (Exception ex)
{
return null;
}
finally
{
m_con.Close();
}
}
public Product GetProductRowById(String P_Id)
{
try
{
string sql = "select * from Product where P_Id ='" + P_Id + "' ";
SqlCommand cmd = new SqlCommand(sql, m_con);
m_con.Open();
SqlDataReader dreader = cmd.ExecuteReader();
// We are going to store product data in this variable (product)
Product p = new Product();
if (dreader.Read())
{
p.P_Id = dreader[0].ToString();
p.P_Type_Id = dreader[1].ToString();
p.P_Name = dreader[2].ToString();
p.P_Description = dreader[3].ToString();
p.P_Cost = dreader[4].ToString();
dreader.Close();
return p;
}
else
{
return null;
}
}
catch (Exception ex)
{
return null;
}
finally
{
m_con.Close();
}
}
public LoadType GetLoadTypeRowById(String L_Type_Id)
{
try
{
string sql = "select * from LoadType where L_Type_Id ='" + L_Type_Id + "' ";
SqlCommand cmd = new SqlCommand(sql, m_con);
m_con.Open();
SqlDataReader dreader = cmd.ExecuteReader();
// We are going to store loadtype data in this variable (loadtype)
LoadType lt = new LoadType();
if (dreader.Read())
{
lt.L_Type_Id = dreader[0].ToString();
lt.L_Type_Name = dreader[1].ToString();
lt.L_Type_Cost = dreader[2].ToString();
return lt;
}
else
{
return null;
}
}
catch (Exception ex)
{
return null;
}
finally
{
m_con.Close();
}
}
}
}
|
C++ | UTF-8 | 1,132 | 3.109375 | 3 | [] | no_license | #include <iostream>
#include "my_memory.h"
using namespace std;
void shareDelete(){
my_shared_ptr<int> t1(new int {5});
my_shared_ptr<int> t2(t1);
if(*t2 == 5)
cout << "test 1 ... OK\n";
t1.~my_shared_ptr();
if(t1.isNullptr())
cout << "test 2 ... OK\n";
if(*t2 == 5)
cout << "test 3 ... OK\n";
}
void shareMove(){
my_shared_ptr<int> t3(new int {8});
my_shared_ptr<int> t4(move(t3));
if(*t4 == 8 && t3.isNullptr())
cout << "test 4 ... OK\n";
}
void shareEqual(){
my_shared_ptr<int> t5(new int {2});
my_shared_ptr<int> t6(new int {5});
t6 = t5;
if(*t5 == *t6){
cout << "test 5 ... OK\n";
}
my_shared_ptr<int> t7;
my_shared_ptr<int> t8(t7);
t7 = t6;
if(*t7 == *t6){
cout << "test 6 ... OK\n";
}
my_shared_ptr<int> t9(new int {44});
t5 = move(t9);
if(*t5 == 44)
cout << "test 7 ... OK\n";
}
void uniquetest(){
//my_unique_ptr<int> u1(new int {6});
//my_unique_ptr<int> u2;
//u2 = u1;
}
int main(){
shareDelete();
shareMove();
shareEqual();
//uniquetest();
} |
PHP | UTF-8 | 5,445 | 2.53125 | 3 | [
"Unlicense"
] | permissive | <?php
class DepartmentsController extends Controller
{
/**
* @var string the default layout for the views. Defaults to '//layouts/docflow'
*/
public $layout='//layouts/column2';
public $defaultAction='admin';
/**
* @return array action filters
*/
public function filters()
{
return array(
'accessControl', // perform access control for CRUD operations
'postOnly + delete', // we only allow deletion via POST request
);
}
/**
* Specifies the access control rules.
* This method is used by the 'accessControl' filter.
* @return array access control rules
*/
public function accessRules() {
return array(
array('allow', // allow all users to perform actions
'actions' => array('select2'),
'users' => array('*'),
),
array('allow',
'actions' => array('create','update','delete','index','admin'),
'users' => array('munspel', 'admin')
),
array('deny', // deny all users
'users' => array('*'),
),
);
}
/**
* Displays a particular model.
* @param integer $id the ID of the model to be displayed
*/
public function actionView($id)
{
$this->render('view',array(
'model'=>$this->loadModel($id),
));
}
/**
* Creates a new model.
* If creation is successful, the browser will be redirected to the 'view' page.
*/
public function actionCreate()
{
$model=new Departments;
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Departments']))
{
$model->attributes=$_POST['Departments'];
if($model->save())
$this->redirect(array('view','id'=>$model->idDepartment));
}
$this->render('create',array(
'model'=>$model,
));
}
/**
* Updates a particular model.
* If update is successful, the browser will be redirected to the 'view' page.
* @param integer $id the ID of the model to be updated
*/
public function actionUpdate($id)
{
$model=$this->loadModel($id);
// Uncomment the following line if AJAX validation is needed
// $this->performAjaxValidation($model);
if(isset($_POST['Departments']))
{
$model->attributes=$_POST['Departments'];
if($model->save())
$this->redirect(array('view','id'=>$model->idDepartment));
}
$this->render('update',array(
'model'=>$model,
));
}
/**
* Deletes a particular model.
* If deletion is successful, the browser will be redirected to the 'admin' page.
* @param integer $id the ID of the model to be deleted
*/
public function actionDelete($id)
{
$this->loadModel($id)->delete();
// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
if(!isset($_GET['ajax']))
$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
}
/**
* Lists all models.
*/
public function actionIndex()
{
$dataProvider=new CActiveDataProvider('Departments');
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
/**
* Manages all models.
*/
public function actionAdmin()
{
$model=new Departments('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['Departments']))
$model->attributes=$_GET['Departments'];
$this->render('admin',array(
'model'=>$model,
));
}
/**
* Метод для асинх. вибірки підрозділів у віджетах select2
* @param string $q параметр для пошуку назви підрозділу
*/
public function actionSelect2($q=null,$n_ids="[]"){
$fields = array();
$criteria = new CDbCriteria();
$n_ids = CJSON::decode($n_ids);
$q = ($rq = Yii::app()->request->getParam('query',null))? $rq : $q;
$criteria->compare('CONCAT(DepartmentName,FunctionDescription)', $q, true);
if (!empty($n_ids)){
$criteria->addNotInCondition('idDepartment',$n_ids);
}
//$criteria->addCondition('idDepartment NOT IN ('.implode(',',$this->my_dept_ids).')');
$criteria->addCondition('idDepartment > 1');
$criteria->order = 'DepartmentName ASC';
foreach (Departments::model()->findAll($criteria) as $model){
$fields[] = array(
'text' => $model->DepartmentName,
'id' => $model->idDepartment
);
}
echo CJSON::encode($fields);
}
/**
* Returns the data model based on the primary key given in the GET variable.
* If the data model is not found, an HTTP exception will be raised.
* @param integer the ID of the model to be loaded
*/
public function loadModel($id)
{
$model=Departments::model()->findByPk($id);
if($model===null)
throw new CHttpException(404,'The requested page does not exist.');
return $model;
}
/**
* Performs the AJAX validation.
* @param CModel the model to be validated
*/
protected function performAjaxValidation($model)
{
if(isset($_POST['ajax']) && $_POST['ajax']==='departments-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
}
}
|
Markdown | UTF-8 | 3,068 | 3.515625 | 4 | [] | no_license | ---
title: Async Reactive Declarations in Svelte JS
date: "2020-01-01T00:00:00.000Z"
---
One of the tricker aspects of writing an app is **handling asynchronous actions**. In Svelte, there are a number of ways to handle async code; in this tutorial, we'll compare and contrast a few of them.
## Challenge
Svelte's reactive declaration syntax is in general quite intuitive. However, when it comes to asynchronous code, it can be a bit confusing to figure out exactly how to take advantage of Svelte's reactivity.
## Setup
In this tutorial, we'll be using the [Numbers API](http://numbersapi.com) to generate random facts about any given number. While there are a quite a lot of options available, we'll stick to facts about years to keep it simple. And we'll just request plain text; no JSON needed today.
To get started, let's create some simple markup with an `<input />` where the user can choose a year.
```html
<script>
let year
</script>
<h1>Get a random fact for any year since 1 AD</h1>
<input bind:value={year} type="number" />
```
Let's add some basic styling as well:
```html
<style>
input {
text-align: center;
height: 2rem;
width: 4rem;
border: 1px solid gray;
border-radius: 5px;
background-color: #f2f2f2;
font-size: 1rem;
}
</style>
```
Now we're ready to start fetching data! Let's look at each method in turn for handling async code in Svelte.
## Method 1: Callbacks
This is probably the simplest way to write async reactive declarations in Svelte. Three easy steps:
1. Declare a variable to store the result of the async function
2. Place the async function in a reactive statement with `$:`
3. In the callback, assign the result of the promise to the storage variable
```js
let result
$: getData(query)
.then(response => result = response)
```
There are a few more aspects of this that we'll go over, but this is the basic flow.
Whenever `query` is updated, `getData()` will be called and `result` will be assigned to the value of the resolved promise.
Let's take a look at this in the context of our number fact app.
```html
<script>
const base = 'http://numbersapi.com'
let result
let year
$: if (year) {
fetch(`${base}/${year}/year`)
.then(response => response.text())
.then(data => result = data)
}
</script>
```
Every time the user changes `year` via the input binding, the fetch function will be called. Note: if `base` weren't a constant, you could change it and also trigger the reactive block. If you add another variable for the block to be dependent on, that will trigger updates as well.
Finally, display the result below the `<input />`:
```js
{#if result}
<h3>{result}</h3>
{/if}
```
This method is quite concise and simple to use. However, in its current state, there is a serious flaw here. Can you spot it?
**Race conditions**. As the user changes the chosen year, new data is fetched each time. If a previous fetch call returns after a more recent one, the result displayed will be incorrect, showing the result of the earlier request.
|
Java | UTF-8 | 2,653 | 2.84375 | 3 | [
"Apache-2.0"
] | permissive | package com.rincliu.library.common.persistence.rootmanager.container;
import java.io.IOException;
import java.io.OutputStream;
import com.rincliu.library.common.persistence.rootmanager.Constants;
import com.rincliu.library.common.persistence.rootmanager.utils.RootUtils;
public abstract class Command {
private String[] commands;
private boolean isFinished;
private int exitCode;
private long timeout;
private int id;
/* Abstract function should be implemented by caller */
public abstract void onUpdate(int id, String message);
public abstract void onFinished(int id);
public Command(String... commands) {
this(Constants.COMMAND_TIMEOUT, commands);
}
public Command(int timeout, String... commands) {
this.id = RootUtils.generateCommandID();
this.timeout = timeout;
this.commands = commands;
}
public int getID() {
return id;
}
public void setExitCode(int code) {
synchronized (this) {
exitCode = code;
isFinished = true;
onFinished(id);
this.notifyAll();
}
}
public void terminate(String reason) {
try {
RootUtils.Log("Terminate all shells with reason " + reason);
Shell.closeAll();
setExitCode(-1);
} catch (IOException e) {
e.printStackTrace();
RootUtils.Log("Terminate all shells and io exception happens");
}
}
public int waitForFinish(long timeout) throws InterruptedException {
synchronized (this) {
while (!isFinished) {
this.wait(timeout);
if (!isFinished) {
isFinished = true;
RootUtils.Log("Timeout Exception has occurred.");
terminate("Timeout Exception");
}
}
}
return exitCode;
}
public int waitForFinish() throws InterruptedException {
synchronized (this) {
waitForFinish(timeout);
}
return exitCode;
}
public String getCommand() {
if (commands == null || commands.length == 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < commands.length; i++) {
sb.append(commands[i]);
sb.append('\n');
}
String command = sb.toString();
RootUtils.Log("Sending command(s): " + command);
return command;
}
public void writeCommand(OutputStream out) throws IOException {
out.write(getCommand().getBytes());
}
}
|
Java | UTF-8 | 658 | 2.546875 | 3 | [
"MIT"
] | permissive | package net.anotheria.anoprise.fs;
/**
* Factory for file system service.
*
* @author abolbat
*/
public final class FSServiceFactory {
/**
* Create instance of {@link net.anotheria.anoprise.fs.FSService} with given {@link net.anotheria.anoprise.fs.FSServiceConfig}.
*
* @param config
* - {@link net.anotheria.anoprise.fs.FSServiceConfig}
* @return {@link net.anotheria.anoprise.fs.FSService}
* @param <T> a T object.
*/
public static <T extends FSSaveable> FSService<T> createFSService(FSServiceConfig config) {
return new FSServiceImpl<T>(config);
}
/**
* Default constructor.
*/
private FSServiceFactory() {
}
}
|
Markdown | UTF-8 | 4,319 | 4.21875 | 4 | [] | no_license | ## [733. 图像渲染](https://leetcode-cn.com/problems/flood-fill)
有一幅以二维整数数组表示的图画,每一个整数表示该图画的像素值大小,数值在 0 到 65535 之间。
给你一个坐标 (sr, sc) 表示图像渲染开始的像素值(行 ,列)和一个新的颜色值 newColor,让你重新上色这幅图像。
为了完成上色工作,从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。将所有有记录的像素点的颜色值改为新的颜色值。
最后返回经过上色渲染后的图像。
示例 1:
```
输入:
image = [[1,1,1],[1,1,0],[1,0,1]]
sr = 1, sc = 1, newColor = 2
输出: [[2,2,2],[2,2,0],[2,0,1]]
解析:
在图像的正中间,(坐标(sr,sc)=(1,1)),
在路径上所有符合条件的像素点的颜色都被更改成2。
注意,右下角的像素没有更改为2,
因为它不是在上下左右四个方向上与初始点相连的像素点。
```
注意:
* image 和 image[0] 的长度在范围 [1, 50] 内。
* 给出的初始点将满足 0 <= sr < image.length 和 0 <= sc < image[0].length。
* image[i][j] 和 newColor 表示的颜色值在范围 [0, 65535]内。
#### 思路:
从初始坐标开始,记录初始坐标的上下左右四个方向上像素值与初始坐标相同的相连像素点,接着再记录这四个方向上符合条件的像素点与他们对应四个方向上像素值与初始坐标相同的相连像素点,……,重复该过程。
简单来看,就是从一个点出发,然后向四周不断地延伸。我们可以用`DFS`或者`BFS`解决问题。
#### 解答:
递归算法
定义一个方法。该方法以坐标`(i, j)`为起点,将`(i, j)`四个方向上像素值与`oldColor`相同的像素点重新上色为`newColor`
```Java
public static int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
final int oldColor = image[sr][sc];
if (oldColor == newColor) {
return image;
}
floodFillDFS(image, sr, sc, oldColor, newColor);
return image;
}
private static void floodFillDFS(int[][] image, int i, int j, int oldColor, int newColor) {
// 判断像素值与初始坐标是否相同
if (oldColor != image[i][j]) {
return;
}
image[i][j] = newColor; // 重新上色
if (i > 0) {
floodFillDFS(image, i - 1, j, oldColor, newColor);
}
if (j > 0) {
floodFillDFS(image, i, j - 1, oldColor, newColor);
}
if (i + 1 < image.length) {
floodFillDFS(image, i + 1, j, oldColor, newColor);
}
if (j + 1 < image[0].length) {
floodFillDFS(image, i, j + 1, oldColor, newColor);
}
}
```
迭代算法
套用`DFS`迭代算法模版。为了节省内存,将坐标`(i, j)`存入`int`中,高16位存放`i`,低16位存放`j`
```Java
public static int[][] floodFill(int[][] image, int sr, int sc, int newColor) {
final int oldColor = image[sr][sc];
if (oldColor == newColor) {
return image;
}
int i = sr, j = sc;
Deque<Integer> stack = new LinkedList<>();
// 高16位存放i,低16位存放j
stack.push((i << 16) | j);
int[] xDirection = {-1, 0, 1, 0};
int[] yDirection = {0, -1, 0, 1};
final int row = image.length;
final int col = image[0].length;
int cur, m, n;
while (stack.size() > 0) {
cur = stack.pop();
i = cur >> 16; // 获取高16位
j = cur & 0xffff; // 获取低16位
image[i][j] = newColor; // 重新上色
for (int k = 0; k < 4; k++) {
m = i + xDirection[k];
n = j + yDirection[k];
// 坐标符合条件,像素值与初始坐标相同,视为相连像素点
if (m >= 0 && m < row && n >= 0 && n < col
&& image[m][n] == oldColor) {
stack.push((m << 16) | n);
}
}
}
return image;
}
``` |
C++ | UTF-8 | 538 | 2.734375 | 3 | [] | no_license | #ifndef PLAYER_H_
#define PLAYER_H_
#include <vector>
#include <string>
#include <set>
#include "Tile.h"
using namespace std;
class Player {
public:
Player();
~Player();
// void place(set<Tile*> tiles, int x, int y);
// void pass();
// void exchange(set<Tile*>tiles);
void setName(string name);
void setScore(int x);
void setTiles(set<Tile*> x);
string getName();
int getScore();
set<Tile*> getTiles();
void place();
void exchange();
void pass();
private:
string name;
int score;
set<Tile*>tiles;
};
#endif |
TypeScript | UTF-8 | 2,263 | 2.796875 | 3 | [
"MIT"
] | permissive | import fs from "fs";
import { join as joinPath } from "path";
import type * as Preserve from "@truffle/preserve";
import type { TargetPathOptions, PathEntryOptions } from "./types";
export async function* targetPath(
options: TargetPathOptions
): Preserve.Process<Preserve.Target> {
const { path } = options;
const stats = await fs.promises.stat(path);
if (stats.isFile()) {
return {
source: yield* pathContent(options)
};
} else if (stats.isDirectory()) {
return {
source: yield* pathContainer(options)
};
}
}
async function* pathContent(
options: TargetPathOptions
): Preserve.Process<Preserve.Targets.Sources.Content> {
const { path, verbose, controls } = options;
const { step } = controls;
const task = verbose
? yield* step({ message: `Opening ./${path}...` })
: controls;
const content = fs.createReadStream(path);
if (verbose) {
yield* (task as Preserve.Control.StepsController).succeed();
}
return content;
}
async function* pathContainer(
options: TargetPathOptions
): Preserve.Process<Preserve.Targets.Sources.Container> {
const { path, verbose, controls } = options;
const { step } = controls;
const task = verbose
? yield* step({ message: `Reading directory ${path}...` })
: controls;
const directory = await fs.promises.readdir(path);
const entries: Preserve.Targets.Sources.Entry[] = [];
for (const childPath of directory) {
const entry = yield* pathEntry({
...options,
controls: task,
path: childPath,
parent: path
});
entries.push(entry);
}
if (verbose) {
yield* (task as Preserve.Control.StepsController).succeed();
}
return {
entries
};
}
async function* pathEntry(
options: PathEntryOptions
): Preserve.Process<Preserve.Targets.Sources.Entry> {
const { path, parent } = options;
const stats = await fs.promises.stat(joinPath(parent, path));
if (stats.isFile()) {
return {
path,
source: yield* pathContent({
...options,
path: joinPath(parent, path)
})
};
}
if (stats.isDirectory()) {
return {
path,
source: yield* pathContainer({
...options,
path: joinPath(parent, path)
})
};
}
}
|
Shell | UTF-8 | 623 | 2.859375 | 3 | [] | no_license | #!/bin/bash
set -o nounset -o pipefail -o errexit
IFACE=enp0s25
config() {
cat <<EOF
conky.config = {
background = false,
own_window = true,
own_window_type = 'desktop',
gap_x = 0,
gap_y = 0,
update_interval = 1,
alignment = 'top_left',
use_xft = true,
font = 'Inconsolata:pixelsize=50'
}
conky.text = [[
\${time %R}
\${exec monitor-client ping avg}ms \${exec monitor-client ping loss}% \${exec monitor-client location}
↓\${downspeedf $IFACE} ↑\${upspeedf $IFACE}
C:\${cpu}% T:\${hwmon 0 temp 1}° S:\${swapperc}% M:\${memperc}%
]]
EOF
}
timeout 5s conky --config=<(config)
|
C# | UTF-8 | 398 | 3.28125 | 3 | [] | no_license | using System;
namespace WhereIsMyCarOOP
{
class Program
{
static void Main(string[] args)
{
Car car = new Car("mark", "model", "123456", "blue");
car.PrintCarInfo();
while (car.DriveLap())
{
Console.WriteLine($"Car {car.Mark} drove a lap.");
}
car.PrintCarInfo();
}
}
}
|
Markdown | UTF-8 | 5,422 | 3.15625 | 3 | [] | no_license | # Conceitos Básicos I
## Dado e Informação
Tendo como base um sistema de computador, dados podem ser definidos como um conjunto de bits (ou de caracteres em uma macro visão) para armazenamento de caracteres e textos no formato alfanumérico ou, até mesmo, de arquivos e imagens.
Basicamente, um dado é um conjunto alfanumérico ou de imagem, que não está agregado a nenhum conhecimento específico, tornando-o inutilizável para quem não souber em qual contexto está contido e o que exatamente representa, não podendo interpretá-lo.
Exemplo:
**Informação**
A informação é um dado agregado a um conhecimento. A informação pode ser interpretada e o conhecimento apenas pode ser visualizado.
## Banco de Dados
**Banco de Dados**
Banco de dados é uma coleção de dados referentes a um assunto ou propósito específico.
>Banco de dados manuais: os dados armazenados em papel.
>Banco de dados automaticos: os dados amazenados em computadores.
>Banco de dados relacionais: há relações entre os seus dados (tabelas e entidades).
Todos os bancos de de dados relacionais mantêm algumas semelhaças entre si no que diz respeito às suas arquiteturas. Suas formas de armazenamento, componentes para criação de relacionamentos, estruturas para indexação de seus dados e organização interna, entre outras caractérsticas, são alguns dos benefícios gerados pela arquitetura de um banco relacional.
## Arquitetura de um Banco de Dados Relacional
**Tabela**
Os banco de dados realcionais, os dados são organizados em formato de tabela, onde cada coluna é um campo e cada linha um resgistro.
| Codigo | Fornecedor | Endereco | Telefone |
| :----: | :---- | :----- | :------ |
| 1 | Dutra Esquadria | Rua XV de Novembro | 1123-4545 |
| 2 | Alfa Aluminios | Rua Nunes Machado | 1263-9598 |
| 3 | Lider dos Metais | Rua Des. Mota | 1397-8426 |
| 4 | Nobre Siderurgica | Avenida dos Estados | 1637-4916 |
**Registro**
As linhas de uma tabela são chamadas de registro. Cada registro é formado por um conjuto de campos, os mesmos que formam a tabela.
| 1 | Dutra Esquadria | Rua XV de Novembro | 1123-4545 |
| :----: | :---- | :----- | :------ |
**Campo**
Cada coluna da tabela está representando um campo, o qual armazena as informaçãoes sobre um tipo de dado.
| Codigo | Fornecedor | Endereco | Telefone |
| :----: | :---- | :----- | :------ |
**Chave**
Chave é a coluna da tabela resposável por identificar os registros. O não uso de chave pode tornar o banco de dados vulnerável a diversos problemas: redundância de dados e inconsistência em relacionamento entre tabelas.
>Seja um cadastros de clientes, não se deve relacionar um cliente diretamente apenas por seu nome, pois há a possibilidade de haver dois clientes com exatamente o mesmo nome completo. Na situação de um sorteio de um prêmio e cliente o nome do cliente sorteado é Mário Anônio, porém no cadastro há dois clientes distintos com esse nome. Qual deles ficará com o prêmio? >Uma solução seria realizar um sorteio com base no número e no telefone do cliente (solução conhecida como chave composta), além disso >poderia ser usado o CPF do cliente, uma vez que o CPF é exclusivo para cada cliente (solução conhecida como chave primária).
Chave Primaira: A chave primária (do inglês, PK - Primary Key) é o caracterizada pelo fato de conter valores únicos. Por exemplo o CPF, na tabela seguinte:
| CPF | Nome |
| :----: | :---- |
| 001.001.001-01 | Carlos Drummond de Andrade |
| 002.002.002-02 | Machado de Assis |
| 003.003.003-03 | Erico Verissimo |
| 004.004 004-04 | Machado de Assis |
Chave Composta: A chave composta tanbém é caracterizada por conter um valor único, porém é formada por dois ou mais campos. Há chave composta pode admitir valores repetidos em suas colunas, mas as se considerar as duas simultaneamente essa possibilidade não pode ocorrer.
| Telefone|Nome |
| :----: | :---- |
| (41)1123-4456| Carlos Drummond de Andrade |
| (47)1223-2345 | Machado de Assis |
| (21)1212-2123 | Erico Verissimo |
| (11)1321-3213 | Machado de Assis |
A chave composta é utilizada para suprir a necessidade do uso de chave primária em um banco de dados não-normalizados. É aconselhavél o uso de chaves primárias simples, tanto por questões de performance quato pela facilidade de relacionamento de tabelas.
Chave Estrangeira: A chave estrangeira (FK - Foreing Key) é uma coluna que armazena a chave primária de outra tabela. A Chave estrangeira e a chave primaria forma o relacionamento entre tabelas.
**Tabela CLIENTES**
|Codigo |Nome |
| :----: | :---- |
| 1 | Carlos Drummond de Andrade |
| 2 | Machado de Assis |
| 3 | Erico Verissimo |
**Tabela VENDAS**
|Nota Fiscal | Cliente | Produto |
| :----: | :---- | :----- |
| 239 | 1 | dvd player |
| 240 | 1 | home theater |
| 241 | 2 | som |
>Neste caso, a coluna **Cliente** da tabela **VENDAS** está encarregada somente de armazenar o número do código do cliente responsável pela compra. Nessa tabela **VENDAS**, esse campo é chave estrangeira, pois tem origem em outra tabela, além de ser possível cadastrá-lo em mais de um registro, tendo em vista que um cliente pode realizar mais de uma compra na loja. A coluna **Codigo** na tabela **CLIENTEs** é a chave primária, pois o cliente é dadstrado uma única vez. Assim, o campo **Cliente** é uma chave estrangeira em **VENDAS** e o campo **Codigo** é a chave primária em **CLIENTE**
|
Markdown | UTF-8 | 2,254 | 3.3125 | 3 | [
"MIT"
] | permissive | ```
X
XXX
X X X
X X X
X X X
F X X X G
X X X
X D X A X
X X X
X X X
XXXXXXXXXXXXXXXXXXXXX
X X X
X X X
X C X B X
X X X
E X X X H
X X X
X X X
X X X
XXX
X
```
This Python3 script will take an eight digit input representing the faces
of a d8, and return the lowest equivalent eight digit output for the same
d8. For example the image above represents a d8 with four faces
visible, and four faces hidden. The first four digits of the input would
be starting from the face in the upper right quadrant, and moving around
the faces clockwise. In this case ABCD. The next four digits would
start from the opposite face from the upper right quadrent, E, and again
moving clockwise. In this case EFGH. The full eight digit input
would be ABCDEFGH.
### Notation about rotations
For this code, there are three axis defined as follows:
* Omega is the axis looking straight down. One turn around Omega is a
90 degree turn clockwise, A moves to B, B moves to C, C moves to D,...
E moves to F, F moves to G, etc.
* Theta is the axis from right to left. One turn around Theta is a 90
degree turn clockwise when viewed from the right: A moves to G, G moves to H, H moves to B, B
moves to A...
* Phi is the axis from bottom to top. One turn around Phi is a 90 degree
turn clockwise when viewed from the bottom: C moves to B, B moves to H,
and so on.
The code works by "rotating" the die so that the 1 is in the A position,
and the face adjacent to 1, that has the smallest value, is moved to
the B position. From there the output is generated in the same way
as the input, by reading of the new values that are in the positions
for ABCDEFGH.
|
Python | UTF-8 | 489 | 2.625 | 3 | [] | no_license | import sys
import random
n,m,c,rev,seed = map(int, sys.argv[1:])
random.seed(seed)
assert c <= n
assert c <= m
cn = random.randint(0, c)
cm = random.randint(0, c)
lim = (n+m) * 5
common = lim // 2
a = [common] * cn + sorted([random.randint(common + 1, lim) for _ in range(n - cn)])
b = sorted([random.randint(1, common - 1) for _ in range(m - cm)]) + [common] * cm
if rev:
n,m = m,n
a,b = b,a
print("{} {}".format(n,m))
print(" ".join(map(str, a)))
print(" ".join(map(str, b)))
|
JavaScript | UTF-8 | 209 | 2.75 | 3 | [] | no_license | class Hello extends React.Component {
render() {
let who = "World";
return (
<h1> Hello {who}! </h1>
);
}
}
ReactDOM.render( <Hello/>, document.querySelector("#root")); |
Python | UTF-8 | 2,040 | 3.234375 | 3 | [] | no_license | import numpy as np
from math import sqrt, pi, exp, pow, factorial, fabs, ceil
distributions = [
{
'name': 'normal',
'func': lambda size: np.random.normal(size=size),
'destiny': lambda x: 1 / sqrt(2 * pi) * exp(-x * x / 2)
},
{
'name': 'poisson',
'func': lambda size: np.random.poisson(10, size=size),
'destiny': lambda x: (pow(10, round(x)) / factorial(round(x))) * exp(-10)
},
{
'name': 'cauchy',
'func': lambda size: np.random.standard_cauchy(size=size),
'destiny': lambda x: 1 / pi * ( 1 / (x*x + 1))
},
{
'name': 'laplace',
'func': lambda size: np.random.laplace(0, 1/sqrt(2), size=size),
'destiny': lambda x: (1 / sqrt(2)) * exp(-sqrt(2) * fabs(x))
},
{
'name': 'uniform',
'func': lambda size: np.random.uniform(-sqrt(3), sqrt(3),size=size),
'destiny': lambda x: 1 / (2 * sqrt(3)) if (fabs(x) <= sqrt(3)) else 0
},
]
specifications = [
{
"name": "M",
"count": lambda x: np.mean(x)
},
{
"name": "med",
"count": lambda x: np.median(x)
},
{
"name": "D",
"count": lambda x: np.var(x)
},
{
"name": "zr",
"count": lambda x: (min(x)+max(x)) / 2
},
{
"name": "zq",
"count": lambda x: (sorted(x)[ceil(len(x) * 1/4)] + sorted(x)[ceil(len(x) * 3 / 4)]) / 2
},
{
"name": "ztr",
"count": lambda x: np.mean([x[i] for i in range(len(x)) if i > (len(x) / 4) and i < len(x) * 3 / 4])
}
]
capacities = [10, 100, 1000]
for dist in distributions:
print("-------" + dist["name"]+"-------")
for spec in specifications:
print(spec["name"])
for cap in capacities:
print("capacity %s" % cap)
char = []
for i in range(1000):
x = dist["func"](cap)
char.append(spec["count"](x))
print("E: %s" % np.mean(char))
print("D: %s" % np.var(char)) |
C | UTF-8 | 532 | 3.296875 | 3 | [] | no_license | #include "array.h"
int printArray(char *st,int n)
{
int i = 0;
if(NULL == st)
{
printf("The array is empty!\n");
return 1;
}
for(i = 0;i < n;i++)
{
printf("%c ",st[i]);
}
printf("\n");
return 0;
}
int getArray(void)
{
char str[10] = "array";
int result = 0;
printf("array!This is in libarray.a");
printf("strlen(string) is %d!\n",strlen(str));
printf("sizeof(string) is %d!\n",sizeof(str));
result = printArray(str,strlen(str));
if (0 != result)
{
printf("printArray error!");
return 1;
}
return 0;
}
|
Markdown | UTF-8 | 5,815 | 2.546875 | 3 | [
"MIT"
] | permissive | # CryptHash.NET
[](#)
[](https://nuget.org/packages/CryptHash.Net)
[](https://nuget.org/packages/CryptHash.Net)
[](https://ci.appveyor.com/project/alecgn/crypthash-net)
### A .NET multi-target Library and .NET Core Console Application utility for encryption/decryption, hashing and encoding/decoding.
The .NET Core console utility is designed to run in Windows, Linux and Mac, for text and files symmetric authenticated encryption/decryption, text/files hashing and text encoding/decoding. File checksum functionality is also available, you can calculate and verify the integrity of downloaded files from the internet with the source supplied hash, with a progress event notifier for big files.
The multi-target libray (.NET Standard 2.0/2.1) can be used in projects with any .NET implementation like **.NET Framework**, **.NET Core**, **Mono**, **Xamarin**, etc. Verify the .NET Standard compatibility table here: https://github.com/dotnet/standard/blob/master/docs/versions.md
Currently symmetric encryption algorithms are:
* **AES 128 bits** in **CBC Mode** with **HMACSHA256 Authentication** and **Salt**, using the **Encrypt-then-MAC (EtM)** strategy.
* **AES 192 bits** in **CBC Mode** with **HMACSHA384 Authentication** and **Salt**, using the **Encrypt-then-MAC (EtM)** strategy.
* **AES 256 bits** in **CBC Mode** with **HMACSHA384 Authentication** and **Salt**, using the **Encrypt-then-MAC (EtM)** strategy.
* **AES 256 bits** in **CBC Mode** with **HMACSHA512 Authentication** and **Salt**, using the **Encrypt-then-MAC (EtM)** strategy.
* **AES 128 bits** in **GCM Mode** with **Authentication** and **Associated Data** (**AEAD**).
* **AES 192 bits** in **GCM Mode** with **Authentication** and **Associated Data** (**AEAD**).
* **AES 256 bits** in **GCM Mode** with **Authentication** and **Associated Data** (**AEAD**).
Currently supported hash/KDF algorithms are:
* **MD5**
* **SHA1**
* **SHA256**
* **SHA384**
* **SHA512**
* **HMAC-MD5**
* **HMAC-SHA1**
* **HMAC-SHA256**
* **HMAC-SHA384**
* **HMAC-SHA512**
* **PBKDF2**
* **BCrypt**
* **Argon2id**
Currently supported encoding types are:
* **Base64**
* **Hexadecimal**
Other encryption/hashing/encoding algorithms will be implemented in the future.
NuGet package: https://www.nuget.org/packages/CryptHash.Net
Compiled console utility binaries (single file self-contained / no framework dependent) for Windows (x86/x64/ARM), Linux (x64/ARM -> Raspberry Pi) and Mac (x64): https://github.com/alecgn/crypthash-net/releases/tag/v3.6.0. When running on Linux or Mac, don't forget to navigate to the program's folder and "**chmod +x crypthash**". For usage help, call the program without patameters or pass the "--help" parameter.
**WARNING:** PER SEMANTIC VERSIONING, THE ABOVE RELEASE (3.x.x) IS NOT COMPATIBLE WITH PREVIOUS RELEASES (1.x.x and 2.x.x), AND AS SUCH MIGHT NOT PROPERLY DECRYPT DATA YOU ENCRYPTED WITH PREVIOUS VERSIONS.
From this version (3.x.x) onwards, any new implementations will be planned so as to maintain compatibility and stability. There should be no more breaking-changes, as the project's architecture and design are already well defined. If there is a need to make a breaking-change going forward then a method for properly decryting data you encryted with version 3.x.x will be provided.
Publish it yourself using the following dotnet client command-line:
>**dotnet publish -c Release -r \<RID\> /p:PublishSingleFile=true /p:PublishTrimmed=true**
--------------------------------------------------
**WINDOWS RIDs**
**Portable**
- win-x86
- win-x64
**Windows 7 / Windows Server 2008 R2**
- win7-x64
- win7-x86
**Windows 8 / Windows Server 2012**
- win8-x64
- win8-x86
- win8-arm
**Windows 8.1 / Windows Server 2012 R2**
- win81-x64
- win81-x86
- win81-arm
**Windows 10 / Windows Server 2016**
- win10-x64
- win10-x86
- win10-arm
- win10-arm64
--------------------------------------------------
**LINUX RIDs**
**ARM / Raspberry Pi (Raspbian)**
- linux-arm
**Portable**
- linux-x64
**CentOS**
- centos-x64
- centos.7-x64
**Debian**
- debian-x64
- debian.8-x64
**Fedora**
- fedora-x64
- fedora.24-x64
- fedora.25-x64 (.NET Core 2.0 or later versions)
- fedora.26-x64 (.NET Core 2.0 or later versions)
**Gentoo (.NET Core 2.0 or later versions)**
- gentoo-x64
**openSUSE**
- opensuse-x64
- opensuse.42.1-x64
**Oracle Linux**
- ol-x64
- ol.7-x64
- ol.7.0-x64
- ol.7.1-x64
- ol.7.2-x64
**Red Hat Enterprise Linux**
- rhel-x64
- rhel.6-x64 (.NET Core 2.0 or later versions)
- rhel.7-x64
- rhel.7.1-x64
- rhel.7.2-x64
- rhel.7.3-x64 (.NET Core 2.0 or later versions)
- rhel.7.4-x64 (.NET Core 2.0 or later versions)
**Tizen (.NET Core 2.0 or later versions)**
- tizen
**Ubuntu**
- ubuntu-x64
- ubuntu.14.04-x64
- ubuntu.14.10-x64
- ubuntu.15.04-x64
- ubuntu.15.10-x64
- ubuntu.16.04-x64
- ubuntu.16.10-x64
**Ubuntu derivatives**
- linuxmint.17-x64
- linuxmint.17.1-x64
- linuxmint.17.2-x64
- linuxmint.17.3-x64
- linuxmint.18-x64
- linuxmint.18.1-x64 (.NET Core 2.0 or later versions)
--------------------------------------------------
**macOS RIDs**
**macOS RIDs use the older "OSX" branding.**
- osx-x64 (.NET Core 2.0 or later versions, minimum version is osx.10.12-x64)
- osx.10.10-x64
- osx.10.11-x64
- osx.10.12-x64 (.NET Core 1.1 or later versions)
- osx.10.13-x64
--------------------------------------------------
**Complete RID LIST**
(https://docs.microsoft.com/en-us/dotnet/core/rid-catalog)
|
Java | UTF-8 | 8,048 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | package com.shijingsh.ai.jsat.math.optimization;
import java.util.ArrayList;
import java.util.List;
import com.shijingsh.ai.jsat.linear.IndexValue;
import com.shijingsh.ai.jsat.linear.Vec;
import com.shijingsh.ai.jsat.math.Function;
import com.shijingsh.ai.jsat.math.FunctionVec;
import com.shijingsh.ai.jsat.linear.IndexValue;
import com.shijingsh.ai.jsat.linear.Vec;
import com.shijingsh.ai.jsat.math.FunctionVec;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
/**
* Implementation of the Limited memory variant of {@link BFGS}. It uses a
* history of {@link #setM(int) m} items to solve {@code n} dimension problems
* with {@code O(m n)} work per iteration.
*
* @author Edward Raff
*/
public class LBFGS implements Optimizer {
private int m;
private int maxIterations;
private LineSearch lineSearch;
private boolean inftNormCriterion = true;
/**
* Creates a new L-BFGS optimization object that uses a maximum of 500
* iterations and a {@link BacktrackingArmijoLineSearch Backtracking} line
* search. A {@link #setM(int) history} of 10 items will be used
*/
public LBFGS() {
this(10);
}
/**
* Creates a new L-BFGS optimization object that uses a maximum of 500
* iterations and a {@link BacktrackingArmijoLineSearch Backtracking} line
* search.
*
* @param m the number of history items
*/
public LBFGS(int m) {
this(m, 500, new BacktrackingArmijoLineSearch());
}
/**
* Creates a new L-BFGS optimization object
*
* @param m the number of history items
* @param maxIterations the maximum number of iterations before stopping
* @param lineSearch the line search method to use for optimization
*/
public LBFGS(int m, int maxIterations, LineSearch lineSearch) {
setM(m);
setMaximumIterations(maxIterations);
setLineSearch(lineSearch);
}
/**
* See Algorithm 7.4 (L-BFGS two-loop recursion).
*
* @param x_grad the initial value ∇ f<sub>k</sub>
* @param rho
* @param s
* @param y
* @param q the location to store the value of H<sub>k</sub> ∇
* f<sub>k</sub>
* @param alphas temp space to do work, should be as large as the number of
* history vectors
*/
public static void twoLoopHp(Vec x_grad, List<Double> rho, List<Vec> s, List<Vec> y, Vec q, double[] alphas) {
// q ← ∇ fk;
x_grad.copyTo(q);
if (s.isEmpty())
return;// identity, we are done
// for i = k−1,k−2,...,k−m
for (int i = 0; i < s.size(); i++) {
Vec s_i = s.get(i);
Vec y_i = y.get(i);
double alpha_i = alphas[i] = rho.get(i) * s_i.dot(q);
q.mutableSubtract(alpha_i, y_i);
}
// r ← Hk0q; and see eq (7.20), done in place in q
q.mutableMultiply(s.get(0).dot(y.get(0)) / y.get(0).dot(y.get(0)));
// for i = k−m,k−m+1,...,k−1
for (int i = s.size() - 1; i >= 0; i--) {
// β ← ρ_i y_i^T r ;
double beta = rho.get(i) * y.get(i).dot(q);
// r ← r + si (αi − β)
q.mutableAdd(alphas[i] - beta, s.get(i));
}
}
@Override
public void optimize(double tolerance, Vec w, Vec x0, Function f, FunctionVec fp, boolean parallel) {
if (fp == null)
fp = Function.forwardDifference(f);
LineSearch search = lineSearch.clone();
final double[] f_xVal = new double[1];// store place for f_x
// history for implicit H
DoubleArrayList Rho = new DoubleArrayList(m);
List<Vec> S = new ArrayList<>(m);
List<Vec> Y = new ArrayList<>(m);
Vec x_prev = x0.clone();
Vec x_cur = x0.clone();
f_xVal[0] = f.f(x_prev, parallel);
// graidnet
Vec x_grad = x0.clone();
x_grad.zeroOut();
Vec x_gradPrev = x_grad.clone();
// p_l
Vec p_k = x_grad.clone();
Vec s_k = x_grad.clone();
Vec y_k = x_grad.clone();
x_grad = fp.f(x_cur, x_grad, parallel);
double[] alphas = new double[m];
int iter = 0;
while (gradConvgHelper(x_grad) > tolerance && iter < maxIterations) {
// p_k = −H_k ∇f_k; (6.18)
twoLoopHp(x_grad, Rho, S, Y, p_k, alphas);
p_k.mutableMultiply(-1);
// Set x_k+1 = x_k + α_k p_k where α_k is computed from a line search
x_cur.copyTo(x_prev);
x_grad.copyTo(x_gradPrev);
double alpha_k = search.lineSearch(1.0, x_prev, x_gradPrev, p_k, f, fp, f_xVal[0], x_gradPrev.dot(p_k), x_cur, f_xVal, x_grad, parallel);
if (alpha_k < 1e-12)// if we are making near epsilon steps consider it done
break;
if (!search.updatesGrad())
fp.f(x_cur, x_grad, parallel);
// Define s_k =x_k+1 −x_k and y_k = ∇f_k+1 −∇f_k;
x_cur.copyTo(s_k);
s_k.mutableSubtract(x_prev);
S.add(0, s_k.clone());
x_grad.copyTo(y_k);
y_k.mutableSubtract(x_gradPrev);
Y.add(0, y_k.clone());
Rho.add(0, 1 / s_k.dot(y_k));
if (Double.isInfinite(Rho.get(0)) || Double.isNaN(Rho.get(0))) {
Rho.clear();
S.clear();
Y.clear();
}
while (Rho.size() > m) {
Rho.remove(m);
S.remove(m);
Y.remove(m);
}
iter++;
}
x_cur.copyTo(w);
}
/**
* By default the infinity norm is used to judge convergence. If set to
* {@code false}, the 2 norm will be used instead.
*
* @param inftNormCriterion
*/
public void setInftNormCriterion(boolean inftNormCriterion) {
this.inftNormCriterion = inftNormCriterion;
}
/**
* Returns whether or not the infinity norm ({@code true}) or 2 norm
* ({@code false}) is used to determine convergence.
*
* @return {@code true} if the infinity norm is in use, {@code false} for the 2
* norm
*/
public boolean isInftNormCriterion() {
return inftNormCriterion;
}
private double gradConvgHelper(Vec grad) {
if (!inftNormCriterion)
return grad.pNorm(2);
double max = 0;
for (IndexValue iv : grad)
max = Math.max(max, Math.abs(iv.getValue()));
return max;
}
/**
* Sets the number of history items to keep that are used to approximate the
* Hessian of the problem
*
* @param m the number of history items to keep
*/
public void setM(int m) {
if (m < 1)
throw new IllegalArgumentException("m must be positive, not " + m);
this.m = m;
}
/**
* Returns the number of history items that will be used
*
* @return the number of history items that will be used
*/
public int getM() {
return m;
}
/**
* Sets the line search method used at each iteration
*
* @param lineSearch the line search method used at each iteration
*/
public void setLineSearch(LineSearch lineSearch) {
this.lineSearch = lineSearch;
}
/**
* Returns the line search method used at each iteration
*
* @return the line search method used at each iteration
*/
public LineSearch getLineSearch() {
return lineSearch;
}
@Override
public void setMaximumIterations(int iterations) {
if (iterations < 1)
throw new IllegalArgumentException("Number of iterations must be positive, not " + iterations);
this.maxIterations = iterations;
}
@Override
public int getMaximumIterations() {
return maxIterations;
}
@Override
public LBFGS clone() {
return new LBFGS(m, maxIterations, lineSearch.clone());
}
}
|
JavaScript | UTF-8 | 5,237 | 2.53125 | 3 | [
"MIT"
] | permissive | /* eslint-disable */
// TODO: Remove previous line and work through linting issues at next edit
'use strict';
var BufferReader = require('../encoding/bufferreader');
var BufferWriter = require('../encoding/bufferwriter');
var BufferUtil = require('../util/buffer');
var _ = require('lodash');
var isHexString = require('../util/js').isHexa;
var SimplifiedMNListEntry = require('./SimplifiedMNListEntry');
var PartialMerkleTree = require('./PartialMerkleTree');
var Transaction = require('../transaction');
var constants = require('../constants');
/**
* @param {Buffer|Object|string} [arg] - A Buffer, JSON string, or Object representing a MnListDiff
* @class {SimplifiedMNListDiff}
* @property {string} baseBlockHash - sha256
* @property {string} blockHash - sha256
* @property {PartialMerkleTree} cbTxMerkleTree;
* @property {Transaction} cbTx;
* @property {Array<string>} deletedMNs - sha256 hashes of deleted MNs
* @property {Array<SimplifiedMNListEntry>} mnList
* @property {string} merkleRootMNList - merkle root of the whole mn list
*/
function SimplifiedMNListDiff(arg) {
if (arg) {
if (arg instanceof SimplifiedMNListDiff) {
return arg.copy();
} else if (BufferUtil.isBuffer(arg)) {
return SimplifiedMNListDiff.fromBuffer(arg);
} else if (_.isObject(arg)) {
return SimplifiedMNListDiff.fromObject(arg);
} else if (isHexString(arg)) {
return SimplifiedMNListDiff.fromHexString(arg);
} else {
throw new TypeError('Unrecognized argument passed to SimplifiedMNListDiff constructor');
}
}
}
/**
* Creates MnListDiff from a Buffer.
* @param {Buffer} buffer
* @return {SimplifiedMNListDiff}
*/
SimplifiedMNListDiff.fromBuffer = function fromBuffer(buffer) {
var bufferReader = new BufferReader(Buffer.from(buffer));
var data = {};
data.baseBlockHash = bufferReader.read(constants.SHA256_HASH_SIZE).reverse().toString('hex');
data.blockHash = bufferReader.read(constants.SHA256_HASH_SIZE).reverse().toString('hex');
data.cbTxMerkleTree = PartialMerkleTree.fromBufferReader(bufferReader);
data.cbTx = new Transaction().fromBufferReader(bufferReader);
var deletedMNsCount = bufferReader.readVarintNum();
data.deletedMNs = [];
for (var i = 0; i < deletedMNsCount; i++) {
data.deletedMNs.push(bufferReader.read(constants.SHA256_HASH_SIZE).reverse().toString('hex'));
}
var mnListSize = bufferReader.readVarintNum();
data.mnList = [];
for (var i = 0; i < mnListSize; i++) {
data.mnList.push(SimplifiedMNListEntry.fromBuffer(bufferReader.read(constants.SML_ENTRY_SIZE)));
}
data.merkleRootMNList = data.cbTx.extraPayload.merkleRootMNList;
return this.fromObject(data);
};
/**
* @param {string} hexString
* @return {SimplifiedMNListDiff}
*/
SimplifiedMNListDiff.fromHexString = function fromHexString(hexString) {
return SimplifiedMNListDiff.fromBuffer(Buffer.from(hexString, 'hex'));
};
/**
* Serializes mnlist diff to a Buffer
* @return {Buffer}
*/
SimplifiedMNListDiff.prototype.toBuffer = function toBuffer() {
var bufferWriter = new BufferWriter();
bufferWriter.write(Buffer.from(this.baseBlockHash, 'hex').reverse());
bufferWriter.write(Buffer.from(this.blockHash, 'hex').reverse());
bufferWriter.write(this.cbTxMerkleTree.toBuffer());
bufferWriter.write(this.cbTx.toBuffer());
bufferWriter.writeVarintNum(this.deletedMNs.length);
this.deletedMNs.forEach(function (deleteMNHash) {
bufferWriter.write(Buffer.from(deleteMNHash, 'hex').reverse());
});
bufferWriter.writeVarintNum(this.mnList.length);
this.mnList.forEach(function (simplifiedMNListEntry) {
bufferWriter.write(simplifiedMNListEntry.toBuffer());
});
return bufferWriter.toBuffer();
};
/**
* Creates MNListDiff from object
* @param obj
* @return {SimplifiedMNListDiff}
*/
SimplifiedMNListDiff.fromObject = function fromObject(obj) {
var simplifiedMNListDiff = new SimplifiedMNListDiff();
simplifiedMNListDiff.baseBlockHash = obj.baseBlockHash;
simplifiedMNListDiff.blockHash = obj.blockHash;
/* cbTxMerkleRoot start */
simplifiedMNListDiff.cbTxMerkleTree = new PartialMerkleTree(obj.cbTxMerkleTree);
/* cbTxMerkleRoot stop */
simplifiedMNListDiff.cbTx = new Transaction(obj.cbTx);
// Copy array of strings
simplifiedMNListDiff.deletedMNs = obj.deletedMNs.slice();
simplifiedMNListDiff.mnList = obj.mnList.map(function (SMLEntry) {
return new SimplifiedMNListEntry(SMLEntry);
});
simplifiedMNListDiff.merkleRootMNList = obj.merkleRootMNList;
return simplifiedMNListDiff;
};
SimplifiedMNListDiff.prototype.toObject = function toObject() {
var obj = {};
obj.baseBlockHash = this.baseBlockHash;
obj.blockHash = this.blockHash;
/* cbTxMerkleRoot start */
obj.cbTxMerkleTree = this.cbTxMerkleTree.toString();
/* cbTxMerkleRoot stop */
obj.cbTx = this.cbTx.serialize(true);
// Copy array of strings
obj.deletedMNs = this.deletedMNs.slice();
obj.mnList = this.mnList.map(function (SMLEntry) {
return SMLEntry.toObject();
});
obj.merkleRootMNList = this.merkleRootMNList;
return obj;
};
SimplifiedMNListDiff.prototype.copy = function copy() {
return SimplifiedMNListDiff.fromBuffer(this.toBuffer());
};
module.exports = SimplifiedMNListDiff;
|
Java | UTF-8 | 2,358 | 2.6875 | 3 | [] | no_license | package com.yhh.mybatis.dao;
import com.yhh.mybatis.entity.User;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
/**
* @Author: -小野猪-
* @Date: 2019/6/30 0:00
* @Version: 1.0
* @Desc:
*/
public class UserDaoImpl implements UserDao {
// 需要向dao实现类中注入SqlSessionFactory
private SqlSessionFactory sqlSessionFactory;
// 这里通过构造方法注入
public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public User findUserById(int id) throws Exception {
/* SqlSession是线程不安全的,在SqlSesion实现类中除了有接口中的方法(操作数据库的方法)还有数据域属性。
*/
SqlSession sqlSession = sqlSessionFactory.openSession();
/*1、将statement的id硬编码了 ("test.findUserById")
*2、sqlsession方法使用泛型,即使变量类型传入错误,在编译阶段也不报错,不利于程序员开发。
*/
User user = sqlSession.selectOne("test.findUserById", id);
sqlSession.close();
return user;
}
@Override
public List<User> findUserByName(String name) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
List<User> list = sqlSession.selectList("test.findUserByName", name);
sqlSession.close();
return list;
}
@Override
public int insertUser(User user) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
int count = sqlSession.insert("test.insertUser", user);
sqlSession.commit();
sqlSession.close();
return count;
}
@Override
public int deleteUser(int id) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
int count = sqlSession.delete("test.deleteUser", id);
sqlSession.commit();
sqlSession.close();
return count;
}
@Override
public int updateUser(User user) throws Exception {
SqlSession sqlSession = sqlSessionFactory.openSession();
int count = sqlSession.update("test.updateUser", user);
sqlSession.commit();
sqlSession.close();
return count;
}
}
|
Java | UTF-8 | 218 | 1.859375 | 2 | [] | no_license | package com.weikun.service;
import com.weikun.model.Account;
/**
* Created by Administrator on 2016/9/5.
*/
public interface IUserService {
Account login( Account record);
int register(Account record);
}
|
Java | GB18030 | 2,762 | 2.796875 | 3 | [] | no_license | package org.housy.mario;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
public class StaticValue {
//
public static List<BufferedImage> allMarioImage = new ArrayList<BufferedImage>();
//ͼƬ
public static BufferedImage startImage = null;
public static BufferedImage endImage = null;
public static BufferedImage bgImage = null;
//
public static List<BufferedImage> allFlowerImage = new ArrayList<BufferedImage>();
public static List<BufferedImage> allTriangleImage = new ArrayList<BufferedImage>();
public static List<BufferedImage> allTurtleImage = new ArrayList<BufferedImage>();
public static List<BufferedImage> allFireImage = new ArrayList<BufferedImage>();
//ϰ
public static List<BufferedImage> allObstructionImage = new ArrayList<BufferedImage>();
public static BufferedImage marioDeadImage = null;
public static String imagePath = System.getProperty("user.dir") + "/mario";
//ʼȫͼƬʼ
public static void init() {
System.out.println(imagePath);
for(int i = 1; i <=10; i ++) {
//System.getProperty("")Ŀǰڵ·
try {
//µͼƬ浽
allMarioImage.add(ImageIO.read(new File(imagePath + "/mario" + i + ".png")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//뱱ͼƬ
try {
startImage = ImageIO.read(new File(imagePath + "/first.jpg"));
endImage = ImageIO.read(new File(imagePath + "/end.jpg"));
bgImage = ImageIO.read(new File(imagePath + "/background.jpg"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//ͼƬ
for(int i = 1; i <= 3; i ++) {
try {
if (i <= 2) {
allFlowerImage.add(ImageIO.read(new File(imagePath + "/flower" + i + ".png")));
allFireImage.add(ImageIO.read(new File(imagePath + "/fire" + i + ".png")));
}
allTriangleImage.add(ImageIO.read(new File(imagePath + "/triangle" + i + ".png")));
allTurtleImage.add(ImageIO.read(new File(imagePath + "/turtuile" + i + ".png")));
} catch(IOException e) {
e.printStackTrace();
}
}
//ϰ
for(int i = 1; i <= 25; i ++) {
try {
allObstructionImage.add(ImageIO.read(new File(imagePath + "/db" + i + ".png")));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//ͼƬ
try {
marioDeadImage = ImageIO.read(new File(imagePath + "/over.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
Java | UTF-8 | 6,056 | 2.875 | 3 | [] | no_license | package laundyclinic;
import java.sql.*;
import java.util.Vector;
import javax.swing.*;
public class MyTools {
// this code is used to manipulate the JTable
// columnNames and data should be return to the caller to fill in the
// columns and rows of the table
private Vector columnNames = new Vector();
private Vector data = new Vector();
private String myDatabaseName;
public void setMyDatabase(String myDatabaseName){
this.myDatabaseName=myDatabaseName;
}
public Vector getColumnNames(){
return columnNames;
}
public Vector getData(){
return data;
}
public void tableLoadData(String query){
Statement st=null;
Connection con=null;
//String query=null;
ResultSet res=null;
ResultSetMetaData rsmd=null;
//columnNames=new Vector();
columnNames.clear();
//data=new Vector();
data.clear();
//JOptionPane.showMessageDialog(null, query);
try{
Class.forName("com.mysql.jdbc.Driver");
//String x = "jdbc:mysql://localhost:3306/sales" + "," + "root" + "," + "";
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/itse","root","");
//con = DriverManager.getConnection(x);
st = con.createStatement();
res = st.executeQuery(query);
rsmd = res.getMetaData();
int column = rsmd.getColumnCount();
for(int i=1; i<=column; i++){
columnNames.add(rsmd.getColumnLabel(i));
}
while(res.next()) {
Vector row = new Vector(column);
for(int i=1; i<=column; i++) {
row.addElement(res.getObject(i));
}
data.addElement(row);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.toString());
}finally{
try{
rsmd=null;
query=null;
st.close();
res.close();
con.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Finally Error:" + e.toString());
}
}
}//reloadData
//This code is used to manipulate the JComboBox
//the parameters are:
//JComboBox --> is where the data will be stored
//query --> code to get data to the database. It should have only two columns
// the id and description
//column1 --> description of column 1
//column2 --> description of column 2
public void loadComboData(JComboBox comboBox,String query,String column1, String column2){
Connection con=null;
Statement st=null;
ResultSet res=null;
comboBox.removeAll();
try{
Class.forName("com.mysql.jdbc.Driver");
//String Base = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=SL.mdb";
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/itse","root","");
st = con.createStatement();
//String query="Select posID,posDescription from tblposition";
//res = st.executeQuery("Select posID,posDescription from tblposition");
res = st.executeQuery(query);
while(res.next()) {
//positionCB.addItem(new Item(res.getInt("posID"),res.getString("posDescription")));
//comboBox.addItem(new Item(res.getInt("posID"),res.getString("posDescription")));
comboBox.addItem(new Item(res.getInt(column1),res.getString(column2)));
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.toString());
}finally{
try{
st.close();
res.close();
con.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Finally Error:" + e.toString());
}
}
}
// used to select a particular data in the combo box
public void empComboData(JComboBox comboBox,String query,String column1, String column2, String column3){
Connection con=null;
Statement st=null;
ResultSet res=null;
comboBox.removeAll();
try{
Class.forName("com.mysql.jdbc.Driver");
//String Base = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=SL.mdb";
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/itse","root","");
st = con.createStatement();
//String query="Select posID,posDescription from tblposition";
//res = st.executeQuery("Select posID,posDescription from tblposition");
res = st.executeQuery(query);
while(res.next()) {
//positionCB.addItem(new Item(res.getInt("posID"),res.getString("posDescription")));
//comboBox.addItem(new Item(res.getInt("posID"),res.getString("posDescription")));
comboBox.addItem(new Item(res.getInt(column1),res.getString(column2)+" "+res.getString(column3)));
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.toString());
}finally{
try{
st.close();
res.close();
con.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, "Finally Error:" + e.toString());
}
}
}
// used to select a particular data in the combo box
public int setSelectedValue(JComboBox comboBox, String value){
Item itemCombo;
int i=0;
for(i=0;i<comboBox.getItemCount();i++){
itemCombo = (Item) comboBox.getItemAt(i);
if(itemCombo.getDescription().equals(value)){
//comboBox.setSelectedIndex(i);
break;
}
}
return i;
//comboBox.updateUI();
}//setSelectedValue
}//class
|
Markdown | UTF-8 | 5,438 | 2.546875 | 3 | [] | no_license | # HTTP는 무엇일까요?
### ❗ HTTP란?
HTTP(Hyper Text Transfer Protocol) 는
텍스트 기반의 통신 규약이며 <u>"인터넷에서 정보를 주고 받을 수 있는 프로토콜"</u> 을 의미한다.
80번 포트를 사용하며, [TCP](https://github.com/hjyeon-n/BE_TIL/blob/master/%EC%9D%B8%ED%84%B0%EB%84%B7/%EC%9D%B8%ED%84%B0%EB%84%B7%EC%9D%80%20%EC%96%B4%EB%96%BB%EA%B2%8C%20%EC%9E%91%EB%8F%99%EB%90%A0%EA%B9%8C%EC%9A%94.md) 와 [UDP](https://github.com/hjyeon-n/BE_TIL/blob/master/%EC%9D%B8%ED%84%B0%EB%84%B7/%EC%9D%B8%ED%84%B0%EB%84%B7%EC%9D%80%20%EC%96%B4%EB%96%BB%EA%B2%8C%20%EC%9E%91%EB%8F%99%EB%90%A0%EA%B9%8C%EC%9A%94.md)를 이용한다.
HTTP는 웹에서만 사용하는 프로콜로 [TCP/IP](TCP/IP)를 기반으로 한 지점에서 다른 지점으로 요청과 응답을 전송한다.
<br/>
#### ❗ HTTP의 동작방식

<br/>
[^Client 이미지]: Icons made by <a href="http://www.freepik.com/" title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" title="Flaticon"> www.flaticon.com</a>
HTTP는 위의 그림처럼, client가 server에게 요청을 보내면 server가 응답하는 방식으로 동작한다.
<br/>
**✔** **요청 (Request)**
- 클라이언트가 서버에게 연락하는 것을 의미하며 요청을 보낼 때 요청에 대한 정보도 함께 보낸다.
<br/>
**✔ 요청의 종류 (Request Method)**
- **GET**: URI형식으로 서버측 데이터를 요청한다.
- **POST**: 요청 URI에 폼 입력을 처리하기 위해 구성한 서버측 스크립트(ASP, PHP, JSP 등) 혹은 CGI 프로그램으로 구성되고, Form Action과 함께 전송된다. 이 때, 헤더 부분이 아닌 데이터 부분에 요청 정보가 포함된다.
- **HEAD**: GET 방식과 유사하나, 웹 서버에서 헤더 정보 이외에는 어떤 데이터도 보내지 않는다.
- **PUT**: POST 방식과 유사한 전송 구조를 가진다. 헤더 이외에 데이터가 함께 전송된다. 서버에 지정한 콘텐츠를 저장하기 위해 사용되며 홈페이지 변조에 많이 악용되고 있다.
- **DELETE**: 웹 서버에 파일을 삭제하기 위해 사용된다. (PUT과 반대개념)
<br/>
**✔ Request 메시지 예시**
GET https://github.com HTTP/1.1 ▶ 메소드 구조 버전을 의미
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) ... ▶ 헤더 (요청에 대한 정보)
Upgrade-Insecure-Requests: 1
▶ 본문은 헤더에서 한 줄을 띄고 구성되며 데이터를 담아 보내는 부분이다. 현재 예시에서는 ❌
<br/>
**✔ 응답 (Response)**
- 서버가 요청에 대한 답변을 클라이언트에 보내는 것이다.
<br/>
**✔ 응답 상태 코드 (Status Code)**
- **1XX (조건부 응답)**: 요청을 받았으며 작업을 계속한다.
- **2XX (성공)**: 클라이언트가 요청한 동작을 승낙해 성공적으로 처리했음을 의미한다.
- **3XX (리다이렉션 완료)**: 클라이언트가 요청을 마치기 위해 추가 동착을 취해야 함을 의미한다.
- **4XX (요청 오류)**: 클라이언트에 오류가 있음을 의미한다.
- **5XX (서버 오류)**: 서버가 요청 수행헤 실패했음을 의미한다.
<br/>
**✔ 응답 메시지 예시**
HTTP/1.1 200 OK ▶ 첫 줄은 버전, 상태 코드, 상태 메시지로 구성되어 있다.
Connection: keep-alive ▶ 헤더 (응답에 대한 정보)
Content-Encoding: gzip
...
```null
<!DOCTYPE html><html lang="ko"><head><title...
```
▲ 본문 (HTML이 담겨 있으며 HTML을 통해 브라우저가 화면에 랜더링 한다. )
<br/>
#### ❗ HTTP의 특징
1. HTTP는 연결상태를 유지하지 않는 비연결성 프로콜이다.
즉, 브라우저를 통해 사용자의 요청에 따라 서버와 접속해 요청에 대한 응답 데이터를 전송 후 연결을 종료한다. 이러한 점은 전산 자원이 적게 든다는 장점이 있지만, 사용자의 종료 후 추가적인 요청을 처리할 수 없다는 단점이 있다. 이를 해소하기 위해 Cookie, Session, URL Rewriting 등이 사용되고 있다.
2. HTTP 메시지는 HTTP 서버와 HTTP 클라이언트에 의해 해석된다.
3. HTTP는 요청을 독립적인 트랜잭션으로 취급한다.
이전 요청과 다음 요청간에 관계가 없어 저장공간을 동적으로 할당할 필요가 없다. 따라서 클라이언트가 트랜잭션 도중 다운이 돼도 서버에서는 이를 처리할 필요가 없다. 하지만 이러한 점은 요청마다 추가 정보를 항상 해석해야 한다는 단점이 있다.
4. TCP/IP 의 socket을 이용해 연결되는 응용 계층 프로토콜이다.
<br/>
### ❗ HTTP 1.1 VS HTTP 2.0
- 처리 방식
* HTTP 1.1 은 앞의 요청에 대한 응답을 받아야만 다음 요청이 처리될 수 있었다. (HOL 블로킹 발생)
* HTTP 2.0 에서는 Multiplexing 방식이 도입되어 동시에 여러 리소스를 받아올 수 있게 되었다.
- 데이터
* HTTP 1.1 은 문자열 형식으로 전송되었다.
* HTTP 2.0 은 binary로 인코딩하여 압축해 전송하며 요청 데이터간 의존관계 또한 지정할 수 있다.
- Server Push
* HTML 문서상에 필요한 리소스를 클라이언트 요청없이 보낼 수 있는 HTTP 2.0에 추가된 기능이다.
|
Python | UTF-8 | 3,091 | 3.5625 | 4 | [] | no_license | def startUp():
"""Read accounts from file and create dictionary with secret code as key.
Returns True if successful, False otherwise"""
global accts
try:
infile = open('accounts.txt')
except:
print('We are very sorry. This ATM is current uder maintainance.\nPlease try later.')
return False
for line in infile:
if len(line) > 1:
lineList = line.split()
accts[lineList[0]] = lineList[1:3]+[ float(lineList[3])]#need to make sure the balance is a float
infile.close()
return True
def getUser():
"""obtain secret code and validate account"""
global accts
global userIntent
try:
user = input('Welcome to the CSC241 Bank ATM\nPlease enter your secret code:\n')
if len(user) == 4 and user in accts:
return user
else:
print('Secret code incorrect. Goodbye.')
userIntent = False
return None
except:
print('Secret code incorrect. Goodbye.')
userIntent = False
return None
def menu():
global user
global accts
return( eval(input(80*'_' +'\n' + 80*'_' +'\n'+
'Welcome '+ accts[user][0] + '.\nPlease select your transaction:\n\t'+
'1: DEPOSIT\n\t'+
'2: WITHDRAW\n\t'+
'3: GET BALANCE\n\t'+
'4: QUIT\n')))
def deposit():
global accts
global user
accts[user][2]+= getAmount('deposit')
print('Your transaction was successful')
def withdraw():
global accts
global user
amount = getAmount('withdraw')
while amount > accts[user][2]:
print('You do not have sufficient funds to complete this transaction.')
amount = getAmount('withdraw')
else:
accts[user][2]-=amount
print('Your transaction was successful')
def getAmount(mode):
amountBad = True
while amountBad:
try:
amount = float(input('\nPlease enter the amount you wish to '+ mode+ ' :\n'))
amountBad = False
except:
print('You entered an incorrect amount.\nPlease try again')
return amount
def balance():
global accts
global user
print(accts[user][0] +', your current balance is ${}'.format(accts[user][2]))
def wrapUp():
outfile = open('accounts.txt', 'w')
for user in accts:
outfile.write(user + ' ')
for i in range (3):
outfile.write(str(accts[user][i] )+ ' ')
outfile.write('\n')
outfile.close()
print(80*'_'+'\n'+
80*'_' + '\n'+
'Thank you for using the CSC241 Bank ATM.\nGoodbye')
accts = {}#dictionary that stores accounts info as code:[fname lastname balance]
userIntent = True
if startUp():
user = getUser()
while userIntent:
choice = menu()
if choice == 1:
deposit()
elif choice == 2:
withdraw()
elif choice == 3:
balance()
else:
wrapUp()
userIntent = False
|
C++ | UTF-8 | 340 | 2.6875 | 3 | [] | no_license | #include "../library/lib.hpp"
class copy {
public:
void solve(std::istream& in, std::ostream& out) {
long long n,a,b,c;
in >> n >> a >> b >> c;
long long req = 4 - (n%4);
long long cost[4];
cost[0] = 0;
cost[1] = a;
cost[2] = min(2*cost[1],b);
cost[3] = min(cost[2] + cost[1],c);
out << cost[req] << "\n";
}
};
|
Java | UTF-8 | 510 | 2.71875 | 3 | [
"MIT"
] | permissive | package graphics;
// This is just a helper class to keep track of the colours
// that I am using, i.e. it translates the colour name to its
// hex value
// You can change the colour definitions if you like
public class ColorDef {
public static String LIGHTGRAY = "#F2F3F3";
public static String DARKGRAY = "#A2A3A3";
public static String YELLOW = "#FFDA89";
public static String BLUE = "#C4F0F0";
public static String GREEN = "#55CBCD";
public static String PURPLE = "#ECD5E3";
}
|
Python | UTF-8 | 12,462 | 3.453125 | 3 | [] | no_license | import pandas as pd
import re
import itertools as it
import collections as cl
movies_bd = pd.read_csv(r"D:\SkillFactory\Module1\movie_bd_v5.csv")
# function to process strings like 'cast', 'genres', 'production_companies'
def name_processor(long_string):
names_list = []
for row in long_string:
temp_list = row.split('|')
for name in temp_list:
if name in names_list:
break
else:
names_list.append(name)
return names_list
# Вопрос 1. У какого фильма из списка самый большой бюджет?
print('Вопрос 1. У какого фильма из списка самый большой бюджет?\n',
movies_bd[['imdb_id', 'original_title', 'budget']][movies_bd.budget == movies_bd.budget.max()])
# Вопрос 2. Какой из фильмов самый длительный (в минутах)?
print('\nВопрос 2. Какой из фильмов самый длительный (в минутах)?\n',
movies_bd[['imdb_id', 'original_title', 'runtime']][movies_bd.runtime == movies_bd.runtime.max()])
# Вопрос 3. Какой из фильмов самый короткий (в минутах)?
print('\nВопрос 3. Какой из фильмов самый короткий (в минутах)?\n',
movies_bd[['imdb_id', 'original_title', 'runtime']][movies_bd.runtime == movies_bd.runtime.min()])
# Вопрос 4. Какова средняя длительность фильмов?
print('\nВопрос 4. Какова средняя длительность фильмов?\n',
round(movies_bd.runtime.mean()), 'мин')
# Вопрос 5. Каково медианное значение длительности фильмов?
print('\nВопрос 5. Каково медианное значение длительности фильмов?\n',
round(movies_bd.runtime.median()), 'мин')
# Вопрос 6. Какой фильм самый прибыльный?
movies_bd['margin'] = movies_bd.apply(lambda row: row['revenue'] - row['budget'], axis=1)
print('\nВопрос 6. Какой фильм самый прибыльный?\n',
movies_bd[['imdb_id', 'original_title', 'budget', 'revenue', 'margin']]
[movies_bd.margin == movies_bd.margin.max()])
# Вопрос 11. Какого жанра фильмов больше всего?
print('\nВопрос 11. Какого жанра фильмов больше всего?')
genres_list = name_processor(movies_bd.genres)
genres_db = pd.DataFrame(genres_list, columns=['genres'])
genres_db['film_count'] = list(map(lambda name:
movies_bd[movies_bd.genres.str.contains(name)]['imdb_id'].count(),
genres_db['genres']))
print(genres_db.sort_values(by='film_count', ascending=False).head(1))
# Вопрос 12. Фильмы какого жанра чаще всего становятся прибыльными?
print('\nВопрос 12. Фильмы какого жанра чаще всего становятся прибыльными?')
genres_db['film_profitable'] = list(map(lambda name: movies_bd[(movies_bd.genres.str.contains(name))
& (movies_bd.margin > 0)]['imdb_id'].count(),
genres_db['genres']))
print(genres_db.sort_values(by='film_profitable', ascending=False).head(1))
# Вопрос 13. У какого режиссёра самые большие суммарные кассовые сборы?
print('\nВопрос 13. У какого режиссёра самые большие суммарные кассовые сборы?',
movies_bd.groupby('director').revenue.sum().sort_values(ascending=False).head(1))
# Вопрос 14. Какой режиссер снял больше всего фильмов в стиле Action?
print('\nВопрос 14. Какой режиссер снял больше всего фильмов в стиле Action?\n',
movies_bd[(movies_bd.genres.str.contains('Action', na=False)) &
(movies_bd.director.isin(
['Ridley Scott', 'Guy Ritchie', 'Robert Rodriguez', 'Quentin Tarantino', 'Tony Scott']))]
.director.value_counts().sort_values(ascending=False).head(1))
# Вопрос 15. Фильмы с каким актером принесли самые высокие кассовые сборы в 2012 году?
print('\nВопрос 15. Фильмы с каким актером принесли самые высокие кассовые сборы в 2012 году?')
actors_list = name_processor(movies_bd.cast)
actors_db = pd.DataFrame(actors_list, columns=['actor_name'])
actors_db['film_revenue'] = list(map(lambda name: movies_bd[(movies_bd.release_year == 2012)
& (movies_bd.cast.str.contains(name))].revenue.sum(),
actors_db['actor_name']))
print(actors_db.sort_values(by='film_revenue', ascending=False).head(1))
# Вопрос 16. Какой актер снялся в большем количестве высокобюджетных фильмов?
# Примечание: в фильмах, где бюджет выше среднего по данной выборке.
print('\nВопрос 16. Какой актер снялся в большем количестве высокобюджетных фильмов?')
actors_db['count'] = list(map(lambda name: movies_bd[(movies_bd.budget > movies_bd.budget.mean())
& (movies_bd.cast.str.contains(name))].imdb_id.count(),
actors_db['actor_name']))
print(actors_db.sort_values(by='count', ascending=False).head(5))
# Вопрос 17. В фильмах какого жанра больше всего снимался Nicolas Cage?
# так же можно было сделать через map+lambda в одну строку, но решил оставить цикл
print('\nВопрос 17. В фильмах какого жанра больше всего снимался Nicolas Cage?')
genres_cage = pd.DataFrame(columns=['genres', 'cage_count'])
for name in genres_list:
temp = 0
for row in movies_bd[movies_bd.cast.str.contains('Nicolas Cage', na=False)].genres:
if row.find(name) != -1:
temp += 1
genres_cage.loc[len(genres_cage)] = [name, temp]
print(genres_cage.sort_values(by='cage_count', ascending=False).head(1))
# Вопрос 18. Самый убыточный фильм от Paramount Pictures?
# print(movies_bd.columns)
print('\nВопрос 18. Самый убыточный фильм от Paramount Pictures?')
print(movies_bd[['imdb_id', 'original_title', 'margin']][movies_bd.production_companies.str.contains('Paramount')]
.sort_values(by='margin', ascending=True).head(1))
# Вопрос 19. Какой год стал самым успешным по суммарным кассовым сборам?
print('\nВопрос 19. Какой год стал самым успешным по суммарным кассовым сборам?')
print(movies_bd.groupby('release_year')['revenue'].sum().sort_values(ascending=False).head(1))
# Вопрос 20. Какой самый прибыльный год для студии Warner Bros?
print('\nВопрос 20. Какой самый прибыльный год для студии Warner Bros?')
print(movies_bd[movies_bd.production_companies.str.contains('Warner Bros')].groupby('release_year')[
'margin'].sum().sort_values(ascending=False).head(1))
print(type(movies_bd.loc[20, 'release_date']))
# Вопрос 21. В каком месяце за все годы суммарно вышло больше всего фильмов?
print('\nВопрос 21. В каком месяце за все годы суммарно вышло больше всего фильмов?')
# adding column with month number (добавление названия месяца надо было делать через создание дополнительного словаря)
movies_bd['release_month'] = movies_bd.release_date.apply(lambda name: int(re.match(r'\d+/', name)[0].strip('/')))
print(movies_bd.groupby('release_month')['imdb_id'].count().sort_values(ascending=False).head(1))
# Вопрос 22. Сколько суммарно вышло фильмов летом (за июнь, июль, август)?
print('\nВопрос 22. Сколько суммарно вышло фильмов летом (за июнь, июль, август)?')
print(movies_bd[movies_bd.release_month.isin([6, 7, 8])]['imdb_id'].count())
# Вопрос 23. Для какого режиссера зима — самое продуктивное время года?
print('\nВопрос 23. Для какого режиссера зима — самое продуктивное время года?')
print(movies_bd[movies_bd.release_month.isin([12, 1, 2])]
.groupby('director')['imdb_id'].count().sort_values(ascending=False).head(1))
# Вопрос 24. Какая студия даёт самые длинные названия своим фильмам по количеству символов?
print('\nВопрос 24. Какая студия даёт самые длинные названия своим фильмам по количеству символов?')
movies_bd['name_long'] = movies_bd.original_title.apply(lambda name: len(str(name)))
name_index = movies_bd[movies_bd.name_long == movies_bd.name_long.max()]['production_companies'].index[0]
print('студия: ', movies_bd.loc[name_index, 'production_companies'].split('|'))
# Вопрос 25. Описания фильмов какой студии в среднем самые длинные по количеству слов?
print('\nВопрос 25. Описания фильмов какой студии в среднем самые длинные по количеству слов?')
production_companies_list = name_processor(movies_bd.production_companies)
production_companies_db = pd.DataFrame(columns=['prod_name', 'overview_long'])
for name in production_companies_list:
temp = 0
movies_count = 0
for counter in movies_bd.index:
if movies_bd.loc[counter, 'production_companies'].find(name) != -1:
temp += len(movies_bd.loc[counter, 'overview'].split())
movies_count += 1
production_companies_db.loc[len(production_companies_db)] = [name, temp / movies_count]
print(production_companies_db[production_companies_db.prod_name.isin
(["Universal Pictures", "Warner Bros", "Midnight Picture Show", "Paramount Pictures", "Total Entertainment"])]
.sort_values(by='prod_name', ascending=False))
# Вопрос 26. Какие фильмы входят в один процент лучших по рейтингу?
print('\nВопрос 26. Какие фильмы входят в один процент лучших по рейтингу?')
movies_bd['vote_percent'] = movies_bd.vote_average.apply(lambda vote: vote / movies_bd.vote_average.sum())
vote_sum = 0
counter = 0
movies_bd = movies_bd.sort_values(by='vote_percent', ascending=False)
while vote_sum <= 0.01:
vote_sum += movies_bd.loc[counter]['vote_percent']
counter += 1
else:
print(movies_bd[['original_title', 'vote_average', 'vote_percent']].iloc[:counter])
# Вопрос 27. Какие актеры чаще всего снимаются в одном фильме вместе?
# Признаюсь - решение содрал. Но с работой функций разобрался
print('\nВопрос 27. Какие актеры чаще всего снимаются в одном фильме вместе?')
actors_pairs = pd.DataFrame(movies_bd.cast)
actors_pairs['names'] = actors_pairs.cast.apply(lambda names: names.split('|'))
actors_pairs['couples'] = actors_pairs.names.apply(lambda row: list(it.combinations(row, 2)))
actors_pairs = actors_pairs.explode('couples')
print(cl.Counter(actors_pairs.couples).most_common(5))
|
C# | UTF-8 | 378 | 2.6875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
namespace _09_DecoratorDesignPattern.Pattern.Decorators
{
class ConcreteDecoratorA : AbstractDecorator
{
private string addedState = "Some state";
public override void Operation()
{
base.Operation();
Console.WriteLine(addedState);
}
}
}
|
Markdown | UTF-8 | 6,033 | 2.515625 | 3 | [] | no_license | ---
title: "2018 IIIF Conference - Washington, DC"
layout: event
tags: [event ]
page: overview
---
The 2018 International Image Interoperability Framework ([IIIF][home-page]) Conference will be held May 21-25 in Washington, DC, co-hosted by the Library of Congress, the Smithsonian Institution, and the Folger Shakespeare Library.
## What is IIIF?
Embraced by a growing number of the world’s leading research and cultural heritage organizations, IIIF provides an open framework for organizations to publish their image-based resources, to be viewed, cited, annotated and compared by any compatible image-viewing application.
## Who is it for?
This event will be valuable for cultural heritage, STEM institutions, repository and collection managers, software engineers; or for anyone engaged with image-based and soon A/V resources on the Web. If you have not been involved with IIIF in the past this is an opportunity to quickly get up to speed and understand the community and its benefits.
## What will I learn?
* How to adopt IIIF at your institution
* Leveraging open source software to get more out of your collection of images and video
* Use cases and best practices from IIIF adopters
* See the latest developments in the community including IIIF A/V
## Conference Sponsors
The 2018 conference is generously supported and sponsored by the following:
* [Brumfield Labs, creators of FromThePage][FromThePage]
* [OCLC][oclc]
* [Design for Context][designforcontext]
* [Luna Imaging Inc][luna]
* [Digital Library Cloud Services][digirati]
* [Quartex][Quartex]
* [LYRASIS][lyrasis]
* [Picturae Inc.][Picturae]
If you are interested in sponsoring the 2018 IIIF Conference, please see the [sponsorship opportunities][sponsor] and get in touch with admin@iiif.io as soon as possible.
## Conference Overview
The conference will be made up of lightning talks, presentations and discussion sessions. There is also optional pre-conference Workshops on Monday. The general schedule will be as follows:
* Monday May 21st - [**Pre Conference workshops** hosted by the Smithsonian Institution][workshops] - **Program now Available**
* Tuesday May 22nd - [**IIIF Showcase** hosted by the Library of Congress][tuesday] - this requires a separate registration.
* Wednesday May 23rd - [**IIIF Conference plenary** hosted by the Library of Congress and a conference reception at the Smithsonian Castle.][wednesday]
* Thursday May 24th - [**IIIF Conference parallel sessions** hosted by the Library of Congress][thursday]
* Friday May 25th - [**IIIF Conference parallel sessions** hosted by the Library of Congress][friday]
Please also see the full list of [accepted presentations][program].
## Logistics
* Registration: there are two registrtions required; one for the Conference and Pre-conference workshops and one for the Showcase. Entry for both closes on the **4th of May**:
* **[Conference and pre-conference workshops registration][washington-registration]** - now closed.
* **[Showcase registration][showcase-eventbrite]** - now closed.
* List of [Hotels][hotels]
* Call for Proposals: is **now closed**.
* Dates: May 21-25, 2018
* Location: Washington, DC
* Cost:
* $145.00 for [IIIF Consortium members][consortium]
* $295.00 for non members
* Capacity: 400
* Code of Conduct: The IIIF [Code of Conduct][conduct] applies to the conference. The conference Conduct and Safety team can be contacted at [iiif-conduct@googlegroups.com][conduct-list]. Individual members of the Conduct and Safety team can be recognized by their blue and white striped badge lanyards and can be contacted individually:
* M.A. Matienzo (Conduct and Safety Team coordinator) - +1 650 683 5769, [matienzo@stanford.edu][matienzo], or @anarchivist (Twitter and IIIF Slack)
* Glen Robson (IIIF Technical Coordinator) - [glen.robson@iiif.io][glen], @glenrobson (Twitter), @glen.robson (IIIF Slack)
* Karen Estlund - [kestlund@gmail.com][kestlund], @estlundkm (Twitter), @kestlund (IIIF Slack)
* Katherine Lynch - [katherly@upenn.edu][klynch]
* Julien Raemy - [julien.raemy@hesge.ch][raemy], @julsraemy (Twitter and IIIF Slack)
* Jack Reed - [pjreed@stanford.edu][reed], @mejackreed (Twitter and IIIF Slack)
* Emma Stanford - [emmastanfordx@gmail.com][estanford], @e_stanf (Twitter), @emmastanford (IIIF Slack)
* Social Media: Tweets about the event should use #iiif or @iiif_io
Stay tuned to the [IIIF-Discuss][iiif-discuss] email list for announcements and updates.
[home-page]: {{ site.root_url | absolute_url }}/
[iiif-discuss]: https://groups.google.com/forum/#!forum/iiif-discuss
[conduct]: {{ site.root_url | absolute_url }}/event/conduct/
[consortium]: {{ site.root_url | absolute_url }}/community/consortium/
[cfp]: https://easychair.org/cfp/IIIF-2018
[registration-form]: https://goo.gl/forms/18EKOxsZn38Cvs3k2
[sponsor]: {{ site.root_url | absolute_url }}/event/2018/washington-sponsors
[hotels]:{{ site.root_url | absolute_url }}/event/2018/washington-hotels
[workshops]:{{ site.root_url | absolute_url }}/event/2018/washington-workshops
[tuesday]:{{ site.root_url | absolute_url }}/event/2018/washington/tuesday/
[wednesday]:{{ site.root_url | absolute_url }}/event/2018/washington/wednesday/
[thursday]:{{ site.root_url | absolute_url }}/event/2018/washington/thursday/
[friday]:{{ site.root_url | absolute_url }}/event/2018/washington/friday/
[program]:{{ site.root_url | absolute_url }}/event/2018/washington/program/
[washington-registration]: https://www.eventbrite.com/e/2018-iiif-conference-in-washington-tickets-44377905510
[showcase-eventbrite]: https://www.eventbrite.com/e/iiif-washington-showcase-tickets-44860722629
[FromThePage]: https://fromthepage.com/
[oclc]: https://www.oclc.org/en/home.html
[designforcontext]: http://www.designforcontext.com
[luna]: http://www.lunaimaging.com/
[digirati]: https://dlcs.info
[Quartex]: http://www.quartexcollections.com/
[lyrasis]: http://www.lyrasis.org
[Picturae]: http://www.picturae.com/
[conduct-list]: mailto:iiif-conduct@googlegroups.com
[matienzo]: mailto:matienzo@stanford.edu
[glen]: mailto:glen.robson@iiif.io
[kestlund]: mailto:kestlund@gmail.com
[klynch]: mailto:katherly@upenn.edu
[raemy]: mailto:julien.raemy@hesge.ch
[reed]: mailto:pjreed@stanford.edu
[estanford]: mailto:emmastanfordx@gmail.com
|
C++ | UTF-8 | 1,157 | 2.640625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
const int N = 25;
string dict[N][N];
int cnt[N], n, res;
void dfs(string str, int last) {
int l = str.size();
res = max(res, l);
for (int i = 1; i <= n; i++) {
if (cnt[i] == 2 || dict[last][i] == "") continue;
cnt[i]++;
dfs(str + dict[last][i], i);
cnt[i]--;
}
}
int main() {
string list[N];
cin >> n;
for (int i = 1; i <= n; i++) cin >> list[i];
for (int i = 1; i <= n; i++) {
int l1 = list[i].size();
for (int j = 1; j <= n; j++) {
int l2 = list[j].size();
for (int len = 1; len < l1; len++) {
string sub1 = list[i].substr(l1 - len, len);
string sub2 = list[j].substr(0, len);
if (sub1 == sub2) {
dict[i][j] = list[j].substr(len, l2 - len);
break;
}
}
}
}
char c;
cin >> c;
for (int i = 1; i <= n; i++)
if (list[i][0] == c) {
cnt[i]++;
dfs(list[i], i);
cnt[i]--;
}
cout << res << endl;
return 0;
}
|
C | UTF-8 | 670 | 3.484375 | 3 | [] | no_license | #include<stdio.h>
#include<string.h>
typedef struct data_strings_t
{
char s1[1000];
char s2[1000];
}data_strings;
data_strings strs[100] = {
{"hello", "hello"},
{"hello", "helloooo"},
{"Hello", "HeLlo"},
{"Hello", "Hello"},
{"helloooooo", "hello"},
{"how are you","HOW are YOU"}
};
main()
{
int i =0;
//for (i = 0; i < 10; i++)
//{
// printf("%d. %s<-->%s\n", i, strs[i].s1, strs[i].s2);
//}
for (i = 0; i < 7; i++)
{
printf("%d. %s<-->%s --->", i, strs[i].s1, strs[i].s2);
if (astrcasecmp(strs[i].s1, strs[i].s2) == 1)
printf("the string are same\n");
else
printf("the strings are not same\n");
}
}
|
Go | UTF-8 | 292 | 3.09375 | 3 | [] | no_license | package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
terms := strings.Split(line, " ")
for _, term := range terms {
out := fmt.Sprintf("%s\t1", term)
fmt.Println(out)
}
}
}
|
C# | UTF-8 | 6,716 | 2.703125 | 3 | [
"MIT"
] | permissive | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Linq;
using Microsoft.Cci;
namespace Microsoft.DotNet.AsmDiff
{
public static class DiffConfigurationExtensions
{
// Options
public static DiffConfiguration UpdateOptions(this DiffConfiguration configuration, DiffConfigurationOptions options)
{
var left = configuration.Left;
var right = configuration.Right;
return new DiffConfiguration(left, right, options);
}
public static bool IsOptionSet(this DiffConfiguration configuration, DiffConfigurationOptions option)
{
return option == DiffConfigurationOptions.None
? configuration.Options == DiffConfigurationOptions.None
: (configuration.Options & option) == option;
}
public static DiffConfiguration SetOption(this DiffConfiguration configuration, DiffConfigurationOptions option, bool set)
{
var newOptions = set
? configuration.Options | option
: configuration.Options & ~option;
return configuration.UpdateOptions(newOptions);
}
// Add assemblies
public static DiffConfiguration AddLeftAssemblies(this DiffConfiguration configuration, IEnumerable<string> addedPaths)
{
return configuration.AddAssemblies(true, addedPaths);
}
public static DiffConfiguration AddRightAssemblies(this DiffConfiguration configuration, IEnumerable<string> addedPaths)
{
return configuration.AddAssemblies(false, addedPaths);
}
private static DiffConfiguration AddAssemblies(this DiffConfiguration configuration, bool isLeft, IEnumerable<string> addedPaths)
{
var existingSet = isLeft
? configuration.Left
: configuration.Right;
var existingAssemblyPaths = from a in existingSet.Assemblies
select a.Location;
var totalAssemblyPaths = existingAssemblyPaths.Concat(addedPaths).ToArray();
var newName = existingSet.IsEmpty ? null : existingSet.Name;
return configuration.UpdateAssemblies(isLeft, totalAssemblyPaths, newName);
}
// Remove assemblies
public static DiffConfiguration RemoveLeftAssemblies(this DiffConfiguration configuration, IEnumerable<IAssembly> removals)
{
return configuration.RemoveAssemblies(true, removals);
}
public static DiffConfiguration RemoveRightAssemblies(this DiffConfiguration configuration, IEnumerable<IAssembly> removals)
{
return configuration.RemoveAssemblies(false, removals);
}
private static DiffConfiguration RemoveAssemblies(this DiffConfiguration configuration, bool isLeft, IEnumerable<IAssembly> removals)
{
var existingSet = isLeft
? configuration.Left
: configuration.Right;
var newSet = existingSet.Remove(removals);
return configuration.UpdateAssemblies(isLeft, newSet);
}
// Update assemblies
public static DiffConfiguration UpdateLeftAssemblies(this DiffConfiguration configuration, IEnumerable<string> paths)
{
return configuration.UpdateLeftAssemblies(paths, null);
}
public static DiffConfiguration UpdateLeftAssemblies(this DiffConfiguration configuration, IEnumerable<string> paths, string name)
{
return configuration.UpdateAssemblies(true, paths, name);
}
public static DiffConfiguration UpdateLeftAssemblies(this DiffConfiguration configuration, AssemblySet assemblySet)
{
return configuration.UpdateAssemblies(true, assemblySet);
}
public static DiffConfiguration UpdateRightAssemblies(this DiffConfiguration configuration, IEnumerable<string> paths)
{
return configuration.UpdateRightAssemblies(paths, null);
}
public static DiffConfiguration UpdateRightAssemblies(this DiffConfiguration configuration, IEnumerable<string> paths, string name)
{
return configuration.UpdateAssemblies(false, paths, name);
}
public static DiffConfiguration UpdateRightAssemblies(this DiffConfiguration configuration, AssemblySet assemblySet)
{
return configuration.UpdateAssemblies(false, assemblySet);
}
private static DiffConfiguration UpdateAssemblies(this DiffConfiguration configuration, bool isLeft, IEnumerable<string> newPaths, string newName)
{
var assemblySet = AssemblySet.FromPaths(newPaths, newName);
return configuration.UpdateAssemblies(isLeft, assemblySet);
}
private static DiffConfiguration UpdateAssemblies(this DiffConfiguration configuration, bool isLeft, AssemblySet assemblySet)
{
var isRight = !isLeft;
var existingSet = isLeft
? configuration.Left
: configuration.Right;
// This is the a debatible thing here.
//
// Without Dipose(), instances of DiffConfiguration would be fully immutable, which means
// we could pass it around to different threads and you could be sure that no than is stepping
// on your toes.
//
// However, this also means we would only unlock the files on disk when the GC collects the
// the underlying metadata reader host. This means, nobody can open the files exlusively or
// deleting them until they are collected.
//
// A workaround for the user is to simply close the app but I feel the workaround feels really
// bad. Especially because most of the assemblies being added to the tool will come from temp
// folders on the desktop.
//
// Since our apps is blocking adding/removing files when an analysis is running, there are
// no real advantages of full immutable sharing.
existingSet.Dispose();
var newLeft = isLeft ? assemblySet : configuration.Left;
var newRight = isRight ? assemblySet : configuration.Right;
return new DiffConfiguration(newLeft, newRight, configuration.Options);
}
}
}
|
Java | UTF-8 | 1,968 | 2.0625 | 2 | [] | no_license | package com.arturjoshi.account;
import com.arturjoshi.project.Project;
import com.arturjoshi.project.entities.ProjectAccountPermission;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.Set;
/**
* Created by arturjoshi on 04-Jan-17.
*/
@NoArgsConstructor
@Data
@Entity
@EqualsAndHashCode(of = {"username", "email", "credentials", "createdTime", "isConfirmed", "isTemp"})
public class Account {
@Id @GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@Column(unique = true)
private String username;
@Column(nullable = false, unique = true)
private String email;
@Embedded
private AccountCredentials credentials = new AccountCredentials();
private String createdTime = LocalDateTime.now().toString();
private Boolean isConfirmed = false;
private Boolean isTemp = false;
@OneToMany(mappedBy = "projectOwner")
@JsonIgnore
private Set<Project> projectOwned = new HashSet<>();
@ManyToMany(mappedBy = "members")
@JsonIgnore
private Set<Project> projects = new HashSet<>();
@ManyToMany(mappedBy = "outboxInvitations")
@JsonIgnore
private Set<Project> projectInvitations = new HashSet<>();
@ManyToMany(mappedBy = "inboxInvitations")
@JsonIgnore
private Set<Project> projectRequests = new HashSet<>();
@OneToMany(mappedBy = "account")
@JsonIgnore
private Set<ProjectAccountPermission> projectAccountPermissions = new HashSet<>();
public Account(Account account) {
this.id = account.id;
this.username = account.username;
this.email = account.email;
this.credentials.setPassword(account.getCredentials().getPassword());
this.isConfirmed = account.isConfirmed;
this.isTemp = account.isTemp;
}
}
|
Java | UTF-8 | 1,410 | 2.25 | 2 | [] | no_license | //package YCpowergroup.mealplanner.oud;
//
//import javax.persistence.Embeddable;
//
////@Embeddable
//public class NutritionValuesDeprecated {
// double netCarbs;
// double carbs;
// double fats;
// double protein;
// double calories;
//
// public NutritionValuesDeprecated(double netCarbs, double carbs, double fats, double protein, double calories) {
// this.netCarbs = netCarbs;
// this.carbs = carbs;
// this.fats = fats;
// this.protein = protein;
// this.calories = calories;
// }
// public NutritionValuesDeprecated() {
//
// }
//
// public double getNetCarbs() {
// return netCarbs;
// }
//
// public void setNetCarbs(double netCarbs) {
// this.netCarbs = netCarbs;
// }
//
// public double getCarbs() {
// return carbs;
// }
//
// public void setCarbs(double carbs) {
// this.carbs = carbs;
// }
//
// public double getFats() {
// return fats;
// }
//
// public void setFats(double fats) {
// this.fats = fats;
// }
//
// public double getProtein() {
// return protein;
// }
//
// public void setProtein(double protein) {
// this.protein = protein;
// }
//
// public double getCalories() {
// return calories;
// }
//
// public void setCalories(double calories) {
// this.calories = calories;
// }
//}
//
//
|
TypeScript | UTF-8 | 366 | 3.5 | 4 | [] | no_license | //https://leetcode-cn.com/problems/subsets/
function subsets(nums: number[]): number[][] {
const n = nums.length
const result: number[][] = []
for (let mask = 0; mask < 1 << n; ++mask) {
const temp = []
for (let i = 0; i < n; ++i) {
if (mask & (1 << i)) {
temp.push(nums[i])
}
}
result.push(temp)
}
return result
}
|
Java | UTF-8 | 214 | 2.3125 | 2 | [] | no_license | package com.springtutorial.aspect.oriented.programming.siddartha;
public class Machine implements IMachine {
@Override
public void start() {
System.out.println(" *** MACHINE STARTING ***");
}
}
|
PHP | UTF-8 | 1,291 | 2.515625 | 3 | [
"MIT"
] | permissive | <?php
namespace App\Form;
use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvents;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class PasswordUpdateType extends AbstractType
{
protected UserPasswordEncoderInterface $encoder;
public function __construct(UserPasswordEncoderInterface $encoder)
{
$this->encoder = $encoder;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('password', RepeatedType::class, [
'type' => PasswordType::class,
'first_options' => ['label' => 'Mot de passe'],
'second_options' => ['label' => 'Confirm ']
]);
$builder->addEventListener(FormEvents::POST_SUBMIT, function ($event) {
$user = $event->getData();
$user->setPassword($this->encoder->encodePassword($user, $user->getPassword()));
});
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults([
'data_class' => User::class,
]);
}
}
|
Markdown | UTF-8 | 2,959 | 3.03125 | 3 | [] | no_license | # DotNetBrowser
This project is to create a fully managed .NET browser implementation that can run on Windows, Linux, MacOs, and anything else that can run .NET.
# Are you nuts? It would take years and tons of man-hours!
The way I see things, those are excuses rather than legitimate reasons not to do this. We go to the moon not because it's easy, etc. I realize the scope of this project, and that it's going to take more than me to get it done. I'm doing this partly to learn, and partly because I hope someday this may be useful to other people. My philosophy is to go forth boldly, so that's what I'm doing.
There are two large pieces that I'm still researching. I don't intend to write a javascript interpreter or whatever is needed to run WebAssembly. If possible, the plan is to integrate an existing javascript engine (maybe allow the user to choose a javascript engine). I need to research WebAssembly more to know what options are possible.
# Ok, so what's the plan? Are you starting totally from scratch?
I thought about starting from scratch and was prepared to do so. Then I found https://github.com/ArthurHub/HTML-Renderer which is a .NET Html Renderer. From the README, it currently targets HTML 4.01 and CSS level 2 specifications support. This is a great starting position, since there is css parsing, image loading, and a DOM. Currently my plan is to add HTML 5 rendering support, then start making the code more browser-like. (This includes things like adding a caching mechanism, handling cookies, file downloads, etc).
# Why this isn't a fork of ArthurHub/HTML-Renderer
The main advantage of making this project a fork would be to submit enhancements upstream. The main issue I see is that making this a full web browser is going to be such a rework that people who use the ArthurHub project would have to change their code significantly to use this project. Also, the ArthurHub project hasn't had much activity in a long time. When possible, I will manually submit PR's to ArthurHub, especially in the beginning as I fix bugs / enhance the rendering portion.
# Current Status
Currently, everything compiles and at least runs. The WPF Demi application is the one I started updating. There is a textbox to enter url's and a go button that navigates to the page. There is currently no history, bookmarks, etc.
I'm currently evaluating the existing codebase and working on setting up overall structures for the various browser features. I'm also working on updating the demo application to be more useful.
# How you can help
If you're interested in helping, PR's are welcome. However, the first priority is to get the architecture right. Once it's posted, feel free to comment, make suggestions, etc.
# How to contact me
I have a regular full time job, but I can get on any of the major chat platforms in the evenings if you'd like to have a deeper conversation. I can also be reached via email -- taladon at gmail dot com |
Shell | UTF-8 | 101 | 2.84375 | 3 | [] | no_license | #!/bin/bash
if [[ -d $HOME/cosmin ]]; then
echo "directory exists"
fi
else
mkdir -p $HOME/cosmin
|
Swift | UTF-8 | 946 | 2.578125 | 3 | [
"MIT"
] | permissive | //
// ProcessingView+Transform.swift
// ProcessingKit
//
// Created by AtsuyaSato on 2018/09/09.
// Copyright © 2018年 Atsuya Sato. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
#elseif os(OSX)
import Cocoa
#endif
extension ProcessingView: TransformModelContract {
public func pushMatrix() {
self.transformModel.pushMatrix()
}
public func popMatrix() {
self.transformModel.popMatrix()
}
public func scale(_ s: CGFloat) {
self.transformModel.scale(s)
}
public func scale(_ x: CGFloat, _ y: CGFloat) {
self.transformModel.scale(x, y)
}
public func shear(_ angleX: CGFloat, _ angleY: CGFloat) {
self.transformModel.shear(angleX, angleY)
}
public func rotate(_ angle: CGFloat) {
self.transformModel.rotate(angle)
}
public func translate(_ x: CGFloat, _ y: CGFloat) {
self.transformModel.translate(x, y)
}
}
|
Python | UTF-8 | 1,286 | 2.59375 | 3 | [
"MIT"
] | permissive | from flask import Flask, request
from flask import Response
from omorfi.omorfi import Omorfi
app = Flask(__name__)
@app.route('/')
def hello():
return 'Hello World!'
@app.route('/api/v1/lemmatise', methods=['POST'])
def lemmatise():
def stream(text):
om = Omorfi()
om.load_from_dir('/usr/local/share/omorfi/', lemmatise=True)
for token in om.tokenise(text):
yield " ".join(map(lambda x: str(x), om.lemmatise(token[0])))
return Response(stream(request.form['text']), mimetype='text/plain')
@app.route('/api/v1/analyse', methods=['POST'])
def analyze():
def stream(text):
om = Omorfi()
om.load_from_dir('/usr/local/share/omorfi/', analyse=True)
for token in om.tokenise(text):
yield "%s\n" % token[0]
for analyse_res in om.analyse(token):
text, weight = analyse_res[:2]
if len(analyse_res)>2:
rest = " ".join([str(x) for x in analyse_res[2:]])
else:
rest=''
yield "%s %s %s\n" % (text, weight, rest)
yield "\n"
return Response(stream(request.values['text']), mimetype='text/plain')
if __name__ == "__main__":
app.debug=True
app.run(host='0.0.0.0')
|
Python | UTF-8 | 2,468 | 2.53125 | 3 | [
"Apache-2.0"
] | permissive | import os
def vtkrow_to_dict(attributes, i):
row = {}
for c in range(attributes.GetNumberOfArrays()):
arr = attributes.GetAbstractArray(c)
values = []
comp = arr.GetNumberOfComponents()
for c in range(comp):
variant_value = arr.GetVariantValue(i*comp + c)
if variant_value.IsInt():
value = variant_value.ToInt()
elif variant_value.IsLong():
value = variant_value.ToLong()
elif variant_value.IsDouble() or variant_value.IsFloat():
value = variant_value.ToDouble()
else:
value = variant_value.ToString()
values.append(value)
row[arr.GetName()] = values[0] if len(values) == 1 else values
return row
def dict_to_vtkarrays(row, fields, attributes):
import vtk
for key in fields:
value = row[key]
comp = 1
if isinstance(value, list):
comp = len(value)
value = value[0]
if isinstance(value, (int, long, float)):
arr = vtk.vtkDoubleArray()
elif isinstance(value, str):
arr = vtk.vtkStringArray()
elif isinstance(value, unicode):
arr = vtk.vtkUnicodeStringArray()
else:
arr = vtk.vtkStringArray()
arr.SetName(key)
arr.SetNumberOfComponents(comp)
attributes.AddArray(arr)
def dict_to_vtkrow(row, attributes):
for key in row:
value = row[key]
if not isinstance(value, (list, int, long, float, str, unicode)):
value = str(value)
found = False
for i in range(attributes.GetNumberOfArrays()):
arr = attributes.GetAbstractArray(i)
if arr.GetName() == key:
if isinstance(value, list):
for v in value:
arr.InsertNextValue(v)
else:
arr.InsertNextValue(value)
found = True
break
if not found:
raise Exception('[dict_to_vtkrow] Unexpected key: ' + key)
def load(params):
from girder_worker.core import format
converters_dir = os.path.join(params['plugin_dir'], 'converters')
format.import_converters([
os.path.join(converters_dir, 'geometry'),
os.path.join(converters_dir, 'graph'),
os.path.join(converters_dir, 'table'),
os.path.join(converters_dir, 'tree')
])
|
TypeScript | UTF-8 | 1,527 | 2.90625 | 3 | [] | no_license | import { Component, OnInit } from '@angular/core';
import {DataService} from '../../services/data.service';
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
name:string; //var of type string initialized
age:number;
address:{ //object type
street:string,
city:string,
state:string
}
//we can also create object type as an interface and use it:
profession:Profession;//interface is created below
//setting up arrays:
hobbies:string[];
//any data type:
variab:any;
c:number;
isEdit:boolean=false ;
constructor(private dataservice:DataService) {
}
ngOnInit() { //will run when the component is initialized
this.name="Hikansh Kapoor"; //defined
this.age=19;
this.address={
street:"rajouri",
city:"delhi",
state:"DL"
}
this.hobbies=['x','y','z'];
this.variab=true;
this.c=1;
}
onClick(){
this.name="Added New Hobby "+this.c+" times";
this.c++;
// this.hobbies.push('New Hobby Added');
}
addHobby(hobby){
this.hobbies.unshift(hobby);
return false;
}
deleteHobby(hobby){
for(let i=0;i<this.hobbies.length;i++){
if(this.hobbies[i]==hobby){
this.hobbies.splice(i,1);
}
}
}
toggleEdit(){
this.isEdit=!this.isEdit;
}
}
interface Profession{
degree:string,
year:number
}
interface Post{
id:number,
title:string,
body:string,
userId:number
} |
JavaScript | UTF-8 | 705 | 2.59375 | 3 | [] | no_license | // 在首页会同时发送三个网络请求,必须在三个请求的数据都到达后再关闭loading
let requestTime = 0
export function request(params) {
let baseUrl = "https://api-hmugo-web.itheima.net/api/public/v1";
requestTime++;
wx.showLoading({
title: '加载中',
mask: true
})
return new Promise((resolve, reject) => {
wx.request({
...params,
url: baseUrl + params.url, // params参数中有url,这里再设置一遍url会将上边解构出来的url的值覆盖掉
success: res => {
resolve(res.data)
},
fail: err => {
reject(err)
},
complete: () => {
requestTime--;
if(requestTime === 0) {
wx.hideLoading();
}
}
})
})
} |
Go | UTF-8 | 3,615 | 2.9375 | 3 | [
"MIT"
] | permissive | package ip
import (
"encoding/binary"
"fmt"
"math"
"math/rand"
"net"
"github.com/NetSys/quilt/minion/network"
log "github.com/Sirupsen/logrus"
)
var (
// Rand32 stores rand.Uint32 in a variable so that it can be easily mocked out
// for unit tests. Nondeterminism is hard to test.
Rand32 = rand.Uint32
// QuiltPrefix is the subnet under which quilt containers are given IP addresses
QuiltPrefix = net.IPv4(10, 0, 0, 0)
// QuiltMask is the subnet mask that corresponds with the Quilt subnet prefix
QuiltMask = net.CIDRMask(8, 32)
// SubMask is the subnet mask that minions can assign container IPs within. It
// resprents a /20 subnet.
SubMask = net.CIDRMask(20, 32)
// LabelPrefix is the subnet that is reserved for label IPs. It represents
// 10.0.0.0/20
LabelPrefix = net.IPv4(10, 0, 0, 0) // Labels get their own /20
minionMaskBits, _ = SubMask.Size()
quiltMaskBits, _ = QuiltMask.Size()
// MaxMinionCount is the largest number of minions that can exist, based
// on the number of available subnets
MaxMinionCount = int(math.Pow(2, float64(minionMaskBits-quiltMaskBits))+0.5) - 1
)
// Sync takes a map of IDs to IPs and creates an IP address for every entry that's
// missing one.
func Sync(ipMap map[string]string, prefixIP net.IP, mask net.IPMask) {
var unassigned []string
ipSet := map[string]struct{}{}
for k, ipString := range ipMap {
ip := Parse(ipString, prefixIP, mask)
if !ip.Equal(net.IPv4zero) {
ipSet[ip.String()] = struct{}{}
} else {
unassigned = append(unassigned, k)
}
}
// Don't assign the IP of the default gateway
ipSet[network.GatewayIP] = struct{}{}
for _, k := range unassigned {
ip := Random(ipSet, prefixIP, mask)
if ip.Equal(net.IPv4zero) {
log.Errorf("Failed to allocate IP for %s.", k)
ipMap[k] = ""
continue
}
ipMap[k] = ip.String()
ipSet[ip.String()] = struct{}{}
}
}
// Parse takes in an IP string, and parses it with respect to the given prefix and mask.
func Parse(ipStr string, prefix net.IP, mask net.IPMask) net.IP {
ip := net.ParseIP(ipStr)
if ip == nil {
return net.IPv4zero
}
if !ip.Mask(mask).Equal(prefix) {
return net.IPv4zero
}
return ip
}
// MaskToInt takes in a CIDR Mask and return the integer representation of it.
func MaskToInt(mask net.IPMask) uint32 {
bits, _ := mask.Size()
return 0xffffffff ^ uint32(0xffffffff>>uint(bits))
}
// FromInt converts the given integer into the equivalent IP address.
func FromInt(ip32 uint32) net.IP {
b := make([]byte, 4)
binary.BigEndian.PutUint32(b, ip32)
return net.IP(b)
}
// Random selects a random IP address in the given prefix and mask that isn't already
// present in conflicts.
// Returns 0 on failure.
func Random(conflicts map[string]struct{}, pre net.IP, subnetMask net.IPMask) net.IP {
prefix := ToInt(pre)
mask := MaskToInt(subnetMask)
randStart := Rand32() & ^mask
randIP := randStart
for {
ip32 := randIP | (prefix & mask)
ip := FromInt(ip32)
if _, ok := conflicts[ip.String()]; !ok {
return ip
}
randIP = (randIP + 1) & ^mask
// Prevent infinite looping in the case that all IPs are taken
if randIP == randStart {
return net.IPv4zero
}
}
}
// ToMac converts the given IP address string into an internal MAC address.
func ToMac(ipStr string) string {
parsedIP := net.ParseIP(ipStr)
if parsedIP == nil {
return ""
}
ip := parsedIP.To4()
return fmt.Sprintf("02:00:%02x:%02x:%02x:%02x", ip[0], ip[1], ip[2], ip[3])
}
// ToInt converts the given IP address into the equivalent integer representation.
func ToInt(ip net.IP) uint32 {
return binary.BigEndian.Uint32(ip.To4())
}
|
Java | UTF-8 | 3,963 | 2.203125 | 2 | [] | no_license | package vn.com.fis.model.cinvoice;
import java.io.Serializable;
public class ViewCreditLimitOutput implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private String account_Status;
private String bill_Cycle;
private String last_Billing_Date;
private String payment_Due_Date;
private String remaining_Credit_Limit;
private String total_Credit_Limit;
private String status;
private String status_Text;
public ViewCreditLimitOutput() {
}
public ViewCreditLimitOutput(
String account_Status,
String bill_Cycle,
String last_Billing_Date,
String payment_Due_Date,
String remaining_Credit_Limit,
String total_Credit_Limit,
String status,
String status_Text) {
this.account_Status = account_Status;
this.bill_Cycle = bill_Cycle;
this.last_Billing_Date = last_Billing_Date;
this.payment_Due_Date = payment_Due_Date;
this.remaining_Credit_Limit = remaining_Credit_Limit;
this.total_Credit_Limit = total_Credit_Limit;
this.status = status;
this.status_Text = status_Text;
}
/**
* Gets the account_Status value for this Response.
*
* @return account_Status
*/
public String getAccount_Status() {
return account_Status;
}
/**
* Sets the account_Status value for this Response.
*
* @param account_Status
*/
public void setAccount_Status(String account_Status) {
this.account_Status = account_Status;
}
/**
* Gets the bill_Cycle value for this Response.
*
* @return bill_Cycle
*/
public String getBill_Cycle() {
return bill_Cycle;
}
/**
* Sets the bill_Cycle value for this Response.
*
* @param bill_Cycle
*/
public void setBill_Cycle(String bill_Cycle) {
this.bill_Cycle = bill_Cycle;
}
/**
* Gets the last_Billing_Date value for this Response.
*
* @return last_Billing_Date
*/
public String getLast_Billing_Date() {
return last_Billing_Date;
}
/**
* Sets the last_Billing_Date value for this Response.
*
* @param last_Billing_Date
*/
public void setLast_Billing_Date(String last_Billing_Date) {
this.last_Billing_Date = last_Billing_Date;
}
/**
* Gets the payment_Due_Date value for this Response.
*
* @return payment_Due_Date
*/
public String getPayment_Due_Date() {
return payment_Due_Date;
}
/**
* Sets the payment_Due_Date value for this Response.
*
* @param payment_Due_Date
*/
public void setPayment_Due_Date(String payment_Due_Date) {
this.payment_Due_Date = payment_Due_Date;
}
/**
* Gets the remaining_Credit_Limit value for this Response.
*
* @return remaining_Credit_Limit
*/
public String getRemaining_Credit_Limit() {
return remaining_Credit_Limit;
}
/**
* Sets the remaining_Credit_Limit value for this Response.
*
* @param remaining_Credit_Limit
*/
public void setRemaining_Credit_Limit(String remaining_Credit_Limit) {
this.remaining_Credit_Limit = remaining_Credit_Limit;
}
/**
* Gets the total_Credit_Limit value for this Response.
*
* @return total_Credit_Limit
*/
public String getTotal_Credit_Limit() {
return total_Credit_Limit;
}
/**
* Sets the total_Credit_Limit value for this Response.
*
* @param total_Credit_Limit
*/
public void setTotal_Credit_Limit(String total_Credit_Limit) {
this.total_Credit_Limit = total_Credit_Limit;
}
/**
* Gets the status value for this Response.
*
* @return status
*/
public String getStatus() {
return status;
}
/**
* Sets the status value for this Response.
*
* @param status
*/
public void setStatus(String status) {
this.status = status;
}
/**
* Gets the status_Text value for this Response.
*
* @return status_Text
*/
public String getStatus_Text() {
return status_Text;
}
/**
* Sets the status_Text value for this Response.
*
* @param status_Text
*/
public void setStatus_Text(String status_Text) {
this.status_Text = status_Text;
}
}
|
PHP | UTF-8 | 1,927 | 2.78125 | 3 | [] | no_license | <?php
/* Based on UserPie Version: 1.0 : http://userpie.com */
function sendUserManagementEmail($EmailAddress, $TemplateName, $TemplateData, $Subject) {
$Header; $EmailContent; $Footer;
include(__DIR__."/views/mailTemplates/Header.php");
include(__DIR__."/views/mailTemplates/" . $TemplateName . ".php");
include(__DIR__."/views/mailTemplates/Footer.php");
if(!$EmailContent || empty($EmailContent) || $EmailContent == '') {
throw new Exception('Empty email.');
}
$EmailContent = $Header.$EmailContent.$Footer;
new Email($EmailAddress, $EmailContent, $Subject);
}
function sanitize($str) {
return strtolower(strip_tags(trim(($str))));
}
function isValidEmail($email) {
return preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",trim($email));
}
function minMaxRange($min, $max, $what) {
if(strlen(trim($what)) < $min) {
return true;
} elseif(strlen(trim($what)) > $max) {
return true;
} else {
return false;
}
}
//@ Thanks to - http://phpsec.org
function generateHash($plainText, $salt = null) {
$plainText = trim($plainText);
if($salt === null) {
$salt = substr(md5(uniqid(rand(), true)), 0, 25);
} else {
$salt = substr($salt, 0, 25);
}
return $salt . sha1($salt . $plainText);
}
function getUniqueCode($length = "") {
$code = md5(uniqid(rand(), true));
if($length != "") {
return substr($code, 0, $length);
} else {
return $code;
}
}
function errorBlock($errors) {
if(!count($errors) > 0) {
return false;
} else {
echo "<ul style='margin-left:0px;'>";
foreach($errors as $error) {
echo "<li style='text-align:center;'>".$error."</li>";
}
echo "</ul>";
}
}
function destorySession($name) {
if(isset($_SESSION[$name])) {
$_SESSION[$name] = NULL;
unset($_SESSION[$name]);
}
}
?> |
PHP | UTF-8 | 237 | 2.65625 | 3 | [] | no_license | <?php
interface IComputer {
public function whoAreYou();
public function showLoadingScreen();
public function bam();
public function closeEverything();
public function turnOff ();
public function state ();
} |
Java | UTF-8 | 3,642 | 3.59375 | 4 | [] | no_license | package Khasang.Java.Level0.lesson6;
import java.util.*;
public class HorsesInRace {
private String teamName;
private List<Animal> animals = new ArrayList<Animal>();
public HorsesInRace(String teamName, Animal... raceParticipants) {
//if (raceParticipants.length == 0) { throw new IllegalArgumentException("PARTICIPANTS OF THE RACE MUST BE GREATER THAN ZERO"); }
this.teamName = teamName;
for (Animal animal : raceParticipants) {
if (!animals.contains(animal)) animals.add(animal);
}
}
public HorsesInRace(String teamName, List<Animal> raceParticipants) {
//if (raceParticipants.size() == 0) { throw new IllegalArgumentException("PARTICIPANTS OF THE RACE MUST BE GREATER THAN ZERO"); }
this.teamName = teamName;
for (Animal animal : raceParticipants) {
if (!animals.contains(animal)) animals.add(animal);
}
}
public void printInfoOnHorsesInRace() {
System.out.printf("Team: \"%s\", Participant(s): %d%n", teamName, animals.size());
for (int i = 0; i < animals.size(); i++) {
System.out.printf("Participant %2d: %s%n", i + 1, animals.get(i).getInfo());
}
}
public String getInfoOnHorsesInRace() {
String s = String.format("Team: \"%s\", Participant(s): %d%n", teamName, animals.size());
for (int i = 0; i < animals.size(); i++) {
s.concat(String.format("Participant %2d: %s%n", i + 1, animals.get(i).getInfo()));
}
return s;
}
public int addRaceParticipants(Animal... raceParticipants) {
int j = 0;
for (Animal animal : raceParticipants) {
if (!animals.contains(animal)) {
animals.add(animal);
j++;
}
}
return j;
}
public int removeRaceParticipants(Animal... raceParticipants) {
int j = 0;
for (Animal animal : raceParticipants) {
if (!animals.contains(animal)) {
animals.remove(animal);
j++;
}
}
return j;
}
public int getNumberOfRaceParticipants() {
return animals.size();
}
public List<Animal> getRaceParticipants() {
if (animals.size() == 0) return Collections.EMPTY_LIST;
return animals;
}
public Animal[] getRaceParticipantsAsArray() {
if (animals.size() == 0) return (Animal[]) Collections.EMPTY_LIST.toArray();
return (Animal[]) animals.toArray();
}
public Animal getRaceParticipant(int index) {
if (index < 0 | index >= animals.size()) return null;
return animals.get(index);
}
public void sortRaceParticipantsByName() {
Collections.sort(animals, Comparator.comparing(horse -> horse.getName()));
}
public String getTeamName() {
return teamName;
}
public void setTeamName(String teamName) {
this.teamName = teamName;
}
public int getSize() {
return animals.size();
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof HorsesInRace)) return false;
HorsesInRace that = (HorsesInRace) o;
if (teamName != null ? !teamName.equals(that.teamName) : that.teamName != null) return false;
return animals != null ? animals.equals(that.animals) : that.animals == null;
}
@Override
public int hashCode() {
int result = teamName != null ? teamName.hashCode() : 0;
result = 31 * result + (animals != null ? animals.hashCode() : 0);
return result;
}
} |
Python | UTF-8 | 650 | 2.703125 | 3 | [] | no_license | # %matplotlib inline
import string
import requests
from bs4 import BeautifulSoup
from selenium import webdriver
def auto_click():
url = "https://www.woolworths.com.au//"
browser = webdriver.Chrome()
browser.get(url)
item = browser.find_element_by_id('categoryHeaderSmallFormat-browseButton')
item.click()
links = browser.find_elements_by_class_name('categoriesNavigation-linkText')
for link in links:
link.click()
browser.back()
if __name__ == "__main__":
auto_click()
# str1 = "helo/hi,me:it'sch.aluka sala^for,say"
# s = re.split(PUNCTUATIONS,str1)
# print(s)
|
TypeScript | UTF-8 | 12,501 | 3.484375 | 3 | [
"MIT"
] | permissive | import { describe, it, expect } from "vitest";
import LinkedList from "@/utils/linked-list";
describe( "Linked list", () => {
it( "should by default be empty upon construction", () => {
const list = new LinkedList();
expect( list.head ).toBeNull(); // expected list to not contain a head upon construction
expect( list.tail ).toBeNull(); // expected list to not contain a tail upon construction
});
it( "should be able to add Objects to its internal list", () => {
const list = new LinkedList();
const obj1 = { title: "foo" };
expect(0).toEqual(list.length); // expected list length to be 0 after construction
const obj1node = list.add(obj1);
expect(1).toEqual(list.length); // expected list length to be 1 after addition of an Object
expect(obj1node).toEqual(list.head); // expected list to have the added Object as its head Node
expect(obj1node).toEqual(list.tail); // expected list to have the added Object as its tail when the list has a length of 1
expect(obj1node.previous).toBeNull(); // expected added node to not have a previous node reference
expect(obj1node.next).toBeNull(); // expected added node to not have a next node reference
});
it( "should be able to wrap added Objects into a Node Object", () => {
const list = new LinkedList();
const obj1 = { title: "foo" };
const obj1node = list.add(obj1);
expect(obj1).toEqual(obj1node.data); // expected data property of the returned node to equal the added Object
});
it( "should be able to add multiple Objects to its internal list", () => {
const list = new LinkedList();
const obj1 = { title: "foo" };
const obj2 = { title: "bar" };
const obj1node = list.add(obj1);
const obj2node = list.add(obj2);
expect(obj1node).toEqual(list.head); // expected list to have the first added Object as its head Node
expect(obj2node).toEqual(list.tail); // expected list to have the last added Object as its tail
expect(obj2node).toEqual(obj1node.next); // expected the first nodes next property to reference the 2nd node
expect(obj1node.previous).toBeNull(); // expected the first node not to reference a previous node
expect(obj1node).toEqual(obj2node.previous); // expected the second nodes previous property to reference the 1st node
expect(obj2node.next).toBeNull(); // expected the second node not to reference a next node
const obj3 = { title: "baz" };
const obj3node = list.add(obj3);
expect(obj1node).toEqual(list.head); // expected list to have the first added Object as its head Node
expect(obj3node).toEqual(list.tail); // expected list to have the last added Object as its tail
expect(obj3node).toEqual(obj2node.next); // expected the 2nd node to have the last added node as its next property
expect(obj2node).toEqual(obj3node.previous); // expected the last node to have the second added node as its next property
expect(3).toEqual(list.length); // expected list length to be 3 after addition of 3 Objects
});
it( "should be able to add an Object before an existing one", () => {
const list = new LinkedList();
const obj1 = { title: "foo" };
const obj2 = { title: "bar" };
const obj3 = { title: "baz" };
const obj4 = { title: "qux" };
const obj1node = list.add(obj1); // index 0
const obj2node = list.add(obj2); // index 1
const obj3node = list.addBefore(obj2, obj3); // index 1 (obj2node is now index 2 )
expect(obj3node).toEqual(obj1node.next); // expected added Object to be the next property of the first added Node
expect(obj3node).toEqual(obj2node.previous); // expected added Object to be the previous property of the second added Node
expect(obj2node).toEqual(obj3node.next);// expected second added Node to be the next property of the added Node
expect(obj1node).toEqual(obj3node.previous); // expected first added Node to be the previous property of the added Node
const obj4node = list.addBefore(obj1, obj4); // index 0 (obj1node is now #1, obj3node #2, obj2node #3)
expect(obj4node).toEqual(list.head); // expected last added Object to be the new list head Node
expect(obj1node).toEqual(obj4node.next); // expected first added Object to be the next property of the new head Node
expect(obj4node).toEqual(obj1node.previous); // expected new head to be the previous property of the first added Object
expect(obj1node).toEqual(obj4node.next); // expected first added Node to be the next property of the newly added head Node
expect(null).toEqual(obj4node.previous); // expected newly added head not to have a previous Node
expect(4).toEqual(list.length); // expected list length to be 4 after addition of 4 Objects
});
it( "should be able to add an Object after an existing one", () => {
const list = new LinkedList();
const obj1 = { title: "foo" };
const obj2 = { title: "bar" };
const obj3 = { title: "baz" };
const obj4 = { title: "qux" };
const obj1node = list.add(obj1); // index 0
const obj2node = list.add(obj2); // index 1
const obj3node = list.addAfter(obj1, obj3); // index 1 (obj2node is now index 2 )
expect(obj3node).toEqual(obj1node.next); // expected added Object to be the next property of the first added Node
expect(obj3node).toEqual(obj2node.previous); // expected added Object to be the previous property of the second added Node
expect(obj2node).toEqual(obj3node.next); // expected second added Node to be the next property of the added Node
expect(obj1node).toEqual(obj3node.previous); // expected first added Node to be the previous property of the added Node
const obj4node = list.addAfter(obj2, obj4); // index 3 (obj1node is now #0, obj3node #1, obj2node #2)
expect(obj4node).toEqual(list.tail); // expected last added Object to be the new list tail
expect(obj2node).toEqual(obj4node.previous); // expected second added Object to be the previous property of the new tail
expect(obj4node).toEqual(obj2node.next); // expected new head to be the next property of the second added Object
expect(null).toEqual(obj4node.next); // expected newly added tail not to have a next Node
expect(obj2node).toEqual(obj4node.previous); // expected second added Node to be the previous property of the new tail
expect(4).toEqual(list.length); // expected list length to be 4 after addition of 4 Objects
});
it( "should be able to remove Objects from its internal list", () => {
const list = new LinkedList();
const obj1 = { title: "foo" };
const obj2 = { title: "bar" };
const obj3 = { title: "baz" };
const obj1node = list.add(obj1);
const obj2node = list.add(obj2);
const obj3node = list.add(obj3);
list.remove(obj2node);
expect(obj1node).toEqual(list.head); // expected list to have the first added Object as its head Node
expect(obj3node).toEqual(list.tail); // expected list to have the last added Object as its tail
expect(obj1node).toEqual(obj3node.previous); // expected 3rd node to have the 1st added node as its previous property
expect(obj3node).toEqual(obj1node.next); // expected 1st node to have the 3rd added node as its next property
list.remove(obj1node);
expect(obj3node).toEqual(list.head); // expected list to have the last added Object as its head Node
expect(obj3node).toEqual(list.tail); // expected list to have the last added Object as its tail
expect(obj3node.previous).toBeNull(); // expected 3rd node to have no previous property after removal of all other nodes
expect(obj3node.next).toBeNull(); // expected 3rd node to have no next property after removal of all other nodes
list.remove(obj3node);
expect(list.head).toBeNull(); // expected list to have no head after removing all its nodes
expect(list.tail).toBeNull(); // expected list to have no tail after removing all its nodes
});
it( "should be able to flush all Objects from its internal list at once", () => {
const list = new LinkedList();
const obj1 = { title: "foo" };
const obj2 = { title: "bar" };
const obj3 = { title: "baz" };
list.add(obj1);
list.add(obj2);
list.add(obj3);
list.flush();
expect(list.head).toBeNull(); // expected list to have no head after flushing
expect(list.tail).toBeNull(); // expected list to have no head after flushing
});
it( "should be able to remove Objects by their Node reference", () => {
const list = new LinkedList();
const obj1 = { title: "foo" };
const obj1node = list.add(obj1);
const obj2 = { title: "bar" };
const obj2node = list.add(obj2);
list.remove(obj1node);
expect(obj2node).toEqual(list.head); // expected list to have 2nd Object as head after removal of 1ast Node
expect(obj2node).toEqual(list.tail); // expected list to have 2nd Object as tail after removal of 1ast Node
});
it( "should be able to remove Objects by their list index", () => {
const list = new LinkedList();
const obj1 = { title: "foo" };
const obj1node = list.add(obj1);
const obj2 = { title: "bar" };
list.add(obj2);
list.remove(1);
expect(obj1node).toEqual(list.head); // expected list to have 1st Object as head after removal of 1ast Node by its index
expect(obj1node).toEqual(list.tail); // expected list to have 1st Object as tail after removal of 1ast Node by its index
});
it( "should be able to remove Objects by their content", () => {
const list = new LinkedList();
const obj1 = { title: "foo" };
const obj1node = list.add(obj1);
const obj2 = { title: "bar" };
list.remove(obj2);
expect(obj1node).toEqual(list.head); // expected list to have 1st Object as head after removal of 1ast Node by its data
expect(obj1node).toEqual(list.tail); // expected list to have 1st Object as tail after removal of 1ast Node by its data
});
it( "should be able to remove Objects directly from their Node", () => {
const list = new LinkedList();
const obj1 = { title: "foo" };
const obj1node = list.add(obj1);
const obj2 = { title: "bar" };
const obj2node = list.add(obj2);
const obj3 = { title: "baz" };
const obj3node = list.add(obj3);
obj2node.remove();
expect(obj1node).toEqual(list.head); // expected list to have 2nd Object as head after removal of 2nd Node
expect(obj3node).toEqual(list.tail); // expected list to have 3rd Object as tail after removal of 2nd Node
expect(2).toEqual(list.length); // expected list length to be 2 after removal of 2nd Node
obj1node.remove();
expect(obj3node).toEqual(list.head); // expected list to have 3rd Object as head after removal of 1st Node
expect(obj3node).toEqual(list.tail); // expected list to have 3rd Object as tail after removal of 1st Node
expect(1).toEqual(list.length); // expected list length to be 1 after removal of 1st Node
obj3node.remove();
expect(list.head).toBeNull(); // expected list to have no head after removal of all Nodes
expect(list.tail).toBeNull(); // expected list to have no tail after removal of all Nodes
expect(0).toEqual(list.length); // expected list length to be 0 after removal of all Nodes
});
it( "should be able to retrieve Node wrappers by their content", () => {
const list = new LinkedList();
const obj1 = { title: "foo" };
const obj1node = list.add(obj1);
const obj2 = { title: "bar" };
const obj2node = list.add(obj2);
let retrievedNode = list.getNodeByData(obj2);
expect(obj2node).toEqual(retrievedNode); // expected list to have retrieved the last Node by the last Nodes data
retrievedNode = list.getNodeByData(obj1);
expect(obj1node).toEqual(retrievedNode); // expected list to have retrieved the first Node by the last Nodes data
});
});
|
Markdown | UTF-8 | 2,341 | 3.21875 | 3 | [
"Apache-2.0"
] | permissive | ---
morea_id: experience-H07
morea_type: experience
title: "H07: Two-Dice Pig Game"
published: True
morea_start_date: "2016-10-21T23:55:00"
morea_summary: "Write a program that allows players to play Two-Dice Pig."
morea_labels:
- "Homework Assignment"
---
# ICS 111 Homework Assignment H07: Two-Dice Pig Game
1) Write a program that allows players to play the game Two-Dice Pig.
The rules of Two-Dice Pig are:
Each turn, a player repeatedly rolls two dice until a 1 is rolled or the player decides to "hold":
* If a single 1 is rolled, the player scores nothing and the turn ends.
* If two 1s are rolled, the player’s entire score is lost, and the turn ends.
* If the player rolls any other number, it is added to their turn total and the player's turn continues.
* If a double is rolled, the point total is added to the turn total as with any roll but the player is obligated to roll again.
* If a player chooses to "hold", their turn total is added to their score, and it becomes the next player's turn.
The first player to 100 or more points wins.
The program should ask for the number of players, then create an array of *Player*s. The *Player* class should have a name instance variable and a score instance variable. Once the players are initialized the program should start playing the game by giving each player a turn.
The program should have a function named *playerTurn* that allows the player to decide when to "hold". The function must return the score for the player's turn.
The program should use an instance of the class *PairOfDice* to do the rolling of the dice. (See the text for examples of the class.)
## Turning in the Assignment
The assignment is due on Friday, October 21st at 11:55pm. You may turn it in early.
1. Conduct a personal review of your code before turning it in. Does your code follow the [Java Coding Standard](../references/reading-java-coding-standard.html)?
Is it clear and well commented?
2. Test your code.
* Does it produce the correct output?
3. Sign into Laulima, then navigate to the ICS111 site. In the left hand side of the site, there is an Assignments tab/link. Click on it and view all of the posted assignments. Select the assignment that you want to turn in and attach your files and accept the honor pledge to submit the assignment.
|
JavaScript | UTF-8 | 974 | 3.109375 | 3 | [] | no_license | "use strict";
(function(){
var Vec2D = (function(){
function Vec2D(x1, y1){
this.x = x1;
this.y = y1;
}
Vec2D.prototype.constructor = Vec2D;
Vec2D.prototype.x = function(){
return this.x;
};
Vec2D.prototype.y = function() {
return this.y;
};
Vec2D.prototype.setX = function(x1) {
this.x = x1;
};
Vec2D.prototype.setY = function(y1) {
this.y = y1;
};
Vec2D.prototype.add = function(a, b){
if(typeof(a)===typeof(b) && typeof(a)==='Vec2D'){
return new Vec2D(a.x+b.x, a.y+b.y);
}
};
Vec2D.prototype.inverse = function(){
return new Vec2D(-this._x, -this._y);
};
Vec2D.prototype.equals = function(other){
if(other!=null && this!=null){
if(other.x==this.x && this.y==other.y){
return true;
}
}
return false;
};
return Vec2D;
})();
if (typeof module !== 'undefined' && typeof module.exports !== 'undefined'){
module.exports = Vec2D;
}else{
window.Vec2D = Vec2D;
}
})();
|
Shell | UTF-8 | 133 | 2.90625 | 3 | [] | no_license | #!/usr/bin/env bash
#Displays Holberton School 10 times using while loop.
for line in *
do
echo "$line" | cut -d '-' -f 2
done
|
Java | UTF-8 | 1,143 | 2.4375 | 2 | [] | no_license | package com.ualr.emoweat.core.utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
/**
* @author - Tolgahan CAKALOGLU "Jackalhan"
*/
public class Property {
private static Properties properties = null;
private static void init() {
InputStream file = null;
try {
file = new FileInputStream(System.getProperty(Constant.configDirectory) + Constant.emoweat + "/" + Constant.config);
properties = new Properties();
properties.load(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static String getValue(String propertyName) {
if (properties == null || properties.size() == 0) {
init();
}
return properties.getProperty(propertyName);
}
}
|
Python | UTF-8 | 3,068 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive |
import xmltodict as xmld #JMDict parsing
from gzip import GzipFile #JMDict streaming
import pickle #cache serialization
import romkan #kana/romaji conversion
def loopOn(input):
if isinstance(input,list):
for i in input:
yield i;
else: yield input;
class Dictionary:
def __init__(self, jmfile, kjfile):
self.jmfile = jmfile;
self.kjfile = kjfile;
pass;
def Load(self, dictfile):
try:
with open(dictfile,"rb") as f:
print("Loading dictionary...");
(self.jmdict,self.rindex,self.jindex,self.kjdict,self.kindex) = pickle.load(f);
except (OSError,IOError):
print("Parsing JMdict...");
self.jmdict = xmld.parse(GzipFile(self.jmfile));
self.jmdict = self.jmdict["JMdict"]["entry"];
print("Indexing...");
self.rindex = {};
self.jindex = {};
for i,entry in enumerate(self.jmdict):
try:
kele = entry["k_ele"];
for j in loopOn(kele):
r = j["keb"];
a = self.rindex.get(r);
if a is None:
self.rindex[r] = [i];
self.jindex[r] = [i];
else:
a.append(i);
self.jindex[r].append(i);
except KeyError:
pass;
try:
rele = entry["r_ele"];
for j in loopOn(rele):#rele:
r = romkan.to_roma(j["reb"]).replace('\'','');
a = self.rindex.get(r);
if a is None:
self.rindex[r] = [i];
else: a.append(i);
except KeyError:
pass;
sense = entry["sense"];
for j in loopOn(sense):
for g in loopOn(j["gloss"]):
t = g["#text"];
a = self.rindex.get(t);
if a is None:
self.rindex[t] = [i];
else: a.append(i);
print("Parsing KANJIDIC2...");
self.kjdict = xmld.parse(GzipFile(self.kjfile));
self.kjdict = self.kjdict["kanjidic2"]["character"];
print("Indexing...");
self.kindex = {};
for i,entry in enumerate(self.kjdict):
lit = entry["literal"];
ron = [];
kun = [];
meaning = [];
try:
rm = entry["reading_meaning"]["rmgroup"];
except KeyError:
continue; #radical: skip for now
try:
for rele in loopOn(rm["reading"]):
if rele["@r_type"] == "ja_on":
ron.append(rele["#text"]);
elif rele["@r_type"] == "ja_kun":
kun.append(rele["#text"]);
except KeyError:
pass;
try:
for mele in loopOn(rm["meaning"]):
if isinstance(mele,str): #other than english are dictionaries
meaning.append(mele);
except KeyError:
pass;
self.kindex[lit] = (ron,kun,meaning);
with open(dictfile,"wb") as f:
print("Caching...");
pickle.dump((self.jmdict,self.rindex,self.jindex,self.kjdict,self.kindex),f);
def LoadTags(self, tagfile, tagdef):
self.tagfile = tagfile;
self.tagdef = tagdef;
try:
with open(self.tagfile,"rb") as f:
print("Loading tags...");
self.tagdict = pickle.load(f);
except (OSError,IOError):
self.tagdict = {};
self.tagdict[self.tagdef] = [];
def SaveTags(self):
if len(self.tagdict) > 1 or len(self.tagdict[self.tagdef]) > 0:
with open(self.tagfile,"wb") as f:
pickle.dump(self.tagdict,f);
|
Java | UTF-8 | 354 | 2.71875 | 3 | [] | no_license | package me.Lorinth.BossApi.Abilities;
import org.bukkit.Location;
import org.bukkit.entity.Creature;
public class Teleport extends Action{
Location loc;
public Teleport(Location loc){
this.loc = loc;
}
@Override
public void execute(Creature ent){
//Entity doesn't change worlds
loc.setWorld(ent.getWorld());
ent.teleport(loc);
}
}
|
Java | UTF-8 | 19,013 | 1.820313 | 2 | [] | no_license | package jp.groupsession.v2.sch.sch040kn;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import jp.co.sjts.util.NullDefault;
import jp.groupsession.v2.cmn.GSConst;
import jp.groupsession.v2.cmn.GSConstSchedule;
import jp.groupsession.v2.cmn.biz.CommonBiz;
import jp.groupsession.v2.cmn.cmn999.Cmn999Form;
import jp.groupsession.v2.cmn.config.PluginConfig;
import jp.groupsession.v2.cmn.dao.BaseUserModel;
import jp.groupsession.v2.cmn.dao.MlCountMtController;
import jp.groupsession.v2.cmn.model.RequestModel;
import jp.groupsession.v2.man.GSConstMain;
import jp.groupsession.v2.sch.AbstractScheduleAction;
import jp.groupsession.v2.sch.dao.SchDataDao;
import jp.groupsession.v2.sch.model.SchDataModel;
import jp.groupsession.v2.sch.sch010.Sch010Biz;
import jp.groupsession.v2.struts.msg.GsMessage;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;
/**
* <br>[機 能] スケジュール確認画面のアクションクラス
* <br>[解 説]
* <br>[備 考]
*
* @author JTS
*/
public class Sch040knAction extends AbstractScheduleAction {
/** エラーの種類 閲覧不可データ */
private static final int ERRORTYPE_VIEW__ = 0;
/** エラーの種類 データなし */
private static final int ERRORTYPE_NONE__ = 1;
/** Logging インスタンス */
private static Log log__ = LogFactory.getLog(Sch040knAction.class);
/**
* <br>アクション実行
* @param map アクションマッピング
* @param form アクションフォーム
* @param req リクエスト
* @param res レスポンス
* @param con コネクション
* @throws Exception 実行例外
* @return アクションフォーム
*/
public ActionForward executeAction(ActionMapping map, ActionForm form,
HttpServletRequest req, HttpServletResponse res, Connection con)
throws Exception {
log__.debug("START_SCH040kn");
ActionForward forward = null;
Sch040knForm uform = (Sch040knForm) form;
//アクセス不可グループ、またはユーザに対してのスケジュール登録を許可しない
int selectUserSid = NullDefault.getInt(uform.getSch010SelectUsrSid(), -1);
if (selectUserSid >= 0) {
//公開範囲についてのチェック
int scdSid = NullDefault.getInt(uform.getSch010SchSid(), -1);
if (scdSid != -1) {
SchDataDao scdDao = new SchDataDao(con);
SchDataModel scdMdl = scdDao.getEditCheckData(scdSid);
int sessionUsrSid = getRequestModel(req).getSmodel().getUsrsid();
Sch010Biz biz = new Sch010Biz(getRequestModel(req));
if (!biz.checkViewOk(scdMdl, sessionUsrSid, con)) {
return getSubmitErrorPage(map, req);
}
}
}
//コマンドパラメータ取得
String cmd = NullDefault.getString(req.getParameter("CMD"), "");
log__.debug("CMD==>" + cmd);
if (cmd.equals("040kn_week")) {
//日間スケジュール
forward = map.findForward("040kn_week");
} else if (cmd.equals("040kn_month")) {
//月間スケジュール
forward = map.findForward("040kn_month");
} else if (cmd.equals("040kn_day")) {
//日間スケジュール
forward = map.findForward("040kn_day");
} else if (cmd.equals("040kn_back")) {
//画面遷移先を取得
forward = __doBack(map, uform, req, res, con);
} else if (cmd.equals("040kn_commit")) {
//登録・更新
forward = __doCommit(map, uform, req, res, con);
} else {
//スケジュール詳細・確認
forward = __doInit(map, uform, req, res, con);
}
log__.debug("forward==>" + forward.getPath());
log__.debug("END_SCH040kn");
return forward;
}
/**
* <br>リクエストを解析し画面遷移先を取得する
* @param map アクションマッピング
* @param form アクションフォーム
* @param req リクエスト
* @param res レスポンス
* @param con コネクション
* @return ActionForward
* @throws SQLException SQL実行時例外
*/
private ActionForward __doInit(ActionMapping map, Sch040knForm form,
HttpServletRequest req, HttpServletResponse res, Connection con)
throws SQLException {
con.setAutoCommit(true);
ActionForward forward = null;
RequestModel reqMdl = getRequestModel(req);
Sch040knBiz biz = new Sch040knBiz(reqMdl);
Sch040knParamModel paramMdl = new Sch040knParamModel();
paramMdl.setParam(form);
biz.getInitData(paramMdl, con);
paramMdl.setFormData(form);
if (form.getCmd().equals(GSConstSchedule.CMD_EDIT)) {
if (!form.isSch040ViewFlg()) {
//編集データ閲覧権限チェック
forward = __doDataError(map, form, req, res, con, ERRORTYPE_VIEW__);
} else if (!form.isSch040DataFlg()) {
//編集データ有無チェック
forward = __doDataError(map, form, req, res, con, ERRORTYPE_NONE__);
} else {
forward = map.getInputForward();
}
} else {
forward = map.getInputForward();
}
con.setAutoCommit(false);
return forward;
}
/**
* <br>リクエストを解析し画面遷移先を取得する
* @param map アクションマッピング
* @param form アクションフォーム
* @param req リクエスト
* @param res レスポンス
* @param con コネクション
* @return ActionForward 画面遷移
* @throws SQLException SQL実行時例外
*/
private ActionForward __doBack(ActionMapping map, Sch040knForm form,
HttpServletRequest req, HttpServletResponse res, Connection con)
throws SQLException {
ActionForward forward = null;
String dspMod = form.getDspMod();
String listMod = form.getListMod();
if (listMod.equals(GSConstSchedule.DSP_MOD_LIST)) {
forward = map.findForward("040kn_list");
return forward;
}
if (dspMod.equals(GSConstSchedule.DSP_MOD_WEEK)) {
forward = map.findForward("040kn_week");
} else if (dspMod.equals(GSConstSchedule.DSP_MOD_MONTH)) {
forward = map.findForward("040kn_month");
} else if (dspMod.equals(GSConstSchedule.DSP_MOD_DAY)) {
forward = map.findForward("040kn_day");
} else if (dspMod.equals(GSConstSchedule.DSP_MOD_MAIN)) {
forward = map.findForward("040kn_main");
} else if (dspMod.equals(GSConstSchedule.DSP_MOD_KOJIN_WEEK)) {
forward = map.findForward("040kn_kojin");
} else {
//デフォルト遷移先(例外処理)
forward = map.findForward("040kn_week");
}
return forward;
}
/**
* <br>処理モードによって登録・修正処理を行う
* @param map アクションマッピング
* @param form アクションフォーム
* @param req リクエスト
* @param res レスポンス
* @param con コネクション
* @return ActionForward 画面遷移
* @throws Exception SQL実行時例外
*/
private ActionForward __doCommit(ActionMapping map, Sch040knForm form,
HttpServletRequest req, HttpServletResponse res, Connection con)
throws Exception {
ActionForward forward = null;
if (!isTokenValid(req, true)) {
log__.info("2重投稿");
forward = getSubmitErrorPage(map, req);
return forward;
}
//セッション情報を取得
HttpSession session = req.getSession();
BaseUserModel usModel =
(BaseUserModel) session.getAttribute(GSConst.SESSION_KEY);
int sessionUsrSid = usModel.getUsrsid(); //セッションユーザSID
//アプリケーションRoot
String appRootPath = getAppRootPath();
//プラグイン設定
PluginConfig plconf = getPluginConfig(req);
PluginConfig pconfig = getPluginConfigForMain(plconf, con);
CommonBiz cmnBiz = new CommonBiz();
boolean smailPluginUseFlg = cmnBiz.isCanUsePlugin(GSConstMain.PLUGIN_ID_SMAIL, pconfig);
RequestModel reqMdl = getRequestModel(req);
MlCountMtController cntCon = getCountMtController(req);
Sch040knBiz biz = new Sch040knBiz(con, reqMdl, cntCon);
boolean commitFlg = false;
con.setAutoCommit(false);
try {
//新規登録
if (form.getCmd().equals(GSConstSchedule.CMD_ADD)) {
Sch040knParamModel paramMdl = new Sch040knParamModel();
paramMdl.setParam(form);
biz.insertScheduleDate(reqMdl, paramMdl,
sessionUsrSid, appRootPath, plconf, smailPluginUseFlg);
paramMdl.setFormData(form);
} else if (form.getCmd().equals(GSConstSchedule.CMD_EDIT)) {
Sch040knParamModel paramMdl = new Sch040knParamModel();
paramMdl.setParam(form);
biz.updateScheduleDate(paramMdl, sessionUsrSid, appRootPath, plconf, con);
paramMdl.setFormData(form);
}
commitFlg = true;
} catch (Exception e) {
log__.error("スケジュール登録に失敗しました" + e);
throw e;
} finally {
if (commitFlg) {
con.commit();
} else {
con.rollback();
}
}
forward = __doCompDsp(map, form, req, res, con);
return forward;
}
/**
* <br>登録・更新完了画面設定
* @param map アクションマッピング
* @param form アクションフォーム
* @param req リクエスト
* @param res レスポンス
* @param con コネクション
* @return ActionForward
*/
private ActionForward __doCompDsp(ActionMapping map, Sch040knForm form,
HttpServletRequest req, HttpServletResponse res, Connection con) {
ActionForward forward = null;
Cmn999Form cmn999Form = new Cmn999Form();
ActionForward urlForward = null;
//スケジュール登録完了画面パラメータの設定
MessageResources msgRes = getResources(req);
cmn999Form.setType(Cmn999Form.TYPE_OK);
cmn999Form.setIcon(Cmn999Form.ICON_INFO);
cmn999Form.setWtarget(Cmn999Form.WTARGET_BODY);
if (form.getListMod().equals(GSConstSchedule.DSP_MOD_LIST)) {
urlForward = map.findForward("040kn_list");
} else {
if (form.getDspMod().equals(GSConstSchedule.DSP_MOD_WEEK)) {
urlForward = map.findForward("040kn_week");
} else if (form.getDspMod().equals(GSConstSchedule.DSP_MOD_MONTH)) {
urlForward = map.findForward("040kn_month");
} else if (form.getDspMod().equals(GSConstSchedule.DSP_MOD_DAY)) {
urlForward = map.findForward("040kn_day");
} else if (form.getDspMod().equals(GSConstSchedule.DSP_MOD_MAIN)) {
urlForward = map.findForward("040kn_main");
} else if (form.getDspMod().equals(GSConstSchedule.DSP_MOD_KOJIN_WEEK)) {
urlForward = map.findForward("040kn_kojin");
} else {
urlForward = map.findForward("040kn_week");
}
}
GsMessage gsMsg = new GsMessage();
//スケジュール
String textSchedule = gsMsg.getMessage(req, "schedule.108");
cmn999Form.setUrlOK(urlForward.getPath());
cmn999Form.setMessage(msgRes.getMessage("touroku.kanryo.object",
textSchedule));
cmn999Form.addHiddenParam("sch010DspDate", form.getSch010DspDate());
cmn999Form.addHiddenParam("changeDateFlg", form.getChangeDateFlg());
cmn999Form.addHiddenParam("sch010DspGpSid", form.getSch010DspGpSid());
cmn999Form.addHiddenParam("sch010SelectUsrSid", form.getSch010SelectUsrSid());
cmn999Form.addHiddenParam("sch010SelectUsrKbn", form.getSch010SelectUsrKbn());
cmn999Form.addHiddenParam("sch010SelectDate", form.getSch010SelectDate());
cmn999Form.addHiddenParam("sch020SelectUsrSid", form.getSch020SelectUsrSid());
cmn999Form.addHiddenParam("schWeekDate", form.getSchWeekDate());
cmn999Form.addHiddenParam("schDailyDate", form.getSchDailyDate());
cmn999Form.addHiddenParam("sch100SelectUsrSid", form.getSch100SelectUsrSid());
cmn999Form.addHiddenParam("sch100PageNum", form.getSch100PageNum());
cmn999Form.addHiddenParam("sch100Slt_page1", form.getSch100Slt_page1());
cmn999Form.addHiddenParam("sch100Slt_page2", form.getSch100Slt_page2());
cmn999Form.addHiddenParam("sch100OrderKey1", form.getSch100OrderKey1());
cmn999Form.addHiddenParam("sch100SortKey1", form.getSch100SortKey1());
cmn999Form.addHiddenParam("sch100OrderKey2", form.getSch100OrderKey2());
cmn999Form.addHiddenParam("sch100SortKey2", form.getSch100SortKey2());
cmn999Form.addHiddenParam("sch100SvOrderKey1", form.getSch100SvOrderKey1());
cmn999Form.addHiddenParam("sch100SvSortKey1", form.getSch100SvSortKey1());
cmn999Form.addHiddenParam("sch100SvOrderKey2", form.getSch100SvOrderKey2());
cmn999Form.addHiddenParam("sch100SortKey2", form.getSch100SvSortKey2());
req.setAttribute("cmn999Form", cmn999Form);
forward = map.findForward("gf_msg");
return forward;
}
/**
* <br>[機 能] スケジュールデータに関するエラーページ設定を行う
* <br>[解 説]
* <br>[備 考]
* @param map アクションマッピング
* @param form アクションフォーム
* @param req リクエスト
* @param res レスポンス
* @param con コネクション
* @param errorType エラーの種類
* @return ActionForward
*/
private ActionForward __doDataError(ActionMapping map, Sch040knForm form,
HttpServletRequest req, HttpServletResponse res, Connection con,
int errorType) {
ActionForward forward = null;
Cmn999Form cmn999Form = new Cmn999Form();
ActionForward urlForward = null;
GsMessage gsMsg = new GsMessage();
//スケジュール登録完了画面パラメータの設定
MessageResources msgRes = getResources(req);
cmn999Form.setType(Cmn999Form.TYPE_OK);
cmn999Form.setIcon(Cmn999Form.ICON_WARN);
cmn999Form.setWtarget(Cmn999Form.WTARGET_BODY);
String listMod = NullDefault.getString(form.getListMod(), "");
if (listMod.equals(GSConstSchedule.DSP_MOD_LIST)) {
urlForward = map.findForward("040kn_list");
} else {
String dspMod = NullDefault.getString(form.getDspMod(), "");
if (dspMod.equals(GSConstSchedule.DSP_MOD_WEEK)) {
urlForward = map.findForward("040kn_week");
} else if (dspMod.equals(GSConstSchedule.DSP_MOD_MONTH)) {
urlForward = map.findForward("040kn_month");
} else if (dspMod.equals(GSConstSchedule.DSP_MOD_DAY)) {
urlForward = map.findForward("040kn_day");
} else if (dspMod.equals(GSConstSchedule.DSP_MOD_MAIN)) {
urlForward = map.findForward("040kn_main");
} else if (dspMod.equals(GSConstSchedule.DSP_MOD_KOJIN_WEEK)) {
urlForward = map.findForward("040kn_kojin");
} else {
urlForward = map.findForward("040kn_week");
}
}
//エラーメッセージ
if (errorType == ERRORTYPE_NONE__) {
//変更
String textSchedule = gsMsg.getMessage(req, "schedule.108");
String textChange = gsMsg.getMessage(req, "cmn.change");
cmn999Form.setMessage(msgRes.getMessage("error.none.edit.data",
textSchedule, textChange));
} else if (errorType == ERRORTYPE_VIEW__) {
cmn999Form.setMessage(msgRes.getMessage("error.notaccess.scd"));
}
cmn999Form.setUrlOK(urlForward.getPath());
cmn999Form.addHiddenParam("sch010DspDate", form.getSch010DspDate());
cmn999Form.addHiddenParam("changeDateFlg", form.getChangeDateFlg());
cmn999Form.addHiddenParam("sch010DspGpSid", form.getSch010DspGpSid());
cmn999Form.addHiddenParam("sch010SelectUsrSid", form.getSch010SelectUsrSid());
cmn999Form.addHiddenParam("sch010SelectUsrKbn", form.getSch010SelectUsrKbn());
cmn999Form.addHiddenParam("sch010SelectDate", form.getSch010SelectDate());
cmn999Form.addHiddenParam("schWeekDate", form.getSchWeekDate());
cmn999Form.addHiddenParam("schDailyDate", form.getSchDailyDate());
cmn999Form.addHiddenParam("sch100SelectUsrSid", form.getSch100SelectUsrSid());
cmn999Form.addHiddenParam("sch100PageNum", form.getSch100PageNum());
cmn999Form.addHiddenParam("sch100Slt_page1", form.getSch100Slt_page1());
cmn999Form.addHiddenParam("sch100Slt_page2", form.getSch100Slt_page2());
cmn999Form.addHiddenParam("sch100OrderKey1", form.getSch100OrderKey1());
cmn999Form.addHiddenParam("sch100SortKey1", form.getSch100SortKey1());
cmn999Form.addHiddenParam("sch100OrderKey2", form.getSch100OrderKey2());
cmn999Form.addHiddenParam("sch100SortKey2", form.getSch100SortKey2());
cmn999Form.addHiddenParam("sch100SvOrderKey1", form.getSch100SvOrderKey1());
cmn999Form.addHiddenParam("sch100SvSortKey1", form.getSch100SvSortKey1());
cmn999Form.addHiddenParam("sch100SvOrderKey2", form.getSch100SvOrderKey2());
cmn999Form.addHiddenParam("sch100SortKey2", form.getSch100SvSortKey2());
req.setAttribute("cmn999Form", cmn999Form);
forward = map.findForward("gf_msg");
return forward;
}
}
|
Rust | UTF-8 | 3,772 | 3.734375 | 4 | [] | no_license | //! A graph data structure backed by a Vec and a Hashmap. The Vec stores the
//! vertices whereas the Hashmap provides a quick way to find a vertex by its
//! name.
// todo:
// - implement tests
// - test performance for this implementation agains one soleny based on HashMap
use std::collections::{HashMap, HashSet};
#[derive(Default)]
pub struct Graph {
names: HashMap<String, usize>,
vertices: Vec<Vertex>,
}
struct Vertex {
name: String,
pointed_by: Vec<Edge>,
points_to: Vec<Edge>,
}
struct Edge {
to_vertex: usize,
weight: u32,
}
//--------------------------------------------------------------------
// Implementation
//--------------------------------------------------------------------
impl Graph {
pub fn new() -> Self {
Graph::default()
}
pub fn add_edge(&mut self, vertex0: &str, vertex1: &str, weight: u32) {
let v0 = self.get_or_add_vertex(vertex0);
let v1 = self.get_or_add_vertex(vertex1);
self.vertices[v0].points_to.push(Edge::new(v1, weight));
self.vertices[v1].pointed_by.push(Edge::new(v0, weight));
}
pub fn add_edges(&mut self, vertex0: &str, vertices: &[(u32, String)]) {
for vertex in vertices {
self.add_edge(vertex0, &vertex.1, vertex.0);
}
}
/// Returns a set containing the indexes of all ancestor vertices
pub fn list_ancestors(&self, name: &str) -> HashSet<usize> {
let mut cache = HashSet::<usize>::new();
if let Some(&idx) = self.names.get(name) {
self.rec_list_ancestors(&mut cache, idx);
}
cache
}
/// Returns the combined weight of all successors vertices
/// For example, the graph 1 - 2 - 3
/// |- 4
/// has a combined weight of 1 + 1 * ( 2 + 2 * (4 + 3)) = 17.
pub fn weigh_successors(&self, name: &str) -> u32 {
let mut weight = 0;
if let Some(&idx) = self.names.get(name) {
weight = self.rec_weigh_sucessors(idx);
}
weight
}
//------------------------------
// Helpers
//------------------------------
fn rec_list_ancestors(&self, cache: &mut HashSet<usize>, idx: usize) {
let pointed_by = &self.vertices[idx].pointed_by;
for edge in pointed_by {
if !cache.contains(&edge.to_vertex) {
cache.insert(edge.to_vertex);
self.rec_list_ancestors(cache, edge.to_vertex);
}
}
}
fn rec_weigh_sucessors(&self, idx: usize) -> u32 {
let points_to = &self.vertices[idx].points_to;
let mut weight = 0;
for edge in points_to {
weight += edge.weight + edge.weight * self.rec_weigh_sucessors(edge.to_vertex);
}
weight
}
fn add_vertex(&mut self, v: Vertex) -> usize {
let idx = self.vertices.len();
self.vertices.push(v);
self.names
.insert(self.vertices.last().unwrap().name.clone(), idx);
idx
}
fn get_or_add_vertex(&mut self, vertex: &str) -> usize {
let idx;
if !self.names.contains_key(vertex) {
idx = self.add_vertex(Vertex::new(vertex));
} else {
idx = *self.names.get(vertex).unwrap();
}
idx
}
}
impl Vertex {
fn new(name: &str) -> Self {
Self {
name: name.to_owned(),
pointed_by: Vec::new(),
points_to: Vec::new(),
}
}
}
impl Edge {
fn new(to_vertex: usize, weight: u32) -> Self {
Self { to_vertex, weight }
}
}
//--------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------
#[cfg(test)]
mod tests {}
|
Java | UTF-8 | 776 | 2.25 | 2 | [] | no_license | import org.apache.log4j.Logger;
import org.sonar.template.java.checks.myException;
public class logTCheckFile {
private static Logger logger = Logger.getLogger(logTCheckFile.class);
public void loggingWithID(String nonsense) throws myException{
logger.error("errorID:20160801 this is an error");
return;
}
public void loggingWithoutID(String nonsens){
try{
logger.error("this is an error");
}catch(NullPointerException e){
logger.error("what",e);
}
return;
}
public void specific(){// Noncompliant {you didn't print the exception in the log}
logger.error("only the logger");
try{
logger.error("this is an error");
}catch(NullPointerException e){
logger.error("without an exception");
}
return;
}
}
|
Java | UTF-8 | 1,359 | 2.46875 | 2 | [] | no_license | package gov.noaa.ncdc.wct.decoders.cdm;
//package gov.noaa.ncdc.ndit.decoders.cdm;
//
//import org.junit.Test;
//
//public class TestGridDatasetContours {
//
//
// @Test
// public void testContour() throws Exception {
// GridDatasetContours ce = new GridDatasetContours();
// String inFile = "H:\\NetCDF\\Stage4\\ST4.2006040112.24h";
// String outDir = "H:\\NetCDF\\Stage4\\";
// ce.process(inFile, outDir);
// }
//
//
//
//
//
//
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// try {
// GridDatasetContours ce = new GridDatasetContours();
//
// if (args.length == 0 || (args.length != 2 && ! args[0].equalsIgnoreCase("test"))) {
// System.err.println("Input arguments of \n 1: Input Stage-IV GRIB file \n 2: Output dir");
// }
// else if (args[0].equalsIgnoreCase("test")) {
// String inFile = "H:\\NetCDF\\Stage4\\ST4.2006040112.24h";
// String outDir = "H:\\NetCDF\\Stage4\\";
// ce.process(inFile, outDir);
// }
// else {
// ce.process(args[0], args[1]);
// }
//
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
//}
|
PHP | UTF-8 | 980 | 3.390625 | 3 | [] | no_license | <?php
class Actor
{
private $id;
private $first_name;
private $last_name;
private $movie_id;
private $title;
public function __construct($first_name, $last_name)
{
$this->first_name = $first_name;
$this->last_name = $last_name;
}
public function setFirstName($first_name)
{
$this->first_name = $first_name;
}
public function getFirstName()
{
return $this->first_name;
}
public function setLastName($last_name)
{
$this->last_name = $last_name;
}
public function getLastName()
{
return $this->last_name;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
if ($this->title) {
return $this->title;
}
return 'Sin pelicula favorita';
}
public function setMovieID($movie_id)
{
$this->movie_id = $movie_id;
}
public function getMovieID()
{
return $this->movie_id;
}
}
|
JavaScript | UTF-8 | 11,670 | 3.046875 | 3 | [] | no_license | // Hunter Figueroa
// New Relic Code Challenge
// 2018 8 28
//
// Mobx AppStore/Data layer, contains most of site data and methods, and all API calls
import {observable, action, toJS} from 'mobx';
import moment from 'moment';
export default class AppStore{
constructor(){
// Initialize Day Range
this.getDayRange();
// Bindings
this.getChartData = this.getChartData.bind(this);
this.setDisplayData = this.setDisplayData.bind(this);
this.setC = this.setC.bind(this);
this.setF = this.setF.bind(this);
this.toggleHigh = this.toggleHigh.bind(this);
this.toggleLow = this.toggleLow.bind(this);
}
// Chart Data
@observable
chartData = null;
@observable
displayData = null;
@observable
chartOptions = {
min: 40,
max: 100
}
@observable
errorMsg = null;
@action
setDisplayData(){
this.displayData = [{name: "High", data: {}}, {name: "Low", data: {}}];
var min = 9999999, max = -9999999;
var tempH = null, tempL = null;
// Sort data by date
var chartData = toJS(this.chartData).sort((a,b)=>{
return new Date(b[0]) - new Date(a[0]);
})
// Get Display depending on timespan
if(this.timeSpan === "daily")
this.displayDaily(min, max, tempH, tempL, chartData);
else if(this.timeSpan === "weekly")
this.displayWeekly(min, max, tempH, tempL, chartData);
else if(this.timeSpan === "monthly")
this.displayMonthly(min, max, tempH, tempL, chartData);
}
@action
displayDaily(min, max, tempH, tempL, chartData){
var count = 0;
for (var data of chartData) {
var date = data[0];
var dayData = data[1];
if(count === 7){
break;
}
//console.log("Daily Data", date, count, dayData)
// Grab all F temperatures
if(this.mode === "F"){
//Grab High
tempH = dayData.high.f;
if(this.high){
this.displayData[0].data[date] = tempH;
// Min max Checker for bounds
if(max < tempH){
max = tempH;
}
if(min > tempH){
min = tempH;
}
}
// Grab Low
tempL = dayData.low.f;
if(this.low){
this.displayData[1].data[date] = tempL;
// Min max Checker for bounds
if(max < tempL){
max = tempL;
}
if(min > tempL){
min = tempL;
}
}
}
else{
// Grab all C temperatures
// Grab High
tempH = dayData.high.c;
if(this.high){
this.displayData[0].data[date] = tempH;
// Min max Checker for bounds
if(max < tempH){
max = tempH;
}
if(min > tempH){
min = tempH;
}
}
//Grab Low
tempL = dayData.low.c;
if(this.low){
this.displayData[1].data[date] = tempL;
// Min max Checker for bounds
if(max < tempL){
max = tempL;
}
if(min > tempL){
min = tempL;
}
}
}
count++;
}
// Setbounds
this.chartOptions.min = min - 5;
this.chartOptions.max = max + 5;
}
@action
displayWeekly(min, max, tempH, tempL, chartData){
var weeklyTotalH = 0, weeklyTotalL = 0;
var weekStart = null;
var avgH = 0, avgL = 0;
var count = 0;
// Iterate through all raw day data
for (var data of chartData){
var date = data[0];
var dayData = data[1];
// Add Data and wipe record at end of each week
if(count === 7){
// Calc average High
if(weeklyTotalH !== 0){
avgH = Math.floor(weeklyTotalH/7);
this.displayData[0].data[weekStart] = avgH;
// Min and Max for graph bounds
if(min > avgH){
min = avgH;
}
if(max < avgH ){
max = avgH;
}
}
// Calc average Low
if(weeklyTotalL !== 0){
avgL = Math.floor(weeklyTotalL/7);
this.displayData[1].data[weekStart] = avgL;
// Min and Max for graph bounds
if(min > avgL){
min = avgL;
}
if(max < avgL ){
max = avgL;
}
}
// Wipe
weeklyTotalH = 0;
weeklyTotalL = 0;
count = 0;
}
// Set the week start
if(count === 0){
weekStart = date;
}
// Grab all F temperatures
if(this.mode === "F"){
//Grab High
if(this.high)
weeklyTotalH += dayData.high.f;
if(this.low)
weeklyTotalL += dayData.low.f;
}
else{
// Grab all C temperatures
if(this.high)
weeklyTotalH += dayData.high.c;
if(this.low)
weeklyTotalL += dayData.low.c;
}
count++;
}
// Set Graph bounds
this.chartOptions.min = min - 5;
this.chartOptions.max = max + 5;
}
@action
displayMonthly(min, max, tempH, tempL, chartData){
var monthlyTotalH = 0, monthlyTotalL = 0;
var monthStart = null, monthEnd = null;
var count = 0;
// Iterate through all raw day data
for (var data of chartData) {
var date = data[0];
var dayData = data[1];
// End and start dates
if(count === 0){
monthStart = date;
}
if(count === 29){
monthEnd = date;
}
// Grab all F temperatures
if(this.mode === "F"){
//Grab High
if(this.high)
monthlyTotalH += dayData.high.f;
if(this.low)
monthlyTotalL += dayData.low.f;
}
else{
// Grab all C temperatures
if(this.high)
monthlyTotalH += dayData.high.c;
if(this.low)
monthlyTotalL += dayData.low.c;
}
count++;
}
// Calcualte Monthly Average - If the total was 0 then dont add data to the graph
var avgH, avgL;
if(monthlyTotalH !== 0){
avgH = Math.floor(monthlyTotalH/30);
this.displayData[0].data[monthStart] = avgH;
this.displayData[0].data[monthEnd] = avgH;
}
else{
avgH = 0;
}
if(monthlyTotalL !== 0){
avgL = Math.floor(monthlyTotalL/30);
this.displayData[1].data[monthStart] = avgL;
this.displayData[1].data[monthEnd] = avgL;
}
else{
avgL = 0;
}
// Find min and max for graph bounds
if( monthlyTotalH !== 0 && monthlyTotalL !== 0){
this.chartOptions.min = avgL - 5;
this.chartOptions.max = avgH + 5;
}
else{
if(monthlyTotalL === 0 && monthlyTotalH !== 0){
this.chartOptions.min = avgH - 5;
this.chartOptions.max = avgH + 5;
}
else if(monthlyTotalH === 0 && monthlyTotalL !== 0){
this.chartOptions.min = avgL - 5;
this.chartOptions.max = avgL + 5;
}
else{
this.chartOptions.min = 10;
this.chartOptions.max = -10;
}
}
}
// Options
@observable
dataCounter = 0;
@observable
mode = "F";
@observable
high = true;
@observable
low = true;
@observable
timeSpan = 'daily';
times = ['daily', 'weekly', 'monthly'];
@action
pickTime(time){
if(this.timeSpan !== time){
this.timeSpan = time;
this.setDisplayData();
}
}
@action
setF(){
if(this.mode !== "F"){
// console.log("Setting f");
this.mode = "F";
this.setDisplayData();
}
}
@action
setC(){
// console.log("Setting C");
if(this.mode !== "C"){
this.mode = "C";
this.setDisplayData();
}
}
@action
toggleHigh(){
this.high = !this.high;
this.setDisplayData();
}
@action
toggleLow(){
this.low = !this.low;
this.setDisplayData();
}
// Location Data
@observable
currentLocation = "Rome, Italy";
locations = ["San Francisco, CA",
"Amsterdam, Netherlands",
"Oakland, CA",
"Rome, Italy",
"Cleveland, OH",
"Tel Aviv, Israel",
"New York City, NY",
"Murmansk, Russia",
"Istanbul, Turkey"];
@action
setLocation(location){
if(this.currentLocation !== location){
this.currentLocation = location;
this.getChartData();
}
}
// Day Range
@observable
dayRange = [];
@action
getDayRange(){
for(let i = 0; i < 30; i++){
this.dayRange.push(moment().subtract(i, 'days').format('YYYY-MM-DD'));
}
}
// Weather API
@action
getChartData(){
this.chartData = [];
this.errorMsg = null;
this.dataCounter = 0;
// Loop through all Days in range
for(let day of toJS(this.dayRange)){
// Dynamicly Fetch data using APIXU
fetch('http://api.apixu.com/v1/history.json?key=0cedbbf7880d4f52919145142182808&q='+this.currentLocation+'&dt='+day)
.then(res =>{
return res.json()
})
.then(data => {
// Grab and reformat raw data
if(data.error){
this.errorMsg = data.error.message;
}
else{
var dayData = data.forecast.forecastday[0].day;
this.chartData.push([day ,{high:{f: dayData.maxtemp_f, c: dayData.maxtemp_c}, low:{f: dayData.mintemp_f, c: dayData.mintemp_c}}]);
// console.log("ChartData:", toJS(this.chartData), this.dataCounter );
this.dataCounter++;
// Refresh UI only when all data aggregated
if(this.dataCounter === 30){
this.setDisplayData();
}
}
});
}
}
} |
Java | UTF-8 | 1,338 | 3.78125 | 4 | [] | no_license | package com.zhangpan.leetcode.tree;
/**
* 110. 平衡二叉树
* 给定一个二叉树,判断它是否是高度平衡的二叉树。
*
* 本题中,一棵高度平衡二叉树定义为:
*
* 一个二叉树每个节点 的左右两个子树的高度差的绝对值不超过 1 。
*
* 示例 1:
*
*
* 输入:root = [3,9,20,null,null,15,7]
* 输出:true
* 示例 2:
*
*
* 输入:root = [1,2,2,3,3,null,null,4,4]
* 输出:false
* 示例 3:
*
* 输入:root = []
* 输出:true
*
* 提示:
*
* 树中的节点数在范围 [0, 5000] 内
* -104 <= Node.val <= 104
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/balanced-binary-tree
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
*
*/
public class LeetCode110 {
public boolean isBalanced(TreeNode root) {
if (root == null || (root.right == null && root.left == null)) {
return true;
}
return Math.abs(getTreeDepth(root.left) - getTreeDepth(root.right)) <= 1 && isBalanced(root.right) && isBalanced(root.left);
}
private int getTreeDepth(TreeNode node) {
if (node == null) {
return 0;
}
return Math.max(getTreeDepth(node.right), getTreeDepth(node.left)) + 1;
}
}
|
C++ | UTF-8 | 1,160 | 2.859375 | 3 | [] | no_license | #pragma once
#include <vector>
#include "glUtility/Vertex.h"
#include "math/Vector.h"
namespace Curves
{
class Curve
{
public:
Curve(
const MathTypes::Vector<3, float>& start,
const MathTypes::Vector<3, float>& end,
const GLUtility::Colour<float>& colourOfControlCurve,
const GLUtility::Colour<float>& colourOfSmoothedCurve);
~Curve() = default;
void insertPoint();
void deletePoint();
std::vector<GLUtility::Vertex<float, float>> vertices() const;
std::vector<MathTypes::Vector<3, float>> coordinates() const;
std::vector<GLUtility::Vertex<float, float>> verticesOfSmoothedCurve() const;
std::vector<MathTypes::Vector<3, float>> coordinatesOfSmoothedCurve() const;
std::vector<GLUtility::Vertex<float, float>> verticesOfBothCurves() const;
MathTypes::Vector<3, float>* intersectedCoordinate(const MathTypes::Vector<3, float>& coordinateToCheck);
private:
std::vector<MathTypes::Vector<3, float>> points_;
std::vector<MathTypes::Vector<3, float>>::iterator insertionPoint_;
GLUtility::Colour<float> colourOfControlCurve_;
GLUtility::Colour<float> colourOfSmoothedCurve_;
};
} |
C# | UTF-8 | 707 | 3.140625 | 3 | [] | no_license | using System;
namespace WorkingWithNulls
{
class Program
{
static void Main(string[] args)
{
Person[] person = new Person[3]
{
new Person(){Name = "Sarah"},
new Person(),
null
};
//int b = (int)person.Lvl;
//Person[] person=null;
var t1 = person?[0]?.Name;
var t2 = person?[1]?.Name;
var t3 = person?[2]?.Name;
var t4 = person[0]?.Name;
Console.WriteLine(t1);
Console.WriteLine(t2);
Console.WriteLine(t3);
//Console.WriteLine(person.B.GetValueOrDefault());
}
}
}
|
Markdown | UTF-8 | 1,038 | 2.578125 | 3 | [] | no_license | # leuko-tf
### local development
* Create a virtual machine using the latest version of Ubuntu 64-bit.
* Launch the virtual machine, upgrade and update
```
sudo apt upgrade
sudo apt update
```
* Install TensorFlow dependencies
```
sudo apt install python-pip python-dev python-virtualenv git
```
* Create virtual environment for TensorFlow development
```
virtualenv --system-site-packages ~/tensorflow
```
* Active the virtual environment
```
source ~/tensorflow/bin/activate
```
* Install TensorFlow (see the TensorFlow installation guide for the latest Linux 64-bit, CPU only, Python 2.7 whl file)
```
pip install --upgrade https://storage.googleapis.com/tensorflow/linux/cpu/tensorflow-0.10.0rc0-cp27-none-linux_x86_64.whl
```
* Install other dependencies
```
pip install scipy Pillow
```
* Clone this repository if you haven't already
```
git clone https://github.com/boerjames/leuko-tf.git
```
Use your favorite IDE (mine is PyCharm) to work on this project using the virtual environment we created.
### server deployment
|
C# | UTF-8 | 1,884 | 3.03125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using UnoServer.Services;
namespace UnoServer.Models
{
public class UnoCard : IEquatable<UnoCard>
{
public Guid Id { get; set; }
public UnoCardType Type { get; set; }
public int NumberValue { get; set; }
public UnoCardColor Color { get; set; }
public override bool Equals(object obj)
{
return Equals(obj as UnoCard);
}
public bool Equals(UnoCard other)
{
if (Type != UnoCardType.ChooseColor || Type != UnoCardType.TakeFourChooseColor)
{
return other != null
&& Type == other.Type
&& NumberValue == other.NumberValue
&& Color == other.Color;
}
else
{
return other != null
&& Type == other.Type;
}
}
public override string ToString()
{
return $"{Type.GetDescription()} {NumberValue} {Color.GetDescription()}";
}
}
public enum UnoCardType
{
[Description("Number")]
Numeric = 0,
[Description("Reverse")]
Reverse = 1,
[Description("Skip move")]
Skip,
[Description("Take two")]
TakeTwo,
[Description("Take four and choose color")]
TakeFourChooseColor,
[Description("Choose color")]
ChooseColor
}
public enum UnoCardColor
{
[Description("Red")]
Red = 0,
[Description("Green")]
Green = 1,
[Description("Blue")]
Blue,
[Description("Yellow")]
Yellow
}
}
|
Java | UTF-8 | 1,239 | 2.5 | 2 | [] | no_license | package com.demo.booking.service;
import java.util.List;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.demo.booking.dto.MovieDTO;
import com.demo.booking.repo.MovieRepo;
@Service
public class MovieServiceImpl implements MovieService{
@Autowired
MovieRepo movieRepo;
@Override
public List<MovieDTO> viewAllMovies() {
// TODO Auto-generated method stub
return (List<MovieDTO>) movieRepo.findAll();
}
@Override
public boolean addMovie(MovieDTO Movie) {
movieRepo.save(Movie);
return true;
}
@Override
public String editMovie(MovieDTO Movie) {
Optional<MovieDTO> findMovie=movieRepo.findById(Movie.getMovieId());
if(!findMovie.isPresent() || findMovie == null) {
movieRepo.save(Movie);
return "Edited Succesfully";
}
return "No movie found for the given id!" ;
}
@Override
public boolean deleteMovie(MovieDTO Movie) {
movieRepo.delete(Movie);
return true;
}
@Override
public String searchMovie(String Movie) {
String findMovie=movieRepo.findByMovieName(Movie);
if(findMovie == null) {
return "No movie found for the given id!" ;
}
return findMovie ;
}
}
|
Java | UTF-8 | 5,521 | 2.1875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright © 2021-present Arcade Data Ltd (info@arcadedata.com)
*
* 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.
*
* SPDX-FileCopyrightText: 2021-present Arcade Data Ltd (info@arcadedata.com)
* SPDX-License-Identifier: Apache-2.0
*/
package com.arcadedb.integration.restore.format;
import com.arcadedb.database.DatabaseFactory;
import com.arcadedb.database.DatabaseInternal;
import com.arcadedb.integration.importer.ConsoleLogger;
import com.arcadedb.integration.restore.RestoreException;
import com.arcadedb.integration.restore.RestoreSettings;
import com.arcadedb.utility.FileUtils;
import java.io.*;
import java.net.*;
import java.util.zip.*;
public class FullRestoreFormat extends AbstractRestoreFormat {
private final byte[] BUFFER = new byte[8192];
private static class RestoreInputSource {
public final InputStream inputStream;
public final long fileSize;
public RestoreInputSource(final InputStream inputStream, final long fileSize) {
this.inputStream = inputStream;
this.fileSize = fileSize;
}
}
public FullRestoreFormat(final DatabaseInternal database, final RestoreSettings settings, final ConsoleLogger logger) {
super(database, settings, logger);
}
@Override
public void restoreDatabase() throws Exception {
settings.validate();
final RestoreInputSource inputSource = openInputFile();
final File databaseDirectory = new File(settings.databaseDirectory);
if (databaseDirectory.exists()) {
if (!settings.overwriteDestination)
throw new RestoreException(String.format("The database directory '%s' already exist and '-o' setting is false", settings.databaseDirectory));
FileUtils.deleteRecursively(databaseDirectory);
}
if (!databaseDirectory.mkdirs())
throw new RestoreException(String.format("Error on restoring database: the database directory '%s' cannot be created", settings.databaseDirectory));
logger.logLine(0, "Executing full restore of database from file '%s' to '%s'...", settings.inputFileURL, settings.databaseDirectory);
try (final ZipInputStream zipFile = new ZipInputStream(inputSource.inputStream, DatabaseFactory.getDefaultCharset())) {
final long beginTime = System.currentTimeMillis();
long databaseOrigSize = 0L;
ZipEntry compressedFile = zipFile.getNextEntry();
while (compressedFile != null) {
databaseOrigSize += uncompressFile(zipFile, compressedFile, databaseDirectory);
compressedFile = zipFile.getNextEntry();
}
zipFile.close();
final long elapsedInSecs = (System.currentTimeMillis() - beginTime) / 1000;
logger.logLine(0, "Full restore completed in %d seconds %s -> %s (%,d%% compression)", elapsedInSecs, FileUtils.getSizeAsString(databaseOrigSize),
FileUtils.getSizeAsString((inputSource.fileSize)), databaseOrigSize > 0 ? (databaseOrigSize - inputSource.fileSize) * 100 / databaseOrigSize : 0);
}
}
private long uncompressFile(final ZipInputStream inputFile, final ZipEntry compressedFile, final File databaseDirectory) throws IOException {
final String fileName = compressedFile.getName();
FileUtils.checkValidName(fileName);
logger.log(2, "- File '%s'...", fileName);
final File uncompressedFile = new File(databaseDirectory, fileName);
if (!uncompressedFile.toPath().normalize().startsWith(databaseDirectory.toPath().normalize())) {
throw new IOException("Bad zip entry");
}
try (final FileOutputStream fileOut = new FileOutputStream(uncompressedFile)) {
int len;
while ((len = inputFile.read(BUFFER)) > 0) {
fileOut.write(BUFFER, 0, len);
}
}
final long origSize = uncompressedFile.length();
final long compressedSize = compressedFile.getCompressedSize();
logger.logLine(2, " %s -> %s (%,d%% compressed)", FileUtils.getSizeAsString(origSize), FileUtils.getSizeAsString(compressedSize),
origSize > 0 ? (origSize - compressedSize) * 100 / origSize : 0);
return origSize;
}
private RestoreInputSource openInputFile() throws IOException {
if (settings.inputFileURL.startsWith("http://") || settings.inputFileURL.startsWith("https://")) {
final HttpURLConnection connection = (HttpURLConnection) new URL(settings.inputFileURL).openConnection();
connection.setRequestMethod("GET");
connection.setDoOutput(true);
connection.connect();
return new RestoreInputSource(connection.getInputStream(), 0);
}
String path = settings.inputFileURL;
if (path.startsWith("file://")) {
path = path.substring("file://".length());
} else if (path.startsWith("classpath://"))
path = getClass().getClassLoader().getResource(path.substring("classpath://".length())).getFile();
final File file = new File(path);
if (!file.exists())
throw new RestoreException(String.format("The backup file '%s' not exist", settings.inputFileURL));
return new RestoreInputSource(new FileInputStream(file), file.length());
}
}
|
JavaScript | UTF-8 | 4,077 | 2.734375 | 3 | [] | no_license | import {
clearButton,
colorPicker,
thicknessSlider,
drawButton,
eraseButton,
colorPickerBtn,
thicknessBtn,
thicknessBarPopup
} from "./constants.js";
import { getRoomId, CanvasData } from "./helpers.js";
import { drawStroke, eraseStroke } from "./stroke_events.js";
import { handleToolbarClick } from "./toolbar.js";
import Atrament from "atrament";
const io = require("socket.io-client");
window.onload = () => {
let socket = io();
const canvasData = new CanvasData(getRoomId(), true, "#000000");
const canvas = document.querySelector('#canvas');
const canvasContext = canvas.getContext("2d");
const sketchpad = new Atrament(canvas, {
width: window.screen.availWidth,
height: window.screen.availHeight,
});
sketchpad.recordStrokes = true;
window.onbeforeunload = () => {
socket.emit('client_disconnecting', { roomId: canvasData.roomId });
}
socket.on("connect", () => socket.emit("joinRoom", canvasData.roomId));
socket.on("disconnect", () => { socket.emit("disconnect") });
socket.on("drawEvent", (strokeData) => drawStroke(strokeData, sketchpad, canvasData));
socket.on("clearEvent", () => sketchpad.clear());
socket.on("eraseEvent", (strokeData) => eraseStroke(strokeData, sketchpad, canvasData));
socket.on("getCanvasImage", (userId) => {
let canvasImage = sketchpad.toImage();
socket.emit("saveCanvasImage", {
roomId: userId,
image: canvasImage
})
});
socket.on("newCanvasImageEvent", (canvasImage) => {
let img = new Image();
img.src = canvasImage;
img.onload = () => {
canvasContext.drawImage(img, 0, 0);
}
});
sketchpad.addEventListener('strokerecorded', ({ stroke }) => {
if (canvasData.recordStrokes) {
if (sketchpad.mode == "draw") {
socket.emit("drawEvent", {
coordinates: stroke.points,
weight: stroke.weight,
color: sketchpad.color,
room: canvasData.roomId
});
}
else if (sketchpad.mode == "erase") {
socket.emit("eraseEvent", {
coordinates: stroke.points,
weight: stroke.weight,
room: canvasData.roomId
});
}
}
}
);
canvas.addEventListener("mousedown", () => {
canvasData.recordStrokes = true;
thicknessBarPopup.style.display = 'none';
});
drawButton.addEventListener("click", () => {
sketchpad.mode = "draw";
handleToolbarClick(drawButton);
});
thicknessBtn.addEventListener("click", () => {
// Boolean indicating if pop is open or not
const isOpen = thicknessBarPopup.style.display == 'block';
if (isOpen) {
thicknessBarPopup.style.display = 'none';
}
else {
thicknessBarPopup.style.display = 'block';
}
});
eraseButton.addEventListener("click", () => {
sketchpad.mode = "erase";
handleToolbarClick(eraseButton);
thicknessBarPopup.style.display = 'none';
});
colorPickerBtn.addEventListener("click", () => {
// Show color picker menu
colorPicker.click();
thicknessBarPopup.style.display = 'none';
})
colorPicker.addEventListener("change", (event) => {
canvasData.strokesColor = event.target.value;
sketchpad.color = event.target.value;
});
clearButton.addEventListener("click", () => {
thicknessBarPopup.style.display = 'none';
const confirmClear = confirm("Are you sure you want to clear the board?");
if (confirmClear) {
sketchpad.clear();
socket.emit("clearEvent", {
room: canvasData.roomId
});
}
});
thicknessSlider.addEventListener("change", () => {
sketchpad.weight = parseInt(thicknessSlider.value);
});
} |
Swift | UTF-8 | 777 | 3 | 3 | [] | no_license | //
// SchoolSAT.swift
// MVCSample
//
// Created by Park, Chanick on 3/8/18.
// Copyright © 2018 Chanick Park. All rights reserved.
//
import Foundation
//
// School SAT Model
//
struct SchoolSAT : Codable {
let dbn: String
let school_name: String
let num_of_sat_test_takers: String
let sat_critical_reading_avg_score: String
let sat_math_avg_score: String
let sat_writing_avg_score: String
// Displays List
var displays: [(name: String, score: String)] {
return [("Num of SAT Test Takers", num_of_sat_test_takers),
("SAT Critical Reading Avg. Score", sat_critical_reading_avg_score),
("SAT Math Avg. Score", sat_math_avg_score),
("SAT Writing Avg. Score", sat_writing_avg_score)]
}
}
|
Java | UTF-8 | 4,350 | 2.421875 | 2 | [] | no_license | package selenium;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
public class Topic_03_Webelement_Api_Commands_Exercises {
WebDriver driver;
By emailTextBoxBy = By.id("mail");
By ageOptionUnder18ButtonBy = By.id("under_18");
By educationTextBoxBy = By.id("edu");
By job1DropdownBy = By.id("job1");
By interestDevelopmentBy = By.id("development");
By slider01By = By.id("slider-1");
By passwordTextBoxBy = By.id("password");
By ageRadioButtonDisabledBy = By.id("radio-disabled");
By biographyTextBoxBy = By.id("bio");
By interestCheckBoxDisabled = By.id("check-disbaled");
By slider02By = By.id("slider-2");
By job3DropdownBy = By.id("job3");
@BeforeClass
public void beforeClass() {
System.setProperty("webdriver.chrome.driver", ".\\libraries\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@BeforeMethod
public void beforeMethod() {
driver.get("https://automationfc.github.io/basic-form/index.html");
}
@Test
public void TC_01_Verified_Element_Displayed() {
if(isElementDisplyed(emailTextBoxBy)) {
sendKeyToElement(emailTextBoxBy,"Automation Testing");
SleepInSecond(2);
}
if(isElementDisplyed(ageOptionUnder18ButtonBy)) {
clickElement(ageOptionUnder18ButtonBy);
SleepInSecond(2);
}
if (isElementDisplyed(educationTextBoxBy)) {
sendKeyToElement(educationTextBoxBy,"Automation Testing");
SleepInSecond(2);
}
}
@Test
public void TC_02_Verified_Element_Enable_Disable() {
// ENABLED
Assert.assertTrue(isElementEnabled(emailTextBoxBy));
Assert.assertTrue(isElementEnabled(educationTextBoxBy));
Assert.assertTrue(isElementEnabled(ageOptionUnder18ButtonBy));
Assert.assertTrue(isElementEnabled(slider01By));
Assert.assertTrue(isElementEnabled(interestDevelopmentBy));
Assert.assertTrue(isElementEnabled(job1DropdownBy));
// DISABLED
Assert.assertFalse(isElementEnabled(passwordTextBoxBy));
Assert.assertFalse(isElementEnabled(ageRadioButtonDisabledBy));
Assert.assertFalse(isElementEnabled(biographyTextBoxBy));
Assert.assertFalse(isElementEnabled(interestCheckBoxDisabled));
Assert.assertFalse(isElementEnabled(slider02By));
Assert.assertFalse(isElementEnabled(job3DropdownBy));
}
@Test
public void TC_03_Verified_Element_Is_Selected() {
clickElement(ageOptionUnder18ButtonBy);
clickElement(interestDevelopmentBy);
Assert.assertTrue(isElementSelected(ageOptionUnder18ButtonBy));
Assert.assertTrue(isElementSelected(interestDevelopmentBy));
clickElement(interestDevelopmentBy);
Assert.assertFalse(isElementSelected(interestDevelopmentBy));
}
public WebElement find(By by) {
return driver.findElement(by);
}
public void clickElement(By by) {
WebElement element = find(by);
element.click();
}
public void sendKeyToElement(By by, String value) {
WebElement element = find(by);
element.sendKeys(value);
}
public boolean isElementDisplyed(By by) {
WebElement element = find(by);
if (element.isDisplayed()) {
System.out.println("Element with by [" + by +"] is DISPLAYED");
return true;
} else {
System.out.println("Element with by [" +by +"] is NOT DISPLAYED");
return false;
}
}
public boolean isElementEnabled(By by) {
WebElement element = find(by);
if(element.isEnabled()) {
System.out.println("Element with by [" + by +"] is ENABLED");
return true;
} else {
System.out.println("Element with by [" +by +"] is DISABLED");
return false;
}
}
public boolean isElementSelected(By by) {
WebElement element = find(by);
if(element.isSelected()) {
System.out.println("Element with by [" + by +"] is Selected");
return true;
} else {
System.out.println("Element with by [" +by +"] is Not Selected");
return false;
}
}
public void SleepInSecond (long second ) {
try {
Thread.sleep(second * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@AfterClass
public void afterClass() {
driver.close();
}
}
|
Python | UTF-8 | 97,661 | 3.140625 | 3 | [] | no_license | __FILENAME__ = build_html
#!/usr/bin/env python
import markdown
f_in = open('README.md', 'r')
guidelines = "".join(f_in.readlines())
md = markdown.Markdown(safe_mode='escape', extensions=['urlize'])
html = md.convert(guidelines)
html = html.replace('<true_pre>', '<pre>')
html = html.replace('</true_pre>', '</pre>')
f_out = open('guidelines.html', 'w')
f_out.write(html)
########NEW FILE########
__FILENAME__ = blockparser
import util
import odict
class State(list):
""" Track the current and nested state of the parser.
This utility class is used to track the state of the BlockParser and
support multiple levels if nesting. It's just a simple API wrapped around
a list. Each time a state is set, that state is appended to the end of the
list. Each time a state is reset, that state is removed from the end of
the list.
Therefore, each time a state is set for a nested block, that state must be
reset when we back out of that level of nesting or the state could be
corrupted.
While all the methods of a list object are available, only the three
defined below need be used.
"""
def set(self, state):
""" Set a new state. """
self.append(state)
def reset(self):
""" Step back one step in nested state. """
self.pop()
def isstate(self, state):
""" Test that top (current) level is of given state. """
if len(self):
return self[-1] == state
else:
return False
class BlockParser:
""" Parse Markdown blocks into an ElementTree object.
A wrapper class that stitches the various BlockProcessors together,
looping through them and creating an ElementTree object.
"""
def __init__(self, markdown):
self.blockprocessors = odict.OrderedDict()
self.state = State()
self.markdown = markdown
def parseDocument(self, lines):
""" Parse a markdown document into an ElementTree.
Given a list of lines, an ElementTree object (not just a parent Element)
is created and the root element is passed to the parser as the parent.
The ElementTree object is returned.
This should only be called on an entire document, not pieces.
"""
# Create a ElementTree from the lines
self.root = util.etree.Element(self.markdown.doc_tag)
self.parseChunk(self.root, '\n'.join(lines))
return util.etree.ElementTree(self.root)
def parseChunk(self, parent, text):
""" Parse a chunk of markdown text and attach to given etree node.
While the ``text`` argument is generally assumed to contain multiple
blocks which will be split on blank lines, it could contain only one
block. Generally, this method would be called by extensions when
block parsing is required.
The ``parent`` etree Element passed in is altered in place.
Nothing is returned.
"""
self.parseBlocks(parent, text.split('\n\n'))
def parseBlocks(self, parent, blocks):
""" Process blocks of markdown text and attach to given etree node.
Given a list of ``blocks``, each blockprocessor is stepped through
until there are no blocks left. While an extension could potentially
call this method directly, it's generally expected to be used internally.
This is a public method as an extension may need to add/alter additional
BlockProcessors which call this method to recursively parse a nested
block.
"""
while blocks:
for processor in self.blockprocessors.values():
if processor.test(parent, blocks[0]):
processor.run(parent, blocks)
break
########NEW FILE########
__FILENAME__ = blockprocessors
"""
CORE MARKDOWN BLOCKPARSER
=============================================================================
This parser handles basic parsing of Markdown blocks. It doesn't concern itself
with inline elements such as **bold** or *italics*, but rather just catches
blocks, lists, quotes, etc.
The BlockParser is made up of a bunch of BlockProssors, each handling a
different type of block. Extensions may add/replace/remove BlockProcessors
as they need to alter how markdown blocks are parsed.
"""
import logging
import re
import util
from blockparser import BlockParser
logger = logging.getLogger('MARKDOWN')
def build_block_parser(md_instance, **kwargs):
""" Build the default block parser used by Markdown. """
parser = BlockParser(md_instance)
parser.blockprocessors['empty'] = EmptyBlockProcessor(parser)
parser.blockprocessors['indent'] = ListIndentProcessor(parser)
parser.blockprocessors['code'] = CodeBlockProcessor(parser)
parser.blockprocessors['hashheader'] = HashHeaderProcessor(parser)
parser.blockprocessors['setextheader'] = SetextHeaderProcessor(parser)
parser.blockprocessors['hr'] = HRProcessor(parser)
parser.blockprocessors['olist'] = OListProcessor(parser)
parser.blockprocessors['ulist'] = UListProcessor(parser)
parser.blockprocessors['quote'] = BlockQuoteProcessor(parser)
parser.blockprocessors['paragraph'] = ParagraphProcessor(parser)
return parser
class BlockProcessor:
""" Base class for block processors.
Each subclass will provide the methods below to work with the source and
tree. Each processor will need to define it's own ``test`` and ``run``
methods. The ``test`` method should return True or False, to indicate
whether the current block should be processed by this processor. If the
test passes, the parser will call the processors ``run`` method.
"""
def __init__(self, parser):
self.parser = parser
self.tab_length = parser.markdown.tab_length
def lastChild(self, parent):
""" Return the last child of an etree element. """
if len(parent):
return parent[-1]
else:
return None
def detab(self, text):
""" Remove a tab from the front of each line of the given text. """
newtext = []
lines = text.split('\n')
for line in lines:
if line.startswith(' '*self.tab_length):
newtext.append(line[self.tab_length:])
elif not line.strip():
newtext.append('')
else:
break
return '\n'.join(newtext), '\n'.join(lines[len(newtext):])
def looseDetab(self, text, level=1):
""" Remove a tab from front of lines but allowing dedented lines. """
lines = text.split('\n')
for i in range(len(lines)):
if lines[i].startswith(' '*self.tab_length*level):
lines[i] = lines[i][self.tab_length*level:]
return '\n'.join(lines)
def test(self, parent, block):
""" Test for block type. Must be overridden by subclasses.
As the parser loops through processors, it will call the ``test`` method
on each to determine if the given block of text is of that type. This
method must return a boolean ``True`` or ``False``. The actual method of
testing is left to the needs of that particular block type. It could
be as simple as ``block.startswith(some_string)`` or a complex regular
expression. As the block type may be different depending on the parent
of the block (i.e. inside a list), the parent etree element is also
provided and may be used as part of the test.
Keywords:
* ``parent``: A etree element which will be the parent of the block.
* ``block``: A block of text from the source which has been split at
blank lines.
"""
pass
def run(self, parent, blocks):
""" Run processor. Must be overridden by subclasses.
When the parser determines the appropriate type of a block, the parser
will call the corresponding processor's ``run`` method. This method
should parse the individual lines of the block and append them to
the etree.
Note that both the ``parent`` and ``etree`` keywords are pointers
to instances of the objects which should be edited in place. Each
processor must make changes to the existing objects as there is no
mechanism to return new/different objects to replace them.
This means that this method should be adding SubElements or adding text
to the parent, and should remove (``pop``) or add (``insert``) items to
the list of blocks.
Keywords:
* ``parent``: A etree element which is the parent of the current block.
* ``blocks``: A list of all remaining blocks of the document.
"""
pass
class ListIndentProcessor(BlockProcessor):
""" Process children of list items.
Example:
* a list item
process this part
or this part
"""
ITEM_TYPES = ['li']
LIST_TYPES = ['ul', 'ol']
def __init__(self, *args):
BlockProcessor.__init__(self, *args)
self.INDENT_RE = re.compile(r'^(([ ]{%s})+)'% self.tab_length)
def test(self, parent, block):
return block.startswith(' '*self.tab_length) and \
not self.parser.state.isstate('detabbed') and \
(parent.tag in self.ITEM_TYPES or \
(len(parent) and parent[-1] and \
(parent[-1].tag in self.LIST_TYPES)
)
)
def run(self, parent, blocks):
block = blocks.pop(0)
level, sibling = self.get_level(parent, block)
block = self.looseDetab(block, level)
self.parser.state.set('detabbed')
if parent.tag in self.ITEM_TYPES:
# It's possible that this parent has a 'ul' or 'ol' child list
# with a member. If that is the case, then that should be the
# parent. This is intended to catch the edge case of an indented
# list whose first member was parsed previous to this point
# see OListProcessor
if len(parent) and parent[-1].tag in self.LIST_TYPES:
self.parser.parseBlocks(parent[-1], [block])
else:
# The parent is already a li. Just parse the child block.
self.parser.parseBlocks(parent, [block])
elif sibling.tag in self.ITEM_TYPES:
# The sibling is a li. Use it as parent.
self.parser.parseBlocks(sibling, [block])
elif len(sibling) and sibling[-1].tag in self.ITEM_TYPES:
# The parent is a list (``ol`` or ``ul``) which has children.
# Assume the last child li is the parent of this block.
if sibling[-1].text:
# If the parent li has text, that text needs to be moved to a p
# The p must be 'inserted' at beginning of list in the event
# that other children already exist i.e.; a nested sublist.
p = util.etree.Element('p')
p.text = sibling[-1].text
sibling[-1].text = ''
sibling[-1].insert(0, p)
self.parser.parseChunk(sibling[-1], block)
else:
self.create_item(sibling, block)
self.parser.state.reset()
def create_item(self, parent, block):
""" Create a new li and parse the block with it as the parent. """
li = util.etree.SubElement(parent, 'li')
self.parser.parseBlocks(li, [block])
def get_level(self, parent, block):
""" Get level of indent based on list level. """
# Get indent level
m = self.INDENT_RE.match(block)
if m:
indent_level = len(m.group(1))/self.tab_length
else:
indent_level = 0
if self.parser.state.isstate('list'):
# We're in a tightlist - so we already are at correct parent.
level = 1
else:
# We're in a looselist - so we need to find parent.
level = 0
# Step through children of tree to find matching indent level.
while indent_level > level:
child = self.lastChild(parent)
if child and (child.tag in self.LIST_TYPES or child.tag in self.ITEM_TYPES):
if child.tag in self.LIST_TYPES:
level += 1
parent = child
else:
# No more child levels. If we're short of indent_level,
# we have a code block. So we stop here.
break
return level, parent
class CodeBlockProcessor(BlockProcessor):
""" Process code blocks. """
def test(self, parent, block):
return block.startswith(' '*self.tab_length)
def run(self, parent, blocks):
sibling = self.lastChild(parent)
block = blocks.pop(0)
theRest = ''
if sibling and sibling.tag == "pre" and len(sibling) \
and sibling[0].tag == "code":
# The previous block was a code block. As blank lines do not start
# new code blocks, append this block to the previous, adding back
# linebreaks removed from the split into a list.
code = sibling[0]
block, theRest = self.detab(block)
code.text = util.AtomicString('%s\n%s\n' % (code.text, block.rstrip()))
else:
# This is a new codeblock. Create the elements and insert text.
pre = util.etree.SubElement(parent, 'pre')
code = util.etree.SubElement(pre, 'code')
block, theRest = self.detab(block)
code.text = util.AtomicString('%s\n' % block.rstrip())
if theRest:
# This block contained unindented line(s) after the first indented
# line. Insert these lines as the first block of the master blocks
# list for future processing.
blocks.insert(0, theRest)
class BlockQuoteProcessor(BlockProcessor):
RE = re.compile(r'(^|\n)[ ]{0,3}>[ ]?(.*)')
def test(self, parent, block):
return bool(self.RE.search(block))
def run(self, parent, blocks):
block = blocks.pop(0)
m = self.RE.search(block)
if m:
before = block[:m.start()] # Lines before blockquote
# Pass lines before blockquote in recursively for parsing forst.
self.parser.parseBlocks(parent, [before])
# Remove ``> `` from begining of each line.
block = '\n'.join([self.clean(line) for line in
block[m.start():].split('\n')])
sibling = self.lastChild(parent)
if sibling and sibling.tag == "blockquote":
# Previous block was a blockquote so set that as this blocks parent
quote = sibling
else:
# This is a new blockquote. Create a new parent element.
quote = util.etree.SubElement(parent, 'blockquote')
# Recursively parse block with blockquote as parent.
# change parser state so blockquotes embedded in lists use p tags
self.parser.state.set('blockquote')
self.parser.parseChunk(quote, block)
self.parser.state.reset()
def clean(self, line):
""" Remove ``>`` from beginning of a line. """
m = self.RE.match(line)
if line.strip() == ">":
return ""
elif m:
return m.group(2)
else:
return line
class OListProcessor(BlockProcessor):
""" Process ordered list blocks. """
TAG = 'ol'
# Detect an item (``1. item``). ``group(1)`` contains contents of item.
RE = re.compile(r'^[ ]{0,3}\d+\.[ ]+(.*)')
# Detect items on secondary lines. they can be of either list type.
CHILD_RE = re.compile(r'^[ ]{0,3}((\d+\.)|[*+-])[ ]+(.*)')
# Detect indented (nested) items of either type
INDENT_RE = re.compile(r'^[ ]{4,7}((\d+\.)|[*+-])[ ]+.*')
# The integer (python string) with which the lists starts (default=1)
# Eg: If list is intialized as)
# 3. Item
# The ol tag will get starts="3" attribute
STARTSWITH = '1'
def test(self, parent, block):
return bool(self.RE.match(block))
def run(self, parent, blocks):
# Check fr multiple items in one block.
items = self.get_items(blocks.pop(0))
sibling = self.lastChild(parent)
if sibling and sibling.tag in ['ol', 'ul']:
# Previous block was a list item, so set that as parent
lst = sibling
# make sure previous item is in a p- if the item has text, then it
# it isn't in a p
if lst[-1].text:
# since it's possible there are other children for this sibling,
# we can't just SubElement the p, we need to insert it as the
# first item
p = util.etree.Element('p')
p.text = lst[-1].text
lst[-1].text = ''
lst[-1].insert(0, p)
# if the last item has a tail, then the tail needs to be put in a p
# likely only when a header is not followed by a blank line
lch = self.lastChild(lst[-1])
if lch is not None and lch.tail:
p = util.etree.SubElement(lst[-1], 'p')
p.text = lch.tail.lstrip()
lch.tail = ''
# parse first block differently as it gets wrapped in a p.
li = util.etree.SubElement(lst, 'li')
self.parser.state.set('looselist')
firstitem = items.pop(0)
self.parser.parseBlocks(li, [firstitem])
self.parser.state.reset()
elif parent.tag in ['ol', 'ul']:
# this catches the edge case of a multi-item indented list whose
# first item is in a blank parent-list item:
# * * subitem1
# * subitem2
# see also ListIndentProcessor
lst = parent
else:
# This is a new list so create parent with appropriate tag.
lst = util.etree.SubElement(parent, self.TAG)
# Check if a custom start integer is set
if not self.parser.markdown.lazy_ol and self.STARTSWITH !='1':
lst.attrib['start'] = self.STARTSWITH
self.parser.state.set('list')
# Loop through items in block, recursively parsing each with the
# appropriate parent.
for item in items:
if item.startswith(' '*self.tab_length):
# Item is indented. Parse with last item as parent
self.parser.parseBlocks(lst[-1], [item])
else:
# New item. Create li and parse with it as parent
li = util.etree.SubElement(lst, 'li')
self.parser.parseBlocks(li, [item])
self.parser.state.reset()
def get_items(self, block):
""" Break a block into list items. """
items = []
for line in block.split('\n'):
m = self.CHILD_RE.match(line)
if m:
# This is a new list item
# Check first item for the start index
if not items and self.TAG=='ol':
# Detect the integer value of first list item
INTEGER_RE = re.compile('(\d+)')
self.STARTSWITH = INTEGER_RE.match(m.group(1)).group()
# Append to the list
items.append(m.group(3))
elif self.INDENT_RE.match(line):
# This is an indented (possibly nested) item.
if items[-1].startswith(' '*self.tab_length):
# Previous item was indented. Append to that item.
items[-1] = '%s\n%s' % (items[-1], line)
else:
items.append(line)
else:
# This is another line of previous item. Append to that item.
items[-1] = '%s\n%s' % (items[-1], line)
return items
class UListProcessor(OListProcessor):
""" Process unordered list blocks. """
TAG = 'ul'
RE = re.compile(r'^[ ]{0,3}[*+-][ ]+(.*)')
class HashHeaderProcessor(BlockProcessor):
""" Process Hash Headers. """
# Detect a header at start of any line in block
RE = re.compile(r'(^|\n)(?P<level>#{1,6})(?P<header>.*?)#*(\n|$)')
def test(self, parent, block):
return bool(self.RE.search(block))
def run(self, parent, blocks):
block = blocks.pop(0)
m = self.RE.search(block)
if m:
before = block[:m.start()] # All lines before header
after = block[m.end():] # All lines after header
if before:
# As the header was not the first line of the block and the
# lines before the header must be parsed first,
# recursively parse this lines as a block.
self.parser.parseBlocks(parent, [before])
# Create header using named groups from RE
h = util.etree.SubElement(parent, 'h%d' % len(m.group('level')))
h.text = m.group('header').strip()
if after:
# Insert remaining lines as first block for future parsing.
blocks.insert(0, after)
else:
# This should never happen, but just in case...
logger.warn("We've got a problem header: %r" % block)
class SetextHeaderProcessor(BlockProcessor):
""" Process Setext-style Headers. """
# Detect Setext-style header. Must be first 2 lines of block.
RE = re.compile(r'^.*?\n[=-]+[ ]*(\n|$)', re.MULTILINE)
def test(self, parent, block):
return bool(self.RE.match(block))
def run(self, parent, blocks):
lines = blocks.pop(0).split('\n')
# Determine level. ``=`` is 1 and ``-`` is 2.
if lines[1].startswith('='):
level = 1
else:
level = 2
h = util.etree.SubElement(parent, 'h%d' % level)
h.text = lines[0].strip()
if len(lines) > 2:
# Block contains additional lines. Add to master blocks for later.
blocks.insert(0, '\n'.join(lines[2:]))
class HRProcessor(BlockProcessor):
""" Process Horizontal Rules. """
RE = r'^[ ]{0,3}((-+[ ]{0,2}){3,}|(_+[ ]{0,2}){3,}|(\*+[ ]{0,2}){3,})[ ]*'
# Detect hr on any line of a block.
SEARCH_RE = re.compile(RE, re.MULTILINE)
def test(self, parent, block):
m = self.SEARCH_RE.search(block)
# No atomic grouping in python so we simulate it here for performance.
# The regex only matches what would be in the atomic group - the HR.
# Then check if we are at end of block or if next char is a newline.
if m and (m.end() == len(block) or block[m.end()] == '\n'):
# Save match object on class instance so we can use it later.
self.match = m
return True
return False
def run(self, parent, blocks):
block = blocks.pop(0)
# Check for lines in block before hr.
prelines = block[:self.match.start()].rstrip('\n')
if prelines:
# Recursively parse lines before hr so they get parsed first.
self.parser.parseBlocks(parent, [prelines])
# create hr
hr = util.etree.SubElement(parent, 'hr')
# check for lines in block after hr.
postlines = block[self.match.end():].lstrip('\n')
if postlines:
# Add lines after hr to master blocks for later parsing.
blocks.insert(0, postlines)
class EmptyBlockProcessor(BlockProcessor):
""" Process blocks and start with an empty line. """
# Detect a block that only contains whitespace
# or only whitespace on the first line.
RE = re.compile(r'^\s*\n')
def test(self, parent, block):
return bool(self.RE.match(block))
def run(self, parent, blocks):
block = blocks.pop(0)
m = self.RE.match(block)
if m:
# Add remaining line to master blocks for later.
blocks.insert(0, block[m.end():])
sibling = self.lastChild(parent)
if sibling and sibling.tag == 'pre' and sibling[0] and \
sibling[0].tag == 'code':
# Last block is a codeblock. Append to preserve whitespace.
sibling[0].text = util.AtomicString('%s/n/n/n' % sibling[0].text )
class ParagraphProcessor(BlockProcessor):
""" Process Paragraph blocks. """
def test(self, parent, block):
return True
def run(self, parent, blocks):
block = blocks.pop(0)
if block.strip():
# Not a blank block. Add to parent, otherwise throw it away.
if self.parser.state.isstate('list'):
# The parent is a tight-list.
#
# Check for any children. This will likely only happen in a
# tight-list when a header isn't followed by a blank line.
# For example:
#
# * # Header
# Line 2 of list item - not part of header.
sibling = self.lastChild(parent)
if sibling is not None:
# Insetrt after sibling.
if sibling.tail:
sibling.tail = '%s\n%s' % (sibling.tail, block)
else:
sibling.tail = '\n%s' % block
else:
# Append to parent.text
if parent.text:
parent.text = '%s\n%s' % (parent.text, block)
else:
parent.text = block.lstrip()
else:
# Create a regular paragraph
p = util.etree.SubElement(parent, 'p')
p.text = block.lstrip()
########NEW FILE########
__FILENAME__ = etree_loader
## Import
def importETree():
"""Import the best implementation of ElementTree, return a module object."""
etree_in_c = None
try: # Is it Python 2.5+ with C implemenation of ElementTree installed?
import xml.etree.cElementTree as etree_in_c
from xml.etree.ElementTree import Comment
except ImportError:
try: # Is it Python 2.5+ with Python implementation of ElementTree?
import xml.etree.ElementTree as etree
except ImportError:
try: # An earlier version of Python with cElementTree installed?
import cElementTree as etree_in_c
from elementtree.ElementTree import Comment
except ImportError:
try: # An earlier version of Python with Python ElementTree?
import elementtree.ElementTree as etree
except ImportError:
raise ImportError("Failed to import ElementTree")
if etree_in_c:
if etree_in_c.VERSION < "1.0.5":
raise RuntimeError("cElementTree version 1.0.5 or higher is required.")
# Third party serializers (including ours) test with non-c Comment
etree_in_c.test_comment = Comment
return etree_in_c
elif etree.VERSION < "1.1":
raise RuntimeError("ElementTree version 1.1 or higher is required")
else:
return etree
########NEW FILE########
__FILENAME__ = urlize
"""A more liberal autolinker
Inspired by Django's urlize function.
Positive examples:
>>> import markdown
>>> md = markdown.Markdown(extensions=['urlize'])
>>> md.convert('http://example.com/')
u'<p><a href="http://example.com/">http://example.com/</a></p>'
>>> md.convert('go to http://example.com')
u'<p>go to <a href="http://example.com">http://example.com</a></p>'
>>> md.convert('example.com')
u'<p><a href="http://example.com">example.com</a></p>'
>>> md.convert('example.net')
u'<p><a href="http://example.net">example.net</a></p>'
>>> md.convert('www.example.us')
u'<p><a href="http://www.example.us">www.example.us</a></p>'
>>> md.convert('(www.example.us/path/?name=val)')
u'<p>(<a href="http://www.example.us/path/?name=val">www.example.us/path/?name=val</a>)</p>'
>>> md.convert('go to <http://example.com> now!')
u'<p>go to <a href="http://example.com">http://example.com</a> now!</p>'
Negative examples:
>>> md.convert('del.icio.us')
u'<p>del.icio.us</p>'
"""
import markdown
# Global Vars
URLIZE_RE = '(%s)' % '|'.join([
r'<(?:f|ht)tps?://[^>]*>',
r'\b(?:f|ht)tps?://[^)<>\s]+[^.,)<>\s]',
r'\bwww\.[^)<>\s]+[^.,)<>\s]',
# r'[^(<\s]+\.(?:com|net|org)\b',
])
class UrlizePattern(markdown.inlinepatterns.Pattern):
""" Return a link Element given an autolink (`http://example/com`). """
def handleMatch(self, m):
url = m.group(2)
if url.startswith('<'):
url = url[1:-1]
text = url
if not url.split('://')[0] in ('http','https','ftp'):
if '@' in url and not '/' in url:
url = 'mailto:' + url
else:
url = 'http://' + url
el = markdown.util.etree.Element("a")
el.set('href', url)
el.text = markdown.util.AtomicString(text)
return el
class UrlizeExtension(markdown.Extension):
""" Urlize Extension for Python-Markdown. """
def extendMarkdown(self, md, md_globals):
""" Replace autolink with UrlizePattern """
md.inlinePatterns['autolink'] = UrlizePattern(URLIZE_RE, md)
def makeExtension(configs=None):
return UrlizeExtension(configs=configs)
if __name__ == "__main__":
import doctest
doctest.testmod()
########NEW FILE########
__FILENAME__ = inlinepatterns
"""
INLINE PATTERNS
=============================================================================
Inline patterns such as *emphasis* are handled by means of auxiliary
objects, one per pattern. Pattern objects must be instances of classes
that extend markdown.Pattern. Each pattern object uses a single regular
expression and needs support the following methods:
pattern.getCompiledRegExp() # returns a regular expression
pattern.handleMatch(m) # takes a match object and returns
# an ElementTree element or just plain text
All of python markdown's built-in patterns subclass from Pattern,
but you can add additional patterns that don't.
Also note that all the regular expressions used by inline must
capture the whole block. For this reason, they all start with
'^(.*)' and end with '(.*)!'. In case with built-in expression
Pattern takes care of adding the "^(.*)" and "(.*)!".
Finally, the order in which regular expressions are applied is very
important - e.g. if we first replace http://.../ links with <a> tags
and _then_ try to replace inline html, we would end up with a mess.
So, we apply the expressions in the following order:
* escape and backticks have to go before everything else, so
that we can preempt any markdown patterns by escaping them.
* then we handle auto-links (must be done before inline html)
* then we handle inline HTML. At this point we will simply
replace all inline HTML strings with a placeholder and add
the actual HTML to a hash.
* then inline images (must be done before links)
* then bracketed links, first regular then reference-style
* finally we apply strong and emphasis
"""
import util
import odict
import re
from urlparse import urlparse, urlunparse
import sys
# If you see an ImportError for htmlentitydefs after using 2to3 to convert for
# use by Python3, then you are probably using the buggy version from Python 3.0.
# We recomend using the tool from Python 3.1 even if you will be running the
# code on Python 3.0. The following line should be converted by the tool to:
# `from html import entities` and later calls to `htmlentitydefs` should be
# changed to call `entities`. Python 3.1's tool does this but 3.0's does not.
import htmlentitydefs
def build_inlinepatterns(md_instance, **kwargs):
""" Build the default set of inline patterns for Markdown. """
inlinePatterns = odict.OrderedDict()
inlinePatterns["backtick"] = BacktickPattern(BACKTICK_RE)
inlinePatterns["escape"] = EscapePattern(ESCAPE_RE, md_instance)
inlinePatterns["reference"] = ReferencePattern(REFERENCE_RE, md_instance)
inlinePatterns["link"] = LinkPattern(LINK_RE, md_instance)
inlinePatterns["image_link"] = ImagePattern(IMAGE_LINK_RE, md_instance)
inlinePatterns["image_reference"] = \
ImageReferencePattern(IMAGE_REFERENCE_RE, md_instance)
inlinePatterns["short_reference"] = \
ReferencePattern(SHORT_REF_RE, md_instance)
inlinePatterns["autolink"] = AutolinkPattern(AUTOLINK_RE, md_instance)
inlinePatterns["automail"] = AutomailPattern(AUTOMAIL_RE, md_instance)
inlinePatterns["linebreak2"] = SubstituteTagPattern(LINE_BREAK_2_RE, 'br')
inlinePatterns["linebreak"] = SubstituteTagPattern(LINE_BREAK_RE, 'br')
if md_instance.safeMode != 'escape':
inlinePatterns["html"] = HtmlPattern(HTML_RE, md_instance)
inlinePatterns["entity"] = HtmlPattern(ENTITY_RE, md_instance)
inlinePatterns["not_strong"] = SimpleTextPattern(NOT_STRONG_RE)
inlinePatterns["strong_em"] = DoubleTagPattern(STRONG_EM_RE, 'strong,em')
inlinePatterns["strong"] = SimpleTagPattern(STRONG_RE, 'strong')
inlinePatterns["emphasis"] = SimpleTagPattern(EMPHASIS_RE, 'em')
if md_instance.smart_emphasis:
inlinePatterns["emphasis2"] = SimpleTagPattern(SMART_EMPHASIS_RE, 'em')
else:
inlinePatterns["emphasis2"] = SimpleTagPattern(EMPHASIS_2_RE, 'em')
return inlinePatterns
"""
The actual regular expressions for patterns
-----------------------------------------------------------------------------
"""
NOBRACKET = r'[^\]\[]*'
BRK = ( r'\[('
+ (NOBRACKET + r'(\[')*6
+ (NOBRACKET+ r'\])*')*6
+ NOBRACKET + r')\]' )
NOIMG = r'(?<!\!)'
BACKTICK_RE = r'(?<!\\)(`+)(.+?)(?<!`)\2(?!`)' # `e=f()` or ``e=f("`")``
ESCAPE_RE = r'\\(.)' # \<
EMPHASIS_RE = r'(\*)([^\*]+)\2' # *emphasis*
STRONG_RE = r'(\*{2}|_{2})(.+?)\2' # **strong**
STRONG_EM_RE = r'(\*{3}|_{3})(.+?)\2' # ***strong***
SMART_EMPHASIS_RE = r'(?<!\w)(_)(?!_)(.+?)(?<!_)\2(?!\w)' # _smart_emphasis_
EMPHASIS_2_RE = r'(_)(.+?)\2' # _emphasis_
LINK_RE = NOIMG + BRK + \
r'''\(\s*(<.*?>|((?:(?:\(.*?\))|[^\(\)]))*?)\s*((['"])(.*?)\12\s*)?\)'''
# [text](url) or [text](<url>) or [text](url "title")
IMAGE_LINK_RE = r'\!' + BRK + r'\s*\((<.*?>|([^\)]*))\)'
#  or 
REFERENCE_RE = NOIMG + BRK+ r'\s?\[([^\]]*)\]' # [Google][3]
SHORT_REF_RE = NOIMG + r'\[([^\]]+)\]' # [Google]
IMAGE_REFERENCE_RE = r'\!' + BRK + '\s?\[([^\]]*)\]' # ![alt text][2]
NOT_STRONG_RE = r'((^| )(\*|_)( |$))' # stand-alone * or _
AUTOLINK_RE = r'<((?:[Ff]|[Hh][Tt])[Tt][Pp][Ss]?://[^>]*)>' # <http://www.123.com>
AUTOMAIL_RE = r'<([^> \!]*@[^> ]*)>' # <me@example.com>
HTML_RE = r'(\<([a-zA-Z/][^\>]*?|\!--.*?--)\>)' # <...>
ENTITY_RE = r'(&[\#a-zA-Z0-9]*;)' # &
LINE_BREAK_RE = r' \n' # two spaces at end of line
LINE_BREAK_2_RE = r' $' # two spaces at end of text
def dequote(string):
"""Remove quotes from around a string."""
if ( ( string.startswith('"') and string.endswith('"'))
or (string.startswith("'") and string.endswith("'")) ):
return string[1:-1]
else:
return string
ATTR_RE = re.compile("\{@([^\}]*)=([^\}]*)}") # {@id=123}
def handleAttributes(text, parent):
"""Set values of an element based on attribute definitions ({@id=123})."""
def attributeCallback(match):
parent.set(match.group(1), match.group(2).replace('\n', ' '))
return ATTR_RE.sub(attributeCallback, text)
"""
The pattern classes
-----------------------------------------------------------------------------
"""
class Pattern:
"""Base class that inline patterns subclass. """
def __init__(self, pattern, markdown_instance=None):
"""
Create an instant of an inline pattern.
Keyword arguments:
* pattern: A regular expression that matches a pattern
"""
self.pattern = pattern
self.compiled_re = re.compile("^(.*?)%s(.*?)$" % pattern,
re.DOTALL | re.UNICODE)
# Api for Markdown to pass safe_mode into instance
self.safe_mode = False
if markdown_instance:
self.markdown = markdown_instance
def getCompiledRegExp(self):
""" Return a compiled regular expression. """
return self.compiled_re
def handleMatch(self, m):
"""Return a ElementTree element from the given match.
Subclasses should override this method.
Keyword arguments:
* m: A re match object containing a match of the pattern.
"""
pass
def type(self):
""" Return class name, to define pattern type """
return self.__class__.__name__
def unescape(self, text):
""" Return unescaped text given text with an inline placeholder. """
try:
stash = self.markdown.treeprocessors['inline'].stashed_nodes
except KeyError:
return text
def get_stash(m):
id = m.group(1)
if id in stash:
return stash.get(id)
return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
class SimpleTextPattern(Pattern):
""" Return a simple text of group(2) of a Pattern. """
def handleMatch(self, m):
text = m.group(2)
if text == util.INLINE_PLACEHOLDER_PREFIX:
return None
return text
class EscapePattern(Pattern):
""" Return an escaped character. """
def handleMatch(self, m):
char = m.group(2)
if char in self.markdown.ESCAPED_CHARS:
return '%s%s%s' % (util.STX, ord(char), util.ETX)
else:
return '\\%s' % char
class SimpleTagPattern(Pattern):
"""
Return element of type `tag` with a text attribute of group(3)
of a Pattern.
"""
def __init__ (self, pattern, tag):
Pattern.__init__(self, pattern)
self.tag = tag
def handleMatch(self, m):
el = util.etree.Element(self.tag)
el.text = m.group(3)
return el
class SubstituteTagPattern(SimpleTagPattern):
""" Return a eLement of type `tag` with no children. """
def handleMatch (self, m):
return util.etree.Element(self.tag)
class BacktickPattern(Pattern):
""" Return a `<code>` element containing the matching text. """
def __init__ (self, pattern):
Pattern.__init__(self, pattern)
self.tag = "code"
def handleMatch(self, m):
el = util.etree.Element(self.tag)
el.text = util.AtomicString(m.group(3).strip())
return el
class DoubleTagPattern(SimpleTagPattern):
"""Return a ElementTree element nested in tag2 nested in tag1.
Useful for strong emphasis etc.
"""
def handleMatch(self, m):
tag1, tag2 = self.tag.split(",")
el1 = util.etree.Element(tag1)
el2 = util.etree.SubElement(el1, tag2)
el2.text = m.group(3)
return el1
class HtmlPattern(Pattern):
""" Store raw inline html and return a placeholder. """
def handleMatch (self, m):
rawhtml = self.unescape(m.group(2))
place_holder = self.markdown.htmlStash.store(rawhtml)
return place_holder
def unescape(self, text):
""" Return unescaped text given text with an inline placeholder. """
try:
stash = self.markdown.treeprocessors['inline'].stashed_nodes
except KeyError:
return text
def get_stash(m):
id = m.group(1)
value = stash.get(id)
if value is not None:
try:
return self.markdown.serializer(value)
except:
return '\%s' % value
return util.INLINE_PLACEHOLDER_RE.sub(get_stash, text)
class LinkPattern(Pattern):
""" Return a link element from the given match. """
def handleMatch(self, m):
el = util.etree.Element("a")
el.text = m.group(2)
title = m.group(13)
href = m.group(9)
if href:
if href[0] == "<":
href = href[1:-1]
el.set("href", self.sanitize_url(self.unescape(href.strip())))
else:
el.set("href", "")
if title:
title = dequote(self.unescape(title))
el.set("title", title)
return el
def sanitize_url(self, url):
"""
Sanitize a url against xss attacks in "safe_mode".
Rather than specifically blacklisting `javascript:alert("XSS")` and all
its aliases (see <http://ha.ckers.org/xss.html>), we whitelist known
safe url formats. Most urls contain a network location, however some
are known not to (i.e.: mailto links). Script urls do not contain a
location. Additionally, for `javascript:...`, the scheme would be
"javascript" but some aliases will appear to `urlparse()` to have no
scheme. On top of that relative links (i.e.: "foo/bar.html") have no
scheme. Therefore we must check "path", "parameters", "query" and
"fragment" for any literal colons. We don't check "scheme" for colons
because it *should* never have any and "netloc" must allow the form:
`username:password@host:port`.
"""
if not self.markdown.safeMode:
# Return immediately bipassing parsing.
return url
try:
scheme, netloc, path, params, query, fragment = url = urlparse(url)
except ValueError:
# Bad url - so bad it couldn't be parsed.
return ''
locless_schemes = ['', 'mailto', 'news']
if netloc == '' and scheme not in locless_schemes:
# This fails regardless of anything else.
# Return immediately to save additional proccessing
return ''
for part in url[2:]:
if ":" in part:
# Not a safe url
return ''
# Url passes all tests. Return url as-is.
return urlunparse(url)
class ImagePattern(LinkPattern):
""" Return a img element from the given match. """
def handleMatch(self, m):
el = util.etree.Element("img")
src_parts = m.group(9).split()
if src_parts:
src = src_parts[0]
if src[0] == "<" and src[-1] == ">":
src = src[1:-1]
el.set('src', self.sanitize_url(self.unescape(src)))
else:
el.set('src', "")
if len(src_parts) > 1:
el.set('title', dequote(self.unescape(" ".join(src_parts[1:]))))
if self.markdown.enable_attributes:
truealt = handleAttributes(m.group(2), el)
else:
truealt = m.group(2)
el.set('alt', truealt)
return el
class ReferencePattern(LinkPattern):
""" Match to a stored reference and return link element. """
NEWLINE_CLEANUP_RE = re.compile(r'[ ]?\n', re.MULTILINE)
def handleMatch(self, m):
try:
id = m.group(9).lower()
except IndexError:
id = None
if not id:
# if we got something like "[Google][]" or "[Goggle]"
# we'll use "google" as the id
id = m.group(2).lower()
# Clean up linebreaks in id
id = self.NEWLINE_CLEANUP_RE.sub(' ', id)
if not id in self.markdown.references: # ignore undefined refs
return None
href, title = self.markdown.references[id]
text = m.group(2)
return self.makeTag(href, title, text)
def makeTag(self, href, title, text):
el = util.etree.Element('a')
el.set('href', self.sanitize_url(href))
if title:
el.set('title', title)
el.text = text
return el
class ImageReferencePattern(ReferencePattern):
""" Match to a stored reference and return img element. """
def makeTag(self, href, title, text):
el = util.etree.Element("img")
el.set("src", self.sanitize_url(href))
if title:
el.set("title", title)
el.set("alt", text)
return el
class AutolinkPattern(Pattern):
""" Return a link Element given an autolink (`<http://example/com>`). """
def handleMatch(self, m):
el = util.etree.Element("a")
el.set('href', self.unescape(m.group(2)))
el.text = util.AtomicString(m.group(2))
return el
class AutomailPattern(Pattern):
"""
Return a mailto link Element given an automail link (`<foo@example.com>`).
"""
def handleMatch(self, m):
el = util.etree.Element('a')
email = self.unescape(m.group(2))
if email.startswith("mailto:"):
email = email[len("mailto:"):]
def codepoint2name(code):
"""Return entity definition by code, or the code if not defined."""
entity = htmlentitydefs.codepoint2name.get(code)
if entity:
return "%s%s;" % (util.AMP_SUBSTITUTE, entity)
else:
return "%s#%d;" % (util.AMP_SUBSTITUTE, code)
letters = [codepoint2name(ord(letter)) for letter in email]
el.text = util.AtomicString(''.join(letters))
mailto = "mailto:" + email
mailto = "".join([util.AMP_SUBSTITUTE + '#%d;' %
ord(letter) for letter in mailto])
el.set('href', mailto)
return el
########NEW FILE########
__FILENAME__ = odict
class OrderedDict(dict):
"""
A dictionary that keeps its keys in the order in which they're inserted.
Copied from Django's SortedDict with some modifications.
"""
def __new__(cls, *args, **kwargs):
instance = super(OrderedDict, cls).__new__(cls, *args, **kwargs)
instance.keyOrder = []
return instance
def __init__(self, data=None):
if data is None:
data = {}
super(OrderedDict, self).__init__(data)
if isinstance(data, dict):
self.keyOrder = data.keys()
else:
self.keyOrder = []
for key, value in data:
if key not in self.keyOrder:
self.keyOrder.append(key)
def __deepcopy__(self, memo):
from copy import deepcopy
return self.__class__([(key, deepcopy(value, memo))
for key, value in self.iteritems()])
def __setitem__(self, key, value):
super(OrderedDict, self).__setitem__(key, value)
if key not in self.keyOrder:
self.keyOrder.append(key)
def __delitem__(self, key):
super(OrderedDict, self).__delitem__(key)
self.keyOrder.remove(key)
def __iter__(self):
for k in self.keyOrder:
yield k
def pop(self, k, *args):
result = super(OrderedDict, self).pop(k, *args)
try:
self.keyOrder.remove(k)
except ValueError:
# Key wasn't in the dictionary in the first place. No problem.
pass
return result
def popitem(self):
result = super(OrderedDict, self).popitem()
self.keyOrder.remove(result[0])
return result
def items(self):
return zip(self.keyOrder, self.values())
def iteritems(self):
for key in self.keyOrder:
yield key, super(OrderedDict, self).__getitem__(key)
def keys(self):
return self.keyOrder[:]
def iterkeys(self):
return iter(self.keyOrder)
def values(self):
return [super(OrderedDict, self).__getitem__(k) for k in self.keyOrder]
def itervalues(self):
for key in self.keyOrder:
yield super(OrderedDict, self).__getitem__(key)
def update(self, dict_):
for k, v in dict_.items():
self.__setitem__(k, v)
def setdefault(self, key, default):
if key not in self.keyOrder:
self.keyOrder.append(key)
return super(OrderedDict, self).setdefault(key, default)
def value_for_index(self, index):
"""Return the value of the item at the given zero-based index."""
return self[self.keyOrder[index]]
def insert(self, index, key, value):
"""Insert the key, value pair before the item with the given index."""
if key in self.keyOrder:
n = self.keyOrder.index(key)
del self.keyOrder[n]
if n < index:
index -= 1
self.keyOrder.insert(index, key)
super(OrderedDict, self).__setitem__(key, value)
def copy(self):
"""Return a copy of this object."""
# This way of initializing the copy means it works for subclasses, too.
obj = self.__class__(self)
obj.keyOrder = self.keyOrder[:]
return obj
def __repr__(self):
"""
Replace the normal dict.__repr__ with a version that returns the keys
in their sorted order.
"""
return '{%s}' % ', '.join(['%r: %r' % (k, v) for k, v in self.items()])
def clear(self):
super(OrderedDict, self).clear()
self.keyOrder = []
def index(self, key):
""" Return the index of a given key. """
return self.keyOrder.index(key)
def index_for_location(self, location):
""" Return index or None for a given location. """
if location == '_begin':
i = 0
elif location == '_end':
i = None
elif location.startswith('<') or location.startswith('>'):
i = self.index(location[1:])
if location.startswith('>'):
if i >= len(self):
# last item
i = None
else:
i += 1
else:
raise ValueError('Not a valid location: "%s". Location key '
'must start with a ">" or "<".' % location)
return i
def add(self, key, value, location):
""" Insert by key location. """
i = self.index_for_location(location)
if i is not None:
self.insert(i, key, value)
else:
self.__setitem__(key, value)
def link(self, key, location):
""" Change location of an existing item. """
n = self.keyOrder.index(key)
del self.keyOrder[n]
i = self.index_for_location(location)
try:
if i is not None:
self.keyOrder.insert(i, key)
else:
self.keyOrder.append(key)
except Error:
# restore to prevent data loss and reraise
self.keyOrder.insert(n, key)
raise Error
########NEW FILE########
__FILENAME__ = postprocessors
"""
POST-PROCESSORS
=============================================================================
Markdown also allows post-processors, which are similar to preprocessors in
that they need to implement a "run" method. However, they are run after core
processing.
"""
import re
import util
import odict
def build_postprocessors(md_instance, **kwargs):
""" Build the default postprocessors for Markdown. """
postprocessors = odict.OrderedDict()
postprocessors["raw_html"] = RawHtmlPostprocessor(md_instance)
postprocessors["amp_substitute"] = AndSubstitutePostprocessor()
postprocessors["unescape"] = UnescapePostprocessor()
return postprocessors
class Postprocessor(util.Processor):
"""
Postprocessors are run after the ElementTree it converted back into text.
Each Postprocessor implements a "run" method that takes a pointer to a
text string, modifies it as necessary and returns a text string.
Postprocessors must extend markdown.Postprocessor.
"""
def run(self, text):
"""
Subclasses of Postprocessor should implement a `run` method, which
takes the html document as a single text string and returns a
(possibly modified) string.
"""
pass
class RawHtmlPostprocessor(Postprocessor):
""" Restore raw html to the document. """
def run(self, text):
""" Iterate over html stash and restore "safe" html. """
for i in range(self.markdown.htmlStash.html_counter):
html, safe = self.markdown.htmlStash.rawHtmlBlocks[i]
if self.markdown.safeMode and not safe:
if str(self.markdown.safeMode).lower() == 'escape':
html = self.escape(html)
elif str(self.markdown.safeMode).lower() == 'remove':
html = ''
else:
html = self.markdown.html_replacement_text
if self.isblocklevel(html) and (safe or not self.markdown.safeMode):
text = text.replace("<p>%s</p>" %
(self.markdown.htmlStash.get_placeholder(i)),
html + "\n")
text = text.replace(self.markdown.htmlStash.get_placeholder(i),
html)
return text
def escape(self, html):
""" Basic html escaping """
html = html.replace('&', '&')
html = html.replace('<', '<')
html = html.replace('>', '>')
return html.replace('"', '"')
def isblocklevel(self, html):
m = re.match(r'^\<\/?([^ ]+)', html)
if m:
if m.group(1)[0] in ('!', '?', '@', '%'):
# Comment, php etc...
return True
return util.isBlockLevel(m.group(1))
return False
class AndSubstitutePostprocessor(Postprocessor):
""" Restore valid entities """
def run(self, text):
text = text.replace(util.AMP_SUBSTITUTE, "&")
return text
class UnescapePostprocessor(Postprocessor):
""" Restore escaped chars """
RE = re.compile('%s(\d+)%s' % (util.STX, util.ETX))
def unescape(self, m):
return unichr(int(m.group(1)))
def run(self, text):
return self.RE.sub(self.unescape, text)
########NEW FILE########
__FILENAME__ = preprocessors
"""
PRE-PROCESSORS
=============================================================================
Preprocessors work on source text before we start doing anything too
complicated.
"""
import re
import util
import odict
def build_preprocessors(md_instance, **kwargs):
""" Build the default set of preprocessors used by Markdown. """
preprocessors = odict.OrderedDict()
if md_instance.safeMode != 'escape':
preprocessors["html_block"] = HtmlBlockPreprocessor(md_instance)
preprocessors["reference"] = ReferencePreprocessor(md_instance)
return preprocessors
class Preprocessor(util.Processor):
"""
Preprocessors are run after the text is broken into lines.
Each preprocessor implements a "run" method that takes a pointer to a
list of lines of the document, modifies it as necessary and returns
either the same pointer or a pointer to a new list.
Preprocessors must extend markdown.Preprocessor.
"""
def run(self, lines):
"""
Each subclass of Preprocessor should override the `run` method, which
takes the document as a list of strings split by newlines and returns
the (possibly modified) list of lines.
"""
pass
class HtmlBlockPreprocessor(Preprocessor):
"""Remove html blocks from the text and store them for later retrieval."""
right_tag_patterns = ["</%s>", "%s>"]
attrs_pattern = r"""
\s+(?P<attr>[^>"'/= ]+)=(?P<q>['"])(?P<value>.*?)(?P=q) # attr="value"
| # OR
\s+(?P<attr1>[^>"'/= ]+)=(?P<value1>[^> ]+) # attr=value
| # OR
\s+(?P<attr2>[^>"'/= ]+) # attr
"""
left_tag_pattern = r'^\<(?P<tag>[^> ]+)(?P<attrs>(%s)*)\s*\/?\>?' % attrs_pattern
attrs_re = re.compile(attrs_pattern, re.VERBOSE)
left_tag_re = re.compile(left_tag_pattern, re.VERBOSE)
markdown_in_raw = False
def _get_left_tag(self, block):
m = self.left_tag_re.match(block)
if m:
tag = m.group('tag')
raw_attrs = m.group('attrs')
attrs = {}
if raw_attrs:
for ma in self.attrs_re.finditer(raw_attrs):
if ma.group('attr'):
if ma.group('value'):
attrs[ma.group('attr').strip()] = ma.group('value')
else:
attrs[ma.group('attr').strip()] = ""
elif ma.group('attr1'):
if ma.group('value1'):
attrs[ma.group('attr1').strip()] = ma.group('value1')
else:
attrs[ma.group('attr1').strip()] = ""
elif ma.group('attr2'):
attrs[ma.group('attr2').strip()] = ""
return tag, len(m.group(0)), attrs
else:
tag = block[1:].split(">", 1)[0].lower()
return tag, len(tag)+2, {}
def _recursive_tagfind(self, ltag, rtag, start_index, block):
while 1:
i = block.find(rtag, start_index)
if i == -1:
return -1
j = block.find(ltag, start_index)
# if no ltag, or rtag found before another ltag, return index
if (j > i or j == -1):
return i + len(rtag)
# another ltag found before rtag, use end of ltag as starting
# point and search again
j = block.find('>', j)
start_index = self._recursive_tagfind(ltag, rtag, j + 1, block)
if start_index == -1:
# HTML potentially malformed- ltag has no corresponding
# rtag
return -1
def _get_right_tag(self, left_tag, left_index, block):
for p in self.right_tag_patterns:
tag = p % left_tag
i = self._recursive_tagfind("<%s" % left_tag, tag, left_index, block)
if i > 2:
return tag.lstrip("<").rstrip(">"), i
return block.rstrip()[-left_index:-1].lower(), len(block)
def _equal_tags(self, left_tag, right_tag):
if left_tag[0] in ['?', '@', '%']: # handle PHP, etc.
return True
if ("/" + left_tag) == right_tag:
return True
if (right_tag == "--" and left_tag == "--"):
return True
elif left_tag == right_tag[1:] \
and right_tag[0] != "<":
return True
else:
return False
def _is_oneliner(self, tag):
return (tag in ['hr', 'hr/'])
def run(self, lines):
text = "\n".join(lines)
new_blocks = []
text = text.split("\n\n")
items = []
left_tag = ''
right_tag = ''
in_tag = False # flag
while text:
block = text[0]
if block.startswith("\n"):
block = block[1:]
text = text[1:]
if block.startswith("\n"):
block = block[1:]
if not in_tag:
if block.startswith("<") and len(block.strip()) > 1:
if block[1] == "!":
# is a comment block
left_tag, left_index, attrs = "--", 2, ()
else:
left_tag, left_index, attrs = self._get_left_tag(block)
right_tag, data_index = self._get_right_tag(left_tag,
left_index,
block)
# keep checking conditions below and maybe just append
if data_index < len(block) \
and (util.isBlockLevel(left_tag)
or left_tag == '--'):
text.insert(0, block[data_index:])
block = block[:data_index]
if not (util.isBlockLevel(left_tag) \
or block[1] in ["!", "?", "@", "%"]):
new_blocks.append(block)
continue
if self._is_oneliner(left_tag):
new_blocks.append(block.strip())
continue
if block.rstrip().endswith(">") \
and self._equal_tags(left_tag, right_tag):
if self.markdown_in_raw and 'markdown' in attrs.keys():
start = re.sub(r'\smarkdown(=[\'"]?[^> ]*[\'"]?)?',
'', block[:left_index])
end = block[-len(right_tag)-2:]
block = block[left_index:-len(right_tag)-2]
new_blocks.append(
self.markdown.htmlStash.store(start))
new_blocks.append(block)
new_blocks.append(
self.markdown.htmlStash.store(end))
else:
new_blocks.append(
self.markdown.htmlStash.store(block.strip()))
continue
else:
# if is block level tag and is not complete
if util.isBlockLevel(left_tag) or left_tag == "--" \
and not block.rstrip().endswith(">"):
items.append(block.strip())
in_tag = True
else:
new_blocks.append(
self.markdown.htmlStash.store(block.strip()))
continue
new_blocks.append(block)
else:
items.append(block)
right_tag, data_index = self._get_right_tag(left_tag, 0, block)
if self._equal_tags(left_tag, right_tag):
# if find closing tag
if data_index < len(block):
# we have more text after right_tag
items[-1] = block[:data_index]
text.insert(0, block[data_index:])
in_tag = False
if self.markdown_in_raw and 'markdown' in attrs.keys():
start = re.sub(r'\smarkdown(=[\'"]?[^> ]*[\'"]?)?',
'', items[0][:left_index])
items[0] = items[0][left_index:]
end = items[-1][-len(right_tag)-2:]
items[-1] = items[-1][:-len(right_tag)-2]
new_blocks.append(
self.markdown.htmlStash.store(start))
new_blocks.extend(items)
new_blocks.append(
self.markdown.htmlStash.store(end))
else:
new_blocks.append(
self.markdown.htmlStash.store('\n\n'.join(items)))
items = []
if items:
if self.markdown_in_raw and 'markdown' in attrs.keys():
start = re.sub(r'\smarkdown(=[\'"]?[^> ]*[\'"]?)?',
'', items[0][:left_index])
items[0] = items[0][left_index:]
end = items[-1][-len(right_tag)-2:]
items[-1] = items[-1][:-len(right_tag)-2]
new_blocks.append(
self.markdown.htmlStash.store(start))
new_blocks.extend(items)
if end.strip():
new_blocks.append(
self.markdown.htmlStash.store(end))
else:
new_blocks.append(
self.markdown.htmlStash.store('\n\n'.join(items)))
#new_blocks.append(self.markdown.htmlStash.store('\n\n'.join(items)))
new_blocks.append('\n')
new_text = "\n\n".join(new_blocks)
return new_text.split("\n")
class ReferencePreprocessor(Preprocessor):
""" Remove reference definitions from text and store for later use. """
RE = re.compile(r'^(\ ?\ ?\ ?)\[([^\]]*)\]:\s*([^ ]*)(.*)$', re.DOTALL)
def run (self, lines):
new_text = [];
for line in lines:
m = self.RE.match(line)
if m:
id = m.group(2).strip().lower()
link = m.group(3).lstrip('<').rstrip('>')
t = m.group(4).strip() # potential title
if not t:
self.markdown.references[id] = (link, t)
elif (len(t) >= 2
and (t[0] == t[-1] == "\""
or t[0] == t[-1] == "\'"
or (t[0] == "(" and t[-1] == ")") ) ):
self.markdown.references[id] = (link, t[1:-1])
else:
new_text.append(line)
else:
new_text.append(line)
return new_text #+ "\n"
########NEW FILE########
__FILENAME__ = serializers
# markdown/searializers.py
#
# Add x/html serialization to Elementree
# Taken from ElementTree 1.3 preview with slight modifications
#
# Copyright (c) 1999-2007 by Fredrik Lundh. All rights reserved.
#
# fredrik@pythonware.com
# http://www.pythonware.com
#
# --------------------------------------------------------------------
# The ElementTree toolkit is
#
# Copyright (c) 1999-2007 by Fredrik Lundh
#
# By obtaining, using, and/or copying this software and/or its
# associated documentation, you agree that you have read, understood,
# and will comply with the following terms and conditions:
#
# Permission to use, copy, modify, and distribute this software and
# its associated documentation for any purpose and without fee is
# hereby granted, provided that the above copyright notice appears in
# all copies, and that both that copyright notice and this permission
# notice appear in supporting documentation, and that the name of
# Secret Labs AB or the author not be used in advertising or publicity
# pertaining to distribution of the software without specific, written
# prior permission.
#
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
# OF THIS SOFTWARE.
# --------------------------------------------------------------------
import util
ElementTree = util.etree.ElementTree
QName = util.etree.QName
if hasattr(util.etree, 'test_comment'):
Comment = util.etree.test_comment
else:
Comment = util.etree.Comment
PI = util.etree.PI
ProcessingInstruction = util.etree.ProcessingInstruction
__all__ = ['to_html_string', 'to_xhtml_string']
HTML_EMPTY = ("area", "base", "basefont", "br", "col", "frame", "hr",
"img", "input", "isindex", "link", "meta" "param")
try:
HTML_EMPTY = set(HTML_EMPTY)
except NameError:
pass
_namespace_map = {
# "well-known" namespace prefixes
"http://www.w3.org/XML/1998/namespace": "xml",
"http://www.w3.org/1999/xhtml": "html",
"http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf",
"http://schemas.xmlsoap.org/wsdl/": "wsdl",
# xml schema
"http://www.w3.org/2001/XMLSchema": "xs",
"http://www.w3.org/2001/XMLSchema-instance": "xsi",
# dublic core
"http://purl.org/dc/elements/1.1/": "dc",
}
def _raise_serialization_error(text):
raise TypeError(
"cannot serialize %r (type %s)" % (text, type(text).__name__)
)
def _encode(text, encoding):
try:
return text.encode(encoding, "xmlcharrefreplace")
except (TypeError, AttributeError):
_raise_serialization_error(text)
def _escape_cdata(text):
# escape character data
try:
# it's worth avoiding do-nothing calls for strings that are
# shorter than 500 character, or so. assume that's, by far,
# the most common case in most applications.
if "&" in text:
text = text.replace("&", "&")
if "<" in text:
text = text.replace("<", "<")
if ">" in text:
text = text.replace(">", ">")
return text
except (TypeError, AttributeError):
_raise_serialization_error(text)
def _escape_attrib(text):
# escape attribute value
try:
if "&" in text:
text = text.replace("&", "&")
if "<" in text:
text = text.replace("<", "<")
if ">" in text:
text = text.replace(">", ">")
if "\"" in text:
text = text.replace("\"", """)
if "\n" in text:
text = text.replace("\n", " ")
return text
except (TypeError, AttributeError):
_raise_serialization_error(text)
def _escape_attrib_html(text):
# escape attribute value
try:
if "&" in text:
text = text.replace("&", "&")
if "<" in text:
text = text.replace("<", "<")
if ">" in text:
text = text.replace(">", ">")
if "\"" in text:
text = text.replace("\"", """)
return text
except (TypeError, AttributeError):
_raise_serialization_error(text)
def _serialize_html(write, elem, qnames, namespaces, format):
tag = elem.tag
text = elem.text
if tag is Comment:
write("<!--%s-->" % _escape_cdata(text))
elif tag is ProcessingInstruction:
write("<?%s?>" % _escape_cdata(text))
else:
tag = qnames[tag]
if tag is None:
if text:
write(_escape_cdata(text))
for e in elem:
_serialize_html(write, e, qnames, None, format)
else:
write("<" + tag)
items = elem.items()
if items or namespaces:
items.sort() # lexical order
for k, v in items:
if isinstance(k, QName):
k = k.text
if isinstance(v, QName):
v = qnames[v.text]
else:
v = _escape_attrib_html(v)
if qnames[k] == v and format == 'html':
# handle boolean attributes
write(" %s" % v)
else:
write(" %s=\"%s\"" % (qnames[k], v))
if namespaces:
items = namespaces.items()
items.sort(key=lambda x: x[1]) # sort on prefix
for v, k in items:
if k:
k = ":" + k
write(" xmlns%s=\"%s\"" % (k, _escape_attrib(v)))
if format == "xhtml" and tag in HTML_EMPTY:
write(" />")
else:
write(">")
tag = tag.lower()
if text:
if tag == "script" or tag == "style":
write(text)
else:
write(_escape_cdata(text))
for e in elem:
_serialize_html(write, e, qnames, None, format)
if tag not in HTML_EMPTY:
write("</" + tag + ">")
if elem.tail:
write(_escape_cdata(elem.tail))
def _write_html(root,
encoding=None,
default_namespace=None,
format="html"):
assert root is not None
data = []
write = data.append
qnames, namespaces = _namespaces(root, default_namespace)
_serialize_html(write, root, qnames, namespaces, format)
if encoding is None:
return "".join(data)
else:
return _encode("".join(data))
# --------------------------------------------------------------------
# serialization support
def _namespaces(elem, default_namespace=None):
# identify namespaces used in this tree
# maps qnames to *encoded* prefix:local names
qnames = {None: None}
# maps uri:s to prefixes
namespaces = {}
if default_namespace:
namespaces[default_namespace] = ""
def add_qname(qname):
# calculate serialized qname representation
try:
if qname[:1] == "{":
uri, tag = qname[1:].split("}", 1)
prefix = namespaces.get(uri)
if prefix is None:
prefix = _namespace_map.get(uri)
if prefix is None:
prefix = "ns%d" % len(namespaces)
if prefix != "xml":
namespaces[uri] = prefix
if prefix:
qnames[qname] = "%s:%s" % (prefix, tag)
else:
qnames[qname] = tag # default element
else:
if default_namespace:
raise ValueError(
"cannot use non-qualified names with "
"default_namespace option"
)
qnames[qname] = qname
except TypeError:
_raise_serialization_error(qname)
# populate qname and namespaces table
try:
iterate = elem.iter
except AttributeError:
iterate = elem.getiterator # cET compatibility
for elem in iterate():
tag = elem.tag
if isinstance(tag, QName) and tag.text not in qnames:
add_qname(tag.text)
elif isinstance(tag, basestring):
if tag not in qnames:
add_qname(tag)
elif tag is not None and tag is not Comment and tag is not PI:
_raise_serialization_error(tag)
for key, value in elem.items():
if isinstance(key, QName):
key = key.text
if key not in qnames:
add_qname(key)
if isinstance(value, QName) and value.text not in qnames:
add_qname(value.text)
text = elem.text
if isinstance(text, QName) and text.text not in qnames:
add_qname(text.text)
return qnames, namespaces
def to_html_string(element):
return _write_html(ElementTree(element).getroot(), format="html")
def to_xhtml_string(element):
return _write_html(ElementTree(element).getroot(), format="xhtml")
########NEW FILE########
__FILENAME__ = treeprocessors
import re
import inlinepatterns
import util
import odict
def build_treeprocessors(md_instance, **kwargs):
""" Build the default treeprocessors for Markdown. """
treeprocessors = odict.OrderedDict()
treeprocessors["inline"] = InlineProcessor(md_instance)
treeprocessors["prettify"] = PrettifyTreeprocessor(md_instance)
return treeprocessors
def isString(s):
""" Check if it's string """
if not isinstance(s, util.AtomicString):
return isinstance(s, basestring)
return False
class Processor:
def __init__(self, markdown_instance=None):
if markdown_instance:
self.markdown = markdown_instance
class Treeprocessor(Processor):
"""
Treeprocessors are run on the ElementTree object before serialization.
Each Treeprocessor implements a "run" method that takes a pointer to an
ElementTree, modifies it as necessary and returns an ElementTree
object.
Treeprocessors must extend markdown.Treeprocessor.
"""
def run(self, root):
"""
Subclasses of Treeprocessor should implement a `run` method, which
takes a root ElementTree. This method can return another ElementTree
object, and the existing root ElementTree will be replaced, or it can
modify the current tree and return None.
"""
pass
class InlineProcessor(Treeprocessor):
"""
A Treeprocessor that traverses a tree, applying inline patterns.
"""
def __init__(self, md):
self.__placeholder_prefix = util.INLINE_PLACEHOLDER_PREFIX
self.__placeholder_suffix = util.ETX
self.__placeholder_length = 4 + len(self.__placeholder_prefix) \
+ len(self.__placeholder_suffix)
self.__placeholder_re = util.INLINE_PLACEHOLDER_RE
self.markdown = md
def __makePlaceholder(self, type):
""" Generate a placeholder """
id = "%04d" % len(self.stashed_nodes)
hash = util.INLINE_PLACEHOLDER % id
return hash, id
def __findPlaceholder(self, data, index):
"""
Extract id from data string, start from index
Keyword arguments:
* data: string
* index: index, from which we start search
Returns: placeholder id and string index, after the found placeholder.
"""
m = self.__placeholder_re.search(data, index)
if m:
return m.group(1), m.end()
else:
return None, index + 1
def __stashNode(self, node, type):
""" Add node to stash """
placeholder, id = self.__makePlaceholder(type)
self.stashed_nodes[id] = node
return placeholder
def __handleInline(self, data, patternIndex=0):
"""
Process string with inline patterns and replace it
with placeholders
Keyword arguments:
* data: A line of Markdown text
* patternIndex: The index of the inlinePattern to start with
Returns: String with placeholders.
"""
if not isinstance(data, util.AtomicString):
startIndex = 0
while patternIndex < len(self.markdown.inlinePatterns):
data, matched, startIndex = self.__applyPattern(
self.markdown.inlinePatterns.value_for_index(patternIndex),
data, patternIndex, startIndex)
if not matched:
patternIndex += 1
return data
def __processElementText(self, node, subnode, isText=True):
"""
Process placeholders in Element.text or Element.tail
of Elements popped from self.stashed_nodes.
Keywords arguments:
* node: parent node
* subnode: processing node
* isText: bool variable, True - it's text, False - it's tail
Returns: None
"""
if isText:
text = subnode.text
subnode.text = None
else:
text = subnode.tail
subnode.tail = None
childResult = self.__processPlaceholders(text, subnode)
if not isText and node is not subnode:
pos = node.getchildren().index(subnode)
node.remove(subnode)
else:
pos = 0
childResult.reverse()
for newChild in childResult:
node.insert(pos, newChild)
def __processPlaceholders(self, data, parent):
"""
Process string with placeholders and generate ElementTree tree.
Keyword arguments:
* data: string with placeholders instead of ElementTree elements.
* parent: Element, which contains processing inline data
Returns: list with ElementTree elements with applied inline patterns.
"""
def linkText(text):
if text:
if result:
if result[-1].tail:
result[-1].tail += text
else:
result[-1].tail = text
else:
if parent.text:
parent.text += text
else:
parent.text = text
result = []
strartIndex = 0
while data:
index = data.find(self.__placeholder_prefix, strartIndex)
if index != -1:
id, phEndIndex = self.__findPlaceholder(data, index)
if id in self.stashed_nodes:
node = self.stashed_nodes.get(id)
if index > 0:
text = data[strartIndex:index]
linkText(text)
if not isString(node): # it's Element
for child in [node] + node.getchildren():
if child.tail:
if child.tail.strip():
self.__processElementText(node, child,False)
if child.text:
if child.text.strip():
self.__processElementText(child, child)
else: # it's just a string
linkText(node)
strartIndex = phEndIndex
continue
strartIndex = phEndIndex
result.append(node)
else: # wrong placeholder
end = index + len(self.__placeholder_prefix)
linkText(data[strartIndex:end])
strartIndex = end
else:
text = data[strartIndex:]
if isinstance(data, util.AtomicString):
# We don't want to loose the AtomicString
text = util.AtomicString(text)
linkText(text)
data = ""
return result
def __applyPattern(self, pattern, data, patternIndex, startIndex=0):
"""
Check if the line fits the pattern, create the necessary
elements, add it to stashed_nodes.
Keyword arguments:
* data: the text to be processed
* pattern: the pattern to be checked
* patternIndex: index of current pattern
* startIndex: string index, from which we start searching
Returns: String with placeholders instead of ElementTree elements.
"""
match = pattern.getCompiledRegExp().match(data[startIndex:])
leftData = data[:startIndex]
if not match:
return data, False, 0
node = pattern.handleMatch(match)
if node is None:
return data, True, len(leftData)+match.span(len(match.groups()))[0]
if not isString(node):
if not isinstance(node.text, util.AtomicString):
# We need to process current node too
for child in [node] + node.getchildren():
if not isString(node):
if child.text:
child.text = self.__handleInline(child.text,
patternIndex + 1)
if child.tail:
child.tail = self.__handleInline(child.tail,
patternIndex)
placeholder = self.__stashNode(node, pattern.type())
return "%s%s%s%s" % (leftData,
match.group(1),
placeholder, match.groups()[-1]), True, 0
def run(self, tree):
"""Apply inline patterns to a parsed Markdown tree.
Iterate over ElementTree, find elements with inline tag, apply inline
patterns and append newly created Elements to tree. If you don't
want to process your data with inline paterns, instead of normal string,
use subclass AtomicString:
node.text = markdown.AtomicString("This will not be processed.")
Arguments:
* tree: ElementTree object, representing Markdown tree.
Returns: ElementTree object with applied inline patterns.
"""
self.stashed_nodes = {}
stack = [tree]
while stack:
currElement = stack.pop()
insertQueue = []
for child in currElement.getchildren():
if child.text and not isinstance(child.text, util.AtomicString):
text = child.text
child.text = None
lst = self.__processPlaceholders(self.__handleInline(
text), child)
stack += lst
insertQueue.append((child, lst))
if child.tail:
tail = self.__handleInline(child.tail)
dumby = util.etree.Element('d')
tailResult = self.__processPlaceholders(tail, dumby)
if dumby.text:
child.tail = dumby.text
else:
child.tail = None
pos = currElement.getchildren().index(child) + 1
tailResult.reverse()
for newChild in tailResult:
currElement.insert(pos, newChild)
if child.getchildren():
stack.append(child)
if self.markdown.enable_attributes:
for element, lst in insertQueue:
if element.text:
element.text = \
inlinepatterns.handleAttributes(element.text,
element)
i = 0
for newChild in lst:
# Processing attributes
if newChild.tail:
newChild.tail = \
inlinepatterns.handleAttributes(newChild.tail,
element)
if newChild.text:
newChild.text = \
inlinepatterns.handleAttributes(newChild.text,
newChild)
element.insert(i, newChild)
i += 1
return tree
class PrettifyTreeprocessor(Treeprocessor):
""" Add linebreaks to the html document. """
def _prettifyETree(self, elem):
""" Recursively add linebreaks to ElementTree children. """
i = "\n"
if util.isBlockLevel(elem.tag) and elem.tag not in ['code', 'pre']:
if (not elem.text or not elem.text.strip()) \
and len(elem) and util.isBlockLevel(elem[0].tag):
elem.text = i
for e in elem:
if util.isBlockLevel(e.tag):
self._prettifyETree(e)
if not elem.tail or not elem.tail.strip():
elem.tail = i
if not elem.tail or not elem.tail.strip():
elem.tail = i
def run(self, root):
""" Add linebreaks to ElementTree root object. """
self._prettifyETree(root)
# Do <br />'s seperately as they are often in the middle of
# inline content and missed by _prettifyETree.
brs = root.getiterator('br')
for br in brs:
if not br.tail or not br.tail.strip():
br.tail = '\n'
else:
br.tail = '\n%s' % br.tail
########NEW FILE########
__FILENAME__ = util
# -*- coding: utf-8 -*-
import re
from logging import CRITICAL
import etree_loader
"""
CONSTANTS
=============================================================================
"""
"""
Constants you might want to modify
-----------------------------------------------------------------------------
"""
BLOCK_LEVEL_ELEMENTS = re.compile("p|div|h[1-6]|blockquote|pre|table|dl|ol|ul"
"|script|noscript|form|fieldset|iframe|math"
"|ins|del|hr|hr/|style|li|dt|dd|thead|tbody"
"|tr|th|td|section|footer|header|group|figure"
"|figcaption|aside|article|canvas|output"
"|progress|video")
# Placeholders
STX = u'\u0002' # Use STX ("Start of text") for start-of-placeholder
ETX = u'\u0003' # Use ETX ("End of text") for end-of-placeholder
INLINE_PLACEHOLDER_PREFIX = STX+"klzzwxh:"
INLINE_PLACEHOLDER = INLINE_PLACEHOLDER_PREFIX + "%s" + ETX
INLINE_PLACEHOLDER_RE = re.compile(INLINE_PLACEHOLDER % r'([0-9]{4})')
AMP_SUBSTITUTE = STX+"amp"+ETX
"""
Constants you probably do not need to change
-----------------------------------------------------------------------------
"""
RTL_BIDI_RANGES = ( (u'\u0590', u'\u07FF'),
# Hebrew (0590-05FF), Arabic (0600-06FF),
# Syriac (0700-074F), Arabic supplement (0750-077F),
# Thaana (0780-07BF), Nko (07C0-07FF).
(u'\u2D30', u'\u2D7F'), # Tifinagh
)
# Extensions should use "markdown.util.etree" instead of "etree" (or do `from
# markdown.util import etree`). Do not import it by yourself.
etree = etree_loader.importETree()
"""
AUXILIARY GLOBAL FUNCTIONS
=============================================================================
"""
def isBlockLevel(tag):
"""Check if the tag is a block level HTML tag."""
if isinstance(tag, basestring):
return BLOCK_LEVEL_ELEMENTS.match(tag)
# Some ElementTree tags are not strings, so return False.
return False
"""
MISC AUXILIARY CLASSES
=============================================================================
"""
class AtomicString(unicode):
"""A string which should not be further processed."""
pass
class Processor:
def __init__(self, markdown_instance=None):
if markdown_instance:
self.markdown = markdown_instance
class HtmlStash:
"""
This class is used for stashing HTML objects that we extract
in the beginning and replace with place-holders.
"""
def __init__ (self):
""" Create a HtmlStash. """
self.html_counter = 0 # for counting inline html segments
self.rawHtmlBlocks=[]
def store(self, html, safe=False):
"""
Saves an HTML segment for later reinsertion. Returns a
placeholder string that needs to be inserted into the
document.
Keyword arguments:
* html: an html segment
* safe: label an html segment as safe for safemode
Returns : a placeholder string
"""
self.rawHtmlBlocks.append((html, safe))
placeholder = self.get_placeholder(self.html_counter)
self.html_counter += 1
return placeholder
def reset(self):
self.html_counter = 0
self.rawHtmlBlocks = []
def get_placeholder(self, key):
return "%swzxhzdk:%d%s" % (STX, key, ETX)
########NEW FILE########
__FILENAME__ = __main__
"""
COMMAND-LINE SPECIFIC STUFF
=============================================================================
"""
import markdown
import sys
import optparse
import logging
from logging import DEBUG, INFO, CRITICAL
logger = logging.getLogger('MARKDOWN')
def parse_options():
"""
Define and parse `optparse` options for command-line usage.
"""
usage = """%prog [options] [INPUTFILE]
(STDIN is assumed if no INPUTFILE is given)"""
desc = "A Python implementation of John Gruber's Markdown. " \
"http://www.freewisdom.org/projects/python-markdown/"
ver = "%%prog %s" % markdown.version
parser = optparse.OptionParser(usage=usage, description=desc, version=ver)
parser.add_option("-f", "--file", dest="filename", default=sys.stdout,
help="Write output to OUTPUT_FILE. Defaults to STDOUT.",
metavar="OUTPUT_FILE")
parser.add_option("-e", "--encoding", dest="encoding",
help="Encoding for input and output files.",)
parser.add_option("-q", "--quiet", default = CRITICAL,
action="store_const", const=CRITICAL+10, dest="verbose",
help="Suppress all warnings.")
parser.add_option("-v", "--verbose",
action="store_const", const=INFO, dest="verbose",
help="Print all warnings.")
parser.add_option("-s", "--safe", dest="safe", default=False,
metavar="SAFE_MODE",
help="'replace', 'remove' or 'escape' HTML tags in input")
parser.add_option("-o", "--output_format", dest="output_format",
default='xhtml1', metavar="OUTPUT_FORMAT",
help="'xhtml1' (default), 'html4' or 'html5'.")
parser.add_option("--noisy",
action="store_const", const=DEBUG, dest="verbose",
help="Print debug messages.")
parser.add_option("-x", "--extension", action="append", dest="extensions",
help = "Load extension EXTENSION.", metavar="EXTENSION")
parser.add_option("-n", "--no_lazy_ol", dest="lazy_ol",
action='store_false', default=True,
help="Observe number of first item of ordered lists.")
(options, args) = parser.parse_args()
if len(args) == 0:
input_file = None
else:
input_file = args[0]
if not options.extensions:
options.extensions = []
return {'input': input_file,
'output': options.filename,
'safe_mode': options.safe,
'extensions': options.extensions,
'encoding': options.encoding,
'output_format': options.output_format,
'lazy_ol': options.lazy_ol}, options.verbose
def run():
"""Run Markdown from the command line."""
# Parse options and adjust logging level if necessary
options, logging_level = parse_options()
if not options: sys.exit(2)
logger.setLevel(logging_level)
logger.addHandler(logging.StreamHandler())
# Run
markdown.markdownFromFile(**options)
if __name__ == '__main__':
# Support running module as a commandline command.
# Python 2.5 & 2.6 do: `python -m markdown.__main__ [options] [args]`.
# Python 2.7 & 3.x do: `python -m markdown [options] [args]`.
run()
########NEW FILE########
|
PHP | UTF-8 | 1,992 | 3.109375 | 3 | [
"MIT"
] | permissive | <?php
namespace Perfumer\Component\Container\Storage;
/**
* FileStorage
* Uses php-files to store parameters.
* You must register folders and files with your parameters first.
* All folders and files must be registered before first "getParamGroup" call.
*
* @package perfumer/container
* @category storage
* @author Ilyas Makashev mehmatovec@gmail.com
* @link https://github.com/blumfontein/perfumer-container
* @copyright (c) 2014 Ilyas Makashev
* @license MIT
*/
class FileStorage extends AbstractStorage
{
/**
* registerFile
* Parsing and saving given file with parameters.
*
* @param string $file
* @return void
* @access public
*/
public function registerFile($file)
{
if (is_file($file))
{
$params = require $file;
$this->params = array_merge($this->params, $params);
}
}
/**
* setParam
* File storage doesn't support setting parameters.
*
* @param string $group
* @param string $name
* @param mixed $value
* @return boolean
* @access public
*/
public function setParam($group, $name, $value)
{
return false;
}
/**
* getParamGroup
* Get array with whole group of parameters. Returns key-value array.
*
* @param string $group
* @return array
* @access public
*/
public function getParamGroup($group)
{
return isset($this->params[$group]) ? $this->params[$group] : [];
}
/**
* setParamGroup
* File storage doesn't support setting parameters.
*
* @param string $group
* @param array $values
* @return boolean
* @access public
*/
public function setParamGroup($group, array $values)
{
return false;
}
public function addParamGroup($group, array $values)
{
return false;
}
public function deleteParamGroup($group, array $keys = [])
{
return false;
}
} |
Markdown | UTF-8 | 3,252 | 3.34375 | 3 | [] | no_license | ---
layout: post
title: 用JavaScript来说数据结构
category: 编程
tag: JavaScript
exception:
readtime: 12
---
## 什么是数据结构
* 在计算机科学中,数据结构(data structure)是计算机存储、组织数据的方式。
* 数据结构是指相互之间存在一种或多种特定关系的数据元素的集合。
## 数据结构概念定义
* 数据:是用来描述一种客观事物的符号,分为数据元素、数据对象、数据项等。
* 结构:数据元素相互之间的关系,分为逻辑结构和存储结构两大类。
* 数据逻辑结构:指数据元素之间的前后件关系,分为集合、线性结构、非线性结构等。
* 数据存储结构:指数据的逻辑结构在计算机存储空间的存放形式,分为顺序结构、链式结构、索引结构、散列结构等。
## 数据结构有哪些
* **列表**:
一个存储元素的线性集合(collection),元素可以通过索引来任意存取,索引通常是数字,用来计算元素之间存储位置的偏移量。
[示例代码](https://github.com/yzsunlei/javascript-data-structure/blob/master/01.list.js)
* **队列**:
用于存储按顺序排列的数据,先进先出。
[示例代码](https://github.com/yzsunlei/javascript-data-structure/blob/master/02.queue.js)
* **栈**:
一种高效的数据结构,数据只能在栈顶添加或删除,先进后出。
[示例代码](https://github.com/yzsunlei/javascript-data-structure/blob/master/03.stack.js)
* **链表**:
由一组节点组成的集合,每个节点都使用一个对象的引用指向它的后继。
[示例代码](https://github.com/yzsunlei/javascript-data-structure/blob/master/04.linkedlist.js)
* **字典**:
以键-值对形式存储数据的数据结构。
[示例代码](https://github.com/yzsunlei/javascript-data-structure/blob/master/05.dictionary.js)
* **散列表**:
散列是一种常用的数据存储技术,散列后的数据可以快速地插入或取用。
[示例代码](https://github.com/yzsunlei/javascript-data-structure/blob/master/06.hashtable.js)
* **集合**:
一种包含不同元素的数据结构。集合中的成员是无序的,集合中不允许相同成员存在。
[示例代码](https://github.com/yzsunlei/javascript-data-structure/blob/master/07.set.js)
* **树**:
一种非线性的数据结构,以分层的方式存储数据,被用来存储具有层级关系的数据。
[示例代码](https://github.com/yzsunlei/javascript-data-structure/blob/master/08.bst.js)
* **图**:
由边的集合及顶点的集合组成。
[示例代码](https://github.com/yzsunlei/javascript-data-structure/blob/master/09.graph.js)
* 上面对常用的9种数据结构做了一个简要的介绍。更好的理解数据结构,还是看图解、看示例源码比较好。
## 参考资料
* [https://book.douban.com/subject/25945449/](https://book.douban.com/subject/25945449/)
* [https://book.douban.com/subject/27129352/](https://book.douban.com/subject/27129352/)
* [https://www.cnblogs.com/shuoer/p/8424848.html](https://www.cnblogs.com/shuoer/p/8424848.html)
* [https://segmentfault.com/a/1190000010343508](https://segmentfault.com/a/1190000010343508)
|
Java | UTF-8 | 224 | 1.960938 | 2 | [] | no_license | package com.tzy.annotationdemo;
import org.springframework.stereotype.Component;
@Component
public class TestService implements Service {
@Override
public String getService() {
return "das ist test service";
}
}
|
Python | UTF-8 | 577 | 3.0625 | 3 | [] | no_license | def maxNum(WH, cut_lst):
last = 0
max_len = 0
for i in range(len(cut_lst)):
if max_len < (cut_lst[i] - last):
max_len = cut_lst[i] - last
last = cut_lst[i]
if max_len < (WH - last):
max_len = WH - last
return max_len
W, H = map(int, input().split(' '))
N = int(input())
cut_W = []
cut_H = []
for n in range(N):
WH, LEN = map(int, input().split(' '))
if WH:
cut_W.append(LEN)
else:
cut_H.append(LEN)
cut_W.sort()
cut_H.sort()
awsW = maxNum(W, cut_W)
awsH = maxNum(H, cut_H)
print(awsW*awsH) |
PHP | UTF-8 | 3,811 | 2.625 | 3 | [] | no_license | <?php
if(isset($_GET['edit_user']) && !empty($_GET['edit_user']) ){
$user_id = $_GET['edit_user'];
$su = $connection->prepare("SELECT * FROM users WHERE user_id=?");
$su->bind_param("i", $user_id);
$su->execute();
if(!$su){
printf("Error: %s.\n", $su->error);
}
$select_users = $su->get_result();
while($row = $select_users->fetch_assoc()){
$user_id = $row['user_id'];
$username = $row['username'];
$db_user_password = $row['user_password'];
$user_firstname = $row['user_firstname'];
$user_lastname = $row['user_lastname'];
$user_email = $row['user_email'];
$user_image = $row['user_image'];
$user_role = $row['user_role'];
}
if(isset($_POST['edit_user'])){
$user_firstname = $_POST['user_firstname'];
$user_lastname = $_POST['user_lastname'];
$user_role = $_POST['user_role'];
$username = $_POST['username'];
$user_email = $_POST['user_email'];
$user_password = $_POST['user_password'];
if($user_password != $db_user_password){
$hash_password = password_hash($user_password,PASSWORD_BCRYPT,array('cost'=> 10));
}else{
$hash_password = $user_password;
}
$dpi = $connection->prepare("UPDATE users SET user_firstname =?,user_lastname=?,user_role=?,username=?,user_email=?,user_password =?
WHERE user_id=?");
$dpi->bind_param("ssssssi", $user_firstname,$user_lastname,$user_role,$username,$user_email,$hash_password,$user_id);
$dpi->execute();
if(!$dpi){
printf("Error: %s.\n", $dpi->error);
}
echo "<p class='bg-success'>User Added: " . "<a href='users.php'>View User</a></p>";
}
}else{
header('Location: index.php');
}
?>
<form action="" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="title">Firstname</label>
<input type="text" class="form-control" name="user_firstname" value="<?php echo $user_firstname; ?>">
</div>
<div class="form-group">
<label for="categories">User Role</label>
<select name="user_role" class="form-control" >
<option value="subscriber"><?php echo $user_role ; ?></option>
<?php
if($user_role == 'admin'){
echo "<option value='subscriber' >Subscriber</option>";
} else {
echo "<option value='admin'>Admin</option>";
}
?>
</select>
</div>
<div class="form-group">
<label for="author">Lastname</label>
<input type="text" class="form-control" name="user_lastname" value="<?php echo $user_lastname; ?>">
</div>
<div class="form-group">
<label for="post_status">Username</label>
<input type="text" class="form-control" name="username" value="<?php echo $username; ?>">
</div>
<!--<div class="form-group">
<label for="post_image">Post Image</label>
<input type="file" name="image">
<p class="help-block">Select an image for the post.</p>
</div>-->
<div class="form-group">
<label for="post_tags">Email</label>
<input type="email" class="form-control" name="user_email" value="<?php echo $user_email; ?>">
</div>
<div class="form-group">
<label for="post_tags">Password</label>
<input type="password" class="form-control" name="user_password" value="<?php echo $db_user_password; ?>">
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" name="edit_user" value="Edit user">
</div>
</form>
|
PHP | UTF-8 | 4,875 | 2.5625 | 3 | [] | no_license | <?php
namespace jinglan\ethereum;
/**
* Created by PhpStorm.
* User: op
* Date: 2018-05-25
* Time: 15:39
*/
use Yii;
class EthereumRPC
{
//private $NODE_HOST = "http://116.62.129.180:8545";
//private $NODE_HOST = "http://47.105.103.240:8545";
private $method; //Ethereum RPC method
private $params; //Ethereum RPC params(array)
/**
* 参数初始化
* @param $method
* @param $params
*/
public function __construct($method,$params){
$this->method = $method;
$this->params = $params;
}
/*请求*/
public function do_rpc(){
try{
// if(isset($_POST['chain_network']) && $_POST['chain_network'] == 'main_network'){
// $NODE_HOST = "http://47.105.103.240:8545";
// }else{
// $NODE_HOST = "http://116.62.129.180:8545";
// }
$open=fopen("createwallet.txt","a+" );
fwrite($open,"\r\n##### ETH ##############\r\n");
if(isset($_POST['chain_network']) && $_POST['chain_network'] == 'main_network'){
$select_host = Yii::$app->config->info('ETH_SELECT_HOST');
if ($select_host == '1') {
$NODE_HOST = Yii::$app->config->info('ETH_HOST_1');
}else{
$NODE_HOST = Yii::$app->config->info('ETH_HOST_2');
}
}else{
$select_host = Yii::$app->config->info('ETH_SELECT_HOST_TEST');
if ($select_host == '1') {
$NODE_HOST = Yii::$app->config->info('ETH_HOST_TEST_1');
}else{
$NODE_HOST = Yii::$app->config->info('ETH_HOST_TEST_2');
}
}
$language = Yii::$app->request->post('language') == 'en_us'?'en_us':'zh_cn';
if ($language == 'en_us') {
$err_msg = 'The background network node is not configured. Please try again later';
}else{
$err_msg = '后台网络节点未配置,请稍后再试!';
}
// 后台未配置节点信息,返回错误信息!
if (empty($NODE_HOST)) {
return array(
'code' => 0,
'data' => $err_msg
);
}
fwrite($open,'$NODE_HOST::'.$NODE_HOST."\r\n");
$data = array(
'jsonrpc' => "2.0",
'method' => $this->method,
'params' => $this->params,
'id' => 1
);
fwrite($open,'data::'.json_encode($data)."\r\n");
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $NODE_HOST);
curl_setopt($ch, CURLOPT_POST, 1);
$httpHeader[] = 'Content-Type:Application/json';
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data) );
curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false); //处理http证书问题
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$ret = curl_exec($ch);
if (false === $ret) {
$code = 0;
$rst = curl_errno($ch);
}else{
$ret = json_decode($ret);
if(!empty($ret->error->code)){
$code = 0;
$rst = $ret->error->message;
}else{
$code = 1;
$rst = $ret->result;
}
}
curl_close($ch);
fclose($open);
}catch(Exception $e){
$code = 0;
$rst = $e->getMessage();
}
return array(
'code' => $code,
'data' => $rst
);
}
/**
* @param $num 科学计数法字符串 如 2.1E-5
* @param int $double 小数点保留位数 默认18位
* @return string
*/
public function sctonum($num, $double = 18){
if(false !== stripos($num, "e")){
$a = explode("e",strtolower($num));
$b = bcmul($a[0], bcpow(10, $a[1], $double), $double);
$c = rtrim($b, '0');
return $c;
}else{
return $num;
}
}
/*
* @param $number int或者string
* @return string
*/
// 十进制转十六进制
public function bc_dechex($number)
{
if ($number <= 0) {
return false;
}
$conf = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];
$char = '';
do {
$key = fmod($number, 16);
$char = $conf[$key].$char;
$number = floor(($number-$key)/16);
} while ( $number > 0);
return $char;
}
}
|
Java | UTF-8 | 6,180 | 1.929688 | 2 | [] | no_license | package com.nonfamous.tang.web.home;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;
import org.springframework.web.servlet.view.RedirectView;
import com.nonfamous.commom.util.web.RequestValueParse;
import com.nonfamous.commom.util.web.cookyjar.Cookyjar;
import com.nonfamous.tang.dao.home.ShopDAO;
import com.nonfamous.tang.domain.RecordInformation;
import com.nonfamous.tang.domain.Shop;
import com.nonfamous.tang.service.video.ITokenCacheManager;
import com.nonfamous.tang.service.video.ITokenGenerator;
import com.nonfamous.tang.web.common.Constants;
@SuppressWarnings("serial")
public class VideoAction extends MultiActionController {
private ShopDAO shopDAO;
private String uploadAddress;
private String recordAddress;
private String liveAddress;
private String chatAddress;
private String recordInformation = "" ;
final static private Long MAX_UPLOAD_FILE_SIZE = 100L ;
final public static Long UPLOAD_LENGTH_1M = 1048576L ;
final public static Long DEFAULT_RECORD_LENGTH = 300L ; // 300 seconds
private ITokenGenerator tokenGenerator ;
private ITokenCacheManager tokenCacheManager ;
public String getRecordInformation() {
return recordInformation;
}
public String getUploadAddress() {
return uploadAddress;
}
public void setUploadAddress(String uploadAddress) {
this.uploadAddress = uploadAddress;
}
public String getChatAddress() {
return chatAddress;
}
public void setChatAddress(String chatAddress) {
this.chatAddress = chatAddress;
}
public String getRecordAddress() {
return recordAddress;
}
public void setRecordAddress(String recordAddress) {
this.recordAddress = recordAddress;
}
public String getLiveAddress() {
return liveAddress;
}
public void setLiveAddress(String liveAddress) {
this.liveAddress = liveAddress;
}
public void setTokenCacheManager(ITokenCacheManager tokenCacheManager) {
this.tokenCacheManager = tokenCacheManager;
}
public void setTokenGenerator(ITokenGenerator tokenGenerator) {
this.tokenGenerator = tokenGenerator;
}
public ModelAndView validateToken( HttpServletRequest request,HttpServletResponse response ){
ModelAndView mv = new ModelAndView("home/video/ri");
String token = request.getParameter( "token" ) ;
if( token != null && tokenCacheManager.isTokenExists(token)){
RecordInformation ri = (RecordInformation)tokenCacheManager.get(token) ;
if( !ri.isValidated() ) {
ri.setValidated(true);
recordInformation = new org.json.JSONObject( ri ).toString( ) ;
mv.addObject( "recordInformation" , recordInformation ) ;
}
}
return mv ;
}
@SuppressWarnings("unchecked")
public ModelAndView proxyAuthentication( HttpServletRequest request,HttpServletResponse response ){
String token = request.getParameter( "token" ) ;
if( token != null && tokenCacheManager.isTokenExists(token)){
RecordInformation ri = (RecordInformation)tokenCacheManager.get(token) ;
RecordInformation ari= new RecordInformation();
ari.setUserId( ri.getUserId() ) ;
ari.setLength( UPLOAD_LENGTH_1M * MAX_UPLOAD_FILE_SIZE ) ;
recordInformation = new org.json.JSONObject( ari ).toString( ) ;
}
ModelAndView mv = new ModelAndView("home/video/ri");
mv.addObject( "recordInformation" , recordInformation ) ;
return mv ;
}
@SuppressWarnings("unchecked")
public ModelAndView uploadVideo(HttpServletRequest request,HttpServletResponse response) throws Exception {
RequestValueParse rvp = new RequestValueParse(request);
Cookyjar cookyjar = rvp.getCookyjar();
String memberId = cookyjar.get(Constants.MemberId_Cookie);
RecordInformation ri = new RecordInformation();
ri.setUserId( "" + memberId ) ;
Shop shop=shopDAO.shopSelectByMemberId(memberId);
String token = tokenGenerator.generateToken() ;
tokenCacheManager.cache(token , ri ) ;
ModelAndView mav = new ModelAndView("home/video/uploadVideo");
mav.addObject( "uploadAddress" , uploadAddress + "?token=" + token ) ;
mav.addObject( "shopId" , shop.getShopId() ) ;
return mav;
}
@SuppressWarnings("unchecked")
public ModelAndView recordVideo(HttpServletRequest request,HttpServletResponse response) throws Exception {
RequestValueParse rvp = new RequestValueParse(request);
Cookyjar cookyjar = rvp.getCookyjar();
String memberId = cookyjar.get(Constants.MemberId_Cookie);
RecordInformation ri = new RecordInformation();
ri.setUserId( "" + memberId) ;
ri.setLength( DEFAULT_RECORD_LENGTH ) ;
Shop shop=shopDAO.shopSelectByMemberId(memberId);
String token = tokenGenerator.generateToken() ;
tokenCacheManager.cache(token , ri ) ;
ModelAndView mav = new ModelAndView("home/video/recordVideo");
mav.addObject( "recordAddress" , recordAddress + "?token=" + token ) ;
mav.addObject( "shopId" , shop.getShopId() ) ;
return mav;
}
@SuppressWarnings("unchecked")
public ModelAndView liveVideo(HttpServletRequest request,HttpServletResponse response) throws Exception {
RecordInformation ri = new RecordInformation();
ri.setUserId( "" + new RequestValueParse(request).getCookyjar().get(Constants.MemberId_Cookie) ) ;
ri.setLength( 0L ) ;
String token = tokenGenerator.generateToken() ;
tokenCacheManager.cache(token , ri ) ;
return new ModelAndView(new RedirectView(liveAddress + "?token=" + token, false)) ;
}
@SuppressWarnings("unchecked")
public ModelAndView viewLive(HttpServletRequest request,HttpServletResponse response) throws Exception {
ModelAndView mav = new ModelAndView( "home/video/viewLive" ) ;
String liveId = null ;
String memberId = request.getParameter( "memberId" ) ;
if( memberId != null){
Shop shop=shopDAO.shopSelectByMemberId(memberId);
if( shop != null ){
liveId = shop.getLiveId() ;
mav.addObject( "liveId" , liveId ) ;
mav.addObject( "shopId" , shop.getShopId() ) ;
}
}
return mav ;
}
public ShopDAO getShopDAO() {
return shopDAO;
}
public void setShopDAO(ShopDAO shopDAO) {
this.shopDAO = shopDAO;
}
}
|
Java | UTF-8 | 1,015 | 2.75 | 3 | [] | no_license | package yanry.lib.java.entity;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @author yanry
*
* 2015年10月4日
*/
public class Session {
private static Map<Integer, Session> uidMap = new HashMap<Integer, Session>();
private static Map<String, Session> sidMap = new HashMap<String, Session>();
private int userId;
private String sessionId;
private Session(int userId) {
this.userId = userId;
sessionId = UUID.randomUUID().toString();
Session oldSession = uidMap.get(userId);
if (oldSession != null) {
oldSession.destroy();
}
uidMap.put(userId, this);
sidMap.put(sessionId, this);
}
private void destroy() {
uidMap.remove(userId);
sidMap.remove(sessionId);
}
public int getUserId() {
return userId;
}
public String getSessionId() {
return sessionId;
}
public static Session createNew(int userId) {
return new Session(userId);
}
public static Session getBySessionId(String sessionId) {
return sidMap.get(sessionId);
}
}
|
JavaScript | UTF-8 | 729 | 3.75 | 4 | [] | no_license | const a = { nome: 'Carlos'}
const b = a
console.log(b)
//Atribuição por Referencia
b.nome = 'Opa' //B aponta para o mesmo endereco de A, logo se eu alterar b, a será alterada
console.log(b)
console.log(a)
let c = 3
let d = c
d++
console.log(c)
console.log(d)
let valor //Variavel não inicializada
console.log(valor)
valor = null //Não aponta para nenhum local de mémoria
console.log(valor)
const produto = {}
console.log(produto.preco)
console.log(produto)
produto.preco = 3.50
console.log(produto)
produto.preco = undefined //metodo errado
console.log(produto.preco)
console.log(produto)
delete produto.preco //metodo certo
console.log(produto)
console.log(produto.preco)
produto.preco = null //sem valor
|
Ruby | UTF-8 | 1,001 | 2.8125 | 3 | [] | no_license | module ExcelAdapter
class ProjectReport
attr_accessor :project
def initialize(project)
@project = project
end
def to_excel
excel = Excel.new
populate_project_properties(excel)
populate_iterations(excel)
excel.write_to_file("#{@project.name}.xls")
excel.path
end
private
def populate_project_properties(excel)
@project.project_properties.each do |key, value|
excel.create_row_with([key.humanize, value])
end
end
def populate_iterations(excel)
@project.iterations.each_with_index do |iteration, index|
excel.create_row_with(["Week"] + iteration.metrics.collect(& :name) + ["DM Notes"]) if index == 0
iteration_info = [[iteration.date, ""]] +
iteration.metrics.inject([]) { |pair, metric| pair << [metric[:value], metric[:comment]]; pair } +
[[iteration.dm_notes, ""]]
excel.create_row_with_comments(iteration_info)
end
end
end
end |
Python | UTF-8 | 1,322 | 2.890625 | 3 | [
"BSD-2-Clause"
] | permissive |
from .atoms import MemoryLocation, Register
from .dataset import DataSet
class Definition(object):
def __init__(self, atom, codeloc, data):
self.atom = atom
self.codeloc = codeloc
self.data = data
# convert everything into a DataSet
if not isinstance(self.data, DataSet):
self.data = DataSet(self.data, self.data.bits)
def __eq__(self, other):
return self.atom == other.atom and self.codeloc == other.codeloc and self.data == other.data
def __repr__(self):
return 'Definition %#x {Atom: %s, Codeloc: %s, Data: %s}' % (id(self), self.atom, self.codeloc, self.data)
def __hash__(self):
return hash((self.atom, self.codeloc, self.data))
@property
def offset(self):
if type(self.atom) is MemoryLocation:
return self.atom.addr
elif type(self.atom) is Register:
return self.atom.reg_offset
else:
raise ValueError('Unsupported operation offset on %s.' % type(self.atom))
@property
def size(self):
if type(self.atom) is MemoryLocation:
return self.atom.size
elif type(self.atom) is Register:
return self.atom.size
else:
raise ValueError('Unsupported operation size on %s.' % type(self.atom))
|
Markdown | UTF-8 | 4,698 | 2.796875 | 3 | [] | no_license | ---
description: "low fat Chocolate Cupcakes w/ Vanilla Buttercream Frosting | how to cook Chocolate Cupcakes w/ Vanilla Buttercream Frosting"
title: "low fat Chocolate Cupcakes w/ Vanilla Buttercream Frosting | how to cook Chocolate Cupcakes w/ Vanilla Buttercream Frosting"
slug: 447-low-fat-chocolate-cupcakes-w-vanilla-buttercream-frosting-how-to-cook-chocolate-cupcakes-w-vanilla-buttercream-frosting
date: 2020-10-03T20:21:00.937Z
image: https://img-global.cpcdn.com/recipes/bf1d6121146317e7/751x532cq70/chocolate-cupcakes-w-vanilla-buttercream-frosting-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/bf1d6121146317e7/751x532cq70/chocolate-cupcakes-w-vanilla-buttercream-frosting-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/bf1d6121146317e7/751x532cq70/chocolate-cupcakes-w-vanilla-buttercream-frosting-recipe-main-photo.jpg
author: Linnie Rice
ratingvalue: 4.2
reviewcount: 7
recipeingredient:
- "3/4 cup unsweetened cocoa powder"
- "3/4 cup flour"
- "1/2 tsp baking powder"
- "1/4 tsp salt"
- "3/4 cup buttermargarine"
- "1 cup sugar"
- "3 eggs"
- "1 tsp vanilla extract"
- "1/2 cup sour cream"
- " frosting"
- "2 cups powdered sugar"
- "1/2 cup margarine"
- "1 1/2 tsp vanilla extract"
- "2 tbsp milk"
recipeinstructions:
- "Sift and set aside the flour, cocoa powder, baking soda and salt."
- "Mix the butter and sugar until light and fluffy. Add and beat in eggs, one at a time, then the vanilla. Gradually add and mix the flour mixture, alternating with sour cream, and ending with flour."
- "Fill up 3/4 of each baking cup with the batter. Bake for approx. 20 minutes at 350°F."
- "FROSTING: mix butter until smooth, beat in powdered sugar, then vanilla and milk."
- "Pipe the buttercream frosting onto the cupcakes. Add strawberries and coconut on top for decoration and extra flavor 🙃(optional)."
categories:
- Recipe
tags:
- chocolate
- cupcakes
- w
katakunci: chocolate cupcakes w
nutrition: 217 calories
recipecuisine: American
preptime: "PT18M"
cooktime: "PT33M"
recipeyield: "1"
recipecategory: Lunch
---

Hey everyone, hope you're having an incredible day today. Today, we're going to make a simple dish, chocolate cupcakes w/ vanilla buttercream frosting. It is one of my favorites food recipe. This time, I am going to make it a little bit unique. This is gonna smell and look delicious.
Chocolate Cupcakes w/ Vanilla Buttercream Frosting is one of the most favored of recent trending foods in the world. It's enjoyed by millions daily. It's easy, it is fast, it tastes delicious. Chocolate Cupcakes w/ Vanilla Buttercream Frosting is something which I have loved my entire life. They are nice and they look fantastic.
To get started with this recipe, we must prepare a few ingredients. You can have chocolate cupcakes w/ vanilla buttercream frosting using 14 ingredients and 5 steps. Here is how you cook that.
<!--inarticleads1-->
##### The ingredients needed to make Chocolate Cupcakes w/ Vanilla Buttercream Frosting:
1. Make ready 3/4 cup unsweetened cocoa powder
1. Make ready 3/4 cup flour
1. Make ready 1/2 tsp baking powder
1. Prepare 1/4 tsp salt
1. Make ready 3/4 cup butter/margarine
1. Prepare 1 cup sugar
1. Make ready 3 eggs
1. Take 1 tsp vanilla extract
1. Make ready 1/2 cup sour cream
1. Make ready frosting:
1. Make ready 2 cups powdered sugar
1. Take 1/2 cup margarine
1. Get 1 1/2 tsp vanilla extract
1. Take 2 tbsp milk
<!--inarticleads2-->
##### Steps to make Chocolate Cupcakes w/ Vanilla Buttercream Frosting:
1. Sift and set aside the flour, cocoa powder, baking soda and salt.
1. Mix the butter and sugar until light and fluffy. Add and beat in eggs, one at a time, then the vanilla. Gradually add and mix the flour mixture, alternating with sour cream, and ending with flour.
1. Fill up 3/4 of each baking cup with the batter. Bake for approx. 20 minutes at 350°F.
1. FROSTING: mix butter until smooth, beat in powdered sugar, then vanilla and milk.
1. Pipe the buttercream frosting onto the cupcakes. Add strawberries and coconut on top for decoration and extra flavor 🙃(optional).
So that is going to wrap it up for this creative food chocolate cupcakes w/ vanilla buttercream frosting recipe. Thank you very much for reading. I'm sure that you can make this at home. There's gonna be more interesting food at home recipes coming up. Don't forget to bookmark this page on your browser, and share it to your family, colleague and friends. Thank you for reading. Go on get cooking!
|
Java | UTF-8 | 10,361 | 2.171875 | 2 | [] | no_license | /*
* JettyDesktop is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* Free Software Foundation,version 3.
*
* JettyDesktop is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* If not, see http://www.gnu.org/licenses/
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or combining
* it with any of the JARS listed in the README.txt (or a modified version of
* (that library), containing parts covered by the terms of that JAR, the
* licensors of this Program grant you additional permission to convey the
* resulting work.
*
* https://github.com/aw20/jettydesktop
*
* May 2013
*/
package org.aw20.jettydesktop.ui;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;
import javax.swing.UIManager;
import javax.swing.WindowConstants;
import org.aw20.jettydesktop.ui.awt.ServerConfig;
import org.aw20.jettydesktop.ui.awt.ServerTab;
public class Start implements ConfigActionInterface {
private static String VERSION = "2.0.6";
private List<ServerConfigMap> serverConfigList;
private JFrame frame;
private JMenu mnServer;
private JMenuItem mAddServerMenuItem;
private JTabbedPane tabbedPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
Start window = new Start();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Start() {
loadSettings();
initialize();
}
private void saveSettings(){
ObjectOutputStream OS;
try {
FileOutputStream out = new FileOutputStream( new File("jettydesktop.settings") );
OS = new ObjectOutputStream( out );
OS.writeObject( serverConfigList );
out.flush();
out.close();
} catch (IOException e) {}
}
private void loadSettings(){
ObjectInputStream ois;
try {
FileInputStream in = new FileInputStream( new File("jettydesktop.settings") );
ois = new ObjectInputStream(in);
serverConfigList = (java.util.List<ServerConfigMap>)ois.readObject();
in.close();
} catch (Exception e) {
serverConfigList = new ArrayList<ServerConfigMap>();
}
}
/**
* Initialise the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setTitle("JettyDesktop v" + VERSION + " by aw2.0 Ltd");
frame.setBounds(100, 100, 610, 414);
frame.setMinimumSize( new Dimension(610, 414) );
frame.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/org/aw20/logo/aw20.jpg")));
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
terminateApp();
}
});
JMenuBar menuBar = new JMenuBar();
frame.setJMenuBar(menuBar);
JMenu mnFile = new JMenu("File");
menuBar.add(mnFile);
JMenuItem mntmExit = new JMenuItem("Exit");
mnFile.add(mntmExit);
mntmExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
terminateApp();
}
});
mnServer = new JMenu("Web App");
menuBar.add(mnServer);
mAddServerMenuItem = new JMenuItem("< add webapp >");
mAddServerMenuItem.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openConfig( ServerConfigMap.getDefault() );
}
});
rebuildServerMenu();
JMenu mnHelp = new JMenu("Help");
menuBar.add(mnHelp);
JMenuItem mntmSupportSite = new JMenuItem("Visit Home Page");
mntmSupportSite.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create("https://github.com/aw20/jettydesktop/"));
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
mnHelp.add(mntmSupportSite);
JMenuItem mntmBugSite = new JMenuItem("Report Bug/Feature");
mntmBugSite.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create("https://github.com/aw20/jettydesktop/issues"));
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
mnHelp.add(mntmBugSite);
JMenuItem mntmAWSite = new JMenuItem("Visit aw2.0 Ltd");
mntmAWSite.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
java.awt.Desktop.getDesktop().browse(java.net.URI.create("http://aw20.is/"));
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
mnHelp.add(mntmAWSite);
mnHelp.addSeparator();
JMenuItem mntmAbout = new JMenuItem("About");
mntmAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog (null, "Designed/Developed by aw2.0 Ltd\r\nhttp://aw20.is/\r\n\r\nGPLv3.0 License\r\nv" + VERSION + " May 2013", "About JettyDesktop", JOptionPane.INFORMATION_MESSAGE);
}
});
mnHelp.add(mntmAbout);
tabbedPane = new JTabbedPane(JTabbedPane.TOP);
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
}
protected boolean terminateApp() {
int totalRunning = 0;
for ( int x=0; x < tabbedPane.getComponentCount(); x++ ){
ServerTab sT = (ServerTab)tabbedPane.getComponent(x);
if ( sT.isServerRunning() )
totalRunning++;
}
if ( totalRunning == 0 )
System.exit(1);
int result = JOptionPane.showConfirmDialog( this.frame, "You have " + totalRunning + " server(s) still running.\r\n\r\nDo you still wish to terminate?\r\n");
if ( result == JOptionPane.OK_OPTION ){
for ( int x=0; x < tabbedPane.getComponentCount(); x++ ){
ServerTab sT = (ServerTab)tabbedPane.getComponent(x);
if ( sT.isServerRunning() )
sT.stopServer();
}
System.exit(1);
}
return false;
}
private void rebuildServerMenu(){
mnServer.removeAll();
mnServer.add( mAddServerMenuItem );
if ( serverConfigList.isEmpty() )
return;
mnServer.addSeparator();
// Get the names
String[] names = new String[serverConfigList.size()];
for ( int x=0; x < names.length; x++ )
names[x] = serverConfigList.get(x).getName();
Arrays.sort( names );
for ( int x=0; x < names.length; x++ ){
JMenuItem menu = new JMenuItem(names[x]);
menu.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
openServer( ((JMenuItem)e.getSource()).getText() );
}
});
mnServer.add( menu );
}
}
protected void openServer(String servername) {
// See if that one is already open in the tabs
for ( int x=0; x < tabbedPane.getComponentCount(); x++ ){
ServerTab sT = (ServerTab)tabbedPane.getComponent(x);
if ( sT.getConfig().getName().equals(servername) ){
tabbedPane.setSelectedIndex(x);
return;
}
}
// We need to add a new tab
ServerTab sT = new ServerTab( get(servername), this );
tabbedPane.add(sT, servername);
tabbedPane.setSelectedComponent(sT);
}
private ServerConfigMap get(String name){
for ( int x=0; x < serverConfigList.size(); x++ ){
if ( serverConfigList.get(x).getName().equals( name ) ){
return serverConfigList.get(x);
}
}
return null;
}
private void openConfig( ServerConfigMap serverConfigMap ){
ServerConfig popup = new ServerConfig( serverConfigMap );
popup.setVisible(true);
if ( popup.getConfig() == null )
return;
ServerConfigMap scm = popup.getConfig();
// We need to run through the list see if its already there
boolean bFound = false;
for ( int x=0; x < serverConfigList.size(); x++ ){
if ( serverConfigList.get(x).getName().equals( scm.getName() ) ){
serverConfigList.set(x, scm);
bFound = true;
break;
}
}
if ( !bFound )
serverConfigList.add(scm);
saveSettings();
rebuildServerMenu();
// Update the reference if it is used in an active TAB
for ( int x=0; x < tabbedPane.getComponentCount(); x++ ){
ServerTab sT = (ServerTab)tabbedPane.getComponent(x);
if ( sT.getConfig().getName().equals(scm.getName()) ){
sT.setConfig(scm);
break;
}
}
}
@Override
public void onEdit(ServerConfigMap scm) {
openConfig(scm);
}
@Override
public void onDelete(ServerConfigMap scm) {
// Remove from the tabs
onClose(scm);
// Remove from the list
for ( int x=0; x < serverConfigList.size(); x++ ){
if ( serverConfigList.get(x).getName().equals( scm.getName() ) ){
serverConfigList.remove(x);
break;
}
}
saveSettings();
rebuildServerMenu();
}
@Override
public void onClose(ServerConfigMap scm) {
// Remove from the tabs
for ( int x=0; x < tabbedPane.getComponentCount(); x++ ){
ServerTab sT = (ServerTab)tabbedPane.getComponent(x);
if ( sT.getConfig().getName().equals(scm.getName()) ){
tabbedPane.remove(x);
break;
}
}
}
}
|
Java | UTF-8 | 1,336 | 2.234375 | 2 | [] | no_license | package com.wz.option;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wz.test.AdminCRUD;
import com.wz.test.MusicTypeCRUD;
public class listMusicType extends BaseServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//当前页
int currentPage=1;
//默认的页面条数的大小
int pageSize=10;
//总的页面数
int totle=0;
if(request.getParameter("page")!=null){
currentPage=Integer.parseInt(request.getParameter("page").toString());
};
MusicTypeCRUD musicType = new MusicTypeCRUD();
request.setAttribute("musicType", musicType.getMusicTypePage(currentPage,pageSize));
int size=musicType.getMusicType().size()%pageSize;
//通过总页数和页面大小来计算页数
if(size==0){
totle=musicType.getMusicType().size()/pageSize;
}else{
totle=musicType.getMusicType().size()/pageSize+1;
}
request.setAttribute("currentPage",currentPage );
request.setAttribute("totle", totle);
request.getRequestDispatcher("/Admin/MusicType/ListMusicType.jsp")
.forward(request, response);
}
}
|
Rust | UTF-8 | 2,600 | 3.0625 | 3 | [] | no_license | use super::LabeledGraph;
pub fn djikstra<T>(g: &LabeledGraph<T>, s: usize) -> Vec<Option<T>>
where
T: std::ops::Add<Output = T> + Ord + Default + Copy,
{
use std::{cmp::Ordering, collections::BinaryHeap};
struct Node<T>(usize, T);
impl<T: PartialEq> PartialEq for Node<T> {
fn eq(&self, other: &Self) -> bool {
self.1 == other.1
}
}
impl<T: Eq> Eq for Node<T> {}
impl<T: PartialOrd> PartialOrd for Node<T> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
other.1.partial_cmp(&self.1)
}
}
impl<T: Ord> Ord for Node<T> {
fn cmp(&self, other: &Self) -> Ordering {
other.1.cmp(&self.1)
}
}
let mut dist = vec![None; g.len()];
dist[s] = Some(T::default());
let mut que = BinaryHeap::new();
que.push(Node(s, T::default()));
while let Some(Node(u, d)) = que.pop() {
if matches!(dist[u], Some(du) if d > du) {
continue;
}
for &(v, w) in &g[u] {
let dsuv = d + w;
if dist[v].map(|dv| dsuv < dv).unwrap_or(true) {
dist[v] = Some(dsuv);
que.push(Node(v, dsuv));
}
}
}
dist
}
#[cfg(test)]
mod tests {
use crate::{graph::LabeledGraph, random::*};
#[test]
fn djikstra() {
const N: usize = 13;
const M: usize = 29;
let mut rand = Pcg::seed_from_u64(819);
for _ in 0..10 {
let mut g = LabeledGraph::builder(N);
for _ in 0..M {
let u = rand.next_u32() as usize % N;
let v = rand.next_u32() as usize % N;
let w = rand.next_u32() >> 10;
g.edge(u, v, w);
}
let g = g.build();
let s = rand.next_u32() as usize % N;
let mut dist_bf = vec![None; N];
dist_bf[s] = Some(0);
for _ in 0..N {
for u in 0..N {
if let Some(du) = dist_bf[u] {
for &(v, w) in &g[u] {
if let Some(dv) = dist_bf[v] {
if du + w < dv {
dist_bf[v] = Some(du + w);
}
} else {
dist_bf[v] = Some(du + w);
}
}
}
}
}
let dist_d = super::djikstra(&g, s);
assert_eq!(dist_d, dist_bf);
}
}
}
|
Java | UTF-8 | 352 | 2.5 | 2 | [] | no_license | package com.dream.composite.menu;
/**
* HeadFirstDesignPatterns
* Created by SuSong on 2015-04-14 下午8:26.
*/
public class Waitress {
private MenuComponent menuComponent;
public Waitress(MenuComponent menuComponent){
this.menuComponent = menuComponent;
}
public void printMenu(){
menuComponent.print();
}
}
|
Java | UTF-8 | 322 | 1.96875 | 2 | [] | no_license | package example.spring.social.with.facebook.repository;
import example.spring.social.with.facebook.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.Optional;
public interface UserRepository extends JpaRepository<User,Integer> {
Optional<User> findByEmail(String email);
}
|
Java | UTF-8 | 1,960 | 3.328125 | 3 | [] | no_license | package thread.pool;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class QueueOverflowPolicy {
public static void main(String[] args){
ThreadPoolExecutor executor = new ThreadPoolExecutor(2,
2,
10,
TimeUnit.SECONDS,
new ArrayBlockingQueue(10),
new DefaultThreadFactory(),
new RejectedExecutionHandler() {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
System.out.println(r);
}
});
for(int i=0; i<100; i++){
int j = i;
executor.submit(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+" "+ j);
}
});
}
}
static class DefaultThreadFactory implements ThreadFactory {
private static final AtomicInteger poolNumber = new AtomicInteger(1);
private final ThreadGroup group;
private final AtomicInteger threadNumber = new AtomicInteger(1);
private final String namePrefix;
DefaultThreadFactory() {
SecurityManager s = System.getSecurityManager();
group = (s != null) ? s.getThreadGroup() :
Thread.currentThread().getThreadGroup();
namePrefix = "pool-" +
poolNumber.getAndIncrement() +
"-thread-";
}
public Thread newThread(Runnable r) {
Thread t = new Thread(group, r,
namePrefix + threadNumber.getAndIncrement(),
0);
if (t.isDaemon())
t.setDaemon(false);
if (t.getPriority() != Thread.NORM_PRIORITY)
t.setPriority(Thread.NORM_PRIORITY);
return t;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.