language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C
UTF-8
551
4.28125
4
[]
no_license
#include<stdio.h> int sum(int, int); int product(int, int); void swap(int*, int*); int main(){ int num1, num2; puts("Enter two number:\n"); scanf("%d%d",&num1,&num2); printf("Sum is %d\n",sum(num1, num2)); printf("Porduct is %d\n",product(num1, num2)); printf("Before swapping A= %d, B= %d\n",num1, num2); swap(&num1, &num2); printf("After swapping A= %d, B= %d\n",num1, num2); return 0; } void swap(int *x, int *y){ int temp; temp=*x; *x=*y; *y=temp; } int sum(int x, int y){ return x+y; } int product(int x, int y){ return x*y; }
Markdown
UTF-8
568
2.515625
3
[]
no_license
_Senior Operations Engineer with more than 10 years of experience in DevOps environments—specializing in observability, Kubernetes, large scale time series databases, and physical infrastructures._ In my career I've focused on building with quality. The systems I build are reliable, are maintainable, and have an emphasis on user experience. I want to continue focusing on deep technical work, but I won't shy away from leadership and architecture responsibilities. I'm seeking a mid-size company running Kubernetes and next generation monitoring tools at scale.
Python
UTF-8
1,237
3.578125
4
[]
no_license
# Define an array, where each element will be one line of verse poem_array = [] # Open the LaTeX file created by pandoc containing the text of the poems with open("latex_poems.tex", "r") as poems: lines = poems.readline() for line in poems: # Add each line in the file to a new element in the array poem_array.append(line) for i in range(len(poem_array)-1): # Cycle through the array, adding the \verseline command to all lines # that aren't the final line in a stanza or part of a stanza break if(("\end{stanza}" not in poem_array[i]) and ("\\begin{stanza}" not in poem_array[i]) and ("\end{stanza}" not in poem_array[i+1])): # Each line ends with a newline character, so we need to strip that # out, append "/verseline", and then put the newline character back poem_array[i] = poem_array[i].rstrip("\n") + "\\verseline" +"\n" # Create a file to write to. Cycle through the array again, this time writing # each element (now with appended /verseline) to a new line in our new file. with open("latex_poems_with_verselines.tex", "w+") as poems_with_verselines: for line in poems_with_verselines: new_poems.write(line)
Ruby
UTF-8
564
2.5625
3
[]
no_license
class AnonymousPerson extend ActiveModel::Naming def first_name "Anonym" end def last_name "Användare" end def name first_name end def to_s "Anonym" end def id nil end # Use some dynamic programming voodo for syntactic sugar, again, DRY IT UP! Role.all.each do |role| define_method "#{role.to_s}?" do false end end def has_role?(role) false end def anonymous? true end def has_feature?(feature) false end end
Python
UTF-8
2,647
2.859375
3
[ "MIT" ]
permissive
#!/usr/bin/env python3 from generators.workflows import Workflow from generators.interactive import generate_task_list_interactively from generators.tasks import * import sys import argparse def parse_args(args): """ By default, argparse treats all arguments that begin with '-' or '--' as optional in the help menu (preferring to have required arguments be positional). To get around this, we must define a required group to contain the required arguments This will cause the help menu to be displayed correctly """ parser = argparse.ArgumentParser(description="Either pass file in with '-i' or use '--interactive'") required_group = parser.add_argument_group('required arguments') required_group.add_argument("-o", required=True, metavar='<File.wdl>', help='The location of the output wdl file') required_group.add_argument("--name", required=True, metavar='<String>', help='The name of the workflow') # Truly optional argument parser.add_argument("-i", required=False, metavar='<File>', help="A workflow task list file") parser.add_argument('--interactive', action="store_true", help='Interactive mode', default=False, required=False ) parser.add_argument('--jobID', type=str, metavar='<String>', help='The job ID', default='NA', required=False) # Debug mode is on when the flag is present and is false by default parser.add_argument("-d", action="store_true", help="Turns on debug mode", default=False, required=False) return parser.parse_args(args) def main(args): parsed_args = parse_args(args) if parsed_args.interactive: task_list = generate_task_list_interactively() # Print a summary message to stdOut print("Attempting to build a workflow with the following inputs\n") for task in task_list: print(task.get_input_output_summary_string()) generator = Workflow(workflow_name=parsed_args.name, debug_mode=parsed_args.d, job_id=parsed_args.jobID, input_file=None, task_list=task_list ) else: generator = Workflow(workflow_name=parsed_args.name, debug_mode=parsed_args.d, job_id=parsed_args.jobID, input_file=parsed_args.i, task_list=None ) generator.create_and_write_wdl_file(parsed_args.o) if __name__ == "__main__": main(sys.argv[1:])
Python
UTF-8
3,661
4.25
4
[]
no_license
# 기초 정렬 # 문제 2750번 수 정렬하기 # Sorting(정렬) # O(nlogn) 정렬 : 퀵 정렬(quick sort), 병합 정렬(merge sort), 힙 정렬(heap sort) import sys r = sys.stdin.readline n = int(r()) input_data = list(int(r()) for _ in range(n)) input_data.sort() for i in input_data: print(i) # # 병합 정렬 # def merge_sort(data): # # 리스트가 2개 미만일 경우 그대로 반환 # if len(data) < 2: # return data # # 중간 지점 저장 # mid = len(data) // 2 # # 중간지점을 기점으로 앞리스트와 뒤리스트 리스트 안의 인덱스가 하나가 될때까지 나누기(재귀적) # low_data = merge_sort(data[:mid]) # high_data = merge_sort(data[mid:]) # # 합칠 리스트 생성 # merged_data = [] # l = h = 0 # # 두 리스트 중 하나라도 마지막 인덱스까지 먼저 도달하면 루프 탈출 # while l < len(low_data) and h < len(high_data): # if low_data[l] < high_data[h]: # merged_data.append(low_data[l]) # l += 1 # else: # merged_data.append(high_data[h]) # h += 1 # # 나머지 뒤에 이어붙이기 # merged_data += low_data[l:] # merged_data += high_data[h:] # return merged_data # # 몇개 입력받을 것인지, 빈 리스트 선언 # n = int(input()) # data = [] # # n개만큼 입력받기 # for i in range(n): # data.append(int(input())) # # list.sort(data) # # data = quick_sort(data) # data = merge_sort(data) # # 정렬된것 출력하기 # for i in range(n): # print(data[i]) # # 퀵 정렬(기본 내장 함수: list.sort()) # def quick_sort(data): # # 데이터가 1개 이하라면 그대로 반환 # if len(data) <= 1: # return data # # # 피봇 및 분류할 빈 리스트 선언 (/ : 실수 나누기, // : 나눈 몫) # pivot = data[len(data) // 2] # lesser_data, equal_data, greater_data = [], [], [] # # # 피봇을 기준으로 크고 작은 값 나누기 # for num in data: # if num < pivot: # lesser_data.append(num) # elif num > pivot: # greater_data.append(num) # else: # equal_data.append(num) # # # 피봇으로 쓰인 배열은 다시 호출할 필요가 없으므로 작은 것과 큰 것에서만 재분류를 위해 재귀적으로 호출 # return quick_sort(lesser_data) + equal_data + quick_sort(greater_data) # # 퀵 정렬 최적화(보완이 필요함) # def quick_sort(data): # # 정렬 범위를 받는 함수 # def sort(low, high): # # 인덱스가 역전되면 그냥 탈출 # if high <= low: # return # # mid = partition(low, high) # sort(low, mid - 1) # sort(mid, high) # return data # # # 피봇 기준으로 작은값은 왼쪽, 큰값은 오른쪽으로 정렬하는 함수 # def partition(low, high): # # 피봇은 인덱스의 중앙값 # pivot = data[(low + high) // 2] # # # 왼쪽에서 피봇보다 큰값 또는 오른쪽에서 피봇보다 작은값 찾아서 바꿔주기(반복) # while low <= high: # while data[low] < pivot: # low += 1 # while data[high] < pivot: # high -= 1 # if low <= high: # data[low], data[high] = data[high], data[low] # low, high = low + 1, high - 1 # return low # # # 배열의 시작과 끝 인덱스 반환 # return sort(0, len(data) - 1) # 입력 예시 # 5 # 5 # 2 # 3 # 4 # 1 # 출력 예시 # 1 # 2 # 3 # 4 # 5
C#
UTF-8
1,638
2.53125
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraScroll : MonoBehaviour { public float zoomSpeed = 2.0f; public float smoothSpeed = 2.0f; public float minOrtho = 3.0f; public float maxOrtho = 5.0f; public float minY = 0; public float maxY = 3.0f; private float targetOrtho; private float targetY; // Use this for initialization void Start () { targetOrtho = Camera.main.orthographicSize; targetY = transform.position.y; } // FixedUpdate is called once per frame void Update () { // if the player holds D, zoom out the camera if (Input.GetKey(KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) { zoomOut (); } else { zoomIn (); } } // zoom in void zoomIn() { // position targetY = Mathf.MoveTowards (transform.position.y, maxY, smoothSpeed * Time.deltaTime); transform.position = new Vector3 (transform.position.x, targetY, transform.position.z); // ortho targetOrtho -= zoomSpeed; targetOrtho = Mathf.Clamp (targetOrtho, minOrtho, maxOrtho); Camera.main.orthographicSize = Mathf.MoveTowards (Camera.main.orthographicSize, targetOrtho, smoothSpeed * Time.deltaTime); } // zoom out void zoomOut() { // position targetY = Mathf.MoveTowards (transform.position.y, minY, smoothSpeed * Time.deltaTime); transform.position = new Vector3 (transform.position.x, targetY, transform.position.z); // ortho targetOrtho += zoomSpeed; targetOrtho = Mathf.Clamp (targetOrtho, minOrtho, maxOrtho); Camera.main.orthographicSize = Mathf.MoveTowards (Camera.main.orthographicSize, targetOrtho, smoothSpeed * Time.deltaTime); } }
PHP
UTF-8
231
2.859375
3
[]
no_license
<?php require 'connectie.php'; $sql = 'SELECT * FROM gebruikers'; try{ $result = $db->query($sql); foreach ($result as $row){ echo $row['voornaam'] . "<br>"; } }catch(PDOexception $e){ echo "Error: " . $e; }
JavaScript
UTF-8
1,544
2.65625
3
[]
no_license
function itemChange(){ var changeItem = ["배송준비","배송중","배송완료"]; var changeItem2 = ["취소대기","취소완료"]; var selectItem = $("#category").val(); $('#subcategory').empty(); if(selectItem == "1"){ var option = $("<option value=''>분류 선택</option>"); $('#subcategory').append(option); for(var count = 0; count < changeItem.length; count++){ var option = $("<option value='"+changeItem[count]+"'>"+changeItem[count]+"</option>"); $('#subcategory').append(option); } $('#searchWord').attr("disabled", true); } else if(selectItem == "2"){ var option = $("<option value=''>분류 선택</option>"); $('#subcategory').append(option); for(var count = 0; count < changeItem2.length; count++){ var option = $("<option value='"+changeItem2[count]+"'>"+changeItem2[count]+"</option>"); $('#subcategory').append(option); } $('#searchWord').attr("disabled", true); } else if(selectItem == "3") { var option = $("<option value='3' selected disable>아이디</option>"); $('#subcategory').append(option); $('#searchWord').attr("disabled", false); } else{ var option = $("<option value='4' selected disable>주문번호</option>"); $('#subcategory').append(option); $('#searchWord').attr("disabled", false); } } /*function checksts(){ if($('#stsCancel').val() == $('#stsCancelSel').val() && $('#stsDeliverySel').val() == $('#stsDelivery').val()){ alert("변동 사항이 없습니다"); return false; } return true; }*/
C++
UTF-8
585
2.875
3
[]
no_license
#include "servo.cpp" #include <csignal> #include <iostream> #include "mraa.hpp" int running=1; void sig_handler(int signo) { if (signo == SIGINT) { printf("closing PWM nicely\n"); running = 0; } }; int main() { signal(SIGINT, sig_handler); Servo claw(15),doorl(13,false),doorr(12,false); while(running) { claw.write(0.2); doorl.write(0.2); doorr.write(0.2); std::cout<<"wriitng 0.2"<<std::endl; sleep(1); claw.write(0.9); doorl.write(0.9); doorr.write(0.9); sleep(1); } claw.release(); doorl.release(); doorr.release(); return 0; }
Go
UTF-8
972
2.734375
3
[]
no_license
package handle import ( "github.com/gin-gonic/gin" "github.com/sirupsen/logrus" "go-dynamicKey/pkg/errno" "net/http" ) type Result struct { Code int `json:"code"` Message string `json:"message"` Data interface{} `json:"data"` } func SendBadRequest(c *gin.Context) { c.Writer.WriteHeader(http.StatusBadRequest) } func SendNotFound(c *gin.Context) { c.Writer.WriteHeader(http.StatusNotFound) } func SendInternalServerError(c *gin.Context) { c.Writer.WriteHeader(http.StatusInternalServerError) } func SendContent(c *gin.Context, data []byte) { _, err := c.Writer.Write(data) if err != nil { logrus.Error("write error : ", err) } } func SendResult(c *gin.Context, err error, data interface{}) { code, message := errno.DecodeErr(err) // always return http.StatusOK c.JSON(http.StatusOK, Result{ Code: code, Message: message, Data: data, }) }
Markdown
UTF-8
600
2.9375
3
[]
no_license
# crypto ## Algoritmo de criptografia Criptografia inspirada pela cifra de César (ouvi sobre em uma aula), os caracteres das letras são adicionados da quantidade de letras presentes na palavra em que estão ("oi" vira "qk", e "oii" vira "rll"). Letras maiúsculas continuam maiúsculas, e o mesmo para minúsculas. Os números se mantém os mesmos. Além de letras e números, suporta os caracteres ```,```, ```.```, ```?``` e ```-```. Underlines (```_```) são transformados em espaços. * O arquivo ```crypto.java``` criptografa palavras/frases comuns, enquanto ```desCrypto.java``` as decifra.
C#
UTF-8
2,578
2.703125
3
[]
no_license
/********************************************************************** * Autor: Leandro Dornela Ribeiro * Contato: leandrodornela@ice.ufjf.br * Data de criação: 12/2018 * Modificação: * ********************************************************************/ using UnityEngine; /// <summary> /// Classe mãe para os estados dos inimigos. Cuidado ao utilizar os metodos de /// update e start nas classes derivadas. /// </summary> public class EnemyState : MonoBehaviour { // Struct para retornar e repassar um novo estado e um input. public struct NewState { public EnemyState state; public NewState(EnemyState st) { state = st; } public void SetNewState(EnemyState st) { state = st; } public void Reset() { state = null; } } // Novo estado. protected NewState newState = new NewState(null); // Administrador de estados. protected EnemyStateManager stateManager; // Script do inimigo. protected Enemy enemy; void Start() { stateManager = GetComponent<EnemyStateManager>(); enemy = GetComponent<Enemy>(); StartState(); } /// <summary> /// Metodo de inicialisação para as classes derivadas. /// </summary> public virtual void StartState() { } /// <summary> /// Executa ações obrigatorias antes deentrar no estado. /// </summary> public void PrepareToEnterState() { newState.Reset(); } /// <summary> /// Ações tomadas ao entrar no estado. /// </summary> public virtual void EnterState(NewState lastState) { } /// <summary> /// Executa o update e retorna null para continuar no mesmo estado ou retorna o novo estado. /// </summary> public virtual NewState UpdateState() { return newState; } /// <summary> /// Executa o fixed update e retorna null para continuar no mesmo estado ou retorna o novo estado. /// </summary> public virtual NewState FixedUpdateState() { return newState; } /// <summary> /// Executa as ações para sair do estado. /// </summary> public virtual void ExitState() { } /// <summary> /// Funções para tratamento de colisão camadas pelo adiministrados de estados. /// </summary> public virtual void TriggerEnter(Collider col) { } public virtual void TriggerExit(Collider col) { } public virtual void CollisionEnter(Collision col) { } }
Java
UTF-8
5,274
2.203125
2
[]
no_license
package com.lithouse.client; import static com.lithouse.client.Constants.DEBUG_TAG; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.util.Log; import com.lithouse.client.exception.LithouseClientException; import com.lithouse.client.model.Record; class HttpHelper { private static final String apiEndpoint = "http://api.lithouse.co/v1/groups/"; private static final int CONNECTION_TIMEOUT = 10000; private static String buildUri ( String groupId ) { String uri = apiEndpoint + groupId + "/records"; Log.d ( DEBUG_TAG, uri ); return uri; } public static void send ( List < Record > records, String appKey, String groupId ) throws ClientProtocolException, IOException, ParseException, JSONException { if ( records == null || records.isEmpty ( ) ) { throw new LithouseClientException ( "missing record list" ); } HttpPost httpPost = new HttpPost ( buildUri ( groupId ) ); httpPost.setHeader ( "appKey", appKey ); httpPost.setHeader ( "Content-type", "application/json" ); httpPost.setEntity ( new StringEntity ( serializeRecordsToJSON ( records ) )); convertHttpResponseToJSON ( getHttpClient ( ).execute ( httpPost ) ); } public static ArrayList < Record > receive ( String appKey, String groupId, List < String > deviceIds, List < String > channels ) throws ParseException, ClientProtocolException, IOException, JSONException { StringBuilder uri = new StringBuilder ( buildUri ( groupId ) ); boolean isFirst = true; if ( deviceIds != null && !deviceIds.isEmpty ( ) ) { for ( String deviceId : deviceIds ) { if ( isFirst ) { uri.append ( "?deviceId=" ); isFirst = false; } else { uri.append ( "&deviceId=" ); } uri.append ( deviceId ); } } if ( channels != null && !channels.isEmpty ( ) ) { for ( String channel : channels ) { if ( isFirst ) { uri.append ( "?channel=" ); isFirst = false; } else { uri.append ( "&channel=" ); } uri.append ( channel ); } } HttpGet httpGet = new HttpGet ( uri.toString ( ) ); httpGet.setHeader ( "appKey", appKey ); return deSerializeJSONToReocrds ( convertHttpResponseToJSON ( getHttpClient ( ).execute ( httpGet ))); } private static JSONObject convertHttpResponseToJSON ( HttpResponse response ) throws ParseException, IOException, JSONException { JSONObject httpReturn; HttpEntity entity = response.getEntity ( ); if ( entity != null ) { String returnString = EntityUtils.toString ( entity ); Log.d ( DEBUG_TAG, returnString ); httpReturn = new JSONObject ( returnString ); } else { throw new LithouseClientException ( "server failed to respond" ); } int httpStatusCode = response.getStatusLine ( ).getStatusCode ( ); if ( httpStatusCode >= 300 ) { throw new LithouseClientException ( httpReturn.getString ( "message" ) ); } return httpReturn; } private static String serializeRecordsToJSON ( List < Record > records ) { if ( records == null || records.isEmpty ( )) return "{}"; StringBuilder result = new StringBuilder ( ); result.append ( "{\"records\":[" ); result.append ( records.get ( 0 ).toString ( ) ); for ( int i = 1; i < records.size ( ) ; i++ ) { result.append ( "," ); result.append ( records.get ( i ).toString ( ) ); } result.append ( "]}" ); Log.d ( DEBUG_TAG, result.toString ( ) ); return result.toString ( ); } private static ArrayList < Record > deSerializeJSONToReocrds ( JSONObject jsonResult ) { ArrayList < Record > records = new ArrayList < Record > ( ); if ( jsonResult != null ) { JSONArray jsonRecords; try { jsonRecords = jsonResult.getJSONArray ( "records" ); } catch ( JSONException e ) { Log.e ( DEBUG_TAG, e.getMessage ( ) ); return records; } for ( int i = 0; i < jsonRecords.length ( ); i++ ) { try { JSONObject jsonRecord = jsonRecords.getJSONObject ( i ); records.add ( new Record ( jsonRecord.getString ( "deviceId" ), jsonRecord.getString ( "channel" ), jsonRecord.getString ( "data" ), jsonRecord.getString ( "timestamp" ))); } catch ( JSONException e ) { Log.e ( DEBUG_TAG, e.getMessage ( ) ); } } } return records; } private static HttpClient getHttpClient ( ) { HttpClient httpClient = new DefaultHttpClient ( ); final HttpParams httpParameters = httpClient.getParams ( ); HttpConnectionParams.setConnectionTimeout ( httpParameters, CONNECTION_TIMEOUT ); return httpClient; } }
Python
UTF-8
3,940
3.125
3
[ "MIT" ]
permissive
# Module to persist (save/load) profiles created in the application Keep Up The Pace import shelve from random import randrange import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../..'))) import libs.applibs.profilem.profile as profile import libs.applibs.profilem.enumandconst as enumandconst def loadprofiles(): ''' Load all the previous saved profiles in a list and return the list ''' profilelist = [] try: shelf = shelve.open("profileshelf") if (len(shelf) != 0): profilelist = list(shelf.values()) #TODO iterate the list and populate the registry with all the profiles for p in profilelist: p.addToRegistry() return profilelist finally: shelf.close def getDefaultProfileFromShelf(): ''' Load all the previous saved profiles in a list and extract the one market as default. Return both the list and the default profile ''' pl = loadprofiles() profiletoreturn = None if (len(pl) !=0): for aProfile in pl: if aProfile.isdefault: profiletoreturn = aProfile if (profiletoreturn is None): #no default profile found, return the first one profiletoreturn = pl[0] profiletoreturn.isdefault = True return pl, profiletoreturn def saveprofiles(): ''' Save all the instances of the class Profile ''' try: shelf = shelve.open('profileshelf') for ProfileObject in profile.Profile._registry: id = str(ProfileObject.uid) shelf[id] = ProfileObject finally: shelf.close def deleteprofile(Profileinstance): ''' Delete an instance of the class Profile from the shelf ''' if isinstance(Profileinstance, profile.Profile): try: shelf = shelve.open('profileshelf') if str(Profileinstance.id) in shelf: id = str(Profileinstance.uid) del shelf[id] finally: shelf.close def clearProfiles(): ''' Clear all previously saved profiles ''' try: shelf = shelve.open('profileshelf') if len(shelf) != 0: shelf.clear() finally: shelf.close if __name__ == "__main__": # verify that the shelf is empty. Empty it otherwise clearProfiles() # create 2 profiles FirstProfile = profile.Profile('test1') FirstProfile.age = 35 FirstProfile.isdefault = True FirstProfile.gender = enumandconst.Gender.FEMALE FirstProfile.weightIntegerPart = 60 FirstProfile.weightDecimalPart = 0 FirstProfile.heightIntegerPart = 1 FirstProfile.heightDecimalPart = 68 FirstProfile.metricChoice = enumandconst.MetricChoice.ISO FirstProfile.computeBMI() SecondProfile = profile.Profile('test2') SecondProfile.age = 35 SecondProfile.gender = enumandconst.Gender.FEMALE SecondProfile.weightIntegerPart = 60 SecondProfile.weightDecimalPart = 0 SecondProfile.heightIntegerPart = 1 SecondProfile.heightDecimalPart = 68 SecondProfile.metricChoice = enumandconst.MetricChoice.ISO SecondProfile.computeBMI() # save then display saved profiles (2 expected) saveprofiles() profileList = loadprofiles() for pr in profileList: print(pr.profileName) if pr.isdefault: print('That one was default') # get the default one and print its name l, p = getDefaultProfileFromShelf() print(p.profileName) print('it was again the default') # delete one profile position = randrange(0, 1) aProfile = profileList[position] deleteprofile(aProfile) # display saved profiles (one expected) profileList = loadprofiles() for pr in profileList: print(pr.profileName) # delete all save profiles clearProfiles()
Java
UTF-8
622
2.1875
2
[]
no_license
package com.student.reg.dto; public class StudentCourseDTO { private int studentcourseID; private int userId; private int courseId; public int getStudentcourseID() { return studentcourseID; } public void setStudentcourseID(int studentcourseID) { this.studentcourseID = studentcourseID; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public int getCourseId() { return courseId; } public void setCourseId(int courseId) { this.courseId = courseId; } }
Markdown
UTF-8
640
2.6875
3
[]
no_license
# GNU_Radio_Guitar # Description This project uses GNU Radio Companion to create digitial guitar pedals. I created 3 pedals for the guitar. They include: * Cosine Modulation (ie Tremelo) * Delay * Railing (ie Overdrive) # Installation The attached files can be simply run through the GNU Radio Companion GUI. # Hardware For my setup, I used a USB Soundcard, a pre-amp for my guitar, and 3 1/4" cables. Choosing the proper audio input/output allows audio to enter GRC processing, and be outputted to either computer speakers or a full-fledged guitar amp. I also believe the popular "Rocksmith" guitar cable should work with this system.
JavaScript
UTF-8
546
2.625
3
[ "MIT", "BSD-3-Clause" ]
permissive
var logic = function( currentDateTime ){ // 'this' is jquery object datetimepicker if(currentDateTime!==null){ if( currentDateTime.today()===newDate.today() ){ this.setOptions({ minTime:currentTime }); }else{ this.setOptions({ minTime:'0:00' }); } } }; jQuery('#timeStart1').datetimepicker({ format:'Y-m-d H:i', minDate: Date.now(), onChangeDateTime:logic, onShow:logic }); jQuery('#timeEnd1').datetimepicker({ format:'Y-m-d H:i', minDate: Date.now(), onChangeDateTime:logic, onShow:logic });
C
UTF-8
1,129
3.484375
3
[]
no_license
#include<stdio.h> #include<stdlib.h> struct stack{ int max; char ch[20]; int top; }; void push(char element,char *st,int *top){ *top=*top+1; st[*top]=element; } char pop(struct stack *st){ if(st->top==-1) return -1; char ch=st->ch[st->top]; st->top-=1; return ch; } void display(char postfix[]){ printf("Testing\n"); puts(postfix); } int isOperand(char a){ if(a=='+' || a=='-' || a=='*' || a=='/') return 0; else return 1; } int precedenceCheck(char a){ if(a=='+' || a=='-') return 1; else if(a=='*' || a=='/') return 2; return 0; } void convert(struct stack *st,char infix[]){ int i=0,j=0; char postfix[20]; while(infix[i]!='\0'){ if(isOperand(infix[i])) postfix[j++]=infix[i++]; else if(precedenceCheck(infix[i])>precedenceCheck(st->ch[st->top])) push(infix[i++],st->ch,&st->top); else postfix[j++]=pop(st); } //printf("Testing"); while(st->top>=0) postfix[j++]=pop(st); postfix[j]='\0'; display(postfix); } int main(){ struct stack st; st.top=-1; st.max=10; char a[10]; printf("Enter the infix expression\n"); gets(a); //puts(a); convert(&st,a); return 0; }
JavaScript
UTF-8
4,483
2.515625
3
[]
no_license
const token = document.getElementById("_csrf").value; Vue.http.headers.common['X-CSRF-TOKEN'] = token; var app = new Vue({ el: '#display-manager', data: { display: { id: 0, name: '', diagonal: '', density: '', idDisplayType: 0, idResolution: 0 }, displays: [], resolutions: [], displayTypes: [], isValidated: false, spinnerClass: 'spinner-border' }, created: function () { Vue.resource('/api/displays').get().then(result => { result.json().then(data => { data.forEach(display => { this.displays.push(display); }) }) }); this.getResolutions(); this.getDisplayTypes(); }, methods: { updateData() { this.getDisplayTypes(); this.getResolutions(); }, getDisplayTypes() { this.displayTypes = []; Vue.resource('/api/display-types').get().then(result => { result.json().then(data => { if (data.length > 0) { this.display.displayType = data[0]; } data.forEach(displayType => { this.displayTypes.push(displayType); }) }) }); }, getResolutions() { this.resolutions = []; Vue.resource('/api/resolutions').get().then(result => { result.json().then(data => { if (data.length > 0) { this.display.resolution = data[0]; } data.forEach(resolution => { this.resolutions.push(resolution); }) }) }); }, add() { this.isValidated = true; if (!isValid(this.display.name, $("#name"))) { return; } enableButton(false, $("#spinner"), $("#btnAdd")); Vue.resource('/api/displays').save(this.display) .then(result => { this.isValidated = false; this.display.name = ''; this.display.density = ''; // this.display.diagonal = ''; result.json().then(data => { this.displays.push(data); }); }) .catch(error => { error.json().then(data => { alert(data.message) }); }) .finally(() => { enableButton(true, $("#spinner"), $("#btnAdd")); } ); }, remove(id, position) { Vue.resource('/api/displays{/id}').delete({id: id}).then(result => this.displays.splice(position, 1) ); }, update(display) { if (display.name.isEmpty()) { return } enableButton(false, $("#spinner" + display.id), $("#btnUpdate" + display.id)); Vue.resource('/api/displays{/id}').update({id: display.id}, display) .then(result => { } ) .catch(error => { error.json().then(data => { alert(data.message) }); }) .finally(() => { enableButton(true, $("#spinner" + display.id), $("#btnUpdate" + display.id)); } ); }, onChange(display, position) { //let id = "btnUpdate" + display.id; //document.getElementById(id).disabled = false; } } }); function isValid(name, view) { let errorClass = 'is-invalid'; if (name.isEmpty()) { view.addClass(errorClass); return false; } else { view.removeClass(errorClass); return true; } } function enableButton(isEnabled, viewSpinner, viewButton) { let spinnerClass = 'spinner-border'; if (!isEnabled) { viewButton.prop("disabled", true); viewSpinner.addClass(spinnerClass); } else { viewButton.prop("disabled", false); viewSpinner.removeClass(spinnerClass); } }
TypeScript
UTF-8
166
2.65625
3
[]
no_license
export class Core { constructor() { console.log('Core module loaded!'); } getName(name: string): string { return `Hello ${name}`; } }
C++
WINDOWS-1251
18,401
3.5
4
[]
no_license
#include<iostream> #include<vector> #include<string> #include<set> #include<deque> #include<map> using namespace std; class vertex;// , edge class edge { vertex* begin;//и , vertex* end;// public: edge() { this->begin = 0; this->end = 0; } edge(vertex* Begin, vertex* End) { this->begin = Begin; this->end = End; } vertex* Begin() { return this->begin; } vertex* End() { return this->end; } void setBegin (vertex* Begin)// vertex { this->begin = Begin; } void setEnd (vertex* End) { this->end = End; } }; class vertex// { string name;// vector<edge*> date;// , "" edge* parent;// , "" public: vertex (string Name) { name = Name; parent = 0; } ~vertex()// , , { name.~basic_string(); free (parent); for ( int i=0 ; i < date.size() ; i++) { date[i]->End()->~vertex(); } date.~vector(); } void addEdge (vertex* End) { edge* temp = new edge(this,End); date.push_back(temp); End->parent = temp; } string Name() { return name; } int rang()// "" { return date.size(); } edge* operator[](int number)// , { return date[number]; } edge* Parent () { return parent; } void Print()// , , "->" { for ( int i = 0; i < date.size() ; i++) { cout<<name<<" -> "<<date[i]->End()->Name()<<endl; date[i]->End()->Print(); } } bool compare (vertex *other)// , { if ( (this->name != other->name) || (this->date.size() != other->date.size() ) ) return false;// , //- . for (int i=0 ; i < this->date.size() ; i++)// , , . // , ( - ). { bool flag = 0;// , for (int j=0 ; j < other->date.size() ; j++) { if ( this->date[i]->End()->compare( other->date[j]->End() ) ) flag = 1; } if (!flag) return false;// , } return true;// , } }; class DFSiterator// { vertex* begin;// edge* last;// , vertex* now;// , public: DFSiterator(vertex* begin) { this->begin = begin; now = begin; last = 0; } DFSiterator operator ++(int) /* ++, : , , ( last) ... , , , , . */ { bool flag = true;// , , , . while (flag)// , { edge* nextEdge = 0;// , for (int i = 0; i < now->rang() ; i++) { if ( ( (*now)[i] == last) && (i != now->rang() -1 ) ) // , , // {// , - , 0, nextEdge = (*now)[ i + 1]; flag = false; break; } if ( ( (*now)[i] == last) && (i == now->rang() -1 ) )// , { nextEdge = now->Parent(); } } if ( (now == begin) && (now->rang() == 0 ) ) // - { break; } if (nextEdge == 0 && now == begin && last != 0)// , 0 //( , , ) { flag = 0; break; } if ( nextEdge == 0 && now->rang() != 0)// 0 (- ) 0, , // "" { nextEdge = (*now)[0]; flag = 0; } if ( nextEdge == 0 && now->rang() == 0)// 0 (- ) - 0, , { nextEdge = now->Parent(); } if (flag == 0)// , 0, { now = nextEdge->End(); last = nextEdge; } else// { now = nextEdge->Begin(); last = nextEdge; } } return *this; } vertex* operator ->() { return now; } bool end()// , ( ) { if (begin->rang() != 0) return ( (now == begin) && (last != 0) ); else return true; } void reuse()// ( "DFS ") { now = begin; last = 0; } }; void CreateTree (vertex* begin, int* number, int max, set<int> *name_space) /* , begin, number , max - , name_space - ( ). */ { int rang = rand() % 4;// for (int i=0 ; i < rang ; i++)// { if ( (*number) == max) break;// , char* temp = new char();// string int new_name = ( rand() % (max-1) ) + 1;// while ( name_space->find(new_name) != name_space->end() ) new_name = ( rand() % (max-1) ) + 1;// ( name_space) (*name_space).insert(new_name);// name_space , sprintf(temp,"%d", new_name );// (*number)++; string temp_String(temp);// vertex* temp_vertex = new vertex(temp_String);// begin->addEdge(temp_vertex);// CreateTree (temp_vertex , number , max, name_space);// } } vector<string> BFS(vertex* begin)// , { deque<vertex*> que; vector<string> result; que.push_back(begin); result.push_back( begin->Name() ); while(!que.empty()) { vertex* temp = que.front(); que.pop_front(); for ( int i=0 ; i < temp->rang() ; i++) { que.push_back( (*temp)[i]->End() ); result.push_back( (*temp)[i]->End()->Name() ); } } return result; } vector< vector<string> > Level_BFS(vertex *begin) // , // - , "" 1- { deque<pair<vertex*,int>> que; vector<vector<string>> result; que.push_back( pair<vertex*,int>( begin, 1) ); result.push_back ( vector<string> (1) ); result[0][0] = begin->Name(); while(!que.empty() ) { vertex* temp = que.front().first; int level = que.front().second; que.pop_front(); if ( (result.size() == level) && (temp->rang()!=0) ) result.push_back(vector<string> () ); for ( int i=0 ; i < temp->rang() ; i++) { que.push_back( pair <vertex*,int> ( (*temp)[i]->End() , level+1 ) ); result[level].push_back( (*temp)[i]->End()->Name() ); } } return result; } vector< vector<string> > Recuva_Level_BFS( vector<string> bfs , DFSiterator iterator) /* , , DFS BFS */ { iterator.reuse(); vector< vector<string> > result(1); result[0].push_back( iterator->Name() );// iterator++;// int level = 0;// , bool flag = 0;// , , ... set<string> data;// , data.insert( result[0][0] ); for ( int i=1 ; i < bfs.size() ; i++ )// { while ( data.find( iterator->Name() ) != data.end() || iterator.end() ) iterator++;// , if ( iterator->Name() == bfs[i] )// DFS BFS result, BFS { if ( !flag ) // , , { level++; result.push_back(vector<string>() ); flag = 1; } iterator++; } else// ( ), DFS , . , while //( , , , ) // ( )... , // BFS. DFS , BFS, - // , ... :) { flag = 0; } result[level].push_back( bfs[i] ); data.insert( bfs[i] ); } return result; } vertex* Recuva(vector< vector<string> > Level_bfs , DFSiterator iterator) /* , . BFS DFS */ { iterator.reuse(); vertex* result = new vertex( iterator->Name() );// map<string,int> Levels;// map<string,vertex*> memory;// , for (int i=0 ; i < Level_bfs.size() ; i++) for (int j=0 ; j < Level_bfs[i].size() ; j++)// { Levels[ Level_bfs[i][j] ] = i; } vector<int> position( Level_bfs.size() , -1);//, , BFS , "" position[0] = 0; memory[ iterator->Name() ] = result; iterator++; while ( !iterator.end() )// DFS ( DFS BFS 1) { vertex* temp = new vertex( iterator->Name() );// memory [ Level_bfs [ Levels [ iterator->Name() ] - 1 ] [ position [ Levels [ iterator->Name() ] - 1 ] ] ] -> addEdge(temp); // memory , "" . position, ... Level memory [temp->Name() ] = temp;// position [ Levels [ iterator->Name() ] ]++; iterator++; } return result; } void main() { for (int i=1 ; i <= 100 ; i++)// 100 { int number = (rand() % 50) + 1;// ( - ) int* num = new int(1); vertex* Tree = new vertex("0"); set<int>* name_space = new set<int>; CreateTree (Tree , num , number, name_space);// DFSiterator it(Tree); vector<string> bfs = BFS(Tree);// BFS DFS vector< vector<string> >Level_bfs = Recuva_Level_BFS(bfs,it); vertex* Test1 = Recuva(Level_bfs,it); vector<string> bfs_Test = BFS(Test1); DFSiterator it_Test(Test1); vector< vector<string> > Level_bfs_original = Level_BFS(Tree);// vertex* Test2 = Recuva(Level_bfs_original,it); cout<<endl<<"Test "<<i<<endl<<"compare Original Tree and Tree from BFS,DFS ";// , BFS DFS bool flag = 1; if (bfs.size() == bfs_Test.size() ) for (int j=0 ; j < bfs.size() ; j++) { if ( bfs[j] != bfs_Test[j] ) flag = 0; if (j % 5 == 0) cout<<"."; } else flag = 0; it.reuse(); while ( !it.end() ) { if (it->Name() != it_Test->Name() ) flag = 0; it++; it_Test++; } cout<<"..... "; if (flag) cout<<"ok"<<endl; else { cout<<"false"<<endl; break; } cout<<"compare Original Tree and Tree from Level_BFS,DFS .............. ";// if (Tree->compare(Test2) ) cout<<"ok"<<endl<<endl; else { cout<<"false"<<endl<<endl; break; } } system("pause");// . }
C#
UTF-8
885
2.578125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Coopec_Lib { public class PhotoClient { private int id; private string photo; public int Id { get { return id; } set { id = value; } } private int id_client; public int Id_client { get { return id_client; } set { id_client = value; } } public string PhotoPersonne { get { return photo; } set { photo = value; } } public void Enregistrer() { Factory.Instance.Save(this); } public void Supprimer() { Factory.Instance.Delete(this); } public void Modifier() { Factory.Instance.Update(this); } } }
Java
UTF-8
1,252
2.171875
2
[]
no_license
package tech.sosa.triage_assistance_service.applications.application; import org.everit.json.schema.Schema; import org.json.JSONObject; import org.json.JSONTokener; import tech.sosa.triage_assistance_service.shared.application.service.ApplicationRequest; import tech.sosa.triage_assistance_service.shared.application.service.ApplicationService; public class TriageJSONSchemaValidationApplicationService<S, T extends ApplicationRequest> implements ApplicationService<S, T> { private ApplicationService<S, T> proxiedApplicationService; private Schema jsonSchema; private String requestBody; public TriageJSONSchemaValidationApplicationService( ApplicationService<S, T> proxiedApplicationService, Schema jsonSchema, String requestBody) { this.proxiedApplicationService = proxiedApplicationService; this.jsonSchema = jsonSchema; this.requestBody = requestBody; } @Override public S execute(T request) { var json = new JSONObject( new JSONTokener(requestBody) ); jsonSchema.validate(json.getJSONObject("triage")); return proxiedApplicationService.execute(request); } }
Markdown
UTF-8
1,553
3.1875
3
[]
no_license
# My Personal MD Cheatsheet ## Headers ``` # H1 ## H2 ### H3 #### H4 ##### H5 ###### H6 ``` --- ## Emphasis Italics, with *asterisks* or _underscores_. Strong emphasis, aka bold, with **asterisks** or __underscores__. Combined emphasis with **asterisks and _underscores_**. Strikethrough uses two tildes. ~~Scratch this.~~ ___ ## Lists 1. A * Unordered List * Unordered List 2. B --- ## Links [I'm an inline-style link](https://www.google.com) [I'm an inline-style link with title](https://www.google.com "Google's Homepage") [I'm a reference-style link][Arbitrary case-insensitive reference text] [I'm a relative reference to a repository file](../blob/master/LICENSE) [You can use numbers for reference-style link definitions][1] Or leave it empty and use the [link text itself]. URLs and URLs in angle brackets will automatically get turned into links. http://www.example.com or <http://www.example.com> and sometimes example.com (but not on Github, for example). Some text to show that the reference links can follow later. [arbitrary case-insensitive reference text]: https://www.mozilla.org [1]: http://slashdot.org [link text itself]: http://www.reddit.com | Tables | Are | Cool | | ------------- |:-------------:| -----:| | A | B | C --- > Quote <!--- Comentario --> Line (---) --- [*]() Hola **Code** ```javascript var s = "JavaScript syntax highlighting"; alert(s); ``` --- - Hola - [ ] List --- :+1: ```mermaid graph TD; A-->B; A-->C; B-->D; C-->D; A-->C; ```
C++
UTF-8
1,393
3.828125
4
[]
no_license
// 9_6.h // Node.h // 节点类模板 #ifndef NODE_H #define NODE_H template<class T> class Node{ private: Node<T> * next; // 指向后继节点的指针 public: T data; // 数据域 Node (const T &data, Node<T> * next=0); // 构造函数 void insertAfter(Node<T> * p); // 在本结点之后插入一个同类节点P Node<T> * deleteAfter(); // 删除本结点的后继结点,并返回其地址 Node<T> * nextNode(); // 获取后继结点的地址 const Node<T> * nextNode() const; // 获取后继结点的地址 }; // 类的实现部分 // 构造函数,初始化数据和指针成员 template<class T> Node<T>::Node(const T& data, Node<T> * next /* =0*/): data(data), next(next){} // 返回后继结点的指针 template<class T> Node<T> * Node<T>::nextNode(){ return next; } // 返回后继结点的指针 template<class T> const Node<T> * Node<T>::nextNode() const{ return next; } // 在当前结点之后插入一个结点P template<class T> void Node<T>::insertAfter(Node<T> *p){ p->next=next; next=p; } // 删除当前结点的后继结点,并返回其地址 template<class T> Node<T> * Node<T>::deleteAfter(){ Node<T> * tempPtr=next; if(next==0) return 0; next=tempPtr->next; return tempPtr; } #endif
JavaScript
UTF-8
1,866
2.828125
3
[ "MIT" ]
permissive
var buster = typeof window !== 'undefined' ? window.buster : require('buster'); var assert = buster.assert; var fail = buster.referee.fail; var when = require('../when'); var sentinel = {}; function assertFulfilled(s, value) { assert.equals(s.state, 'fulfilled'); assert.same(s.value, value); } function assertRejected(s, reason) { assert.equals(s.state, 'rejected'); assert.same(s.reason, reason); } buster.testCase('when.settle', { 'should settle empty array': function() { return when.settle([]).then(function(settled) { assert.equals(settled.length, 0); }); }, 'should reject if promise for input array rejects': function() { return when.settle(when.reject(sentinel)).then( fail, function(reason) { assert.same(reason, sentinel); } ); }, 'should settle values': function() { var array = [0, 1, sentinel]; return when.settle(array).then(function(settled) { assertFulfilled(settled[0], 0); assertFulfilled(settled[1], 1); assertFulfilled(settled[2], sentinel); }); }, 'should settle promises': function() { var array = [0, when.resolve(sentinel), when.reject(sentinel)]; return when.settle(array).then(function(settled) { assertFulfilled(settled[0], 0); assertFulfilled(settled[1], sentinel); assertRejected(settled[2], sentinel); }); }, 'returned promise should fulfill once all inputs settle': function() { /*global setTimeout*/ var array, p1, p2, resolve, reject; p1 = when.promise(function(r) { resolve = r; }); p2 = when.promise(function(_, r) { reject = r; }); array = [0, p1, p2]; setTimeout(function() { resolve(sentinel); }, 0); setTimeout(function() { reject(sentinel); }, 0); return when.settle(array).then(function(settled) { assertFulfilled(settled[0], 0); assertFulfilled(settled[1], sentinel); assertRejected(settled[2], sentinel); }); } });
C++
UTF-8
623
2.78125
3
[ "MIT" ]
permissive
#ifndef BUTTON_H #define BUTTON_H #include <Particle.h> class Button { String name; String currentStatus; public: uint16_t x0, x1; uint16_t y0, y1; uint16_t w, h; String buttonText; uint16_t textOffsetLeft; uint16_t textOffsetTop; Button(String name, uint16_t x0, uint16_t y0, uint16_t w, uint16_t h, String buttonText, uint16_t textOffsetLeft, uint16_t textOffsetTop); String getName() { return this->name; } bool isPressed(int x, int y); void setStatus(String status) { this->currentStatus = status; } String getStatus() { return this->currentStatus; } }; #endif
Markdown
UTF-8
3,170
3
3
[]
no_license
Exercices : interagir avec une base de données via Python Attention : Afin de garder les choses simples et vous permettre de vous concentrer sur les problématiques liées aux bases de données, les applications que vous produirez dans le cadre de ces exercices seront sans interfaces graphiques et pour un usage théorique sur serveur distant. Exercice 1: Un forum Dans cet exercice, vous réaliserez une application simulant le fonctionnement d’un forum. Votre application sera développée en orienté objet. L’application présentera les fonctionnalités suivantes : - Quand l’utilisateur lance l’application, la page d’accueil lui affiche l’ensemble des messages contenus dans la base de données - Un message est présenté avec le nom de celui qui l’a écrit, la date de publication, l’heure de publication et son id - L’utilisateur peut choisir entre voir les messages (action par défaut), écrire un message ou quitter l’application - Quand l’utilisateur écrit un message, on lui demande successivement le pseudo qu’il souhaite utiliser et le message qu’il souhaite poster Bien entendu pour stocker les messages écrits par les utilisateurs et pouvoir les retrouver par la suite, vous allez les sauvegarder dans une base de données PostgreSQL. Cette base de données ne contiendra qu’une seule table : message, dont voici la structure. id(integer, clé primaire) content(text, non nul) publishing_date(timestampz, non nul) author(varchar maximum 50 caractères, non nul) Pour vous aider, voici l’ordre des étapes que vous pouvez suivre. Ce n’est pas la seule manière de faire mais cela peut vous aider si vous êtes perdu : - Créer la table message via la ligne de commande en veillant à respecter la structure demandée - Tenter de se connecter à la BDD grâce à la librairie Psycopg2, vérifier que la connexion peut s’établir avant de passer à la suite en exécutant le script - Écrire dans un fichier main.py un code capable de récupérer l’action utilisateur et d’effectuer une action spécifique selon la commande rentrée - Créer un fichier de vues contenant deux méthodes, une pour l’affichage des messages et une pour l’écriture d’un message. Pour l’instant, ces commandes ne font rien de particulier si ce n’est un print d’un message de test - Vérifiez que lorsque l’utilisateur demande à voir les message ou à écrire un message ce soit la bonne méthode de la vue qui est appelée dans le fichier main.py - Créer un fichier de modèle contenant deux méthodes, une pour récupérer tous les messages en base de données et une pour enregistrer un message en base de données. Attention cette méthode attend au moins deux arguments, le nom de l’auteur et le contenu de son message - Appeler chaque méthode du modèle dans la méthode correspondante de la vue et vérifier son fonctionnement - Mettre en forme l’affichage des messages - Mettre en forme les inputs pour récupérer les informations nécessaires à la rédaction d’un nouveau message -------------------------------------------------------------------------------------------------------
TypeScript
UTF-8
1,932
2.609375
3
[ "MIT" ]
permissive
import CodeMirror from 'codemirror'; import 'codemirror/addon/mode/simple'; // https://codemirror.net/demo/simplemode.html // TODO support error linting (CodeMirror as any).defineSimpleMode("zaml", { // The start state contains the rules that are initially used start: [ // Block labels {regex: /#[^#\s\n}]+/, token: 'variable-3'}, // Entity tag & block tag without attributes {regex: /{\/?([^\s}]+)}/, token: 'keyword'}, // attribute names {regex: /[^\s{\n]+(?=[::=][^\n])/, token: 'variable-2'}, // Block brackets {regex: /{|}/, token: 'def'}, // Block starting tag {regex: /(?={)[^\s}]+/, token: 'keyword'}, // Entity text content {regex: /\[[^\]]+\]/, token: "string"}, // Block tag {regex: /(?:BLOCK|INLINE)\b/, token: "keyword"}, // Special values {regex: /true|false|null|undefined/, token: "atom"}, // Numbers {regex: /0x[a-f\d]+|[-+]?(?:\.\d+|\d+\.?\d*)(?:e[-+]?\d+)?/i, token: "number"}, // Single line comment {regex: /~[^~].*/, token: "comment"}, // Multi-line comment start {regex: /~~~/, token: "comment", next: "comment"}, // ? {regex: /\/(?:[^\\]|\\.)*?\//, token: "variable-3"}, // Intends {regex: /[{]/, indent: true}, {regex: /[}]/, dedent: true}, // {regex: /[a-z$][\w$]*/, token: "variable"}, // {regex: /<</, token: "meta", mode: {spec: "xml", end: />>/}} ], // The multi-line comment state. comment: [ // Multi-line comment ends {regex: /.*?~~~/, token: "comment", next: "start"}, // Multi-line comment continues {regex: /.*/, token: "comment"} ], // The meta property contains global information about the mode. It // can contain properties like lineComment, which are supported by // all modes, and also directives like dontIndentStates, which are // specific to simple modes. meta: { dontIndentStates: ["comment"], lineComment: "~" } });
Markdown
UTF-8
8,142
3.046875
3
[]
no_license
# 离屏渲染 ##GPU屏幕渲染有两种方式: (1)On-Screen Rendering (当前屏幕渲染) 指的是GPU的渲染操作是在当前用于显示的屏幕缓冲区进行。 (2)Off-Screen Rendering (离屏渲染) 指的是在GPU在当前屏幕缓冲区以外开辟一个缓冲区进行渲染操作。 当前屏幕渲染不需要额外创建新的缓存,也不需要开启新的上下文,相对于离屏渲染性能更好。但是受当前屏幕渲染的局限因素限制(只有自身上下文、屏幕缓存有限等),当前屏幕渲染有些情况下的渲染解决不了的,就使用到离屏渲染。 相比于当前屏幕渲染,离屏渲染的代价是很高的,主要体现在两个方面: (1)创建新缓冲区要想进行离屏渲染,首先要创建一个新的缓冲区。 (2)上下文切换离屏渲染的整个过程,需要多次切换上下文环境:先是从当前屏幕(On-Screen)切换到离屏(Off-Screen),等到离屏渲染结束以后,将离屏缓冲区的渲染结果显示到屏幕上有需要将上下文环境从离屏切换到当前屏幕。而上下文环境的切换是要付出很大代价的。 由于垂直同步的机制,如果在一个 HSync 时间内,CPU 或者 GPU 没有完成内容提交,则那一帧就会被丢弃,等待下一次机会再显示,而这时显示屏会保留之前的内容不变。这就是界面卡顿的原因。 ##既然离屏渲染这么耗性能,为什么有这套机制呢? 有些效果被认为不能直接呈现于屏幕,而需要在别的地方做额外的处理预合成。图层属性的混合体没有预合成之前不能直接在屏幕中绘制,所以就需要屏幕外渲染。屏幕外渲染并不意味着软件绘制,但是它意味着图层必须在被显示之前在一个屏幕外上下文中被渲染(不论CPU还是GPU)。 ##下面的情况或操作会引发离屏渲染: - 为图层设置阴影(layer.shadow *)。解决办法:使用shadowPath - 为图层设置遮罩(layer.mask) 一定会产生离屏渲染 - 将图层的layer.masksToBounds / view.clipsToBounds属性设置为true - 将图层layer.allowsGroupOpacity属性设置为YES和layer.opacity小于1.0 - 为图层设置layer.shouldRasterize=true 当视图内容是静态不变时,设置 shouldRasterize(光栅化)为YES,此方案最为实用方便。 - 具有layer.cornerRadius,layer.edgeAntialiasingMask,layer.allowsEdgeAntialiasing的图层 方案:不设置 allowsEdgeAntialiasing 属性为YES(默认为NO) - 文本(任何种类,包括UILabel,CATextLayer,Core Text等)。 - 使用CGContext在drawRect :方法中绘制大部分情况下会导致离屏渲染,甚至仅仅是一个空的实现。 方案:放到后台线程中进行。 优化方案 官方对离屏渲染产生性能问题也进行了优化: iOS 9.0 之前UIImageView跟UIButton设置圆角都会触发离屏渲染。 iOS 9.0 之后UIButton设置圆角会触发离屏渲染,而UIImageView里png图片设置圆角不会触发离屏渲染了,如果设置其他阴影效果之类的还是会触发离屏渲染的。 >https://www.jianshu.com/p/cff0d1b3c915 >https://www.jianshu.com/p/e879aeff93f3 >https://www.jianshu.com/p/b0442491141e ##设置圆角的四种方法 一、设置CALayer的cornerRadius cornerRadius属性影响layer显示的background颜色和前景框border,对layer的contents不起作用。故一个imgView(类型为UIImageView)的image不为空,设置imgView.layer的cornerRadius,是看不出显示圆角效果的,因为image是imgView.layer的contents部分。 这种情况下将layer的masksToBounds属性设置为YES,可以正确的绘制出圆角效果。但是cornerRadius>0,masksToBounds=YES,会触发GPU的离屏渲染,当一个屏幕上有多处触发离屏渲染,会影响性能。通过勾选Instruments->Core Animation->Color Offscreen-Rendered Yellow,可以看到屏幕上触发离屏渲染的会被渲染成黄色。离屏渲染的代价昂贵,苹果也意识到会产生性能问题,所以iOS9以后的系统里能不产生离屏渲染的地方也就不用离屏渲染了。比如对UIImageView里png图片设置圆角不会触发离屏渲染。 1. 对contents为空的视图设置圆角 ``` view.backgroundColor = [UIColor redColor]; view.layer.cornerRadius = 25; //UILabel设置backgroundColor的行为被更改,不再是设定layer的背景色而是为contents设置背景色 label.layer.backgroundColor = aColor label.layer.cornerRadius = 5 ``` 2. 对contents不为空的视图设置圆角 ``` imageView.image = [UIImage imageNamed:@"img"]; imageView.image.layer.cornerRadius = 5; imageView.image.layer.masksToBounds = YES; ``` 二、设置CALayer的mask 通过设置view.layer的mask属性,可以将另一个layer盖在view上,也可以设置圆角,但是mask同样会触发离屏渲染。 有两种方式来生成遮罩,一是通过图片生成,图片的透明度影响着view绘制的透明度,图片遮罩透明度为1的部分view被绘制成的透明度为1,相反图片遮罩透明度为0的部分view被绘制成的透明度为0。二是通过贝塞尔曲线生成,view中曲线描述的形状部分会被绘制出来。 ``` // 通过图片生成遮罩, UIImage *maskImage = [UIImage imageNamed:@"someimg"]; CALayer *mask = [CALayer new]; mask.frame = CGRectMake(0, 0, maskImage.size.width, maskImage.size.height); mask.contents = (__bridge id _Nullable)(maskImage.CGImage); view.layer.mask = mask; //通过贝塞尔曲线生成 CAShapeLayer *mask = [CAShapeLayer new]; mask.path = [UIBezierPath bezierPathWithOvalInRect:view.bounds].CGPath; view.layer.mask = mask; ``` 三、通过Core Graphics重新绘制带圆角的视图 通过CPU重新绘制一份带圆角的视图来实现圆角效果,会大大增加CPU的负担,而且相当于多了一份视图拷贝会增加内存开销。但是就显示性能而言,由于没有触发离屏渲染,所以能保持较高帧率。下例是绘制一个圆形图片,绘制其它UIView并无本质区别。重新绘制的过程可以交由后台线程来处理。 ``` @implementation UIImage (CircleImage) - (UIImage *)drawCircleImage { CGFloat side = MIN(self.size.width, self.size.height); UIGraphicsBeginImageContextWithOptions(CGSizeMake(side, side), false, [UIScreen mainScreen].scale); CGContextAddPath(UIGraphicsGetCurrentContext(), [UIBezierPath bezierPathWithOvalInRect:CGRectMake(0, 0, side, side)].CGPath); CGContextClip(UIGraphicsGetCurrentContext()); CGFloat marginX = -(self.size.width - side) / 2.f; CGFloat marginY = -(self.size.height - side) / 2.f; [self drawInRect:CGRectMake(marginX, marginY, self.size.width, self.size.height)]; CGContextDrawPath(UIGraphicsGetCurrentContext(), kCGPathFillStroke); UIImage *output = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return output; } @end //在需要圆角时调用如下 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ UIImage *img = [[UIImage imageNamed:@"image.png"] drawCircleImage]; dispatch_async(dispatch_get_main_queue(), ^{ view.image = img; }); }); ``` 四、通过混合图层 此方法就是在要添加圆角的视图上再叠加一个部分透明的视图,只对圆角部分进行遮挡。图层混合的透明度处理方式与mask正好相反。此方法虽然是最优解,没有离屏渲染,没有额外的CPU计算,但是应用范围有限。 总结 在可以使用混合图层遮挡的场景下,优先使用第四种方法。 即使是非iOS9以上系统,第一种方法在综合性能上依然强于后两者,iOS9以上由于没有了离屏渲染更是首选。 方法二和方法三由于使用了贝塞尔曲线,都可以应对复杂的圆角。只不过前者牺牲帧率,后者需要大量计算和增加部分内存,需要实际情况各自取舍。 >https://www.jianshu.com/p/86dd5bf298a0 #iOS Core Animation---隐式动画 https://blog.csdn.net/u011774517/article/details/66967648
Markdown
UTF-8
36,572
2.859375
3
[]
no_license
# Creating a Simple App with Redux-ORM Move to latest * "react": "^16.8.6", * "react-bootstrap": "^1.0.0-beta.5", * "react-datepicker": "^2.5.0", * "react-datetime": "^2.16.3", "react-dom": "^16.8.6", "react-jsonschema-form": "^1.2.1", "react-pure-render": "^1.0.2", "react-redux": "^6.0.1", "react-router": "^5.0.0", "react-router-dom": "^5.0.0", "react-scripts": "^3.0.1", "redux": "^4.0.1", "redux-diff-logger": "0.0.6", "redux-logger": "^2.4.0", "redux-orm": "0.13.3", "redux-orm-proptypes": "^0.1.0", "redux-thunk": "^2.3.0", "reselect": "^2.0.1" This article shows you how to create and test a simple todo application with some related data using [Redux-ORM](https://github.com/tommikaikkonen/redux-orm). I'll assume you're already familiar with Redux and React. The source for the app is in this repository and you can play around with the [live demo here](http://tommikaikkonen.github.io/redux-orm-primer). ![Screenshot of the Example App](https://raw.githubusercontent.com/tommikaikkonen/redux-orm-primer/master/screenshot.png) ## Overview of Redux-ORM You want your data to be normalized in your Redux store. Now if your data is relational, your state is bound to look like tables in a relational database, because that's the normalized way to represent that kind of data. As you write your Redux reducers and selectors, you want to divide them to small functions to create a hierarchy of functions. This makes the functions easy to test and reason about, and is one of the great things about Redux. You might have a reducer for a list of entities, lets say restaurants. To store information about restaurants, you have an `items` array of restaurant id's, and an `itemsById` map. In the main restaurant reducer, you delegate to separate `items` and `itemsById` reducers. You create another subreducer inside `itemsById` reducer that applies updates on individual restaurants' attributes. That works great until you need to access employee entities related to that restaurant. The state supplied to your restaurant reducers doesn't have information about employees. You might end up at some of these solutions to the problem: - use `redux-thunk` to query the state with `getState` before dispatching the final action object with all the data needed for the separate reducers to do their job, - write the reducer / selector logic higher up in the hierarchy or - pass a larger piece of state to child reducers / selectors as an additional argument. You can work with all these, but in my opinion, they get hairy to manage. Your code ends up handling a lot of low-level logic, and the bigger picture gets lost. Redux-ORM provides an abstraction over the "relational database" state object. You define a schema through models, and start database sessions by passing a Schema instance the relational database state object. Reducers and selectors are able to respectively update and query the whole database through an immutable ORM API, which makes your code more expressive, readable and manageable. In practice, the workflow with Redux-ORM looks like this: 1. Declare the relational schema with model classes 2. Write model-specific reducers to edit data 3. Write selectors to query data for connected components and actions 4. Plug the Redux-ORM reducer somewhere in your Redux reducer. ## Designing State For Our App In our app we have Users, Todos and Tags. Every Todo is associated with a single User. A Todo can have multiple Tags, and a Tag can have multiple Todos. The schema looks like this: ``` **User** - id: integer - name: string **Todo** - id: integer - text: string - done: boolean - user: foreign key to User - tags: many-to-many relation with Tag **Tag** - name: string (used as the primary key) ``` Additionally we'll store the selected user id in the Redux state, but outside the relational database. Our Redux state would look something like this: ```javascript { orm: {/* the relational database state */}, selectedUserId: 0, } ``` The following actions are possible: - Select a User - Create a Todo with Tags - Mark a Todo done - Add a Tag to a Todo - Remove a Tag from a Todo - Delete a Todo An app this simple would not normally warrant using an ORM, but it'll do great to get you up to speed. ## Defining Models To let Redux-ORM know about the structure of our relational data, we create models. They are ES6 classes that extend from Redux-ORM's `Model`, which means that you can define any helper methods or attributes you might need on your models. You'll often want to define your own base model for your project that extends from Model, and continue to extend your concrete models from that. The base model can contain, for example, functionality related to async calls and validation which Redux-ORM doesn't provide. The methods will be accessible to you when using the ORM API. This example will use vanilla Model classes. Let's begin writing our Models. ```javascript // models.js import { Model } from 'redux-orm'; export class Todo extends Model {} // Note that the modelName will be used to resolve // relations! Todo.modelName = 'Todo'; export class Tag extends Model { } Tag.modelName = 'Tag'; Tag.backend = { idAttribute: 'name'; }; export class User extends Model {} User.modelName = 'User'; ``` Just like React components need a `displayName`, models need a `modelName` so that running the code through a mangler won't break functionality. The value in `modelName` will be used to construct the relations. We also pass a `backend` attribute to Tag, where we define the custom setting `idAttribute`, so that we identify tags by its `name` attribute like we defined in the schema. The default `idAttribute` is `id`. To declare how these models are related, we specify a static `fields` variable to the model class, where you declare the type of relations (`fk` for many to one, `oneToOne` for one to one, and `many` for many to many). ```javascript // models.js import { Model, many, fk, Schema } from 'redux-orm'; export class Todo extends Model {} Todo.modelName = 'Todo'; Todo.fields = { user: fk('User', 'todos'), tags: many('Tag', 'todos'), }; export class Tag extends Model {} Tag.modelName = 'Tag'; Tag.backend = { idAttribute: 'name'; }; export class User extends Model {} User.modelName = 'User'; ``` `many`, `fk` and `oneToOne` field factories take two arguments: the related model's `modelName` and an optional reverse field name. If the reverse field name is not specified, it will be autogenerated (the default way to access Todos related to a user instance would be `user.todoSet`). For example, the declaration ```javascript tags: many('Tag', 'todos'), ``` means that accessing the `todos` property of a Tag model instance returns the set of Todo's that have that tag. The value returned by `tagInstance.todos` is not an array but a `QuerySet` instance, which enables filtering, ordering, editing and reading operations on a set of entities. > ### How State Is Managed For Many-To-Many Relations > > Redux-ORM internally mimics relational databases and creates a new "table" for many-to-many relations, represented by an internal "through" Model class. > So when we define this field on a Todo: > > ```javascript > tags: many('Tag', 'todos'), > ``` > > Redux-ORM creates a model named `TodoTags`, that's entities are in this form: > ```javascript > { > id: 0, > fromTodoId: 0, > toTagId: 1, > } > ``` What about non-relational fields like `User.name`, `Todo.text` and `Todo.done` that we defined in our schema plan? You don't need to declare non-relational fields in Redux-ORM. You can assign attributes to Model instances as if they were JavaScript objects. Redux-ORM takes care of "shallow immutability" in the model instances, so assignment to Model instances happens in an immutable fashion, but the immutability of the assigned values is your responsibility. This is only a concern if you assign referential (Object or Array) values to a Model instance and mutate those values. > ### Using PropTypes to validate non-relational fields > > In non-trivial applications, it's smart to validate non-relational fields, > just like you validate incoming props on React components. [This gist](https://gist.github.com/tommikaikkonen/45d0d2ff2a5a383bb14d) shows you how to define a Model subclass, `ValidatingModel`, that you can use to define your concrete models. You could use it with the Todo model like this: > > ```javascript > class Todo extends ValidatingModel {} > // ... > Todo.propTypes = { > id: React.PropTypes.number, > text: React.PropTypes.string.isRequired, > done: React.PropTypes.boolean.isRequired, > user: React.PropTypes.oneOf([ > React.PropTypes.instanceOf(User), > React.PropTypes.number > ]).isRequired, > tags: React.PropTypes.arrayOf([ > React.PropTypes.instanceOf(Tag), > React.PropTypes.number > ]), > }; > > Todo.defaultProps = { > done: false, > }; > ``` ## Defining Actions and Action Creators First up, let's define our action type constants: ```javascript // actionTypes.js export const SELECT_USER = 'SELECT_USER'; export const CREATE_TODO = 'CREATE_TODO'; export const MARK_DONE = 'MARK_DONE'; export const ADD_TAG_TO_TODO = 'ADD_TAG_TO_TODO'; export const REMOVE_TAG_FROM_TODO = 'REMOVE_TAG_FROM_TODO'; export const DELETE_TODO = 'DELETE_TODO'; ``` And here are our simple action creators. ```javascript // actions.js import { SELECT_USER, CREATE_TODO, MARK_DONE, DELETE_TODO, ADD_TAG_TO_TODO, REMOVE_TAG_FROM_TODO, } from './actionTypes'; export const selectUser = id => { return { type: SELECT_USER, payload: id, }; }; export const createTodo = props => { return { type: CREATE_TODO, payload: props, }; }; export const markDone = id => { return { type: MARK_DONE, payload: id, }; }; export const deleteTodo = id => { return { type: DELETE_TODO, payload: id, }; }; export const addTagToTodo = (todo, tag) => { return { type: ADD_TAG_TO_TODO, payload: { todo, tag, }, }; }; export const removeTagFromTodo = (todo, tag) => { return { type: REMOVE_TAG_FROM_TODO, payload: { todo, tag, }, }; }; ``` Pretty standard stuff. ## Writing Reducers Redux-ORM uses model-specific reducers to operate on data. You define a static `reducer` method on Model classes, which will receive all Redux-dispatched actions. If you don't define a `reducer`, the default implementation will be used, which calls `.getNextState` on the model class and returns the value. First up, we'll write the reducer for the Todo model. Note that when creating a Todo, we want to pass a comma-delimited list of tags in the user interface and create the Tag instances based on that. ```javascript // models.js import { Schema, Model, many, fk } from 'redux-orm'; import { CREATE_TODO, MARK_DONE, DELETE_TODO, ADD_TAG_TO_TODO, REMOVE_TAG_FROM_TODO, } from './actionTypes'; export class Todo extends Model { static reducer(state, action, Todo, session) { const { payload, type } = action; switch (type) { case CREATE_TODO: // Payload includes a comma-delimited string // of tags, corresponding to the `name` property // of Tag, which is also its `idAttribute`. const tagIds = action.payload.tags.split(',').map(str => str.trim()); // You can pass an array of ids for many-to-many relations. // `redux-orm` will create the m2m rows automatically. const props = Object.assign({}, payload, { tags: tagIds }); Todo.create(props); break; case MARK_DONE: // withId returns a Model instance. // Assignment doesn't mutate Model instances. Todo.withId(payload).set('done', true); break; case DELETE_TODO: Todo.withId(payload).delete(); break; case ADD_TAG_TO_TODO: Todo.withId(payload.todo).tags.add(payload.tag); break; case REMOVE_TAG_FROM_TODO: Todo.withId(payload.todo).tags.remove(payload.tag); break; } // This call is optional. If the reducer returns `undefined`, // Redux-ORM will call getNextState for you. return Todo.getNextState(); } } Todo.modelName = 'Todo'; Todo.fields = { tags: many('Tag', 'todos'), user: fk('User', 'todos'), }; ``` All Model reducers receive four arguments: the model state, the current action, the Model class, and the current Redux-ORM Session instance. You usually won't need the Session instance, but you can access and query other models through the Session instance (for example, you can access the Tag model through `session.Tag`), but modifying other model's data is not recommended nor supported. Redux-ORM enables you to be pretty expressive in your reducers and not worry about the low level stuff. All of the actions done during a session (`create`, `delete`, `add`, `set`, `update`, `remove`) record updates, which will be applied in the new state returned by `Todo.getNextState()`. Here's the reducer for Tag. Our simple app won't have any actions that act on User data, so we won't write a reducer for it. ```javascript // models.js // ... export class Tag extends Model { static reducer(state, action, Tag) { const { payload, type } = action; switch (type) { case CREATE_TODO: const tags = payload.tags.split(','); const trimmed = tags.map(name => name.trim()); trimmed.forEach(name => Tag.create({ name })); break; case ADD_TAG_TO_TODO: // Check if the tag already exists if (!Tag.filter({ name: payload.tag }).exists()) { Tag.create({ name: payload.tag }); } break; } // Tag.getNextState will be implicitly called for us } } Tag.modelName = 'Tag'; Tag.backend = { idAttribute: 'name', }; ``` Now that we've finished our Model definitions, we create a Schema instance, register our models and export it as the default export of models.js: ```javascript // models.js // ... model definitions above export const schema = new Schema(); schema.register(Todo, Tag, User); export default schema; ``` We'll use the `schema` instance later to create selectors and inject the ORM reducer to Redux. We have one additional reducer outside Redux-ORM we need to define, `selectedUserIdReducer`. We'll put it in `reducers.js`. It's very simple as it maintains a single number corresponding to the selected User id. ```javascript // reducers.js import { SELECT_USER } from './actionTypes'; export function selectedUserIdReducer(state = 0, action) { const { type, payload } = action; switch (type) { case SELECT_USER: return payload; default: return state; } } ``` ## Writing Selectors `redux` and `reselect` libraries fit together with the [*Command Query Responsibility Segregation* pattern](http://martinfowler.com/bliki/CQRS.html). The gist of it is that you use a different model to update data (reducers in Redux) and to read data (selectors in Redux). We've handled the updating part of our state management. We're yet to define our selectors. First, let's think about what we want to pass to our React components. - Since we want to show the name of the current user, and bind action creators with the currently selected user's id, we need an object that describes the currently selected user with an id and a name. We'll call this selector `user`. - We want to show a list of todos for the selected user. Each todo in that list should have its id, text, status (done or not), and a list of tag names associated with that todo, so we can render it nicely. We'll call this selector `todos`. - Since we want the end user to be able to select which User to show todos for, we need a list of users you can select, with an id and the name for each user. We'll call this selector `users`. Here's selectors.js, where we implement those selectors: ```javascript // selectors.js import { schema } from './models'; import { createSelector } from 'reselect'; // Selects the state managed by Redux-ORM. export const ormSelector = state => state.orm; // Redux-ORM selectors work with reselect. To feed input // selectors to a Redux-ORM selector, we use the reselect `createSelector` function. export const todos = createSelector( // The first input selector should always be the orm selector. // Behind the scenes, `schema.createSelector` begins a Redux-ORM // session with the value returned by `ormSelector` and passes // that Session instance as an argument instead. // So `orm` below is a Session instance. ormSelector, state => state.selectedUserId, schema.createSelector((orm, userId) => { console.log('Running todos selector'); // We could also do orm.User.withId(userId).todos.map(...) // but this saves a query on the User table. // // `.withRefs` means that the next operation (in this case filter) // will use direct references from the state instead of Model instances. // If you don't need any Model instance methods, you should use withRefs. return orm.Todo.withRefs.filter({ user: userId }).map(todo => { // `todo.ref` is a direct reference to the state, // so we need to be careful not to mutate it. // // We want to add a denormalized `tags` attribute // to each of our todos, so we make a shallow copy of `todo.ref`. const obj = Object.assign({}, todo.ref); obj.tags = todo.tags.withRefs.map(tag => tag.name); return obj; }); }) ); export const user = createSelector( ormSelector, state => state.selectedUserId, schema.createSelector((orm, selectedUserId) => { console.log('Running user selector'); // .ref returns a reference to the plain // JavaScript object in the store. // It includes the id and name that we need. return orm.User.withId(selectedUserId).ref; }) ); export const users = createSelector( ormSelector, schema.createSelector(orm => { console.log('Running users selector'); // `.toRefArray` returns a new Array that includes // direct references to each User object in the state. return orm.User.all().toRefArray(); }) ); ``` Like `reselect` selectors, Redux-ORM selectors have memoization, but it works a little differently. `reselect` checks if the passed arguments match the previous ones, and if so, returns the previous result. Redux-ORM selectors always take the whole `orm` branch as the first argument, therefore `reselect` style memoization would only work when the whole database has not changed. To solve this, Redux-ORM observes which models' states you actually accessed when you ran the `todos` selector for the first time. On consecutive calls, before running the selector, the memoize function checks if any of those models' state has changed - if so, the selector is run again. Otherwise the previous result is returned. Redux-ORM selectors are compatible with `reselect` selectors, as they are `reselect` selectors with a schema-specific memoization function. > ### How Redux-ORM Selector Memoization Works > > You don't need to know this to use Redux-ORM, but in case you're interested, here are the step-by-step instructions Redux-ORM uses to memoize selectors. > > 1. Has the selector been run before? If not, go to 5. > 2. If the selector has other input selectors in addition to the ORM state selector, check their results for equality with the previous results. If they aren't equal, go to 5. > 3. Is the ORM state referentially equal to the previous ORM state the selector was called with? If yes, return the previous result. > 4. Check which Model's states the selector has accessed on previous runs. Check for equality with each of those states versus their states in the previous ORM state. If all of them are equal, return the previous result. > 5. Run the selector. Check the Session object used by the selector for which Model's states were accessed, and merge them with the previously saved information about accessed models (if-else branching can change which models are accessed on different inputs). Save the ORM state and other arguments the selector was called with, overriding previously saved values. Save the selector result. Return the selector result. So for `todos` selector, we access the Todo and Tag models (because we access all todos with `Todo.map(todo => ...)` and the related tags with `todo.tags`). The `user` selector accesses only the User model. All of our actions modify either the Todo or Tag model states, or change the selected user, so the `todos` selector is run after every update. If we also had a Tag selector like this: ```javascript const tagNames = schema.createSelector(orm => { return orm.Tag.map(tag => tag.name); }); ``` it would only get run after the actions `createTodo`, `addTagToTodo` and `removeTagFromTodo` that possibly change the Tag model state. When possible, we return plain objects and direct references from the state from selectors. It is much easier to use pure React components by passing plain JavaScript to props -- with Model instances, you would have to override `shouldComponentUpdate` to avoid redundant renders. ## Creating React Components Next up, let's create our application's main React component that uses the action creators we defined and receives the views we defined through selectors as props. ```jsx // app.js /* eslint-disable no-shadow */ import React, { PropTypes } from 'react'; import PureComponent from 'react-pure-render/component'; import { connect } from 'react-redux'; // Dumb components, their implementation is not relevant // to this article. import { TodoItem, AddTodoForm, UserSelector, } from './components'; import { selectUser, createTodo, markDone, deleteTodo, addTagToTodo, removeTagFromTodo, } from './actions'; import { todos, user, users, } from './selectors'; class App extends PureComponent { render() { const props = this.props; const { todos, users, selectedUser, selectUser, createTodo, markDone, deleteTodo, addTagToTodo, removeTagFromTodo, } = props; console.log('Props received by App component:', props); const todoItems = todos.map(todo => { return ( // TodoItem is a dumb component, it's implementation // is not in this article's interest. <TodoItem key={todo.id} tags={todo.tags} done={todo.done} onAddTag={addTagToTodo.bind(null, todo.id)} onRemoveTag={removeTagFromTodo.bind(null, todo.id)} onMarkDone={markDone.bind(null, todo.id)} onDelete={deleteTodo.bind(null, todo.id)}> {todo.text} </TodoItem> ); }); const userChoices = users.map(user => { return <option key={user.id} value={user.id}>{user.name}</option>; }); const onUserSelect = userId => { selectUser(userId); }; const onCreate = ({ text, tags }) => createTodo({ text, tags, user: selectedUser.id}); return ( <div> <h1>Todos for {selectedUser.name}</h1> <UserSelector onSelect={onUserSelect}> {userChoices} </UserSelector> <ul className="list-group"> {todoItems} </ul> <h2>Add Todo for {selectedUser.name}</h2> <AddTodoForm onSubmit={onCreate}/> </div> ); } } App.propTypes = { todos: PropTypes.arrayOf(PropTypes.object).isRequired, users: PropTypes.arrayOf(PropTypes.object).isRequired, selectedUser: PropTypes.object.isRequired, selectUser: PropTypes.func.isRequired, createTodo: PropTypes.func.isRequired, markDone: PropTypes.func.isRequired, deleteTodo: PropTypes.func.isRequired, addTagToTodo: PropTypes.func.isRequired, removeTagFromTodo: PropTypes.func.isRequired, }; // This function takes the Redux state, runs the // selectors and returns the props passed to App. function stateToProps(state) { return { todos: todos(state), selectedUser: user(state), users: users(state), }; } // This maps our action creators to props and binds // them to dispatch. const dispatchToProps = { selectUser, createTodo, markDone, deleteTodo, addTagToTodo, removeTagFromTodo, }; export default connect(stateToProps, dispatchToProps)(App); ``` ## Bootstrapping Initial State To create an initial state for our app, we can manually instantiate an ORM session. To construct the initial state, we don't need immutable operations. We can do that with a mutating session. In the model reducers and selectors, a session was instantiated for us automatically. You can instantiate a mutating session by calling the `withMutations` method on a Schema instance, and an immutable one with the `from` method. Both methods take a state object as the required first argument, and optionally an action object as the second argument. Let's define a bootstrap function in bootstrap.js that initializes our state with some simple data. ```javascript // bootstrap.js export default function bootstrap(schema) { // Get the empty state according to our schema. const state = schema.getDefaultState(); // Begin a mutating session with that state. // `state` will be mutated. const session = schema.withMutations(state); // Model classes are available as properties of the // Session instance. const { Todo, Tag, User } = session; // Start by creating entities whose props are not dependent // on others. const user = User.create({ id: 0, // optional. If omitted, Redux-ORM uses a number sequence starting from 0. name: 'Tommi', }); const otherUser = User.create({ id: 1, // optional. name: 'John', }); // Tags to start with. const work = Tag.create({ name: 'work' }); const personal = Tag.create({ name: 'personal' }); const urgent = Tag.create({ name: 'urgent' }); const chore = Tag.create({ name: 'chore' }); // Todo's for `user` Todo.create({ text: 'Buy groceries', done: false, user, tags: [personal], // We could also pass ids instead of the Tag instances. }); Todo.create({ text: 'Attend meeting', done: false, user, tags: [work], }); Todo.create({ text: 'Pay bills', done: false, user, tags: [personal, urgent], }); // Todo's for `otherUser` Todo.create({ text: 'Prepare meals for the week', done: false, user: otherUser, tags: [personal, chore], }); Todo.create({ text: 'Fix the washing machine', done: false, user: otherUser, tags: [personal, chore], }); Todo.create({ text: 'Negotiate internet subscription', done: false, user: otherUser, tags: [personal, urgent], }); // Return the whole Redux initial state. return { orm: state, selectedUserId: 0, }; } ``` Then we can feed that state to Redux. Schema instances have a `reducer` method that returns a reducer function you can plug in to a root reducer. A common way to do that is to have an `orm` branch in your state. Here's the index.js file that brings the whole app together. ```jsx // index.js import React from 'react'; import ReactDOM from 'react-dom'; import { createStore, combineReducers, applyMiddleware } from 'redux'; import { Provider } from 'react-redux'; import createLogger from 'redux-logger'; import { schema } from './models'; import { selectedUserIdReducer } from './reducers'; import bootstrap from './bootstrap'; import App from './app'; const rootReducer = combineReducers({ orm: schema.reducer(), selectedUserId: selectedUserIdReducer, }); // We're using `redux-logger`. Open up the console in the demo and you can inspect // the internal state maintained by Redux-ORM. const createStoreWithMiddleware = applyMiddleware(createLogger())(createStore); const store = createStoreWithMiddleware(rootReducer, bootstrap(schema)); function main() { // In the repo, we have a simple index.html that includes Bootstrap CSS files // and a div element with id `app`. const app = document.getElementById('app'); ReactDOM.render(( <Provider store={store}> <App /> </Provider> ), app); } main(); ``` ## Testing Reducers and Selectors We want to test that we update our state correctly based on action objects. No problem. Redux-ORM makes testing easier too. For good integration testing, we want to have nice test data and have the ability to easily generate it. Using an adapter, we can utilize the [`factory-girl`](https://github.com/aexmachina/factory-girl) library to generate data for us (this is overkill for a Todo app, but it is handy in larger projects). You could also use the function we wrote in bootstrap.js to generate test data. Here's test/factories.js: ```javascript // test/factories.js import _factory from 'factory-girl'; import { Todo, User, Tag } from '../models'; import bluebird from 'bluebird'; import { ReduxORMAdapter } from './utils'; // factory-girl only works asynchronously with associated models, // so we need to roll with that even though Redux-ORM is synchronous. // We promisify factory-girl so we can use Promises instead of callbacks. const factory = _factory.promisify(bluebird); // Use a simple adapter for Redux-ORM factory.setAdapter(new ReduxORMAdapter()); factory.define('Todo', Todo, { id: factory.sequence(n => n), text: factory.sequence(n => `Todo ${n}`), user: factory.assoc('User', 'id'), tags: factory.assocMany('Tag', 'name', 4), // 4 tags for each Todo done: factory.sequence(n => n % 2 ? true : false), }); factory.define('User', User, { id: factory.sequence(n => n), name: factory.sequence(n => `User ${n}`), }); factory.define('Tag', Tag, { name: factory.sequence(n => `Tag ${n}`), }); export default factory; ``` Now we can use the factories to generate some initial data. In our model test suite's `beforeEach`, we start a mutating session, so that `factory-girl` generates the data to a mutating state object. (*Model classes are currently singletons that can be connected to zero or one sessions at a time, so this works even though `factory-girl` knows only about our Model classes and not our Session instance. The Model classes may not be singletons in the future, so I recommend always getting your Model classes from the Session instance*) ```javascript /* eslint no-unused-expressions: 0 */ import { expect } from 'chai'; import { CREATE_TODO, MARK_DONE, DELETE_TODO, ADD_TAG_TO_TODO, REMOVE_TAG_FROM_TODO, } from '../actionTypes'; import { schema } from '../models'; import factory from './factories'; import Promise from 'bluebird'; import { applyActionAndGetNextSession } from './utils'; describe('Models', () => { // This will be the initial ORM state. let state; // This will be a Session instance with the initial data. let session; beforeEach(done => { // Get the default state and start a mutating session. // Before we start another session, all Model classes // will be bound to this session. state = schema.getDefaultState(); session = schema.withMutations(state); factory.createMany('User', 2).then(users => { return Promise.all(users.map(user => { const userId = user.getId(); // Create 10 todos for both of our 2 users. return factory.createMany('Todo', { user: userId }, 10); })); }).then(() => { // Generating data is finished, start up an immutable session. session = schema.from(state); // Let mocha know we're done setting up. done(); }); }); it('correctly handle CREATE_TODO', () => { const todoText = 'New Todo Text!'; const todoTags = 'testing, nice, cool'; const user = session.User.first(); const userId = user.getId(); const action = { type: CREATE_TODO, payload: { text: todoText, tags: todoTags, user: userId, }, }; expect(user.todos.count()).to.equal(10); expect(session.Todo.count()).to.equal(20); expect(session.Tag.count()).to.equal(80); // The below helper function completes an action dispatch // loop with the given state and action. // Finally, it returns a new Session started with the // next state yielded from the dispatch loop. // With this new Session, we can query the resulting state. const { Todo, Tag, User, } = applyActionAndGetNextSession(schema, state, action); expect(User.withId(userId).todos.count()).to.equal(11); expect(Todo.count()).to.equal(21); expect(Tag.count()).to.equal(83); const newTodo = Todo.last(); expect(newTodo.text).to.equal(todoText); expect(newTodo.user.getId()).to.equal(userId); expect(newTodo.done).to.be.false; expect(newTodo.tags.map(tag => tag.name)).to.deep.equal(['testing', 'nice', 'cool']); }); // To see tests for the rest of the actions, check out the source. }); ``` We can use a similar `beforeEach` setup with selectors, although we'll construct the whole Redux state that they take as an input instead of just the ORM state (this includes the selected user id): ```javascript import { expect } from 'chai'; import { users, user, todos, } from '../selectors'; import { schema } from '../models'; import factory from './factories'; import Promise from 'bluebird'; import { applyActionAndGetNextSession } from './utils'; describe('Selectors', () => { let ormState; let session; let state; beforeEach(done => { ormState = schema.getDefaultState(); session = schema.withMutations(ormState); factory.createMany('User', 2).then(users => { return Promise.all(users.map(user => { const userId = user.getId(); return factory.createMany('Todo', { user: userId }, 10); })); }).then(() => { session = schema.from(ormState); state = { orm: ormState, selectedUserId: session.User.first().getId(), }; done(); }); }); it('users works', () => { const result = users(state); expect(result).to.have.length(2); expect(result[0]).to.contain.all.keys(['id', 'name']); }); it('todos works', () => { const result = todos(state); expect(result).to.have.length(10); expect(result[0]).to.contain.all.keys(['id', 'text', 'user', 'tags', 'done']); expect(result[0].tags).to.have.length(4); }); it('user works', () => { const result = user(state); expect(result).to.be.an('object'); expect(result).to.contain.all.keys(['id', 'name']); }); }); ``` And that's it! Play around with the [live demo](https://tommikaikkonen.github.io/redux-orm-primer) and remember to open up the console. Ping me on Twitter ([@tommikaikkonen](https://twitter.com/tommikaikkonen)) if you have any questions, or open up an issue in the [redux-orm repository](https://github.com/tommikaikkonen/redux-orm).
C++
UTF-8
363
2.78125
3
[ "MIT" ]
permissive
/* g++ --std=c++20 -pthread -o ../_build/cpp/language_ascii.exe ./cpp/language_ascii.cpp && (cd ../_build/cpp/;./language_ascii.exe) https://en.cppreference.com/w/cpp/language/ascii */ #include <iostream> int main() { std::cout << "Printable ASCII [32..126]:\n"; for (char i = ' '; i <= '~'; ++i) { std::cout << i << ((i % 16 == 15) ? '\n' : ' '); } }
Python
UTF-8
512
4.25
4
[]
no_license
# Given two strings, write a method to decide if one is a permutation of the other. def is_permutation(s1, s2): # LOG COST # O(n lg n) solution - just sort the strings and O(n) compare # Can be done in O(n) using a hash table but requires O(n) space s1 = sorted(s1) s2 = sorted(s2) return True if s1 == s2 else False test_data = [ ("reap", "pear"), ("jest", "test") ] for t in test_data: print "%s and %s %s permutations of each other" % (t[0], t[1], "are" if is_permutation(t[0], t[1]) else "are not")
PHP
UTF-8
4,077
2.671875
3
[]
no_license
<?php include '../controllers/common.php'; auth_check(); $username = $_SESSION['username']; $userid = $_SESSION['userID']; //if(isset($_POST) && count($_POST) > 0) if(isset($_POST) && count($_POST) > 0){ if(isset($_POST['title']) && isset($_POST['description'])){ $validated = true; }else{ $validated = false; } if($validated){ //$target_dir = 'uploads/books/' . $userid . '/'; $target_dir = 'uploads/books/'; $target_file = $target_dir . basename($_FILES["book-img"]["name"]); $uploadOk = true; $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); //If IT really a image if($_FILES["book-img"]["tmp_name"]){ $check = getimagesize($_FILES["book-img"]["tmp_name"]); if($check !== false) { $message = "File is an image - " . $check["mime"] . "."; $uploadOk = true; } else { $message = "File is not an image."; $uploadOk = false; } } } if($uploadOk){ if (move_uploaded_file($_FILES["book-img"]["tmp_name"], $target_file)) { $message = "The file ". basename( $_FILES["book-img"]["name"]). " has been uploaded."; $uploadOk = true; } else { $message = "Sorry, there was an error uploading your file."; $uploadOk = false; } } if($uploadOk){ $img_url = 'uploads/books/'.$_FILES["book-img"]["name"]; $timestamp = time(); $posted = date( 'Y-m-d h:m:s',$timestamp); $sql = "INSERT INTO `books` (book_title, user_id, description, book_image, published) values ('" .$_POST['title']. "','".$userid. "', '" .$_POST['description']. "', '".$img_url."', '".$posted."')"; $response = query_to_base($sql); if($response){ $message = "Book uploaded"; }else{ $message = "Failed. Try again later"; } } } include '../includes/header.php'; include '../includes/top-menu.php'; ?> <div id = "content"> <div class = "title-container text-center text-inverse"> <h1 class="page-title">Upload your book here</h1> <h4 class="sub-title">@<?= $username ?></h4> </div> <div class = "container post-container"> <?php if(isset($message)){ ?> <div class="alert alert-success" role="alert"><?= $message ?></div> <?php } ?> <div> <form method="POST" action="<?= $base_url?>admin/upload.php" enctype="multipart/form-data"> <div class="form-group row"> <label for="inputEmail3" class="col-sm-2 col-form-label">Book Name</label> <div class="col-sm-10"> <input type="text" class="form-control" id="inputEmail3" name="title" placeholder="Title"> </div> </div> <div class="form-group row"> <label for="inputbook3" class="col-sm-2 col-form-label">Description</label> <div class="col-sm-10"> <textarea id = "create-textbox" class="form-control" id="exampleTextarea" rows="6" name="description" placeholder="Write some description"></textarea> </div> </div> <div class="form-group row"> <label for="inputEmail3" class="col-sm-2 col-form-label">Book image</label> <div class="col-sm-10"> <input type="file" class="form-control" name="book-img" id = "book-img"> </div> </div> <div class="form-group row"> <div class="offset-sm-2 col-sm-10"> <input type="submit" class="btn btn-primary" value="Publish"> </div> </div> </form> </div> </div> </div> <?php include '../includes/footer-menu.php'; include '../includes/footer.php'; ?>
Python
UTF-8
439
2.875
3
[]
no_license
class Solution(object): def containsNearbyDuplicate(self, nums, k): """ :type nums: List[int] :type k: int :rtype: bool """ hash_table = {} for i,v in enumerate(nums): if v in hash_table and i - hash_table[v] <= k: return True else: hash_table[nums[i]]=i return False print Solution().containsNearbyDuplicate([],0)
C#
UTF-8
3,099
3.0625
3
[]
no_license
using System; using System.Collections.Generic; public class VendingMachine { private decimal ValorInserido = new decimal(0); private decimal ValorTotalDeVendas = new decimal(0); private List<Produto> Produtos = new List<Produto>(); private Produto ProdutoSelecionado; public void Abastecer() { if (Produtos.Count > 0) { Console.WriteLine("A máquina já está abastecida!"); return; } Produtos.Add(new Produto("Coca-Cola", new decimal(15.50), 4)); Produtos.Add(new Produto("Sprite", new decimal(12.70), 2)); Produtos.Add(new Produto("Pepsi", new decimal(14.50), 3)); Produtos.Add(new Produto("Fanta", new decimal(7.30), 8)); } public void MostrarEstoque() { Console.WriteLine("-- Bebidas na máquina: --"); bool mostrou = false; Produtos.ForEach(produto => { if (produto.Quantidade > 0) { Console.WriteLine(produto); mostrou = true; } }); if (!mostrou) { Console.WriteLine("As bebidas estão esgotadas..."); } } public void SelecionarProduto(string nome) { if (ProdutoSelecionado != null) { Console.WriteLine("Já há outro produto selecionado: " + ProdutoSelecionado.Nome); return; } var produtos = Produtos.FindAll( produto => produto.Nome.ToLower().StartsWith(nome.ToLower()) && produto.Quantidade > 0 ); if (produtos.Count > 1) { Console.WriteLine("Por favor, escreva um nome mais específico!"); } else if (produtos.Count == 0) { Console.WriteLine("Produto não encontrado!"); } else { ProdutoSelecionado = produtos[0]; Console.WriteLine("Selecionado: " + ProdutoSelecionado.Nome); Console.WriteLine($"Insira R$ {ProdutoSelecionado.FormatarPreco()} para concluir a compra"); } } public void InserirValor(decimal valor) { if (ProdutoSelecionado == null) { Console.WriteLine("Não há produto selecionado!"); return; } ValorInserido += valor; if (ValorInserido >= ProdutoSelecionado.Preco) { Console.WriteLine("Venda concluída. Aqui está sua " + ProdutoSelecionado.Nome); decimal troco = ValorInserido - ProdutoSelecionado.Preco; if (troco > 0) { Console.WriteLine("Troco: R$ " + troco.ToString("0.00")); } ValorTotalDeVendas += ProdutoSelecionado.Preco; ProdutoSelecionado.Quantidade--; ProdutoSelecionado = null; ValorInserido = 0; } else { decimal valorRestante = ProdutoSelecionado.Preco - ValorInserido; Console.WriteLine("Valor faltante: R$ " + valorRestante.ToString("0.00")); } } public void MostrarValorTotalDeVendas() { Console.WriteLine($"Valor total de vendas realizadas: R$ {ValorTotalDeVendas.ToString("0.00")}"); } }
C++
UTF-8
383
2.546875
3
[]
no_license
#include <iostream> #include <vector> using namespace std; int main() { int n = 0; int t1 = 0; int t2 = 1; cin>>n; int cont = 3; cout<<"-> "<<t1<<" ->"<<t2; while(cont<= n){ int t3=t1+t2; if(t3 < n){ cout<<" -> "<<t3; t1=t2; t2=t3; cont +=1; }else{ return 0; } } return 0; }
PHP
UTF-8
1,357
2.578125
3
[ "MIT" ]
permissive
<?php namespace App; use App\Models\Employee; use Illuminate\Foundation\Auth\User as Authenticatable; use Illuminate\Notifications\Notifiable; class User extends Authenticatable { use Notifiable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'name', 'email', 'password', 'present_phone', 'perma_number', 'role', 'password', 'images', ]; /** * The attributes that should be hidden for arrays. * * @var array */ protected $hidden = [ 'password', 'remember_token', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'email_verified_at' => 'datetime', ]; public function is_admin() { if ($this->role == '1') { return true; } return false; } public function employee() { return $this->hasOne(Employee::class, 'user_id', 'id'); } public function currentCountry() { return $this->belongsTo('App\Models\Country', 'curr_country_id', 'id'); } public function state() { return $this->hasOne('App\Models\State', 'id', 'curr_state_id'); } public function city() { return $this->hasOne('App\Models\City', 'id'); } }
C#
UTF-8
966
2.578125
3
[]
no_license
using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; using WebApi3.Models; using WebApi3.Services; namespace WebApi3.Controllers { [ApiController] [Route("api/warehouses2")] public class Warehouses2Controller : ControllerBase { private IProductService2 _iProductService2; public Warehouses2Controller(IProductService2 productService2) { _iProductService2 = productService2; } [HttpPost] public async Task<IActionResult> RegisterProductWithProcedure([FromBody] Product newProduct) { var resultOperation = await _iProductService2.AddNewProductFromProc(newProduct); var error = int.Parse(resultOperation.Substring(0, 3)); if (error == 200) { return Ok(resultOperation.Substring(4)); } else { return BadRequest("Procedura nie udana"); } } } }
SQL
UTF-8
4,435
2.90625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.7.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1 -- Generation Time: Apr 11, 2019 at 05:48 AM -- Server version: 10.1.29-MariaDB -- PHP Version: 7.2.0 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `project` -- -- -------------------------------------------------------- -- -- Table structure for table `match_info` -- CREATE TABLE `match_info` ( `match_name` varchar(15) NOT NULL, `Bat1` varchar(20) NOT NULL, `Bat2` varchar(20) NOT NULL, `Bat3` varchar(20) NOT NULL, `Bat4` varchar(20) NOT NULL, `WK1` varchar(20) NOT NULL, `Bat6` varchar(20) NOT NULL, `Bat7` varchar(20) NOT NULL, `Bat8` varchar(20) NOT NULL, `Bat9` varchar(20) NOT NULL, `WK2` varchar(20) NOT NULL, `Bow1` varchar(20) NOT NULL, `Bow2` varchar(20) NOT NULL, `Bow3` varchar(20) NOT NULL, `Bow4` varchar(20) NOT NULL, `Bow5` varchar(20) NOT NULL, `Bow6` varchar(20) NOT NULL, `Bow7` varchar(20) NOT NULL, `Bow8` varchar(20) NOT NULL, `All1` varchar(20) NOT NULL, `All2` varchar(20) NOT NULL, `All3` varchar(20) NOT NULL, `All4` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `p1_team` -- CREATE TABLE `p1_team` ( `PhoneNo` bigint(15) NOT NULL, `match_name` varchar(20) NOT NULL, `WK` varchar(20) NOT NULL, `Bat1` varchar(12) NOT NULL, `Bat2` varchar(15) NOT NULL, `Bat3` varchar(15) NOT NULL, `Bat4` varchar(15) NOT NULL, `Bow1` varchar(15) NOT NULL, `Bow2` varchar(15) NOT NULL, `Bow3` varchar(15) NOT NULL, `Bow4` varchar(15) NOT NULL, `All1` varchar(15) NOT NULL, `All2` varchar(15) NOT NULL, `Points` int(15) NOT NULL, `Captain` varchar(20) DEFAULT NULL, `Vice_Captain` varchar(20) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `p1_team` -- INSERT INTO `p1_team` (`PhoneNo`, `match_name`, `WK`, `Bat1`, `Bat2`, `Bat3`, `Bat4`, `Bow1`, `Bow2`, `Bow3`, `Bow4`, `All1`, `All2`, `Points`, `Captain`, `Vice_Captain`) VALUES (9979271245, 'INDVsAUS', 'Dhoni', 'Rohit', 'Virat', 'Steve', 'Warner', 'Bhuvi', 'Bumrah', 'Shami', 'Ashwin', 'Jadeja', 'Maxwell', 150, 'Dhoni', 'Virat'), (9999944444, 'INDVsAUS', 'Nevil', 'Steve', 'Warner', 'Khwaja', 'Ricky', 'Shami', 'Ashwin', 'Lyon', 'Zampa', 'Hardik', 'Stoinis', 80, 'Warner', 'Hardik'); -- -------------------------------------------------------- -- -- Table structure for table `reguser` -- CREATE TABLE `reguser` ( `Name` varchar(15) NOT NULL, `Password` varchar(50) NOT NULL, `Email` varchar(30) NOT NULL, `PhoneNo` bigint(15) NOT NULL, `Points` int(15) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `reguser` -- INSERT INTO `reguser` (`Name`, `Password`, `Email`, `PhoneNo`, `Points`) VALUES ('Vedang', '7c4a8d09ca3762af61e59520943dc26494f8941b', 'vedang@gmail.com', 8888888888, 50), ('Hardik', '7c4a8d09ca3762af61e59520943dc26494f8941b', 'hardik@gmail.com', 9979271245, 100), ('ronak', '7c4a8d09ca3762af61e59520943dc26494f8941b', 'ronak@gmail.com', 9999944444, 80), ('Harshad', '7c4a8d09ca3762af61e59520943dc26494f8941b', 'harshad@gmail.com', 9999999999, 50); -- -------------------------------------------------------- -- -- Table structure for table `time_to_expire` -- CREATE TABLE `time_to_expire` ( `date_of_expiry` datetime NOT NULL, `match_name` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `time_to_expire` -- INSERT INTO `time_to_expire` (`date_of_expiry`, `match_name`) VALUES ('2019-04-12 18:15:00', 'INDVSNZ'); -- -- Indexes for dumped tables -- -- -- Indexes for table `match_info` -- ALTER TABLE `match_info` ADD PRIMARY KEY (`match_name`); -- -- Indexes for table `p1_team` -- ALTER TABLE `p1_team` ADD PRIMARY KEY (`PhoneNo`), ADD UNIQUE KEY `PhoneNo` (`PhoneNo`); -- -- Indexes for table `reguser` -- ALTER TABLE `reguser` ADD PRIMARY KEY (`PhoneNo`); -- -- Indexes for table `time_to_expire` -- ALTER TABLE `time_to_expire` ADD PRIMARY KEY (`match_name`); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Java
UTF-8
1,777
2.3125
2
[]
no_license
package ng.com.bitsystems.mis.converters.accounts.payment.insurance; import ng.com.bitsystems.mis.command.accounts.payments.insurrance.InsuredConsultationCommand; import ng.com.bitsystems.mis.converters.consultation.BookConsultationCommandToBookConsultation; import ng.com.bitsystems.mis.models.accounts.payments.insurance.InsuredConsultations; import org.springframework.core.convert.converter.Converter; public class InsuredConsultationCmdToInsuredConsultation implements Converter<InsuredConsultationCommand, InsuredConsultations> { private BookConsultationCommandToBookConsultation bookConsultationCommandToBookConsultation; private ProgramCommandToProgram programCommandToProgram; public InsuredConsultationCmdToInsuredConsultation(BookConsultationCommandToBookConsultation bookConsultationCommandToBookConsultation, ProgramCommandToProgram programCommandToProgram) { this.bookConsultationCommandToBookConsultation = bookConsultationCommandToBookConsultation; this.programCommandToProgram = programCommandToProgram; } @Override public InsuredConsultations convert(InsuredConsultationCommand source) { if(source == null){ return null; } final InsuredConsultations insuredConsultations = new InsuredConsultations(); insuredConsultations.setId(source.getId()); insuredConsultations.setPercentageIncured(source.getPercentageIncurred()); insuredConsultations.setBookConsultation(bookConsultationCommandToBookConsultation.convert(source.getBookConsultationCommand())); insuredConsultations.setPrograms(programCommandToProgram.convert(source.getProgramsCommand())); return insuredConsultations; } }
Markdown
UTF-8
6,722
2.859375
3
[ "Unlicense" ]
permissive
# Why Minecraft is the most important game of the decade Published at: **2019-11-07T16:30:00+00:00** Author: **Charlie Hall** Original: [Polygon](https://www.polygon.com/2019/11/7/20952214/minecraft-most-important-game-of-the-decade-2010) When I first heard about Minecraft, it was how its creator, Markus “Notch” Persson, had made an outlandish amount of money through PayPal. In 2010, a few months after putting the unfinished version of his game up for sale, the Swedish developer had raked in more than €600,000. The cash came in so quickly that the payment processor eventually froze his account to prevent fraud. Almost exactly four years later, that massive take would pale in comparison to what Microsoft paid for Notch’s company — an astounding $2.5 billion. Counting Minecraft among the most influential games of the 2010s is a no-brainer. According to its developer, Mojang, Minecraft recently became the bestselling video game of all time, beating out Tetris by moving over 176 million units. Unlike Tetris, it hit that number in a single decade. As the 2010s draw to a close, we’re taking stock of the best pop culture of the decade. And we’re reevaluating the all the ways in which the face of entertainment changed from 2010 through 2019. Join us! Read more: The 100 best games of the decade The best movies of the decade, according to us The best comics of the decade Minecraft has achieved this success because it’s more than a game; it’s a platform, a pocket dimension inside your computer or game console or smartphone or prototype augmented reality headset. It can become anything you need it to be. Press a button, and Minecraft generates a world eight times larger than the surface of the Earth. You can walk across it for years, or you can dig beneath the surface and use the treasures you find to build a fortress atop a mountain. Take a little time and you can make castles and cities, or just settle down in the country with a herd of pigs. Minecraft is somewhere you can be alone, when you need to be — your own giant world. Community has been the single largest factor in Minecraft’s growth over the last decade, and it happened even as the game launched. The sheer gravitational power of its blocky little worlds forced people onto YouTube in order to properly explain what the hell the game even is. As Minecraft grew, so too did this new personality-driven aspect of gaming. Now there’s an entire industry of people who essentially perform games like Minecraft on demand. But it’s also the perfect place to build a community. The game has grown a thin veneer of narrative over the years, but the story has been an afterthought. The most memorable moments are the anecdotes players share in playgrounds, offices, and on countless livestreams. Without Minecraft, Twitch might have never gotten off the ground. Without these blocky digital worlds, it’s safe to say that there might not be a “PewDiePie” or a “Ninja,” or the dozens of people around the world nipping at their heels. Without Minecraft, games themselves would be very different today. Minecraft set off a kind of arms race. Suddenly the market for video games was much, much larger than many in the mainstream thought it was or ever could be. There was a yearslong scramble to create the next big thing, and the next big thing had to be just as popular on YouTube and Twitch as Minecraft. It took a while for game developers to figure out what that meant. For a time it seemed like every new project was open-world, every new game had to include mechanics for construction, and everything had to have elements of resource gathering and survival. Suddenly, everything new and exciting was being launched directly into early access. Games didn’t need to be finished anymore; developers were committing themselves to building things entirely in the open, rather than hiding them for years behind layers of secrecy. For a time — and almost by necessity — Kickstarter became the funding platform of choice for every independent game developer. How else were individuals and small teams supposed to take money from consumers hunting for the next breakout hit? Most games that tried to be the next Minecraft failed in the attempt. The biggest exception was Fortnite. But, seven years into development, Epic Games’ attempt to fuse Minecraft-style building mechanics with a third-person shooter had veered wildly off course. When the game initially launched — on retail store shelves, while also still in early access — all it managed to do was hurt people’s hands. Yet, just like Mojang with Minecraft, Epic managed to build a game that was actually a platform. Of course, the company also created the powerful game engine called Unreal, which is itself a platform. But Fortnite was unique, something pliable and stable, whose core mechanics Epic could style and adapt into something else. The gamble paid off, and now Fortnite’s battle royale mode stands as the next contender, the thing most likely to knock Minecraft off its throne as the biggest game of all time. All the while, people have kept on playing Minecraft. It’s become a comfortable space, especially for YouTubers and streamers who find themselves in a rut. In a very real way, even after a decade of development, Persson’s most significant achievement isn’t the number of units Minecraft has sold or the quality of the games that have been inspired by it. His biggest success is in creating a legacy — something that will continue go on long after his departure. Minecraft’s legacy is its ability to create and support communities, both inside the game world and out. A decade from now, despite whatever toxic tirade its billionaire creator latches onto next, Minecraft will still be bringing people together. Ultimately, video games aren’t a monolith. This hobby, this art form, and this industry are bigger than just one game; they’re bigger than any console; and they certainly aren’t limited to just one genre. And neither is Minecraft, a game that is now more influential and more vital than its creator could ever hope to be. The most influential video games aren’t always the most popular, and rankings never tell the whole story. To mark the end of the decade, our editorial team published a list of the top 100 games . We’ve also created this supplemental series, in which individual Polygon writers get to talk about the most important games from that same period, and exactly how they changed the course of the industry.
Java
UTF-8
2,653
2.375
2
[]
no_license
package avaliacao_pratica_andrecremonezi.andrecremoneziprova.model.persistence; import android.content.ContentValues; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.List; import avaliacao_pratica_andrecremonezi.andrecremoneziprova.model.entities.SocialNetwork; public class SocialNetworkRepository { public SocialNetworkRepository(){ super(); } public static void save(SocialNetwork socialNetwork) { DataBaseHelper dataBaseHelper = DataBaseHelper.getIstance(); SQLiteDatabase db = dataBaseHelper.getWritableDatabase(); ContentValues values = SocialNetworkContract.getContentValues(socialNetwork); if (socialNetwork.getId() == null) { db.insert(SocialNetworkContract.TABLE, null, values); } else { String where = SocialNetworkContract.ID + " = ? "; String[] params = {socialNetwork.getId().toString()}; db.update(SocialNetworkContract.TABLE, values, where, params); } db.close(); dataBaseHelper.close(); } public static void delete(long id) { DataBaseHelper dataBaseHelper = DataBaseHelper.getIstance(); SQLiteDatabase db = dataBaseHelper.getWritableDatabase(); String where = SocialNetworkContract.ID + " = ? "; String[] params = {String.valueOf(id)}; db.delete(SocialNetworkContract.TABLE, where, params); db.close(); dataBaseHelper.close(); } public static List<SocialNetwork> getAllByContact(Long idcontact) { DataBaseHelper dataBaseHelper = DataBaseHelper.getIstance(); SQLiteDatabase db = dataBaseHelper.getReadableDatabase(); String where = SocialNetworkContract.CONTACTID + " = ? "; String[] params = {idcontact.toString()}; Cursor cursor = db.query(SocialNetworkContract.TABLE, SocialNetworkContract.COLUNS, where, params, null, null, SocialNetworkContract.ID); List<SocialNetwork> values = SocialNetworkContract.getSocialNetworks(cursor); db.close(); dataBaseHelper.close(); return values; } public static List<SocialNetwork> getAll() { DataBaseHelper dataBaseHelper = DataBaseHelper.getIstance(); SQLiteDatabase db = dataBaseHelper.getReadableDatabase(); Cursor cursor = db.query(SocialNetworkContract.TABLE, SocialNetworkContract.COLUNS, null, null, null, null, SocialNetworkContract.ID); List<SocialNetwork> values = SocialNetworkContract.getSocialNetworks(cursor); db.close(); dataBaseHelper.close(); return values; } }
C#
UTF-8
5,110
3.078125
3
[]
no_license
// Name: Gene Pressinger // CSC339 - Spring 2021 // Assignment 4 using System; using System.Drawing; using System.Windows.Forms; namespace Connect4 { public partial class Form1 : Form { private Board board; public Form1() { InitializeComponent(); //adds the event handler for when the screen is painted Paint += new PaintEventHandler(pic_board_Paint); } private void Form1_Load(object sender, EventArgs e) { //gets called when the main form is loaded board = new Board(this); // Get the name for Yellow UserInput Input = new UserInput("Enter a name for Yellow.", board); Input.ShowDialog(); // Get the name for Red Input = new UserInput("Enter a name for Red.", board); Input.ShowDialog(); // Start the game board.StartGame(); } private void pic_board_Paint(object sender, PaintEventArgs e) { //gets called whenever the screen is painted board.DrawBoard(e.Graphics); } private void btn_col1_Click(object sender, EventArgs e) { // place a mark at column index 0 board.PlaceMark(0); } private void btn_col2_Click(object sender, EventArgs e) { // place a mark at column index 1 board.PlaceMark(1); } private void btn_col3_Click(object sender, EventArgs e) { // place a mark at column index 2 board.PlaceMark(2); } private void btn_col4_Click(object sender, EventArgs e) { // place a mark at column index 3 board.PlaceMark(3); } private void btn_col5_Click(object sender, EventArgs e) { // place a mark at column index 4 board.PlaceMark(4); } private void btn_col6_Click(object sender, EventArgs e) { // place a mark at column index 5 board.PlaceMark(5); } private void btn_col7_Click(object sender, EventArgs e) { // place a mark at column index 6 board.PlaceMark(6); } public void GameWon() { // Get the winner string Winner = board.GetWinner(); // Write the winner to the console Console.WriteLine("Player {0} won the game.", Winner); // Send players a system message showing who won MessageBox.Show("Congratualations " + Winner + "! You won the game.", "Game Finished"); // Update current player label text and center it CurrentPlayerLabel.Text = Winner + " won the game!"; CurrentPlayerLabel.Location = new Point((Width - CurrentPlayerLabel.Width) / 2, CurrentPlayerLabel.Location.Y); // Disable buttons btn_col1.Enabled = false; btn_col2.Enabled = false; btn_col3.Enabled = false; btn_col4.Enabled = false; btn_col5.Enabled = false; btn_col6.Enabled = false; btn_col7.Enabled = false; } private void NewGameMenuItem_Click(object sender, EventArgs e) { // Reset the board board.ResetBoard(); // Refresh to update the board UI Refresh(); // Enable all buttons btn_col1.Enabled = true; btn_col2.Enabled = true; btn_col3.Enabled = true; btn_col4.Enabled = true; btn_col5.Enabled = true; btn_col6.Enabled = true; btn_col7.Enabled = true; // Start the new game board.StartGame(); } public void DisableColumn(int Column) { // Disable the given column's button Controls["btn_col" + Column].Enabled = false; } private void QuitGameMenuItem_Click(object sender, EventArgs e) { // Ask the user if they really want to quit DialogResult Dialog = MessageBox.Show("Are you sure you want to quit?", "Quit Confirmation", MessageBoxButtons.YesNo); if (Dialog == DialogResult.Yes) Dispose(); } private void ChangeStarterMenuItem_Click(object sender, EventArgs e) { // Change menu text and show confirmation message ChangeStarterMenuItem.Text = "Change Starter to: " + board.ChangeStarter(); MessageBox.Show("Change will take affect next game.", "Starter Color Changed"); } public void UpdateTurnLabel(string Player) { // Update the current player text CurrentPlayerLabel.Text = "Current Player: " + Player + " (" + board.GetCurrentPlayerString() + ")"; // Center the current player label CurrentPlayerLabel.Location = new Point((Width - CurrentPlayerLabel.Width) / 2, CurrentPlayerLabel.Location.Y); } } }
Python
UTF-8
428
3.390625
3
[]
no_license
c = soma = 0 x = 1 while c < 2 and x == 1: n = float(input()) if n < 0 or n > 10: print("nota invalida") if 0 <= n <= 10: soma += n c += 1 if c == 2: print("media = {:.2f}".format(soma/2)) x = -1 while x < 1 or x > 2: print("novo calculo (1-sim 2-nao)") x = int(input()) if x == 1: c = soma = 0 if x == 2: break
Java
UTF-8
2,672
2.203125
2
[ "MIT" ]
permissive
package rocks.frieler.android.beans; import static org.hamcrest.CoreMatchers.hasItem; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import android.content.Context; import android.content.res.AssetManager; import org.jetbrains.annotations.NotNull; import org.junit.jupiter.api.Test; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Collections; import java.util.List; class BeanConfigurationsAssetScannerJavaApiTest { private final Context context = mock(Context.class); private final BeanConfigurationsAssetScanner beanConfigurationsAssetScanner = new BeanConfigurationsAssetScanner(context); private final AssetManager assetManager = mock(AssetManager.class); @Test void canInstantiateAJavaBeanConfiguration() throws IOException { when(assetManager.list(BeanConfigurationsAssetScanner.BEAN_CONFIGURATIONS_ASSET_PATH)).thenReturn(new String[] { "beans.txt" }); when(assetManager.open(BeanConfigurationsAssetScanner.BEAN_CONFIGURATIONS_ASSET_PATH + "/beans.txt")) .thenReturn(new ByteArrayInputStream(("rocks.frieler.android.beans.BeanConfigurationsAssetScannerJavaApiTest$AJavaBeanConfiguration\n").getBytes())); List<BeanConfiguration> beanConfigurations = beanConfigurationsAssetScanner.scan(assetManager); assertThat(beanConfigurations, hasItem(instanceOf(AJavaBeanConfiguration.class))); } public static class AJavaBeanConfiguration extends BeanConfiguration { @NotNull @Override public List<BeanDefinition<?>> getBeanDefinitions() { return Collections.emptyList(); } } @Test void canInstantiateAJavaBeanConfigurationNeedingTheContext() throws IOException { when(assetManager.list(BeanConfigurationsAssetScanner.BEAN_CONFIGURATIONS_ASSET_PATH)).thenReturn(new String[] { "beans.txt" }); when(assetManager.open(BeanConfigurationsAssetScanner.BEAN_CONFIGURATIONS_ASSET_PATH + "/beans.txt")) .thenReturn(new ByteArrayInputStream(("rocks.frieler.android.beans.BeanConfigurationsAssetScannerJavaApiTest$AJavaBeanConfigurationNeedingTheContext\n").getBytes())); List<BeanConfiguration> beanConfigurations = beanConfigurationsAssetScanner.scan(assetManager); assertThat(beanConfigurations, hasItem(instanceOf(AJavaBeanConfigurationNeedingTheContext.class))); } public static class AJavaBeanConfigurationNeedingTheContext extends BeanConfiguration { public AJavaBeanConfigurationNeedingTheContext(Context context) {} @NotNull @Override public List<BeanDefinition<?>> getBeanDefinitions() { return Collections.emptyList(); } } }
C++
GB18030
1,340
3.46875
3
[]
no_license
// ƣл˹(Sierpinski)ΣҲеƬ // 뻷Visual C++ 6.0EasyX 2011ݰ // £2010-11-16 // #include <graphics.h> #include <conio.h> #include <time.h> /* ˵һʵֹ̣ 3 P[0]P[1]P[2] 1 P Ƶ P [0, 2] ڵ n P = P P[n] е㣻 ظִв (3)(5) Ρ ܼ򵥣ȻԺܴ󣬵ǽȫƵģһȤͼҲǴ˵ел˹Ρϲл˹ε £ עΪЧ(1)ֶָˡϲĻԽ޸Ϊ */ void main() { srand((unsigned)time(NULL)); // POINT P[3] = { { 320, 50 }, { 120, 400 }, { 520, 400 } }; // 趨ε POINT p = { rand() % 640, rand() % 480 }; // ǰ // ʼͼģʽ initgraph(640, 480); // int n; for (int i = 0; i <= 30000; i++) { n = rand() % 3; p.x = (p.x + P[n].x) / 2; p.y = (p.y + P[n].y) / 2; putpixel(p.x, p.y, GREEN); } // ˳ getch(); closegraph(); }
PHP
UTF-8
2,532
2.671875
3
[]
no_license
<?php //if(!isset($_SESSION["login"])){ // header("Location: http://fieldofdreams.ml/Sign-In.html"); //} // Get the PHP helper library from https://twilio.com/docs/libraries/php //Database: //Table-> user_phonenumbers; column-> phonenum; require __DIR__ . '/twilio-php-master/Twilio/autoload.php'; // Loads the library use Twilio\Twiml; use Twilio\Rest\Client; // Your Account SID, Auth Token, and Twilio phone number from twilio.com/console $twilioPhone = '+13025817175'; $sid = 'AC89a94ed31367669484d648d1157dcadd'; $token = 'c96131fb4b572ca3844d9de828e0832d'; //connect to database $DB_HOST = 'localhost'; $DB_NAME = 'id7335129_db'; $DB_USER = 'id7335129_fieldofdreams'; $DB_PASSWORD = 'database'; //Twilio API to respond to incoming message $response = new Twiml; $body = $_REQUEST['Body']; $fromNumber = $_REQUEST['From']; // user's number $default = "Not a valid keyword"; $userJoin = false; $userStop = false; if (strtolower(trim($body)) == "join") { $response->message("Thank you for signing up for alerts from Field of Dreams. Text 'done' at anytime if you no longer to wish receive our alerts"); $userJoin = true; } else if(strtolower(trim($body)) == "done") { $response->message("You will no longer recieve alerts from Field of Dreams. Text 'join' at anytime to recieve our alerts."); $userStop = true; }else{ $response->message($default); } //responds to user message print $response; // Got errors when trying to print/echo something if($userJoin == true){ //create connection $conn=mysqli_connect($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME); //check connection if (!$conn){ die("Failed to connect to MySQL: " . mysqli_connect_error()); } //echo "Connected to database "; //query for database $sql = "INSERT IGNORE INTO user_phonenumbers (phonenum) VALUES ('$fromNumber')"; if(mysqli_query($conn, $sql)){ //echo "new record created "; }else{ //echo "Error: " . $sql . "<br>" . mysqli_error($conn); } } if($userStop == true){ //create connection $conn=mysqli_connect($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME); //check connection if (!$conn){ die("Failed to connect to MySQL: " . mysqli_connect_error()); } //echo "Connected to database "; //query for database $sql = "DELETE FROM user_phonenumbers WHERE phonenum='$fromNumber'"; if(mysqli_query($conn, $sql)){ //echo "new record created "; }else{ //echo "Error: " . $sql . "<br>" . mysqli_error($conn); } } ?>
Markdown
UTF-8
7,985
3.09375
3
[]
no_license
--- author: name: Rob Hawkes picture: 112529 body: "I'm new here - so Hi everybody =D\r\n\r\nCurrently I'm working on the logo and website for my freelance web design company. The company is called Rawkes - I want to portray youth, strength and a feel of modernism in the logo.\r\n\r\nI have come up with some graphical logos, but I will keep them off here. The latest attempt at the logo is purely text based, and I would love some feedback on it.\r\n\r\nThe 'R' in the logo was designed on paper and traced into a vector application.\r\n\r\n[Below is the original design]\r\n[img:sites/default/files/old-images/rawkes_text_4571.jpg]\r\n\r\n\r\n.\r\n\r\n\r\n[The version below has some tweaks (..but no styling at the moment)]\r\n[img:sites/default/files/old-images/rawkes_text_take2_6261.jpg]\r\n\r\n\r\n\r\nThank you,\r\nRob" comments: - author: name: kco picture: 110793 body: "<em> > I want to portray youth, strength and a feel of modernism in the logo.</em>\r\n\r\nWhat do you mean by modernist? is it the <a href=\"http://en.wikipedia.org/wiki/Modernism\">modernist art movement </a>(which I don't relate to much to your logo) or \"New-Fresh\" \r\n\r\nWhy don't you give us a bit more background about this freelance company? What is it that you do? how different could you make it from others? why should I hire you to do some freelance work? Maybe that could help you integrate some new elements to it. Think about metaphors, or anything that could relate to it.\r\n\r\nPersonally, I really hate to see the \"R\" chopped like that, I recently saw it done to another logo that I can't recall at the moment and it really bothers me. The letter has no balance and looks like its going to fall backwards.\r\n\r\nHope that helps to keep you going!\r\n\r\nKco" created: '2007-05-15 20:09:33' - author: name: Rob Hawkes picture: 112529 body: "I obviously used modernism in the wrong way - I mean I just want it to look fresh and new, exactly like you said.\r\n\r\nHere is a brief background behind Rawkes. It is a web site design company set up by a young creative to build fresh, clean and efficient web sites - in both design and programming. It prides itself on following current web standards and guidelines which let it stand out from the many other 'web design' companies that offer quick and dirty websites produced with no skill or affection.\r\n\r\nThat's enough spiel.\r\n\r\nI think you are right about the balancing of the R, which is a shame. Luckily I came up with many different R's in my sketches - so I can try picking another one.\r\n\r\nDo you have any advice on the styling of the R, or any metaphors that sprung to mind after hearing about me?\r\n\r\nThank you,\r\n\r\nRob" created: '2007-05-15 22:57:10' - author: name: Ratbaggy picture: 111633 body: "a play on the word ROCKS! in 'leet' speak i.e, \"Web Design Rawkes\"\r\n\r\non a side note, just for thought ... \"build fresh, clean and efficient web sites\" by \"following current web standards and guidelines\" - the use of the word 'fresh' is destroyed by including 'following' - fresh = original and of a kind not seen before.\r\n<br />\r\n<br />\r\n<br />\r\n<br />\r\n----------\r\n<strong>Paul Ducco</strong>\r\n<a href=\"http://www.solid-creative.com/design.htm\">Graphic Design Melbourne</a>\r\n" created: '2007-05-15 23:18:29' - author: name: Rob Hawkes picture: 112529 body: "My skills obviously don't lie in writing. Thanks for pointing that discrepancy out though, I'll use something other than 'following' in the future.\r\n\r\nI like the 'rocks' idea, it might confuse people with the pronunciation of Rawkes, but it is definitely something to play with - Thank you." created: '2007-05-16 01:06:14' - author: name: kco picture: 110793 body: "Rob, \r\n\r\nI do not doubt that you can build fresh, clean and efficient websites. In fact there's a ton of talented people out there. There's also plenty of mediocre design out there. There's a ton of people that follow web standards too, <a href=\"http://simplebits.com/\"> here's one</a> that I believe do their job quite as you describe yours. I think you don't need to let us know your skills (your clients will see that once they see your portfolio. Instead have fun with this, put some extra meaning to it.\r\nI like the ROCKS idea too. The name is a clever too, I believe it comes from your name \"Rob Hawkes\" right? well you got a good start. You have shorten it why not emphasize that? perhaps add an apostrophe then try to find a reason for it. First though, why do you shorten things? maybe because it doesn't fit somewhere, well now it does! you could play along with concepts/metaphors/stories like that. Perhaps it fits into a box or what not?\r\n\r\nAs of the \"R\" i would say don't get stuck on trying to fit a special \"R\". If the concept recalls it, then do so after you have your Idea clear.\r\n\r\nKeep it up!\r\n\r\nKco" created: '2007-05-16 06:22:49' - author: name: Rob Hawkes picture: 112529 body: "All this advice is very helpful. You were correct about the origins of the word Rawkes, I felt that I would be restricting future growth by naming the company after my full name.\r\n\r\nMy one concern with using a phrase (ie. Web design that Rawkes), do you mean to use a phrase as the logo - or just an idea for a banner or strap line? I'm still a little confused about what is being suggested here for the logo in particular.\r\n\r\nI've only just got up and my brain isn't quite up to speed, but what do you mean by \"Perhaps it fits into a box..\"?\r\n\r\nThank you.\r\n\r\nRob" created: '2007-05-16 10:14:17' - author: name: Ratbaggy picture: 111633 body: "my suggestion was just an idea of a new way of thinking ... outside the box (not wanting to confuse you with your 'fits within a box' comment.)\r\n\r\nAnd just to clarify ... my initial thought was \"Web Design Rawkes\" ... without the \"that\" - it shows a passion and playfulness that simply shines freshness. However you convey that visually is up to you, but it sure opens a few more doors that just saying \"Ok, the name is Rawkes, let's make it [insert 'fresh' word here]\"\r\n\r\ni.e, just brainstorming\r\n\r\nenjoy\r\n\r\n<br />\r\n<br />\r\n<br />\r\n<br />\r\n----------\r\n<strong>Paul Ducco</strong>\r\n<a href=\"http://www.solid-creative.com/design.htm\">Graphic Design Melbourne</a>\r\n" created: '2007-05-16 13:54:20' - author: name: Ratbaggy picture: 111633 body: "regarding your existing logos ... they don't do much for me.\r\n\r\nThe foot of the R should (IMO) definitely sit on the baseline though.<br />\r\n<br />\r\n<br />\r\n<br />\r\n----------\r\n<strong>Paul Ducco</strong>\r\n<a href=\"http://www.solid-creative.com/design.htm\">Graphic Design Melbourne</a>\r\n" created: '2007-05-16 13:56:44' - author: name: kco picture: 110793 body: "Don't lock up on what I said, I was just trowing words. What I meant is that you could find an interesting reason for your name to be shortened. The key element is being said by Paul, *BRAINSTORM.\r\n\r\n*Get all your ideas out, start with your worst (don't be afraid) and then the good ones will come up. Write words, thoughts, get a <a href=\"http://en.wikipedia.org/wiki/Mind_map\">mind map</a> going. That would help you squeeze your brain for ideas. At least that's how I do.\r\n\r\nKco" created: '2007-05-16 19:55:04' - author: name: henrypijames picture: 112537 body: Drop the gradient effect -- it looks very cheap. And to get a "modern and fresh" feel, consider thinning down the letters. created: '2007-05-18 21:22:43' date: '2007-05-15 13:33:10' node_type: forum title: Rawkes Design - Logo ---
PHP
UTF-8
1,486
2.875
3
[ "Apache-2.0" ]
permissive
<?php namespace SparkPost\Test\TestUtils; class ClassUtils { private $class; public function __construct($fqClassName) { $this->class = new \ReflectionClass($fqClassName); } /** * Allows access to private methods. * * This is needed to mock the GuzzleHttp\Client responses * * @param string $name * * @return \ReflectionMethod */ public function getMethod($name) { $method = $this->class->getMethod($name); $method->setAccessible(true); return $method; } /** * Allows access to private properties in the Transmission class. * * This is needed to mock the GuzzleHttp\Client responses * * @param object $instance * @param string $property * * @return mixed */ public function getProperty($instance, $property) { $prop = $this->class->getProperty($property); $prop->setAccessible(true); return $prop->getValue($instance); } /** * Allows access to private properties in the Transmission class. * * This is needed to mock the GuzzleHttp\Client responses * * * @param object $instance * @param string $property * @param mixed $value */ public function setProperty($instance, $property, $value) { $prop = $this->class->getProperty($property); $prop->setAccessible(true); $prop->setValue($instance, $value); } }
Java
UTF-8
6,949
2.28125
2
[]
no_license
package stage_one.chicken; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Point; import java.awt.Toolkit; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import AdditionalFunction.Brush; import AdditionalFunction.Timer; import AdditionalFunction.pause; import stage_one.menu; class stage_chicken3 extends JPanel{ ImageIcon bgimage = new ImageIcon(getClass().getClassLoader().getResource("pic/table.png")); ImageIcon[] sauce = {new ImageIcon(getClass().getClassLoader().getResource("pic/sauce1.png")), new ImageIcon(getClass().getClassLoader().getResource("pic/sauce2.png")), new ImageIcon(getClass().getClassLoader().getResource("pic/sauce3.png")), new ImageIcon(getClass().getClassLoader().getResource("pic/sauce4.png")), new ImageIcon(getClass().getClassLoader().getResource("pic/sauce5.png")), new ImageIcon(getClass().getClassLoader().getResource("pic/sauce6.png"))}; ImageIcon ketchup = new ImageIcon(getClass().getClassLoader().getResource("pic/ketchup.png")); ImageIcon kochujang = new ImageIcon(getClass().getClassLoader().getResource("pic/kochujang.png")); ImageIcon water = new ImageIcon(getClass().getClassLoader().getResource("pic/water.png")); ImageIcon soy_sauce = new ImageIcon(getClass().getClassLoader().getResource("pic/soy_sauce.png")); JPanel panel; int count = 0; static int count2 = 0; boolean clear = false; int startX, startY, endX, endY; stage_chicken3(JFrame frame){ setLayout(null); panel = this; Timer tm = new Timer(30, panel, frame,4); tm.start(); new pause(panel,tm); JLabel ingre_sauce = new JLabel(sauce[0]); ingre_sauce.setSize(615, 475); ingre_sauce.setBounds(210, 210, ingre_sauce.getWidth(), ingre_sauce.getHeight()); JLabel ingre_ketchup = new JLabel(ketchup); ingre_ketchup.setSize(191, 146); ingre_ketchup.setBounds(90, 80, ingre_ketchup.getWidth(), ingre_ketchup.getHeight()); JLabel ingre_kochujang = new JLabel(kochujang); ingre_kochujang.setSize(191, 146); ingre_kochujang.setBounds(310, 40, ingre_kochujang.getWidth(), ingre_kochujang.getHeight()); JLabel ingre_water = new JLabel(water); ingre_water.setSize(191, 146); ingre_water.setBounds(520, 40, ingre_water.getWidth(), ingre_water.getHeight()); JLabel ingre_soysauce = new JLabel(soy_sauce); ingre_soysauce.setSize(191, 146); ingre_soysauce.setBounds(750, 80, ingre_soysauce.getWidth(), ingre_soysauce.getHeight()); add(ingre_water); add(ingre_ketchup); add(ingre_soysauce); add(ingre_kochujang); add(ingre_sauce); ingre_water.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if(pause.work) { setCursor(Toolkit.getDefaultToolkit().createCustomCursor( new ImageIcon(getClass().getClassLoader().getResource("pic/water.png")).getImage(), new Point(31,31),"custom cursor")); } } @Override public void mouseReleased(MouseEvent e) { if(e.getX() >= -294 && e.getX() <= 313 && e.getY() >= 188 && e.getY() <= 650 && pause.work) { menu.stage3_score += 3; count++; ingre_sauce.setIcon(sauce[1]); ingre_water.setVisible(false); } setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); ingre_soysauce.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if(pause.work) { setCursor(Toolkit.getDefaultToolkit().createCustomCursor( new ImageIcon(getClass().getClassLoader().getResource("pic/soy_sauce.png")).getImage(), new Point(31,31),"custom cursor")); } } @Override public void mouseReleased(MouseEvent e) { if(e.getX() >= -523 && e.getX() <= 84 && e.getY() >= 148 && e.getY() <= 611 && count == 1 && pause.work) { menu.stage3_score += 3; count++; ingre_sauce.setIcon(sauce[2]); ingre_soysauce.setVisible(false); } setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); ingre_ketchup.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if(pause.work) { setCursor(Toolkit.getDefaultToolkit().createCustomCursor( new ImageIcon(getClass().getClassLoader().getResource("pic/ketchup.png")).getImage(), new Point(31,31),"custom cursor")); } } @Override public void mouseReleased(MouseEvent e) { if(e.getX() >= 139 && e.getX() <= 744 && e.getY() >= 149 && e.getY() <= 613 && count==2 && pause.work) { menu.stage3_score += 3; count++; ingre_sauce.setIcon(sauce[3]); ingre_ketchup.setVisible(false); } setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); ingre_kochujang.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { if(pause.work) { setCursor(Toolkit.getDefaultToolkit().createCustomCursor( new ImageIcon(getClass().getClassLoader().getResource("pic/kochujang.png")).getImage(), new Point(31,31),"custom cursor")); } } @Override public void mouseReleased(MouseEvent e) { if(e.getX() >= -80 && e.getX() <= 521 && e.getY() >= 190 && e.getY() <= 656 && count==3 && pause.work) { menu.stage3_score += 3; ingre_sauce.setIcon(sauce[4]); ingre_kochujang.setVisible(false); clear = true; } setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); } }); Brush b = new Brush(); ingre_sauce.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseMoved(MouseEvent e) { repaint(); revalidate(); } @Override public void mouseDragged(MouseEvent e) { if(clear && pause.work) { b.xx = e.getX(); b.yy = e.getY(); b.printAll(ingre_sauce.getGraphics()); } } }); ingre_sauce.addMouseListener(new MouseAdapter() { @Override public void mouseReleased(MouseEvent e) { endX = e.getX(); endY = e.getY(); //System.out.println(e.getY()); if(clear && pause.work) { count2++; if(count2 == 4) { ingre_sauce.setIcon(sauce[5]); count2++; } else if(count2 >= 5) { count = 0; count2 = 0; Timer.complete = true; frame.add(new exam(frame)); frame.remove(panel); frame.repaint(); frame.revalidate(); } } } @Override public void mousePressed(MouseEvent e) { startX = e.getX(); startY = e.getY(); } }); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); g.drawImage(bgimage.getImage(),0,0,null); } }
Java
UTF-8
1,625
1.828125
2
[]
no_license
package org.jxjz.framework.util; import org.jxjz.common.util.PropUtils; public class ConfigUtil { public static String environment; public static String server_app_host_url; public static String server_app_host; public static String sys_session_mode; public static String sys_appSecret; public static String sys_secKey; public static String sys_uploadPath; public static String sys_user_defaultPassword; public static String cus_headPic; public static String dimeCode_path; public static String logName="hjserver"; public static String logName_sys="hjserver"; public static String Session_Login_User= "session_login_user";//页面跳转类型【请求数据】 public static String Cookie_Login_User= "CKLHJ";//页面跳转类型【请求数据】 static{ environment =PropUtils.getMsgStr("environment"); server_app_host_url =PropUtils.getMsgStr("server.app.host.url"); server_app_host =PropUtils.getMsgStr("server.app.host"); sys_session_mode =PropUtils.getMsgStr("sys.session.mode"); sys_appSecret =PropUtils.getMsgStr("sys.appSecret"); sys_secKey =PropUtils.getMsgStr("sys.secKey"); sys_uploadPath =PropUtils.getMsgStr("sys.uploadPath"); sys_user_defaultPassword=PropUtils.getMsgStr("sys.user.defaultPassword"); cus_headPic =PropUtils.getMsgStr("cus.headPic"); dimeCode_path =PropUtils.getMsgStr("dimeCode.path"); } public static boolean isSessionLocal(){ boolean isLocal = "local".equalsIgnoreCase(sys_session_mode); return isLocal; } }
Java
UTF-8
467
3.5625
4
[]
no_license
package kadai; public class Kadai05 { public static void main(String[] args) { int a = 30; int b = 20; System.out.print("大きいほうの値は"); if(a > b) { System.out.println(a +"です。"); }else { System.out.println(b + "です。"); /*if(a > b) { System.out.println("大きいほうの値はaです。"); }else { System.out.println("大きいほうの値はbです。");*/ } } }
C++
UTF-8
724
4.15625
4
[]
no_license
#include <iostream> #include <vector> int findMissingNumber(const std::vector<int>& numbers) { int len = numbers.size() + 1; // one number missing in array, hence added 1 // find xor of all numbers from 1 .. n int xor_n = 0; for (int i = 1; i <= len; i++) { xor_n ^= i; } std::cout << "xor of n numbers: " << xor_n << std::endl; // find xor of all numbers in input array int xor_arr = 0; for (auto num : numbers) { xor_arr ^= num; } std::cout << "xor of input numbers: " << xor_arr << std::endl; return xor_n ^ xor_arr; } auto main() -> int { std::vector<int> arr{ 1,2,4,5,6 }; auto missing_number = findMissingNumber(arr); std::cout << "Missing Number = " << missing_number << std::endl; return 0; }
Java
UTF-8
907
2.21875
2
[]
no_license
package com.example.wjx.xing.db; public class TableSkill extends BaseDataBase { public final static String TABLE_NAME = "table_skill"; public final static String COLUMN_ID = "id"; public final static String COLUMN_NAME = "name"; public final static String COLUMN_MAX_LEVEL = "max_level"; private static final long serialVersionUID = 8901239358437203242L; private String id; private String name; private String max_level; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getMax_level() { return max_level; } public void setMax_level(String max_level) { this.max_level = max_level; } @Override public String toString() { return "TableSkillDataBase [id=" + id + ", name=" + name + ", max_level=" + max_level + "]"; } }
Java
UTF-8
609
1.929688
2
[]
no_license
package net.helpscout.api.model.report.user; import java.util.List; import lombok.AccessLevel; import lombok.Data; import lombok.experimental.FieldDefaults; import net.helpscout.api.cbo.Status; @Data @FieldDefaults(level = AccessLevel.PRIVATE) public class ConversationStats { Integer number; Integer responseTime; Integer firstResponseTime; Integer resolveTime; Integer repliesSent; Integer id; Status status; List<Customer> customers; @Data @FieldDefaults(level = AccessLevel.PRIVATE) public class Customer { Integer id; String name; } }
Markdown
UTF-8
3,127
2.828125
3
[]
no_license
## Arduino 1 ```C #include "DHT.h" #define DHTPIN 4 // Digital pin connected to the DHT sensor // Feather HUZZAH ESP8266 note: use pins 3, 4, 5, 12, 13 or 14 -- // Pin 15 can work but DHT must be disconnected during program upload. // Uncomment whatever type you're using! //#define DHTTYPE DHT11 // DHT 11 #define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321 //#define DHTTYPE DHT21 // DHT 21 (AM2301) // Connect pin 1 (on the left) of the sensor to +5V // NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1 // to 3.3V instead of 5V! // Connect pin 2 of the sensor to whatever your DHTPIN is // Connect pin 3 (on the right) of the sensor to GROUND (if your sensor has 3 pins) // Connect pin 4 (on the right) of the sensor to GROUND and leave the pin 3 EMPTY (if your sensor has 4 pins) // Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor DHT dht(DHTPIN, DHTTYPE); void setup() { Serial.begin(9600); pinMode(5,OUTPUT); dht.begin(); } char data[6]={0x02,0x00,0x00,0x00,0x00,0x00}; void T_H_sensing(){ float h = dht.readHumidity(); // Read temperature as Celsius (the default) float t = dht.readTemperature(); // Read temperature as Fahrenheit (isFahrenheit = true) //float f = dht.readTemperature(true); // Check if any reads failed and exit early (to try again). if (isnan(h) || isnan(t)){ data_trans(0,'E');delay(150); //return; } else { int data_t=h*10; data_trans(data_t,'H'); delay(150); data_t=t*10; data_trans(data_t,'T'); delay(150); } } void PHR_sensing(){ unsigned int light_in=analogRead(A0); //Serial.println(light_in); if (light_in>999) light_in=999; data_trans(light_in,'L'); delay(150); } int delay_150ms=0; void loop() { if(delay_150ms>=14){ T_H_sensing(); //150-300ms delay_150ms=0; } else delay_150ms++; PHR_sensing(); //150ms UART_check(); } void UART_check() { while (Serial.available()>=6) { char c=Serial.read(); if (c==0x02) { char data_in[5]; int i; for (i=0;i<5;i++) data_in[i]=Serial.read(); char chk_sum=0x02; for (i=0;i<4;i++) chk_sum=chk_sum^data_in[i]; if (data_in[4]==chk_sum) { if (data_in[0]=='L') { if ((data_in[1]=='0')&&(data_in[2]=='0')&&(data_in[3]=='0')) { digitalWrite(5,LOW);} else if((data_in[1]=='0')&&(data_in[2]=='0')&&(data_in[3]=='1')) { digitalWrite(5,HIGH);} } else if (data_in[0]=='H') { if ((data_in[1]=='0')&&(data_in[2]=='0')) { int LED_level=data_in[3]-0x30; if((LED_level <= 9)&&(LED_level >= 0)){ analogWrite(5,LED_level*28); } } } } } } } void data_trans(int data_o,char func) { data[0]=0x02; data[1]=func; data[2]=(data_o/100)+0x30; data[3]=((data_o/10)%10)+0x30; data[4]=(data_o%10)+0x30; char chk_sum=0x00; for (int i=0;i<5;i++) chk_sum=chk_sum^data[i]; data[5]=chk_sum; Serial.print(data); } ```
Java
UTF-8
6,566
2.140625
2
[]
no_license
package co.ryred.checkerservlet; import co.ryred.checkerservlet.configuration.InvalidConfigurationException; import co.ryred.checkerservlet.configuration.file.YamlConfiguration; import com.google.common.base.Throwables; import org.apache.commons.io.IOUtils; import org.apache.log4j.Level; import org.apache.log4j.Logger; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.List; import java.util.UUID; import java.util.concurrent.TimeUnit; /** * @author Cory Redmond * Created by acech_000 on 03/04/2015. */ public class CheckerServletConfig { private static final File CONFIG_FILE = new File( new File( System.getProperty( "catalina.base" ), "conf" ), "CheckServlet.yml" ); private static final String HEADER = "YAML only please!"; public static YamlConfiguration config; public static boolean debug; public static String ips_url; public static String password; public static File configFile; public static File cacheDir; public static long cacheTime; static int version; private static boolean initted = false; public static void init() { init( false ); } public static void init( boolean force ) { if ( !force && initted ) { Logger.getRootLogger().log( Level.WARN, "Config was already init'd." ); return; } if ( !CONFIG_FILE.exists() ) { CONFIG_FILE.getParentFile().mkdirs(); } config = new YamlConfiguration(); try { Logger.getRootLogger().log( Level.INFO, "Config dir: " + CONFIG_FILE.getAbsolutePath() ); config.load( CONFIG_FILE ); } catch ( IOException ex ) { } catch ( InvalidConfigurationException ex ) { Logger.getRootLogger().log( Level.FATAL, "Could not load UUIDServlet.yml, please correct your syntax errors", ex ); throw Throwables.propagate( ex ); } config.options().header( HEADER ); config.options().copyDefaults( true ); version = getInt( "config-version", 6 ); set( "config-version", 6 ); readConfig( CheckerServletConfig.class, null ); Logger.getRootLogger().log( Level.INFO, "Configuration summary!" ); for ( Field field : CheckerServletConfig.class.getDeclaredFields() ) { if ( Modifier.isPublic( field.getModifiers() ) && Modifier.isStatic( field.getModifiers() ) ) { field.setAccessible( true ); try { Logger.getRootLogger() .log( Level.INFO, " | " + field.getName() + " | " + field.getType() + " | " + field.get( null ) .toString() ); } catch ( IllegalAccessException e ) { Logger.getRootLogger().log( Level.FATAL, "Error reporting " + field, e ); } } } config = null; } static void readConfig( Class<?> clazz, Object instance ) { for ( Method method : clazz.getDeclaredMethods() ) { if ( Modifier.isPrivate( method.getModifiers() ) ) { if ( method.getParameterTypes().length == 0 && method.getReturnType() == Void.TYPE ) { try { method.setAccessible( true ); method.invoke( instance ); } catch ( InvocationTargetException ex ) { throw Throwables.propagate( ex.getCause() ); } catch ( Exception ex ) { Logger.getRootLogger().log( Level.FATAL, "Error invoking " + method, ex ); } } } } try { config.save( CONFIG_FILE ); } catch ( IOException ex ) { Logger.getRootLogger().log( Level.FATAL, "Could not save " + CONFIG_FILE, ex ); } } private static void set( String path, Object val ) { config.set( path, val ); } private static long getLong( String path, long def ) { config.addDefault( path, def ); return config.getLong( path, config.getLong( path ) ); } private static boolean getBoolean( String path, boolean def ) { config.addDefault( path, def ); return config.getBoolean( path, config.getBoolean( path ) ); } private static int getInt( String path, int def ) { config.addDefault( path, def ); return config.getInt( path, config.getInt( path ) ); } private static <T> List getList( String path, T def ) { config.addDefault( path, def ); return config.getList( path, config.getList( path ) ); } private static String getString( String path, String def ) { config.addDefault( path, def ); return config.getString( path, config.getString( path ) ); } private static double getDouble( String path, double def ) { config.addDefault( path, def ); return config.getDouble( path, config.getDouble( path ) ); } private static File getFile( String path, String def ) { String fileLoc = getString( path, def ); if ( System.getProperty( "catalina.base" ) != null ) { fileLoc = fileLoc.replace( "{HOME}", System.getProperty( "catalina.base" ) ).replace( "/", File.separator ); } File file = new File( fileLoc ); file.getParentFile().mkdirs(); return file; } private static void debug() { debug = getBoolean( "settings.debug", false ); } private static void urls() { if ( version < 4 ) { Logger.getRootLogger().log( Level.FATAL, "Oudated config, urls are not configured!" ); set( "settings.known_ips_json", "http://somewhere.someplace/myjson.json" ); } ips_url = getString( "settings.known_ips_json", "http://somewhere.someplace/myjson.json" ); } private static void security() { if ( version < 5 ) { Logger.getRootLogger().log( Level.FATAL, "Oudated config, security is not configured!" ); set( "settings.password", UUID.randomUUID().toString().replace( "-", "" ) ); } password = getString( "settings.password", UUID.randomUUID().toString().replace( "-", "" ) ); } private static void caching() { if ( version < 6 ) { Logger.getRootLogger().log( Level.FATAL, "Oudated config, caching is not configured!" ); set( "settings.cache.cachedir", "data/cache" ); set( "settings.cache.expiretime", 10 ); } cacheDir = getFile( "settings.cache.cachedir", "data/cache" ); cacheTime = TimeUnit.DAYS.toMillis( getLong( "settings.cache.expiretime", 10 ) ); } private static void dataSettings() { if ( version < 2 ) { Logger.getRootLogger().log( Level.FATAL, "Oudated config, dataconfig is not configured!" ); set( "settings.data.configLocation", "conf/checker-spring.xml" ); } configFile = getFile( "settings.data.configLocation", "conf/checker-spring.xml" ); if ( !configFile.exists() ) { try { IOUtils.copy( CheckerServlet.class.getResourceAsStream( "/spring.xml" ), new FileOutputStream( configFile ) ); } catch ( Exception e ) { e.printStackTrace(); } } } }
Java
UTF-8
634
2.046875
2
[]
no_license
package Test.DAO; import BusinessLogic.Project.AbstractProject; import BusinessLogic.Project.Project; import Facade.Chat.ChatFacade; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; /** * * @author Guillaume Tessier */ public class ChatDAOMySQLTest { @Test void getChatByProjectId(){ AbstractProject project = new Project(0,null,null,null,true); assertEquals(false,ChatFacade.getInstance().getChatByProjectId(project.getId())); assertFalse(ChatFacade.getInstance().getChatByProjectId(0)); } }
C++
UTF-8
4,478
3.6875
4
[]
no_license
/** Akash Chaurasia (achaura1) akashc@jhu.edu */ #include "edit.h" /** Function to return the nth letter of the alphabet @param i the numbered alphabet to return @return a string with one desired alphabetical character */ string get_nth_letter(const int i) { //make string of alphabet to refer to string alphabet = "abcdefghijklmnopqrstuvwxyz"; //make sure that index is appropriate if (0 <= i && i <= 25) { //return letter at index position return string(1, alphabet.at(i)); } else { return NULL; } } /** Function to add all possible insertion edits to string vector given a word to make edits of @param user_string the string to make edits of @param all_edits the typedef'd vector of strings to add edits onto */ void insertion(const string user_string, s_vec& all_edits) { //find size of string int str_size = user_string.size(); for(int i = 0; i < 26; i++) { for (int j = 0; j < str_size; j++) { //create pre-edited string identical to original string string new_edit = user_string; //insert character at every possible position except last //using get_nth_letter function which returns all letters //of the alphabet iteratively new_edit.insert(j, get_nth_letter(i)); //add edited string to string vector all_edits.push_back(new_edit); } //can't use string.insert function to add to end of string //so use append after iterating through all other positions string new_edit = user_string; all_edits.push_back(new_edit.append(get_nth_letter(i))); } } /** Function to make all possible deletion edits of a given string and add them to a given string vector @param user_string the string on which to make edits @param all_edits the string vector to add all edits to */ void deletion(const string user_string, s_vec& all_edits) { //find size of given string int str_size = user_string.size(); //iterate through all possible characters to edit for (int i = 0; i < str_size; i++) { //create pre-edited string identical to original string string new_edit = user_string; //erase character at ith position new_edit.erase(i, 1); //add new edit to string vector all_edits.push_back(new_edit); } } /** Function to create all possible transposition edits of a given string and add them to a given string vector @param user_string the string on which to make edits @param all_edits the string vector to add all edits to */ void transposition(const string user_string, s_vec& all_edits) { //find size of given string int str_size = user_string.size(); //iterate through all first of two adjacent characters to swap //can't go to size index because loop uses (i + 1)th character for (int i = 0; i < str_size - 1; i++) { //create pre-edited string identical to original string string new_edit = user_string; //use swap function from algorithm library to swap adjacent characters swap(new_edit[i], new_edit[i + 1]); //add new edit to string vector all_edits.push_back(new_edit); } } /** Function to create all possible substitution edits of a given string and add them to a given string vector @param user_string the string on which to make all edits @param all_edits the string vector to add all edits to */ void substitution(const string user_string, s_vec& all_edits) { //find size of given string int str_size = user_string.size(); //iterate through all letters for (int i = 0; i < 26; i++) { //iterate through all letters in string for (int j = 0; j < str_size; j++) { //create pre-edited string identical to original string string new_edit = user_string; //change original letter at index to letter obtained //using get_nth_letter function new_edit[j] = (get_nth_letter(i))[0]; //add new edit to string vector all_edits.push_back(new_edit); } } } /** Function to make all possible edits of a given string and add them all to a given string vector @param user_string the string on which to make edits @param all_edits the string vector to add all edits to */ void edits(const string user_string, s_vec& all_edits) { //call all edit functions in specified order insertion(user_string, all_edits); deletion(user_string, all_edits); transposition(user_string, all_edits); substitution(user_string, all_edits); }
Markdown
UTF-8
1,712
3.1875
3
[]
no_license
--- layout: post title: "How to self-host a blog" date: 2018-08-21 categories: Programming --- One of the purposes of this blog is to experiment with simple ways put up a blog on the web without depending on any blogging platform. For this I wanted a free way to deploy static web pages on my own domain name. For this I chose [Firebase Hosting][1], partly because I am very familiar with it, having worked on the Firebase team and personally knowing many of the Hosting development team, but also because it is actually the best solution I know of for what I want, and it is free for sites that have the traffic of typical personal sites. People who are comfortable using the command line might be interested in following along the steps I took. 1. Go to http://firebase.com, login, and create a project.</li> 1. Install Node. If you don’t already have it installed already, I suggest first installing [nvm][2] then doing: ```sh nvm install stable nvm use stable</pre> ``` 1. Follow the instructions in the [Hosting quickstart][3]. 1. Replace `index.html` with the HTML you want as your home page. 1. Do `firebase deploy` 1. I’d recommend storing everything in Git, and you might as well make it a public repo, as the web site is public anyway. (Mine is [on GitHub][4]) 1. You also might want to register a domain name, and use Firebase Hosting to use that domain name (complete with a free SSL certificate so you the `https:` security for free.). I did this for `eamonn.org` [1]: https://firebase.google.com/docs/hosting/ [2]: https://github.com/creationix/nvm [3]: https://firebase.google.com/docs/hosting/quickstart [4]: https://github.com/eobrain/webhome
Shell
UTF-8
595
2.8125
3
[]
no_license
# Set HOSTNAME and PS1 HOSTNAME=`hostname -s` PS1="$HOSTNAME%; " # Keybindings set -o vi alias __A=`echo "\020"` # up arrow = ^p = back a command alias __B=`echo "\016"` # down arrow = ^n = down a command alias __C=`echo "\006"` # right arrow = ^f = forward a character alias __D=`echo "\002"` # left arrow = ^b = back a character alias __H=`echo "\001"` # home = ^a = start of line alias __Y=`echo "\005"` # end = ^e = end of line # History HISTFILE="$HOME/.ksh_history" HISTSIZE=50000 # Path PATH="/usr/local/bin:/usr/bin:/usr/local/sbin:/usr/sbin:$HOME/.local/bin"
C#
UTF-8
2,707
3.609375
4
[]
no_license
using System; namespace Exercicios_de_fixação_1 { class Program { static void Main(string[] args) { { static float CalcularMedia(float[] numeros){ float soma = 0; for (var i = 0; i < numeros.Length; i++) { // soma = soma + numeros [i]; soma+= numeros[i]; } float resultado = soma / numeros.Length; return resultado; } static void main(string[] args) { /* void = função vazia float = Variável que serve para números decimais /* Exercício: Faça um programa que receba o nome e quatro notas de 10 alunos e armezena essas notas em votores. Calcule e mostre: A) A média do aluno - Função B) A quantidade de Aprovados (Média >=7) C) A quantidade de reprovados (Média <=7) D) A média geral dos 10 alunos */ // Criar as variáveis necessárias string [] nomes = new string[2]; float[] medias = new float[7]; float[] notas = new float [4]; // Estruturas de repetição // Laços contados // array.Length = tamanho do array for (int i = 0; i < nomes.Length; i++) { Console.WriteLine("Digite o nome do aluno : "); nomes[i] = Console.ReadLine(); // laço com o nome dos alunos definido for (int n = 0; n < notas.Length; n++) { Console.WriteLine("Digite a "+(n+1)+"° nota:"); // ($"Digite a {(n+1)}° nota: ") > Outra forma usando interpolação, com $ notas[n] = float.Parse( Console.ReadLine() ); // laço das notas } // Calcula a média fora do laço de notas // medias[i] = (notas[0] + notas[1] + notas[2] + notas[3] + notas[4]) / 7; medias[i] = CalcularMedia(notas); } // fim de laço for Console.ForegroundColor = ConsoleColor.Green; // Sintaxe que serve pra cor // Laços condicionais // variável criada "name" em laço foreach // foreach organiza em lista foreach (string name in nomes){ Console.WriteLine(name); } Console.ForegroundColor = ConsoleColor.Red; // Mostramos as infos for (var i = 0; i < nomes.Length; i++) { // Interpolação Console.WriteLine($"Nome: {nomes[i]} Média: {medias[i]}"); } Console.ResetColor(); Console.WriteLine("Média geral da turma:" + CalcularMedia(medias)); } // Fim de Main } } }
C++
UTF-8
823
2.515625
3
[]
no_license
#include<cstdio> #include<cstring> char field[110][110]; int d[8][2]={1,0,-1,0,0,1,0,-1,1,1,-1,-1,1,-1,-1,1}; int r,c; void dfs(int x,int y) { int next_x,next_y,i; field[x][y]='*'; for(i=0;i<8;i++) { next_x=x+d[i][0]; next_y=y+d[i][1]; if(next_x>=0&&next_x<r&&next_y>=0&&next_y<c&&field[next_x][next_y]=='@') dfs(next_x,next_y); } return ; } int main() { int i,j,sum; while(scanf("%d%d",&r,&c)&&r!=0) { for(i=0;i<r;i++) scanf("%s",field[i]); sum=0; for(i=0;i<r;i++) { for(j=0;j<c;j++) { if(field[i][j]=='@') { dfs(i,j); sum++; } } } printf("%d\n",sum); } return 0; }
C
UTF-8
1,603
3.421875
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<time.h> #include"sorting.h" int main(int argc, char ** argv){ //argv[0]: excecutable, ./proj1 //argv[1]: type of sort, i or s //argv[2]: input file name, #.b //argv[3]: output file name, #seq.t //argv[4]: output file name, #s.b clock_t start; clock_t end; double iot = 0; //io time double st = 0; //sorting time long *Array; //Array of numbers int length = 0; //number of values double Comps = 0; //number of comparisons double Moves = 0; //number of moves int seq; //numbers in sequence int stored = 0; //numbers stored start = clock(); Array = Load_From_File(argv[2], &length); seq = Print_Seq(argv[3], length); end = clock(); iot = ((double)(end - start)); //insertion or selection if(argv[1][0] == 'i'){ start = clock(); Shell_Insertion_Sort( Array, length, &Comps, &Moves); end = clock(); st = ((double)(end - start)); } if(argv[1][0] == 's'){ start = clock(); Shell_Selection_Sort( Array, length, &Comps, &Moves); end = clock(); st = ((double)(end - start)); } start = clock(); stored = Save_To_File(argv[4], Array, length); end = clock(); iot += ((double)(end - start)); printf("\nNumber of long integers read: %d\n", length); printf("Number of long integers stored: %d\n", stored); printf("Length if sequence: %d\n", seq); printf("Number of comparisons: %le\n", Comps); printf("Number of moves: %le\n", Moves); printf("I/O time: %le\n", (iot / CLOCKS_PER_SEC)); printf("Sorting time: %le\n", (st / CLOCKS_PER_SEC)); free(Array); return 0; }
Markdown
UTF-8
11,840
2.84375
3
[ "BSD-3-Clause" ]
permissive
# API Reference ## Router ### Configuration Creates a mock `Router` instance, ready to be used as decorator/manager for activation. > <code>respx.<strong>mock</strong>(assert_all_mocked=True, *assert_all_called=True, base_url=None*)</strong></code> > > **Parameters:** > > * **assert_all_mocked** - *(optional) bool - default: `True`* > Asserts that all sent and captured `HTTPX` requests are routed and mocked. > If disabled, all non-routed requests will be auto mocked with status code `200`. > * **assert_all_called** - *(optional) bool - default: `True`* > Asserts that all added and mocked routes were called when exiting context. > * **base_url** - *(optional) str* > Base URL to match, on top of each route specific pattern *and/or* side effect. > > **Returns:** `Router` !!! note "NOTE" When using the *default* mock router `respx.mock`, *without settings*, `assert_all_called` is **disabled**. !!! tip "pytest" Use the `@pytest.mark.respx(...)` marker with these parameters to configure the `respx_mock` [pytest fixture](examples.md#built-in-marker). ### .route() Adds a new, *optionally named*, `Route` with given [patterns](#patterns) *and/or* [lookups](#lookups) combined, using the [AND](#and) operator. > <code>respx.<strong>route</strong>(*\*patterns, name=None, \*\*lookups*)</strong></code> > > **Parameters:** > > * **patterns** - *(optional) args* > One or more [pattern](#patterns) objects. > * **lookups** - *(optional) kwargs* > One or more [pattern](#patterns) keyword [lookups](#lookups), given as `<pattern>__<lookup>=value`. > * **name** - *(optional) str* > Name this route. > > **Returns:** `Route` ### .get(), .post(), ... HTTP method helpers to add routes, mimicking the [HTTPX Helper Functions](https://www.python-httpx.org/api/#helper-functions). > <code>respx.<strong>get</strong>(*url, name=None, \*\*lookups*)</strong></code> > <code>respx.<strong>options</strong>(...)</strong></code> > <code>respx.<strong>head</strong>(...)</strong></code> > <code>respx.<strong>post</strong>(...)</strong></code> > <code>respx.<strong>put</strong>(...)</strong></code> > <code>respx.<strong>patch</strong>(...)</strong></code> > <code>respx.<strong>delete</strong>(...)</strong></code> > > **Parameters:** > > * **url** - *(optional) str | compiled regex | tuple (httpcore) | httpx.URL* > Request URL to match, *full or partial*, turned into a [URL](#url) pattern. > * **name** - *(optional) str* > Name this route. > * **lookups** - *(optional) kwargs* > One or more [pattern](#patterns) keyword [lookups](#lookups), given as `<pattern>__<lookup>=value`. > > **Returns:** `Route` ``` python respx.get("https://example.org/", params={"foo": "bar"}, ...) ``` ### .request() > <code>respx.<strong>request</strong>(*method, url, name=None, \*\*lookups*)</strong></code> > > **Parameters:** > > * **method** - *str* > Request HTTP method to match. > * **url** - *(optional) str | compiled regex | tuple (httpcore) | httpx.URL* > Request URL to match, *full or partial*, turned into a [URL](#url) pattern. > * **name** - *(optional) str* > Name this route. > * **lookups** - *(optional) kwargs* > One or more [pattern](#patterns) keyword [lookups](#lookups), given as `<pattern>__<lookup>=value`. > > **Returns:** `Route` ``` python respx.request("GET", "https://example.org/", params={"foo": "bar"}, ...) ``` --- ## Route ### .mock() Mock a route's response or side effect. > <code>route.<strong>mock</strong>(*return_value=None, side_effect=None*)</strong></code> > > **Parameters:** > > * **return_value** - *(optional) [Response](#response)* > HTTPX Response to mock and return. > * **side_effect** - *(optional) Callable | Exception | Iterable of httpx.Response/Exception* > [Side effect](guide.md#mock-with-a-side-effect) to call, exception to raise or stacked responses to respond with in order. > > **Returns:** `Route` ### .return_value Setter for the `HTTPX` [Response](#response) to return. > <code>route.**return_value** = Response(204)</code> ### .side_effect Setter for the [side effect](guide.md#mock-with-a-side-effect) to trigger. > <code>route.**side_effect** = ...</code> > > See [route.mock()](#mock) for valid side effect types. ### .respond() Shortcut for creating and mocking a `HTTPX` [Response](#response). > <code>route.<strong>respond</strong>(*status_code=200, headers=None, content=None, text=None, html=None, json=None, stream=None*)</strong></code> > > **Parameters:** > > * **status_code** - *(optional) int - default: `200`* > Response status code to mock. > * **headers** - *(optional) dict* > Response headers to mock. > * **content** - *(optional) bytes | str | iterable bytes* > Response raw content to mock. > * **text** - *(optional) str* > Response *text* content to mock, with automatic content-type header added. > * **html** - *(optional) str* > Response *HTML* content to mock, with automatic content-type header added. > * **json** - *(optional) str | list | dict* > Response *JSON* content to mock, with automatic content-type header added. > * **stream** - *(optional) Iterable[bytes]* > Response *stream* to mock. > > **Returns:** `Route` ### .pass_through() > <code>route.<strong>pass_through</strong>(*value=True*)</strong></code> > > **Parameters:** > > * **value** - *(optional) bool - default: `True`* > Mark route to pass through, sending matched requests to real server, *e.g. don't mock*. > > **Returns:** `Route` --- ## Response !!! note "NOTE" This is a partial reference for how to the instantiate the **HTTPX** `Response`class, e.g. *not* a RESPX class. > <code>httpx.<strong>Response</strong>(*status_code, headers=None, content=None, text=None, html=None, json=None, stream=None*)</strong></code> > > **Parameters:** > > * **status_code** - *int* > HTTP status code. > * **headers** - *(optional) dict | httpx.Headers* > HTTP headers. > * **content** - *(optional) bytes | str | Iterable[bytes]* > Raw content. > * **text** - *(optional) str* > Text content, with automatic content-type header added. > * **html** - *(optional) str* > HTML content, with automatic content-type header added. > * **json** - *(optional) str | list | dict* > JSON content, with automatic content-type header added. > * **stream** - *(optional) Iterable[bytes]* > Content *stream*. --- ## Patterns ### M() Creates a reusable pattern, combining multiple arguments using the [AND](#and) operator. > <code><strong>M</strong>(*\*patterns, \*\*lookups*)</strong></code> > > **Parameters:** > > * **patterns** - *(optional) args* > One or more [pattern](#patterns) objects. > * **lookups** - *(optional) kwargs* > One or more [pattern](#patterns) keyword [lookups](#lookups), given as `<pattern>__<lookup>=value`. > > **Returns:** `Pattern` ``` python import respx from respx.patterns import M pattern = M(host="example.org") respx.route(pattern) ``` > See [operators](#operators) for advanced usage. ### Method Matches request *HTTP method*, using <code>[eq](#eq)</code> as default lookup. > Key: `method` > Lookups: [eq](#eq), [in](#in) ``` python respx.route(method="GET") respx.route(method__in=["PUT", "PATCH"]) ``` ### Scheme Matches request *URL scheme*, using <code>[eq](#eq)</code> as default lookup. > Key: `scheme` > Lookups: [eq](#eq), [in](#in) ``` python respx.route(scheme="https") respx.route(scheme__in=["http", "https"]) ``` ### Host Matches request *URL host*, using <code>[eq](#eq)</code> as default lookup. > Key: `host` > Lookups: [eq](#eq), [regex](#regex), [in](#in) ``` python respx.route(host="example.org") respx.route(host__regex=r"example\.(org|com)") respx.route(host__in=["example.org", "example.com"]) ``` ### Port Matches request *URL port*, using <code>[eq](#eq)</code> as default lookup. > Key: `port` > Lookups: [eq](#eq), [in](#in) ``` python respx.route(port=8000) respx.route(port__in=[2375, 2376]) ``` ### Path Matches request *URL path*, using <code>[eq](#eq)</code> as default lookup. > Key: `path` > Lookups: [eq](#eq), [regex](#regex), [startswith](#startswith), [in](#in) ``` python respx.route(path="/api/foobar/") respx.route(path__regex=r"^/api/(?P<slug>\w+)/") respx.route(path__startswith="/api/") respx.route(path__in=["/api/v1/foo/", "/api/v2/foo/"]) ``` ### Params Matches request *URL query params*, using <code>[contains](#contains)</code> as default lookup. > Key: `params` > Lookups: [contains](#contains), [eq](#eq) ``` python respx.route(params={"foo": "bar", "ham": "spam"}) respx.route(params=[("foo", "bar"), ("ham", "spam")]) respx.route(params=(("foo", "bar"), ("ham", "spam"))) respx.route(params="foo=bar&ham=spam") ``` !!! note "NOTE" A request querystring with multiple parameters of the same name is treated as an ordered list when matching. !!! tip "ANY value" Use `mock.ANY` as value to only match on parameter presence, e.g. `respx.route(params={"foo": ANY})`. ### URL Matches request *URL*. When no *lookup* is given, `url` works as a *shorthand* pattern, combining individual request *URL* parts, using the [AND](#and) operator. > Key: `url` > Lookups: [eq](#eq), [regex](#regex), [startswith](#startswith) ``` python respx.get("//example.org/foo/") # == M(host="example.org", path="/foo/") respx.get(url__eq="https://example.org:8080/foobar/?ham=spam") respx.get(url__regex=r"https://example.org/(?P<slug>\w+)/") respx.get(url__startswith="https://example.org/api/") respx.get("all://*.example.org/foo/") ``` ### Content Matches request raw *content*, using [eq](#eq) as default lookup. > Key: `content` > Lookups: [eq](#eq), [contains](#contains) ``` python respx.post("https://example.org/", content="foobar") respx.post("https://example.org/", content=b"foobar") respx.post("https://example.org/", content__contains="bar") ``` ### Data Matches request *form data*, using [eq](#eq) as default lookup. > Key: `data` > Lookups: [eq](#eq) ``` python respx.post("https://example.org/", data={"foo": "bar"}) ``` ### JSON Matches request *json* content, using [eq](#eq) as default lookup. > Key: `json` > Lookups: [eq](#eq) ``` python respx.post("https://example.org/", json={"foo": "bar"}) ``` The `json` pattern also supports path traversing, *i.e.* `json__<path>=<value>`. ``` python respx.post("https://example.org/", json__foobar__0__ham="spam") httpx.post("https://example.org/", json={"foobar": [{"ham": "spam"}]}) ``` ### Headers Matches request *headers*, using [contains](#contains) as default lookup. > Key: `headers` > Lookups: [contains](#contains), [eq](#eq) ``` python respx.route(headers={"foo": "bar", "ham": "spam"}) respx.route(headers=[("foo", "bar"), ("ham", "spam")]) ``` ### Cookies Matches request *cookie header*, using [contains](#contains) as default lookup. > Key: `cookies` > Lookups: [contains](#contains), [eq](#eq) ``` python respx.route(cookies={"foo": "bar", "ham": "spam"}) respx.route(cookies=[("foo", "bar"), ("ham", "spam")]) ``` ## Lookups ### eq ``` python M(path="/foo/bar/") M(path__eq="/foo/bar/") ``` ### contains Case-sensitive containment test. ``` python M(params__contains={"id": "123"}) ``` ### in Case-sensitive within test. ``` python M(method__in=["PUT", "PATCH"]) ``` ### regex ``` python M(path__regex=r"^/api/(?P<slug>\w+)/") ``` ### startswith Case-sensitive starts-with. ``` python M(path__startswith="/api/") ``` ## Operators Patterns can be combined using bitwise operators, creating new patterns. ### AND (&) Combines two `Pattern`s using `and` operator. ``` python M(scheme="http") & M(host="example.org") ``` ### OR (&) Combines two `Pattern`s using `or` operator. ``` python M(method="PUT") | M(method="PATCH") ``` ### INVERT (~) Inverts a `Pattern` match. ``` python ~M(params={"foo": "bar"}) ```
Shell
UTF-8
1,108
3.828125
4
[]
no_license
#!/bin/bash # Tai Sakuma <sakuma@fnal.gov> ##____________________________________________________________________________|| function create_backUpFile_path { local outfile=$1 local timenow=$(date '+%y%m%d_%H%M') local i=1 local ext=${outfile##*.} local backUpFile=${outfile%.*}_${timenow}_${i}.${ext} while [ -s ${backUpFile} ] do local i=$((i+1)) local backUpFile=${outfile%.*}_${timenow}_${i}.${ext} done echo ${backUpFile} } ##____________________________________________________________________________|| function mv_with_timestamp { local outfile=$1 if [ -s ${outfile} ]; then local backUpFile=$(create_backUpFile_path ${outfile}) echo "mv -f ${outfile} ${backUpFile}" echo "wait" fi } ##____________________________________________________________________________|| function cp_with_timestamp { local outfile=$1 if [ -s ${outfile} ]; then local backUpFile=$(create_backUpFile_path ${outfile}) echo "cp -a ${outfile} ${backUpFile}" echo "wait" fi } ##____________________________________________________________________________||
Markdown
UTF-8
8,114
2.6875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Scowl [![status](http://joss.theoj.org/papers/1b9d09aab8754997884a04c081cfc019/status.svg)](http://joss.theoj.org/papers/1b9d09aab8754997884a04c081cfc019) Scowl provides a Scala DSL allowing a declarative approach to composing OWL expressions and axioms using the [OWL API](http://owlapi.sourceforge.net). ## Usage Since version 1.2.1, Scowl is available via Maven Central. Add the dependency to your `build.sbt` if you are using OWL API 4.x: ```scala libraryDependencies += "org.phenoscape" %% "scowl" % "1.4.1" ``` For OWL API 5.x: ```scala libraryDependencies += "org.phenoscape" %% "scowl-owlapi5" % "1.4.1" ``` Import `org.phenoscape.scowl._`, and Scowl implicit conversions will add pseudo Manchester syntax methods to native OWL API objects. Additionally, functional syntax-style constructors and extractors will be in scope. Scowl 1.2+ is built with OWL API 4.x (and from 1.4.1, additionally OWL API 5.x). For OWL API 3.5, use Scowl 1.0.2. Scowl is cross-compiled to support Scala 2.13 and Scala 3. ## Examples The easiest way to get started is to see how the DSL can be used to implement all the examples from the [OWL 2 Web Ontology Language Primer](https://www.w3.org/TR/owl2-primer/): * [Manchester syntax style](https://github.com/phenoscape/scowl/blob/master/src/main/scala/org/phenoscape/scowl/example/OWL2PrimerManchester.scala) * [Functional syntax style](https://github.com/phenoscape/scowl/blob/master/src/main/scala/org/phenoscape/scowl/example/OWL2PrimerFunctional.scala) The examples below are also available in [code](https://github.com/phenoscape/scowl/blob/master/src/main/scala/org/phenoscape/scowl/example/ReadMeExamples.scala). ### Scowl expressions use and return native OWL API objects ```scala import org.phenoscape.scowl._ // import org.phenoscape.scowl._ val hasParent = ObjectProperty("http://www.co-ode.org/roberts/family-tree.owl#hasParent") // hasParent: org.semanticweb.owlapi.model.OWLObjectProperty = <http://www.co-ode.org/roberts/family-tree.owl#hasParent> val isParentOf = ObjectProperty("http://www.co-ode.org/roberts/family-tree.owl#isParentOf") // isParentOf: org.semanticweb.owlapi.model.OWLObjectProperty = <http://www.co-ode.org/roberts/family-tree.owl#isParentOf> val isSiblingOf = ObjectProperty("http://www.co-ode.org/roberts/family-tree.owl#isSiblingOf") // isSiblingOf: org.semanticweb.owlapi.model.OWLObjectProperty = <http://www.co-ode.org/roberts/family-tree.owl#isSiblingOf> val Person = Class("http://www.co-ode.org/roberts/family-tree.owl#Person") // Person: org.semanticweb.owlapi.model.OWLClass = <http://www.co-ode.org/roberts/family-tree.owl#Person> val FirstCousin = Class("http://www.co-ode.org/roberts/family-tree.owl#FirstCousin") // FirstCousin: org.semanticweb.owlapi.model.OWLClass = <http://www.co-ode.org/roberts/family-tree.owl#FirstCousin> val axiom = FirstCousin EquivalentTo (Person and (hasParent some (Person and (isSiblingOf some (Person and (isParentOf some Person)))))) // axiom: org.semanticweb.owlapi.model.OWLEquivalentClassesAxiom = EquivalentClasses(<http://www.co-ode.org/roberts/family-tree.owl#FirstCousin> ObjectIntersectionOf(<http://www.co-ode.org/roberts/family-tree.owl#Person> ObjectSomeValuesFrom(<http://www.co-ode.org/roberts/family-tree.owl#hasParent> ObjectIntersectionOf(<http://www.co-ode.org/roberts/family-tree.owl#Person> ObjectSomeValuesFrom(<http://www.co-ode.org/roberts/family-tree.owl#isSiblingOf> ObjectIntersectionOf(<http://www.co-ode.org/roberts/family-tree.owl#Person> ObjectSomeValuesFrom(<http://www.co-ode.org/roberts/family-tree.owl#isParentOf> <http://www.co-ode.org/roberts/family-tree.owl#Person>)))))) ) ``` ### Add some axioms and programmatically generated GCIs to an ontology ```scala val manager = OWLManager.createOWLOntologyManager() val ontology = manager.createOntology() val PartOf = ObjectProperty("http://example.org/part_of") val HasPart = ObjectProperty("http://example.org/has_part") val DevelopsFrom = ObjectProperty("http://example.org/develops_from") val Eye = Class("http://example.org/eye") val Head = Class("http://example.org/head") val Tail = Class("http://example.org/tail") manager.addAxiom(ontology, Eye SubClassOf (PartOf some Head)) manager.addAxiom(ontology, Eye SubClassOf (not(PartOf some Tail))) val gcis = for { term <- ontology.getClassesInSignature(true) } yield { (not(HasPart some term)) SubClassOf (not(HasPart some (DevelopsFrom some term))) } manager.addAxioms(ontology, gcis) ``` ### Using pattern matching extractors to implement negation normal form ```scala def nnf(expression: OWLClassExpression): OWLClassExpression = expression match { case Class(_) => expression case ObjectComplementOf(Class(_)) => expression case ObjectComplementOf(ObjectComplementOf(expression)) => nnf(expression) case ObjectUnionOf(operands) => ObjectUnionOf(operands.map(nnf)) case ObjectIntersectionOf(operands) => ObjectIntersectionOf(operands.map(nnf)) case ObjectComplementOf(ObjectUnionOf(operands)) => ObjectIntersectionOf(operands.map(c => nnf(ObjectComplementOf(c)))) case ObjectComplementOf(ObjectIntersectionOf(operands)) => ObjectUnionOf(operands.map(c => nnf(ObjectComplementOf(c)))) case ObjectAllValuesFrom(property, filler) => ObjectAllValuesFrom(property, nnf(filler)) case ObjectSomeValuesFrom(property, filler) => ObjectSomeValuesFrom(property, nnf(filler)) case ObjectMinCardinality(num, property, filler) => ObjectMinCardinality(num, property, nnf(filler)) case ObjectMaxCardinality(num, property, filler) => ObjectMaxCardinality(num, property, nnf(filler)) case ObjectExactCardinality(num, property, filler) => ObjectExactCardinality(num, property, nnf(filler)) case ObjectComplementOf(ObjectAllValuesFrom(property, filler)) => ObjectSomeValuesFrom(property, nnf(ObjectComplementOf(filler))) case ObjectComplementOf(ObjectSomeValuesFrom(property, filler)) => ObjectAllValuesFrom(property, nnf(ObjectComplementOf(filler))) case ObjectComplementOf(ObjectMinCardinality(num, property, filler)) => ObjectMaxCardinality(math.max(num - 1, 0), property, nnf(filler)) case ObjectComplementOf(ObjectMaxCardinality(num, property, filler)) => ObjectMinCardinality(num + 1, property, nnf(filler)) case ObjectComplementOf(ObjectExactCardinality(num, property, filler)) => ObjectUnionOf(ObjectMinCardinality(num + 1, property, nnf(filler)), ObjectMaxCardinality(math.max(num - 1, 0), property, nnf(filler))) case _ => ??? } ``` ### Using pattern matching extractors in for comprehensions ```scala // Print all properties and fillers used in existential restrictions in subclass axioms for { SubClassOf(_, subclass, ObjectSomeValuesFrom(property, filler)) <- ontology.getAxioms } yield { println(s"$property $filler") } // Make an index of language tags to label values val langValuePairs = for { AnnotationAssertion(_, RDFSLabel, _, value @@ Some(lang)) <- ontology.getAxioms(Imports.INCLUDED) } yield { lang -> value } val langToValues: Map[String, Set[String]] = langValuePairs.foldLeft(Map.empty[String, Set[String]]) { case (langIndex, (lang, value)) => langIndex.updated(lang, langIndex.getOrElse(value, Set.empty) ++ Set(value)) } ``` ## Question or problem? If you have questions about how to use Scowl, feel free to send an email to balhoff@gmail.com, or [open an issue on the tracker](https://github.com/phenoscape/scowl/issues). [Contributions are welcome](CONTRIBUTING.md). ## Funding Development of Scowl has been supported by National Science Foundation grant DBI-1062404 to the University of North Carolina. ## License Scowl is open source under the [MIT License](http://opensource.org/licenses/MIT). See [LICENSE](LICENSE) for more information.
Python
UTF-8
1,862
2.765625
3
[ "MIT" ]
permissive
from __future__ import annotations from typing import TYPE_CHECKING, Any from .base import TelegramObject class Invoice(TelegramObject): """ This object contains basic information about an invoice. Source: https://core.telegram.org/bots/api#invoice """ title: str """Product name""" description: str """Product description""" start_parameter: str """Unique bot deep-linking parameter that can be used to generate this invoice""" currency: str """Three-letter ISO 4217 `currency <https://core.telegram.org/bots/payments#supported-currencies>`_ code""" total_amount: int """Total price in the *smallest units* of the currency (integer, **not** float/double). For example, for a price of :code:`US$ 1.45` pass :code:`amount = 145`. See the *exp* parameter in `currencies.json <https://core.telegram.org/bots/payments/currencies.json>`_, it shows the number of digits past the decimal point for each currency (2 for the majority of currencies).""" if TYPE_CHECKING: # DO NOT EDIT MANUALLY!!! # This section was auto-generated via `butcher` def __init__( __pydantic__self__, *, title: str, description: str, start_parameter: str, currency: str, total_amount: int, **__pydantic_kwargs: Any, ) -> None: # DO NOT EDIT MANUALLY!!! # This method was auto-generated via `butcher` # Is needed only for type checking and IDE support without any additional plugins super().__init__( title=title, description=description, start_parameter=start_parameter, currency=currency, total_amount=total_amount, **__pydantic_kwargs, )
TypeScript
UTF-8
1,532
3.296875
3
[]
no_license
import { createHandyClient, IHandyRedis } from 'handy-redis'; /** * Cache client class integrated with handy-redis library. * The API is to use in asynchronous code. */ export default class CacheClient { private client: IHandyRedis; private readonly VALUE_EXISTS = 1; /** * Create new cache client. * * @param port Port of the redis instance. * @param host Address of the redis instance. */ constructor(port: number, host: string) { this.client = createHandyClient(port, host); } /** * Save the value under given key to redis. * Recommended is to set up TTL because the default TTL is set to 60 seconds. * * @param key Redis key. * @param value Value to save in cache. * @param ttl TTL (time to live) of the key in redis. */ writeToCache = async (key: string, value: string, ttl = 60): Promise<void> => { await this.client.set(key, value, [ 'EX', ttl ]); } /** * Get value from cache * * @param key */ readFromCache = async (key: string): Promise<string | null> => { return await this.client.get(key); } /** * Check if key is inside the redis. * * @param key Redis key. * * @returns True if key exists, false if don't. */ isKeyInCache = async (key: string): Promise<boolean> => { const isKeyInCache = await this.client.exists(key); return isKeyInCache === this.VALUE_EXISTS; } /** * Close connection to Redis. */ closeConnection = async (): Promise<void> => { await this.client.quit(); } };
C++
UTF-8
487
3.59375
4
[]
no_license
#include<iostream> #include<math.h> using namespace std; bool isPrime(int n) { for (int j = 2; j <= sqrt(n); j++) { if (n % j == 0) { return false; } } return true; } int main() { int num1, num2; cin >> num1 >> num2; cout << "Prime no. bw " << num1 << " & " << num2 << " are "; for (int i = num1; i <= num2; i++) { if (isPrime(i)) { cout << i << " "; } } return 0; }
Markdown
UTF-8
3,068
2.78125
3
[ "MIT" ]
permissive
--- layout: page title: About permalink: /about/ image: /assets/images/mcarroll.jpg --- # About Me <br /> I am an IBM Senior Cloud Engineer who specializes in the Watson Data and AI services. I work primarily by leveraging technical skills build cloud-native solutions for customers. Before joining IBM I worked for [NASA's Columbia Scientific Balloon Facility](http://www.csbf.nasa.gov) as a Software Engineering Intern. While there I focused on the Aquila display program which was used to display flight data in real-time from payloads. I'm also a former [High School Aerospace Scholar](https://www.nasa.gov/centers/johnson/stem/High_School_Aerospace_Scholars.html) and [Community College Aerospace Scholar](https://www.nasa.gov/centers/johnson/stem/NASA_Community_College_Aerospace_Scholars.html)! Because I enjoy staying busy, I participated in the [Distributed Research Experience for Undergraduates](https://cra.org/cra-wp/dreu/) program at through the [National Science Foundation](http://www.nsf.gov) at The University of Alabama during the summer of 2015 where I researched pervasive systems for elder care. You can read about my experience in [this article](https://cra.org/profiles-women-computing-morgan-carroll/) from the Computing Research Association for Women or on [my blog from that summer](https://mcarroll15.weebly.com/). I earned my Bachelor's degree in Computer Science (math minor, woot) from [The University of Texas at Tyler](http://www.uttyler.edu) shortly after that. Again because I evidently do not enjoy free time, I decided to begin working towards my Master's degree in Computer Science and as of 2020, I have graduated from [Texas State University's](https://www.txstate.edu/) Computer Science graduate program! Outside of work, I am an East Texas native (8th generation) but have lived in Austin for 4 years. My interests include gaming, astronomy, reading, kayaking, women's rights, spending time with my dogs, and trying new restaurants around Austin. Until recently I owned a motorcycle and still consider it to be one of my favorite hobbies. ## Patents Coming soon! ## The Dogs I love dogs and have three of my own: Apollo, Asia, and Mr. Hubble. They are all rescues, and I would highly encourage anyone looking to add a furry member to their family to consider adopting. If you can't adopt, consider donating or volunteering! Since 2012 I have been volunteering as the webmaster for the animal shelter that I adopted two of the dogs from: [www.barctx.org](https://www.barctx.org) !["Apollo was born in 2009, and I adopted her when she was only 6 weeks old. She likes to follow me everywhere I go!"](/assets/images/dogs-apollo.jpg) !["Mr. Hubble is the most sociable of the three. He even has his own Instagram account: @mrhubble He was born in 2012 and I adopted him in 2013 after he was found roaming the streets."](/assets/images/dogs-mrhubble.jpeg) !["The newest edition, Asia! I adopted her in 2019, and as of 2020 she is 12 years young. She loves sleeping and snacking, as we all do."](/assets/images/dogs-asia.png)
Markdown
UTF-8
2,465
2.921875
3
[]
no_license
## Aggregation Example Proof of Concept application of a mock telemetry aggregation. Logic done using akka, primarily streams, since they present a nice fit for high frequency data (small in size).<br /> *Notes*: Some presumptions are taken into account when designing this. - Data is always correct (i.e no negative speed/distance) - Aggregation is done with an "until now" concept in mind. The data is generated dynamically using `DataSource`. This decision was made to mimic high data volume (the data itself should be valid, however this was not the focus). For testing purposes static data was created to be able to control the scenario tested: <br /> Example: vehicleState change (parked -> driving) <br /> <br /> The main aggregation logic is contained in `TelemetryService` class, using filtering to mimic a batch operation on a stream. Current implementation assumes data ordering is important, if data is split up in such a way where data points are not dependent (ordering does not matter) it would be easy to switch to `foldAsync` combined with `ask` pattern actor(s). <br /> <br /> Core logic is contained in `runBatch` method that returns a `runnableGraph` for easier debuuging manipulation (it can be run anywhere). <br /> Couple of methods `getAggregationByIDs` and `getAggregationByID` were added for exposing direct access to aggregation. Calling either would run the aggregation each time, so a real implementation would include some sort of storage (however this is outside the scope of the example). <br /> <br /> *Note*: While a database storage is outside the scope, it would be easy to add a db Sink or a construct a custom db Flow at any point in the stream composition. Rest of the code is mostly orchestration and coordination of the actors, to make sure the application does not exit before all the data has been processed (This would not be an issue in a real world example where the app would be running constantly). ## How to run `sbt run` to run the main example app. <br /> `sbt test` to run the tests. <br /> App configuration is in `application.conf` parameters can be configured from there. ### Params: - DataSource: - throttle (Boolean): Used to simulate a throttled stream (rate limited to `rate` per second) - rate: See above - numberOfSources: number of "telemetry sources" merged together - persistence - persistence (Boolean): Enable file persistence of raw data - filePath: path of the file
Markdown
UTF-8
3,051
2.578125
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: Create a canvas app from Figma (preview) description: Learn about how to create canvas apps from Figma. author: mduelae ms.topic: article ms.custom: canvas ms.reviewer: mkaur ms.date: 06/01/2022 ms.subservice: canvas-maker ms.author: kaagar search.audienceType: - maker contributors: - mduelae --- # Create a canvas app from Figma [This article is pre-release documentation and is subject to change.] In this article, you'll learn about creating canvas apps using your existing Figma design. [Figma](https://www.figma.com/) is a graphics editor and a design tool that you can use to create prototypes for your intended software design. After the design has been finalized, use the **Figma to app** feature to generate apps directly from the layout and design that you defined in your Figma file. ## Prerequisites - You must have access to a Figma design file that you want to use and create an app from. - The Figma file must be designed using the [Create Apps from Figma UI Kit](https://go.microsoft.com/fwlink/?linkid=2193981). > [!NOTE] > - If you're using the UI kit for the first time, familiarize yourself with the feature [overview](overview.md), the [UI kit](design-using-kit.md) capabilities, and its [components](supported-components.md). > - Power Apps doesn't persist the Figma files that you provide. The Figma files are only processed in-memory to generate the app. ## Create an app 1. Sign in to [Power Apps](https://make.powerapps.com). 1. Under **Start from**, select **Figma**. :::image type="content" source="media/maker-figma.png" alt-text="Select Figma from available options."::: 1. Enter an app name. 1. Enter the Figma file URL. More information: [Share files and prototypes](https://help.figma.com/hc/articles/360040531773-Share-or-embed-files-and-prototypes) 1. Enter the Figma personal access token. More information: [Create a new personal access token](https://help.figma.com/hc/articles/360052378433-Bubble-and-Figma#In_Figma) :::image type="content" source="media/create-app.png" alt-text="Create app dialog box with app name, Figma URL and personal access token created."::: > [!NOTE] > Power Apps uses your personal access token to connect to your Figma page or frame with **Can view** (read-only) access, and doesn't make any changes inside Figma. 1. Select **Create**. Once the app is created, your new app will open up in Power Apps Studio so you can continue building and customizing your app. :::image type="content" source="media/studio.png" alt-text="Created app opened inside Power Apps Studio."::: 1. Extend this app by [connecting to data](../add-data-connection.md), [adding app logic](../working-with-formulas.md), and adding more [screens](../add-screen-context-variables.md) and [controls](../add-configure-controls.md) as necessary. 1. [Save, publish](../save-publish-app.md), and [share](../share-app.md) the app. ### See also - [Troubleshoot common errors](common-errors.md) - [Components supported by the UI Kit](supported-components.md)
Markdown
UTF-8
1,375
3.8125
4
[]
no_license
# 0647 - Palindromic Substrings Difficulty | Tags | Links | Solutions ----------- | ---- | ----- | ----- Medium | String, Dynamic Programming | [Leetcode](https://leetcode.com/problems/palindromic-substrings) | [solution](https://leetcode.com/problems/palindromic-substrings/solution/) ----------- <p>Given a string, your task is to count how many palindromic substrings in this string.</p> <p>The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.</p> <p><b>Example 1:</b></p> <pre> <b>Input:</b> &quot;abc&quot; <b>Output:</b> 3 <b>Explanation:</b> Three palindromic strings: &quot;a&quot;, &quot;b&quot;, &quot;c&quot;. </pre> <p>&nbsp;</p> <p><b>Example 2:</b></p> <pre> <b>Input:</b> &quot;aaa&quot; <b>Output:</b> 6 <b>Explanation:</b> Six palindromic strings: &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;aa&quot;, &quot;aa&quot;, &quot;aaa&quot;. </pre> <p>&nbsp;</p> <p><b>Note:</b></p> <ol> <li>The input string length won&#39;t exceed 1000.</li> </ol> <p>&nbsp;</p> ----------- ## Similar Problems - [Medium] [Longest Palindromic Substring](longest-palindromic-substring) - [Medium] [Longest Palindromic Subsequence](longest-palindromic-subsequence) - [Medium] [Palindromic Substrings](palindromic-substrings) ## Thought:
Markdown
UTF-8
3,597
2.78125
3
[]
no_license
# 다른 분산장부 기술 Quorum : 이더리움 기반 Permissioned Corda : 사업간 자동화된 법적 동의를 기록, 관리 Chain Core : 재무서비스 기관에 의해 디자인됨 ## Chain core []( https://chain.com/technology/) Chain Core is an enterprise permissioned blockchain system that is mostly focused on financial services, like currencies, securities, derivatives, gift cards, and loyalty points. The company partners with clients to launch and operate a network under the client's brand. Thanks to its strategic partnerships with companies such as Capital One, Citigroup, Fiserv, Nasdaq, Orange, Visa, etc., the company raised over $40 million in funding since 2014. Within the Chain Core network, the creation and transfer of assets is decentralized. However, as stated in the 2016 Kudelski Security report, "the operation of the network is governed by a designated set of entities known as a federation". ## Corda Corda is a distributed ledger platform, which features a blockchain-style P2P network; however, it is not a blockchain platform. Unlike blockchains, which involve global availability of data across the network and third party validators, Corda only allows information access and validation functions to parties actually involved in the transaction. Featuring a different software architecture, "Corda achieves consensus between firms at the level of individual deals, not the level of the system" (Richard Gendal Brown, 2016), while supporting a variety of consensus mechanisms. [](www.corda.net) ## Quroum Created by JPMorgan, Quorum is, in fact, a fork of the Ethereum public blockchain, which uses a voting-based consensus algorithm to facilitate an enterprise-focused distributed ledger and smart contract platform. Data privacy is achieved within the network by allowing data visibility on a need-to-know basis. The platform is designed to support "both transaction-level privacy and network-wide transparency" (jpmorgan.com). The network validates all smart contracts and overall system state through the involvement of all running nodes. As with other permissioned ledgers, regulatory compliance is front and center in the Quorum platform. ## IOTA The cryptocurrency IOTA has been around since 2015. According to Martin Rosulek, "It is the first cryptocurrency that provides the whole ecosystem based on blockless blockchain" to enable machine-to-machine (M2M) transactions. IOTA, however, is more than just a cryptocurrency. Essentially, the platform entails a generalization of the blockchain protocol (the technology called Tangle) that sits at the backend of the IOTA platform. Instead of paying miners to validate the transactions, the architecture of the network involves peer-based validation. We can think of a simple analogy, that of a teacher grading students' homework: the students are the clients/users in the Bitcoin protocol, and the teacher is the miner/validator. Tangle technology asks students (users) to grade each other's homework, making the need for a teacher (external validator) redundant, and avoiding expenses related to the teacher's/validator's work. This allows the platform to be completely free of cost, without facing the scaling challenges that are inherent in the first generation of blockchains. f blockchains. Additionally, the use of the platform with connected devices or the Internet of Things "enables companies to explore new business-to-business models by making every technological resource a potential service to be traded on an open market in real time, with no fees"
Java
UTF-8
2,569
2.109375
2
[]
no_license
package com.cookandroid.haje; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import android.widget.Toast; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.firestore.FirebaseFirestore; public class LoginActivity extends AppCompatActivity { private FirebaseAuth auth; TextView inputID; TextView inputPW; ImageButton btnSignIn; ImageButton btnSignUp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); btnSignIn = findViewById(R.id.btnSignIn); btnSignUp = findViewById(R.id.btnSignUp); btnSignIn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { login(); } }); btnSignUp.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getApplicationContext(), SignupActivity.class); startActivity(intent); } }); } public void login(){ inputID = findViewById(R.id.inputID); inputPW = findViewById(R.id.inputPW); if(inputID.getText().toString().isEmpty() || inputPW.getText().toString().isEmpty()){ Toast.makeText(this, "이메일과 비밀번호를 입력하세요", Toast.LENGTH_LONG).show(); } auth = FirebaseAuth.getInstance(); auth.signInWithEmailAndPassword(inputID.getText().toString(), inputPW.getText().toString()) .addOnCompleteListener(task -> { if(task.isSuccessful()){ Toast.makeText(this, "로그인 되었습니다", Toast.LENGTH_LONG).show(); Intent intent = new Intent(getApplicationContext(), GpsActivity.class); intent.putExtra("email", inputID.getText().toString()); startActivity(intent); } else{ Toast.makeText(this, task.getException().getMessage(), Toast.LENGTH_LONG).show(); } }); } public void onShowClick(View v){ Intent intent = new Intent(getApplicationContext(), ShowRideActivity.class); startActivity(intent); } }
Ruby
UTF-8
685
2.8125
3
[]
no_license
class EntityParser attr_reader :entity def initialize entity=nil @entity = entity check_entity unless entity.nil? end def find_entity Dir['*.vhd'].each do |vhd_file| open(vhd_file) do |vhd_file_content| if not vhd_file_content.grep(/entity\s+#{@entity}\s+/).empty? @vhd_entity_file = vhd_file return true end end end return false end def check_entity if not find_entity then puts "ERROR 1: entity not found, exiting..." Process.exit 1 end end def get_entity_body open(@vhd_entity_file) do |vhd| matchs = vhd.read.match(/(entity\s+#{@entity}\s+is\s+)(.*)(end\s+(entity|#{@entity}))/m) return matchs[2] end end end
Java
UTF-8
323
1.820313
2
[]
no_license
package iotgo.bean; import lombok.*; @Data @Builder public class UserTag { private String uuid; private String tagName; private String tagDesc; private String tagType; private long createAt; private long updateAt; /** * 是否拥有该标签 */ private boolean haveTag; }
PHP
UTF-8
265
2.765625
3
[]
no_license
<?php session_start(); if (isset($_SESSION['login'])) { echo "Selamat Datang ".$_SESSION['login']; echo "<a href='session2,5.php'>(session2,5.php)</a> Logout"; }else { die("Anda Belum Login. Silahkan Login<a href=session1.php>disini</a>"); }
Java
UTF-8
1,118
2.109375
2
[]
no_license
// isComment package com.github.mobile.ui; import android.app.AlertDialog; import android.content.Context; /** * isComment */ public class isClassOrIsInterface extends AlertDialog { /** * isComment */ public static AlertDialog isMethod(final Context isParameter) { return new LightAlertDialog(isNameExpr, isNameExpr); } private isConstructor(final Context isParameter, final int isParameter) { super(isNameExpr, isNameExpr); } private isConstructor(final Context isParameter) { super(isNameExpr); } /** * isComment */ public static class isClassOrIsInterface extends AlertDialog.Builder { /** * isComment */ public static LightAlertDialog.Builder isMethod(final Context isParameter) { return new LightAlertDialog.Builder(isNameExpr, isNameExpr); } private isConstructor(Context isParameter) { super(isNameExpr); } private isConstructor(Context isParameter, int isParameter) { super(isNameExpr, isNameExpr); } } }
Java
UTF-8
3,585
2.140625
2
[]
no_license
package com.rec.model; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.fasterxml.jackson.annotation.JsonIgnore; @Entity @Table(name="applicationModel") public class ApplicationModel { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long Id; @Column(name="AppliedDate") @Temporal(value=TemporalType.TIMESTAMP) private Date AppliedDate; @Column(name="Education") private String Education; @Column(name="Experience") private String Experience; @Column(name="OtherInfo") private String OtherInfo; @Column(name="jobId") private Long jobId; @Column(name="applicantId") private Long applicantId; @ManyToOne(cascade = CascadeType.ALL) private ApplicantModel applicantmodel; @OneToMany(targetEntity = ApplicationDocumentModel.class,mappedBy = "applicationmodel", cascade = {CascadeType.ALL}) private List<ApplicationDocumentModel> applicationdocumodel=new ArrayList<>(); public Long getId() { return Id; } public void setId(Long id) { Id = id; } public Date getAppliedDate() { return AppliedDate; } public void setAppliedDate(Date appliedDate) { AppliedDate = appliedDate; } public String getEducation() { return Education; } public void setEducation(String education) { Education = education; } public String getExperience() { return Experience; } public void setExperience(String experience) { Experience = experience; } public String getOtherInfo() { return OtherInfo; } public void setOtherInfo(String otherInfo) { OtherInfo = otherInfo; } public Long getJobId() { return jobId; } public void setJobId(Long jobId) { this.jobId = jobId; } public Long getApplicantId() { return applicantId; } public void setApplicantId(Long applicantId) { this.applicantId = applicantId; } public ApplicantModel getApplicantmodel() { return applicantmodel; } public void setApplicantmodel(ApplicantModel applicantmodel) { this.applicantmodel = applicantmodel; } public List<ApplicationDocumentModel> getApplicationdocumodel() { return applicationdocumodel; } public void setApplicationdocumodel(List<ApplicationDocumentModel> applicationdocumodel) { this.applicationdocumodel = applicationdocumodel; } public ApplicationModel() { super(); } @Override public String toString() { return "ApplicationModel [Id=" + Id + ", AppliedDate=" + AppliedDate + ", Education=" + Education + ", Experience=" + Experience + ", OtherInfo=" + OtherInfo + ", jobId=" + jobId + ", applicantId=" + applicantId + ", applicantmodel=" + applicantmodel + ", applicationdocumodel=" + applicationdocumodel + "]"; } public ApplicationModel(Long id, Date appliedDate, String education, String experience, String otherInfo, Long jobId, Long applicantId, ApplicantModel applicantmodel, List<ApplicationDocumentModel> applicationdocumodel) { super(); Id = id; AppliedDate = appliedDate; Education = education; Experience = experience; OtherInfo = otherInfo; this.jobId = jobId; this.applicantId = applicantId; this.applicantmodel = applicantmodel; this.applicationdocumodel = applicationdocumodel; } }
Markdown
UTF-8
3,646
2.71875
3
[]
no_license
# How to install open mpi on Raspberry pi (fixing the arm) MPI is most famous communication protocol for parallel computing. As time passed, a lot of parallel programming languages have been sprang up, but still, MPI is dominant in high performance computing. The key characteristic of MPI is versatility. Thus, its uses isn’t confined to supercomputer. Actually, MPI is fascinating tool to construct distributed system which consist of simple and identical machines. There are 2 major implementation in MPI. First one is MPICH, and second one is Open MPI. # known Issue Since last year, as I’ve been working on some project, I found that there were some issues in terms of configuring Open MPI on RPi. When I trying to build mpi, I have to show the following message all the time : Error: selected processor does not support ARM mode `dmb' At the time, I just bypassed by using mpich instead of OMPI or install the old version from Raspbian Software Center ( equivalent of basic application : Add/ Remove Software, this method is not work recently though .. ), because I couldn’t find firm answer from google. Recently, I succeeded in solve the problem, which I struggled with. I hope the people who want to use MPI on Raspberry pi (but suffer from same problem) get some help from this simple guide. # solution ### Operation environment Raspberry pi 3 Linux raspberrypi 4.4.34-v7+ armv7l GNU/Linux gcc(Raspbian 4.9.2-10) 4.9.2 You might aware that the architecture showed up is different with real hardware architecture (cortex-a53, armv8) it because RPi is working on 32-bit OS. Similarly, this sort of thing is happened in case of RPi1 and RPi2 (as armv6l). It’s the principal cause of make command failure. Because of this, while processing configure script raspberry pi capture its own information in a wrong way. So, we should give integral instruction manually using gcc flag option. ## Step 1 : download and extract open mpi At first, you need to download lastest stable version of open mpi from official (https://www.open-mpi.org/software/ompi/v3.0/), or you can just type following line : wget https://www.open-mpi.org/software/ompi/v3.0/downloads/openmpi-3.0.1.tar.gz Likewise, in odrder to extract the downloaded file and change directory : tar xvzf openmpi-3.0.1.tar.gz cd openmpi-3.0.1 ## Step 2 : give ARM option when configure ./configure CFLAGS=”-mcpu=cortex-a53 -mfloat-abi=hard -mfpu=neon-fp-armv8 -mneon-for-64bits” make make install Of course, detail variable is depend on your setup. For example, if you want to build OMPI on RPi2, than you need to put CFLAGS=”-mcpu=cortex-7 -mfloat-abi=hard -mfpu=neon-vfpv4” instead of flag for RPi3 in upper box. ## Step 3 (optional) : use ldconfig In the process of installation, I found several library linking errors were occurred. It can cause another problem when compile mpi program. mpicc: error while loading shared libraries: libopen-pal.so.4: cannot open shared object file: No such file or directory But ldconfig will create links for mpi easily. Only thing we have to do is type following command on terminal. sudo ldconfig After all, with these simple steps, now we can compile and run the mpi program. ## References - [GCC ARM OPTIONS]( https://gcc.gnu.org/onlinedocs/gcc/ARM-Options.html) - [GCC compiler optimization for ARM-based systems](https://gist.github.com/fm4dd/c663217935dc17f0fc73c9c81b0aa845) - [LDCONFIG Linux Programmer’s Manual]( http://man7.org/linux/man-pages/man8/ldconfig.8.html) - [Building Open MPI](https://www.open-mpi.org/faq/?category=building)
Markdown
UTF-8
1,932
2.828125
3
[]
no_license
--- uid: bb9ab3ea0c546b87900fafd21424cd19 title: 3.2 Asymptotics course_id: 6-042j-mathematics-for-computer-science-spring-2015 type: course layout: course_section parent_title: 3.2 Asymptotics --- * [<Little oh Big Oh]({{< baseurl >}}/sections/counting/tp8-3/vertical-5c04897d10e6) * [3.2.1Asymptotic Notation: Video]({{< baseurl >}}/sections/counting/tp8-3) * [3.2.2Asymptotics as Relations]({{< baseurl >}}/sections/counting/tp8-3/vertical-3800c4b1c397) * [3.2.3Asymptotic Properties: Video]({{< baseurl >}}/sections/counting/tp8-3/vertical-e35ce9684389) * [3.2.4Little oh Big Oh]({{< baseurl >}}/sections/counting/tp8-3/vertical-5c04897d10e6) * [3.2.5Theta]({{< baseurl >}}/sections/counting/tp8-3/theta) * [3.2.6Asymptotic Blunders: Video]({{< baseurl >}}/sections/counting/tp8-3/vertical-f4d8cd185706) * [3.2.7Asymptotics the Right Way]({{< baseurl >}}/sections/counting/tp8-3/vertical-9df50ab7aa43) * [3.2.8Practice with Big O]({{< baseurl >}}/sections/counting/tp8-3/vertical-4c14279fa60f) * [3.2.9Practice with Order of Growth]({{< baseurl >}}/sections/counting/tp8-3/vertical-171ad650135b) * [\>Asymptotic Blunders]({{< baseurl >}}/sections/counting/tp8-3/vertical-f4d8cd185706) Theta ----- If \\(f=\\Theta(g)\\), which of the following MUST be true? Exercise 1 &nbsp;\\(g = \\Theta(f)\\)&nbsp; &nbsp;\\(f = o(g)\\)&nbsp; &nbsp;\\(g = o(f)\\)&nbsp; &nbsp;\\(f = O(g)\\)&nbsp; &nbsp;\\(g = O(f)\\)&nbsp; &nbsp;\\(f \\sim g\\)&nbsp; If \\(f=\\Theta(g)\\), which of the following CAN be true? Exercise 2 &nbsp;\\(g = \\Theta(f)\\)&nbsp; &nbsp;\\(f = o(g)\\)&nbsp; &nbsp;\\(g = o(f)\\)&nbsp; &nbsp;\\(f = O(g)\\)&nbsp; &nbsp;\\(g = O(f)\\)&nbsp; &nbsp;\\(f \\sim g\\)&nbsp; CheckShow Answer * [BackLittle oh Big Oh]({{< baseurl >}}/sections/counting/tp8-3/vertical-5c04897d10e6) * [ContinueAsymptotic Blunders: Video]({{< baseurl >}}/sections/counting/tp8-3/vertical-f4d8cd185706)
Python
UTF-8
902
2.671875
3
[]
no_license
import cv2 import numpy as np #img_name = "image4.pgm" #img = cv2.imread(img_name) def segmentation(im): #im = cv2.resize(im, (250, 288)) h, w = im.shape[:2] print(h,w) #cv2.waitKey(0) #for image 3 should not blur #for image 4 blur(3,3),mask 111 111 4/8 #blur 2,2 for image3 im = cv2.blur(im,(2,2)) mask = np.zeros((h+2, w+2), np.uint8) #using floodFill to separate background and object cv2.floodFill(im, mask, (w-1,h-1), (255,255,255), (1,1,1),(1,1,1),4) #blured = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) #cv2.imshow("s",blured) ret, binary = cv2.threshold(im,190,255,cv2.THRESH_BINARY) #cv2.imshow("s",binary) #cv2.waitKey(0) return binary #segmentation(img) # from PIL import Image # #print(im[1,2]) # im1 = Image.open("poker.png") # #im1 = np.asarray(Image.open('poker.png')) # im11 = im1.load() # #a,b = im1.size # print(im1.size)
C++
UTF-8
7,008
2.90625
3
[ "MIT" ]
permissive
#pragma once #include "intrhash.h" #include "nodeallc.h" namespace intrhash_map_priv { template <class K, class T, class O, class A> struct impl { using value_type = std::pair<const K, T>; struct node_t : public value_type , public intrhash_item_t<node_t> { node_t(const value_type& value) : value_type(value) {} template <class _K> node_t(const _K& key) : value_type(key, T()) {} }; struct ops: public O { static const K& extract_key(const value_type& node) noexcept { return node.first; } static value_type& extract_value(node_t& node) noexcept { return node; } static const value_type& extract_value(const node_t& node) noexcept { return node; } }; using allc_type = nodeallc_t<node_t, A>; using impl_type = intrhash_t<node_t, ops, A>; }; } template <class K, class T, class O = generic_intrhash_ops, class A = std::allocator<T>> class intrhash_map_t : private intrhash_map_priv::impl<K, T, O, A>::allc_type , private intrhash_map_priv::impl<K, T, O, A>::impl_type { private: using priv_impl = typename intrhash_map_priv::impl<K, T, O, A>; using allc_type = typename priv_impl::allc_type; using impl_type = typename priv_impl::impl_type; using item_type = typename impl_type::item_type; using node_type = typename impl_type::node_type; public: using value_type = typename priv_impl::value_type; public: using iterator = typename impl_type::iterator; using const_iterator = typename impl_type::const_iterator; public: using allc_type::get_allocator; using impl_type::begin; using impl_type::end; using impl_type::cbegin; using impl_type::cend; using impl_type::find; using impl_type::has; using impl_type::equal_range; using impl_type::count; using impl_type::size; using impl_type::empty; public: std::pair<iterator, bool> insert(const value_type& value) { return this->find_or_push(priv_impl::ops::extract_key(value), [this, &value](){ return this->new_node(value); }); } size_t erase(iterator iter) { if (node_type *const node = this->pop(iter.node())) { this->delete_node(node); return 1; } else { return 0; } } template <class _K> size_t erase(const _K& key) { if (node_type* const node = this->pop_one(key)) { this->delete_node(node); return 1; } else { return 0; } } void clear() { this->decompose([this](node_type* node){ this->delete_node(node); }); } public: template <class _K> T& operator[](const _K& key) { return this->find_or_push(key, [this, &key](){ return this->new_node(key); }).first->second; } public: intrhash_map_t() = default; explicit intrhash_map_t(size_t n) : impl_type(n) {} template <class X> explicit intrhash_map_t(size_t n, X&& allocator_param) : allc_type(std::forward<X>(allocator_param)) , impl_type(n, allc_type::get_allocator()) {} intrhash_map_t(intrhash_map_t&& right) : allc_type(std::move(right)) , impl_type(std::move(right)) {} intrhash_map_t(const intrhash_map_t& right) : allc_type(right) , impl_type(right, [this](const node_type* node){ return this->new_node(*node); }) {} ~intrhash_map_t() noexcept { clear(); } public: void swap(intrhash_map_t& right) noexcept { static_cast<allc_type*>(this)->swap(right); static_cast<impl_type*>(this)->swap(right); } intrhash_map_t& operator=(const intrhash_map_t& right) { intrhash_map_t(right).swap(*this); return *this; } intrhash_map_t& operator=(intrhash_map_t&& right) { intrhash_map_t(std::move(right)).swap(*this); return *this; } }; template <class K, class T, class O = generic_intrhash_ops, class A = std::allocator<T>> class intrhash_multimap_t : private intrhash_map_priv::impl<K, T, O, A>::allc_type , private intrhash_map_priv::impl<K, T, O, A>::impl_type { private: using priv_impl = typename intrhash_map_priv::impl<K, T, O, A>; using allc_type = typename priv_impl::allc_type; using impl_type = typename priv_impl::impl_type; using item_type = typename impl_type::item_type; using node_type = typename impl_type::node_type; public: using value_type = typename priv_impl::value_type; public: using iterator = typename impl_type::iterator; using const_iterator = typename impl_type::const_iterator; public: using allc_type::get_allocator; using impl_type::begin; using impl_type::end; using impl_type::cbegin; using impl_type::cend; using impl_type::find; using impl_type::has; using impl_type::equal_range; using impl_type::count; using impl_type::size; using impl_type::empty; public: iterator insert(const value_type& value) { return {this->push(this->new_node(value))}; } size_t erase(iterator iter) { if (node_type *const node = pop(iter.node())) { delete_node(node); return 1; } else { return 0; } } template <class _K> size_t erase(const _K& key) { size_t result = 0; this->pop_all(key, [this, &result](node_type* node){ this->delete_node(node); ++result; }); return result; } void clear() { this->decompose([this](node_type* node){ this->delete_node(node); }); } public: intrhash_multimap_t() = default; explicit intrhash_multimap_t(size_t n) : impl_type(n) {} template <class X> explicit intrhash_multimap_t(size_t n, X&& allocator_param) : allc_type(std::forward<X>(allocator_param)) , impl_type(n, allc_type::get_allocator()) {} intrhash_multimap_t(intrhash_multimap_t&& right) noexcept : allc_type(std::move(right)) , impl_type(std::move(right)) {} intrhash_multimap_t(const intrhash_multimap_t& right) : allc_type(right) , impl_type(right, [this](const node_type* node){ return this->new_node(*node); }) {} ~intrhash_multimap_t() noexcept { clear(); } public: void swap(intrhash_multimap_t& right) noexcept { static_cast<allc_type*>(this)->swap(right); static_cast<impl_type*>(this)->swap(right); } intrhash_multimap_t& operator=(const intrhash_multimap_t& right) { intrhash_multimap_t(right).swap(*this); return *this; } intrhash_multimap_t& operator=(intrhash_multimap_t&& right) noexcept { intrhash_multimap_t(std::move(right)).swap(*this); return *this; } };
Java
UTF-8
1,026
2.0625
2
[]
no_license
package com.capgemini.account.Account; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.context.annotation.Bean; import com.capgemini.account.Account.entity.CurrentAccount; import com.capgemini.account.Account.entity.SavingsAccount; import com.capgemini.account.Account.repository.AccountRepository; @EnableDiscoveryClient @SpringBootApplication public class AccountApplication { public static void main(String[] args) { SpringApplication.run(AccountApplication.class, args); } @Bean public CommandLineRunner init(AccountRepository repository) { return (arg) -> { repository.save(new SavingsAccount(101,"Aakash", 10000.00,true)); repository.save(new CurrentAccount(102,"Saket", 20000.00,5000.00)); repository.save(new SavingsAccount(103,"Shivam", 30000.00,true)); }; } }
PHP
UTF-8
1,498
2.578125
3
[ "Apache-2.0" ]
permissive
<?php require 'vendor/autoload.php'; // Report ALL errors error_reporting(E_ALL); // Turn assertion handling way the hell up to fatal assert_options(ASSERT_ACTIVE, 1); assert_options(ASSERT_CALLBACK, function ($script, $line, $message) { throw new \Exception($message); }); // Set an error handler that catches EVERYTHING PHP may throw at us // (notices, warnings, etc) so that we can throw them all as strict errors. set_error_handler(function ($errno, $errstr, $errfile, $errline, $errcontext) { throw new \Exception(strtr( 'Unhandled PHP Error: {message} at {file}:{line}', [ '{message}' => $errstr, '{file}' => $errfile, '{line}' => $errline ] )); }); $app = new \IMP\SlimTwigWrapper('_ref'); $app->twig->enableDebug(); $app->twig->addExtension(new \Twig_Extension_Debug()); $app->route('get', '', function () { $apps = array(); $baseDir = dirname(dirname(__FILE__)); $fileWalker = new \IMP\FileWalker($baseDir); $fileWalker->setReturnDirectories(true); $fileWalker->setRecursiveWalk(false); while($fileWalker->walk()) { if (!$fileWalker->isDir) { continue; } if (substr($fileWalker->filename, 0, 1) === '_') { continue; } if (!file_exists($fileWalker->file . '/index.php')) { continue; } $apps[$fileWalker->filename] = $fileWalker->file; } $this->render('home.html', [ 'apps' => $apps, ]); }); $app->route('get', 'env', function () { $this->write('<pre>'.print_r($this->getVars(), true).'</pre>'); }); $app->run();
JavaScript
UTF-8
1,494
2.859375
3
[ "WTFPL" ]
permissive
var phone = require('phone'), _ = require('lodash'), areacodes = require('../data/areacodes.json') ; function validateAndNormalizeNumber(num) { var numData = phone(num), number = numData.length > 0 ? numData[0] : false, country = numData.length > 0 ? numData[1] : '' ; if(!number) { throw new Error('Invalid number format (does not align with E.164)'); return false; } // Only supporting US based area codes for now if(country !== 'USA') { throw new Error('Number (' + number + ') is not a valid USA number. ('+country+')'); return false; } return number; } var AreaCode = { // Pull info on specific Area Code // byCode(###) byCode : function(code) { return _.find(areacodes, {'areacode': code}); }, // By phone number, can handle most phone formats // leverages teh node-phone package so it should normalize well // - www.npmjs.com/package/phone // - https://github.com/aftership/node-phone // byNumber : function(num) { var number = validateAndNormalizeNumber(num); if(number) { var code = AreaCode.extractFromNumber(number); return AreaCode.byCode(code); } return false; }, // Extracts the area code from most number formats // uses the same method as byNumber to normalize extractFromNumber : function(num) { var number = validateAndNormalizeNumber(num); if(number) { return number.slice(2,5); } return false; } }; module.exports = AreaCode;
Shell
UTF-8
2,106
3.96875
4
[]
no_license
#!/bin/bash . /usr/local/lib/monitor-functions . /etc/monitoring/hostname LogFile="${LogDir}/services.log" LogContent="$(sed 1d "$LogFile")" MailSubject="Service was not running" NotRunning=() RestartVarnish=0 Process="$(basename $0)" restartService() { echo "Restarting service $1..." | tee -a "$LogFile" service $1 restart if ! service $1 status > /dev/null ; then echo "Service $1 still not running!" | tee -a "$LogFile" return 1 fi return 0 } checkService() { if ! service $1 status > /dev/null ; then echo "Service $1 is not running!" | tee -a "$LogFile" if ! restartService $1 ; then Failed=1 NotRunning+=( $1 ) else if [ -n "$2" ] ; then for Service in $(tr ',' ' ' <<< "$2") ; do restartService $Service done fi fi else echo "Service $1 is running" | tee -a "$LogFile" fi } checkServices() { while read line ; do Service="$(awk '{ print $1 }' <<< "$line")" Restart="$(awk '{ print $2 }' <<< "$line")" checkService $Service "$Restart" | logger -t "${Process}/${Service}" done < "$Services" if [ $RestartVarnish -eq 1 ] ; then service varnish restart | logger -t "${Process}/varnish" fi } if [ $EUID -ne 0 ] ; then sudo -u root MAILRC="/etc/mail.rc" $0 exit 0 fi date > "$LogFile" checkServices if [ "$LogContent" != "$(sed 1d "$LogFile")" ] ; then if [ x"$1" != "xnomail" ] ; then echo "FAILED: $Failed - Sending email..." if [ $Failed -eq 1 ] ; then Message="$(server-id ; echo ; echo)$(for ((i=0; i<${#NotRunning[@]}; i++)) ; do echo ${NotRunning[$i]} ; done)" mail -s "$MailSubject" $MailRecipient <<< "$Message" else MailSubject="Failed services working again" mail -s "$MailSubject" $MailRecipient < <(echo -e "$(server-id)\n\n$(cat "$LogFile")") fi else "Errors were found. No email will be sent." fi fi | logger -t "$Process" exit 0
Python
UTF-8
3,005
2.984375
3
[ "BSD-3-Clause" ]
permissive
""" Sky statistics computation class for `~skymatch.skymatch` and `~skymatch.skymatch._weighted_sky`. :Authors: Mihai Cara :License: :doc:`LICENSE` """ # THIRD PARTY from stsci.imagestats import ImageStats from copy import deepcopy __all__ = ['SkyStats'] __taskname__ = 'skystatistics' __author__ = 'Mihai Cara' class SkyStats(object): """ This is a superclass build on top of :py:class:`stsci.imagestats.ImageStats`. Compared to ImageStats, SkyStats has "persistent settings" in the sense that object's parameters need to be set once and these settings will be applied to all subsequent computations on different data. """ def __init__(self,skystat='mean',**kwargs): """ Initializes the SkyStats object. Parameters ----------- skystat : str Sets the statistics that will be returned by the `~SkyStats.calc_sky`. The following statistics are supported: 'mean', 'mode', 'midpt', and 'median'. First three statistics have the same meaning as in `stsdas.toolbox.imgtools.gstatistics <http://stsdas.stsci.edu/cgi-bin/gethelp.cgi?gstatistics>`_ while `skystat`\ ='median' will compute the median of the distribution. kwargs : dict A dictionary of optional arguments to be passed to `ImageStats`. """ self.npix = None self.skyval = None self._fields = ','.join(['npix',skystat]) self._kwargs = deepcopy(kwargs) if 'fields' in self._kwargs: del self._kwargs['fields'] if 'image' in self._kwargs: del self._kwargs['image'] self._skystat = { 'mean' : self._extract_mean, 'mode' : self._extract_mode, 'median' : self._extract_median, 'midpt' : self._extract_midpt }[skystat] def _extract_mean(self, imstat): return imstat.mean def _extract_median(self, imstat): return imstat.median def _extract_mode(self, imstat): return imstat.mode def _extract_midpt(self, imstat): return imstat.midpt def calc_sky(self, data): """ Computes statistics on data. Parameters ----------- data : numpy.ndarray A numpy array of values for which the statistics needs to be computed. Returns -------- statistics : tuple A tuple of two values: (`skyvalue`, `npix`), where `skyvalue` is the statistics specified by the `skystat` parameter during the initialization of the `SkyStats` object and `npix` is the number of pixels used in comuting the statistics reported in `skyvalue`. """ imstat = ImageStats(image = data, fields = self._fields, **(self._kwargs)) self.skyval = self._skystat(imstat) self.npix = imstat.npix return (self.skyval,self.npix)
C
UTF-8
592
3.40625
3
[ "MIT" ]
permissive
#include <stdio.h> #include <stdlib.h> char *reverse_string(char *input_string); char *reverse_string(char *input_string) { int i=0; int j=0; char *return_string; char filled_buffer[16]; while (input_string[i]!='\0') i++; while (i!=0) { filled_buffer[j]=input_string[i-1]; i--; j++; } return_string=filled_buffer; printf("%s", return_string); return return_string; } int main (void) { char *returned_string; returned_string=reverse_string("tasdflkj"); printf("%s", returned_string); return 1; }
Java
UTF-8
2,888
2.03125
2
[]
no_license
/** * * Copyright (c) 2016 乐视云计算有限公司(lecloud.com). All rights reserved * */ package com.letv.portal.task.gce.service.add.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.letv.common.result.ApiResultObject; import com.letv.portal.fixedPush.IFixedPushService; import com.letv.portal.model.elasticcalc.gce.EcGce; import com.letv.portal.model.elasticcalc.gce.EcGceCluster; import com.letv.portal.model.elasticcalc.gce.EcGceContainer; import com.letv.portal.model.task.TaskResult; import com.letv.portal.model.task.service.IBaseTaskService; import com.letv.portal.service.elasticcalc.gce.IEcGceContainerService; /** * 购买GCE:同步固资系统 * @author linzhanbo . * @since 2016年8月15日, 下午2:23:26 . * @version 1.0 . */ @Service("taskEcGceAddFixedPushService") public class TaskEcGceAddFixedPushServiceImpl extends BaseTaskEcGceServiceImpl implements IBaseTaskService { private final static Logger logger = LoggerFactory .getLogger(TaskEcGceAddFixedPushServiceImpl.class); @Autowired private IEcGceContainerService ecGceContainerService; @Autowired private IFixedPushService fixedPushService; @Override public TaskResult execute(Map<String, Object> params) throws Exception { String serverName = (String) params.get("serviceName"); logger.debug("同步集群[" + serverName + "]到固资系统"); TaskResult tr = super.execute(params); if (!tr.isSuccess()) return tr; EcGceCluster gceCluster = super.getGceCluster(params); Map<String, Object> map = new HashMap<String, Object>(); map.put("gceId", gceCluster.getGceId()); map.put("gcePackageId", gceCluster.getGcePackageId()); List<EcGceContainer> containers = this.ecGceContainerService.selectByMap(map); for(EcGceContainer container:containers){ ApiResultObject apiResult = this.fixedPushService.sendFixedInfo(container.getHostIp(),container.getContainerName(),container.getIpAddr(),"add"); if(!apiResult.getAnalyzeResult()) { //发送推送失败邮件,流程继续。 buildResultToMgr("GCE服务相关系统推送异常", container.getContainerName() +"节点固资系统数据推送失败,请运维人员重新推送", tr.getResult(), null); tr.setSuccess(apiResult.getAnalyzeResult()); tr.setResult(apiResult.getResult()); break; } } tr.setParams(params); return tr; } @Override public void rollBack(TaskResult tr) { } @Override public void beforeExecute(Map<String, Object> params) { } }
Java
UTF-8
2,101
3.921875
4
[]
no_license
package java_example.threads.lesson93; public class ConcurrentMain { public static void main(String[] args) { // 1-й Способ создания нового потока var th0 = new SimpleThread(); th0.start(); System.out.println("hello from main"); var th1 = new SimpleThread(); th1.start(); th1.interrupt(); // 2-й Способ создания нового потока Thread th2 = new Thread(new SimpleRunner()); th2.start(); // еще один (3-й) способ создания потока - с помощью lambda выражения new Thread(() -> System.out.println(ColorScheme.BLUE + "hello from Lambda Runnable")).start(); } } class SimpleThread extends Thread { // тут указывается тот код, к-й должен выполнится в отдельном потоке @Override public void run() { for (int i = 0; i < 10; i++) { try { sleep(1000); } catch (InterruptedException e) { System.out.println(ColorScheme.YELLOW + "WARN - " + currentThread().getName() + " was interrupted " + i); return; } // currentThread().getName() - выводит имя текущего потока System.out.println(ColorScheme.BLUE + "INFO - " + currentThread().getName() + " - " + i); } } } // еще один способ создания нового потока (выполнение кода в отдельном потоке) class SimpleRunner implements Runnable { @Override public void run() { // Thread.currentThread().setName("Runnable Thread"); for (int i = 0; i < 10; i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { System.out.println(ColorScheme.YELLOW + "WARN - " + Thread.currentThread().getName() + " was interrupted " + i); return; } // currentThread().getName() - выводит имя текущего потока System.out.println(ColorScheme.BLUE + "INFO - Runnable" + Thread.currentThread().getName() + " - " + i); } } }
Markdown
UTF-8
1,652
3.90625
4
[]
no_license
# python中的else `else`在python中使用还是挺多的,有些用法还是和其他的语言中不太一样 ## 1. if/else 这个是很常用的,条件判断成立则执行`if`下的语句,否则执行`else`下的 ```python if condition: # executed when condition == True ... else: # executed when condition == False ``` ## 2. for/else 这个用法的情况会发生在当需要遍历一个集合之类的东西的时候,在找到符合条件的时候`break`出循环, 之后需要判断是否在遍历的时候发生了`break`,可能需要加一个标志位来标记: ```python car_found_for_repair = False for car in cars: if needs_repair(car): send_for_repair(car) car_found_for_repair = True break if not car_found_for_repair: # do something ``` 这个时候使用`else`的话,代码就是这样的: ```python for car in cars: if needs_repair(car): send_for_repair(car) break else: # do something ``` 也就是说在`for`循环的时候没有发生`break`,那么`else`的语句就会执行 ## 3. while/else 这个和上面的`for/else`是一样的 ## 4. try/except/else 在处理异常的时候的使用,`else` 下的代码会在没有发生异常的时候执行 ```python try: # run some code except ValueError: # run this when ValueError is raised else: # run this only when no exception is raised finally: # run this after the code and any exception handling code ```
Java
UTF-8
2,031
1.859375
2
[]
no_license
package com.samcm.repository.dispatchpartydetails; import java.util.List; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.samcm.model.DispatchParty; import com.samcm.model.DispatchPartyDetails; /** * * Copyright 2020, Geeks Solutions * Geeks Solutions retains all ownership rights to this source code * * @author: Alim Khowaja * * DispatchPartyDetailsRepository.java used to */ @Repository public interface DispatchPartyDetailsRepository extends JpaRepository<DispatchPartyDetails, Integer>, CrudRepository<DispatchPartyDetails, Integer> { @Query(value = "select distinct dispd from DispatchPartyDetails dispd " + " left outer join dispd.dispatchParty disp" + " where " + " (:dispatchPartyId is null or disp.dispatchPartyId=(:dispatchPartyId) )" ) Page<DispatchPartyDetails> filter(@Param("dispatchPartyId") Integer dispatchPartyId, Pageable pageable); @Query("select distinct dispd from DispatchPartyDetails dispd " + " join dispd.dispatchParty disp " + "where" + "(:dispatchPartyDetailsId is null or dispd.dispatchPartyDetailsId=(:dispatchPartyDetailsId) )") DispatchPartyDetails findbyDispatchPartyDetailsId(@Param("dispatchPartyDetailsId") Integer dispatchPartyDetailsId); @Query("select distinct disp from DispatchParty disp " + " where" + " (:dispatchPartyId is null or disp.dispatchPartyId=(:dispatchPartyId) )") DispatchParty findDetailsByDispatchId(@Param("dispatchPartyId") Integer dispatchPartyId); @Query("select distinct dispd from DispatchPartyDetails dispd " + " join dispd.dispatchParty disp ") List<DispatchPartyDetails> findDispatchPartyDetailsWithParentProp(); }
PHP
UTF-8
970
2.703125
3
[ "MIT" ]
permissive
<?php /* * Copyright (c) 2016 Refinery29, Inc. * * For the full copyright and license information, please view * the LICENSE file that was distributed with this source code. */ namespace Refinery29\Sitemap\Component\News; use Assert\Assertion; final class Publication implements PublicationInterface { /** * @var string */ private $name; /** * @var string */ private $language; /** * @param string $name * @param string $language * * @throws \InvalidArgumentException */ public function __construct($name, $language) { Assertion::string($name); Assertion::notBlank($name); Assertion::string($language); Assertion::notBlank($language); $this->name = $name; $this->language = $language; } public function name() { return $this->name; } public function language() { return $this->language; } }
JavaScript
UTF-8
365
3.453125
3
[]
no_license
let rs = require('readline-sync') for (let i = 0; i < 5; i++) { let nome = rs.question('Digite o nome do aluno: ') let notaA = rs.questionFloat('Digite o valor da nota A: ') let notaB = rs.questionFloat('Digite o valor da nota B: ') let notaFinal = (notaA*30)/100 + (notaB*70)/100 console.log(`O aluno ${nome} tem uma média: ${notaFinal}`) }
C#
UTF-8
3,757
3.109375
3
[]
no_license
using System; using MySql.Data.MySqlClient; namespace FAS { public class AssetsModelDataValidator { Connection _connection; AssetsModel _assetModel; public AssetsModelDataValidator(AssetsModel assetModel) { _connection = new Connection(); _assetModel = assetModel; } private bool CheckPropertyTagIfAvailable() { bool property_tag_match_found = false; string query = @"SELECT count(*) from assets where property_tag = @property_tag AND property_tag != '' "; using (var connection = _connection.GetConnection()) { using (var cmd = new MySqlCommand(query,connection)) { cmd.Parameters.AddWithValue("property_tag",_assetModel.PropertyTag); property_tag_match_found = (Convert.ToInt32(cmd.ExecuteScalar()) > 0); } } return property_tag_match_found; } private void PropertyTagIsValid() { if (CheckPropertyTagIfAvailable()== true) { throw new ArgumentException("-Property Tag already used."); } } private void ItemIdIsGreaterThanZero() { if(_assetModel.Items.Id == 0){ throw new ArgumentException("-Item Model is empty."); } } private void ItemRequiresSerial() { if (_assetModel.Items.HasSerial == 1 && _assetModel.Serial.Id == 0) { throw new ArgumentException("-This item requires serial."); } } private void EmployeeIdIsGreaterThanZero() { if(_assetModel.EmployeeId == 0 ){ throw new ArgumentException("- Employee ID is required"); } } private void Quantity() { if (_assetModel.Quantity == 0) { throw new ArgumentException("-Quantity must be greater than 0."); } } private void Price() { switch (_assetModel.Price == 0) { case true: throw new ArgumentException("-Price must be greater than 0."); break; case false: DefinePriceIfValid(); break; } } private void DefinePriceIfValid() { ReceiptRepository receiptRepository = new ReceiptRepository(); switch (_assetModel.Items.HasSerial == 1) { case true: var list = receiptRepository.ItemPriceRange(_assetModel.Items.Id); int count = 0; foreach (var priceList in list) { if (priceList == _assetModel.Price) { count++; } } if (count == 0) { throw new ArgumentException("-Price must match on price list."); } break; case false: //var price = receiptRepository.GetPrice(_assetModel.Items.Id); //if (price != _assetModel.Price) { // throw new ArgumentException("-Price must match on price list."); //} break; } } public bool AssetsModelDataIsValid() { EmployeeIdIsGreaterThanZero(); PropertyTagIsValid(); ItemIdIsGreaterThanZero(); ItemRequiresSerial(); Quantity(); Price(); return true; } } }