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
1,988
2.78125
3
[]
no_license
#include "app/HelloTriangle.h" #include <iostream> bool HelloTriangle::setup() { const char* vertexCode = R"##( #version 460 core layout(location = 0) in vec2 vpos_ndc; in vec3 base_color; out vec3 fragmentColor; void main(){ gl_Position = vec4(vpos_ndc, 0.f, 1.f); fragmentColor = base_color; } )##"; const char* fragmentCode = R"##( #version 460 core out vec3 color; void main(){ color = vec3(1.f, 0.f, 0.f); } )##"; // Vertices const std::vector<glm::vec2> vertices{{-0.5f, -0.5f}, {0.5f, -0.5f}, {0.f, 0.5f}}; // Create vertex buffer std::vector<unsigned int> components{2}; m_vertexBuffer = std::make_unique<VertexBuffer>((const float*)vertices.data(), vertices.size() * 2, components); //glCreateBuffers(1, &vertexBuffer); //glNamedBufferData(vertexBuffer, vertices.size() * sizeof(float) * 2, (float*)vertices.data(), GL_STATIC_DRAW); // Vertex array object glGenVertexArrays(1, &vertexArray); glBindVertexArray(vertexArray); glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer); m_vertexBuffer->bind(GL_ARRAY_BUFFER); // Vec2, xy positions in normalized device coordinates glEnableVertexAttribArray(0); auto attribute = m_vertexBuffer->getAttributes().at(0); glVertexAttribPointer(0, attribute.componentCount, m_vertexBuffer->getType(), GL_FALSE, m_vertexBuffer->getStride(), (void*)attribute.offset); glBindVertexArray(0); m_shader = std::make_unique<Shader>(vertexCode, fragmentCode); // Global state glClearColor(0.2f, 0.3f, 0.3f, 1.f); return true; } void HelloTriangle::render() { // Clear color buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw glBindVertexArray(vertexArray); m_shader->setActive(); m_shader->set("base_color", {1.f, 0.f, 0.f}); glDrawArrays(GL_TRIANGLES, 0, m_vertexBuffer->getEntryCount()); glBindVertexArray(0); } HelloTriangle::~HelloTriangle() { glDeleteVertexArrays(1, &vertexArray); }
C++
UTF-8
1,450
2.71875
3
[]
no_license
#include <vector> #include <stdio.h> #include <cstring> #include <algorithm> using namespace std; typedef pair<int, int> P; const int N = 22; const int dx[] = { 0,-1, 0, 1}; // direction const int dy[] = {-1, 0, 1, 0}; int n, m, g[N][N], ex, ey; bool vis[N][N], ok; // visited vector <P> ans; void printAns(){ for (int i = 0; i < ans.size()-1; i++){ printf("(%d,%d)->", ans[i].first, ans[i].second); } printf("(%d,%d)\n", ex, ey); } void dfs(int x, int y){ //printf("dfs(%d, %d)\n", x, y); vis[x][y] = true; ans.push_back(P(x, y)); if (x==ex && y==ey){ ok=true; printAns(); vis[x][y] = false; ans.pop_back(); return; } for (int i = 0; i < 4; i++){ int cx = x + dx[i]; // cur, current int cy = y + dy[i]; if (cx<1 || cx > n || cy<1 || cy>m) continue; if (vis[cx][cy] || g[cx][cy] == 0) continue; dfs(cx, cy); } vis[x][y] = false; ans.pop_back(); //printf("End==dfs(%d, %d)\n", x, y); } int main(){ freopen("in.txt", "r", stdin); //freopen("out.txt", "w", stdout); scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++){ for (int j = 1; j <= m; j++){ scanf("%d", &g[i][j]); } } int sx, sy; scanf("%d%d%d%d", &sx, &sy, &ex, &ey); memset(vis, 0, sizeof vis); ans.clear(); ok = false; dfs(sx, sy); if (!ok) puts("-1"); return 0; }
Java
UTF-8
9,468
2.5
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2018 Institute of Computing Technology, Chinese Academy of Sciences. * Licensed under the terms of the Apache 2.0 license. * Please see LICENSE file in the project root for terms */ package eml.studio.server.visual.service; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import eml.studio.server.visual.charts.BarChart; import eml.studio.server.visual.statics.ThreadDataParser; import eml.studio.server.visual.statics.ThreadUtils; import eml.studio.shared.util.DataTools; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; /** * Service for generate bar chart */ public class BarChartService extends ChartService { private static final Logger logger = Logger.getLogger(ChartService.class.getName()); private static final int MAX_GROUP_SIZE = 16; /** * Get bar chart data option string to draw the chart * * @param filePath data file path * @param dataType data type * @param columns data all columns * @param gByCol group by column * @param valCol value column * @param aggCol aggregation column * @param logScale value column log scale * @return * @throws IllegalArgumentException */ public BarChart barChartGen(String filePath, String dataType, List<String> columns, String gByCol, String valCol, String aggCol,boolean logScale) throws IllegalArgumentException { // TODO Auto-generated method stub //Read data from hdfs List<String> results = readAllData(filePath,true); //Only read limited line data(if the data length over max length) //Prepare selected column list and init result list List<String> selectedCols = new ArrayList<String>(); selectedCols.add(gByCol); selectedCols.add(valCol); List<List<String>> selectedColsDatas = new ArrayList<List<String>>(); initiaColResults(selectedColsDatas,selectedCols); //Use Multithread to parse specific column data ExecutorService exec = Executors.newCachedThreadPool(); int threadNum = ThreadUtils.THREAD_NUM; int countNum = (int)Math.ceil(results.size() / threadNum); for(int i=0; i<threadNum; i++) { int startInx = i*countNum; int endInx = startInx + countNum; if(i == threadNum-1) endInx = results.size(); exec.execute(new ThreadDataParser(results.subList(startInx, endInx),selectedCols,columns,dataType,selectedColsDatas)); } exec.shutdown(); // wait until sum-process is over try { exec.awaitTermination(5, TimeUnit.MINUTES); } catch (InterruptedException e) { logger.info("exec.awaitTermination(1, TimeUnit.HOURS) occurs error : " + e); } List<String> gByDatas = selectedColsDatas.get(0); List<String> valDatas = selectedColsDatas.get(1); logger.info("【BarChart】Parse group column="+gByCol+", size = " + gByDatas.size()); logger.info("【BarChart】Parse value column="+valCol+", size = " + valDatas.size()); //Use group column to group value column data HashMap<String,List<String>> groupDatas = new HashMap<String,List<String>>(); for(int k=0;k<gByDatas.size();k++) { String key = gByDatas.get(k); String value = valDatas.get(k); if(groupDatas.containsKey(key)) groupDatas.get(key).add(value); else { List<String> values = new ArrayList<String>(); values.add(value); groupDatas.put(key, values); } } // If the group over MAX_GROUP_SIZE, then return barChart with null category, tell user this column can not group data if(groupDatas.keySet().size()>MAX_GROUP_SIZE) { double[] datas = new double[groupDatas.keySet().size()]; BarChart barChart = new BarChart(null,datas); return barChart; }else{ HashMap<String,Double> statRets = new HashMap<String,Double>(); switch(aggCol) { case "average": computAvg(groupDatas,statRets); break; case "stand_deviation": computStand(groupDatas,statRets); break; case "count": computCount(groupDatas,statRets); break; case "minimum": computMin(groupDatas,statRets); break; case "maximum": computMax(groupDatas,statRets); break; } if(statRets.size() == 0) //If the data is not numerical, the return barChart with null values, tell user this column is not numerical { String[] categories = new String[MAX_GROUP_SIZE]; return new BarChart(categories,null); } String[] categories = new String[statRets.keySet().size()]; double[] values = new double[statRets.keySet().size()]; Iterator<Entry<String,Double>> dataIter = statRets.entrySet().iterator(); int k =0; while(dataIter.hasNext()) { Entry<String,Double> entry = dataIter.next(); categories[k] = entry.getKey(); if(logScale) values[k] = m3(Math.log(entry.getValue())); else values[k] = entry.getValue(); k++; } BarChart barChart = new BarChart(categories,values); return barChart; } } /** * Compute data average * * @param groupDatas group list datas * @param statRets group average values */ private void computAvg(HashMap<String,List<String>> groupDatas,HashMap<String,Double> statRets) { Iterator<Entry<String,List<String>>> dataIter = groupDatas.entrySet().iterator(); while(dataIter.hasNext()) { Entry<String,List<String>> entry = dataIter.next(); String key = entry.getKey(); List<String> datas = entry.getValue(); double sum = 0; int count = 0; for(String data : datas) { if(data.equals("")) continue; if(DataTools.isNumeric(data)) { count = count +1; sum = sum + Double.valueOf(data); }else{ // As long as one is not numeric, it returns null statRets = new HashMap<String,Double>(); return; } } if(count != 0) statRets.put(key, sum/count); } } /** * Compute standard deviation * * @param groupDatas group list datas * @param statRets group standard deviation values */ private void computStand(HashMap<String,List<String>> groupDatas,HashMap<String,Double> statRets) { Iterator<Entry<String,List<String>>> dataIter = groupDatas.entrySet().iterator(); while(dataIter.hasNext()) { Entry<String,List<String>> entry = dataIter.next(); String key = entry.getKey(); List<String> datas = entry.getValue(); double sum = 0; int count = 0; for(String data : datas) { if(DataTools.isNumeric(data)) { count = count +1; sum = sum + Double.valueOf(data); }else{ // As long as one is not numeric, it returns null statRets = new HashMap<String,Double>(); return; } } if(count != 0) { double avg = sum/count; double stdSum = 0; for(String data: datas) { if(DataTools.isNumeric(data)) { double numData = Double.valueOf(data); stdSum = stdSum +Math.pow(numData-avg, 2); } } statRets.put(key, Math.sqrt(stdSum/count)); } } } /** * Compute data count * * @param groupDatas group list datas * @param statRets group count values */ private void computCount(HashMap<String,List<String>> groupDatas,HashMap<String,Double> statRets) { Iterator<Entry<String,List<String>>> dataIter = groupDatas.entrySet().iterator(); while(dataIter.hasNext()) { Entry<String,List<String>> entry = dataIter.next(); String key = entry.getKey(); List<String> datas = entry.getValue(); int count = 0; for(String data : datas) { if(DataTools.isNumeric(data)) { count = count +1; }else{ // As long as one is not numeric, it returns null statRets = new HashMap<String,Double>(); return; } } if(count != 0) statRets.put(key, Double.valueOf(count)); } } /** * Compute minimum value * * @param groupDatas group list datas * @param statRets group minimum values */ private void computMin(HashMap<String,List<String>> groupDatas,HashMap<String,Double> statRets) { Iterator<Entry<String,List<String>>> dataIter = groupDatas.entrySet().iterator(); while(dataIter.hasNext()) { Entry<String,List<String>> entry = dataIter.next(); String key = entry.getKey(); List<String> datas = entry.getValue(); double min = Double.MAX_VALUE ; int count = 0; for(String data : datas) { if(DataTools.isNumeric(data)) { if(Double.valueOf(data) < min) min = Double.valueOf(data); count = count +1; }else{ // As long as one is not numeric, it returns null statRets = new HashMap<String,Double>(); return; } } if(count != 0) statRets.put(key, min); } } /** * Compute maximal value * * @param groupDatas group list datas * @param statRets group maximal values */ private void computMax(HashMap<String,List<String>> groupDatas,HashMap<String,Double> statRets) { Iterator<Entry<String,List<String>>> dataIter = groupDatas.entrySet().iterator(); while(dataIter.hasNext()) { Entry<String,List<String>> entry = dataIter.next(); String key = entry.getKey(); List<String> datas = entry.getValue(); double max = Double.MIN_VALUE ; int count = 0; for(String data : datas) { if(DataTools.isNumeric(data)) { if(Double.valueOf(data) > max) max = Double.valueOf(data); count = count +1; }else{ // As long as one is not numeric, it returns null statRets = new HashMap<String,Double>(); return; } } if(count != 0) statRets.put(key, max); } } }
Java
UTF-8
5,684
1.765625
2
[ "MIT" ]
permissive
/******************************************************************************* Copyright © 2017 Sankine Corporation Inc. All rights reserved. Author: Hoang Van Que Email: quehvbg@gmail.com Phone : 0983.138.328 Description: Modifier : Version : 1.0.0.1 ********************************************************************************/ package sankine.marketing.entities; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Objects; import java.util.UUID; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Convert; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.Fetch; import org.hibernate.annotations.FetchMode; import sankine.plugin.base.SK_BaseEntity; import sankine.plugin.base.SK_UUIDAttributeConverter; @Entity @Table(name = "DIM_CAMPAIGN") public class SK_CampaignEntity extends SK_BaseEntity { @Id @Column(name = "ID") @Convert(converter = SK_UUIDAttributeConverter.class) private UUID campaignId; @Column(name = "CAMPAIGN_CODE") private String campaignCode; @Column(name = "CAMPAIGN_NAME") private String campaignName; @Column(name = "IS_ACTIVE") private boolean isActive; @Column(name = "IS_SHUTDOWN") private boolean isShutdown; @Column(name = "IS_TRACKING") private boolean isTracking; @Column(name = "MODIFIED_DATE") @Temporal(TemporalType.TIMESTAMP) private Date modifiedDate; @Column(name = "SPONSOR") private String sponsor; @Column(name = "DESCRIPTION") private String description; @Column(name = "VALUE_PROPOSITION") private String valueProposition; @Column(name = "GOAL_DESCRIPTION") private String goalDescription; @Column(name = "START_DATE") @Temporal(TemporalType.TIMESTAMP) private Date startDate; @Column(name = "END_DATE") @Temporal(TemporalType.TIMESTAMP) private Date endDate; public UUID getCampaignId() { return this.campaignId; } public void setCampaignId(UUID campaignId) { this.campaignId = campaignId; super.setId(campaignId); } public String getCampaignCode() { return campaignCode; } public void setCampaignCode(String campaignCode) { this.campaignCode = campaignCode; } public String getCampaignName() { return campaignName; } public void setCampaignName(String campaignName) { this.campaignName = campaignName; } public boolean getIsActive() { return isActive; } public void setIsActive(boolean isActive) { this.isActive = isActive; } public boolean getIsShutdown() { return isShutdown; } public void setIsShutdown(boolean isShutdown) { this.isShutdown = isShutdown; } public boolean getIsTracking() { return isTracking; } public void setIsTracking(boolean isTracking) { this.isTracking = isTracking; } public Date getModifiedDate() { return modifiedDate; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } public String getSponsor() { return sponsor; } public void setSponsor(String sponsor) { this.sponsor = sponsor; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getValueProposition() { return valueProposition; } public void setValueProposition(String valueProposition) { this.valueProposition = valueProposition; } public String getGoalDescription() { return goalDescription; } public void setGoalDescription(String goalDescription) { this.goalDescription = goalDescription; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } @OneToMany(mappedBy = "campaign", cascade = CascadeType.ALL, fetch = FetchType.EAGER) @Fetch(value = FetchMode.SUBSELECT) private List<SK_CampaignStrategyEntity> listStrategy = new ArrayList<>(); public List<SK_CampaignStrategyEntity> getListStrategy() { return listStrategy; } public void setListStrategy(List<SK_CampaignStrategyEntity> listStrategy) { this.listStrategy = listStrategy; } // @OneToMany(mappedBy = "campaign", cascade = CascadeType.ALL, fetch = FetchType.EAGER) // @Fetch(value = FetchMode.SUBSELECT) // private List<SK_EmailReportDetailsEntity> listTracking = new ArrayList<>(); // // public List<SK_EmailReportDetailsEntity> getListTracking() { // return listTracking; // } // // public void setListTracking(List<SK_EmailReportDetailsEntity> listTracking) { // this.listTracking = listTracking; // } public SK_CampaignEntity() { super(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; SK_CampaignEntity identity = (SK_CampaignEntity) obj; return Objects.equals(campaignId, identity.campaignId); } @Override public int hashCode() { return Objects.hash(campaignId); } @Override public String toString() { return this.getCampaignName(); } @Override public boolean isGuidEmpty() { if(this.campaignId == null){ return true; } return this.campaignId.equals(new UUID( 0L , 0L )); } }
Swift
UTF-8
4,573
2.734375
3
[]
no_license
import Foundation func so3FromTwoVecN(a:Vector3d, _ b:Vector3d, inout result:Matrix3x3d) { var so3FromTwoVecNN:Vector3d = Vector3d() Vector3d.cross(a, b, result: &so3FromTwoVecNN) if so3FromTwoVecNN.length() == 0.0 { let dot:Double = Vector3d.dot(a, b) if ( dot >= 0.0 ) { result.identity() } else { var so3FromTwoVecNRotationAxis:Vector3d = Vector3d() Vector3d.ortho(a, result: &so3FromTwoVecNRotationAxis) rotationPiAboutAxis(so3FromTwoVecNRotationAxis, result: &result) } return } let so3FromTwoVecNA = Vector3d(a) let so3FromTwoVecNB = Vector3d(b) so3FromTwoVecNN.normalize() so3FromTwoVecNA.normalize() so3FromTwoVecNB.normalize() var tempVector = Vector3d() Vector3d.cross(so3FromTwoVecNN, so3FromTwoVecNA, result: &tempVector) let r1 = Matrix3x3d() r1.setColumn(0, so3FromTwoVecNA) r1.setColumn(1, so3FromTwoVecNN) r1.setColumn(2, tempVector) let r2 = Matrix3x3d() Vector3d.cross(so3FromTwoVecNN, so3FromTwoVecNB, result: &tempVector) r2.setColumn(0, so3FromTwoVecNB) r2.setColumn(1, so3FromTwoVecNN) r2.setColumn(2, tempVector) r1.transpose() Matrix3x3d.mult(r2, r1, result: &result) } func rotationPiAboutAxis(v:Vector3d, inout result:Matrix3x3d) { let temp = Vector3d(v) temp.scale(M_PI/temp.length()) let kA:Double = 0.0 let kB:Double = 0.20264236728467558 rodriguesSo3Exp(temp, kA, kB, result: &result) } func rodriguesSo3Exp(w:Vector3d, _ kA:Double, _ kB:Double, inout result:Matrix3x3d) { let wx2 = w.x * w.x let wy2 = w.y * w.y let wz2 = w.z * w.z result.set(0, 0, 1.0 - kB * (wy2 + wz2)) result.set(1, 1, 1.0 - kB * (wx2 + wz2)) result.set(2, 2, 1.0 - kB * (wx2 + wy2)) var a:Double = kA * w.z var b:Double = kB * (w.x * w.y) result.set(0, 1, b - a) result.set(1, 0, b + a) a = kA * w.y b = kB * (w.x * w.z) result.set(0, 2, b + a) result.set(2, 0, b - a) a = kA * w.x b = kB * (w.y * w.z) result.set(1, 2, b - a) result.set(2, 1, b + a) } func so3FromMu(w:Vector3d, inout result:Matrix3x3d) { let thetaSq:Double = Vector3d.dot(w, w) let theta:Double = sqrt(thetaSq) var kA:Double = 0.0 var kB:Double = 0.0 if thetaSq < 1.0E-08 { kA = 1.0 - 0.16666667163372 * thetaSq kB = 0.5 } else { if thetaSq < 1.0E-06 { kB = 0.5 - 0.0416666679084301 * thetaSq kA = 1.0 - thetaSq * 0.16666667163372 * (1.0 - 0.16666667163372 * thetaSq) } else { let invTheta:Double = 1.0 / theta kA = sin(theta) * invTheta kB = (1.0 - cos(theta)) * (invTheta * invTheta) } } rodriguesSo3Exp(w, kA, kB, result: &result) } func muFromSO3(so3:Matrix3x3d, inout result:Vector3d) { let cosAngle = (so3.get(0, 0) + so3.get(1, 1) + so3.get(2, 2) - 1.0) * 0.5 result.set((so3.get(2, 1) - so3.get(1, 2)) / 2.0, (so3.get(0, 2) - so3.get(2, 0)) / 2.0, (so3.get(1, 0) - so3.get(0, 1)) / 2.0) let sinAngleAbs = result.length() if cosAngle > 0.7071067811865476 { if sinAngleAbs > 0.0 { result.scale(asin(sinAngleAbs) / sinAngleAbs) } } else if cosAngle > -0.7071067811865476 { let angle = acos(cosAngle) result.scale(angle / sinAngleAbs) } else { let angle = M_PI - asin(sinAngleAbs) let d0 = so3.get(0, 0) - cosAngle let d1 = so3.get(1, 1) - cosAngle let d2 = so3.get(2, 2) - cosAngle let r2 = Vector3d() if (d0 * d0 > d1 * d1) && (d0 * d0 > d2 * d2) { r2.set(d0, (so3.get(1, 0) + so3.get(0, 1)) / 2.0, (so3.get(0, 2) + so3.get(2, 0)) / 2.0) } else if d1 * d1 > d2 * d2 { r2.set((so3.get(1, 0) + so3.get(0, 1)) / 2.0, d1, (so3.get(2, 1) + so3.get(1, 2)) / 2.0) } else { r2.set((so3.get(0, 2) + so3.get(2, 0)) / 2.0, (so3.get(2, 1) + so3.get(1, 2)) / 2.0, d2) } if Vector3d.dot(r2, result) < 0.0 { r2.scale(-1.0) } r2.normalize() r2.scale(angle) result.set(r2) } }
Ruby
UTF-8
1,725
2.890625
3
[]
no_license
#!/usr/bin/env ruby #http://mtsmfm.github.io/2017/06/03/doukaku-e14.html #http://qiita.com/mtsmfm/items/89b6634f363bbf5b47f5 def parsefasta(f) arc={} seq=[] line=f.gets line.chomp! name=line[1..-1] while line=f.gets line.chomp! if line[0,1]=='>' arc[name]=seq seq=[] name=line[1..-1] else seq<<line.chars.to_a end end arc[name]=seq arc end #cf: https://github.com/cielavenir/codeiq_solutions/blob/master/thisweek_masuipeo2/tyama_codeiq3106.rb class Array def rotate180 self.reverse.map(&:reverse) end def rotate90 self.reverse.transpose end def rotate270 self.transpose.reverse end end A=[ [ # 反転 lambda{|a|a}, lambda{|a|a.map(&:reverse)}, ],[ # 回転 lambda{|a|a}, lambda{|a|a.rotate90}, lambda{|a|a.rotate180}, lambda{|a|a.rotate270}, ] ] T=parsefasta(DATA).values.to_a def solve(a) A[0].product(*A[1..-1]).each{|e| # 重複あるけど気にしないことにします… T.each{|b| c=e.reduce(b){|s,f|f.call(s)} (0..a.size-c.size).each{|sy| (0..a[0].size-c[0].size).each{|sx| h=Hash.new{|h,k|h[k]=[]} c.size.times{|y| c[0].size.times{|x| if c[y][x]!='*' h[c[y][x]]<<a[sy+y][sx+x] end } } if h.values.flatten.all?{|e|e>=0} return (h.values.find{|e|e.include?(0)}-[0])[0] end } } } } nil end while gets s=$_.chomp a=5.times.map{[-1]*5} s.chars.each.with_index{|c,i| y,x=(c.ord-97).divmod 5 a[y][x]=i } r=solve(a) puts r ? s[r] : :- STDOUT.flush end __END__ >1 1*** 2323 1*** >2 1*** 2323 *1** >3 1*** 2323 **1* >4 1*** 2323 ***1 >5 *1** 2323 *1** >6 *1** 2323 **1* >7 21** *323 *1** >8 21** *323 **1* >9 21** *32* **13 >10 21** *323 ***1 >11 121** **323
TypeScript
UTF-8
523
2.6875
3
[]
no_license
import {Activity} from "../../shared/activity/activity"; export class TimedActivity { restPeriodInSecs: number; workPeriodInSecs: number; activity: Activity; repeat: number; constructor(restPeriodInSecs: number, workPeriodInSecs: number, activity: Activity, repeat: number ) { this.activity = activity; this.workPeriodInSecs = workPeriodInSecs; this.restPeriodInSecs = restPeriodInSecs; this.repeat = repeat; } }
Java
UTF-8
4,707
2.546875
3
[ "Apache-2.0" ]
permissive
package com.paddy.mynotes.data; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class NotesDataManager extends SQLiteOpenHelper { private static final String TAG = "NotesDataManager"; private static final int VERSION = 1; private static final String DB_NAME = "notes.db"; private static final String TABLE_NOTELIST = "notelist"; public static final String SQL_CREATE_TABLE_NOTELIST = "create table " + TABLE_NOTELIST + "(_id Integer primary key autoincrement, parent_id Integer,type Integer, bg_color_id Integer," + "content text,created_date Integer,modified_date Integer)"; private static final String[] COLUMNS_NOTELIST = { "_id", "parent_id", "type", "bg_color_id", "content", "created_date", "modified_date" }; private static NotesDataManager mNotesDataManager; public NotesDataManager(Context context) { super(context, DB_NAME, null, VERSION); } public static NotesDataManager getInstance(Context context) { if (mNotesDataManager == null) { mNotesDataManager = new NotesDataManager(context); } return mNotesDataManager; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_TABLE_NOTELIST); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } public long insertNote(Note note) { ContentValues cv = new ContentValues(); cv.put("parent_id", String.valueOf(note.getParent_id())); cv.put("type", String.valueOf(note.getType())); cv.put("bg_color_id", String.valueOf(note.getBg_color_id())); cv.put("content", note.getContent()); cv.put("created_date", note.getCreated_date()); cv.put("modified_date", note.getModified_date()); return this.getWritableDatabase().insert(TABLE_NOTELIST, null, cv); } public long deleteNote(Note note) { String whereClause = "_id=?"; String[] whereArgs = { String.valueOf(note.get_id()) }; return this.getWritableDatabase().delete(TABLE_NOTELIST, whereClause, whereArgs);// 执行删除 } public long updateNote(Note note) { ContentValues cv = new ContentValues(); cv.put("parent_id", String.valueOf(note.getParent_id())); cv.put("type", String.valueOf(note.getType())); cv.put("bg_color_id", String.valueOf(note.getBg_color_id())); cv.put("content", note.getContent()); cv.put("created_date", note.getCreated_date()); cv.put("modified_date", note.getModified_date()); String whereClause = "_id=?"; String[] whereArgs = { String.valueOf(note.get_id()) }; return this.getWritableDatabase().update(TABLE_NOTELIST, cv, whereClause, whereArgs); } public Note queryNoteById(int noteId) { String selection = "_id=?"; String[] selectionArgs = { String.valueOf(noteId) }; Cursor cursor = this.getWritableDatabase().query(TABLE_NOTELIST, COLUMNS_NOTELIST, selection, selectionArgs, null, null, null); Note note = null; if (cursor.moveToFirst()) { note = getNoteFromCursor(cursor); } return note; } public Note getNoteFromCursor(Cursor cursor) { int _id = cursor.getInt(cursor.getColumnIndex("_id")); int parent_id = cursor.getInt(cursor.getColumnIndex("parent_id")); int type = cursor.getInt(cursor.getColumnIndex("type")); int bg_color_id = cursor.getInt(cursor.getColumnIndex("bg_color_id")); String content = cursor.getString(cursor.getColumnIndex("content")); long created_date = cursor.getLong(cursor .getColumnIndex("created_date")); long modified_date = cursor.getLong(cursor .getColumnIndex("modified_date")); return new Note(_id, parent_id, type, bg_color_id, content, created_date, modified_date); } public Cursor queryNoteListByFolderId(int folderId) { String selection = "parent_id=?"; String[] selectionArgs = { String.valueOf(folderId) }; String orderBy = "type desc, modified_date desc"; Cursor cursor = this.getWritableDatabase() .query(TABLE_NOTELIST, COLUMNS_NOTELIST, selection, selectionArgs, null, null, orderBy); Log.d(TAG, "queryNoteListByFolderId folderId:" + folderId + " rows:" + cursor.getCount()); return cursor; } public boolean isFolderNameExist(int parentFolderId, String folderName) { String[] columns = { "count(*)" }; String selection = "type=1 and parent_id=? and content=?"; String[] selectionArgs = { String.valueOf(parentFolderId), folderName.trim() }; Cursor cursor = this.getWritableDatabase().query(TABLE_NOTELIST, columns, selection, selectionArgs, null, null, null); boolean isExist = false; if (cursor.moveToFirst()) { isExist = (cursor.getInt(0) > 0); } return isExist; } }
C++
UTF-8
1,292
3.03125
3
[]
no_license
#include<cstdio> #include<cmath> using namespace std; #define MAX_TAG 64 char tag[MAX_TAG]; const double pi = acos(-1.0); inline double longitude( double x ) { return x*pi/180; } inline double latitude( double x ) { return log(tan(pi/4+(x*pi/360))); } const double left = longitude(-180); const double right = longitude(180); const double up = latitude(85); const double down = latitude(-85); void map(double x,double y,int level,double left, double right,double up,double down) { int tag_idx = 1; tag[0] = 't'; double midx,midy; x = longitude(x); y = latitude(y); while( level != 0 ) { midx = (left+right)/2; midy = (up+down)/2; if( x > midx && y > midy ) { left = midx; down = midy; tag[tag_idx++] = 'r'; } else if( x > midx && y < midy ) { left = midx; up = midy; tag[tag_idx++] = 's'; } else if( x < midx && y > midy ) { right = midx; down = midy; tag[tag_idx++] = 'q'; } else { right = midx; up = midy; tag[tag_idx++] = 't'; } level -= 1; } tag[tag_idx] = 0; } int main() { int level; double x,y; while( scanf("%lf%lf%d",&x,&y,&level) != -1 ) { map(x,y,level,left,right,up,down); printf("%s\n",tag); } return 0; }
C#
UTF-8
1,278
3.234375
3
[ "MIT" ]
permissive
using System; namespace Firestorm.Data { public static class PluralConventionUtility { public static string GetTableName<T>() { return GetTableName(typeof(T)); } public static string GetTableName(Type entityType) { return Pluralize(entityType.Name); } public static string Pluralize(string singular) { const StringComparison comp = StringComparison.InvariantCultureIgnoreCase; if (singular.ToLower() == "person") return "People"; if (singular.ToLower() == "tooth") return "Teeth"; if (singular.EndsWith("y", comp)) return singular.Remove(singular.Length - 1, 1) + "ies"; if (singular.EndsWith("f", comp)) return singular.Remove(singular.Length - 1, 1) + "ves"; if (singular.EndsWith("fe", comp)) return singular.Remove(singular.Length - 2, 2) + "ves"; if (singular.EndsWith("s", comp) || singular.EndsWith("ch", comp) || singular.EndsWith("x", comp) || singular.EndsWith("z", comp) || singular.EndsWith("sh", comp)) return singular + "es"; return singular + "s"; } } }
Markdown
UTF-8
6,107
2.734375
3
[]
no_license
--- title: "关于“这是命,得认”" layout: "note" link: http://www.zhihu.com/question/24721077/answer/28778451 note_date: "2014-08-10" --- 工作好头大,再加上基本没人参加上次的“快速问答”,所以也一直懒得更新。这里先贴一个最近我在知乎上较多人支持的回答吧,触发下更新的开关。点击下方“<span style="color:blue;">阅读原文</span>”链接可跳转到知乎。 ## 提问 为什么有些人随着年龄增加,逐渐相信了「宿命」? 今年本命年,依然碌碌无为一事无成。家境不好。性格孤僻,然而在外也能敷衍迎合。应该说从高一下学期狂读史记和李太白全集(清王琦注)时开始有自我意识。至今已十年矣。读过不少书,有过许多愿望与追求,漂亮的女孩和向往的大学。然而皆以失败结束,或者说我真的没有勇气去追求。在北京求学,做过兼职,现已工作半年。见识了不少,经历了不少,越发相信了宿命的说法。想改变自己。正在看资治通鉴中华书局版竖排版,希望可以见古知今,解我心中困惑。感谢大家的回答。向来崇敬鲁迅先生,这个时代应该更好一些。 ## 回答 这东西我想得很清楚,“命”对我来说就是“一切不可把握或预测或影响的客观因素的总和”。 比如我出生在80年代中期,成长在一个普通人家,这就导致了除非我有奇遇(这也是“命”),否则我很难凭一己之力买房。假如可以早生个五年十年,凭我的努力和能力,我觉得三套房都已经有了。我在深圳认识很多人,都是因为来深圳早,买房早,现在车房齐全,一年随便拿个二三十万的工资,生活就能过的很舒服,幸福度很高。我可以赚得比他们多得多,但有什么用,缺少过去的积累,我照样付不起一套稍微满意一些的房子的首付。当然,还有比我命更差的,比如香港的普通老百姓,嗯…… 我也赶上过07~08年的金融危机,那时候我在创业,于是投资也没了,自然活不下去。那年的就业形势也很糟糕,公司都不设岗位不招人了,许多毕业生都找不到工作,找到工作工资也比较低。一年后经济复苏了,晚一年毕业,你可以很轻易的比干了一年的人工资还高。要知道公司是基本不会给你额外涨薪的,基数低,你就很难追。就算追上了,你付出的额外的努力就不是代价了吗?这也是命不好。 还有比如某一年微软谷歌扩招,于是那年毕业的人就可以轻松地加入大公司,甚至是总部。而当年我毕业的时候,Head Count用完以后,我作为实习生都没法转为FTE,最多只能当Vendor——我干得再好有什么用,比某些FTE更好有什么用,我大二就去微软一直实习到毕业又有什么用……于是我就去创业了,然后不久就遇到金融危机了。 近几年我算是运气稍微好一点了。当时从高大上的互联网行业,进了与之风格大相径庭的十八摸,在十八摸内部几乎没法升迁。所幸遇到了一个靠谱的甲方老板以及难得的好项目,正当要放弃之际,甲方老板说靠这项目怎能没你,于是我就为人所不齿的外包男,瞬间变成了高大上的投行男。 你说这一切都是我努力来的么?当然有我努力来的成分,我努力所以我水平高,但一个不可忽视的关键还是遇到了靠谱的老板,做上了靠谱的项目。我那些转甲方失败的前十八摸同事们,他们水平肯定比我差么(当然也说不定呢)?就肯定没我努力么(当然也说不定呢)?谁知道。当回头看时发现,自己的努力并非得到回报的充分条件,这事儿想想其实也挺悲哀的,因为这无法可靠重现。说不定三年后遇到个什么事情就失去了,回不来了——所以我现在基本没跳槽打算,因为好不容易来的运气,不想轻易作掉。 总之,个人的努力在这个客观世界面前是渺小的。俗话说得好,等你真正努力过就知道智商(或脸)有多重要了。当然,我并没有否定“努力”的重要性,我同样认为对于相同的客观条件来说,“努力”在一般情况下会比“不努力”会要来的好一些,当然假如你的命不好,那自然也说不准。 还有一种常见的说法是“机遇”,说没有命这回事,是努力和机遇的问题,努力了才能把握住机遇。我不认同这点。Head Count多出来的时候阿猫阿狗都能进微软去总部,这算什么机遇?这就是命。在互联网泡沫的年代,读个CS专业,随便混到毕业一个月赚当时三平方米房间,这算什么机遇?这就是命。有人买了彩票中了500万,这算什么机遇?这就是命。 我既然没有否定努力的价值,因此也不会认同“机遇”这种说法。 我经常说“这是命,得认”,于是总有人会跳出来附和我,还说什么命啊运啊风水啊积德啊什么的——我最烦这种人,根本不知道我说的“命”是什么,他们只不过找一个说辞来附和自己罢了。对我来说,所有一切不可控制影响预测的都统称为“命”,不会分更细。而且所谓“转运”,“看风水”,“算星盘”之类的说法,就意味着这些东西是可以改变,可以影响的,可以预测的,这显然也不是我说的“命”。 所以我的确信“命”,但我信的不是很多人口中的“命”,更不信“运”啊“积德”啊“风水”什么的。 ## 广告 Surface Pro 3即将在香港正式发布,现已接受预定。这东西同事一个月前已经在美国买回来了,我尝试了一下,喜欢地不得了,必须做一次广告。本次封面是卫讯官网的广告,目前可以在那里订货,8月28日发货,八月底之前原价代购,需要的同学可以在新浪微博上私信我:<span style="color:red;">@老赵</span>。
Java
UTF-8
9,924
1.796875
2
[]
no_license
package com.example.dubstep; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.app.ProgressDialog; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.dubstep.ViewHolder.OtpActivity; import com.google.android.gms.auth.api.signin.GoogleSignIn; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInClient; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.ApiException; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.android.material.snackbar.Snackbar; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.auth.GoogleAuthProvider; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; public class LoginActivity extends AppCompatActivity { EditText txtemail, txtpassword; Button btn_login; private FirebaseAuth firebaseAuth; ProgressDialog progressDialog; private SignInButton GoogleSignInButton; private GoogleSignInClient mGoogleSignInClient; private final static int RC_SIGN_IN = 1; private FirebaseAuth.AuthStateListener mAuthStateListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); txtemail = (EditText) findViewById(R.id.EmailLoginEditText); txtpassword = (EditText) findViewById(R.id.PasswordLoginEditText); btn_login = (Button) findViewById(R.id.LoginButton); GoogleSignInButton = (SignInButton) findViewById(R.id.GoogleSignInButton); firebaseAuth = FirebaseAuth.getInstance(); GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build(); mGoogleSignInClient = GoogleSignIn.getClient(this, gso); GoogleSignInButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { GSignIn(); } }); mAuthStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser mFireBaseUser = firebaseAuth.getCurrentUser(); if (mFireBaseUser != null){ //FirebaseAuth.getInstance().signOut(); //mGoogleSignInClient.signOut(); //Toast.makeText(LoginActivity.this, "You are logged in",Toast.LENGTH_LONG).show(); } else { //Toast.makeText(LoginActivity.this, "Please Log in",Toast.LENGTH_LONG).show(); } } }; btn_login.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { progressDialog = new ProgressDialog(LoginActivity.this); progressDialog.show(); progressDialog.setContentView(R.layout.progress_dialog); progressDialog.getWindow().setBackgroundDrawableResource( android.R.color.transparent ); String email = txtemail.getText().toString().trim(); String password = txtpassword.getText().toString().trim(); if (TextUtils.isEmpty(email)) { Toast.makeText(LoginActivity.this, "Please Enter Email",Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); return; } if (TextUtils.isEmpty(password)) { Toast.makeText(LoginActivity.this, "Please Enter Password",Toast.LENGTH_SHORT).show(); progressDialog.dismiss(); return; } firebaseAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { FirebaseDatabase.getInstance().getReference("user") .child(FirebaseAuth.getInstance().getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(@NonNull DataSnapshot dataSnapshot) { String Role = dataSnapshot.child("Role").getValue().toString(); if (Role.equals("Customer")){ progressDialog.dismiss(); startActivity(new Intent(LoginActivity.this, MainActivity.class)); finish(); } else if (Role.equals("Rider")) { progressDialog.dismiss(); startActivity(new Intent(LoginActivity.this, RiderMainActivity.class)); finish(); } } @Override public void onCancelled(@NonNull DatabaseError databaseError) { progressDialog.dismiss(); Toast.makeText(LoginActivity.this, "Error fetching Rider or Customer from database",Toast.LENGTH_SHORT).show(); } }); } else { progressDialog.dismiss(); Toast.makeText(LoginActivity.this, "Login Failed or User not Available",Toast.LENGTH_SHORT).show(); } } }); } }); } @Override protected void onStart() { super.onStart(); firebaseAuth.addAuthStateListener(mAuthStateListener); FirebaseUser user = firebaseAuth.getCurrentUser(); } public void btn_register(View view) { startActivity(new Intent(getApplicationContext(), SignUpActivity.class)); } public void GSignIn(){ Intent signInIntent = mGoogleSignInClient.getSignInIntent(); startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...); if (requestCode == RC_SIGN_IN) { Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data); try { // Google Sign In was successful, authenticate with Firebase GoogleSignInAccount account = task.getResult(ApiException.class); firebaseAuthWithGoogle(account); } catch (ApiException e) { // Google Sign In failed, update UI appropriately Toast.makeText(LoginActivity.this, "Login Failed or User not Available",Toast.LENGTH_SHORT).show(); } } } private void firebaseAuthWithGoogle(GoogleSignInAccount acct) { AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null); firebaseAuth.signInWithCredential(credential) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { // Sign in success, update UI with the signed-in user's information FirebaseUser user = firebaseAuth.getCurrentUser(); boolean newuser = task.getResult().getAdditionalUserInfo().isNewUser(); if (newuser) { startActivity(new Intent(LoginActivity.this, SignUpActivity.class)); } else { startActivity(new Intent(LoginActivity.this, MainActivity.class)); //change later based on rider/customer } } else { // If sign in fails, display a message to the user. Toast.makeText(LoginActivity.this, "Login Failed or User not Available",Toast.LENGTH_SHORT).show(); } } }); } }
Java
UTF-8
1,747
2.46875
2
[]
no_license
package com.refactorlabs.cs378.assign3; import junit.framework.Assert; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.mapreduce.MapDriver; import org.apache.hadoop.mrunit.mapreduce.ReduceDriver; import org.junit.Before; import org.junit.Test; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Unit test for the WordCount map-reduce program. * * @author Jorge Zapien-Diaz */ public class InvertedIndexTest { MapDriver<LongWritable, Text, Text, Text> mapDriver; ReduceDriver<Text, Text, Text, Text> reduceDriver; @Before public void setup() { InvertedIndex.MapClass mapper = new InvertedIndex.MapClass(); InvertedIndex.ReduceClass reducer = new InvertedIndex.ReduceClass(); mapDriver = MapDriver.newMapDriver(mapper); reduceDriver = ReduceDriver.newReduceDriver(reducer); } @Test public void testReduceClass() { Text key = new Text("From:jane.tholt@enron.com"); Text[] values = new Text[]{new Text("<23426663.1075857497542.JavaMail.evans@thyme>"),new Text("<23426663.1075857497542.JavaMail.evans@thyme>"),new Text("<14443098.1075857499469.JavaMail.evans@thyme>"),new Text("<6571521.1075857500090.JavaMail.evans@thyme>")}; List<Text> valueList = new ArrayList<Text>(); for (Text val: values) valueList.add(val); Text out = new Text("<23426663.1075857497542.JavaMail.evans@thyme>,<23426663.1075857497542.JavaMail.evans@thyme>,<14443098.1075857499469.JavaMail.evans@thyme>,<6571521.1075857500090.JavaMail.evans@thyme>"); reduceDriver.withInput(new Text("From:jane.tholt@enron.com"), valueList); reduceDriver.withOutput(new Text("From:jane.tholt@enron.com"), out); try { reduceDriver.runTest(); } catch (IOException ioe) { Assert.fail("IOException from mapper: " + ioe.getMessage()); } } }
Markdown
UTF-8
17,883
2.625
3
[]
no_license
--- templateKey: blog-post title: Best Belt Sanders – Top 9 List with Buyers Guide slug: best-belt-sanders seoTitle: 9 Best Belt Sanders [Buyers Guide & Reviews] seoDescription: This article is about the best belt sanders 2021. In this article, I will explain to you the best belt sanders 2021. I will explain the features... featuredimage: /img/best-belt-sanders.webp hidefeaturedimage: true date: 2021-04-08T16:47:14.523Z moddate: 2021-04-08T16:47:14.571Z tableofcontent: true author: 3c88ffc6-7b6b-4bd7-86f9-098daf42c223 category: 2dd29605-5541-46cc-950f-6059c305db0a rating: false rcount: 0 rvalue: 5 beforebody: >- Belt sanders have now become an essential part of any toolkit or workshop. These tools are used to perform a wide variety of applications. They can be used for smoothing, shaping, sanding, and trimming purposes. Belt sanders come up in different sizes and shapes. You have to choose the right one according to your task. Some sanders are versatile and can be used for many applications as the market is flooded with a range of belt sanders, so it becomes difficult for anyone to choose the right brand. We have come up with a solution to this problem. This article list of the top 9 **best belt sanders 2021** is provided, which are available at a reasonable price in the market.[](<>) ## Top 9 List - Best Belt Sanders. table: table: true products: - btnText: View on Amazon body: >- Its unique and incredible features make it the **best belt sander** among all. It shows exceptional performance, and it is effortless to use. It is ideal for carpenters, contractors, furniture makers, and woodworkers. It produces less noise as compared to its competitors. And hence it is considered as the quietest among all sanders. Makita manufactures it, and it comprises the weight of 13 pounds. It is equipped with an 11 AMP powerful motor. It has a unique and attractive design and is available in teal color in the market. It is powered by corded electricity, and it requires 240 volts to operate. It produces a noise of only 84dB. It has 4 inches wide belt with 1640 feet per minute fast speed. It has a firm grip that makes it easy to handle. 360-degree dust bag swivels make the operation more convenient. When you open the box, you will find one Makita belt sander and dust bag. It is the most versatile tool for sanding, 0and. It is highly recommended for a high-quality and professional sanding finish. pros: - Large front grip - Very powerful and Durable - It gives fast and quick results - "Provided with dust bag " - Suitable for shops, homes, and offices cons: - "Little bit heavy " - Don’t have variable speed control. name: Makita 9403 Belt Sander link: https://amzn.to/3qUhHT3 image: /img/makita-9403.webp - btnText: View on Amazon name: Astro Pneumatic Tool 3037 Air Belt Sander link: https://amzn.to/3uA5IMr body: >- It is the **best sanding tool for metal preparation and spot welds**. It can efficiently perform all your sanding tasks within a limited time and at cheaper rates. Its adjustable arm angle makes it very easy to use. Let’s have a look at its features. It is manufactured by Astro Pneumatic Tool company, and it weighs 2.2 pounds. It has a length of ½ inches to 18 inches. Astro Pneumatic Tools is a renowned company and has always provided high-quality and easy-to-use tools to their customers. Their products are reliable to use. This belt sander is also composed of strong aluminum material. It is designed so that it can be easily fit all kinds of belts styles and brands. It provides 16000 rotations per minute. These rotations adjustments are present on the back of the handle. It is fully equipped with the latest technology and is designed considering the ease of users. Its variable speed control feature allows you to control the speed easily. It does not require any battery to operate. It is also provided with increased space for thicker belts. Its non-slip and robust grip makes it very comfortable to use. Its 0.5HP motor makes it perfect for spot weld removal tasks. pros: - "Quick results " - Cheap rates - Suitable to use in tight spaces - Produces less noise - "More pulling space " - Variable speed control - Easily adjustable speed cons: - No cushioning or cover on the wheel image: /img/astro-pneumatic-tool-3037.webp - btnText: View on Amazon link: https://amzn.to/3kkB98Y name: Black + Decker Belt Sander body: >- This Black+ Decker **belt sander is provided with a cloth dust bag.** Its 7 AMP motor shows robust performance and is suitable for variable types of sanding tasks. It possesses a retractable hook and angled belt design that makes it very convenient to use.  This small machine is a fantastic tool for sanding, not suitable for large tasks. Black+Decker is a world-famous provider of engineering and fastening products. It has always provided reliable and durable products. It weighs 6.5 pounds and is available in black color and black finish in the market. It is composed of durable and sturdy material.It doesn’t require any battery to operate. It needs 120 volts to perform its function. Its lightweight and compact design make it easy to transport from one place to another. Its power source is corded electric. Its amperage capacity is 7 AMP. Its innovative design makes it accessible to tight spaces. This tool is perfect for those who want to make their homes beautiful. Its flush body design also makes it suitable for vertical surfaces. It is also equipped with a dust collector. By using this, you can make your work area clean. It is provided with a two years warranty. In the box, you will find a black+decker sander, dust bag, and user manual. It is not designed for very high-level tasks. pros: - "Lightweight and compact " - Suitable for tight spaces - Affordable price - "Front roller feature " cons: - Needed periodic adjustments image: /img/black-decker.webp - btnText: View on Amazon name: Ridgid 18 V GEN5X Cordless Brushless Belt Sander body: >- This is one of the best belt sanders provided with a dustbag and all other accessories. This brushless tool can easily handle challenging tasks and shows excellent performance. This tool is a perfect addition to performing all kinds of punch list tasks. Its tool-free belt release makes it very easy to use. You can change the belts easily. It comprises a weight of 6.3 lb and is composed of durable material. Its automatic belt tracking system keeps the belt in a balanced position. Its lever is crafted of durable metal. It features an ergonomic and compact design. Its soft and robust grip handle makes it comfortable to use. The grip is over-molded with a soft material. You can adjust the handle into three positions.  Its variable speed dial makes it easy to switch between multiple speed modes. If we talk about its performance, then this tool shows excellent performance. By using its 80 grit belt, it can easily clean woods. This belt sander is suitable to use in smaller spaces. It is provided with a dust collection system that makes your working area clean. It claims to collect up to 90% of the dust. With its 5 AMP battery, it provides a runtime of 13 minutes and 40 seconds. It is supplied with three years warranty. pros: - "Affordable price " - "Automatic belt tracking " - Adjustable three handle positions. - "Used for a variety of applications " - Integrated dust bag - "The tool-free belt release system " cons: - No major drawbacks image: /img/ridgid-18-v-gen5x.webp link: https://amzn.to/3dMJgtu - btnText: View on Amazon name: Ryobi BE 319 6 Amp belt sander body: >- It is the **best belt sander to use in homes and shops. I**t is provided with all the accessories required to perform the function efficiently. It is suitable for 0 ranger functions, and it is also ideal for tight spaces. Its powerful motor shows excellent performance. Its lightweight and compact size make it easy to handle.  Let’s have a look at its incredible features and specifications. Ryobi manufactures it, and it comprises the weight of 6.18 pounds. It is 3″x8″ in length that makes it perfect to use in any tight space. It is composed of durable and sturdy material. It is available in green color in the market. Its power source is corded electric, and it does not require any battery to operate. Its amperage capacity is 6 Amp. It has an over-molded soft grip that enables you to handle it properly. It is equipped with a tool-less belt-changing system. In the box, you will find the following things.  Ryobi belt sander, dust bag, user manual, and sanding belt. link: https://amzn.to/2ZN0IWO pros: - "Powerful 6Amp motor " - Lightweight and compact - Suitable for heavy-duty tasks - User friendly - "Soft rubberized grip " cons: - No such cons image: /img/ryobi-be-319.webp - btnText: View on Amazon name: TACKLIFE 3 X 18-inch belt sander link: https://amzn.to/3st4zo4 body: >- This belt sander is suitable to perform heavy-duty tasks and is available at reasonable rates in the market. It can be the best gift for your loved ones. It can easily tackle both are easy and tough jobs. Its 5 Amp motor shows excellent performance. Its 13 pieces sanding belt is widely used in a range of applications. Let’s talk about its features and specifications. It weighs 7.56 pounds and is manufactured by tackle. It is composed of durable plastic material. It is available in back and orange color in the market. It requires 120 volts to operate, and it is powered by corded electricity. It requires 600-watt power to operate. It has two screw clamps that make the sanding easy. It is equipped with 13 pieces sanding belt that enhances the efficiency of your work. It features a perfect dust collection system that helps you to clean the working area. It can easily collect 90% of the dust. Its over-molded soft grip helps to reduce user fatigue.  It is provided with a variable speed knob with six dials by which you can easily adjust the speed. It is also equipped with a lock on the button that makes it convenient to use. pros: - "Lightweight and compact " - "Affordable price " - "Very easy to use " - "Variable speed knob with six dials " - "13 PCS sanding belt " - 5Amp motor - "Lock-on button " cons: - Weak belt image: /img/tacklife-3-x.webp - btnText: View on Amazon name: Skil 7510-01 Belt Sander link: https://amzn.to/303FtjL body: >- This innovative belt sander is perfect for both professionals and beginners. After using this product, you will love its unique features and will shop again and again. Its small size makes it perfect for medium-sized jobs. Let’s talk about its incredible features. It weighs 6.75 pounds. It is available in black color. Its power source is corded electric, and it requires 120 volts to operate. It does not require any battery to work. It is equipped with microfiltration technology that traps and manages wood dust particles. Its pressure control technology can easily control pressure in sanding pads and helps to provide an optimal finish. Its 6 Amp can be used for a variety of wood surfaces.  It features an automatic belt alignment system that keeps the belt well centered and well balanced. Its lock on the button makes it user-friendly and helps to reduce finger fatigue. pros: - "Lock-on button " - Lightweight and durable - Pressure control technology - The automatic belt alignment system - User-friendly cons: - Short lifespan image: /img/skil-7510-01.webp - btnText: View on Amazon name: Metabo HPT SB 8V2 belt sander body: >- It is the **best handheld and powerful belt Sander** for both professionals and beginners. Its powerful motor shows robust performance. It is equipped with exciting features that will amaze you, and you will buy it. It can do sandling on all kinds of surfaces. It is user-friendly, and it is very convenient to use. It weighs 9.5 pounds. It is manufactured by koki holdings America limited. It is a well-known company in America and has manufactured several user-friendly products. All their products are reliable and durable. It doesn’t require any battery to operate. Its lightweight and compact size make it easy to carry from one place to another. It has a 9 Amp motor, and it is provided with variable speed control to control the belt skillfully’s speed. It is suitable to use with any metallic or wooden surface. It is provided with a 5-year warranty. Its flesh surface design helps in quick sanding. It is equipped with a tracking window by which you can quickly check the sanding surface during usage. link: https://amzn.to/2ZR8cYQ pros: - Variable speed Sander - "Lightweight and compact " - Powerful motor Show excellent performance - "5-year warranty " - "Easy to use " cons: - No major drawbacks image: /img/metabo-hpt.webp - btnText: View on Amazon name: Genesis GBS 321 A variable speed belt sander body: >- It is the **best cheap belt Sander** equipped with numerous exciting features. It is suitable for aggressive applications like evening up floors. This variable speed Sander has upgraded its ergonomic design. This sturdy and durable material comes with three years warranty. It has a lot of new fancy functions. Let’s talk about its exciting features and specifications. It weighs 9.05 pounds, and it is light in weight as compared to many other belt sanders. Artisans manufacture it. Craftsman is a well-known company worldwide and has prepared many electronic products that are reliable and safe to use. This belt Sander is one of these fantastic tools. Its amperage capacity is 8 Amp. A standard dust box is provided with the device to help you clean your working environment efficiently. It has a variable speed design by which you can easily control your work’s speed and accuracy. This tool can work on any type of sand material.  Its LED pressure control indicator will enhance your work efficiency. It is also equipped with LED lights that will help you to work better in dark conditions. Its vibrant shield grip design will make it comfortable to use. Thus, this tool is user-friendly and is very handy to use. link: https://amzn.to/3sxaNDD pros: - "Built-in LED lights " - "LED pressure control indicator " - "Highly efficient motor " - "Comfortable grip design " - "Affordable price " - Standard dust box with microfine filters cons: - No major drawbacks image: /img/genesis-gbs-321.webp afterbody: >- ## Final Verdict  After reviewing each product, I concluded that the Victorinox Swiss army multi-tool is ideal among the **top best multi-tools for home users and professionals**. This Victorinox tool is composed of high-quality material and is provided with 27 different tools. It provides a lifetime warranty. Similarly, SOG power liter is perfect for home-usage. However, you can choose the best device according to your requirements, budget, and needs. ## Buying Guide Before buying any belt sander, you must take the following things in concentration. ### Size Every product is provided with different sizes and shapes. The size of a belt sander depends on the task you want to perform. If you are professional, you should go for heavy and large sizes but if you are a home user, then go for small and lightweight sizes. ### Grip and Comfort Choose the center which is comfortable to use, and its grip is easy to handle. Usually, these devices come up with soft rubberized grips. ### Motor capacity It is a significant factor to consider while buying a belt Sander. Usually, a 9 Amp motor is preferable over a 3 Amp motor. So, you should go for the powerful engine. sidebar: stoc: - level: true name: Top 9 List - Best Belt Sanders. - level: true name: Makita 9403 Belt Sander - level: true name: Astro Pneumatic Tool 3037 Air Belt Sander - level: true name: Black + Decker Belt Sander - level: true name: Ridgid 18 V GEN5X Cordless Brushless Belt Sander - level: true name: Ryobi BE 319 6 Amp belt sander - level: true name: TACKLIFE 3 X 18-inch belt sander - level: true name: Skil 7510-01 Belt Sander - level: true name: Metabo HPT SB 8V2 belt sander - level: true name: Genesis GBS 321 A variable speed belt sander - level: true name: "Final Verdict " - level: true name: Buying Guide stitle: Editor's Choice atext: Makita 9403 alink: https://amzn.to/3qUhHT3 image: /img/makita-9403.webp faq: - ques: Should I buy a belt, Sander? ans: You should go for belt Sander. These tools have now become the necessity of every workshop and every carpenter or plumber. These tools are essential to perform any wood finishing your sanding jobs. - ques: Should I Which is the best belt Sander for wood? ans: Makita 9403 belt sander is the best belt sander overall. DEWALT sanders are the best value tools. ---
Java
UTF-8
1,353
3.265625
3
[]
no_license
package World; import java.util.ArrayList; import Player.Player; public class Continent { private ArrayList<Country> countries; private int bonus; private String color; private String name; private World world; public Continent(String color, String name, int bonus, World world){ this.countries = new ArrayList<Country>(); this.bonus = bonus; this.color = color; this.name = name; this.world = world; } public String toString() { String retString = ""; for(Country c: this.countries) { retString += c.toString(); } return retString; } public void addCountry(Country c){ c.setContinent(this); countries.add(c); } public void removeCountry(Country c){ for(Country A : countries){ if(A.equals(c)){ countries.remove(A); break; } } } public ArrayList<Country> getCountries(){ return countries; } public void setBonus(int bonus){ this.bonus = bonus; } public int getBonus(){ return bonus; } public void setColor(String col){ color = col; } public String getColor(){ return color; } public void setName(String name){ this.name = name; } public String getName(){ return name; } public void setWorld(World w){ world = w; } public World getWorld(){ return world; } /*public Player checkIfRuled(){ Player placeHolder = new Player(); return placeHolder; }*/ }
Ruby
UTF-8
1,431
3.109375
3
[]
no_license
require 'pg' require_relative '../db/runner' require_relative '../models/event' class Discipline attr_reader :id, :name def initialize(options) @id = options['id'].to_i @name = options['name'] end def save() sql = "INSERT INTO disciplines (name) VALUES ('#{@name}') RETURNING *" discipline_data = SqlRunner.run(sql) @id = discipline_data.first['id'].to_i end def events() sql = "SELECT * FROM events WHERE discipline_id = #{@id}" events_data = SqlRunner.run(sql) events = events_data.map {|event_data| Event.new(event_data)} return events end def self.all(query = "") query = query.to_s sql = "SELECT * FROM disciplines" sql = sql + " WHERE name LIKE '<%#{query}%>'" unless query.empty? disciplines_data = SqlRunner.run(sql) return disciplines_data.map {|discipline_data| Discipline.new(discipline_data)} end def self.find(id) sql = "SELECT * FROM disciplines WHERE id = #{id}" found_discipline = SqlRunner.run(sql) return Discipline.new(found_discipline.first) end def self.update(options) sql = "UPDATE disciplines SET name = '#{options['name']}' WHERE id = #{options['id']} RETURNING *" SqlRunner.run(sql).first end def self.destroy(id) sql = "DELETE FROM disciplines WHERE id = #{id}" SqlRunner.run(sql) end def self.delete_all() sql = "DELETE FROM disciplines" SqlRunner.run(sql) end end
Python
UTF-8
2,385
4.59375
5
[]
no_license
#THIS PRACTICE IS ABOUT CONDITIONAL STATEMENTS #Simple if statement age = 20 if age >= 18: print('Your age is',age) print('adult') #If and else statements age = 3 if age >= 18: print("your age is", age) print ('adult') else: print("Your age is", age) print("teenager") #Else if statements age = 3 print('Your age is:', age) if age >= 18: print('adult') elif age >= 6: print('teenager') else: print('kid') #Nested condiitonals x = 5 y = 10 print("The values specified are: X =", x, "and Y =", y) if x == y: print('x and y are equal') else: if x < y: print("x is less than y") else: print('x is greater than y') #Exercise 1 #Problem 1: BMI Calculator (Metric system). Weight in kilograms and height in meters systemused = str(input("What system would you like to use: 'imperial' or 'metric'")) if systemused == "imperial": weight = float(input("Enter your weight in pounds")) height = float(input("Enter your height in inches")) bmi = 703 * (weight / (height**2)) roundbmi = round(bmi,2) elif systemused == "metric": weight = float(input("Enter your weight in kilograms")) height = float(input("Enter your height in meters")) bmi = weight / (height**2) roundbmi = round(bmi,2) else: print("You entered an incorrect system. Check your spelling and make sure you do not use quotation marks!") if roundbmi <= 18.5: print("Underweight") elif roundbmi < 25: print("Normal weight") elif roundbmi < 30: print("Overweight") else: print("Obese") #Problem 2:Two variables VarA and VarB varA = "Troll" varB = 55 if isinstance(varA,str) or isinstance(varB,str) == True: print("String involvled") else: if varA > varB: print("varA is larger than varB") elif varA == varB: print("varA and varB is equal") else: print("varA is smaller than varB") #RECURSIONS def countdown(n): if n <= 0: print('Blastoff!') else: print(n) countdown(n-1) countdown(3) def print_n(s,n): if n<= 0: return print(s) print_n(s, n-1) print_n("Hello",3) #This is an example of infinite recursion. BELOW. def recurse(): recurse() #ON PURPOSE I AM NOT RUNNING THIS CAUSE IT CAUSES ISSUES.
Java
UTF-8
4,619
2.4375
2
[]
no_license
package com.spanglerware.termtracker; import android.app.ListActivity; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; public class TermListActivity extends AppCompatActivity { private ArrayList<Term> terms; private ListView listView; private static final int TERM_DETAIL_REQUEST_CODE = 100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_term_list); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setTitle("Term List"); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.d("Term List", "toolbar onclick"); setResult(RESULT_OK); finish(); } }); terms = new ArrayList<>(); loadTerms(); int arraySize = terms.size(); //todo double check array init size String[] tempArray = new String[arraySize]; for (int i = 0; i < arraySize; i++) { tempArray[i] = terms.get(i).getTermTitle(); } listView = (ListView) findViewById(R.id.listView); listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tempArray)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { Intent intent = new Intent(TermListActivity.this, TermDetailActivity.class); intent.putExtra("termId", terms.get(i).getTermId()); startActivityForResult(intent, TERM_DETAIL_REQUEST_CODE); } }); Log.d("Term List", "onCreate"); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == TERM_DETAIL_REQUEST_CODE) { if (resultCode == RESULT_OK) { //impl } } } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); menu.removeItem(R.id.action_load); menu.removeItem(R.id.action_clear); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int menuId = item.getItemId(); switch(menuId) { case R.id.action_add: addTerm(); break; case R.id.action_home: Intent home = new Intent(this, MainActivity.class); home.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(home); break; case R.id.action_settings: Intent settingsIntent = new Intent(this, SettingsActivity.class); startActivity(settingsIntent); break; } return super.onOptionsItemSelected(item); } private void loadTerms() { //load array from database DatabaseUtil dbUtil = new DatabaseUtil(this); dbUtil.open(); Cursor cursor = dbUtil.getTerms(); Term term; while (cursor.moveToNext()) { term = new Term(); term.setTermId(cursor.getLong(DatabaseUtil.COLUMN_ROW_ID)); term.setTermTitle(cursor.getString(DatabaseUtil.COLUMN_TERM_TITLE)); term.setStartDate(TimeUtil.millisToDate( cursor.getInt(DatabaseUtil.COLUMN_TERM_START))); term.setEndDate(TimeUtil.millisToDate( cursor.getInt(DatabaseUtil.COLUMN_TERM_END))); terms.add(term); } cursor.close(); dbUtil.close(); } private void addTerm() { Intent intent = new Intent(this, TermDetailActivity.class); intent.putExtra("termId", Term.NEW_ENTRY); startActivity(intent); } } //end of TermListActivity class
PHP
UTF-8
2,511
2.625
3
[]
no_license
<?php namespace App\Http\Controllers; use App\Article; use EloquentBuilder; use Illuminate\Http\Request; class ArticleController extends Controller { /** * Display a listing of the resource. * @param Request $request * @return Response */ public function index(Request $request) { $articles = EloquentBuilder::to(Article::class, request()->filter); if ($request->has('order') && $request->has('sort')) { $response = $articles->orderBy($request->order, $request->sort); } // Nest relations data $response = $articles->with('author:id,first_name,last_name')->get(); // Enable pagination if ($request->has('paginate') && $request->paginate > 0) { $response = $articles->paginate($request->paginate); // Paginate with limit } return response()->json($response, 200); } /** * Display the specified resource. * * @param int $id * @return Response */ public function show($id) { $response = Article::where('id', $id)->with('author:id,first_name,last_name')->first(); return response()->json($response, 200); } /** * Store a newly created resource in storage. * * @param Request $request * @return Response */ public function store(Request $request) { $request->validate([ 'author' => 'int', 'title' => 'required|string', 'body' => 'required|string', 'date' => 'required|date_format:Y-m-d H:i', ]); $article = Article::create($request->all()); return response()->json($article, 201); } /** * Update the specified resource in storage. * * @param Request $request * @param Article $article * @return Response */ public function update(Request $request, Article $article) { $request->validate([ 'author' => 'int', 'title' => 'string', 'body' => 'string', 'date' => 'date_format:Y-m-d H:i', ]); $article->update($request->all()); return response()->json($article, 200); } /** * Remove the specified resource from storage. * * @param Article $article * @return Response */ public function destroy(Article $article) { $article->delete(); // forceDelete for permanentlyx return response()->json(null, 204); } }
Java
UTF-8
343
1.921875
2
[]
no_license
package com.ehr.framework.worker.workhandler; import com.ehr.framework.context.BatchParaManager; /** * 在线程中存放,读取,清除BatchPara参数的管理类 * @author zoe */ public interface WriteBatchParaManager extends BatchParaManager{ public void openThreadLocal(String[] parameter); public void closeThreadLocal(); }
Markdown
UTF-8
4,617
2.78125
3
[ "MIT" ]
permissive
--- layout: post title: Extracting Images and Files From SQL Server image: ../img/ExtractingImage/vacuum.jpg tags: [SQL, SQL Server, BLOBs, Images] --- [Last time](https://andyspecht.github.io/2017-06-12-inserting-images/) we looked at the fairly straightforward process of inserting images and file into SQL Server. Now, let's figure out how to get these things out of SQL Server and onto your filesystem. It would be nice if you could just copy the BLOB into a text file, change the extension of the file, and voila you have a PDF or JPEG. It won't work. Instead, we need to use some .NET features to extract the BLOBs in a useable format. The most obvious vehicles for using these .NET features are C# and PowerShell, and we will use PowerShell, since it's something that anyone with SQL Server should have easy access to on their system. ### A PowerShell script for Extracting SQL Server BLOBs Last time, we used this SQL to set up our test: ```sql CREATE DATABASE chockerBoxoFiles; USE chockerBoxoFiles; CREATE TABLE theFiles ( id INT IDENTITY(1,1) PRIMARY KEY, fileName VARCHAR(200), actualFile VARBINARY(MAX) ); INSERT INTO theFiles(fileName, actualFile) SELECT 'C:\Users\Andrew\Desktop\avatar-icon.png', BulkColumn FROM OPENROWSET( BULK 'C:\Users\Andrew\Desktop\avatar-icon.png', SINGLE_BLOB) AS myfile; ``` So I'll assume we are working with this table structure, and we have at least one file in the database with a full filename. We will use a script that will restore the file to the location specified in our table (in our example C:\Users\Andrew\Desktop\avatar-icon.png). Fortunately, there are already a few different PowerShell scripts that do almost exactly what we want to do. I'm using the one [here](https://social.technet.microsoft.com/wiki/contents/articles/890.export-sql-server-blob-data-with-powershell.aspx) as a template. ```powershell $Server = "(LocalDb)\MSSQLLocalDB"; # SQL Server Instance. $Database = "chockerBoxoFiles"; #$Dest = "C:\Users\Andrew\Desktop"; # Path to export to. Not necessary if file names have full location $bufferSize = 8192; # Stream buffer size in bytes. # Select-Statement for name & blob # with filter. $Sql = "SELECT fileName ,actualFile FROM theFiles"; # Open ADO.NET Connection $con = New-Object Data.SqlClient.SqlConnection; $con.ConnectionString = "Data Source=$Server;" + "Integrated Security=True;" + "Initial Catalog=$Database"; $con.Open(); # New Command and Reader $cmd = New-Object Data.SqlClient.SqlCommand $Sql, $con; $rd = $cmd.ExecuteReader(); # Create a byte array for the stream. $out = [array]::CreateInstance('Byte', $bufferSize) # Looping through records While ($rd.Read()) { $fileLocation = $rd.GetString(0) Write-Output ("Exporting: {0}" -f $rd.GetString(0)); # New BinaryWriter $fs = New-Object System.IO.FileStream $fileLocation,'Create','Write'; $bw = New-Object System.IO.BinaryWriter $fs; $start = 0; # Read first byte stream $received = $rd.GetBytes(1, $start, $out, 0, $bufferSize - 1); While ($received -gt 0) { $bw.Write($out, 0, $received); $bw.Flush(); $start += $received; # Read next byte stream $received = $rd.GetBytes(1, $start, $out, 0, $bufferSize - 1); } $bw.Close(); $fs.Close(); } # Closing & Disposing all objects $fs.Dispose(); $rd.Close(); $cmd.Dispose(); $con.Close(); Write-Output ("Finished"); ``` The key feature we are using is the BinaryWriter. This is what is used to transform your SQL Server BLOB back into a file. It's handy to have a script like this in your pocket in case you need bulk-extract files from a database, and there is not a good export utility attached to the database's application. Now that we have the basics down, in the future I want to look at alternative ways of using a database to store images/file and the merits of various strategies.
Java
UTF-8
5,126
2.5625
3
[]
no_license
package net.burgin.racetrack.gui; import com.github.sarxos.webcam.*; import net.burgin.racetrack.detection.HotSpotDetector; import net.burgin.racetrack.detection.OneTimeHotSpotDetector; import net.burgin.racetrack.gui.adapters.WebcamAdapter; import net.burgin.racetrack.gui.heats.RacetrackWebcamPanel; import javax.swing.*; import java.awt.*; import java.awt.event.*; /** * Created by jonburgin on 11/13/15. */ public class RaceTrackFrame extends JFrame implements Runnable, Thread.UncaughtExceptionHandler, ItemListener,WebcamDiscoveryListener{ private static final long serialVersionUID = 1L; private Webcam webcam = null; private RacetrackWebcamPanel panel = null; private WebcamPicker picker = null; private DefaultWebCamListener webCamListener = new DefaultWebCamListener(); private WindowListener defaultWindowListener = new DefaultWindowListener(); @Override public void run() { Webcam.addDiscoveryListener(this); setTitle("Java Webcam Capture POC"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLayout(new BorderLayout()); addWindowListener(defaultWindowListener); picker = new WebcamPicker(); picker.setSelectedIndex(picker.getItemCount() - 1); picker.addItemListener(this); webcam = picker.getSelectedWebcam(); if (webcam == null) { System.out.println("No webcams found..."); System.exit(1); } webcam.setViewSize(WebcamResolution.VGA.getSize()); webcam.addWebcamListener(webCamListener); panel = new RacetrackWebcamPanel(webcam, false); panel.setFitArea(true); panel.setFPSDisplayed(true); panel.setDisplayLanes(true); add(picker, BorderLayout.NORTH); add(this.panel, BorderLayout.CENTER); JSpinner spinner = new JSpinner(new SpinnerNumberModel(70,1,100,2)); spinner.addChangeListener((event)->((OneTimeHotSpotDetector)panel.getHotSpotDetector()).setSensitivity((Integer)((JSpinner)event.getSource()).getValue())); JButton button = new JButton("Reset"); button.addActionListener((event)->panel.getHotSpotDetector().reset()); JPanel buttonPanel = new JPanel(); buttonPanel.add(button); buttonPanel.add(spinner); add(buttonPanel, BorderLayout.SOUTH); pack(); setVisible(true); Thread t = new Thread(()->{ webcam.open(true); RaceTrackFrame.this.panel.start(); }); t.setName("example-starter"); t.setDaemon(true); t.setUncaughtExceptionHandler(this); t.start(); } public static void main(String[] args) { SwingUtilities.invokeLater(new RaceTrackFrame()); } @Override public void uncaughtException(Thread t, Throwable e) { System.err.println(String.format("Exception in thread %s", t.getName())); e.printStackTrace(); } @Override public void itemStateChanged(ItemEvent e) { if ((e.getItem() != webcam) && (webcam != null) ){ panel.stop(); remove(panel); webcam.removeWebcamListener(webCamListener); webcam.close(); webcam = (Webcam) e.getItem(); webcam.setViewSize(WebcamResolution.VGA.getSize()); webcam.addWebcamListener(webCamListener); System.out.println("selected " + webcam.getName()); panel = new RacetrackWebcamPanel(webcam, false); panel.setFPSDisplayed(true); add(panel, BorderLayout.CENTER); pack(); Thread t = new Thread(()-> panel.start()); t.setName("example-stoper"); t.setDaemon(true); t.setUncaughtExceptionHandler(this); t.start(); } } @Override public void webcamFound(WebcamDiscoveryEvent event) { if (picker != null) { picker.addItem(event.getWebcam()); } } @Override public void webcamGone(WebcamDiscoveryEvent event) { if (picker != null) { picker.removeItem(event.getWebcam()); } } class DefaultWindowListener extends WindowAdapter{ @Override public void windowClosed(WindowEvent e) { webcam.close(); } @Override public void windowDeiconified(WindowEvent e) { System.out.println("webcam viewer resumed"); panel.resume(); } @Override public void windowIconified(WindowEvent e) { System.out.println("webcam viewer paused"); panel.pause(); } } class DefaultWebCamListener extends WebcamAdapter { @Override public void webcamOpen(WebcamEvent we) { System.out.println("webcam open"); } @Override public void webcamClosed(WebcamEvent we) { System.out.println("webcam closed"); } @Override public void webcamDisposed(WebcamEvent we) { System.out.println("webcam disposed"); } } }
C#
UTF-8
2,052
2.765625
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.Linq; using System.Text; namespace ADPhotoPrep { public class ImageAdjustment { protected float _brightness = 1f; protected float _contrast = 1f; protected float _gamma = 1f; protected ImageAttributes _attribs = null; public float Brightness { get { return _brightness; } set { _brightness = value; _attribs = null; } } public float Contrast { get { return _contrast; } set { _contrast = value; _attribs = null; } } public float Gamma { get { return _gamma; } set { _gamma = value; _attribs = null; } } public ImageAttributes Attributes { get { if (_attribs == null) { // Code adapted from: http://stackoverflow.com/questions/15408607/adjust-brightness-contrast-and-gamma-of-an-image float adjustedBrightness = _brightness - 1.0f; // create matrix that will brighten and contrast the image float[][] ptsArray ={ new float[] {_contrast, 0, 0, 0, 0}, // scale red new float[] {0, _contrast, 0, 0, 0}, // scale green new float[] {0, 0, _contrast, 0, 0}, // scale blue new float[] {0, 0, 0, 1.0f, 0}, // don't scale alpha new float[] {adjustedBrightness, adjustedBrightness, adjustedBrightness, 0, 1}}; _attribs = new ImageAttributes(); _attribs.ClearColorMatrix(); _attribs.SetColorMatrix(new ColorMatrix(ptsArray), ColorMatrixFlag.Default, ColorAdjustType.Bitmap); _attribs.SetGamma(_gamma, ColorAdjustType.Bitmap); } return _attribs; } } public Bitmap Adjust(Bitmap source) { if (_brightness == 1f && _contrast == 1f && _gamma == 1f) return source; var adjustedImage = new Bitmap(source.Width, source.Height); using (Graphics g = Graphics.FromImage(adjustedImage)) g.DrawImage(source, new Rectangle(new Point(0, 0), source.Size), 0, 0, source.Width, source.Height, GraphicsUnit.Pixel, Attributes); return adjustedImage; } } }
Java
UTF-8
3,663
2.078125
2
[ "Apache-2.0" ]
permissive
package com.google.api.ads.adwords.jaxws.v201409.cm; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.bind.annotation.XmlType; /** * * Represents an asynchronous macro unit of work. * * * <p>Java class for Job complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Job"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="failureReason" type="{https://adwords.google.com/api/adwords/cm/v201409}ApiErrorReason" minOccurs="0"/> * &lt;element name="stats" type="{https://adwords.google.com/api/adwords/cm/v201409}JobStats" minOccurs="0"/> * &lt;element name="billingSummary" type="{https://adwords.google.com/api/adwords/cm/v201409}BillingSummary" minOccurs="0"/> * &lt;element name="Job.Type" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Job", propOrder = { "failureReason", "stats", "billingSummary", "jobType" }) @XmlSeeAlso({ SimpleMutateJob.class }) public abstract class Job { protected ApiErrorReason failureReason; protected JobStats stats; protected BillingSummary billingSummary; @XmlElement(name = "Job.Type") protected String jobType; /** * Gets the value of the failureReason property. * * @return * possible object is * {@link ApiErrorReason } * */ public ApiErrorReason getFailureReason() { return failureReason; } /** * Sets the value of the failureReason property. * * @param value * allowed object is * {@link ApiErrorReason } * */ public void setFailureReason(ApiErrorReason value) { this.failureReason = value; } /** * Gets the value of the stats property. * * @return * possible object is * {@link JobStats } * */ public JobStats getStats() { return stats; } /** * Sets the value of the stats property. * * @param value * allowed object is * {@link JobStats } * */ public void setStats(JobStats value) { this.stats = value; } /** * Gets the value of the billingSummary property. * * @return * possible object is * {@link BillingSummary } * */ public BillingSummary getBillingSummary() { return billingSummary; } /** * Sets the value of the billingSummary property. * * @param value * allowed object is * {@link BillingSummary } * */ public void setBillingSummary(BillingSummary value) { this.billingSummary = value; } /** * Gets the value of the jobType property. * * @return * possible object is * {@link String } * */ public String getJobType() { return jobType; } /** * Sets the value of the jobType property. * * @param value * allowed object is * {@link String } * */ public void setJobType(String value) { this.jobType = value; } }
PHP
UTF-8
869
2.578125
3
[]
no_license
<?php require_once("config.php"); /*$root = new Usuario(); //carrega somente um usuario $root->loadById(3); echo $root;*/ /* $lista = Usuario::getList(); //carrega lista de usuario echo json_encode($lista); */ /* $search = Usuario::search("jo"); echo json_encode($search); */ /* $pesquisa = new Sql(); $usuarios = $pesquisa->select("SELECT * FROM tb_usuarios WHERE idusuario = :ID", array(":ID"=>4)); echo json_encode($usuarios); */ //$usuario = new Usuario(); // carrega o usuario por login e senha //$usuario->login("jose","123445678"); //echo $usuario; /* $aluno = new Usuario(); $aluno->insert(); echo $aluno; */ /* $usuario = new Usuario(); $usuario->loadById(8); $usuario->update("professor","ij434534jk"); echo $usuario; */ $usuario = new Usuario(); $usuario->loadById(7); $usuario->delete(); echo $usuario; ?>
C++
UTF-8
4,094
2.953125
3
[]
no_license
#include "Cube.h" #include "Types.h" #include <iostream> static const GLfloat CubeVertices_Duplicated[] = { /* Front */ 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, /* Back */ 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, /* Bottom */ 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, /* Top */ 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f, /* Right */ 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, /* Left */ 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f }; static const GLfloat CubeVertices[] = { /* Front */ 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, /* Back */ 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; static const GLushort CubeIndices[] = { /* Front */ 0, 1, 2, 1, 2, 3, /* Back */ 5, 7, 4, 4, 7, 6, /* Bottom */ 4, 0, 5, 5, 0, 1, /* Top */ 2, 6, 7, 7, 6, 3, /* Right */ 1, 3, 5, 5, 3, 7, /* Left */ 4, 6, 0, 0, 6, 2 }; Cube::Cube(GLfloat cubeLength, const GLfloat cubeColor[3]) { this->length = length; /* Adjust size & color */ int currentId; for(int i=0; i<8; i++) { currentId = i*3; verticesArray[currentId] = CubeVertices[currentId]*cubeLength; verticesArray[currentId+1] = CubeVertices[currentId+1]*cubeLength; verticesArray[currentId+2] = CubeVertices[currentId+2]*cubeLength; colorsArray[currentId] = cubeColor[0]; colorsArray[currentId+1] = cubeColor[1]; colorsArray[currentId+2] = cubeColor[2]; } hasInitiatedVBO = false; verticesArraySize = sizeof(CubeVertices)/sizeof(GLfloat); indicesArraySize = sizeof(CubeIndices)/sizeof(GLushort); } Cube::~Cube() { glDeleteBuffers(1, &VertexVBOID); glDeleteBuffers(1, &ColorVBOID); glDeleteBuffers(1, &IndicesVBOID); } void Cube::initVBO() { /* VBOs generation & binding */ glGenBuffers(1, &VertexVBOID); glBindBuffer(GL_ARRAY_BUFFER, VertexVBOID); glBufferData(GL_ARRAY_BUFFER, verticesArraySize*sizeof(GLfloat), verticesArray, GL_STATIC_DRAW); glGenBuffers(1, &ColorVBOID); glBindBuffer(GL_ARRAY_BUFFER, ColorVBOID); glBufferData(GL_ARRAY_BUFFER, verticesArraySize*sizeof(GLfloat), colorsArray, GL_STATIC_DRAW); glGenBuffers(1, &IndicesVBOID); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndicesVBOID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, indicesArraySize*sizeof(GLushort), CubeIndices, GL_STATIC_DRAW); hasInitiatedVBO = true; } /* TODO : Recall initVBO when data changes ? */ void Cube::drawShape(const char* shader_name) { /* Enable attributes arrays */ GLint positionLocation = glGetAttribLocation(m_Framework->getCurrentShaderId(), "position"); GLint colorLocation = glGetAttribLocation(m_Framework->getCurrentShaderId(), "color"); glEnableVertexAttribArray(positionLocation); glEnableVertexAttribArray(colorLocation); /* Draw the cube */ if(!hasInitiatedVBO) this->initVBO(); /* Draw the cube */ glBindBuffer(GL_ARRAY_BUFFER, VertexVBOID); glVertexAttribPointer(positionLocation, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, ColorVBOID); glVertexAttribPointer(colorLocation, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, IndicesVBOID); glDrawElements(GL_TRIANGLES, indicesArraySize, GL_UNSIGNED_SHORT, 0); /* Disable attributes arrays */ glDisableVertexAttribArray(positionLocation); glDisableVertexAttribArray(colorLocation); }
C++
UTF-8
2,446
3.9375
4
[]
no_license
/* You are given two integer arrays nums1 and nums2 both of unique elements, where nums1 is a subset of nums2. Find all the next greater numbers for nums1's elements in the corresponding places of nums2. The Next Greater Number of a number x in nums1 is the first greater number to its right in nums2. If it does not exist, return -1 for this number. Example 1: Input: nums1 = [4,1,2], nums2 = [1,3,4,2] Output: [-1,3,-1] Explanation: For number 4 in the first array, you cannot find the next greater number for it in the second array, so output -1. For number 1 in the first array, the next greater number for it in the second array is 3. For number 2 in the first array, there is no next greater number for it in the second array, so output -1. Example 2: Input: nums1 = [2,4], nums2 = [1,2,3,4] Output: [3,-1] Explanation: For number 2 in the first array, the next greater number for it in the second array is 3. For number 4 in the first array, there is no next greater number for it in the second array, so output -1. Constraints: 1 <= nums1.length <= nums2.length <= 1000 0 <= nums1[i], nums2[i] <= 104 All integers in nums1 and nums2 are unique. All the integers of nums1 also appear in nums2. */ #include<bits/stdc++.h> using namespace std; // N^2 vector<int> nextGreaterElement(vector<int>& nums1, vector<int>& nums2) { vector<int> out; for(int i=0;i<nums1.size();i++) { int key=nums1[i]; bool flag=false; int index; for(int j=0;j<nums2.size();j++) { if(nums2[j]==key && flag==false) { flag=true; index=j; } if(flag==true) { bool flag1=false; for(int k=index;k<nums2.size();k++) { if(nums2[k]>nums2[index]) { flag1=true; out.push_back(nums2[k]); flag=false; break; } } if(flag1==false) { out.push_back(-1); flag=false; } } } } return out; } int main() { vector<int> a={4,1,2}; vector<int> b={1,3,4,2}; vector<int> out=nextGreaterElement(a,b); for(int i=0;i<out.size();i++) { cout<<out[i]<<" "; } }
C#
UTF-8
2,855
2.609375
3
[]
no_license
using Contracts; using Entities; using System; using System.Collections.Generic; using System.Text; namespace Repository { public class RepositoryWrapper : IRepositoryWrapper { private readonly RepositoryContext _repoContext; private IUserRepository _user; private IPodcastRepository _podcast; private ICommentRepository _comment; private IRatingRepository _rating; private ISubscriptionRepository _subscription; private IPlaylistRepository _playlist; private IPodcastToPlaylistRepository _podcastToPlaylist; public IUserRepository User { get { if (_user == null) { _user = new UserRepository(_repoContext); } return _user; } } public IPodcastRepository Podcast { get { if (_podcast == null) { _podcast = new PodcastRepository(_repoContext); } return _podcast; } } public ISubscriptionRepository Subscription { get { if (_subscription == null) { _subscription = new SubscriptionRepository(_repoContext); } return _subscription; } } public ICommentRepository Comment { get { if (_comment == null) { _comment = new CommentRepository(_repoContext); } return _comment; } } public IRatingRepository Rating { get { if (_rating == null) { _rating = new RatingRepository(_repoContext); } return _rating; } } public IPlaylistRepository Playlist { get { if (_playlist == null) { _playlist = new PlaylistRepository(_repoContext); } return _playlist; } } public IPodcastToPlaylistRepository PodcastToPlaylist { get { if (_podcastToPlaylist == null) { _podcastToPlaylist = new PodcastToPlaylistRepository(_repoContext); } return _podcastToPlaylist; } } public RepositoryWrapper(RepositoryContext repositoryContext) { _repoContext = repositoryContext; } public void Save() { _repoContext.SaveChanges(); } } }
TypeScript
UTF-8
311
2.625
3
[]
no_license
function Main(input: string[]) { const [N, X, Y] = input[0].split(" ").map((value) => parseInt(value, 10)); } //*この行以降は編集しないでください(標準入出力から一度に読み込み、Mainを呼び出します) Main(require("fs").readFileSync("/dev/stdin", "utf8").split("\n"));
TypeScript
UTF-8
952
2.53125
3
[]
no_license
import { CallHandler, ExecutionContext, Injectable, NestInterceptor, Logger, } from '@nestjs/common'; import { Observable, throwError } from 'rxjs'; import { tap, catchError } from 'rxjs/operators'; @Injectable() export class LoggerInterceptor implements NestInterceptor { private readonly context = 'REQUEST'; constructor(private logger: Logger) {} intercept(context: ExecutionContext, next: CallHandler): Observable<any> { const httpContext = context.switchToHttp(); this.logger.log( `<< Server response from route ${httpContext.getRequest().originalUrl}`, this.context, ); return next.handle().pipe( tap(data => this.logger.log(`Response: ${JSON.stringify(data)}`, this.context), ), catchError(error => { this.logger.log( `Error response: ${JSON.stringify(error)}`, this.context, ); return throwError(error); }), ); } }
Java
UTF-8
1,576
2.59375
3
[]
no_license
package de.legoshi.speedplugin.inventory; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import java.util.ArrayList; public class InventoryObject { Player player; Inventory inventory; String mode; public InventoryObject(Player player) { this.player = player; this.inventory = player.getInventory(); mode = "build"; } public InventoryObject() {} public Player getPlayer() { return this.player; } public Inventory getInventory() { return this.inventory; } public String getMode() { return this.mode; } public void setBuild(Player player) { player.getInventory().clear(); this.mode = "build"; ArrayList<String> lore = new ArrayList<String>(); lore.add("§l§6Practice"); ItemStack red = new ItemStack(Material.INK_SACK, 1, (short)1); ItemMeta metared = red.getItemMeta(); metared.setLore(lore); metared.setDisplayName("§lCheckpoint"); red.setItemMeta(metared); ItemStack arrow = new ItemStack(Material.ARROW, 1); ItemStack redstone = new ItemStack(Material.REDSTONE, 1); player.getInventory().setItem(0, red); //player.getInventory().setItem(7, redstone); //player.getInventory().setItem(8, arrow); } }
C++
UTF-8
2,515
2.625
3
[]
no_license
// This file is a part of quicksave project. // Copyright (c) 2017 Aleksander Gajewski <adiog@quicksave.io>. #pragma once #include <filesystem> #include <fstream> #include <qs/server/RequestContext.h> #include <qs/storage/Storage.h> namespace qs { namespace storage { class LocalStorage : public storage::Storage { public: LocalStorage() = default; LocalStorage(RequestContext& ctx, std::string path) : path(std::move(path)) { } std::string getMetaPath(const std::string &metaHash) const { return path + "/" + std::string(&metaHash[0], 2) + "/" + std::string(&metaHash[2], 2) + "/" + std::string(&metaHash[4], metaHash.size() - 4) + "/"; } std::string getMetaPrefixPath(const std::string &metaHash) const { return path + "/" + std::string(&metaHash[0], 2) + "/"; } std::string getFilePath(const std::string &metaHash, const std::string &filename) const { return getMetaPath(metaHash) + filename; } std::string getFilePath(const FileBean& fileBean) { return getFilePath(fileBean.meta_hash, fileBean.filename); } void init(const std::string &meta) override { std::string metaPath = getMetaPath(meta); std::filesystem::create_directories(metaPath); } void save(const std::string &metaHash, const std::string &filename, const std::string &filebody) override { const std::string filePath = getFilePath(metaHash, filename); std::ofstream fileStream(filePath, std::ios::binary); fileStream << filebody; fileStream.close(); } std::string read(const FileBean &fileBean) const override { const std::string filePath = getFilePath(fileBean.meta_hash, fileBean.filename); std::ifstream fileStream(filePath, std::ios::binary); std::ostringstream stringStream; stringStream << fileStream.rdbuf(); fileStream.close(); std::string test = stringStream.str(); return test; } void remove(const std::string &metaHash) override { std::filesystem::remove_all(getMetaPrefixPath(metaHash)); } void remove(const FileBean &fileBean) override { std::filesystem::remove_all(getFilePath(fileBean.meta_hash, fileBean.filename)); } void move(const FileBean & sourceFileBean, const FileBean& targetFileBean) override { std::filesystem::rename(getFilePath(sourceFileBean), getFilePath(targetFileBean)); } protected: std::string path; }; } }
Python
UTF-8
7,046
2.546875
3
[]
no_license
#################################################################################### ## For comparison with PileUpBunchTrains2011Config8_DigitConfig.py ## Quadruple-Train: A train made up of a sub-trains of 36 filled bunch ## crossings with intra train spacings of 50ns, followed by a 225ns gap ## then a second sub-train of 36 filled bunch crossings with intra ## train spacings of 50s, followed by a 225ns gap then a third ## sub-train of 36 filled bunch crossings with intra train spacings of ## 50s, followed by a 225ns gap then a fourth sub-train of 36 filled ## bunch crossings with intra train spacings of 50s. Any of the filled ## bunch crossings can be chosen as the central bunch crossing, so the ## timing of the out-of-time pile-up will vary significantly from event ## to event. ## Cavern Background is independent of the bunch pattern. (Compatible ## with 50ns cavern background.) #################################################################################### from Digitization.DigitizationFlags import digitizationFlags digitizationFlags.bunchSpacing = 25 # This now sets the bunch slot length. digitizationFlags.numberOfCavern = 1 #FIXME need to check on appropriate values digitizationFlags.numberOfCollisions = 2.2 digitizationFlags.initialBunchCrossing = -32 digitizationFlags.finalBunchCrossing = 32 digitizationFlags.numberOfBeamHalo = 0.05 #FIXME need to check on appropriate values digitizationFlags.numberOfBeamGas = 0.0003 #FIXME need to check on appropriate values if hasattr(digitizationFlags, 'numberOfLowPtMinBias'): digitizationFlags.numberOfLowPtMinBias = 2.2 if hasattr(digitizationFlags, 'numberOfHighPtMinBias'): digitizationFlags.numberOfHighPtMinBias = 0.0022 if hasattr(digitizationFlags, 'numberOfNDMinBias'): digitizationFlags.numberOfNDMinBias = 2.2 if hasattr(digitizationFlags, 'numberOfSDMinBias'): digitizationFlags.numberOfSDMinBias = 0.05 if hasattr(digitizationFlags, 'numberOfDDMinBias'): digitizationFlags.numberOfDDMinBias = 0.05 digitizationFlags.BeamIntensityPattern = [0.0, # bunch crossing zero is always empty 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 1 (50ns gap) 2 (50ns gap) 3 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 4 (50ns gap) 5 (50ns gap) 6 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 7 (50ns gap) 8 (50ns gap) 9 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 10 (50ns gap) 11 (50ns gap) 12 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 13 (50ns gap) 14 (50ns gap) 15 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 16 (50ns gap) 17 (50ns gap) 18 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 19 (50ns gap) 20 (50ns gap) 21 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 22 (50ns gap) 23 (50ns gap) 24 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 25 (50ns gap) 26 (50ns gap) 27 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 28 (50ns gap) 29 (50ns gap) 30 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 31 (50ns gap) 32 (50ns gap) 33 (50ns gap) 1.0,0.0,1.0,0.0, # filled bunch crossing 34 (50ns gap) 35 (50ns gap) 1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,# filled bunch crossing 36 (225ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 1 (50ns gap) 2 (50ns gap) 3 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 4 (50ns gap) 5 (50ns gap) 6 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 7 (50ns gap) 8 (50ns gap) 9 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 10 (50ns gap) 11 (50ns gap) 12 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 13 (50ns gap) 14 (50ns gap) 15 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 16 (50ns gap) 17 (50ns gap) 18 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 19 (50ns gap) 20 (50ns gap) 21 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 22 (50ns gap) 23 (50ns gap) 24 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 25 (50ns gap) 26 (50ns gap) 27 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 28 (50ns gap) 29 (50ns gap) 30 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 31 (50ns gap) 32 (50ns gap) 33 (50ns gap) 1.0,0.0,1.0,0.0, # filled bunch crossing 34 (50ns gap) 35 (50ns gap) 1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,# filled bunch crossing 36 (225ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 1 (50ns gap) 2 (50ns gap) 3 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 4 (50ns gap) 5 (50ns gap) 6 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 7 (50ns gap) 8 (50ns gap) 9 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 10 (50ns gap) 11 (50ns gap) 12 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 13 (50ns gap) 14 (50ns gap) 15 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 16 (50ns gap) 17 (50ns gap) 18 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 19 (50ns gap) 20 (50ns gap) 21 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 22 (50ns gap) 23 (50ns gap) 24 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 25 (50ns gap) 26 (50ns gap) 27 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 28 (50ns gap) 29 (50ns gap) 30 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 31 (50ns gap) 32 (50ns gap) 33 (50ns gap) 1.0,0.0,1.0,0.0, # filled bunch crossing 34 (50ns gap) 35 (50ns gap) 1.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,0.0,# filled bunch crossing 36 (225ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 1 (50ns gap) 2 (50ns gap) 3 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 4 (50ns gap) 5 (50ns gap) 6 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 7 (50ns gap) 8 (50ns gap) 9 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 10 (50ns gap) 11 (50ns gap) 12 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 13 (50ns gap) 14 (50ns gap) 15 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 16 (50ns gap) 17 (50ns gap) 18 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 19 (50ns gap) 20 (50ns gap) 21 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 22 (50ns gap) 23 (50ns gap) 24 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 25 (50ns gap) 26 (50ns gap) 27 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 28 (50ns gap) 29 (50ns gap) 30 (50ns gap) 1.0,0.0,1.0,0.0,1.0,0.0,# filled bunch crossing 31 (50ns gap) 32 (50ns gap) 33 (50ns gap) 1.0,0.0,1.0,0.0, # filled bunch crossing 34 (50ns gap) 35 (50ns gap) 1.0,0.0,0.0,0.0,0.0,0.0,# filled bunch crossing 36 (975ns gap) 0.0,0.0,0.0,0.0,0.0,0.0, 0.0,0.0,0.0,0.0,0.0,0.0, 0.0,0.0,0.0,0.0,0.0,0.0, 0.0,0.0,0.0,0.0,0.0,0.0, 0.0,0.0,0.0,0.0,0.0,0.0, 0.0,0.0,0.0]# this gap is long enough to prevent unwanted wrap-around effects digitizationFlags.cavernIgnoresBeamInt=False from AthenaCommon.BeamFlags import jobproperties jobproperties.Beam.bunchSpacing = 50 # Set this to the spacing between filled bunch-crossings within the train.
Java
UTF-8
9,340
2.421875
2
[]
no_license
package com.kcom.javatest; import com.kcom.javatest.exception.ChangeNotGivenException; import com.kcom.javatest.utils.FileOperations; import com.kcom.javatest.vo.Coin; import org.junit.Before; import org.junit.Test; import org.junit.experimental.theories.DataPoints; import org.junit.experimental.theories.Theories; import org.junit.experimental.theories.Theory; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Properties; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertThat; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; import static org.powermock.api.mockito.PowerMockito.mockStatic; /** * This class is used to test the Change class. This uses Theories and DataPoints to test the Change class */ @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(Theories.class) @PrepareForTest(FileOperations.class) public class ChangeTest { private Change change; Properties properties; @Before public void setup() { change = new Change(); properties = spy(new Properties()); } /** * This defines the data structure for the test data to get the change with unlimited coins * pence = input * coinsCollection = expected output to be compared. */ public final static class ChangeTestData { private int pence; private Collection<Coin> coinsCollection; protected ChangeTestData(int pence, Collection<Coin> coinsCollection) { this.pence = pence; this.coinsCollection = coinsCollection; } } /** * This defines the data structure for the test data to test get the change with limiting the * coins with properties file. * pence = input * inputProps = the input from the properties file * coinsCollection = expected number of change * outputProps = the output to be stored in the properties file */ public final static class ChangeTestDataWithProps { private int pence; private String[] inputProps; private Collection<Coin> coinsCollection; private String[] outputProps; protected ChangeTestDataWithProps(int pence, String[] inputProps, Collection<Coin> coinsCollection, String[] outputProps) { this.pence = pence; this.inputProps = inputProps; this.coinsCollection = coinsCollection; this.outputProps = outputProps; } } /** * The datapoints to test the getOptimalChange functionality */ @DataPoints public static final ChangeTestData[] changeTestData = { new ChangeTestData(100, Arrays.asList(new Coin(100, 1))), new ChangeTestData(143, Arrays.asList(new Coin(100, 1), new Coin(20, 2), new Coin(2, 1), new Coin(1, 1))), new ChangeTestData(558, Arrays.asList(new Coin(100, 5), new Coin(50, 1), new Coin(5, 1), new Coin(2, 1), new Coin(1, 1))), new ChangeTestData(5961593, Arrays.asList(new Coin(100, 59615), new Coin(50, 1), new Coin(20, 2), new Coin(2, 1), new Coin(1, 1))), new ChangeTestData(999, Arrays.asList(new Coin(100, 9), new Coin(50, 1), new Coin(20, 2), new Coin(5, 1), new Coin(2, 2), new Coin(1, 1))), new ChangeTestData(0, new ArrayList<Coin>()), new ChangeTestData(-1, new ArrayList<Coin>()) }; /** * The datapoints to test the getChangeFor functionality */ @DataPoints public static final ChangeTestDataWithProps[] changeTestDataWithProps = { new ChangeTestDataWithProps(100, new String[] {"5", "5", "5", "5", "5", "5", "5"}, Arrays.asList(new Coin(100, 1)), new String[] {"4", "5", "5", "5", "5", "5", "5"}), new ChangeTestDataWithProps(143, new String[] {"5", "5", "5", "5", "5", "5", "5"}, Arrays.asList(new Coin(100, 1), new Coin(20, 2), new Coin(2, 1), new Coin(1, 1)), new String[] {"4", "5", "3", "5", "5", "4", "4"}), new ChangeTestDataWithProps(658, new String[] {"5", "5", "5", "5", "5", "5", "5"}, Arrays.asList(new Coin(100, 5), new Coin(50, 1), new Coin(5, 1), new Coin(2, 1), new Coin(1, 1)), new String[] {"0", "2", "5", "5", "4", "4", "4"}), new ChangeTestDataWithProps(940, new String[] {"5", "5", "5", "5", "5", "5", "5"}, Arrays.asList(new Coin(100, 5), new Coin(50, 5), new Coin(20, 5), new Coin(10, 5), new Coin(5, 5), new Coin(2, 5), new Coin(1, 5)), new String[] {"0", "0", "0", "0", "0", "0", "0"}), new ChangeTestDataWithProps(0, new String[] {"5", "5", "5", "5", "5", "5", "5"}, new ArrayList<Coin>(), new String[] {"5", "5", "5", "5", "5", "5", "5"}), new ChangeTestDataWithProps(-1, new String[] {"5", "5", "5", "5", "5", "5", "5"}, new ArrayList<Coin>(), new String[] {"5", "5", "5", "5", "5", "5", "5"}) }; /** * The method that actually tests the getOptimalChange functionality. This is taking in the * data from the datapoints object, both for input and output. * * @param changeTestData */ @Theory @Test public void checkForOptimalChangeToRunWithDataPoints(ChangeTestData changeTestData) throws ChangeNotGivenException { Collection<Coin> coinsList = change.getOptimalChange(changeTestData.pence); assertThat("The returned coin collection is not the same", isReturnedCoinCollectionCorrect(coinsList, changeTestData.coinsCollection), is(true)); } /** * The method that actually tests the getChangeFor functionality. This is taking in the * data from the datapoints object, both for input and output. * Mocking file operations here. * * @param changeTestDataWithProps * @throws Exception */ @Theory @Test public void checkGetChangeForWithDatapoints(ChangeTestDataWithProps changeTestDataWithProps) throws Exception { Properties newProperties = new Properties(); // Defining the expected output newProperties.setProperty("100", changeTestDataWithProps.outputProps[0]); newProperties.setProperty("50", changeTestDataWithProps.outputProps[1]); newProperties.setProperty("20", changeTestDataWithProps.outputProps[2]); newProperties.setProperty("10", changeTestDataWithProps.outputProps[3]); newProperties.setProperty("5", changeTestDataWithProps.outputProps[4]); newProperties.setProperty("2", changeTestDataWithProps.outputProps[5]); newProperties.setProperty("1", changeTestDataWithProps.outputProps[6]); // Mocking the Given, When and Then mockStatic(FileOperations.class); when(FileOperations.loadPropertiesFromPropertiesFile(anyString())).thenReturn(properties); when(FileOperations.savePropertiesToPropertiesFile(anyString(), eq(properties))).thenReturn(newProperties); when(properties.getProperty("100")).thenReturn(changeTestDataWithProps.inputProps[0]); when(properties.getProperty("50")).thenReturn(changeTestDataWithProps.inputProps[1]); when(properties.getProperty("20")).thenReturn(changeTestDataWithProps.inputProps[2]); when(properties.getProperty("10")).thenReturn(changeTestDataWithProps.inputProps[3]); when(properties.getProperty("5")).thenReturn(changeTestDataWithProps.inputProps[4]); when(properties.getProperty("2")).thenReturn(changeTestDataWithProps.inputProps[5]); when(properties.getProperty("1")).thenReturn(changeTestDataWithProps.inputProps[6]); // Executing the method Collection<Coin> coinCollection = change.getChangeFor(changeTestDataWithProps.pence, "any.properties"); // Verifying whether the correct number of coins are deducted from the properties object (which will then be // written to the file. for(Coin coin: coinCollection) { assertThat(newProperties.getProperty(String.valueOf(coin.getDenomination())), is( String.valueOf(Integer.parseInt(properties.getProperty(String.valueOf(coin.getDenomination()))) -coin.getNumberOfCoins()))); } } /** * Testing the expected exception functionality from the getChangeFor. The identified scenario is where there * are less coins than are asked for in the change. * * @throws Exception */ @Test (expected = ChangeNotGivenException.class) public void checkChangeForPenceMoreThanAvailable() throws Exception { // Mocking classes and setting the When and Then mockStatic(FileOperations.class); when(FileOperations.loadPropertiesFromPropertiesFile(anyString())).thenReturn(properties); when(properties.getProperty("100")).thenReturn("5"); when(properties.getProperty("50")).thenReturn("5"); when(properties.getProperty("20")).thenReturn("5"); when(properties.getProperty("10")).thenReturn("5"); when(properties.getProperty("5")).thenReturn("5"); when(properties.getProperty("2")).thenReturn("5"); when(properties.getProperty("1")).thenReturn("5"); // Executing the method where an exception is expected Collection<Coin> coinCollection = change.getChangeFor(941, "any.properties"); } /** * Checks whether the two collections are equal or not. * * @param collectionA * @param collectionB * @return */ private boolean isReturnedCoinCollectionCorrect(Collection<Coin> collectionA, Collection<Coin> collectionB) { collectionA.removeAll(collectionB); return collectionA.isEmpty(); } }
SQL
UTF-8
1,206
2.921875
3
[ "MIT" ]
permissive
DROP table if EXISTS member; CREATE TABLE `member` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(20) NOT NULL DEFAULT '', `group` int(3) NOT NULL DEFAULT 1, `status` tinyint(2) NOT NULL DEFAULT 0, `file_name` varchar(128) DEFAULT NULL, `filesize_total` int(11) NOT NULL DEFAULT 0 COMMENT 'Total file size', `register_type` tinyint(1) NOT NULL DEFAULT 0 COMMENT '0: normal, 1:facebook, 2:twitter, 3:google', `sex` varchar(16) DEFAULT NULL, `sex_public_flag` tinyint(2) NOT NULL DEFAULT 0, `birthyear` int(4) DEFAULT NULL, `birthyear_public_flag` tinyint(2) NOT NULL DEFAULT 0, `birthdate` varchar(5) DEFAULT NULL, `birthdate_public_flag` tinyint(2) NOT NULL DEFAULT 0, `country` varchar(2) DEFAULT NULL COMMENT 'Save format by ISO 3166-1 alpha-2', `country_public_flag` tinyint(2) NOT NULL DEFAULT 0, `login_hash` varchar(255) DEFAULT NULL, `last_login` datetime DEFAULT NULL, `previous_login` datetime DEFAULT NULL, `invite_member_id` int(11) NULL, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL, PRIMARY KEY (`id`), KEY `birthdate_id` (`birthdate`,`id`), UNIQUE KEY `name_UNIQUE_idx` (`name`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Markdown
UTF-8
10,122
3.328125
3
[ "Apache-2.0" ]
permissive
# 附录 ## 附录A 梯度下降法 梯度下降法(gradient descent)或最速下降法(steepest descent)是求解无约束最优化问题的一种最常用的方法 有实现简单的优点.梯度下降法是迭代算法,每一步需要求解目标函数的梯度向量 假设f(x)是R^n上具有一阶连续偏导数的函数.要求解的无约束最优化问题是:minf(x) x*表示目标函数f(x)的极小点.x*表示目标函数f(x)的极小点. 梯度下降法是一种迭代算法.选取适当的初值x(0),不断迭代,更新x的值, 进行目标函数的极小化,直到收敛.由于负梯度方向是使函数值下降最快的方向, 在迭代的每一步,以负梯度方向更新x的值,从而达到减少函数值的目的. 由于f(x)具有一阶连续偏导数,若第k次迭代值为x^(k),则可将f(x)在x^(k)附近进行一阶泰勒展开: f(x)=f(x(k))+gk^T(x-x(k)).这里,gk=g(x(k))=gradf(x^(k))为f(x)在x^(k)的梯度. 这里,gk=g(x(k))=gradf(x(k))为f(x)在x^(k)的梯度. 求出第k+1次迭代值x(k+1):x(k+1)<-x(k)+lkpk 其中,pk是搜索方向,取负梯度方向pk=-gradf(x(k)),lk是步长, 由一维搜索确定,即lk使得f(x(k),lkpk)=minf(x^(k)+lkpk) 梯度下降算法如下: 算法A.1 (梯度下降法) 输入:目标函数f(x),梯度函数g(x)=gradf(x),计算精度e; 输出:f(x)的极小点x*. (1) 取初始值x(0)∈R^n,置k=0 (2) 计算f(x^(k)) (3) 计算梯度gk=g(x^(k)),当||gk||<e,停止迭代,令x*=x^(k);否则, 令pk=-g(x^(k)),求lk,使 ## 附录B 牛顿法和拟牛顿法 牛顿法(Newton method)和拟牛顿法(quasi Newton method)也是求解无约束最优化问题的常用方法, 有收敛速度快的优点.牛顿法是迭代算法,每一步需要求解目标函数的海森矩阵的逆矩阵,计算比较复杂. 拟牛顿法通过正定矩阵近似海森矩阵的逆矩阵或海森矩阵, 1.牛顿法 考虑无约束最优化问题minf(x),其中x*为目标函数的极小点. 假设f(x)具有二阶连续偏导数,若第k次迭代值为x^(k),则可将f(x)在x^(k)附近进行二阶泰勒展开: f(x)=f(x^(k))+gk^T(x-x(k))+0.5(x-x^(k))^TH(x^(k))(x-x(k)) 这里,gk=g(x^(k))=gradf(x^(k))是f(x)的梯度向量在点x^(k)的值,H(x^(k))是f(x)的海森矩阵(Hesse matrix), H(x)=[d2f/dxidxj](n*n) 在点x^(k)的值.函数f(x)有极值的有必要条件是在极值点处一阶导数为0, 即梯度向量为0.特别是当H(x^(k))是正定矩阵时,函数f(x)的极值为极小值 牛顿法利用极小点的必要条件gradf(x)=0,每次迭代中从点x^(k)开始,求目标函数的极小点, 作为第k+1次迭代值x(k+1).具体地,假设x(k+1)满足:gradf(x(k+1))=0 gradf(x)=gk+Hk(x-x(k)) 其中Hk=H(x^(k)). 这样有gk+Hk(x^(k+1)-x^(k))=0 因此,x^(k+1)=x^(k)-Hk^-1gk 或者,x^(k+1)=x^(k)+pk 其中,Hkpk=-gk 算法B.1 (牛顿法) 输入:目标函数f(x),梯度g(x)=gradf(x),海森矩阵H(x),精度要求e; 输出:f(x)的极小点x* (1) 取初始点x^(0),置k=0 (2) 计算gk=g(x^(k)) (3) 若||gk||<e,则停止计算,得近似解x*=x^(k) (4) 计算Hk=H(x^(k)),并求pk,Hkpk=-gk (5) 置x^(k+1)=x^(k)+pk (6) 置k=k+1,转(2) 步骤(4)求pk,pk=-Hk^-1gk,要求Hk^-1,计算比较负责,所以有其他改进的方法. 2.拟牛顿法的思路 在牛顿法的迭代中,需要计算海森矩阵的逆矩阵H^-1,这一计算比较复杂, 考虑用一个n阶矩阵Gk=G(x^(k))来近似代替Hk^-1=H^-1(x^(k)). 这就是拟牛顿法的基本想法. 先看牛顿法迭代中海森矩阵Hk满足的条件.首先,Hk满足以下关系. 在式子中取x=x^(k+1),即得gk+1-gk=Hk(x^(k+1)-x(k)) 记yk=gk+1-gk,dk=x(k+1)-x(k),则 yk=Hkdk 或Hk^-1yk=dk 如果Hk是正定的(Hk^-1也是正定的),那么可以保证牛顿法搜索方向pk是下降方向. 这是因为搜索方向是pk=-lgk,x=x(k)+lpk=x(k)-lHk^-1gk 所以f(x)在x^(k)的泰勒展开式可以近似写成:f(x)=f(x^(k))-lgk^THk^-1gk 因Hk^-1正定,故有gk^THk^-1gk>0.当l为一个充分小的正数时,总有f(x)<f(x^(k)), 也就是说pk是下降方向. 拟牛顿法将Gk作为Hk^-1的近似,要求矩阵Gk满足同样的条件.首先,每次迭代矩阵Gk是正定的. 同时,Gk满足下面的逆牛顿条件:Gk+1=Gk+ΔGk 这种选择有一定的灵活性,因此有多种具体实现方法.下面介绍Broyden类拟牛顿法. 3.DFP (Davidon-Fletcher-Powell)算法(DFP algorithm) DFP算法选择Gk+1的方法是,假设每一步迭代中矩阵Gk+1是由Gk加上两个附加项构成的,即 Gk+1=Gk+Pk+Qk. 其中Pk,Qk是待定矩阵.这时,Gk+1yk=Gkyk+Pkyk+Qkyk 为使Gk+1满足拟牛顿条件,可使Pk和Qk满足:Pkyk=dk,Qkyk=-Gkyk 事实上,不难找出这样的Pk和Qk,例如取: Pk=dkdk^T/dk^Tyk Qk=-Gkykyk^TGk/yk^TGkyk 这样就可以得到矩阵Gk+1的迭代公式: Gk+1=Gk+dkdk^T/dk^Tyk-Gkykyk^TGk/yk^TGkyk称为DFP算法 可以证明:如果初始矩阵G0是正定的,则迭代过程中每个矩阵Gk都是正定的. DFP算法如下: 算法B.2 (DFP算法) 输入:目标函数f(x),梯度g(x)=gradf(x),精度要求e; 输出:f(x)的极小值点x* (1) 选定初始点x(0),取G0为正定对称矩阵,置k=0 (2) 计算gk=g(x(k)).若||gk||<e,则停止计算,得近似解x*=x^(k);否则转(3) (3) 置pk=-Gkgk (4) 一维搜索:求lk使得 f(x^(k)+lkpk)=minf(x^(k)+lpk) (5) 置x^(k+1)=x^(k)+lkpk (6) 计算gk+1=g(x^(k+1)),若||gk+1||<e,则停止计算,得近似解x*=x^(k+1); 否则,计算Gk+1 (7) 置k=k+1,转(3) 4.BFGS算法(BFGS algorithm) BFGS算法是最流行的拟牛顿算法. 可以考虑用Gk逼近海森矩阵的逆矩阵H^-1,也可以考虑用Bk逼近海森矩阵H. 这时,相应的拟牛顿条件是Bk+1dk=yk 可以用同样的方法得到另一迭代公式.首先令Bk+1=Bk+Pk+Qk Bk+1dk=Bkdk+Pkdk+Qkdk 考虑使Pk和Qk满足:Pkdk=yk, Qkdk=-Bkdk 找出适合条件的Pk和Qk,得到BFGS算法矩阵Bk+1的迭代公式: Bk+1=Bk+ykyk^T/yk^Tdk-Bkdkdk^TBk/dk^TBkdk 可以证明,如果初始矩阵B0是正定的,则迭代过程中的每个矩阵Bk都是正定的. 下面写出BFGS拟牛顿算法 算法B.3 (BFGS算法) 输入:目标函数f(x),g(x)=gradf(x),精度要求e; 输出:f(x)的极小点x*. (1) 选定初始点x(0),取B0为正定对称矩阵,置k=0 (2) 计算gk=g(x(k)).若||gk||<e,则停止计算,得近似解x*=x(k); 否则转(3) (3) 由Bkpk=-gk求出pk (4) 一维搜索:求lk使得f(x(k)+lkpk)=minf(x(k)+lpk) (5) 置x(k+1)=x(k)+lkpk (6) 计算gk+1=g(x(k+1)),若||gk+1||<e,则停止计算,得近似解x*=x^(k+1); 否则,算出Bk+1 (7) 置k=k+1,转(3) 5.Broyden类算法 (Broyden's algorithm) 可以从BFGS算法矩阵Bk的迭代公式得到BFGS算法关于Gk的迭代公式. 若记Gk=Bk^-1, Gk+1=Bk+1^-1,那么对BFGS算法矩阵的迭代公式应用两次Sherman-Morrison公式即得: Gk+1=(I-dkyk^T/dk^Tyk)Gk(I-dkyk^T/dk^Tyk)+dkdk^T/dk^Tyk 称为BFGS算法关于Gk的迭代公式. 由DFP算法Gk的迭代公式得到的Gk+1记作G(DFP),由BFGS算法Gk的迭代公式得到的Gk+1记作G(BFGS), 它们都满足方程拟牛顿条件式,所以它们的线性组合:Gk+1=aG(DFP)+(1-a)G(BFGS) 也满足拟牛顿条件式,而且是正定的.其中0<=a<=1.这样就得到了一类拟牛顿法, 称为Broyden类算法 ## 附录C 拉格朗日对偶性 在约束最优化问题中,常常利用拉格朗日对偶性(Lagrange duality)将原始问题转换为对偶问题, 通过解对偶问题而得到原始问题的解.该方法应用在许多统计学习方法中,例如, 最大熵模型与支持向量机. 这里要叙述拉格朗日对偶性的主要概念和结果. 1.原始问题 假设f(x),ci(x),hj(x)是定义在R^n上的连续可微函数.考虑约束最优化问题 minf(x) s.t. ci(x)<=0,i=1,2,...,k, hj(x)=0,j=1,2,...,l 称此约束最优化问题为原始最优化问题或原始问题. 首先,引进广义拉格朗日函数(generalized Lagrange function), 这里,x=(x(1),x(2),...,x(n))∈R^n,ai,bj是拉格朗日乘子,ai>=0.考虑x的函数: t(x)=maxL(x,a,b).这里,下标P表示原始问题 假设给定某个x.如果x违反原始问题的约束条件,即存在某个i使得ci(w)或者存在某个j使得hj(w)!=0,那么就有, tp(x)=max[f(x)+∑aici(x)+∑bjhj(x)]=+∞ 因为若某个i使约束ci(x)>0,则可令ai->+∞,若某个j使hj(x)!=0, 则可令bj使bjhj(x)->+∞,而将其余各ai,bj均取为0. 相反地,如果x满足约束条件,则可得tp(x)=f(x).因此, tp(x)=f(x),x满足原始问题约束; tp(x)=+∞, 其他. 如果考虑极小化问题mintp(x)=minmaxL(x,a,b) 它是与原始最优化问题等价的,即它们有相同的解. 问题minmaxL(x,a,b)称为广义拉格朗日函数的极小极大问题. 这样一来,就把原始问题表示为广义拉格朗日函数的极小极大问题. 为了方便,定义原始问题的最优值p*=mintp(x)称为原始问题的值 2.对偶问题 定义tD(a,b)=minL(x,a,b) 再考虑极大化tD(a,b)=minL(x,a,b),即maxtD(a,b)=maxminL(x,a,b), 问题maxminL(x,a,b)称为广义拉格朗日函数的极大极小问题 可以将广义拉格朗日函数的极大极小问题表示为约束最优化问题; maxtD(a,b)=maxminL(x,a,b) s.t. ai>=0, i=1,2,...,k 称为原始问题的对偶问题.定义对偶问题的最优值, d*=maxtD(a,b)称为对偶问题的值d*=maxtD(a,b)称为对偶问题的值 3.原始问题和对偶问题的关系 定理C.1 若原始问题和对偶问题都有最优值,则 d*=maxminL(x,a,b)<=minmaxL(x,a,b)=p* 推论C.1 设x*和a*,b*分别是原始问题和对偶问题的可行解, 则x*和a*,b*分别是原始问题和对偶问题的最优解. 定理C.2 考虑原始问题和对偶问题.假设函数f(x)和ci(x)是凸函数,hj(x)是仿射函数; 并且假设不等式约束ci(x)是严格可行的,即存在x,对所有i有ci(x)<0,则存在x*,a*,b*, 使x*是原始问题的解,a*,b*是对偶问题的解,并且p*,d*,L(x*) 定理C.3 对原始问题(C.1)-(C.3)和对偶问题,假设函数f(x)和ci(x)是凸函数, hj(x)是仿射函数,并且不等式约束ci(x)是严格可行的, 则x*和a*,b*分别是原始问题和对偶问题的解的充分必要条件是x*,a*,b*满足下面的 Karush-Kuhn-Tucker(KKT)条件: gradxL(x*,a*,b*)=0 gradaL(x*,a*,b*)=0 gradbL(x*,a*,b*)=0 ai*ci(x*)=0,i=1,2,...,k ci(x*)<=0,i=1,2,...,k ai*>=0,i=1,2,..,k hj(x*)=0,j=1,2,...,l 特别指出,KKT条件对偶互补条件.由此条件可知:若ai*>0,则ci(x*)=0
Python
UTF-8
3,696
2.828125
3
[]
no_license
from game_class.all_class import Player, Card, Deck import game_class.explain as explain def choose_pokemon(plyr): global choice if (len(plyr.plyr_crd) > 1 ): print("Player {0} - Your Pokemon's are - {1}" .format(plyr.plyr_nm,plyr.plyr_crd)) print("Your Pokemon Details are as below.") explain.sepr(len("Your Pokemon Details are as below.")) for i in range(len(plyr.plyr_crd)): explain.poke_expl(plyr.plyr_crd[i]) ap = input("Please choose your active pokemon - ") plyr.set_actpk(Card('P',ap)) plyr.rem_actpk(ap) else : ap = str(plyr.plyr_crd[0].crd_nm) plyr.set_actpk(Card('P',ap)) print("Player {0} - Your active Pokemon is {1}" .format(plyr.plyr_nm,plyr.plyr_actpk.crd_nm)) plyr.rem_actpk(ap) def play_turn(plyr1,plyr2,mv): mv_hp = str(mv)+'_hp' print("{0} played {1} on {2} and caused a damage of {3}" .format(plyr1.plyr_actpk.crd_nm,plyr1.plyr_actpk.get_char(mv),plyr2.plyr_actpk.crd_nm,plyr1.plyr_actpk.get_char(mv_hp))) plyr2.plyr_actpk.pk_hp = int(plyr2.plyr_actpk.get_char('hp')) - int(plyr1.plyr_actpk.get_char(mv_hp)) print("Player {0} - Active Pokemon is {1} Balance HP is {2}" .format(plyr2.plyr_nm,plyr2.plyr_actpk.crd_nm,plyr2.plyr_actpk.pk_hp)) explain.start() g = input("Do you want to start the game. Press Y/N.") if (g.upper() == 'Y'): print ("Starting Game") elif (g.upper() == 'N') : print ("See you again, Quitting the game") else : print ("Please enter only Y or N") player_one = input("Welcome, Please enter a name for Player 1 ") player_two = input("Welcome, Please enter a name for Player 2 ") plyr1 = Player(player_one) plyr2 = Player(player_two) print("") print("Welcome {0} and {1} to the Battle of the Pokemon Game".format(plyr1.plyr_nm,plyr2.plyr_nm)) d1 = Deck() d1.shuffle() plyr1.plyr_crd = d1.deal_cards(3) plyr2.plyr_crd = d1.deal_cards(3) choose_pokemon(plyr1) choose_pokemon(plyr2) repeat = 1 while(repeat == 1): repeat = explain.options(plyr1) repeat = 1 while(repeat == 1): repeat = explain.options(plyr2) while ((plyr1.pk_count != 0) and (plyr2.pk_count != 0)): print(plyr1.pk_count) print(plyr2.pk_count) if (int(plyr1.plyr_actpk.pk_hp) > 0): if ('-' in plyr1.plyr_actpk.pk_mov2): opt = input("Player {0} - Do you want to use move1 or move2? " .format(plyr1.plyr_nm)) else: opt = '1' if (opt == '1'): opt1 = 'move1' else: opt1 = 'move2' play_turn(plyr1,plyr2,opt1) else: plyr1.pk_count -= 1 if (plyr1.pk_count > 0): choose_pokemon(plyr1) explain.move_expl(plyr1.plyr_actpk) if ('-' in plyr1.plyr_actpk.pk_mov2): opt = input("Player {0} - Do you want to use move1 or move2? " .format(plyr1.plyr_nm)) else: opt = '1' if (opt == '1'): opt1 = 'move1' else: opt1 = 'move2' play_turn(plyr1,plyr2,opt1) if (int(plyr2.plyr_actpk.pk_hp) > 0 and plyr1.pk_count > 0): if ('-' in plyr2.plyr_actpk.pk_mov2): opt = input("Player {0} - Do you want to use move1 or move2? " .format(plyr2.plyr_nm)) else: opt = '1' if (opt == '1'): opt1 = 'move1' else: opt1 = 'move2' play_turn(plyr2,plyr1,opt1) elif (int(plyr2.plyr_actpk.pk_hp) <= 0 and plyr1.pk_count > 0): plyr2.pk_count -= 1 if (plyr2.pk_count > 0): choose_pokemon(plyr2) explain.move_expl(plyr2.plyr_actpk) if ('-' in plyr2.plyr_actpk.pk_mov2): opt = input("Player {0} - Do you want to use move1 or move2? " .format(plyr2.plyr_nm)) else: opt = '1' if (opt == '1'): opt1 = 'move1' else: opt1 = 'move2' play_turn(plyr2,plyr1,opt1) if (plyr1.pk_count == 0 and plyr2.pk_count != 0): print("Player {0} wins" .format(plyr2.plyr_nm)) elif (plyr2.pk_count == 0 and plyr1.pk_count != 0): print("Player {0} wins" .format(plyr1.plyr_nm))
TypeScript
UTF-8
528
2.65625
3
[]
no_license
import { readFileSync } from "fs"; const seasons = ['1718', '1819']; export class DataHelper { static getSeasonData(prefix) { let data = []; for (let j=0; j<seasons.length; j++) { let seasonData = JSON.parse(readFileSync('../data/' + prefix + seasons[j] + '.json').toString()); data = data.concat(seasonData); } return data; } static getFixtures(prefix) { return JSON.parse(readFileSync('../data/' + prefix + '-fixtures.json').toString()); } }
PHP
UTF-8
2,027
2.515625
3
[]
no_license
<?php add_action( 'wp_login_failed', 'wpesec_on_login_failed' ); function wpesec_on_login_failed( $username ) { // $username is already sanitize_user'ed $addr = $_SERVER['REMOTE_ADDR']; $prefix = 'wpe_rate_limits_login_failed_' . floor( time() / 300 ); $bump = array( "${prefix}_addr_$addr", "${prefix}_user_$username", "${prefix}_global", ); foreach ( $bump as $key ) { // wp_cache_incr does not support setting expiry // or default value even though memcached does // so we atomic add the key first every time :/ // expiry time is just a touch longer than the window if ( !wp_cache_add( $key, 1, '', 400 ) ) { wp_cache_incr( $key ); } } } add_action( 'login_form_login', 'wpesec_on_before_login' ); function wpesec_on_before_login() { if ( 'GET' === $_SERVER['REQUEST_METHOD'] ) { return; } // need to sanitize to match failed login value $username = sanitize_user( $_POST['log'] ); $addr = $_SERVER['REMOTE_ADDR']; $prefix = 'wpe_rate_limits_login_failed_' . floor( time() / 300 ); $check = array( "${prefix}_addr_$addr" => 1000, "${prefix}_user_$username" => 20, "${prefix}_global" => 10000, ); foreach ( $check as $key => $limit ) { $state = wp_cache_get( $key ); if ( $state > $limit ) { error_log( "enforcing rate limit [$key]" ); header( 'Rate-Limit: login', false, 503 ); // change this to readfile(__DIR__ . '/ratelimit.html') // whenever someone wants to put together a pretty page echo '<h1>RATE LIMIT EXCEEDED', PHP_EOL; die; } } } // add_action( 'init', 'wpesec_encourage_tls' ); function wpesec_encourage_tls() { // get the domain name in the form blah.wpengine.com global $wpengine_platform_config; $domain = PWP_NAME . '.' . $wpengine_platform_config['locations']['domain_base']; if ( !force_ssl_admin() // not already using ssl && $domain === $_SERVER['HTTP_HOST'] // cert available for our base domain && !isset($_REQUEST['wpe_token']) // not an sso call ) { force_ssl_admin( true ); } }
Shell
UTF-8
576
2.90625
3
[]
no_license
# create directories for local FileSystem # mkdir -p /tmp/csv /tmp/ssn # create a destination directory on HDFS # sudo -u hdfs hdfs dfs -mkdir /tmp/nossn # sudo -u hdfs hdfs dfs -chmod -R 777 /tmp/nossn # download the latest HDF release cd ~ wget http://public-repo-1.hortonworks.com.s3.amazonaws.com/HDF/centos6/1.x/updates/1.2.0.0/HDF-1.2.0.0-91.tar.gz tar xvzf HDF-1.2.0.0-91.tar.gz && cd HDF-1.2.0.0/nifi/conf # replace nifi port 8080 to 9090 cd ~/HDF-1.2.0.0/nifi/conf sed 's/8080/9090/' nifi.properties > new mv new nifi.properties # start nifi ../bin/nifi.sh start
Shell
UTF-8
1,469
3.5
4
[ "MIT" ]
permissive
#/bin/sh #start or stop the im-server function start() { cd login_server if [ -e loginserver.conf ]; then echo "loginserver.conf exist" ../daeml ./login_server fi cd ../route_server if [ -e routeserver.conf ]; then ../daeml ./route_server fi cd ../msg_server if [ -e msgserver.conf ]; then ../daeml ./msg_server fi cd ../file_server if [ -e fileserver.conf ]; then ../daeml ./file_server fi cd ../msfs if [ -e msfs.conf ]; then ../daeml ./msfs fi cd .. } function stop() { cd login_server for i in `ls log*_1.txt`; do pid=`echo $i|awk -F_ '{print $2}'` # get pid kill $pid done mkdir -p oldlog mv log*.txt oldlog/ cd ../route_server for i in `ls log*_1.txt`; do pid=`echo $i|awk -F_ '{print $2}'` # get pid kill $pid done mkdir -p oldlog mv log*.txt oldlog/ cd ../msg_server for i in `ls log*_1.txt`; do pid=`echo $i|awk -F_ '{print $2}'` # get pid kill $pid done mkdir -p oldlog mv log*.txt oldlog/ cd ../file_server for i in `ls log*_1.txt`; do pid=`echo $i|awk -F_ '{print $2}'` # get pid kill $pid done mkdir -p oldlog mv log*.txt oldlog/ cd ../msfs for i in `ls log*_1.txt`; do pid=`echo $i|awk -F_ '{print $2}'` # get pid kill $pid done mkdir -p oldlog mv log*.txt oldlog/ cd .. } case $1 in start) start ;; stop) stop ;; restart) stop start ;; *) echo "Usage: " echo " ./run.sh (start|stop|restart)" ;; esac
TypeScript
UTF-8
527
2.71875
3
[ "MIT" ]
permissive
import { AxiosTransformer } from "../types"; /** * @description:处理转换函数调用逻辑 * @param {fn} 处理函数 * @return {type} */ const transform: (data: any, headers: any, fns?: AxiosTransformer | AxiosTransformer[]) => any = (data, headers, fns) => { if (!fns) return data if (!Array.isArray(fns)) { fns = [fns] } fns.forEach(fn => { data = fn(data, headers) // 这里将data结果当参数继续传递,形成管道式调用 }) return data } export default transform
C++
GB18030
2,432
2.6875
3
[]
no_license
#include"header.h" #include<iostream> #include<iomanip> using namespace std; int main() { /********************************/ /******EXAMPLES IN TEXTBOOK******/ /********************************/ /*Chapter1*/ //P1_1(); //P1_2(); //P1_3(); /*Chapter2*/ //P2_1(); //P2_2(); //P2_3(); //P2_4(); //P2_5(); //P2_6(); //P2_7(); //P2_8(); //P2_9(); //P2_10(); //P2_11(); //P2_12(); //P2_13(); //P2_14(); //P2_15(); //P2_16(); //P2_17(); //P2_18(); //P2_19(); /*Chapter3*/ //P3_1(); //P3_2(); //P3_3(); //P3_4(); //P3_5(); //P3_6(); //P3_7(); //P3_8(); //P3_9(); //P3_10::P3_10(); //P3_11::P3_11(); //P3_12(); //P3_13::P3_13(); //P3_14::P3_14(); //P3_15(); /*Chapter4*/ //P4_1(); //P4_2::P4_2(); //P4_3(); //P4_4::P4_4(); //P4_5::P4_5(); //P4_6(); //P4_7::P4_7(); /*Chapter5*/ //P5_1_A::P5_1_A(); //P5_1_B::P5_1_B(); //P5_2::P5_2(); //P5_3::P5_3(); //P5_4::P5_4(); //P5_5::P5_5(); //P5_6::P5_6(); //P5_7::P5_7(); //P5_8::P5_8(); //P5_9::P5_9(); //P5_10::P5_10(); //P5_11::P5_11(); //P5_12::P5_12(); /*Chapter6*/ //P6_1::P6_1(); //P6_2::P6_2(); //P6_3::P6_3(); //P6_4::P6_4(); //P6_5::P6_5(); //P6_6::P6_6(); //P6_7::P6_7(); /*Chapter7*/ //P7_1::P7_1(); //P7_2::P7_2(); //P7_3::P7_3(); //P7_4::P7_4(); //P7_5::P7_5(); //P7_6::P7_6(); //P7_7::P7_7(); //P7_8::P7_8(); //P7_9::P7_9(); //P7_10::P7_10(); /*Chapter8*/ //P8_1(); //P7_2::P7_2(); //P7_3::P7_3(); //P7_4::P7_4(); //P7_5::P7_5(); //P7_6::P7_6(); //P7_7::P7_7(); //P7_8::P7_8(); //P7_9::P7_9(); //P7_10::P7_10(); /**********************/ /******ASSIGNMENT******/ /**********************/ /*Assignment1.cpp*/ //sortThreeNum(); //harmonicSeries(); //dispalyStars_1(); //dispalyStars_2(); //dispalyStars_3(); //multiplication(); /*Assignment2.cpp*/ //sortTest(); //calendarTest(); // /*Assignment3.cpp*/ //strTest(); //ַ /*Assignment4.cpp*/ //manipulateMat(); //д¼txtļ /*Assignment5.cpp*/ ///=readTxtFile("D:\\CHY\\Program\\C++\\Textbook\\Example\\Example\\ѧɼ.txt"); //ͨļд /***********************/ /******OTHER ITEMS******/ /***********************/ /*Others.cpp*/ //pointerConvert(); //testTraverseByteWise(); //ֽڷת //testToBitArray(); //testStudentList(); //ģʹ return 0; }
Python
UTF-8
877
3.25
3
[]
no_license
#!/usr/bin/env python import sys if len(sys.argv) != 2: sys.ext("Usage: " + sys.argv[0] + "<input>") f = open(sys.argv[1], 'r') def solve( c, f, x ): cps = 2 num_farms = 0 # x = (cps * t) + (f * t * num_farms) - (c * num_farms) sum_t = 0; t = 0 # don't buy a new farm T = x / cps # time to complete after buying a farm nt = c / cps # time to complete after buying that new farm nT = x / (cps + f) while sum_t + t + T > sum_t + t + nt + nT : num_farms += 1 sum_t += t t = nt T = nT nt = c / (cps + f * num_farms) # time to buy a new farm nT = x / (cps + f * (num_farms + 1)) # time to complete after buying that new farm return sum_t + t + T games = int(f.readline()) game = 0 while game < games: line = list(map(float,f.readline().split())) time = solve( line[0], line[1], line[2] ) game += 1 print("Case #" + str(game) + ": " + str(time))
Java
UTF-8
496
1.859375
2
[]
no_license
package com.xlauncher.entity.deployment.spec; /** * @author YangDengcheng * @date 2018/2/28 14:09 */ public class ConfigMapIn { private Integer defaultMode; private String name; public Integer getDefaultMode() { return defaultMode; } public void setDefaultMode(Integer defaultMode) { this.defaultMode = defaultMode; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
Markdown
UTF-8
14,548
3.234375
3
[ "MIT" ]
permissive
--- layout: post title: "Kaggle: Digit Recognition" date: 2018-07-19T10:20:00Z categories: Kaggle --- <br> So this blog post is actually going to be a little different because this has nothing to do with GSOC(Google Summer of Code) but well it could because some of the projects have to deal with NLP(Natural Language Processing) but for now we will be dealing with a competition relating to digit recognition. So essentially we want to teach the computer to be able to read handwritten digits. The images generated are a 28 * 28 image that is in greyscale. Now working on the project was myself Keanu Nichols and [Akil Hosang](https://github.com/Akil313) we used a Neural Network approach and we tried to model it after the Coursera Machine Learning (ML) course by Andrew Ng. We did a very simple implementation by the way, it was for us to simply work on a problem since we were working on the ML course and wanted to get some actual experience working on a project so we looked to [Kaggle](https://www.kaggle.com/c/digit-recognizer) and one of the beginner projects was this. Overtime I hope we can improve the score of this approach which I believe is possible. So let's dive into it. First we go about importing our different modules as seen below, pandas is used for dataframes to store the pixels of the images and do a number of different operations. Matplotlib is used to actually see the image using the dataframes storing the pixels. Numpy is used to manipulate array to do things like transposing a matrix or multiplying two matrices. Random is used to give random numbers as will be seen in the function "randInit". And finally minimize which is an equivalent to fmincg in matlab which is used to train the actual Neural Network. {% highlight python linenos %} # Plot ad hoc mnist instances import pandas as pd import matplotlib.pyplot as plt %matplotlib inline import numpy as np import pandas as pd import random import math from scipy.optimize import minimize {% endhighlight %} Then we go onto loading our data into a training set {% highlight python linenos %} # load (downloaded if needed) the Kaggle dataset train = pd.read_csv('./datasets/train.csv') train.head() {% endhighlight %} {% include digit_rec_train.md %} and test set. {% highlight python linenos %} test = pd.read_csv('./datasets/test.csv') test.head() {% endhighlight %} {% include digit_rec_test.md %} Since we would want to just have the pixels we take the first column and onwards to get all the pixel data and store it in X_train. We then store the labels of the numbers for e.g. if the number is 2 or 3 and we store that in y_train. After we train our test date into X_test, we will actually feed this to the Neural Network and get our outputs and submit to Kaggle. {% highlight python linenos %} X_train = (train.iloc[:,1:].values.astype('float32')) y_train = (train.iloc[:,0].values.astype('int32')) X_test = test.values.astype('float32') {% endhighlight %} Now the order in which I do this will not be the exact format of the jupyter notebook but this is for us to better understand the order in which it is executed. So the first part is to store our data into the Neural Network class. {% highlight python linenos %} nn = Neural_Network(X_train,np.transpose(y_train)) {% endhighlight %} The Neural_Network class looks like this and we see that it's initialized with m the number of inputs which in our case will be 784 (28 * 28) our input layer is set to 784, hidden layer is 25 (was used in the exercise for the ML course) and our output layer size is 10 (because we have 10 digits 0-9). Epsilon is what we're going to calculate soon enough. J is our cost function and grad is our gradient. Num_labels I think is self explanatory the number of labels and lambda1 is lambda which will be used in both forward and back propagation, iter is used when we are going through using minimize for us to see our iteration number of training the Neural Network. {% highlight python linenos %} class Neural_Network: #The Neural_Network class we use to store all the values that #will be used to teach our model to start recognizing handwritten #digits def __init__(self,X,y): self.m = X_train.shape[0] self.input_layer_size = X_train.shape[1] self.hidden_layer_size = 25 self.output_layer_size = 10 self.epsilon = [] self.J = 0 self.grad = 0 self.num_labels = 10 self.lambda1 = 0 self.iter = 0 {% endhighlight %} So we go forward actually getting theta1 (for our pixels) and theta2 (for our number labels). We will call the function "randInit()" to actually populate it with values. {% highlight python linenos %} theta1 = theta2 = [] theta1,theta2 = nn.randInit() {% endhighlight %} We first go out getting our values for epsilon, which was given by the [ML course](https://www.coursera.org/learn/machine-learning/resources/EcbzQ) (under Random Initialization), we split it for theta1 and theta2 that's why epsilon is a list of two values. We also add our bias unit. We then store our values for theta1 and theta2 by random initialization. It is more or less using what's in the course. {% highlight python linenos %} def randInit(self): theta1 = [] theta2 = [] for x in range(2): if(x == 0): L_in = self.input_layer_size L_out = self.hidden_layer_size if(x == 1): L_in = self.hidden_layer_size L_out = self.output_layer_size self.epsilon.append(math.sqrt(6) / math.sqrt(L_in + L_out)) X_bias = self.input_layer_size + 1 theta1 = (np.random.rand(self.hidden_layer_size, self.input_layer_size + 1) * (2 * self.epsilon[0]) - self.epsilon[0]) theta2 = (np.random.rand(self.output_layer_size, self.hidden_layer_size + 1) * (2 * self.epsilon[1]) - self.epsilon[1]) return theta1,theta2 {% endhighlight %} The next part is the go ahead and actually train the Neural Network. As seen below we first format the values of theta1 and theta2 and store it so we can use it in different parts of the program, I also used it because the function we will be using called minimize which actually trains the Neural Network want theta1 and theta2 to be store in this format so we store it in nn_params (line 1). The next step is to actually go ahead and train the network (line 2). {% highlight python linenos %} nn_params = np.concatenate((theta1.reshape(theta1.size, order='F'), theta2.reshape(theta2.size, order='F'))) theta1,theta2 = nn.train(theta1,theta2,nn_params,X_train,np.transpose(y_train),0.08) {% endhighlight %} So as we see here train is used to better adjust the values of theta1 and theta2. So we will be using the function minimize which will be using the function nnCostFunction and that will return the cost and gradient each time. Minimize actually is able to detect if the cost function is decreasing and if it isn't it will adjust accordingly. {% highlight python linenos %} def train(self,theta1,theta2,nn_params, X, y, lambda_reg): print(self.J) print('Training Neural Network...') maxiter = 20 #maxiter = 30 #maxiter = 60 #maxiter = 5 #lambda_reg = 0 nn_params = np.concatenate((theta1.reshape(theta1.size, order='F'), theta2.reshape(theta2.size, order='F'))) myargs = (self.input_layer_size, self.hidden_layer_size, self.num_labels, X, y, lambda_reg) results = minimize(self.nnCostFunction, x0=nn_params, args=myargs, options={'disp': True, 'maxiter':maxiter}, method="L-BFGS-B", jac=True) nn_params = results["x"] # Obtain Theta1 and Theta2 back from nn_params Theta1 = np.reshape(nn_params[:self.hidden_layer_size * (self.input_layer_size + 1)], \ (self.hidden_layer_size, self.input_layer_size + 1), order='F') Theta2 = np.reshape(nn_params[self.hidden_layer_size * (self.input_layer_size + 1):], \ (self.num_labels, self.hidden_layer_size + 1), order='F') print('Program paused. Press enter to continue.\n') return Theta1,Theta2 {% endhighlight%} So we will look at the nnCostFunction the first part is to computer forward propagation. We first unpack nn_params and then add a bias unit to both theta1 and theta2. We then go about calculating the activation function from the input layer to the hidden layer and then we do it for the hidden layer to the output layer. We then create a create a matrix that will have 10 labels and will have 0's in all positions except one which will have 1 which represents what digit the pixels form. We then can calculate the cost function we also use regularization to stop overfitting. {% highlight python linenos %} def nnCostFunction(self,nn_params, input_layer_size, hidden_layer_size, \ num_labels, X, y, lambda_reg): self.J = 0; self.iter+=1; self.lambda1 = lambda_reg theta1 = np.reshape(nn_params[:hidden_layer_size * (input_layer_size + 1)], \ (hidden_layer_size, input_layer_size + 1), order='F') theta2 = np.reshape(nn_params[hidden_layer_size * (input_layer_size + 1):], \ (num_labels, hidden_layer_size + 1), order='F') Theta1_grad = np.zeros( theta1.shape ) Theta2_grad = np.zeros( theta2.shape ) a1 = np.column_stack((np.ones((self.m,1)), X)) z2 = np.dot(a1, theta1.T) a2 = self.sigmoid(z2) a2 = np.column_stack((np.ones((a2.shape[0],1)), a2)) z3 = np.dot(a2, theta2.T) a3 = self.sigmoid(z3) numLabels_temp = y yMatrix = y yMatrix = np.zeros((self.m,self.num_labels)) for i in range(self.m): yMatrix[i, numLabels_temp[i]-1] = 1 cost = 0 for i in range(self.m): cost += np.sum( yMatrix[i] * np.log(a3[i]) + (1 - yMatrix[i]) * np.log(1 - a3[i]) ) sqTheta1 = np.sum(np.sum(theta1[:,1:]**2)) sqTheta2 = np.sum(np.sum(theta2[:,1:]**2)) self.J = -(1.0/self.m) * cost self.J = self.J + ( (lambda_reg/(2.0*self.m)) *(sqTheta1 + sqTheta2) ) print( str(self.iter) + ") ",self.J," cost") {% endhighlight %} The next step is to do back propagation, so we go ahead and use values we had gotten from the feedforward calculations and use that to better adjust our theta values and we then store that in 'self.grad'. We do this for 20 iterations, however this can be increased. There starts to become a point where it does not matter how many iterations you do since the values don't change by much, which happened with our model. This may have been due to overfitting or underfitting, this is a simple model but later we hope to improve on it and do some analysis on what is happening by using for example cross validation. {% highlight python linenos %} #Back Prop delta1 = 0; delta2 = 0; for t in range(0,self.m): #print(a1.shape) a1_t = a1[t,] a2_t = a2[t,].T a3_t = a3[t,].T y_output_t = yMatrix[t,].T delta3_t = (a3_t - y_output_t); z2_t = np.dot(a1_t, theta1.T); z2_t= np.insert(z2_t,0 ,1, axis=0) delta2_t = np.dot(theta2.T, delta3_t) * self.sigmoidGradient(z2_t) delta2_t = delta2_t[1:] delta2 = delta2 + np.outer(delta3_t, a2_t) delta1 = delta1 + np.outer(delta2_t, a1_t.T) Theta1_grad = delta1 / self.m Theta2_grad = delta2 / self.m Theta1_grad_unregularized = np.copy(Theta1_grad) Theta2_grad_unregularized = np.copy(Theta2_grad) Theta1_grad += (float(self.lambda1)/self.m)*theta1 Theta2_grad += (float(self.lambda1)/self.m)*theta2 Theta1_grad[:,0] = Theta1_grad_unregularized[:,0] Theta2_grad[:,0] = Theta2_grad_unregularized[:,0] self.grad = np.concatenate((Theta1_grad.reshape(Theta1_grad.size, order='F'), Theta2_grad.reshape(Theta2_grad.size, order='F'))) #print(Theta2_grad) return self.J,self.grad {% endhighlight %} Our next step is the begin to predict what numbers are represented in our training set. {% highlight python linenos %} pred = nn.predict(theta1, theta2, X_train) {% endhighlight %} We then compare that to the labels in our training set, as discussed before this may cause a problem with overfitting. We have a accuracy of 76% which to be honest by today's standards doesn't seem too great but one step at a time! {% highlight python linenos %} k = 0 print(pred[k]) for i in pred: if(i == 10): pred[k] = 0 k+=1 print('Training Set Accuracy: {:f}'.format( ( np.mean(pred == y_train)*100 ) ) ) {% endhighlight%} We then use our model to go ahead and predict for the test set and then we just upload that to the Kaggle website. You will see in the file that we had to do some adjusting since for example the model would predict 10 but this is actually 0. {% highlight python linenos %} ans = nn.predict(theta1,theta2, X_test) {% endhighlight %} {%highlight python linenos %} k = 0 print(ans[1]) for i in ans: if(i == 10): ans[k] = 0 k+=1 print(ans[1]) df = pd.DataFrame(data=ans,columns=["Label"]) file = "submission0.csv" df.reset_index(level=0, inplace=True) #df['ImageId'] = df.index df.columns = ['ImageId', 'Label'] for i in df['ImageId']: df['ImageId'][i]+=1 #for print(df[:5]) df.to_csv(file, index=False) {% endhighlight %} {% highlight python linenos %} digit = X_test.reshape(X_test.shape[0],28,28) print(ans[0]) plt.subplot(221) plt.imshow(digit[i], cmap=plt.get_cmap('gray')) {% endhighlight %} {% highlight python lineos %} 2 {% endhighlight %} ![digit](https://raw.githubusercontent.com/kmn5409/keanu-nichols/master/_includes/digit2.png) Our best score on Kaggle is 0.87914 but this can definitely be increased through different models. Resources: [Coursera to python](https://github.com/arturomp/coursera-machine-learning-in-python/tree/master/mlclass-ex4-004/mlclass-ex4) [Andrew Ng Machine Learning](https://www.coursera.org/learn/machine-learning) Files Used:<br> Jupyter Notebook - [digit_recognizer_blog_code](https://github.com/kmn5409/Digit-Recognizer/blob/master/digit_recognizer_blog_code.ipynb)
Markdown
UTF-8
8,306
2.84375
3
[ "Apache-2.0" ]
permissive
# CLOUD AZURE EVENTHUB DataDog monitors ## How to use this module ```hcl module "datadog-monitors-cloud-azure-eventhub" { source = "claranet/monitors/datadog//cloud/azure/eventhub" version = "{revision}" environment = var.environment message = module.datadog-message-alerting.alerting-message } ``` ## Purpose Creates DataDog monitors with the following checks: - Event Hub is down - Event Hub too many errors - Event Hub too many failed requests ## Requirements | Name | Version | | --------- | -------- | | terraform | >= 1.0.0 | ## Inputs | Name | Description | Type | Default | Required | | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -------------- | ----------- | :------: | | environment | Architecture environment | `string` | n/a | yes | | errors_rate_enabled | Flag to enable Event Hub errors monitor | `string` | `"true"` | no | | errors_rate_extra_tags | Extra tags for Event Hub errors monitor | `list(string)` | `[]` | no | | errors_rate_message | Custom message for Event Hub errors monitor | `string` | `""` | no | | errors_rate_thresold_critical | Errors ratio (percentage) to trigger the critical alert | `number` | `90` | no | | errors_rate_thresold_warning | Errors ratio (percentage) to trigger a warning alert | `number` | `50` | no | | errors_rate_time_aggregator | Monitor aggregator for Event Hub errors [available values: min, max or avg] | `string` | `"min"` | no | | errors_rate_timeframe | Monitor timeframe for Event Hub errors [available values: `last_#m` (1, 5, 10, 15, or 30), `last_#h` (1, 2, or 4), or `last_1d`] | `string` | `"last_5m"` | no | | evaluation_delay | Delay in seconds for the metric evaluation | `number` | `900` | no | | eventhub_status_no_data_timeframe | Number of minutes before reporting no data | `string` | `10` | no | | failed_requests_rate_enabled | Flag to enable Event Hub failed requests monitor | `string` | `"true"` | no | | failed_requests_rate_extra_tags | Extra tags for Event Hub failed requests monitor | `list(string)` | `[]` | no | | failed_requests_rate_message | Custom message for Event Hub failed requests monitor | `string` | `""` | no | | failed_requests_rate_thresold_critical | Failed requests ratio (percentage) to trigger the critical alert | `number` | `90` | no | | failed_requests_rate_thresold_warning | Failed requests ratio (percentage) to trigger a warning alert | `number` | `50` | no | | failed_requests_rate_time_aggregator | Monitor aggregator for Event Hub failed requests [available values: min, max or avg] | `string` | `"min"` | no | | failed_requests_rate_timeframe | Monitor timeframe for Event Hub failed requests [available values: `last_#m` (1, 5, 10, 15, or 30), `last_#h` (1, 2, or 4), or `last_1d`] | `string` | `"last_5m"` | no | | filter_tags_custom | Tags used for custom filtering when filter_tags_use_defaults is false | `string` | `"*"` | no | | filter_tags_custom_excluded | Tags excluded for custom filtering when filter_tags_use_defaults is false | `string` | `""` | no | | filter_tags_use_defaults | Use default filter tags convention | `string` | `"true"` | no | | message | Message sent when an alert is triggered | `any` | n/a | yes | | new_host_delay | Delay in seconds before monitor new resource | `number` | `300` | no | | notify_no_data | Will raise no data alert if set to true | `bool` | `true` | no | | prefix_slug | Prefix string to prepend between brackets on every monitors names | `string` | `""` | no | | status_enabled | Flag to enable Event Hub status monitor | `string` | `"true"` | no | | status_extra_tags | Extra tags for Event Hub status monitor | `list(string)` | `[]` | no | | status_message | Custom message for Event Hub status monitor | `string` | `""` | no | | status_time_aggregator | Monitor aggregator for Event Hub status [available values: min, max or avg] | `string` | `"max"` | no | | status_timeframe | Monitor timeframe for Event Hub status [available values: `last_#m` (1, 5, 10, 15, or 30), `last_#h` (1, 2, or 4), or `last_1d`] | `string` | `"last_5m"` | no | ## Outputs | Name | Description | | --------------------------- | --------------------------------------- | | eventhub_errors_id | id for monitor eventhub_errors | | eventhub_failed_requests_id | id for monitor eventhub_failed_requests | | eventhub_status_id | id for monitor eventhub_status | ## Related documentation Datadog documentation : [https://docs.datadoghq.com/integrations/azure_event_hub/](https://docs.datadoghq.com/integrations/azure_event_hub/) Azure metrics documentation : [https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-metrics-azure-monitor](https://docs.microsoft.com/en-us/azure/event-hubs/event-hubs-metrics-azure-monitor)
TypeScript
UTF-8
313
2.890625
3
[ "MIT" ]
permissive
export type TupleToUnion<T> = T extends Array<infer ITEMS> ? ITEMS : never; export type ReduceTupleOn< T extends any[], FIELD extends keyof TupleToUnion<T>, EXTRACTFIELD extends keyof TupleToUnion<T> > = { [key in TupleToUnion<T>[FIELD]]: Extract<TupleToUnion<T>, { [exc in FIELD]: key }>[EXTRACTFIELD] };
C#
UTF-8
7,491
3.03125
3
[]
no_license
//Author: Nicholas Marshman using System.Collections.Generic; using UnityEngine; public class AStar : MonoBehaviour { private int initAix; //the initial Ai X coordinate private int initAiy; //the initial Ai Y coordinate private int xTarget; //the x coordinate of the target location private int yTarget; //the y coordinate of the target location private Queue<Vector2> path; //the generated path from the AI to the Target //Function that checks to see if the AI is on it's target or not private bool IsGoal(Node n) { if (n.aix == xTarget && n.aiy == yTarget) return true; else return false; } //Calculate ManHatthen distance from enemy to player, and use that as the heuristic private int Heuristic(Node n) { return Mathf.Abs(n.aix - xTarget) + Mathf.Abs(n.aiy - yTarget); } //Check to see if the neighbors are "valid" //Valid spaces are floor tiles and the tile the player is on, not walls or tiles that are out of bounds. private bool ValidNeighbor(int x, int y, int[,] state) { if (x < 0 || y < 0 || y >= state.GetLength(0) || x >= state.GetLength(0)) return false; else if (state[x, y] == 5) { return true; } else if (state[x, y] != 0) { return false; } else return true; } //Deep copy a board state private int[,] Clone(int[,] board) { int[,] copy = new int[board.GetLength(0), board.GetLength(0)]; for (int i = 0; i < board.GetLength(0); i++) { for (int j = 0; j < board.GetLength(0); j++) { copy[i, j] = board[i, j]; } } return copy; } //A method to swap the current location of the AI with the location he is moving private int[,] Swap(Node n, int x, int y) { int[,] cp = Clone(n.state); int t = cp[x, y]; cp[x, y] = cp[n.aix, n.aiy]; cp[n.aix, n.aiy] = t; return cp; } //Get all the possible neighboring spaces of the AI, first checking if they are valid. private List<State> GetNeighbors(Node n) { List<State> neighbors = new List<State>(); if (ValidNeighbor(n.aix - 1, n.aiy, n.state)) { State child = new State(Swap(n, n.aix - 1, n.aiy)); neighbors.Add(child); } if (ValidNeighbor(n.aix + 1, n.aiy, n.state)) { State child = new State(Swap(n, n.aix + 1, n.aiy)); neighbors.Add(child); } if (ValidNeighbor(n.aix, n.aiy - 1, n.state)) { State child = new State(Swap(n, n.aix, n.aiy - 1)); neighbors.Add(child); } if (ValidNeighbor(n.aix, n.aiy + 1, n.state)) { State child = new State(Swap(n, n.aix, n.aiy + 1)); neighbors.Add(child); } return neighbors; } //Recursively set the path to the goal private void SetPath(Node n, Queue<Vector2> path) { if (n.parent == null) return; SetPath(n.parent, path); Vector2 vec = new Vector2(n.aix - n.parent.aix, n.aiy - n.parent.aiy); path.Enqueue(vec); } //Find the location of the AI on the board, since it's not stored in memory //Note: AStar is memory intensive, not time intensive. This is why we are locating it //rather than storing it. private Vector2 FindAi(State state) { for (int i = 0; i < state.board.GetLength(0); i++) { for (int j = 0; j < state.board.GetLength(0); j++) { if (state.board[i, j] == 4) return new Vector2(i, j); } } return new Vector2(-1, -1); } //The function that will run the AStar Algorithm public Queue<Vector2> DoAStar(int[,] board, int aix, int aiy, int xTarget, int yTarget) { path = new Queue<Vector2>(); //init path to the goal this.xTarget = xTarget; this.yTarget = yTarget; //set the target location MinPQ<Node> minPQ = new MinPQ<Node>(); //create a MinPQ //Note: 4 on the board is the AI location, 5 is target location board[xTarget, yTarget] = 5; //initalize the location of the last viewed player board[aix, aiy] = 4; //initalize enemy location //Initialize the root node/state of the board Node root = new Node(board, aix, aiy, null) { g = 0, inFrontier = true }; //calculate the heursistic and store it root.h = Heuristic(root); minPQ.Add(root); //add the root to the PQ //In Java, we use a HashMap to do AStar. C# doesn't have a HashMap explicitly //A dictionary is functionally the same though! Dictionary<State, Node> hashmap = new Dictionary<State, Node>(); hashmap[new State(board)] = root; //C# dictionaries use the same syntax as an array //While the min PQ isn't empty while (!minPQ.IsEmpty()) { Node data = minPQ.Remove(); //get the node with the lowest priority data.inFrontier = false; //remove it from the frontier //check if it's a goal state if (IsGoal(data)) { SetPath(data, path); //if it is a goal, then set the path and return return path; } //if it's not a goal foreach (State neighbor in GetNeighbors(data)) { //Get the neighbors of the node Vector2 coord = FindAi(neighbor); //get the location of the AI if ((int)coord.x == -1) { //Error in finding ai on board print("Error: enemy returned coord: " + coord); GameManager.instance.PrintIt<int>(neighbor.board); return null; } //Create a new node with the AI's location Node n = new Node(neighbor.board, (int)coord.x, (int)coord.y, data) { g = data.g + 1, //initalize the g value to be the parent's + 1 inFrontier = true //set it to be in the frontier } n.h = Heuristic(n); //Calculate the heuristic and store it //If the neighbor's state is a new state that hasn't been seen before if (!hashmap.ContainsKey(neighbor)) { n.parent = data; //set it's parent minPQ.Add(n); //add it to the pq hashmap[neighbor] = n; //add it to the hashmap } //same state already exists else if (hashmap.ContainsKey(neighbor)) { Node old = hashmap[neighbor]; //get the old node from the hashmap //if old node is in the frontier and the new node has a lower f value if (old.inFrontier && ((old.g + old.h) > (n.h + n.g))) { //Update the old node's values old.g = n.g; //set the g to be the new node's old.h = n.h; //set the h to be the new hode's old.parent = data; //set the parent to be the current node hashmap[neighbor] = old; //place the node back into the hashmap minPQ.Update(hashmap[neighbor]); //update the priority in the MinPQ } } //Else the state has already been visited (in hash and no longer in frontier) } } return null; //Failure } }
PHP
UTF-8
3,360
3
3
[ "MIT" ]
permissive
<?php require_once ('com/gmo_pg/client/output/BaseOutput.php'); /** * <b>Paypal決済実行 出力パラメータクラス</b> * * @package com.gmo_pg.client * @subpackage output * @see outputPackageInfo.php * @author GMO PaymentGateway * @version 1.0 * @created 12-24-2009 00:00:00 */ class ExecTranPaypalOutput extends BaseOutput { /** * @var string オーダーID */ var $orderId; /** * @var string 加盟店自由項目1 */ var $clientField1; /** * @var string 加盟店自由項目2 */ var $clientField2; /** * @var string 加盟店自由項目3 */ var $clientField3; /** * コンストラクタ * * @param IgnoreCaseMap $params 出力パラメータ */ function ExecTranPaypalOutput($params = null) { $this->__construct($params); } /** * コンストラクタ * * @param IgnoreCaseMap $params 出力パラメータ */ function __construct($params = null) { parent::__construct($params); // 引数が無い場合は戻る if (is_null($params)) { return; } // マップの展開 $this->setOrderId($params->get('OrderID')); $this->setClientField1($params->get('ClientField1')); $this->setClientField2($params->get('ClientField2')); $this->setClientField3($params->get('ClientField3')); } /** * オーダーID取得 * @return string オーダーID */ function getOrderId() { return $this->orderId; } /** * 加盟店自由項目1取得 * @return string 加盟店自由項目1 */ function getClientField1() { return $this->clientField1; } /** * 加盟店自由項目2取得 * @return string 加盟店自由項目2 */ function getClientField2() { return $this->clientField2; } /** * 加盟店自由項目3取得 * @return string 加盟店自由項目3 */ function getClientField3() { return $this->clientField3; } /** * オーダーID設定 * * @param string $orderId オーダーID */ function setOrderId($orderId) { $this->orderId = $orderId; } /** * 加盟店自由項目1設定 * * @param string $clientField1 加盟店自由項目1 */ function setClientField1($clientField1) { $this->clientField1 = $clientField1; } /** * 加盟店自由項目2設定 * * @param string $clientField2 加盟店自由項目2 */ function setClientField2($clientField2) { $this->clientField2 = $clientField2; } /** * 加盟店自由項目3設定 * * @param string $clientField3 加盟店自由項目3 */ function setClientField3($clientField3) { $this->clientField3 = $clientField3; } /** * 文字列表現 * <p> * 現在の各パラメータを、パラメータ名=値&パラメータ名=値の形式で取得します。 * </p> * @return 出力パラメータ文字列表現 */ function toString() { $str = 'OrderID=' . $this->getOrderId(); $str .= '&'; $str .= 'ClientField1=' . $this->getClientField1(); $str .= '&'; $str .= 'ClientField2=' . $this->getClientField2(); $str .= '&'; $str .= 'ClientField3=' . $this->getClientField3(); if ($this->isErrorOccurred()) { // エラー文字列を連結して返す $errString = parent::toString(); $str .= '&' . $errString; } return $str; } }
Markdown
UTF-8
4,601
2.828125
3
[]
no_license
## About ### Profession Currently, I am a freelance full-stack developer and looking for a full-time front-end developer job. By job I mean, not just a job, but also an environment in which I could continually improve my professional and human skills. As a programmer, I value clean and quality code the most. Because of that, I am always trying to provide a clean and reasonable code event if it will cost extra time for me. #### Stack: - Javascript / Typescript / ReactJS / Angular / NodeJS - CSS / SCSS - HTML - C# / .NET / ASP.NET / WPF - C++ / Arduino - MySQL / SQLite / MongoDB ### Hobbies & Interests #### Motorcycles I love motorcycles and the culture of riders. It is and integral part of my life and It is starting to be more than just a hobby. It is now more like a lifestyle. The wind, engine roaring, acceleration, freedom, and a tiny bit of adrenaline are just enough to make me smile even after the worst day. #### Music Like many other people, I can't imagine life without music. I believe that music can tell some things about a person. I usually vibe on rock, R&B, soul, funk, disco, and jazz (usually instrumental music) but it can variate depending on the mood. Mostly listening to older music. The '80s is my favorite decade but it can variate around two decades up and down also. I am always open to share my playlists on [Spotify](https://open.spotify.com/user/11148697856?si=4c4181ea13464df6) ## Education ### Kaunas University of Technology _(2016-09-01 - Now)_ I've started my software engineering studies with no knowledge about programming. I just knew that I like computers and tech. There was a variety of subjects that I learned over those years in university. Starting basic object-oriented programming and ending teamwork concepts. Studies developed not only software engineering skills but also soft skills like time management and responsibility. I do not have a degree yet, but I will have one in 2022. ## Experience ### Teltonika Networks - C++ / Server developer _(2021-08-16 - now)_ Began a journey as a junior C++ developer and currently working on a system side of [Remote Management System](https://rms.teltonika-networks.com/). ### Visma Lietuva - Front-end Internship _(2020-02-02 - 2020-03-27)_ I have made big progress during these two months. Starting with the strong fundamentals of front-end development, ending team project using Angular framework. I had two coolest mentors which shared their experience as much as they could. They trained me to respect, appreciate and produce clean and quality code. --- ### Freelancing Gigs _(since 2019)_ I've done some freelancing gigs. Most of them are small. Usually, I fix problems with websites (mostly WordPress) or create custom themes and elements. Because of the big competition between WordPress developers and lack of having regular customers sometimes it is hard to get a gig. Otherwise, sometimes I get more interesting projects. A few of them are: - #### Jetski Race Lap Timer App _(2021)_ One of the recent projects. A windows application to make jetski race referee work easier. Requested by [Lithuanian Federation of Jetski sports](https://lvmsf.lt/). It was built using __C#__ programming language, __WPF (_Windows Presentation Foundation_)__ framework and __SQLite__ database. Features: - Participant registration and management. - Importing Participants from past events. - Qualification calculation. - Lap taking. - Penalty setting. - Reports printing. - Combining different race classes into one. - Live results presentation. - #### Orienteering Game Web App _(2019)_ It is one of the earliest projects as a freelance developer. The project was requested by the [Ringaudai Community Center](https://ringaudai.eu/). Idea was to create a "[Šturmas](https://www.sturmas.lt/)" style app that shows participants a list of tasks (riddles). Participants should solve a riddle get to the right place. Then take a photo of himself (or themselves if it is a team) and upload it to the system. After the time is up it shows all answers, scores, mistakes, leaderboards. The administrator's part is to rate and ban participants and supervise the game. Project is created using __React__ and __Django__ frameworks connected using __REST API__. ## You can reach me through: - Linkedin *[@justas-dovydaitis](https://www.linkedin.com/in/justas-dovydaitis/)* - Telegram *[@justas_dovydaitis](https://t.me/justas_dovydaitis)* - Messenger *[@justas.dovydaitis](https://m.me/justas.dovydaitis)*
Python
UTF-8
1,074
2.671875
3
[ "MIT" ]
permissive
# # Author: Sunil # credits: https://rpubs.com/dvorakt/144238 # from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB from sklearn.linear_model import LogisticRegression from sklearn import preprocessing import json from pprint import pprint with open('data.json') as df: data = json.load(df) emails = list() types = list() for d in data: emails.append(d["message"]) types.append(d["type"]) evec = CountVectorizer() features = evec.fit_transform(emails) le = preprocessing.LabelEncoder() labeler = le.fit(types) target = labeler.transform(types) gnb = GaussianNB() model = gnb.fit(features.todense(), target.T) test = ["viagra meet"] Xpredict = evec.transform(test) pl = model.predict(Xpredict.todense()) print(le.inverse_transform(pl)) # # useful links: # http://stackoverflow.com/questions/19984957/scikit-predict-default-threshold # http://scikit-learn.org/stable/modules/naive_bayes.html # https://www.analyticsvidhya.com/blog/2015/09/naive-bayes-explained/ #
Markdown
UTF-8
648
3.078125
3
[]
no_license
- 1: Canvas – Use your mouse to draw - 2: Colors – Click to switch between the four available shades - 3: History – Use these icons to undo or redo an action - 4: Title – Give your sprite a name - 5: Description – Optional description - 6: Save – Make sure to save regularly With PixBoy, you can quickly and easily create your own Game Boy sprites. Use the limited color palette to draw on the 16x16 canvas. Add a title and an optional description. There is no dedicated **eraser**. To erase part of your drawing, simply use the lightest shade to draw over the existing pixels. On mobile devices, the use of a stylus is recommended.
C#
UTF-8
2,971
2.546875
3
[]
no_license
using System.Collections.Generic; using Newtonsoft.Json; using NUnit.Framework; using Optional.Serialization; using Optional.Tests.Dtos; namespace Optional.Tests { [TestFixture] public class OptionalSerializationTests { [Test] public void WhenSerializingWithOptionalJsonConverterAndOptionalIsSet() { var documentDto = new DocumentDto() { Id = 1, Name = "test1", Revisions = new Optional<IEnumerable<string>>( new List<string>() { "test" } ) }; var json = JsonConvert.SerializeObject( documentDto, Formatting.Indented, new OptionalJsonConverter()); Assert.AreEqual(json, "{\r\n \"Id\": 1,\r\n \"Name\": \"test1\",\r\n \"Revisions\": [\r\n \"test\"\r\n ]\r\n}"); } [Test] public void WhenSerializingWithOptionalJsonConverterAndOptionalIsNotSet() { var documentDto = new DocumentDto() { Id = 1, Name = "test1" }; var json = JsonConvert.SerializeObject( documentDto, Formatting.Indented, new OptionalJsonConverter()); Assert.AreEqual(json, "{\r\n \"Id\": 1,\r\n \"Name\": \"test1\",\r\n \"Revisions\": null\r\n}"); } [Test] public void WhenSerializingWithOptionalContractResolverAndOptionalIsSet() { var documentDto = new DocumentDto() { Id = 1, Name = "test1", Revisions = new Optional<IEnumerable<string>>( new List<string>() { "test" } ) }; var json = JsonConvert.SerializeObject( documentDto, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new OptionalContractResolver() }); Assert.AreEqual(json, "{\r\n \"Id\": 1,\r\n \"Name\": \"test1\",\r\n \"Revisions\": [\r\n \"test\"\r\n ]\r\n}"); } [Test] public void WhenSerializingWithOptionalContractResolverAndOptionalIsNotSet() { var documentDto = new DocumentDto() { Id = 1, Name = "test2" }; var json = JsonConvert.SerializeObject( documentDto, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new OptionalContractResolver() }); Assert.AreEqual(json, "{\r\n \"Id\": 1,\r\n \"Name\": \"test2\"\r\n}"); } } }
PHP
UTF-8
802
2.5625
3
[]
no_license
<?php // session_start(); header('charset=utf-8'); include './baza.class.php'; $baza = new Baza(); $datum = date('Y-m-d H:i:s'); header('charset=utf-8'); if (isset($_REQUEST['sezona'])) { $sezona = $_REQUEST['sezona']; } else { $sezona = null; } if ($sezona != null){ $upit="SELECT * FROM sezone_has_lovina WHERE id_sezona ='$sezona'"; $rezultat=$baza->selectDB($upit); while($nesto=$rezultat->fetch_array()){ $temp = $nesto['id_lovina']; $upit2="SELECT * FROM lovina WHERE idlovina ='$temp'"; $rezultat2=$baza->selectDB($upit2); $nesto2 = $rezultat2->fetch_array(); $sezona_info[] = array("Lovina" => $nesto['id_lovina'], "Naziv" => $nesto2['naziv'], "Link" => $nesto2['link']); } echo json_encode($sezona_info); } else { $ispis = "Error"; echo $ispis; } ?>
PHP
UTF-8
2,496
2.625
3
[]
no_license
<?php class User extends CI_Controller{ public function __construct() { parent::__construct(); $this->load->model('admin/role_model'); $this->load->model('admin/user_model'); } function index() { $this->load->helper('login_helper');admin_log(); $data['title'] = "User"; $data['page'] = "admin/view_user"; $data['users'] = $this->user_model->select_user(); $this->load->view('admin/container',$data); } function insert() { $this->load->helper('login_helper');admin_log(); $data['title'] = "Add User"; $data['page'] = "admin/add_user"; $data['roles'] = $this->role_model->select_role(); $this->load->view('admin/container',$data); } function post() { $this->load->helper('login_helper');admin_log(); $data = array( 'fld_name' => $this->input->post('name'), 'fld_username' => $this->input->post('username'), 'fld_password' => $this->input->post('password'), 'fld_email' => $this->input->post('email'), 'fld_role_id'=>$this->input->post('role') ); return $data; } function create() { $this->load->helper('login_helper');admin_log(); $data = $this->post(); $this->user_model->create_user($data); $this->session->set_flashdata('msg','The user is successfully created.'); redirect( base_url().'admin/user'); } function edit($user_id) { $this->load->helper('login_helper');admin_log(); $data['title'] = "Edit User"; $data['page'] = "admin/edit_user"; $data['user'] = $this->user_model->select_user($user_id); $data['roles'] = $this->role_model->select_role(); $this->load->view('admin/container',$data); } function update($user_id) { $this->load->helper('login_helper');admin_log(); $data = $this->post(); $this->user_model->update_user($user_id,$data); $this->session->set_flashdata('msg','The user is successfully updated.'); redirect( base_url().'admin/user'); } function delete($user_id) { $this->load->helper('login_helper');admin_log(); $this->user_model->delete_user($user_id); $this->session->set_flashdata('msg','The user is successfully deleted.'); redirect( base_url().'admin/user'); } }
Markdown
UTF-8
3,477
3.078125
3
[ "Apache-2.0" ]
permissive
# Attrapez Les Tous!!! This simple app is a .Net Core 5.0 Web Api, exposing two endpoints to retrieve Pokemons's details, with or without a funny description. # Pre-requisites To be able to build and run the application, make sure you have .Net 5.0 SDK installed. This app can also be run in Docker container, if you wish to do so, make sure Docker is installed. # Build and Run the Application ## In Visual Studio Simply build the `AttrapezLesTous` project and press F5. This should start a new browser window that will allow you to explore the API. This will also launch a console window where logs are available. A log file `AttrapezLesTous-YYYYMMDD.log` is also created in the binary directory. ## From a terminal From the solution directory, execute the command: `dotnet build` You may also run the unit tests with `dotnet test` The app can be run with: `dotnet .\src\AttrapezLesTousApp\bin\Debug\net5.0\AttrapezLesTousApp.dll`. Then open a new browser and navigate to `https://localhost:5001/pokemon/mewtwo` ## As a container From the solution directory, to build a docker image, execute the command: `docker build -t attrapez-les-tous -f .\Dockerfile .` To create a container from that image and immediately start it, execute: `docker run -p 80:5000 attrapez-les-tous` (This binds the local port 80 to the port 5000 inside the container, where the app is running) To access the containerized app, open a new browser and navigate to `http://localhost/pokemon/mewtwo` # Design decisions ## .Net 5.0 I am comfortable with .Net Web APIs, so this was my defacto choice to build this app. I choose .Net 5.0 to give a try to the latest stuff! The `WriteAsJsonAsync` method in the custom exception handler (in `Startup.cs`) is .Net 5.0 specific, and it's a very useful feature. ## Solution structure The solution is composed of two projects: - A .Net 5.0 Web Api Application, created from a Visual Studio C# template, with only one controller. - A `Core` project which implements the logic of the app in F#. I choose this language because it provides a very concise syntax that allows us to build applications little block by little block (aka function). Also, the JsonProviders from the `FSharp.Data` library is a great and simple way to make web requests. # Improvements to be production ready ## Caching The caching mechanism is very basic, it is simply a concurrent dictionary, manually maintained. One issue is that we might have duplicated cached entries: when a Pokemon is queried by name or by Id. Both returned the same data, which will be stored twice in the cache. Moving forward, this would need to be improved, probably by implementing an `IMemoryCache`. Also, using Dependency Injection for accessing the cache seems a good approach but how this fits with an F# library (where things are supposed to be immutable and pure), would need to be carefully considered. ## Config At the moment, the Poke API and Fun Translation API urls are hard coded in F# files. These should be provided through an config file. ## Adding a Service layer Ideally, each endpoint in a controller should be a call to a single function which would handle dispatching work to the appropriate place and deal with exceptions. Having a new "Service layer" to do that is probably the correct approach for production code, but given the small size of this app, it seemed un-necessary
Java
UTF-8
337
1.859375
2
[]
no_license
package net.jupic.spring.security.sso; import java.io.Serializable; import java.util.Date; public interface SignedSession extends Serializable { String getSignedSessionId(); Date getCreatedTime(); Date getExpiredTime(); boolean isExpired(); Object getPrincipal(); Object getCredential(); String getPrincipalAsString(); }
C#
UTF-8
2,275
3.265625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BoardgameInc.Logic_layer { public class PlayField { private List<Ship> ships; private List<int> grid; private int shipsLeft; private string name; public PlayField(List<Ship> s, string n) { ships = s; shipsLeft = 3; name = n; grid = new List<int>(); for (int i = 0; i < 100; i++) { grid.Add(0); } } public PlayField(List<Ship> s, string n, List<int> g) { ships = s; shipsLeft = s.Count(); name = n; grid = g; } ~PlayField() { } public int checkHit(int loc) { Console.WriteLine(loc); for (int i = 0; i < ships.Count; i++) { int checkIfHit = ships[i].checkHit(loc); if (checkIfHit >= 0) { grid[loc] = 2; if (checkIfHit == 0) { ships.RemoveAt(i); shipsLeft--; } return checkIfHit; } else { grid[loc] = 1; } } return -1; } public List<Ship> getShips() { return this.ships; } public void setShips(List<Ship> s) { this.ships = s; } public Boolean getShipsLeft() { if (shipsLeft > 0) { return true; } else { return false; } } public int getShipsLeftInt() { return shipsLeft; } public void setShipsLeft(int i) { this.shipsLeft = i; } public List<int> getGrid() { return grid; } public string getName() { return name; } public void setName(String n){ name = n; } } }
Python
UTF-8
691
2.546875
3
[]
no_license
#!/usr/bin/python import binascii import sys from termcolor import colored txt = sys.argv[1] n = 4 base="0x01010101" pieces = [txt[i:i+n] for i in range(0, len(txt), n)] for reverted in pieces[::-1]: if (len(reverted) < n): parsed = binascii.hexlify(reverted[::-1]) parsed = hex(int(parsed,16) + int(base,16)) print colored("; bypassing Nullbytes restriction", 'green') print colored("mov ebx, " + parsed, 'yellow') print colored("sub ebx, " + base,'yellow') print colored("push ebx" + " ;" + reverted[::-1],'yellow') else: print("push 0x"+binascii.hexlify(reverted[::-1]) + " ;" + reverted[::-1]) print("mov ebx, esp")
Java
GB18030
5,583
3.625
4
[]
no_license
package tree; import java.util.Scanner; import java.util.Stack; public class SortedBiTree { protected SortedBiNode root; protected int nodeNum; public int CreateSortedBiTree(){ Scanner sc = new Scanner(System.in); SortedBiNode pointer = null; System.out.println("ڵ"); nodeNum = sc.nextInt(); System.out.println("˳ڵֵ"); root = new SortedBiNode(); root.data = sc.nextInt(); for(int i=1; i<nodeNum; i++){ pointer = new SortedBiNode(); pointer.data = sc.nextInt(); insertNodeByNoRecursion(root,pointer); } return 0; } public int insertNode(SortedBiNode topNode, SortedBiNode node){ if(node.data > topNode.data){ if(topNode.rightChildren == null){ topNode.rightChildren = node; } else{ insertNode(topNode.rightChildren, node); } } else if(node.data <= topNode.data){ if(topNode.leftChildren == null){ topNode.leftChildren = node; } else{ insertNode(topNode.leftChildren, node); } } return 0; } public int insertNodeByNoRecursion(SortedBiNode topNode, SortedBiNode node){ SortedBiNode pointer = topNode; while(true){ if(node.data > pointer.data){ if(pointer.rightChildren == null){ pointer.rightChildren = node; break; } else{ pointer = pointer.rightChildren; } } else{ if(pointer.leftChildren == null){ pointer.leftChildren = node; break; } else{ pointer = pointer.leftChildren; } } } return 0; } public int deleteNode(int data){ SortedBiNode pre = null; SortedBiNode pointer = root; while(true){ if(pointer.data == data){ break; } else if(pointer.data < data){ pre = pointer; pointer = pointer.rightChildren; } else if(pointer.data > data){ pre = pointer; pointer = pointer.leftChildren; } } if(pre == null){ root = null; } else if(pointer.rightChildren == null && pointer.leftChildren == null){ if(pre.leftChildren == pointer){ pre.leftChildren = null; } else if(pre.rightChildren == pointer){ pre.rightChildren = null; } } else if(pointer.rightChildren != null && pointer.leftChildren == null){ if(pre.leftChildren == pointer){ pre.leftChildren = pointer.rightChildren; } else if(pre.rightChildren == pointer){ pre.rightChildren = pointer.rightChildren; } } else if(pointer.leftChildren != null && pointer.rightChildren == null){ if(pre.leftChildren == pointer){ pre.leftChildren = pointer.leftChildren; } else if(pre.rightChildren == pointer){ pre.rightChildren = pointer.leftChildren; } } else{ SortedBiNode temp = pointer.leftChildren; while(temp.rightChildren != null){ temp = temp.rightChildren; } temp.rightChildren = pointer.rightChildren; if(pre.leftChildren == pointer){ pre.leftChildren = pointer.leftChildren; } else if(pre.rightChildren == pointer){ pre.rightChildren = pointer.leftChildren; } } return 0; } public int deleteNodeNew(int data){ SortedBiNode pre = null; SortedBiNode pointer = root; while(true){ if(pointer.data == data){ break; } else if(pointer.data < data){ pre = pointer; pointer = pointer.rightChildren; } else if(pointer.data > data){ pre = pointer; pointer = pointer.leftChildren; } } if(pre == null){ root = null; } else if(pointer.rightChildren == null && pointer.leftChildren == null){ if(pre.leftChildren == pointer){ pre.leftChildren = null; } else if(pre.rightChildren == pointer){ pre.rightChildren = null; } } else if(pointer.rightChildren != null && pointer.leftChildren == null){ if(pre.leftChildren == pointer){ pre.leftChildren = pointer.rightChildren; } else if(pre.rightChildren == pointer){ pre.rightChildren = pointer.rightChildren; } } else if(pointer.leftChildren != null && pointer.rightChildren == null){ if(pre.leftChildren == pointer){ pre.leftChildren = pointer.leftChildren; } else if(pre.rightChildren == pointer){ pre.rightChildren = pointer.leftChildren; } } else{ SortedBiNode tempPre = pointer; SortedBiNode temp = pointer.leftChildren; while(temp.rightChildren != null){ pre = temp; temp = temp.rightChildren; } pre.rightChildren = temp.leftChildren; pointer.data = temp.data; } return 0; } public SortedBiNode findNode(int data){ SortedBiNode pointer = root; while(pointer != null){ if(pointer.data == data){ return pointer; } else if(pointer.data > data){ pointer = pointer.leftChildren; } else if(pointer.data < data){ pointer = pointer.rightChildren; } } return null; } public int printSortedBiTreeByIn(){ Stack<SortedBiNode> stack = new Stack<SortedBiNode>(); SortedBiNode pointer = null; boolean flag = false; if(root != null) stack.push(root); while(!stack.isEmpty()){ while(!flag && stack.peek().leftChildren != null){ stack.push(stack.peek().leftChildren); } pointer = stack.pop(); System.out.print(pointer.data); if(pointer.rightChildren != null){ flag = false; stack.push(pointer.rightChildren); } else{ flag = true; } } return 0; } public static void main(String[] args){ SortedBiTree tree = new SortedBiTree(); tree.CreateSortedBiTree(); tree.printSortedBiTreeByIn(); System.out.println(); tree.deleteNode(5); tree.printSortedBiTreeByIn(); SortedBiNode temp = tree.findNode(4); if(temp != null){ System.out.println(temp.data); } } }
C#
UTF-8
1,683
2.75
3
[]
no_license
using System; using System.Collections.Generic; using Core.Enums; namespace Core.Entities { public class Autor { public int Id { get; set; } public string Nome { get; set; } public string Email { get; set; } public virtual IEnumerable<Artigo> Artigos { get; set; } public string UsuarioId { get; set; } public Genero Genero { get; set; } public DateTime DataCadastro { get; set; } public DateTime? DataAtualizacao { get; set; } public DateTime? DataRemocao { get; set; } public Autor() { } public Autor(Usuario usuario) { Nome = usuario.UserName; Email = usuario.Email; UsuarioId = usuario.Id; DataCadastro = DateTime.Now; } public void Validar() { if(string.IsNullOrEmpty(Nome)) throw new ArgumentException("É necessário informar o nome"); ValidarEnderecoDeEmail(); } public void ValidarEnderecoDeEmail() { if(string.IsNullOrEmpty(Email)) throw new ArgumentException("É necessário informar o endereço de email"); if(!Email.Contains("@") || !Email.Contains(".")) throw new ArgumentException("Endereço de e-mail inválido"); } public void Atualizar(string nome, string email, string genero) { Nome = nome; Email = email; Genero = (Genero) Enum.Parse(typeof(Genero), genero); Validar(); DataAtualizacao = DateTime.Now; } public void Remover() => DataRemocao = DateTime.Now; } }
Java
UTF-8
4,353
2.140625
2
[]
no_license
package com.quwb.web.entity; import com.fasterxml.jackson.annotation.JsonFormat; import java.util.Date; public class ShopDetail { /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column ShopDetail.DetailID * * @mbg.generated */ private Long detailid; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column ShopDetail.ShopID * * @mbg.generated */ private Long shopid; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column ShopDetail.Info * * @mbg.generated */ private String info; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column ShopDetail.CreateTime * * @mbg.generated */ @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss") private Date createtime; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column ShopDetail.IsActive * * @mbg.generated */ private Short isactive; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column ShopDetail.DetailID * * @return the value of ShopDetail.DetailID * * @mbg.generated */ public Long getDetailid() { return detailid; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column ShopDetail.DetailID * * @param detailid the value for ShopDetail.DetailID * * @mbg.generated */ public void setDetailid(Long detailid) { this.detailid = detailid; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column ShopDetail.ShopID * * @return the value of ShopDetail.ShopID * * @mbg.generated */ public Long getShopid() { return shopid; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column ShopDetail.ShopID * * @param shopid the value for ShopDetail.ShopID * * @mbg.generated */ public void setShopid(Long shopid) { this.shopid = shopid; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column ShopDetail.Info * * @return the value of ShopDetail.Info * * @mbg.generated */ public String getInfo() { return info; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column ShopDetail.Info * * @param info the value for ShopDetail.Info * * @mbg.generated */ public void setInfo(String info) { this.info = info == null ? null : info.trim(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column ShopDetail.CreateTime * * @return the value of ShopDetail.CreateTime * * @mbg.generated */ public Date getCreatetime() { return createtime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column ShopDetail.CreateTime * * @param createtime the value for ShopDetail.CreateTime * * @mbg.generated */ public void setCreatetime(Date createtime) { this.createtime = createtime; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column ShopDetail.IsActive * * @return the value of ShopDetail.IsActive * * @mbg.generated */ public Short getIsactive() { return isactive; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column ShopDetail.IsActive * * @param isactive the value for ShopDetail.IsActive * * @mbg.generated */ public void setIsactive(Short isactive) { this.isactive = isactive; } }
Java
UTF-8
2,697
2.09375
2
[ "Apache-2.0", "BSD-3-Clause", "MIT" ]
permissive
/* * * Copyright [2022] [DMetaSoul Team] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * */ package org.apache.flink.lakesoul.sink; import org.apache.flink.streaming.api.functions.sink.filesystem.PartFileInfo; import org.apache.flink.streaming.api.functions.sink.filesystem.rollingpolicies.CheckpointRollingPolicy; import org.apache.flink.table.data.RowData; import static org.apache.flink.lakesoul.tool.LakeSoulSinkOptions.DEFAULT_BUCKET_ROLLING_SIZE; import static org.apache.flink.lakesoul.tool.LakeSoulSinkOptions.DEFAULT_BUCKET_ROLLING_TIME; public class LakeSoulRollingPolicyImpl extends CheckpointRollingPolicy<RowData, String> { private boolean rollOnCheckpoint; private long rollingSize; private long rollingTime; public LakeSoulRollingPolicyImpl(long rollingSize, long rollingTime) { this.rollOnCheckpoint = true; this.rollingSize = rollingSize; this.rollingTime = rollingTime; } public LakeSoulRollingPolicyImpl(boolean rollOnCheckpoint) { this.rollingSize = DEFAULT_BUCKET_ROLLING_SIZE; this.rollingTime = DEFAULT_BUCKET_ROLLING_TIME; this.rollOnCheckpoint = rollOnCheckpoint; } @Override public boolean shouldRollOnCheckpoint(PartFileInfo<String> partFileState) { return this.rollOnCheckpoint; } @Override public boolean shouldRollOnEvent(PartFileInfo<String> partFileState, RowData element) { return false; } @Override public boolean shouldRollOnProcessingTime( PartFileInfo<String> partFileState, long currentTime) { return currentTime - partFileState.getLastUpdateTime() > rollingTime; } public boolean shouldRollOnMaxSize(long size) { return size > rollingSize; } public long getRollingSize() { return rollingSize; } public void setRollingSize(long rollingSize) { this.rollingSize = rollingSize; } public long getRollingTime() { return rollingTime; } public void setRollingTime(long rollingTime) { this.rollingTime = rollingTime; } public boolean isRollOnCheckpoint() { return rollOnCheckpoint; } public void setRollOnCheckpoint(boolean rollOnCheckpoint) { this.rollOnCheckpoint = rollOnCheckpoint; } }
C
UTF-8
7,700
3.09375
3
[ "MIT" ]
permissive
#include <stdio.h> #include <stdlib.h> #include <omp.h> #include <sys/time.h> inline void scanint(int *x) { register char c = getchar_unlocked(); *x = 0; for(; (c<48)||(c>57);c = getchar_unlocked()); for(; (c>47)&&(c<58);c = getchar_unlocked()) *x = (int)((((*x)<<1) + ((*x)<<3)) + c - 48); } inline void printint(int n) { char buf[11]; buf[10] = '\n'; int i = 9; while(n) { buf[i--] = n % 10 + '0'; n /= 10; } while(buf[i] != '\n') putchar_unlocked(buf[++i]); } struct timeval start_total_time, end_total_time; /*Algo times*/ struct timeval start_read_time, end_read_time; /* io need 2 timers */ struct timeval start_write_time, end_write_time; struct timeval start_endtoend_time, end_endtoend_time; /* end to end time*/ struct Point { int x; int y; int z; }; struct Edge { int first; int second; }; struct hashNode { struct Point *key; int index; struct hashNode *next; }; struct hashMap { int size1; struct hashNode **root; } hashMap1; int equalsPoint(struct Point *a,struct Point *b) { return (a->x==b->x && a->y==b->y && a->z==b->z); } void init_hashMap(int n) { hashMap1.size1 = n; hashMap1.root = (struct hashNode **)malloc(n*sizeof(struct hashNode *)); int i; for(i=0;i<n;i++) { hashMap1.root[i] = NULL; } } void insertInLinkedList(int listIndex,struct Point *point,int index) { struct hashNode *soonToBeRoot = (struct hashNode *)malloc(sizeof(struct hashNode )); soonToBeRoot->next = hashMap1.root[listIndex]; hashMap1.root[listIndex] = soonToBeRoot; soonToBeRoot->key = point; soonToBeRoot->index = index; } int searchInLinkedList(int listIndex,struct Point *point) { struct hashNode *root = hashMap1.root[listIndex]; while(root) { if(equalsPoint(root->key,point)) return root->index; root = root -> next ; } return -1; } void insert_hashMap(struct Point *point,int index) { int hashCode = hashFunc(point); insertInLinkedList(hashCode%(hashMap1.size1),point,index); } int hashFunc(struct Point *p) { int val1 = (p->x*997*661 + p->y*661 + p->z); return val1&0x7FFFFFFF; } int getIndex(struct Point *point) { int hashCode = hashFunc(point); return searchInLinkedList(hashCode%(hashMap1.size1),point); } int *parent; int findRoot(int x) { if(parent[x]==x) return x; return ( parent[x] = findRoot(parent[x]) ); } void union1(int x,int y) { int xRoot = findRoot(x); int yRoot = findRoot(y); if(xRoot>yRoot) { parent[xRoot] = yRoot; } else if(xRoot<yRoot) { parent[yRoot] = xRoot; } } void beautifyOutputAndPrint(int N,struct Point *points) { int i; int *prefixSum1 = (int *)malloc(N*sizeof(int)); int count1 = 0; for(i=0;i<N;i++) { if(parent[i]==i) prefixSum1[i] = ++count1; } for(i=0;i<N;i++) { printint(prefixSum1[findRoot(i)]); } } int main(int argc,char* argv[]) { gettimeofday(&start_endtoend_time,NULL); if(argc < 2) { printf("Input Format: <NumberOfLines>\n"); exit(1); } int n,i; n = atoi(argv[1]); struct Point *points = (struct Point *)malloc(n*sizeof(struct Point)); struct Edge *edges = (struct Edge *)malloc(6*n*sizeof(struct Edge)); parent = (int *)malloc(n*sizeof(int)); init_hashMap(n); int m = -1; gettimeofday(&start_read_time,NULL); for(i=0;i<n;i++) { scanint(&points[i].x); scanint(&points[i].y); scanint(&points[i].z); /*scanf("%d,%d,%d\n",&points[i].x,&points[i].y,&points[i].z);*/ } gettimeofday(&end_read_time,NULL); omp_set_num_threads(omp_get_max_threads()); gettimeofday(&start_total_time,NULL); for(i=0;i<n;i++) { insert_hashMap(&points[i],i); parent[i] = i; } #pragma omp parallel { const int ithread = omp_get_thread_num(); const int nthreads = omp_get_num_threads(); int start1 = ithread*n/nthreads; int end1 = (ithread+1)*n/nthreads; int myStart = start1*6; int i; int index1; for(i = start1;i<end1;i++) { struct Point temp = points[i]; /* changing x co-ordinate*/ temp.x++; index1 = getIndex(&temp); if(index1 > i ) { edges[myStart].first = i; edges[myStart].second = index1; myStart++; } temp.x--; temp.x--; index1 = getIndex(&temp); if(index1 > i ) { edges[myStart].first = i; edges[myStart].second = index1; myStart++; } temp.x++; /* changing y co-ordinate*/ temp.y++; index1 = getIndex(&temp); if(index1 > i ) { edges[myStart].first = i; edges[myStart].second = index1; myStart++; } temp.y--; temp.y--; index1 = getIndex(&temp); if(index1 > i ) { edges[myStart].first = i; edges[myStart].second = index1; myStart++; } temp.y++; /* changing z co-ordinate*/ temp.z++; index1 = getIndex(&temp); if(index1 > i ) { edges[myStart].first = i; edges[myStart].second = index1; myStart++; } temp.z--; temp.z--; index1 = getIndex(&temp); if(index1 > i ) { edges[myStart].first = i; edges[myStart].second = index1; myStart++; } } int start2 = start1*6; for(i=start2;i<myStart;i++) { #pragma critical union1(edges[i].first,edges[i].second); } } gettimeofday(&end_total_time,NULL); gettimeofday(&start_write_time,NULL); beautifyOutputAndPrint(n,points); gettimeofday(&end_write_time,NULL); gettimeofday(&end_endtoend_time,NULL); double endtoendTime = ( end_endtoend_time.tv_usec - start_endtoend_time.tv_usec ); endtoendTime += (end_endtoend_time.tv_sec - start_endtoend_time.tv_sec)*1000000; endtoendTime /= 1000000; double ioTime = (end_read_time.tv_usec - start_read_time.tv_usec) + (end_read_time.tv_sec - start_read_time.tv_sec)*1000000; ioTime += (end_write_time.tv_usec - start_write_time.tv_usec) + (end_write_time.tv_sec - start_write_time.tv_sec)*1000000;; double algoTime = (end_total_time.tv_usec - start_total_time.tv_usec) + (end_total_time.tv_sec - start_total_time.tv_sec)*1000000; fprintf(stderr, "--- other user output (if any) ---\n"); fprintf(stderr, "Algorithm time = %f microsecs\n",algoTime); fprintf(stderr, "IO time = %f microsecs\n",ioTime); fprintf(stderr, "End to end time = %f secs\n",endtoendTime); return 0; }
Markdown
UTF-8
6,491
2.609375
3
[]
no_license
<div> <p>Khoai lang có nhiều chất dinh dưỡng tốt cho cơ thể, dễ ăn và giúp bạn giảm cân hiệu quả.</p> </div> <div id="maincontent"> <div> <p>Giảm cân là mục tiêu khó đạt được do mọi người không thể kiểm soát mong muốn ăn những món yêu thích. Trong trường hợp đó, bạn phải lựa chọn thực phẩm có lợi cho sức khỏe và tạo cảm giác ngon miệng.</p> <p>Khoai lang là món dễ ăn, giàu chất xơ và các khoáng chất cần thiết giúp bạn giữ được thân hình cân đối, khỏe mạnh. Bạn có thể kết hợp loại củ này vào chế độ ăn uống của mình.</p> <p><a href="https://tangcangiamcan.webflow.io/posts/an-yen-mach-giam-can" style="color: rgb(17, 85, 204);" target="_blank">https://tangcangiamcan.webflow.io/posts/an-yen-mach-giam-can</a><br /> <a href="https://tangcangiamcan.webflow.io/posts/giam-can-an-bao-nhieu-calo" style="color: rgb(17, 85, 204);" target="_blank">https://tangcangiamcan.webflow.io/posts/giam-can-an-bao-nhieu-calo</a><br /> <a href="https://tangcangiamcan.webflow.io/posts/giam-can-bang-giam-tao" style="color: rgb(17, 85, 204);" target="_blank">https://tangcangiamcan.webflow.io/posts/giam-can-bang-giam-tao</a><br /> <a href="https://tangcangiamcan.webflow.io/posts/giam-can-bang-khoai-lang" style="color: rgb(17, 85, 204);" target="_blank">https://tangcangiamcan.webflow.io/posts/giam-can-bang-khoai-lang</a><br /> <a href="https://tangcangiamcan.webflow.io/posts/giam-can-bang-la-oi" style="color: rgb(17, 85, 204);" target="_blank">https://tangcangiamcan.webflow.io/posts/giam-can-bang-la-oi</a><br /> <a href="https://tangcangiamcan.webflow.io/posts/giam-can-bang-mat-ong" style="color: rgb(17, 85, 204);" target="_blank">https://tangcangiamcan.webflow.io/posts/giam-can-bang-mat-ong</a><br /> <a href="https://tangcangiamcan.webflow.io/posts/giam-can-bang-trung" style="color: rgb(17, 85, 204);" target="_blank">https://tangcangiamcan.webflow.io/posts/giam-can-bang-trung</a><br /> <a href="https://tangcangiamcan.webflow.io/posts/giam-can-bang-yen-mach" style="color: rgb(17, 85, 204);" target="_blank">https://tangcangiamcan.webflow.io/posts/giam-can-bang-yen-mach</a><br /> <a href="https://tangcangiamcan.webflow.io/posts/giam-can-co-nen-an-com-khong" style="color: rgb(17, 85, 204);" target="_blank">https://tangcangiamcan.webflow.io/posts/giam-can-co-nen-an-com-khong</a><br /> <a href="https://tangcangiamcan.webflow.io/posts/giam-can-cho-nguoi-luoi" style="color: rgb(17, 85, 204);" target="_blank">https://tangcangiamcan.webflow.io/posts/giam-can-cho-nguoi-luoi</a></p> <p><img alt="{keywords}" src="https://vnn-imgs-f.vgcloud.vn/2021/03/06/13/thuc-don-giam-can-bang-khoai-lang-trong-3-ngay.jpg" /></p> <p>Ảnh minh họa: Livescience</p> <p>Các lợi ích của khoai lang</p> <p>- Chứa ít calorie</p> <p>Một điều bạn cần làm khi muốn&nbsp;giảm cân&nbsp;là giảm lượng calorie. Trong khi đó, 100g khoai lang chỉ chứa 86 calorie. Thêm khoai lang vào bữa ăn sẽ khiến bạn có cảm giác no nhưng không hấp thụ nhiều calorie.</p> <p>- Giàu chất xơ</p> <p>Thực phẩm giàu chất xơ giúp bạn không ăn quá nhiều và cải thiện sức khỏe hệ tiêu hóa. Chúng kích thích sản xuất các vi khuẩn có lợi cho đường ruột và ngăn chặn hấp thụ chất béo. Khoai lang chứa một lượng lớn chất xơ cải thiện quá trình trao đổi chất, tiêu hóa và bài tiết, từ đó giúp giảm cân.</p> <p>- Chỉ số đường huyết thấp</p> <p>Chế độ ăn có chỉ số đường huyết cao (GI) làm tăng lượng đường trong máu, dẫn đến các vấn đề sức khỏe như tiểu đường, béo phì... Khoai lang có chỉ số đường huyết thấp, đó là lý do bạn phải thêm thực phẩm này vào chế độ ăn uống của mình.</p> <p>Tuy nhiên, bạn phải lưu ý khoai lang luộc sẽ có nhiều lợi ích giảm cân hơn. Khoai luộc có GI là 44, khoai lang nướng có GI là 94.</p> <p>- Hàm lượng nước cao</p> <p>Điều cần thiết là giữ cho cơ thể bạn đủ nước để giảm cân. Khi bạn bị mất nước, quá trình trao đổi chất diễn ra chậm lại, gây ra tăng cân. Khoai lang có hàm lượng nước cao giúp cơ thể không tích tụ chất béo, thải độc tố ra ngoài, cân bằng độ pH bên trong. Ngoài ra, khoai lang chứa nhiều nước và chất xơ giúp bạn cảm thấy no lâu.</p> <p><img alt="{keywords}" src="https://vnn-imgs-f.vgcloud.vn/2021/03/06/13/thuc-don-giam-can-bang-khoai-lang-trong-3-ngay-1.jpg" /></p> <p>Thực đơn ăn kiêng giảm 2 kg trong 3 ngày</p> <p>Ngày 1:</p> <p>Bữa sáng: 1 quả trứng luộc, 1 củ khoai lang luộc không muối, 1 tách trà xanh</p> <p>Bữa trưa: 2 củ khoai lang luộc không muối, 1 cốc sữa chua</p> <p>Bữa tối: 1 củ khoai lang luộc, 2 cốc sữa chua</p> <p>Ngày 2</p> <p>Bữa sáng: 1 củ khoai lang luộc, 1 tách cà phê đen, 2 lòng trắng trứng ốp lết</p> <p>Bữa trưa: Salad nấm và khoai lang luộc, 1 tách sữa bơ không béo</p> <p>Bữa tối: 1 củ khoai lang luộc, súp lơ luộc, 100g thịt gà nướng</p> <p>Ngày 3</p> <p>Bữa sáng: 1 củ khoai lang luộc, 1 tách trà xanh, 1 quả chuối, 4 hạt hạnh nhân</p> <p>Bữa trưa: 1 bát súp khoai lang, 1 lát bánh mì ngũ cốc nướng, 1 tách sữa chua</p> <p>Bữa tối: Khoai lang nghiền, nấm nướng, súp lơ và đậu luộc.&nbsp;</p> <p>Lưu ý</p> <p>Món cần tránh: Đồ ăn có đường, đóng hộp, chế biến sẵn, nước tăng lực.</p> <p>Áp dụng thực đơn trên sẽ tăng tỷ lệ trao đổi chất và giảm cân. Tuy nhiên, nếu bạn đang dùng bất kỳ loại thuốc nào, hãy hỏi ý kiến bác sĩ trước khi bắt đầu ăn kiêng. Ngoài ra, không tiếp tục chế độ này nếu bạn cảm thấy mệt.</p> <p>Bạn không được áp dụng chế độ ăn kiêng trên liên tục vì nguy cơ suy giảm sức lực. Nếu muốn, bạn có thể lặp lại chế độ ăn kiêng này sau 2 tuần.</p> <p>Ngoài ra, hãy ăn uống lành mạnh, cân bằng và tập thể dục thường xuyên, đi kiểm tra sức khỏe ít nhất 1 lần trong năm.</p> </div> </div>
C++
GB18030
2,433
2.828125
3
[]
no_license
#include <iostream> #include <stdio.h> #include <stdlib.h> #include "EGraph.h" using namespace std; int x[11][3]= { 1,2,19, 2,3,5, 1,7,18, 1,5,14, 2,5,12, 2,4,7, 3,4,3, 7,5,16, 5,4,8, 4,6,21, 7,6,27, }; void CreateGraph (EGraph *g){ int i; g->vexnum=7; g->edgenum=11; for(i=0;i<g->vexnum;i++) g->vexlist[i]=i+1; for(i=0;i<g->edgenum;i++) { g->edgelist[i].ivex=x[i][0]; g->edgelist[i].jvex=x[i][1]; g->edgelist[i].weight=x[i][2]; } /*char c; printf("Input vertex number and edge number in the graph:\n"); scanf("%d %d",&g->vexnum,&g->edgenum); scanf("%c",&c); for(i=0;i<g->vexnum;i++) scanf(" %d",&g->vexlist[i]); printf("Input edge info: starting vertex,ending vertex,weight:\n"); for(i=0;i<g->edgenum;i++) { scanf(" %d %d %d",&g->edgelist[i].ivex,&g->edgelist[i].jvex,&g->edgelist[i].weight); } */ //룺7 11 1 2 3 4 5 6 7 // 1,2,19, 2,3,5, 1,7,18, 1,5,14, 2,5,12, 2,4,7, 3,4,3, 7,5,16, 5,4,8, 4,6,21,7,6,27, //for(i=0;i<g->edgenum;i++) //printf("%d,%d,%d\n",g->edgelist[i].ivex,g->edgelist[i].jvex,g->edgelist[i].weight); } void BubbleSort(Enode a[], int n) //aгС {int i,j,change=0; Enode y; for (i=n-1, change=1; i>=1 && change; --i) for (j=0, change=0; j<i; ++j) if (a[j].weight>a[j+1].weight) { //yн飬a[j],a[j+1] y=a[j]; a[j]=a[j+1]; a[j+1]=y; change= 1; } } MSTEdge *Kruskal(EGraph *g){ int i,j,k,s1,s2; MSTEdge *TE; TE=(MSTEdge *)malloc(g->vexnum*sizeof(MSTEdge)); int *vSet; vSet=(int *)malloc(g->vexnum*sizeof(int)); for(i=0;i<g->vexnum;i++) vSet[i]=i;//ʼvSet BubbleSort(g->edgelist,g->edgenum);//Ա߰ȨֵС i=0;j=0; while(i<g->vexnum && j<g->edgenum) { s1=vSet[g->edgelist[j].ivex]; s2=vSet[g->edgelist[j].jvex]; //ߵͨŲͬ, 򽫸ñ߼뵽TE if(s1!=s2) { TE[i].vex1=g->edgelist[j].ivex; TE[i].vex2=g->edgelist[j].jvex; TE[i].weight=g->edgelist[j].weight; i++; for(k=0;k<g->vexnum;k++) if(vSet[k]==s2) vSet[k]=s1; } j++; } free(vSet); return TE; } int main() { EGraph g; MSTEdge *edges; CreateGraph (&g); edges=Kruskal(&g); printf("MST:\n"); for(int i=0;i<g.vexnum-1;i++) printf("%d %d %d\n",edges[i].vex1,edges[i].vex2,edges[i].weight); system("pause"); return 0; }
Ruby
UTF-8
2,471
3.296875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# frozen_string_literal: true module TTY class ProgressBar # Responsible for converting values to different formats # # @api public module Converter HOURSECONDS = 3600 # Convert seconds to time notation # # @param [Numeric] seconds # the seconds to convert to time # # @api public def to_time(seconds) days = (seconds / (24 * HOURSECONDS).to_f).floor seconds -= days * 24 * HOURSECONDS hours = (seconds / HOURSECONDS.to_f).floor seconds -= hours * HOURSECONDS minutes = (seconds / 60).floor seconds -= minutes * 60 if days > 0 # over 24 hours switch to days format("%dd%2dh%2dm", days, hours, minutes) elsif hours > 0 format("%2dh%2dm", hours, minutes) elsif minutes > 0 format("%2dm%2ds", minutes, seconds) else format("%2ds", seconds) end end module_function :to_time # Convert seconds to set precision # # @param [Numeric] seconds # the seconds to convert # # @return [String] # the formatted result # # @api public def to_seconds(seconds, precision: nil) precision ||= (seconds < 1 && !seconds.zero?) ? 5 : 2 format "%5.#{precision}f", seconds end module_function :to_seconds BYTE_UNITS = %w[b kb mb gb tb pb eb].freeze # Convert value to bytes # # @param [Numeric] value # the value to convert to bytes # @param [Integer] decimals # the number of decimals parts # @param [String] separator # the separator to use for thousands in a number # @param [String] unit_separator # the separtor to use between number and unit # # @return [String] # # @api public def to_bytes(value, decimals: 2, separator: ".", unit_separator: "") base = 1024 pattern = "%.#{decimals}f" unit = BYTE_UNITS.find.with_index { |_, i| value < base**(i + 1) } if value < base formatted_value = value.to_i.to_s else value_to_size = value / (base**BYTE_UNITS.index(unit)).to_f formatted_value = format(pattern, value_to_size) end formatted_value.gsub(/\./, separator) + unit_separator + unit.to_s.upcase end module_function :to_bytes end # Converter end # ProgressBar end # TTY
JavaScript
UTF-8
7,979
3.140625
3
[]
no_license
$(document).ready(function() { //v1.02 //variables var wins = 0; var losses = 0; var lettersGuessed = []; var wordBank = []; var guessesLeft; var dashWordClue = []; var guessesMade = 0; var pickedWord; var isWinner; var pickedWordArray = []; var pickedWordPlaceholders; var keyboard = { "row1": ["q", "w", "e", "r", "t", "y", "u", "i", "o", "p"], "row2": ["a", "s", "d", "f", "g", "h", "j", "k", "l"], "row3": ["z", "x", "c", "v", "b", "n", "m"] }; //functions //grab a random word from the API function RandomWord() { var requestStr = "https://api.wordnik.com:443/v4/words.json/randomWords?hasDictionaryDef=true&includePartOfSpeech=noun&excludePartOfSpeech=conjunction&minCorpusCount=0&minLength=5&maxLength=15&limit=1&api_key=a2a73e7b926c924fad7001ca3111acd55af2ffabf50eb4ae5"; $.ajax({ type: "GET", url: requestStr }).done(function(result) { pickedWord = result[0].word.toLowerCase(); // split pickedWord into an array (array.split("")) pickedWordArray = pickedWord.split(""); displayWord(); isWinner = pickedWordArray.length; //create the dashWordClue dashWordClue = []; for (var i = 0; i < pickedWordArray.length; i++) { dashWordClue.push("-"); } }) } function displayWord() { console.log("displayword"); $('#picked-word-array').empty(); $('#picked-word-array').html($('<h2>').text("Your Clue: ")); var pickedWordSendIt = ""; for (var i = 0; i < pickedWordArray.length; i++) { pickedWordSendIt = ($('<button>').addClass("btn btn-danger clue-buttons")).append($('<i>').addClass("fa fa-minus")); $('#picked-word-array').append(pickedWordSendIt); } $('#guesses-left').html($('<h3>').text("Guesses Left: " + guessesLeft)); $('#guesses-made').html($('<h3>').text("Guesses Made So Far: ")); } function newGame() { // reset guesses left guessesLeft = 8; //display the score $('#wins').html($('<h3>').text("Wins: " + wins)); $('#losses').html($('<h3>').text("Losses: " + losses)); // empty out pickedWordPlaceholders $('#picked-word-array').empty(); // empty out lettersGuessed $('#guesses-left').empty(); $('#guesses-made').empty(); $('#messages').empty(); lettersGuessed = []; //create the keyboard //empty the div, add the first row $('#keyboard-id').html($('<div>').addClass("row1 text-center")); //create the first row for (var i = 0; i < keyboard.row1.length; i++) { var newButton = $('<button>'); newButton.attr("class", "btn btn-primary keyboardButton").text(keyboard.row1[i]).attr("data-value", keyboard.row1[i]); $('#keyboard-id').append(newButton); } //create the second row $('#keyboard-id').append($('<div>').addClass("row2")); for (var i = 0; i < keyboard.row2.length; i++) { var newButton = $('<button>'); newButton.attr("class", "btn btn-danger keyboardButton").text(keyboard.row2[i]).attr("data-value", keyboard.row2[i]); $('#keyboard-id').append(newButton); } //create the third row $('#keyboard-id').append($('<div>').addClass("row3")); for (var i = 0; i < keyboard.row3.length; i++) { var newButton = $('<button>'); newButton.attr("class", "btn btn-info keyboardButton").text(keyboard.row3[i]).attr("data-value", keyboard.row3[i]); $('#keyboard-id').append(newButton); } // grab a new word RandomWord(); } function letterIsClicked(keyPressed) { //check to see if the letter is in the lettersGuessed var letterIndex = lettersGuessed.indexOf(keyPressed) if (letterIndex != -1) { //check to see if guessesLeft = 0 if (guessesLeft <= 0) { //if its zero, call gameover gameOver("lose"); } $('#messages').html($('<h2>').text("Letter Has Been Pressed Before")); } //letter is new else if (letterIndex === -1) { //check to see if guessesLeft = 0 if (guessesLeft <= 0) { //if its zero, call gameover gameOver("lose"); } letterIsNewGuess(keyPressed); } else { console.log("ERROR") } }; function letterIsNewGuess(keyPressed) { //Add the key to the #guesses-made lettersGuessed.push(keyPressed); //if the pickedWord includes the keypressed, //push the message $('#picked-word-array').empty(); $('#picked-word-array').html($('<h2>').text("Your Clue: ")); if (pickedWordArray.includes(keyPressed)) { $('#guesses-made').append($('<button>').addClass("btn btn-success clue-buttons").text(keyPressed)); var pickedWordSendIt = ""; //redraw the clue for (var i = 0; i < pickedWordArray.length; i++) { //if the array[i] is equal to the key, display the button as a key if (pickedWordArray[i] === keyPressed) { dashWordClue[i] = keyPressed; isWinner--; if (isWinner <= 0) { gameOver("win"); } } // if it doesnt match and the clue is a dash (if its not a dash leave it alone) else if (pickedWordArray[i] != keyPressed && dashWordClue[i] === "-") { dashWordClue[i] = "-"; } } } else { $('#messages').html($('<h2>').text("Ouch. That wasn't good.")); $('#guesses-made').append($('<button>').addClass("btn btn-warning clue-buttons").text(keyPressed)); guessesLeft--; $('#guesses-left').html($('<h3>').text("Guesses Left: " + guessesLeft)); } //display the Clue for (var j = 0; j < dashWordClue.length; j++) { if (dashWordClue[j] === "-") { pickedWordSendIt = ($('<button>').addClass("btn btn-danger clue-buttons").attr("index-value", j)).append($('<i>').addClass("fa fa-minus")); $('#picked-word-array').append(pickedWordSendIt); } else { pickedWordSendIt = $('<button>').addClass("btn btn-danger clue-buttons").text(dashWordClue[j]); $('#picked-word-array').append(pickedWordSendIt); } } } function gameOver(outcome) { winOrLoss = outcome; switch (winOrLoss) { case "win": wins++; $('#messages').html($('<h2>').text("Game Over. WINNER WINNER CHICKEN DINNER. Press a New Game to play again")); $("#winModal").modal(); break; case "lose": $('#messages').html($('<h2>').text("Game Over. Better Luck Next Time. The correct word was: " + pickedWord)); losses++; $("#loseModal").modal(); $('#modal-message').text("Game Over. Better Luck Next Time. The correct word was: " + pickedWord); } }; //event listeners //newgame $(document).on('click', '#new-game', function(event) { event.preventDefault(); //$(".modal").modal(); newGame(); }); // Keyboard Listener. When a letter is clicked, execute the letterIsClicked function. $(document).on('click', '.keyboardButton', function(event) { var keyPressed = $(this).attr('data-value'); //disable the letter on the keyboard. $(this).addClass("disabled"); letterIsClicked(keyPressed); }); });
Java
UTF-8
937
2.140625
2
[]
no_license
package com.mop.qa.test.CAT; import org.testng.annotations.Test; import com.mop.qa.pageobject.JdeHomePage; import com.mop.qa.pageobject.SignOnPage; import com.mop.qa.pageobject.TMSShipConfirmCatPage; import com.mop.qa.pageobject.WorkWithShippmentPage; import com.mop.qa.testbase.TestBase; public class TC510 extends TestBase { @Test public void executeTest() { try { // input-->recieveOption, System.out.println("IT 510 Ship Confirm"); SignOnPage signOnPage = new SignOnPage(remoteDriver); JdeHomePage jdeHomePage = signOnPage.loginAsValidUser(); TMSShipConfirmCatPage tmsShip = jdeHomePage.navigateToTMSShipConfirmPage(); tmsShip.workWithTMSShipConfirmCat(); jdeHomePage.goToHomeScreen(); WorkWithShippmentPage workShipmentTMS = jdeHomePage.navigateToWorkWithShipment3(); workShipmentTMS.workWithShipmentTMSConfirmCAT(); } catch (Exception ex) { System.out.println("Exception" + ex); } } }
Python
UTF-8
1,173
4.5
4
[]
no_license
''' Простейшие арифметические операции (1) Написать функцию arithmetic, принимающую 3 аргумента: первые 2 - числа, третий - операция, которая должна быть произведена над ними. Если третий аргумент +, сложить их; если —, то вычесть; * — умножить; / — разделить (первое на второе). В остальных случаях вернуть строку "Неизвестная операция". ''' def arifmetic (num1,num2,operation): try: a = int(num1) b = int(num2) if operation is "+": c = a+b return c elif operation is "-": c = a-b return c elif operation is "*": c = a*b return c elif operation is "/": c = a/b return c else: return "unknown operation" except ValueError: print("Wrong input, check numbers") x = arifmetic("6","5","+") print(x) #Test
C#
UTF-8
1,563
2.921875
3
[]
no_license
using System; using Veam.Domain.Core.ValueObjects; namespace Veam.Domain.Core.ValueObjects { /// <summary> /// person Value Object /// </summary> public class Person : ValueObject<Person> { public Person(string firstName, string lastName, string middleName, string nickName, string gender, string salutation) { this.firstName = firstName /*?? throw new ArgumentNullException(nameof(firstName)) */; this.lastName = lastName /*?? throw new ArgumentNullException(nameof(lastName)) */; this.middleName = middleName /*?? throw new ArgumentNullException(nameof(middleName))*/; this.nickName = nickName /*?? throw new ArgumentNullException(nameof(nickName)) */; this.gender = gender /*?? throw new ArgumentNullException(nameof(gender)) */; this.salutation = salutation /*?? throw new ArgumentNullException(nameof(salutation))*/; } public string firstName { get; protected set; } public string lastName { get; protected set; } public string middleName { get; protected set; } public string nickName { get; protected set; } public string gender { get; protected set; } public string salutation { get; protected set; } public override string ToString() => $"{salutation}. {firstName} {lastName} "; } //public enum Salutation //{ // Mr, // Mrs, //} //public enum Gender //{ // Male, // Female //} }
C#
UTF-8
565
2.734375
3
[]
no_license
using REVISAO_H1.Entidades; using System; namespace REVISAO_H1 { class Program { static void Main(string[] args) { FilaEstaticaInteiros f = new FilaEstaticaInteiros(10); f.Enfilera(10); f.Enfilera(20); f.Enfilera(30); f.Enfilera(40); int t = f.Tamanho(); bool b = f.EstaVazia(); bool b1 = f.EstaCheia(); int x = f.Desenfilera(); Console.WriteLine("Testando fila"); Console.ReadLine(); } } }
JavaScript
UTF-8
1,688
3.34375
3
[]
no_license
(function(){ const Data = []; function newNote(){ //elements const dialog = document.getElementById('dialog'); const title= document.getElementById('inputTile'); const description = document.getElementById('description'); const createBtn = document.getElementById('createBtn'); const saveBtn = document.getElementById('saveBtn'); const closeBtn = document.getElementById('closeBtn'); const reset = document.getElementById('resetBtn'); dialog.style.display = 'block'; function getValues (){ event.preventDefault(); let Note = { title : title.value, description : description.value, date : new Date(), id : null } Data.push(Note); return Note; } //events saveBtn.addEventListener('click', ()=> { getValues(); list(); dialog.close(); createBtn.removeAttribute('disabled'); }); //close the dialog closeBtn.addEventListener('click', function(){ event.preventDefault(); dialog.close(); createBtn.removeAttribute('disabled'); dialog.style.display = 'none'; }); //reset textarea reset.addEventListener('click', function(){ event.preventDefault(); title.value= ''; description.value = ''; }) } function list(){ const listContainer = document.getElementById('list'); const lastItem = Data[Data.length -1].title; const titles = document.createElement('li'); titles.innerText = lastItem; listContainer.appendChild(titles); listContainer.insertBefore(titles, listContainer.childNodes[0]); } createBtn.addEventListener('click', newNote); })();
Python
UTF-8
1,301
2.984375
3
[ "WTFPL" ]
permissive
import sys import time import logging from watchdog.observers import Observer from watchdog.events import LoggingEventHandler class FileWatcher(): def __init__(self, path_to_watch="."): self.path_to_watch = path_to_watch self.event_handler = LoggingEventHandler() self.observer = Observer() self.recursive=True def set_log(self, log_file_path): logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filename=log_file_path ) def schedule(self): self.observer.schedule(self.event_handler, self.path_to_watch, self.recursive) def start(self): self.observer.start() def stop(self): self.observer.stop() def join(self): self.observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: self.observer.stop() self.observer.join() if __name__ == "__main__": path_to_watch = sys.argv[1] if len(sys.argv) > 1 else '.' log_file_path = sys.argv[2] if len(sys.argv) > 2 else None watcher = FileWatcher(path_to_watch) watcher.set_log(log_file_path) watcher.schedule() watcher.join()
TypeScript
UTF-8
1,575
3.625
4
[ "MIT" ]
permissive
/// ----- Shopping Cart Billing ----- /// /* * Complete the 'findLowestPrice' function below. * * The function is expected to return an INTEGER. * The function accepts following parameters: * 1. 2D_STRING_ARRAY products * 2. 2D_STRING_ARRAY discounts */ function findLowestPrice(products: string[][], discounts: string[][]): number { // Write your code here let totalCost = 0; // Create a map of discounts indexed by tag name const disc: { [tag: string]: [string, number] } = {}; for (let i = 0, d = discounts.length; i < d; i++) { let [tag, type, amount] = discounts[i]; disc[tag] = [type, +amount]; } // Iterate over product list for (let j = 0, p = products.length; j < p; j++) { let tags = products[j]; let price = +tags[0]; let min = price; // Iterate over discount tags for (let k = 1, t = tags.length; k < t; k++) { if (tags[k] === "EMPTY") continue; // Apply discount according to type let [type, amount] = disc[tags[k]]; let discountedPrice = price; if (type === "0") { discountedPrice = amount; } else if (type === "1") { discountedPrice -= Math.round((price * amount) / 100); } else { discountedPrice -= amount; } // Update min price if (discountedPrice < min) { min = discountedPrice; } } totalCost += min; } return totalCost; }
Java
UTF-8
3,773
2.234375
2
[]
no_license
package lwj.app; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.web.authentication.WebAuthenticationDetails; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttribute; import org.springframework.web.bind.annotation.SessionAttributes; import lwj.app.models.system.account.Account; import lwj.app.models.system.account.AccountService; import lwj.app.models.system.history.History; import lwj.app.models.system.history.HistoryService; import lwj.app.utils.system.BrowserUtil; import lwj.app.utils.system.LogUtil; /** * Web主函数 * @author LF * */ @Controller @Transactional @SessionAttributes({ "sa_account" }) public class AppLogin { private LogUtil log = new LogUtil(AppLogin.class); @Autowired private AccountService accountService; @Autowired private HistoryService historyService; /** * 登录界面 * @return */ @RequestMapping("/v/login") public String login(@RequestHeader("User-Agent") String useAgent, Model model) { // 判断是否为手机浏览器 if (BrowserUtil.isMoblie(useAgent)) { return "/mobile/login"; } return "/main/login"; } /** * 登录失败 * @return */ @RequestMapping("/loginFailure") public String loginFailure(Model model, HttpSession session) { log.print("loginFailure"); model.addAttribute("failure", null == session.getAttribute("SPRING_SECURITY_LAST_EXCEPTION") ? false : true); return "main/login"; } /** * 登录成功 * @return * @throws Exception */ @RequestMapping("/loginSuccess") public String loginSuccess(History history, Model model) throws Exception { log.print("loginSuccess"); // 取得登录信息 UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); WebAuthenticationDetails webAuthenticationDetails = (WebAuthenticationDetails)SecurityContextHolder.getContext().getAuthentication().getDetails(); Account account = accountService.findOneByAccountId(userDetails.getUsername()); history.setSessionId(webAuthenticationDetails.getSessionId()); // 使用Spring security时生成的SessionId更HttpSession里的不一样 history.setLogMsg("Login success!"); history.setInUser(account); history.setInIp(webAuthenticationDetails.getRemoteAddress()); historyService.save(history); // 设置Session model.addAttribute("sa_account", account); return "redirect:/main"; } /** * 登出 * @return * @throws Exception */ @RequestMapping("/logout") public String logout(History history, @SessionAttribute("sa_account") Account account) throws Exception { log.print("loginSuccess"); // 取得登录信息 WebAuthenticationDetails webAuthenticationDetails = (WebAuthenticationDetails)SecurityContextHolder.getContext().getAuthentication().getDetails(); history.setSessionId(webAuthenticationDetails.getSessionId()); // 使用Spring security时生成的SessionId更HttpSession里的不一样 history.setLogMsg("Login success!"); history.setInUser(account); history.setInIp(webAuthenticationDetails.getRemoteAddress()); historyService.save(history); return "redirect:/"; } }
Java
UTF-8
255
2.71875
3
[]
no_license
package com.alliswell.hashcode; public class Human { String name; int adharano; public Human(String name, int adharano) { this.name = name; this.adharano = adharano; } @Override public int hashCode() { return adharano; } }
C#
UTF-8
3,287
2.609375
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using PBingenering.SQL; using PBingenering.Model; namespace PBingenering { public partial class CreateUserPr : Form { User currentUser; public bool HasAdded { get; private set; } public CreateUserPr(User user) { InitializeComponent(); this.currentUser = user; } private void CreateUser_Load(object sender, EventArgs e) { ClearFieldsUser(); Rol.DataSource = new BindingSource(SqlManager.GetRolView(), null); Rol.DisplayMember = "Value"; Rol.ValueMember = "Key"; } private void ClearFieldsUser() { SurName.Text = string.Empty; IsName.Text = string.Empty; ThirdName.Text = string.Empty; Login.Text = string.Empty; Password.Text = string.Empty; Rol.Text = string.Empty; } private void Rol_SelectedIndexChanged(object sender, EventArgs e) { // MessageBox.Show($"Выбрано:{((KeyValuePair<int, string>)(sender as ComboBox).SelectedItem).Key}"); } private void BtnCreateUser_Click(object sender, EventArgs e) { if (string.IsNullOrEmpty(SurName.Text)) { MessageBox.Show("Фамилия должна быть заполнена."); return; } if (string.IsNullOrEmpty(IsName.Text)) { MessageBox.Show("Имя должно быть заполнено."); return; } if (string.IsNullOrEmpty(ThirdName.Text)) { MessageBox.Show("Отчество должно быть заполнено."); return; } if (string.IsNullOrEmpty(Login.Text)) { MessageBox.Show("Логин должн быть заполнен."); return; } if (string.IsNullOrEmpty(Password.Text)) { MessageBox.Show("Пароль должн быть задан."); return; } if (string.IsNullOrEmpty(Rol.Text)) { MessageBox.Show("Роль должна быть выбрана."); return; } User user = new User(); user.role = new Role(); int index = Rol.SelectedIndex+1; user.Surname = SurName.Text; user.Name = IsName.Text; user.NameName = ThirdName.Text; user.Login = Login.Text; user.Password = Password.Text; user.role.id = ((KeyValuePair<int, string>)Rol.SelectedItem).Key; user.role.Name = ((KeyValuePair<int, string>)Rol.SelectedItem).Value; User writeUser = SqlManager.CreateUser(user); MessageBox.Show("Пользователь создан."); HasAdded = true; ClearFieldsUser(); } } }
C
UTF-8
432
3.734375
4
[]
no_license
#include <stdio.h> #include <string.h> //Find some digits in a fractional part of a number and multiply what you get int main(int argc, char **argv) { char s1[10], s2[1100000]; strcpy(s2, ""); int i; for(i=1; i<190000; i++){ sprintf(s1, "%d", i); strcat(s2, s1); } printf("The product of those digits is %d\n", (s2[0]-48)*(s2[9]-48)*(s2[99]-48)*(s2[999]-48)*(s2[9999]-48)*(s2[99999]-48)*(s2[999999]-48)); return 0; }
Python
UTF-8
3,536
3
3
[]
no_license
from experta import * from questions import ask_question from .facts import Question, Confirmed, DepartureTime, Input, DepartingFrom class DepartureTimeRules: # No departure date specified @Rule(Question('departure_time') & ~Fact(departure_date=W())) def ask_departure_date(self): self.output_question('BOT:\t{}\n'.format(ask_question('departure_time'))) # Departure date, i.e. not the time has been specified @Rule( Question('departure_time') & ~Fact(departure_date=W()) & AS._input << Input()) def departure_date_answered(self, _input): self.retract(_input) self.declare(Fact(departure_date=_input[0])) # No departure time specified @Rule( Question('departure_time') & Fact(departure_date=MATCH.dep_date) & ~Fact(departure_time=W()) & ~Confirmed()) def ask_departure_time(self, dep_date): self.output_question( 'BOT:\tWhen on {} do you want to leave?\n'.format(dep_date)) # Departure time specified @Rule( Question('departure_time') & Fact(departure_date=MATCH.dep_date) & ~Fact(departure_time=W()) & AS._input << Input()) def departure_time_answered(self, dep_date, _input): self.retract(_input) self.declare(Fact(departure_time=_input[0])) # Date and Time both specified @Rule( Question('departure_time') & Fact(departure_date=MATCH.dep_date) & Fact(departure_time=MATCH.dep_time) & ~Confirmed()) def date_time_unconfirmed(self, dep_date, dep_time): self.output_statement('BOT:\tSo you want to leave at {} on {}?'.format( dep_time, dep_date)) self.output_question('BOT:\tIs this right?\n') # Await confirmation @Rule( Question('departure_time') & Fact(departure_date=MATCH.dep_date) & Fact(departure_time=MATCH.dep_time) & AS._input << Input()) def date_time_confirmed(self, dep_date, dep_time, _input): self.retract(_input) # Implement smarted logic for yes or no if _input[0].lower()[0] == 'y': self.declare(Confirmed(True)) elif _input[0].lower()[0] == 'n': self.declare(Confirmed(False)) else: self.output_statement("BOT:\tI'm not sure what you mean by that.") # Departure date/time accepted @Rule(AS.f << Question('departure_time') & Fact(departure_date=MATCH.dep_date) & Fact(departure_time=MATCH.dep_time) & AS.f1 << Confirmed(True) & OR(~DepartingFrom(), DepartingFrom(MATCH.dep_from))) def date_time_accepted(self, dep_date, dep_time, f, f1, dep_from=None): self.retract(f) self.retract(f1) # Summarise the info that's known so far # Handle this more elegantly later if dep_from: self.output_statement( "BOT:\tOkay, so you want to travel from {} at {} on {}.". format(dep_from, dep_time, dep_date)) else: self.output_statement("BOT:\tOkay, I'll make a note of that.") self.declare(DepartureTime(date=dep_date, time=dep_time)) self.declare(Question('departing_to')) # Departure date/time rejected @Rule( Question('departure_time') & AS.f << Fact(departure_date=W()) & AS.f1 << Fact(departure_time=W()) & AS.f2 << Confirmed(False)) def date_time_rejected(self, f, f1, f2): self.retract(f) self.retract(f1) self.retract(f2) self.output_statement('Alright, then.')
Java
UTF-8
208
2.09375
2
[]
no_license
package ba.bitcamp.ludogame; import java.util.Random; public class Utility { public static int getRandomNumber() { Random rand = new Random(); int option = rand.nextInt(6) + 1; return option; } }
C
UTF-8
1,167
3.171875
3
[ "MIT" ]
permissive
/* 例程187. 字符左右排序 整理优化by:千百度QAIU QQ:736226400 编译环境:gcc/tcc 2017/10/25 */ #include<stdio.h> #include<string.h> #include<conio.h> char xx[20][80]; void jsSort() { int i,strl,half,j,k; char ch; for(i=0;i<20;i++) /*行循环*/ { strl=strlen(xx[i]); /*每行长度*/ half=strl/2; for(j=0;j<half-1;j++) /*每行的第j个位置*/ for(k=j+1;k<half;k++) if(xx[i][j]>xx[i][k]) { ch=xx[i][j]; /*每次将最小数赋给xx[i][j]*/ xx[i][j]=xx[i][k]; xx[i][k]=ch; } for(j=half-1,k=strl-1;j>=0;j--,k--) { ch=xx[i][j]; xx[i][j]=xx[i][k]; xx[i][k]=ch; } } } void readDat() { FILE *in; int i=0; char *p; in=fopen("in187.dat","r"); while(i<20&&fgets(xx[i],80,in)!=NULL) { p=strchr(xx[i],'\n'); if(p) *p=0; i++; } fclose(in); } void writeDat() { FILE *out; int i; clrscr(); out=fopen("out187.dat","w"); for(i=0;i<20;i++) { printf("%s\n",xx[i]); fprintf(out,"%s\n",xx[i]); } fclose(out); } void PressKeyToQuit() { printf("\n Press any key to quit..."); getch(); return; } int main() { readDat(); jsSort(); writeDat(); PressKeyToQuit(); return 0; }
Markdown
UTF-8
720
2.65625
3
[]
no_license
# Article 16 Si, lors d'un contrôle en un lieu situé dans une zone protégée, il apparaît que les exigences prévues à l'article 15 ne sont pas respectées, sans préjudice des mesures prévues à l'article R. 251-9 du code rural qui peuvent être prises lorsque les exigences phytosanitaires ne sont pas remplies, les agents chargés de la protection des végétaux peuvent prendre les mesures suivantes : - apposition des scellés sur l'emballage ou, le cas échéant, sur le véhicule transportant ces végétaux, produits végétaux ou autres objets ; - transport, sous leur contrôle, des végétaux, produits végétaux ou autres objets vers une destination extérieure à la zone protégée considérée.
Python
UTF-8
2,736
3.125
3
[ "Apache-2.0" ]
permissive
import copy from hashlib import md5 class TestingDataFrame: def __init__(self, df): self._df = df self._df = self._df.fillna('').astype('str') def __repr__(self): columns = ', '.join(self._df.columns) values = str(self._df.values) return f'Columns: {columns}\n{values}' def _hash_images(self): if 'image' in self._df.columns: self._df['image'] = self._df['image'].apply( lambda c: md5(c.encode()).hexdigest() if c else None ) def _pop_error_columns(self): for column in ('error', 'error_bool'): if column in self._df.columns: self._df.pop(column) def sort(self): columns = sorted(self._df.columns) self._df.sort_values(by=columns, inplace=True) self._df = self._df[columns] def check_errors(self, is_ocr): def check_error_msg(error): if error: assert 'Traceback' in error if 'text' in self._df.columns: pdftotext_error_msg = 'poppler error creating document' assert (pdftotext_error_msg in error) != is_ocr self._df['error'].apply(check_error_msg) def _assert_equal_errors(self, other): check_column = 'error' if check_column not in other._df.columns: self._df['error_bool'] = self._df.pop('error').apply(bool) check_column = 'error_bool' self_values = self._df[check_column].values other_values = other._df[check_column].values return (self_values == other_values).all() def assert_equal(self, expected): if any([self._df.empty, expected._df.empty]): if self._df.empty and expected._df.empty: assert True assert False self_cp = copy.deepcopy(self) expected_cp = copy.deepcopy(expected) self_cp._assert_equal_errors(expected_cp) self_cp._pop_error_columns() expected_cp._pop_error_columns() # Improve visualization for debugging self_cp._hash_images() expected_cp._hash_images() self_cp.sort() expected_cp.sort() # Making debug easier assert list(self_cp._df.columns) == list(expected_cp._df.columns) assert self_cp._df.shape == expected_cp._df.shape assert (self_cp._df.values == expected_cp._df.values).all() def check_and_compare(self, expected, is_ocr=False): self.check_errors(is_ocr) self.assert_equal(expected) def check_and_compare(df, expected, is_ocr=False): expected = TestingDataFrame(expected) df = TestingDataFrame(df) df.check_and_compare(expected, is_ocr)
Python
UTF-8
680
3.078125
3
[ "MIT" ]
permissive
""" Style Transfer """ import os import base64 def transfer(input_image_name, style, color, ratio): """ Load model and perform style transfer on input image :param input_image_name: filename of an input image :param style: a style name before '-' in image filename :return: output_image """ output_image = '../images/output/' + style + '-' if '+' in style: output_image += str(ratio) + '-' output_image += input_image_name.rstrip('.jpg') if color == "True": output_image += '-color' output_image += '.jpg' encoded__output_image = base64.b64encode(open(output_image, 'rb').read()) return encoded__output_image
PHP
UTF-8
4,057
3.09375
3
[]
no_license
<?php require_once("Connection.php"); class Model { protected static $pk; protected static $fields; protected static $identityMap; protected $dirty; public $data; public function __construct($data = []) { $this->data = $data; $this->dirty = false; static::$identityMap[$this->{static::getPk()}] = $this; } public function __set($name, $value) { if (in_array($name, static::getDesc()) && ($name !== static::getPk())) { $this->data[$name] = $value; $this->dirty = true; } } public function __get($name) { if (array_key_exists($name, $this->data)) { return $this->data[$name]; } } protected function setPk($pk, $id) { $this->data[$pk] = $id; } public static function getPk() { if (!static::$pk) { $sql = "DESC " . static::$__table__ . ";"; $query = Connection::get_instance()->prepare($sql); $query->execute(); $desc = $query->fetchAll(PDO::FETCH_ASSOC); foreach ($desc as $value) { if ($value['Extra'] == "auto_increment") { static::$pk = $value['Field']; break; } } } return static::$pk; } public static function getDesc() { if (!static::$fields) { $sql = "DESC " . static::$__table__ . ";"; $query = Connection::get_instance()->prepare($sql); $query->execute(); $desc = $query->fetchAll(PDO::FETCH_ASSOC); foreach ($desc as $value) { static::$fields[] = $value['Field']; if ($value['Extra'] == "auto_increment") { static::$pk = $value['Field']; } } } return static::$fields; } public static function getByPk($pk) { if (!isset(static::$identityMap[$pk])) { $sql = 'SELECT * FROM ' . static::$__table__ . ' WHERE ' . static::getPk() . ' = :pk'; $query = Connection::get_instance()->prepare($sql); $params = [':pk' => $pk]; $query->execute($params); $data = $query->fetch(PDO::FETCH_ASSOC); return new static($data); } else return static::$identityMap[$pk]; } public function save() { if ($this->dirty) { $pk = static::getPk(); list($setArray, $setString) = $this->buildSetValues(); $pdo = Connection::get_instance(); $execute = []; foreach ($setArray as $key => $value) { $execute[":" . $key] = $value; } if (isset($this->data[$pk])) { $sql = "update " . static::$__table__ . " set " . $setString . " where " . $pk . " = " . $this->data[$pk]; $query = $pdo->prepare($sql); $query->execute($execute); } else { $sql = "insert into " . static::$__table__ . " set " . $setString; $query = $pdo->prepare($sql); $query->execute($execute); $id = $pdo->lastInsertId(); $this->setPk($pk, $id); } $this->dirty = false; } } public function buildSetValues () { $setArray = []; $setString = ""; $pk = static::getPk(); foreach ($this->data as $key => $value) { if ($key !== $pk) { $setArray[$key] = $value; $setString .= $key . " = :" . $key . ","; } } return [$setArray, trim($setString, ",")]; } } class Posts extends Model { protected static $__table__ = "posts"; } class Comments extends Model { protected static $__table__ = "comments"; } $post = new Posts(); $post->author = "Maks"; $post->message = "Exp"; $post->save(); $comment = Comments::getByPk(1); $comment->message = "Exp2"; $comment->save();
Rust
UTF-8
138
2.921875
3
[ "MIT", "LicenseRef-scancode-other-permissive", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "NCSA" ]
permissive
fn main() { let x = 3; match x { 1 | 2 || 3 => (), //~ ERROR unexpected token `||` after pattern _ => (), } }
JavaScript
UTF-8
951
4.0625
4
[]
no_license
let arr = [1, [2, [3, 4]]] // function flatten(arr) { // let res = [] // function fla(arr) { // for (item of arr) { // if (typeof item === 'object') { // fla(item) // } else { // res.push(item) // } // } // } // fla(arr) // return res // } // console.log(flatten(arr)); // let arr = [1, [2, [3, 4]]] // function flatten(arr) { // let result = [] // for (let i = 0, len = arr.length; i < len; i++) { // if (arr.isArray(arr[i])) { // result = result.concat(flatten(arr[i])) // } else { // result.push(arr[i]) // } // } // return result // } // reduce // function flatten(arr) { // return arr.reduce(function(pre, next) { // return pre.concat(Array.isArray(next) ? flatten(next) : next) // } , []) // } function flatten(arr) { while (arr.some(item => Array.isArray(item))) { arr = [].concat(...arr) } return arr } console.log(flatten(arr));
C#
UTF-8
1,155
2.96875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class TestOrderedInt : MonoBehaviour { void Start() { TestAddMiddle(); TestRemoveMiddle(); } void TestAddMiddle() { OrderedInt array = new OrderedInt(); array.Add(40); array.Add(42); array.Add(41); Debug.Log("TestAddMiddle"); String arrayString = array.ToString(); if(arrayString.Equals("40,41,42") && array.Count == 3) { Debug.Log("Passed"); } else { Debug.Log("Failed! it not : " + arrayString); } } void TestRemoveMiddle() { OrderedInt array = new OrderedInt(); array.Add(40); array.Add(41); array.Add(42); Debug.Log("TestRemoveMiddle"); bool removed = array.Remove(41); String arrayString = array.ToString(); if (arrayString.Equals("40,42") && array.Count == 2) { Debug.Log("Passed"); } else { Debug.Log("Failed! it not : " + arrayString); } } }
JavaScript
UTF-8
4,508
2.5625
3
[ "MIT" ]
permissive
'using strict'; const fs = require("fs"); const path = require('path'); function _retrieveConfigurationOverrides(argv, profileNameDefault, configLocationDefault) { let temp; let profileNameFinal = profileNameDefault; let configLocationFinal = configLocationDefault; ret = { } for (let j = 0; j < argv.length; j++) { switch(j) { case 0: case 1: break; case 2: temp = "" + argv[j]; if (temp) { profileNameFinal = temp; } break; case 3: temp = "" + argv[j]; if (temp) { configLocationFinal = temp; } break; } } return { "profileName":profileNameFinal, "configLocation":configLocationFinal } } function _normalizeConfigLocation(baseDirectory, configLocation) { return path.isAbsolute(configLocation) ? configLocation : path.normalize(path.join(baseDirectory,configLocation)); } function _mergeProps(source, target) { if (!source || !target) { return; } //var visibleFound = false; for (var key in source) { if (source.hasOwnProperty(key)) target[key] = source[key]; } } function _mergeCommonConfiguration(source, target) { if (source.hasOwnProperty("static")) { let staticConfiguration = source["static"]; if (typeof(staticConfiguration) === 'object') { _mergeProps(staticConfiguration,target); } else { throw new Error("Configuration section 'static' is not an object."); } } else { throw new Error("Cannot locate configuration section 'static'."); } } function _mergeProfileConfiguration(source, target, profileName) { if (source.hasOwnProperty("profiles")) { let profilesConfiguration = source["profiles"]; if (typeof(profilesConfiguration) === 'object') { if (profilesConfiguration.hasOwnProperty(profileName)) { let profileConfiguration = profilesConfiguration[profileName]; if (typeof(profileConfiguration) === 'object') { _mergeProps(profileConfiguration,target); } } else { throw new Error("Cannot locate configuration profile. profileName:" + profileName); } } else { throw new Error("Configuration section 'profiles' is not an object."); } } else { throw new Error("Cannot locate configuration section 'profiles'."); } } class ConfigurationHelper { constructor(profileNameDefault, baseDirectory, configLocationDefault) { this._configuration = {}; this._baseDirectory = baseDirectory this._profileNameDefault = profileNameDefault; this._configLocationDefault = configLocationDefault; } load() { let objOverrides = _retrieveConfigurationOverrides(process.argv, this._profileNameDefault, this._configLocationDefault,); this._profileName = objOverrides["profileName"]; this._configLocation = objOverrides["configLocation"]; this._configuration = {}; let normalizedConfigLocation = _normalizeConfigLocation(this._baseDirectory, this._configLocation) let fileText; try { fileText = fs.readFileSync(normalizedConfigLocation); } catch(e) { //console.error(e); throw new Error("Cannot read configuration file. location:" + normalizedConfigLocation + " details:" + e); } if (!fileText) { throw new Error("Configuration file is empty. location:" + normalizedConfigLocation); } let configSource = {}; try { configSource = JSON.parse(fileText); } catch(e) { //console.error(e); throw new Error("Cannot parse configuration file. location:" + normalizedConfigLocation + " details:" + e); } _mergeCommonConfiguration(configSource,this._configuration); _mergeProfileConfiguration(configSource, this._configuration, this._profileName); //console.dir(this._configuration); } read(key) { return this._configuration.hasOwnProperty(key) ? this._configuration[key] : (arguments.length > 1 ? arguments[1] : null); } } module.exports = { 'Configuration':ConfigurationHelper, };
Markdown
UTF-8
7,547
2.875
3
[]
no_license
--- title: Ruby vs Language Classics --- C • C++ • Perl • Python • PHP • Lua • Java • JavaScript • Erlang ## First Appeared | Lang | First Appeared | |----------------|---------------------| | **Ruby** | 1995; 23 years ago | | | - vs - | | **C** | 1972; 46 years ago | | **C++** | 1985; 33 years ago | | **Erlang** | 1986; 32 years ago | | **Perl** | 1987; 30 years ago | | **Python** | 1991; 26 years ago | | **Lua** | 1993; 25 years ago | | **PHP** | 1995; 23 years ago | | **Java** | 1995; 22 years ago | | **JavaScript** | 1995; 22 years ago | Source: Wikipedia Programming Language Infoboxes ## Designed by / Developers | Lang | Designed by | |----------------|----------------------------------------------------------------------| | **Ruby** | Yukihiro Matsumoto | | | - vs - | | **C** | Dennis Ritchie | | **C++** | Bjarne Stroustrup | | **Erlang** | Joe Armstrong, Robert Virding, Mike Williams | | **Perl** | Larry Wall | | **Python** | Guido van Rossum | | **PHP** | Rasmus Lerdorf | | **Lua* | Roberto Ierusalimschy, Waldemar Celes, Luiz Henrique de Figueiredo | | **Java** | James Gosling | | **JavaScript** | Brendan Eich | Source: Wikipedia Programming Language Infoboxes ## Paradigm | Lang | Paradigm | |----------------|----------------------------------------------------------------------| | **Ruby** | Multi-paradigm: object-oriented, imperative, functional, reflective | | | - vs - | | **C** | Imperative (procedural), structured | | **C++** | Multi-paradigm: procedural, functional, object-oriented, generic | | **Erlang** | Multi-paradigm: concurrent, functional, distributed, process-oriented | | **Perl** | Multi-paradigm: functional, imperative, object-oriented (class-based), reflective, procedural, event-driven, generic | | **Python** | Object-oriented, imperative, functional, procedural, reflective | | **PHP** | Imperative, functional, object-oriented, procedural, reflective | | **Lua** | Multi-paradigm: scripting, imperative (procedural, prototype-based, object-oriented), functional | | **Java** | Multi-paradigm: object-oriented (class-based), structured, imperative, generic, reflective, concurrent | | **JavaScript** | Multi-paradigm: object-oriented (prototype-based), imperative, functional, event-driven | Source: Wikipedia Programming Language Infoboxes ## Typing Discipline _Dynamic vs Static (Manifest vs Inferred) - Strong vs Weak - Duck (Structural) vs Explicit Interface / Protocol Declarations_ | Lang | Typing Discipline | |----------------|----------------------------------------------------------------------| | **Ruby** | Dynamic, strong, duck | | | - vs - | | **Perl** | Dynamic | | **Python** | Dynamic, strong, duck | | **PHP** | Dynamic, weak | | **Lua** | Dynamic, strong, duck | | **Erlang** | Dynamic, strong | | **JavaScript** | Dynamic, duck | | | | | **C** | Static, weak, manifest, nominal | | **C++** | Static, nominative, partially inferred | | **Java** | Static, strong, safe, nominative, manifest | Source: Wikipedia Programming Language Infoboxes ## Influenced by | Lang | Influenced by | |----------------|----------------------------------------------------------------------| | **Ruby** | Ada, C++, CLU, Dylan, Eiffel, Lisp, Lua, Perl, Python, Smalltalk | | | - vs - | | **C** | B (BCPL, CPL), ALGOL 68, Assembly, PL/I, FORTRAN | | **C++** | Ada, ALGOL 68, C, CLU, ML, Simula | | **Perl** | AWK, C, C++, Lisp, Pascal, sed, Smalltalk 80, Unix shell | | **Python** | ABC, ALGOL 68, C, C++, CLU, Dylan, Haskell, Icon, Java, Lisp, Modula-3, Perl | | **PHP** | Perl, C, C++, Java, Tcl | | **Lua** | C++, CLU, Modula, Scheme, SNOBOL | | **Erlang** | Prolog, Smalltalk, PLEX, LISP | | **Java** | Ada 83, C++, C#, Eiffel, Generic Java, Mesa, Modula-3, Oberon, Objective-C, UCSD Pascal, Object Pascal | | **JavaScript** | Lua, Scheme, Perl, Self, Java, C, Python, AWK, HyperTalk | Source: Wikipedia Programming Language Infoboxes ## Influenced | Lang | Influenced | |----------------|----------------------------------------------------------------------| | **Ruby** | Clojure, CoffeeScript, Crystal, D, Elixir, Falcon, Groovy, Ioke, Julia, Mirah, Nu, Reia, Ring, Rust, Swift | | | - vs - | | **C** | Numerous: AMPL, AWK, csh, C++, C--, C#, Objective-C, BitC, D, Go, Java, JavaScript, Julia, Limbo, LPC, Perl, PHP, Pike, Processing, Python, Ring, Rust, Seed7, Vala, Verilog (HDL) | | **C++** | Ada 95, C#, C99, Chapel, D, Java, Lua, Perl, PHP, Python, Rust, Nim | | **Perl** | CoffeeScript, ECMAScript, Falcon, Groovy, JavaScript, Julia, LPC, Perl 6, PHP, Python, **Ruby**, Windows PowerShell | | **Python** | Boo, Cobra, Coconut, CoffeeScript, D, F#, Falcon, Genie, Go, Groovy, JavaScript, Julia, Nim, Ring, **Ruby**, Swift | | **PHP** | Falcon, Hack | | **Lua** | Falcon, GameMonkey, Io, JavaScript, Julia, MiniD, Red, Ring, **Ruby**, Squirrel, MoonScript | | **Erlang** | F#, Clojure, Rust, Scala, Opa, Reia, Elixir, Dart, Akka, Oz | | **Java** | Ada 2005, BeanShell, C#, Chapel, Clojure, ECMAScript, Fantom, Gambas, Groovy, Hack, Haxe, J#, JavaScript, Kotlin, PHP, Python, Scala, Seed7, Vala | | **JavaScript** | ActionScript, AtScript, CoffeeScript, Dart, JScript .NET, LiveScript, Objective-J, Opa, Perl 6, QML, TypeScript | Source: Wikipedia Programming Language Infoboxes
C#
UTF-8
4,422
2.875
3
[]
no_license
using Blueberry; using Blueberry.Graphics; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DN { public enum CellType:byte { Free = 0, Wall = 1, Ladder = 2, VRope = 3 } public class TileMap { private Texture _wallTile; private Texture _stairTile; private CellType[,] _map; public CellType this[int i, int j] { get { return _map[i, j]; } set { _map[i, j] = value; } } public readonly int Width; public readonly int Height; public TileMap(int width, int height) { Width = width; Height = height; _map = new CellType[Width, Height]; } public void InitTextures() { _wallTile = CM.I.tex("wall_tile"); _stairTile = CM.I.tex("stair_tile"); } public void FillWith(CellType cellType) { FillWith(_map, Width, Height, cellType); } static public void FillWith(CellType[,] map, int width, int height, CellType cellType) { for (var i = 0; i < width; i++) for (var j = 0; j < height; j++) map[i, j] = cellType; } public Rectangle GetRect(int x, int y) { return new Rectangle(x * 64, y * 64, 64, 64); } public Rectangle GetRect(Point pos) { return new Rectangle(pos.Y * 64, pos.Y * 64, 64, 64); } public bool IsFree(Point p) { return _map[p.X, p.Y] == CellType.Free; } public bool IsFree(int x, int y) { return _map[x, y] == CellType.Free; } public List<Rectangle> GetRectanglesAround(Point p, CellType cellType) { List<Rectangle> rects = new List<Rectangle>(); for (int i =Math.Max(0, p.X - 1); i <= p.X + 1; i++) { for (int j = Math.Max(0, p.Y - 1); j <= p.Y + 1; j++) { // if (_map[i, j] != cellType) rects.Add(GetRect(i, j)); } } return rects; } public void Draw(Rectangle region) { Size ts = _wallTile.Size; int ifrom = Math.Max(0, region.Left); int ito = Math.Min(region.Right, Width); int jfrom = Math.Max(0, region.Top); int jto = Math.Min(region.Bottom, Height); for (int i = ifrom; i < ito; i++) { for (int j = jfrom; j < jto; j++) { switch(_map[i,j]) { case CellType.Wall: SpriteBatch.Instance.DrawTexture(_wallTile, i * ts.Width, j * ts.Height, ts.Width, ts.Height, Rectangle.Empty, Color.White, 0, 0, 0); break; } } } for (int i = ifrom; i < ito; i++) { for (int j = jfrom; j < jto; j++) { switch (_map[i, j]) { case CellType.Ladder: SpriteBatch.Instance.DrawTexture(_stairTile, i * ts.Width, j * ts.Height, ts.Width, ts.Height, Rectangle.Empty, Color.White, 0, 0, 0); break; case CellType.VRope: SpriteBatch.Instance.DrawTexture(_stairTile, i * ts.Width, j * ts.Height, ts.Width, ts.Height, Rectangle.Empty, Color.Brown, 0, 0, 0); break; } } } } public bool InRange(Point cell) { return InRange(cell.X, cell.Y); } public bool InRange(int x, int y) { return x >= 0 && x < Width && y >= 0 && y < Height; } public void PrintDebug() { for (int j = 0; j < Height; j++) { Console.WriteLine(); for (int i = 0; i < Width; i++) { Console.Write((byte)_map[i,j]); } } } } }
Java
UTF-8
3,377
2.421875
2
[]
no_license
/* * Copyright (C) 2012 Krawler Information Systems Pvt Ltd * All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package jyuicompressor; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.Thread; import javax.print.DocFlavor.STRING; /** * * @author pm */ public class UseThread extends Thread { public int jscount = 0; /** Creates a new instance of UseThread */ public void run() { File sourcedir = new File("E:\\javaproj\\wtfesp\\web\\"); File sourcedir1 = new File("E:\\javaproj\\wtfesp\\web\\scripts\\"); File sourcedir2 = new File("E:\\javaproj\\wtfesp\\web\\lib\\"); CompressFiles(sourcedir); System.out.println("Number of files processed: " + jscount); } private void CompressFiles(File sourcedir) { if (sourcedir.exists()) { File[] files = sourcedir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) CompressFiles(files[i]); else { String type = ""; if (files[i].getName().endsWith(".js")) type = ".js"; else if (files[i].getName().endsWith(".css")) type = ".css"; if (type != "") { File tempfile = new File(jscount + "temp" + type); try { copyFile(files[i], tempfile); String cmd = "java -jar yuicompressor-2.2.5.jar --charset UTF-8 -o " + files[i].getAbsolutePath() + " " + tempfile.getAbsolutePath() + " 2>&1"; // java -jar yuicompressor-x.y.z.jar myfile.js -o // myfile-min.js Process p = Runtime.getRuntime().exec(cmd, null); InputStream es = p.getErrorStream(); // tempfile.delete(); System.out.println("Executing: " + cmd); System.out.println("FILE" + jscount + ": " + files[i].getAbsolutePath()); byte[] buf = new byte[4096]; int len; while ((len = es.read(buf)) != -1) { System.out.println(new String(buf)); } es.close(); sleep(50); } catch (Exception ex) { // ex.printStackTrace(); System.out.println("FILE(failed to process): " + files[i].getAbsolutePath()); } jscount++; } } } } else System.out.println("No directory present with this name"); } public void copyFile(File in, File out) throws Exception { FileInputStream fis = new FileInputStream(in); FileOutputStream fos = new FileOutputStream(out); byte[] buf = new byte[1024]; int i = 0; while ((i = fis.read(buf)) != -1) { fos.write(buf, 0, i); } fis.close(); fos.close(); } }
Java
UTF-8
1,777
2.265625
2
[]
no_license
package ru.taxofon.dao.impl; import ru.taxofon.dao.DamageListDao; import ru.taxofon.entity.DamageList; import javax.persistence.Query; import java.util.List; public class DamageListDaoImpl extends BasicDaoImpl<DamageList> implements DamageListDao { public DamageListDaoImpl(Class<DamageList> entityClass) { super(entityClass); } @Override public List<DamageList> getDamageByTlfNum(String tlfNum, boolean closed) { Query query; if (closed){ query = getSessionFactory().createQuery("SELECT d FROM DamageList as d WHERE d.tlfnum = :tlfnum"); } else { query = getSessionFactory().createQuery("SELECT d FROM DamageList as d WHERE d.tlfnum = :tlfnum AND d.dateTimeEnd = null"); } query.setParameter("tlfnum", tlfNum); return query.getResultList(); } @Override public List<DamageList> getDamageByDescription(String description, boolean closed) { Query query; if (closed){ query = getSessionFactory().createQuery("SELECT d FROM DamageList as d WHERE d.description = :description"); } else { query = getSessionFactory().createQuery("SELECT d FROM DamageList as d WHERE d.description = :description AND d.dateTimeEnd = null"); } query.setParameter("description", description); return query.getResultList(); } @Override public List<DamageList> getDamageAll(boolean closed) { Query query; if (closed){ query = getSessionFactory().createQuery("SELECT d FROM DamageList as d"); } else { query = getSessionFactory().createQuery("SELECT d FROM DamageList as d WHERE d.dateTimeEnd = null"); } return query.getResultList(); } }
PHP
UTF-8
380
2.53125
3
[]
permissive
<?php namespace common\fixtures\helpers; interface FixtureTester { public function haveFixtures($fixtures); public function grabFixture($name, $index = null); public function seeRecord(string $class, array $array); /** * @param string $className * @param array $attributes * @return mixed */ public function haveRecord(string $className, array $attributes); }
Python
UTF-8
1,752
3.015625
3
[ "MIT" ]
permissive
__author__ = 'Robert Havelaar, with help from group c Study group. ' from morse_dict import MORSE_2_ASCII import re # This module provides regular expression # matching operations similar to # those found in Perl. # def decode_bits(bits): pattern_one = re.split(r'(0+)', bits.strip('0')) unit_rate = len(sorted(pattern_one, key=len)[0]) results = [] for match in pattern_one: if '1' in match: if len(match) // unit_rate == 1: results.append('.') else: results.append('-') else: if len(match) // unit_rate == 1: results.append('') elif len(match) // unit_rate == 3: results.append(' ') else: results.append(' ') clean = ''.join(results) return clean def decode_morse(morse): pattern = re.split(r'(\s+)', morse) results = [] for match in pattern: if match == ' ': results.append(match) elif match in MORSE_2_ASCII: results.append(MORSE_2_ASCII[match]) clean_up = ''.join(results).replace(" ", " ").strip() return clean_up if __name__ == '__main__': hey_jude_morse = ".... . -.-- .--- ..- -.. ." hey_jude_bits = "11001100110011000000110000001111110011001111110011111100000000000000000000011001111110011111100111111000000110011001111110000001111110011001100000011" # noqa # Be sure to run all included unit tests, not just this one. print("Morse Code decoder test") print("Part A:") print(f"'{hey_jude_morse}' -> {decode_morse(hey_jude_morse)}") print() print("Part B:") print(f"'{hey_jude_bits}' -> {decode_morse(decode_bits(hey_jude_bits))}") print("\nCompleted.")
Markdown
UTF-8
6,344
2.609375
3
[]
no_license
# disk io 阻塞引发 golang 线程数暴涨的问题 我们知道golang对用户抽象了协程,协程要跑起来必然是需要系统线程来承载上下文,因为线程是最小的调度单元。golang的scheduler会帮你调度关联 PMG,这里的M是线程,G就是我们在golang里用go关键字spawn的协程。 对于用户来说,你是看不到也无法创建native thread原生线程的。 不管是golang nuts和golang issue里有人提过native thread feature的需求,但社区给出的论调是没必要,如果有必要那么可以用cgo,或者手动触发runtime.LockOSThread绑定。 golang抽象了pmg,我们通常不会特意的去关注某个golang线程数目,但上次就遇到了golang线程异常暴增, 最多的时候涨到1300多个线程。那我们知道线程过多有什么问题? 每个pthread的stack栈空间是8MB, 当然是virt, 这些线程也会增加kernel的调度成本,光上下文切换就不是闹的。当然golang 不会这么傻,不会让这么多的线程去轮询P上下文队列, 应该会有条件变量去控制调度。 ## golang 线程暴增的原因? 什么问题会导致产生这么多的线程? 我先告诉大家答案,在我的这个场景下是 因为磁盘io问题引起的。 因为一些杂七杂八的程序都在这台主机,iops过高,又因为是阿里云磁盘性能低下,又又因为内存被占用的差不多了…. 首先我们知道 golang写文件是阻塞,后面会说明原因。当我们写日志一般是先写到内核的page cache里,然后再由kernel通过阈值或定时刷新到磁盘,而不会像数据库那样调用fsync来磁盘落地。 既然先写到page cache内存里应该很快呀。 但这台服务器上有不少相关的服务在跑,在压测的场景下会产生大量的日志,而大量的日志都会扔到page cahe里,但刚才说了不少相关的服务都在一台阿里云主机上,虽然这台阿里云是高配,但相关服务都是吃内存不吐骨头的角色,导致page cache的内存明显少了。既然内存少了,那么kernel调用sync来持久化,但又因为阿里云主机的磁盘io吞吐很可悲,导致不能很快的flush到磁盘上。 那么就导致golang写日志的线程越来越多。 golang runtime是有个sysmon的协程,他会轮询的检测所有的P上下文队列,只要 G-M 的线程长时间在阻塞状态,那么就重新创建一个线程去从runtime P队列里获取任务。先前的阻塞的线程会被游离出去了,当他完成阻塞操作后会触发相关的callback回调,并加入回线程组里。简单说,如果你没有特意配置runtime.SetMaxThreads,那么在可没有复用的线程下会一直创建新线程。 golang默认的最大线程数10000个线程,这个是硬编码。 如果想要控制golang的pthread线程数可以使用 runtime.SetMaxThreads() 。 ![https://xiaorui.cc/wp-content/uploads/2018/04/20180421093608_90448.jpg](https://xiaorui.cc/wp-content/uploads/2018/04/20180421093608_90448.jpg) ## golang 磁盘io问题? golang针对网络io使用了epoll事件机制来实现了同步非阻塞,但磁盘io用不了这套,首先 io fd 没有实现 Poll 接口,另外磁盘始终是就绪状态,而 epoll 是根据事件就绪通知,就绪 & 非就绪状态。 现在常见的一些高性能框架都没有直接的解决磁盘io异步非阻塞问题。 像nginx之前读写磁盘会阻塞worker进程,只有开启aio及线程池thread才会绕开阻塞问题。 可以说,整个linux下的 aio 不是很完善。新内核有个 io_uring 机制,不仅可监听常规的 net fd,也可监听文件 fd。 ## 如何分析问题? 下面说下分析问题的过程, 首先通过ps和pprof看到golang的线程数,然后通过golang stack分析出当前的调用栈逻辑,继而通过strace来追踪系统调用情况。 golang stack没啥好说的,写日志阻塞那么调用栈里会显示不少log的调用情况。 那么我们主要来分析下,写日志和创建线程是怎么做的关联 ? 很简单就两个工具,一个是strace, 一个是 lsof 。 通过strace是可以看到write(8) fd的时候会mmap mprotect clone创建线程, 通过lsof 可以看到8是一个日志文件。配合Prometheus监控是可以看出iostat过高的时候,线程的数目也会跟着增长起来。 因为其他原因系统的内存也在减少,所以引起page cache不断刷盘。 ![https://xiaorui.cc/wp-content/uploads/2018/04/20180421101626_47324.jpg](https://xiaorui.cc/wp-content/uploads/2018/04/20180421101626_47324.jpg) 下面是用 golang pprof 观测到的数据,可以看到1009个线程. ![https://xiaorui.cc/wp-content/uploads/2018/04/20180421095449_51622.jpg](https://xiaorui.cc/wp-content/uploads/2018/04/20180421095449_51622.jpg) 当前的磁盘io使用情况, utils表示 长时间io吞吐 100% ![https://xiaorui.cc/wp-content/uploads/2018/04/20180421100759_74405.jpg](https://xiaorui.cc/wp-content/uploads/2018/04/20180421100759_74405.jpg) 通过Prometheus查看io wait的趋势, 下面的图表可以看出io等待时间还是蛮高的。 ![https://xiaorui.cc/wp-content/uploads/2018/04/20180423142119_77419.jpg](https://xiaorui.cc/wp-content/uploads/2018/04/20180423142119_77419.jpg) ## 怎么解决? 上面说了,磁盘io造成golang线程暴涨是有很多原因的? 比如内存太小呀,日志输出太多呀,磁盘吞吐不行呀,各种各样的。 我们的解决方法是 首先限制runtime的线程数为200个 ( runtime.SetMaxThreads ),一般正常情况下都够用了。 通常24 core cpu的环境下,一个高频的proxy服务正常压测也才80多个线程。 这里主要还是为了避免预防各种未知诡异问题。 另外线上把服务的日志级别调高到warn警告,别整个debug level,导致io疯狂输出。 据我的测试,剩余的内存如果够大,也是可以减少线程的异常增长, 毕竟写日志O_APPEND按道理是速度很快的顺序io。 ## 总结 到此为止,golang线程暴增的问题差不多说完了。写这篇文章废了不少时间,其实发现问题 到 解决问题,一共也才十来分钟。当大家遇到一些性能问题时,使用golang pprof及性能工具来检查, 比较容易就可以定位问题。
PHP
UTF-8
2,066
3.328125
3
[]
no_license
<?php class Eleve { private $_id; private $_nom; private $_prenom; private $_adresse; private $_ville; private $_cp; private $_tel; public function __construct(array $donnees) { $this->hydrate($donnees); } public function hydrate (array $donnees) { foreach($donnees as $key => $value ) { $method = 'set'.ucfirst($key); if (method_exists($this, $method)) { $this->$method($value); } } } public function id() { return $this->_id; } public function nom() { return $this->_nom; } public function prenom() { return $this->_prenom; } public function adresse() { return $this->_adresse; } public function ville() { return $this->_ville; } public function cp() { return $this->_cp; } public function tel() { return $this->_tel; } public function setId($id) { $id = (int) $id; if ($id >0) { $this->_id = $id; } } public function setNom($nom) { if(is_string($nom)) { $this->_nom = $nom; } } public function setPrenom($prenom) { if(is_string($prenom)) { $this->_prenom = $prenom; } } public function setAdresse($adresse) { if(is_string($adresse)) { $this->_adresse = $adresse; } } public function setVille($ville) { if(is_string($ville)) { $this->_ville = $ville; } } public function setCp($cp) { if(is_string($cp)) { $this->_cp = $cp; } } public function setTel($tel) { if(is_string($tel)) { $this->_tel = $tel; } } } ?>
C++
UTF-8
486
3.09375
3
[]
no_license
#include<vector> using namespace std; class Solution { public: int maxProfit(vector<int> &prices) { int pre = -1; int profit = 0; for(int& i: prices) { if (pre == -1) { pre = i; } else { if (i >= pre) { profit += (i - pre); pre = i; } else { pre = i; } } } return profit; } };