language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
PHP
UTF-8
1,322
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\eegt\Repositories; use App\eegt\Interfaces\BackendRepositoryInterface; use App\Research; use App\Visit; //komunikacja z BD class BackendRepository implements BackendRepositoryInterface { //znajdz wszystkie wizyty public function getAllVisits() { return Visit::with('user', 'research', 'research_hours')->orderBy('research_id')->get(); } //znajdz wszystkie badania public function getAllResearch() { return Research::orderBy('research_id')->get(); } public function getResearch($research_id) { return Research::find($research_id); } public function deleteResearch(Research $research) { //wykonaj met delete na obiekcie room z param return $research->delete(); } public function updateResearch($request, $research_id) { if($request->research_id == $research_id) return Research::where('research_id', $research_id)->update([ 'research_id' => $research_id, 'research_name' => $request->research_name, 'description' => $request->description, 'research_date' => $request->research_date, 'availability' => $request->availability, ]); else return false; } }
Java
UTF-8
2,212
3.703125
4
[]
no_license
/* Project: * Longest Increasing Sub-sequence (LIS) * Given an array, finds its longest increasing * subsequence using dynamic programming * Complexity: O(n^2) * */ public class LCS { private static int SubsequenceLength(int[] array_sequence) { int int_sequence_length = array_sequence.length;//get number of integers in set int[] array_best = new int[int_sequence_length];//create a copy of the set array //initialize array_best[0] = 1;//base case int int_max = 0; int int_max_index = 0; //build the array containing the length of the LIS. //keep track of the longest LIS with int_max / int_max_index. for (int i = 0; i < int_sequence_length; i++){ for (int j = 0; j < i; j++){ if( (array_sequence[i] > array_sequence[j] && (array_best[i] < array_best[j] + 1) )) { array_best[i] =array_best[j] + 1; }//end j if (array_best[i] > int_max) { int_max = array_best[i]; int_max_index = i; } //end i int k = int_max+1; int[] lis = new int[k ]; for(int i = int_max_index; i >0; i--) { if (array_best[i] == k-1) { lis[k-1] = (array_sequence[i]); k = array_best[i]; } } //print the LIS System.out.print("["); for (int i = 0; i < lis.length; i++) { System.out.print( lis[i] +" "); } System.out.println("]"); return int_max + 1; //return length of LIS } //end method public static void testProgram(){ int[ ] Seq1 = {9,5,2,8,7,3,1,6,4}; int[ ] Seq2= {11, 17, 5, 8, 6, 4, 7, 12, 3}; System.out.println("length - " + SubsequenceLength(Seq1)); System.out.println("length - " + SubsequenceLength(Seq2)); } public static void main(String[] args) { testProgram(); }//end main }//end class public static int increasingSubsequence(int[]seq) { int[]L = new int[seq.length]; L[0] = 1; for (int i = 1; i < L.length; i++) { int maxn=0; for(int j = 0; j < i; j++) { if(seq[j] < seq[i] && L[j] > maxn) { maxn=L[j]; } } L[i]=maxn+1; } int maxi=0; for(int i = 0;i < L.length; i++) { if(L[i] > maxi) { maxi = L[i]; } } return(maxi); }
Markdown
UTF-8
262
2.90625
3
[]
no_license
# Image-Inversion Program to create new images that are photographic negatives (or inverted images) of selected images and save these new images with filenames that are related to the original images, such as adding “inverted-” in front of the old filename.
Java
UTF-8
589
2.125
2
[ "Apache-2.0" ]
permissive
package br.indie.fiscal4j.nfe310.transformers; import br.indie.fiscal4j.nfe310.classes.NFNotaInfoCombustivelTipo; import org.simpleframework.xml.transform.Transform; public class NFNotaInfoCombustivelTipoTransformer implements Transform<NFNotaInfoCombustivelTipo> { @Override public NFNotaInfoCombustivelTipo read(final String codigoCombustivelTipo) { return NFNotaInfoCombustivelTipo.valueOfCodigo(codigoCombustivelTipo); } @Override public String write(final NFNotaInfoCombustivelTipo combustivelTipo) { return combustivelTipo.getCodigo(); } }
C#
UTF-8
5,845
2.640625
3
[ "MIT" ]
permissive
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AISteeringController : MonoBehaviour { public Agent agent; [Header("Steering Settings")] public float maxSpeed = 6.0f; public float maxForce = 10.0f; public float fleeSeekDist = 10.0f; [Header("List of behaviours")] List<SteeringBehavior> steerings = new List<SteeringBehavior>(); [Header("Important Transforms")] public Transform seekTarget; public PathFindingBehavior pathFinder; private Tile currentTile; private Tile targetTile; private Tile attackTile; public GameObject obstaclePrefab; protected Vector3 CalculateSteeringForce() { Vector3 steeringForce = Vector3.zero; float dist = Vector3.Distance(seekTarget.position, transform.position); //choosing our action if (dist < fleeSeekDist) { steeringForce += steerings[1].Steer(this, fleeSeekDist); //fleeing }else if (dist > fleeSeekDist + 5.0f) { steeringForce += steerings[0].Steer(this, fleeSeekDist); //seeking } else { findAttackTile(); attackTile.isWalkable = false; GameObject tmpObstacle = Instantiate(obstaclePrefab, attackTile.transform.position, transform.rotation); } //clamp it steeringForce = Vector3.ClampMagnitude(steeringForce, maxForce); return steeringForce; } protected Vector3 WalkTheRoad(Tile pathTarget) { return (pathTarget.transform.position - transform.position).normalized * maxSpeed; } public bool checkObstacles(Vector3 direction) //gonna try and use the steering force as a direction { //I plan to use a raycast to check obstacles or walls in front of the enemy AI int layerMask = 1 << 9; //setting the layer mask so it will only collide with objects on layer 9 RaycastHit hit; //setting our hit //these will also call a method that will adjust for the obstacle avoidance if (Physics.Raycast(transform.position, direction, out hit, Mathf.Infinity, layerMask)) //shooting the raycast { return true; } else { return false; } //okay this works now I have to program something to move around the obstacle, maybe I should go back to the A* pathfinding to seek my way around the obstacle } public void setCurrentTile() { int layerMask = 1 << 8; RaycastHit hit; if(Physics.Raycast(transform.position, Vector3.down, out hit, Mathf.Infinity, layerMask)) { currentTile = hit.transform.GetComponent<Tile>(); } } public void findTargetTile() { int layerMask = 1 << 8; RaycastHit hit; Vector3 angleFourtyFive = new Vector3(0, -1, 10); angleFourtyFive = agent.transform.TransformDirection(angleFourtyFive); if (Physics.Raycast(transform.position, angleFourtyFive , out hit, Mathf.Infinity, layerMask)) { targetTile = hit.transform.GetComponent<Tile>(); } } public void findAttackTile() { int layerMask = 1 << 8; RaycastHit hit; Vector3 angleFourtyFive = new Vector3(0, -1, 5); angleFourtyFive = agent.transform.TransformDirection(angleFourtyFive); if (Physics.Raycast(transform.position, angleFourtyFive, out hit, Mathf.Infinity, layerMask)) { attackTile = hit.transform.GetComponent<Tile>(); } } private void Start() //I don't see a world where I will ever "call" the Start method since it will be used when the program starts { steerings.Add(new SeekSteering { target = seekTarget }); //in the start we'd add all the different behaviours steerings.Add(new FleeSteering { target = seekTarget }); } private void Update()//another method that auto activates and shouldn't be called by me { setCurrentTile(); findTargetTile(); Vector3 steeringForce = CalculateSteeringForce(); agent.velocity = Vector3.ClampMagnitude(agent.velocity + steeringForce, maxSpeed); //give em the clamps clamps if(agent.velocity != Vector3.zero) agent.transform.forward = agent.velocity; if (!checkObstacles(steeringForce)) { agent.UpdateMovement(); } else { //we're going to steer down the optimal tile path using seek with the target on every tile in the returned path list List<Tile> avoidObstacle = pathFinder.FindPath(currentTile,targetTile); for(int i = 0; i < avoidObstacle.Count; i++) { steeringForce = WalkTheRoad(avoidObstacle[i]); steeringForce.y = 0; agent.velocity = Vector3.ClampMagnitude(agent.velocity + steeringForce, maxSpeed); //give em the clamps clamps agent.UpdateMovement(); } } } }//Steering controller public class SteeringBehavior { public virtual Vector3 Steer(AISteeringController controller, float fleeSeekDist) { return Vector3.zero; } } public class SeekSteering : SteeringBehavior { public Transform target; public override Vector3 Steer(AISteeringController controller, float fleeSeekDist) { return (target.position - controller.transform.position).normalized * controller.maxSpeed; } } //going to need these two get pursue working public class FleeSteering : SteeringBehavior { public Transform target; public override Vector3 Steer(AISteeringController controller,float fleeSeekDist) { return (controller.transform.position - target.position).normalized * controller.maxSpeed; } }
C++
UTF-8
490
2.515625
3
[]
no_license
#pragma once #ifndef __DustParticleH__ #define __DustParticleH__ #include "ParticleBase.h" // Class is 16-bit aligned to allow use of SIMD member variables __declspec(align(16)) class DustParticle : public ALIGN16<DustParticle>, public ParticleBase { public: // Force the use of aligned allocators to distinguish between ambiguous allocation/deallocation functions in multiple base classes USE_ALIGN16_ALLOCATORS(DustParticle) DustParticle(void); ~DustParticle(void); }; #endif
Java
UTF-8
2,009
2.671875
3
[]
no_license
package concurrency.java.wrappers.isg.jobs; import java.util.concurrent.Callable; import java.util.concurrent.atomic.AtomicLong; import concurrency.java.wrappers.isg.threads.JobListener; /** * * * @author EMAIL:vuquangtin@gmail.com , tel:0377443333 * @version 1.0.0 * @see <a * href="https://github.com/vuquangtin/concurrency">https://github.com/vuquangtin/concurrency</a> * */ public class SendMsgJob<V> extends MyJob implements Callable { public static AtomicLong jobsProcessed = new AtomicLong(0); private MessageSender msgSender; private Object sharedLock; private static AtomicLong msgNumber = new AtomicLong(0); public SendMsgJob(String myName, JobListener myJobListener) { super(myName, myJobListener); } public SendMsgJob(Object mySharedLock) { super(null, null); this.sharedLock = mySharedLock; } @Override public void run() { msgNumber.incrementAndGet(); try { System.out.println("sending msg....msgNumber : " + msgNumber); try { synchronized (this) { if (msgSender == null) msgSender = new MessageSender(); } msgSender.sendTextToQueue(); } catch (Exception e) { e.printStackTrace(); } } finally { jobListener.jobDone(Thread.currentThread()); } } @Override public int compareTo(Object obj) { SendMsgJob thatJob = (SendMsgJob) obj; if (timeOfCreation > thatJob.timeOfCreation) return 1; return 0; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public Object call() throws Exception { msgNumber.incrementAndGet(); try { System.out.println("sending msg....msgNumber : " + msgNumber); try { synchronized (this) { if (msgSender == null) msgSender = new MessageSender(); } msgSender.sendTextToQueue(); } catch (Exception e) { e.printStackTrace(); } } finally { jobListener.jobDone(Thread.currentThread()); jobsProcessed.incrementAndGet(); } return jobsProcessed; } }
JavaScript
UTF-8
401
3.75
4
[]
no_license
function randomize(array) { let randomDictionary = {}; let results = []; while (Object.keys(randomDictionary).length < array.length) { index = getRandomIndex(array.length); if (!randomDictionary[index]) { randomDictionary[index] = true; results.push(array[index]); } } return results; } function getRandomIndex(num) { return Math.ceil(Math.random() * num) - 1; }
Rust
UTF-8
385
2.609375
3
[ "BSD-3-Clause" ]
permissive
pub use url::Url as Uri; pub fn to_uri(uri_like: &str) -> Uri { let path = std::fs::canonicalize(uri_like).unwrap(); let mut path_str = path.as_path().to_str().unwrap().to_string(); if cfg!(windows) { path_str = path_str.split_off(4); path_str = path_str.replace('\\', "/"); } let uri_str = format!("file://{}", path_str); Uri::parse(uri_str.as_str()).unwrap() }
PHP
UTF-8
1,216
2.78125
3
[ "MIT" ]
permissive
<?php namespace Dnetix\Redirection\Validators; use Dnetix\Redirection\Entities\Recurring; class RecurringValidator extends BaseValidator { const PERIOD_DAY = 'D'; const PERIOD_MONTH = 'M'; const PERIOD_YEAR = 'Y'; public static $PERIODS = [ self::PERIOD_DAY, self::PERIOD_MONTH, self::PERIOD_YEAR, ]; /** * @param Recurring $entity * @param $fields * @return bool */ public static function isValid($entity, &$fields) { $errors = []; if (!in_array($entity->periodicity(), self::$PERIODS)) { $errors[] = 'periodicity'; } if (!self::isInteger($entity->interval())) { $errors[] = 'interval'; } if (!$entity->nextPayment() || !self::isActualDate($entity->nextPayment())) { $errors[] = 'nextPayment'; } if (!self::isInteger($entity->maxPeriods())) { $errors[] = 'maxPeriods'; } if ($entity->dueDate() && !self::isActualDate($entity->dueDate())) { $errors[] = 'dueDate'; } if ($errors) { $fields = $errors; return false; } return true; } }
Swift
UTF-8
1,662
2.625
3
[]
no_license
import UIKit class SideMenuTableView:UITableView { weak var menu:SideMenu? var items:[MenuItem]! init(menu:SideMenu,items:[MenuItem]) { super.init(frame: .zero, style: UITableView.Style.plain) self.items = items translatesAutoresizingMaskIntoConstraints = false backgroundColor = .clear separatorStyle = .none self.menu = menu register(SideMenuItemCell.self, forCellReuseIdentifier: "menuItem") delegate = self dataSource = self } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension SideMenuTableView:UITableViewDelegate,UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let menuItem = items[indexPath.row] let cell = tableView.dequeueReusableCell(withIdentifier: "menuItem", for: indexPath) as! SideMenuItemCell cell.menuItem = menuItem return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 50 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let item = items[indexPath.row] menu?.didSelectItem(item: item) } } // // SideMenuTableView.swift // Conapeme 2019 // // Created by LUIS ENRIQUE MEDINA GALVAN on 2/20/19. // Copyright © 2019 LUIS ENRIQUE MEDINA GALVAN. All rights reserved. // import Foundation
Java
UTF-8
1,978
2.25
2
[]
no_license
package com.sc.mytown.dao; import java.util.List; import org.apache.ibatis.session.SqlSession; import com.sc.mytown.util.SqlSessionUtil; import com.sc.mytown.vo.AddHashTagVo; import com.sc.mytown.vo.HashTagVo; import com.sc.mytown.vo.SpotVo; public class AddHashTagsDAO { public static int insertAddHashTag(AddHashTagVo addHashtagVo) { int result = 0; SqlSession session = null; try { session = SqlSessionUtil.getSqlSession(); result = session.insert("addHashTags.insertAddHashTag",addHashtagVo); } catch (Exception e) { e.printStackTrace(); } finally { if (session != null) { session.close(); } } return result; } public static List<HashTagVo> selectGuAddHashTagVo(SpotVo spot){ List<HashTagVo> list = null; SqlSession session = null; try{ session = SqlSessionUtil.getSqlSession(); list = session.selectList("addHashTags.selectGuHashTags",spot); }catch(Exception e){ e.printStackTrace(); }finally{ if(session!=null){session.close();} }//try~ catch finally end return list; }//selectGuAddHashTagVo() end public static int insertAddHashTags(AddHashTagVo addHashTagvo){ int result = 0; SqlSession session = null; try{ session = SqlSessionUtil.getSqlSession(); result = session.insert("addHashTags.insertAddHashTag",addHashTagvo); }catch(Exception e){ e.printStackTrace(); }finally{ if(session!=null){session.close();} }//try~ catch finally end return result; }//insertAddHashTags() end public static List<AddHashTagVo> talkTagList(int talkNo) { List<AddHashTagVo> addTags = null; SqlSession session = null; try { session = SqlSessionUtil.getSqlSession(); addTags = session.selectList("addHashTags.talkTagList", talkNo); }catch (Exception e) { e.printStackTrace(); }finally { if(session!=null) session.close(); } return addTags; } }
Java
UTF-8
2,406
2.625
3
[]
no_license
package com.example.baselibrary.http; import android.content.Context; import java.util.HashMap; import java.util.Map; /** * 网络请求工具类 * Created by cherish * 实现链式调用的方法 */ public class HttpUtils { private static final int POST_TYPE = 0x0011; private static final int GET_TYPE = 0x0022; private static final int DOWN_TYPE = 0x0033; private static final int UPLOAD_TYPE = 0x0044; private static HttpEngine mHttpEngine; private Context mContext; private String mUrl; private Map<String, Object> mParams; private boolean mCatch; private int mType = GET_TYPE; private String mPath; private String mName; public static void initEngine(HttpEngine httpEngine) { mHttpEngine = httpEngine; } private HttpUtils(Context context) { mContext = context; mParams=new HashMap<>(); } public static HttpUtils with(Context context) { return new HttpUtils(context); } public HttpUtils url(String url) { mUrl = url; return this; } public HttpUtils param(String key,Object value) { mParams .put(key,value); return this; } public HttpUtils params(Map<String, Object> params) { mParams = params; return this; } public HttpUtils path(String path) { mPath = path; return this; } public HttpUtils name(String name) { mName = name; return this; } public HttpUtils cache(boolean cache) { mCatch = cache; return this; } public HttpUtils get() { mType = GET_TYPE; return this; } public HttpUtils post() { mType = POST_TYPE; return this; } public HttpUtils down() { mType = DOWN_TYPE; return this; } public HttpUtils switchEngine(HttpEngine httpEngine) { mHttpEngine = httpEngine; return this; } /** * 执行 * * @param callBack */ public void execute(EngineCallBack callBack) { if (mType == GET_TYPE) { mHttpEngine.get(mContext, mUrl, mParams, callBack); } else if (mType == POST_TYPE) { mHttpEngine.post(mContext, mUrl, mParams, callBack); }else if(mType==DOWN_TYPE){ mHttpEngine.downLoadFile(mContext,mUrl,mParams,mPath,mName,callBack); } } }
Python
UTF-8
4,891
3.09375
3
[ "MIT" ]
permissive
import pickle import os import numpy as np from sklearn.tree import DecisionTreeClassifier class AdaBoostClassifier: '''A simple AdaBoost Classifier.''' def __init__(self, weak_classifier, n_weakers_limit): '''Initialize AdaBoostClassifier Args: weak_classifier: The class of weak classifier, which is recommend to be sklearn.tree.DecisionTreeClassifier. n_weakers_limit: The maximum number of weak classifier the model can use. ''' self.weak_classifier = weak_classifier self.n_weakers_limit = n_weakers_limit pass def is_good_enough(self): '''Optional''' pass def fit(self,X,y): '''Build a boosted classifier from the training set (X, y). Args: X: An ndarray indicating the samples to be trained, which shape should be (n_samples,n_features). y: An ndarray indicating the ground-truth labels correspond to X, which shape should be (n_samples,1). ''' self.G={} self.alpha={} save_G_path = "/home/sun/ComputerScience/MachineLearning/Experiments/Experiment_three/ML2017-lab-03/self_G" save_alpha_path = "/home/sun/ComputerScience/MachineLearning/Experiments/Experiment_three/ML2017-lab-03/self_alpha" if os.path.exists(save_G_path): pkl_G = open(save_G_path, "rb") self.G = pickle.load(pkl_G) if os.path.exists(save_alpha_path): pkl_alpha = open(save_alpha_path, "rb") self.alpha = pickle.load(pkl_alpha) if self.G and self.alpha: return True n_samples = X.shape[0] n_features = X.shape[1] #initilize the W self.W = np.ones(n_samples) / n_samples for i in range(self.n_weakers_limit): self.G.setdefault(i) self.alpha.setdefault(i) #training a basic classifier for i in range(self.n_weakers_limit): self.G[i] = self.weak_classifier self.G[i].fit(X, y, sample_weight = self.W) train_score = self.G[i].score(X, y) e = 1 - train_score print("e = ", e) self.alpha[i] = 1 / 2 * np.log((1 - e) / e) prediction = self.G[i].predict(X) prediction = prediction.reshape((prediction.shape[0], 1)) print("prediction = ", prediction.shape) self.W = self.W.reshape(self.W.shape[0], 1) print("self.W = ", self.W.shape) tmp = np.exp(-self.alpha[i] * np.multiply(y, prediction)) print("tmp = ", tmp.shape) Zi = np.sum(np.dot(tmp.T, self.W)) self.W = np.multiply(self.W, tmp) / Zi self.W = self.W.reshape((self.W.shape[0],)) print("alpha", self.alpha[i]) print("self.W reshap = ",self.W.shape) print("Zi = ",Zi) print(" ") if not os.path.exists(save_G_path): pkl_G = open(save_G_path, "wb") pickle.dump(self.G, pkl_G) if not os.path.exists(save_alpha_path): pkl_alpha = open(save_alpha_path, "wb") pickle.dump(self.alpha, pkl_alpha) pass def predict_scores(self, X): '''Calculate the weighted sum score of the whole base classifiers for given samples. Args: X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features). Returns: An one-dimension ndarray indicating the scores of differnt samples, which shape should be (n_samples,1). ''' fx = 0 for i in range(self.n_weakers_limit): fx = fx + self.alpha[i] * self.G[i].predict(X) fx = fx.reshape((fx.shape[0], 1)) return fx def predict(self, X, threshold=0): '''Predict the catagories for geven samples. Args: X: An ndarray indicating the samples to be predicted, which shape should be (n_samples,n_features). threshold: The demarcation number of deviding the samples into two parts. Returns: An ndarray consists of predicted labels, which shape should be (n_samples,1). ''' final_prediction = self.sign(self.predict_scores(X)) print("final_prediction = ", final_prediction.shape) return final_prediction def sign(self, x): sig_value = 1 / (1 + np.exp(-x)) print(sig_value) sig_value[sig_value > 0.5] = 1 sig_value[sig_value <= 0.5] = -1 return sig_value @staticmethod def save(model, filename): with open(filename, "wb") as f: pickle.dump(model, f) @staticmethod def load(filename): with open(filename, "rb") as f: return pickle.load(f)
Java
UTF-8
5,854
2.578125
3
[]
no_license
import static java.util.Map.entry; import java.util.HashMap; import java.util.Map; public class grafixGlobs { static final Map<String, Integer> OBJ_TO_INDEX = Map.ofEntries(entry("arc", 0), entry("circle", 1), entry("polygon", 2)); static final int SIZE = OBJ_TO_INDEX.size(); public int[] execute(String[] commands, int sel) { Map<Integer, int[]> idToGlob = new HashMap<>(); for (String command : commands) { String[] parts = command.split(" "); if (parts[0].equals("make")) { int[] counts = new int[SIZE]; ++counts[OBJ_TO_INDEX.get(parts[1])]; idToGlob.put(generateId(idToGlob), counts); } else if (parts[0].equals("delete")) { idToGlob.remove(Integer.parseInt(parts[1])); } else if (parts[0].equals("merge")) { int id1 = Integer.parseInt(parts[1]); int id2 = Integer.parseInt(parts[2]); for (int i = 0; i < SIZE; ++i) { idToGlob.get(id1)[i] += idToGlob.get(id2)[i]; } idToGlob.remove(id2); } else { int[] counts = idToGlob.remove(Integer.parseInt(parts[1])); for (int i = 0; i < SIZE; ++i) { for (int j = 0; j < counts[i]; ++j) { int[] newCounts = new int[SIZE]; ++newCounts[i]; idToGlob.put(generateId(idToGlob), newCounts); } } } } return idToGlob.getOrDefault(sel, new int[0]); } int generateId(Map<Integer, int[]> idToGlob) { for (int id = 0; ; ++id) { if (!idToGlob.containsKey(id)) { return id; } } } // BEGIN KAWIGIEDIT TESTING // Generated by KawigiEdit 2.1.4 (beta) modified by pivanof private static boolean KawigiEdit_RunTest( int testNum, String[] p0, int p1, boolean hasAnswer, int[] p2) { System.out.print("Test " + testNum + ": [" + "{"); for (int i = 0; p0.length > i; ++i) { if (i > 0) { System.out.print(","); } System.out.print("\"" + p0[i] + "\""); } System.out.print("}" + "," + p1); System.out.println("]"); grafixGlobs obj; int[] answer; obj = new grafixGlobs(); long startTime = System.currentTimeMillis(); answer = obj.execute(p0, p1); long endTime = System.currentTimeMillis(); boolean res; res = true; System.out.println("Time: " + (endTime - startTime) / 1000.0 + " seconds"); if (hasAnswer) { System.out.println("Desired answer:"); System.out.print("\t" + "{"); for (int i = 0; p2.length > i; ++i) { if (i > 0) { System.out.print(","); } System.out.print(p2[i]); } System.out.println("}"); } System.out.println("Your answer:"); System.out.print("\t" + "{"); for (int i = 0; answer.length > i; ++i) { if (i > 0) { System.out.print(","); } System.out.print(answer[i]); } System.out.println("}"); if (hasAnswer) { if (answer.length != p2.length) { res = false; } else { for (int i = 0; answer.length > i; ++i) { if (answer[i] != p2[i]) { res = false; } } } } if (!res) { System.out.println("DOESN'T MATCH!!!!"); } else if ((endTime - startTime) / 1000.0 >= 2) { System.out.println("FAIL the timeout"); res = false; } else if (hasAnswer) { System.out.println("Match :-)"); } else { System.out.println("OK, but is it right?"); } System.out.println(""); return res; } public static void main(String[] args) { boolean all_right; all_right = true; String[] p0; int p1; int[] p2; // ----- test 0 ----- p0 = new String[] { "make polygon", "make circle", "make polygon", "merge 0 1", "merge 2 0", "split 2" }; p1 = 0; p2 = new int[] {0, 1, 0}; all_right = KawigiEdit_RunTest(0, p0, p1, true, p2) && all_right; // ------------------ // ----- test 1 ----- p0 = new String[] { "make circle", "make circle", "make arc", "merge 2 1", "delete 0", "split 2", "delete 0", "make polygon" }; p1 = 0; p2 = new int[] {0, 0, 1}; all_right = KawigiEdit_RunTest(1, p0, p1, true, p2) && all_right; // ------------------ // ----- test 2 ----- p0 = new String[] { "make circle", "make circle", "make arc", "merge 2 1", "delete 0", "split 2", "delete 0", "make polygon" }; p1 = 2; p2 = new int[] {}; all_right = KawigiEdit_RunTest(2, p0, p1, true, p2) && all_right; // ------------------ // ----- test 3 ----- p0 = new String[] {"make arc"}; p1 = 999; p2 = new int[] {}; all_right = KawigiEdit_RunTest(3, p0, p1, true, p2) && all_right; // ------------------ // ----- test 4 ----- p0 = new String[] { "make polygon", "make polygon", "make arc", "make circle", "make circle", "delete 3", "make polygon", "make arc", "make arc", "merge 1 3", "merge 1 4", "merge 2 1", "make arc", "make arc", "make circle", "make circle", "merge 6 5", "split 6", "merge 2 1" }; p1 = 2; p2 = new int[] {2, 1, 2}; all_right = KawigiEdit_RunTest(4, p0, p1, true, p2) && all_right; // ------------------ if (all_right) { System.out.println("You're a stud (at least on the example cases)!"); } else { System.out.println("Some of the test cases had errors."); } } // END KAWIGIEDIT TESTING } // Powered by KawigiEdit 2.1.4 (beta) modified by pivanof!
JavaScript
UTF-8
1,000
2.609375
3
[ "MIT" ]
permissive
let scanner = new Instascan.Scanner({ video: document.getElementById('qrscanner') }); scanner.addListener('scan', function (content) { var array = content.split("&"); array[0] = array[0].replace("npm=", ""); array[1] = array[1].replace("nama=", ""); array[2] = array[2].replace("kelas=", ""); array[3] = array[3].replace("mata_kuliah=", ""); array[4] = array[4].replace("minggu=",""); document.getElementById('npm').value = array[0]; document.getElementById('kelas_id').value = " " + array[2] + " "; document.getElementById('mata_kuliah_id').value = " " + array[3] + " "; document.getElementById('minggu').value = " " + array[4] + " "; document.inputAbsen.submit(); alert("Data milik" + array[0] + " telah masuk"); }); Instascan.Camera.getCameras().then(function (cameras) { if (cameras.length > 0) { scanner.start(cameras[0]); } else { console.error('No cameras found.'); } }).catch(function (e) { console.error(e); });
Markdown
UTF-8
4,232
3.609375
4
[]
no_license
--- title: for... in与for... of date: 2023-07-02T14:17:19.138Z size: 4153 --- - for...in用于可枚举数据,对象、数组、字符串 - for...of用户可迭代数据,数组、字符串、Map、etc - for...of为es6的特性,弥补for...in的不足 - for...in获取键名,for...of获取键值 ##### for...in缺点 - 数组的键名是数字,但是for...in循环是以字符串作为键名 - 会循环遍历对象的所有可枚举属性 - 某些情况下,for...in循环会乱序 ##### for...of优点 - 没有for...in的缺点 - for...of内部调用的是数据结构的Symbol.iterator(迭代器)方法 - 不同于forEach方法,它可以与break、continue和return配合使用 ##### Iterator(遍历器) 遍历器(Iterator)是一种接口,为各种不同的数据结构提供统一的访问机制 ###### 作用 - 为各种数据结构,提供一个统一的、简便的访问接口 - 使得数据结构的成员能够按某种次序排列 - ES6 创造了一种新的遍历命令`for...of`循环,Iterator 接口主要供`for...of`消费 ###### 遍历过程 - 创建一个指针对象,指向当前数据结构的起始位置。也就是说,遍历器对象本质上,就是一个指针对象 - 第一次调用指针对象的`next`方法,可以将指针指向数据结构的第一个成员 - 第二次调用指针对象的`next`方法,指针就指向数据结构的第二个成员 - 不断调用指针对象的`next`方法,直到它指向数据结构的结束位置 - 每一次调用`next`方法,都会返回一个包含`value`和`done`两个属性的对象 - `value`属性是当前成员的值 - `done`属性是一个布尔值,表示遍历是否结束 ```javascript let arr = ['a', 'b', 'c']; // 迭代器 let iter = arr[Symbol.iterator](); iter.next() // { value: 'a', done: false } iter.next() // { value: 'b', done: false } iter.next() // { value: 'c', done: false } iter.next() // { value: undefined, done: true } //{value: undefined, done: true} [][Symbol.iterator]().next() ``` ##### 对象 不支持for...of 对象的property至少有三个方面的因素: - 来源:是仅own property还是包括原型链上的 - 类型:是仅string还是包括symbol - 是仅可枚举(enumerable为true)还是包括不可枚举的 如果再考虑迭代key、value、[key, value] 这三种可能,就多达24种组合,到底哪一种适合作为默认迭代行为,较难取舍(不像数组,我们直觉上默认迭代就应该那样) ```javascript let target = { edition: 6, committee: "TC39", standard: "ECMA-262" }; target[Symbol("symbol")] = 'symbol' // edition // committee // standard // Symbol不会输出,需要通过Object.getOwnPropertySymbols()得到 for (let item in target) { console.log(item); } // TypeError: target is not iterable for (let item of target) { console.log(item); } ``` ##### 字符串 扩展运算符其内部实现也是使用了同样的迭代协议 ```javascript // 字符串 let str = "hello"; //0 1 2 3 4 for (let s in str) { console.log(s); } // h e l l o for (let s of str) { console.log(s); } // [ 'h', 'e', 'l', 'l', 'o' ] console.log([...str]); ``` ##### 数组 for...of循环,只返回具有数字索引的属性 ```javascript const arr = ['a', 'b', 'c', 'd']; arr.foo = 'hello'; arr[10] = 'ten'; // (11) ["a", "b", "c", "d", empty × 6, "hello", foo: "hello"] // foo不占size console.log(arr); // 0 string // 1 string // 2 string // 3 string // 10 string // foo string for (let a in arr) { console.log(a, typeof a); } // a b c d undefined...6次 ten for (let a of arr) { console.log(a); } ``` ##### Set、Map 不支持for...in ```javascript let pets = new Set(["Cat", "Dog", "Hamster"]); pets["species"] = "mammals"; for (let pet in pets) { console.log(pet); // "species" } for (let pet of pets) { console.log(pet); // "Cat", "Dog", "Hamster" } let map = new Map(); map.set("edition", 6); map.set("committee", "TC39"); // 无输出,也不报错 for (let pair in map) { console.log(pair, 'for...in'); } // [ 'edition', 6 ] for...of // [ 'committee', 'TC39' ] for...of for (let pair of map) { console.log(pair, 'for...of'); } ```
Markdown
UTF-8
2,639
2.90625
3
[]
no_license
# 静态购物商城 ## 实现功能和作业要求: - 完成电子商务网站页面(动态)(仿京东) 1. 主页部分 - `:hover`纯CSS导航菜单 - `float`瀑流商品布局 - ``js左侧伸缩菜单 - ``js图片自动切换 - `@media screen`以1190px为临界实现两种布局 2. 注册页面 - js部分表单验证 3. 登录页面 - 登录页面和注册页面基本一致,前面写特效耗时太多,这个页面就不做了。 4. 一些记录 - 字符超出元素长度以"..."结尾 ``` overflow:hidden; white-space: nowrap; text-overflow: ellipsis; //三个一起才能生效 ``` - `border-radius`设置边框圆角 --------- - `box-shadow`设置阴影,参数如下: ``` none:无阴影 <length>①:第1个长度值用来设置对象的阴影水平偏移值。可以为负值 <length>②:第2个长度值用来设置对象的阴影垂直偏移值。可以为负值 <length>③:如果提供了第3个长度值则用来设置对象的阴影模糊值。不允许负值 <length>④:如果提供了第4个长度值则用来设置对象的阴影外延值。模糊半径 <color>:设置对象的阴影的颜色。 ``` - 单边阴影示例:`box-shadow: 0px 10px 10px -6px rgba(0,0,0,.2);`设置下边阴影,设置模糊半径要大于偏移值得一半 --------- - `transition:[ transition-property ] || [ transition-duration ] || [ transition-timing-function ] || [ transition-delay ]`过度效果 - 取值: - [ transition-property ]:检索或设置对象中的参与过渡的属性 - [ transition-duration ]:检索或设置对象过渡的持续时间 - [ transition-timing-function ]:检索或设置对象中过渡的动画类型 - [ transition-delay ]:检索或设置对象延迟过渡的时间 - 例`transition:left 2s ease-in .5s`;当left改变时,将从left初始位置移动到改变后位置,持续2秒,由慢到快,延迟0.5秒开始 - linear:线性过渡。等同于贝塞尔曲线(0.0, 0.0, 1.0, 1.0) - ease:平滑过渡。等同于贝塞尔曲线(0.25, 0.1, 0.25, 1.0) - ease-in:由慢到快。等同于贝塞尔曲线(0.42, 0, 1.0, 1.0) - ease-out:由快到慢。等同于贝塞尔曲线(0, 0, 0.58, 1.0) - ease-in-out:由慢到快再到慢。等同于贝塞尔曲线(0.42, 0, 0.58, 1.0) --------- ## About Me ```python myname = 'MC.Lee' mylink = 'limich.cn' ``` [我的博客](https://limich.cn) QQ:289959141 E-mail:limich@aliyun.com [代码GitHub地址](https://github.com/limingchang/python_study_task.git) [代码国内码云同步地址](https://git.oschina.net/limich/python_study.git)
Markdown
UTF-8
1,849
3.625
4
[]
no_license
# 문제 ## 삽입 정렬 만들기 * 내림차순이 되도록 코드 작성하기 # 예제 출력 124 112 87 55 17 9 6 5 3 1 # 접근방식 삽입 정렬은 하나의 값은 선택하고 자신 앞에 있는 값들과 하나씩 비교해나가면서 자리를 교환하는 정렬 방법이다. 첫 시작은 arr[1]부터 시작하는데, 먼저 arr[1]을 임시변수 temp에 저장한 후 이를 앞의 요소인 arr[0]의 값과 비교하여 더 크면 arr[0]의 원소를 arr[1]의 자리에 넣어준다. 즉, 앞의 원소를 뒤로 미뤄주게 된다. 그리고 기존의 arr[0]자리는 temp값으로 덮어 씌워주면 된다. 이렇게가 한번의 for문이며 그 다음 arr[2]를 선택한후 다시 arr[1]과 arr[0]의 값과 비교해준다. 이는 while문을 이용해 반복 수행한다. 이 때, 선택된 원소보다 앞의 원소들은 이미 정렬되어 있는 상태이기 때문에 원소를 선택하고 바로 앞 원소를 비교해서 선택한 원소가 작다면, 더 이상 앞의 원소들을 비교할 필요가 없기 때문에 다음 원소를 선택한다. 따라서 쓸모없는 비교를 줄일 수 있으므로 버블 정렬보다 속도가 빠르다. # 코드 ```c #include <stdio.h> int main() { int arr[10] = { 9, 17, 5, 6, 124, 112, 1, 3, 87, 55 }; int temp; // 두 값을 바꿀 때 사용할 변수 int length = sizeof(arr) / sizeof(int); int j; for(int i = 1; i<length; i++){ temp = arr[i]; j = i-1; while(j>=0 && arr[j] < temp){ arr[j+1] = arr[j]; j = j-1; } arr[j+1] = temp; } for(int i=0; i<length; i++){ printf("%d ", arr[i]); } return 0; } ``` # 실행 결과 ![insertsort_img](https://github.com/jdaun/TIL/blob/master/C/c_ex/image/c_insertsort.PNG) # 출처 구름EDU, 한눈에 끝내는 C언어 기초 13강(http://bitly.kr/MeLINwbL9)
PHP
UTF-8
3,628
2.578125
3
[]
no_license
<?php namespace App\Http\Controllers; use App\Job; use Carbon\Carbon; use Illuminate\Http\Request; class JobController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { $jobs = Job::all(); return response()->json(['data' => $jobs], 200); } /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function availableJobs() { $today = Carbon::today(); $jobs = Job::where('start_date', '<', $today)->get(); return response()->json(['data' => $jobs], 200); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $model = Job::find($id); if(!$model){ return response()->json(['message' => 'job not found'], 400); } return response()->json(['data' => $model], 200); } /** * create Product for admin * @param Request $request * @return mixed * @throws \Illuminate\Validation\ValidationException */ public function store(Request $request){ $this->validate($request, [ 'title' => 'required|string|max:255|unique:jobs,title', 'required_experience_level' => 'required|string|max:255', 'brief' => 'required|string', 'start_date' => 'required|date|after_or_equal:today', 'end_date' => 'required|date|after:start_date', ]); $job = $request->all(); $job['start_date'] = Carbon::createFromDate($job['start_date']); $job['end_date'] = Carbon::createFromDate($job['end_date']); try{ Job::create($job); }catch (\Exception $e){ return response()->json(['message' => $e->getMessage()], 400); } return response()->json(['message' => "Product {$request->get('title')} created Successfully"], 200); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response * @throws \Illuminate\Validation\ValidationException */ public function update(Request $request, $id) { $this->validate($request, [ 'title' => "string|max:255|unique:jobs,title,{$id}", 'required_experience_level' => 'string|max:255', 'brief' => 'string', 'start_date' => 'date', 'end_date' => 'date|after:start_date', ]); $job = $request->all(); if($job['start_date']) $job['start_date'] = Carbon::createFromDate($job['start_date']); if($job['end_date']) $job['end_date'] = Carbon::createFromDate($job['end_date']); $model = Job::find($id); if(!$model){ return response()->json(['message' => 'job not found'], 400); } $model->update($request->all()); return response()->json(['message' => "Job {$model->title} updated Successfully"], 200); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $model = Job::find($id); if(!$model){ return response()->json(['message' => 'job not found'], 400); } $model->delete(); return response()->json(['message' => "Job {$model->title} deleted Successfully"], 200); } }
Java
UTF-8
302
1.757813
2
[]
no_license
package com.finolweb.userapp.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import com.github.javafaker.Faker; @Configuration public class FakerBeanConfig { @Bean public Faker getFaker() { return new Faker(); } }
C
UTF-8
6,424
2.796875
3
[]
no_license
#include "Serial.h" #include <fcntl.h> #include <termios.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <stdio.h> #include <linux/limits.h> /********************----- STRUCT: Serial -----********************/ struct Serial_t { int m_deviceHandle; }; /**************************************************/ Result serial_create(int const i_deviceID, BaudRate const i_baudRate, SerialMode const i_serialMode, Serial ** const o_serialHandle) { int cfResult = 0; int deviceBaudRate = 0; Result result = R_FAILURE; struct termios serialAttributes; Serial *serialHandle = NULL; char serialPathname[PATH_MAX]; int tcResult = 0; /***** Get baud rate *****/ switch(i_baudRate) { case SERIAL_BAUDRATE_4800: deviceBaudRate = B4800; break; case SERIAL_BAUDRATE_9600: deviceBaudRate = B9600; break; #ifdef B14400 case SERIAL_BAUDRATE_14400: deviceBaudRate = B14400; break; #endif case SERIAL_BAUDRATE_19200: deviceBaudRate = B19200; break; #ifdef B28800 case SERIAL_BAUDRATE_28800: deviceBaudRate = B28800; break; #endif case SERIAL_BAUDRATE_38400: deviceBaudRate = B38400; break; case SERIAL_BAUDRATE_57600: deviceBaudRate = B57600; break; case SERIAL_BAUDRATE_115200: deviceBaudRate = B115200; break; default: CARL_ERROR("Invalid baudrate (%d).", i_baudRate); result = R_INPUTBAD; goto end; } /***** Serial Handle *****/ serialHandle = (Serial *)malloc(sizeof(Serial)); if(serialHandle == NULL) { CARL_ERROR("Insufficient memory for serial handle."); result = R_MEMORYALLOCATIONERROR; goto end; } serialHandle->m_deviceHandle = -1; /***** Setup serial pathname *****/ snprintf(serialPathname, sizeof(serialPathname), "/dev/ttyUSB%d", i_deviceID); /***** Open serial port *****/ serialHandle->m_deviceHandle = open(serialPathname, O_RDWR | O_NOCTTY | O_NDELAY); if(serialHandle->m_deviceHandle < 0) { CARL_ERRORNO("Unable to open serial device."); result = R_DEVICEOPENFAILED; goto end; } tcResult = tcgetattr(serialHandle->m_deviceHandle, &serialAttributes); if(tcResult < 0) { CARL_ERRORNO("Unable to get serial attributes."); result = R_DEVICEATTRIBUTEGETFAILED; goto end; } /***** Setup parameters *****/ cfResult = cfsetispeed(&serialAttributes, deviceBaudRate); if(cfResult < 0) { CARL_ERRORNO("Unable to set serial input speed."); result = R_DEVICEINPUTSPEEDFAILED; goto end; } cfResult = cfsetospeed(&serialAttributes, deviceBaudRate); if(cfResult < 0) { CARL_ERRORNO("Unable to set serial output speed."); result = R_DEVICEOUTPUTSPEEDFAILED; goto end; } switch(i_serialMode) { case SERIAL_MODE_ARDUINO: //Based on: //http://todbot.com/arduino/host/arduino-serial/arduino-serial.c serialAttributes.c_cflag &= ~(PARENB); //No parity serialAttributes.c_cflag &= ~(CSTOPB); //One stop bit serialAttributes.c_cflag &= ~(CSIZE); //Clear all CS* bits serialAttributes.c_cflag |= CS8; //8 bits serialAttributes.c_cflag &= ~(CRTSCTS); //No hardware flow control serialAttributes.c_cflag |= CREAD; //Enable receiver serialAttributes.c_cflag |= CLOCAL; //Ignore control lines serialAttributes.c_iflag &= ~(IXON | IXOFF | IXANY); //No software flow control; serialAttributes.c_lflag &= ~(ICANON | ECHO | ECHOE); //Disable echo serialAttributes.c_lflag &= ~(ISIG); //Disable signals serialAttributes.c_oflag &= ~(OPOST); //Disble output processing //See: //http://unixwiz.net/techtips/termios-vmin-vtime.html serialAttributes.c_cc[VMIN] = 0; //Wait for any data serialAttributes.c_cc[VTIME] = 20; //Wait VTIME tenths of a second for more data break; case SERIAL_MODE_DEFAULT: default: break; } /***** Set attributes *****/ tcResult = tcsetattr(serialHandle->m_deviceHandle, TCSANOW, &serialAttributes); if(tcResult < 0) { CARL_ERRORNO("Unable to set serial attributes."); result = R_DEVICEATTRIBUTESETFAILED; goto end; } if(o_serialHandle != NULL) { (*o_serialHandle) = serialHandle; } else { serial_destroy(&serialHandle); } return R_SUCCESS; end: CARL_ERROR("serial_create(%d, %d, %p)", i_deviceID, i_baudRate, o_serialHandle); serial_destroy(&serialHandle); return result; } Result serial_read( size_t const i_bytesToRead, uint8_t * const o_outputBuffer, size_t * const o_bytesRead, Serial const * const i_serialHandle) { Result result = R_FAILURE; ssize_t readResult = 0; if(i_serialHandle == NULL) { CARL_ERROR("Handle not created."); result = R_OBJECTNOTEXTANT; goto end; } readResult = read(i_serialHandle->m_deviceHandle, o_outputBuffer, i_bytesToRead); if(readResult < 0) { CARL_ERRORNO("IO Error"); result = R_DEVICEREADFAILED; goto end; } if(o_bytesRead != NULL) { (*o_bytesRead) = readResult; } return R_SUCCESS; end: CARL_ERROR("serial_read(%zu, %p, %p, %p)", i_bytesToRead, o_outputBuffer, o_bytesRead, i_serialHandle); return result; } Result serial_write( size_t const i_bytesToWrite, uint8_t const * const i_data, size_t * const o_bytesWritten, Serial const * const i_serialHandle) { Result result = R_FAILURE; ssize_t writeResult = 0; if(i_serialHandle == NULL) { CARL_ERROR("Handle not created."); result = R_OBJECTNOTEXTANT; goto end; } writeResult = write(i_serialHandle->m_deviceHandle, i_data, i_bytesToWrite); if(writeResult < 0) { CARL_ERRORNO("IO Error."); result = R_DEVICEWRITEFAILED; goto end; } if(o_bytesWritten != NULL) { (*o_bytesWritten) = writeResult; } return R_SUCCESS; end: CARL_ERROR("serial_write(%zu, %p, %p, %p)", i_bytesToWrite, i_data, o_bytesWritten, i_serialHandle); return result; } Result serial_destroy(Serial ** const io_serialHandle) { int closeResult = 0; Serial * serialHandle = NULL; /***** Input Validation *****/ if(io_serialHandle == NULL) { return R_INPUTBAD; } /***** Check if already destroyed *****/ serialHandle = (*io_serialHandle); if(serialHandle == NULL) { return R_SUCCESS; } /***** Close handle *****/ closeResult = close(serialHandle->m_deviceHandle); if(closeResult < 0) { CARL_ERRORNO("Error closing port"); return R_DEVICECLOSEFAILED; } /***** Return *****/ return R_SUCCESS; }
Python
UTF-8
145
2.984375
3
[]
no_license
a=list(map(int,input().replace('',' ').split()));i=0 while len(a)!=1: a=list(map(int,str(sum(a)).replace('',' ').split())) i+=1 print(i)
Go
UTF-8
2,022
2.78125
3
[]
no_license
package main import ( "fmt" "image" "image/color" "image/gif" "os" "github.com/husl-colors/husl-go" "github.com/kriskowal/bottle-world/sim" "github.com/kriskowal/bottle-world/viz" ) func newPalette() color.Palette { pal := make(color.Palette, 0) for h := 0; h < 16; h++ { for w := 0; w < 16; w++ { pal = append(pal, newColor(float64(h)/16, float64(w)/16)) } } return pal } func newColor(w, h float64) color.Color { r, g, b := husl.HuslToRGB(240, 10+w*80, 10+h*80) return color.RGBA{ uint8(r * 0xff), uint8(g * 0xff), uint8(b * 0xff), 0xff, } } func render(w *sim.World) func(*sim.Cell) color.Color { return func(c *sim.Cell) color.Color { saturation := 0.0 lightness := 0.0 hydraulicLightness := float64(c.WaterElevation-w.LowestWaterElevation) / float64(w.HighestWaterElevation-w.LowestWaterElevation) topographicLightness := float64(c.SurfaceElevation-w.LowestSurfaceElevation) / float64(w.HighestSurfaceElevation-w.LowestSurfaceElevation) if c.Water < 10 { saturation = 0 lightness = topographicLightness } else if c.Water < 20 { lightness = hydraulicLightness/2 + topographicLightness/2 saturation = 0.5 } else { lightness = hydraulicLightness saturation = 1 } return newColor(saturation, lightness) } } func main() { prev := sim.NewWorld() next := prev pal := newPalette() images := make([]*image.Paletted, 0, next.Width) delays := make([]int, 0, next.Width) speed := 5 duration := 1 overture := 20000 // Overture t := 0 for ; t < overture; t++ { next, prev = prev, next sim.Tick(next, prev, t) } // Show for ; t < overture+next.Width*speed*duration; t++ { fmt.Printf(".") next, prev = prev, next sim.Tick(next, prev, t) if t%speed == 0 { fmt.Printf(".") images = append(images, viz.Capture(next, pal, render(next))) delays = append(delays, 10) } } f, _ := os.OpenFile("hydro.gif", os.O_WRONLY|os.O_CREATE, 0600) defer f.Close() gif.EncodeAll(f, &gif.GIF{ Image: images, Delay: delays, }) }
Python
UTF-8
1,268
2.546875
3
[]
no_license
from task_manager.db import db from passlib.apps import custom_app_context as pwd_context from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired) from config import Config class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer(), primary_key=True) login = db.Column(db.String(20), unique=True, index=True, nullable=False) password_hash = db.Column(db.String()) created_at = db.Column(db.DateTime(), nullable=False) tasks = db.relationship('Task', backref='user', lazy=True) def hash_password(self, password): self.password_hash = pwd_context.encrypt(password) def verify_password(self, password): return pwd_context.verify(password, self.password_hash) def generate_auth_token(self, expiration=600): s = Serializer(Config.SECRET_KEY, expires_in=expiration) return s.dumps({'id': self.id}) @staticmethod def verify_auth_token(token): s = Serializer(Config.SECRET_KEY) try: data = s.loads(token) except SignatureExpired: return None except BadSignature: return None user = User.query.get(data['id']) return user
Java
UTF-8
2,679
2.71875
3
[]
no_license
package sk.tuke.kpi.oop.game.controllers; import org.jetbrains.annotations.NotNull; import sk.tuke.kpi.gamelib.Actor; import sk.tuke.kpi.gamelib.Input; import sk.tuke.kpi.gamelib.KeyboardListener; import sk.tuke.kpi.gamelib.Scene; import sk.tuke.kpi.oop.game.Keeper; import sk.tuke.kpi.oop.game.actions.Drop; import sk.tuke.kpi.oop.game.actions.Shift; import sk.tuke.kpi.oop.game.actions.Take; import sk.tuke.kpi.oop.game.actions.Use; import sk.tuke.kpi.oop.game.items.Collectible; import sk.tuke.kpi.oop.game.items.Usable; public class CollectorController implements KeyboardListener { private Keeper<Collectible> player; public CollectorController(Keeper<Collectible> player) { this.player = player; } @Override public void keyPressed(@NotNull Input.Key key) { switch (key) { case ENTER: doTake(); break; case BACKSPACE: doDrop(); break; case S: doShift(); break; case U: doUseNearest(); break; case B: doUseFromBackpack(); break; default: } } private void doTake() { Take<Collectible> action = new Take<>(Collectible.class); action.scheduleOn(player); } private void doDrop() { Drop<Collectible> action = new Drop<>(); action.scheduleOn(player); } private void doShift() { new Shift().scheduleOn(player); } private void doUseNearest() { Scene scene = player.getScene(); Actor anActor = scene.getActors().stream() .filter(actor -> actor.intersects(player) && actor instanceof Usable && !(actor instanceof Collectible)) .findFirst() .orElse(null); if (anActor == null) return; @SuppressWarnings("unchecked") Usable<Actor> usable = (Usable<Actor>) anActor; if (usable.getUsingActorClass().isInstance(player)) { Use<Actor> action = new Use<>(usable); action.scheduleOn(player); } } private void doUseFromBackpack() { if (player.getContainer().getSize() == 0) return; Collectible item = null; try { item = player.getContainer().peek(); } catch (Exception e) { item = null; } if (item instanceof Collectible && item instanceof Usable) { @SuppressWarnings("unchecked") Use<Actor> action = new Use<Actor>((Usable<Actor>) item); action.scheduleOnIntersectingWith(player); } } }
Java
UTF-8
655
3.28125
3
[]
no_license
package DoIt; import java.util.Scanner; public class Max3 { static int max4(int a, int b, int c, int d){ int max = a; if(b > a) max = b; if (c > b) max = c; if (d > c) max = d; return max; } public static void main(String[] args){ Scanner stdIn = new Scanner(System.in); int a, b, c, d; System.out.println("a ="); a = stdIn.nextInt(); System.out.println("b ="); b = stdIn.nextInt(); System.out.println("c ="); c = stdIn.nextInt(); System.out.println("d ="); d = stdIn.nextInt(); System.out.println("max : " + max4(a, b, c, d)); } }
Java
UTF-8
3,338
2.546875
3
[]
no_license
package com.ran.engine.factories.interpolation.curvecreators; import com.ran.engine.algebra.function.DoubleFunction; import com.ran.engine.algebra.matrix.DoubleMatrix; import com.ran.engine.algebra.vector.ThreeDoubleVector; import com.ran.engine.factories.interpolation.input.SimpleInputParameters; import com.ran.engine.factories.interpolation.tools.BigArcsBuilder; import com.ran.engine.factories.interpolation.tools.CurvesSmoothingCreator; import java.util.ArrayList; import java.util.List; public class SphereBezierCurveCreator extends AbstractSphereCurveCreator { private static final SphereBezierCurveCreator INSTANCE = new SphereBezierCurveCreator(); public static SphereBezierCurveCreator getInstance() { return INSTANCE; } @Override public DoubleFunction<ThreeDoubleVector> interpolateCurve(List<ThreeDoubleVector> verticesList, SimpleInputParameters parameters, int degree) { validateVerticesList(verticesList); double t0 = parameters.getT0(); double t1 = parameters.getT1(); int k = verticesList.size(); CurvesSmoothingCreator curvesSmoothingCreator = CurvesSmoothingCreator.getInstance(); BigArcsBuilder bigArcsBuilder = BigArcsBuilder.getInstance(); List<ThreeDoubleVector> arcsCenters = new ArrayList<>(k - 1); for (int i = 0; i < k - 1; i++) { BigArcsBuilder.Result bigArcsBuilderResult = bigArcsBuilder.buildBigArcBetweenVerticesOnSphere( verticesList.get(i), verticesList.get(i + 1)); arcsCenters.add(new ThreeDoubleVector(bigArcsBuilderResult.getRotation().apply(0.5) .multiply(verticesList.get(i).getDoubleVector()))); } List<DoubleFunction<DoubleMatrix>> halfRotationsForward = new ArrayList<>(k - 1); List<DoubleFunction<DoubleMatrix>> halfRotationsBack = new ArrayList<>(k - 1); for (int i = 0; i < k - 1; i++) { BigArcsBuilder.Result firstHalfBigArcsBuilderResult = bigArcsBuilder.buildBigArcBetweenVerticesOnSphere( verticesList.get(i), arcsCenters.get(i)); halfRotationsForward.add(firstHalfBigArcsBuilderResult.getRotation()); BigArcsBuilder.Result secondHalfBigArcsBuilderResult = bigArcsBuilder.buildBigArcBetweenVerticesOnSphere( verticesList.get(i + 1), arcsCenters.get(i)); halfRotationsBack.add(secondHalfBigArcsBuilderResult.getRotation()); } List<DoubleFunction<DoubleMatrix>> smoothedRotations = new ArrayList<>(k); smoothedRotations.add(halfRotationsForward.get(0)); for (int i = 1; i < k - 1; i++) { smoothedRotations.add(curvesSmoothingCreator.smoothCurves( halfRotationsBack.get(i - 1), halfRotationsForward.get(i), degree)); } smoothedRotations.add(new DoubleFunction<>( point -> halfRotationsBack.get(k - 2).apply(1.0 - point), 0.0, 1.0) ); List<Double> timeMoments = new ArrayList<>(k + 1); double timeDelta = t1 - t0; for (int i = 0; i < k + 1; i++) { timeMoments.add(t0 + i * timeDelta); } return buildFinalCurve(timeMoments, verticesList, smoothedRotations, k); } }
Markdown
UTF-8
6,832
2.9375
3
[]
no_license
# Bottom-CMS ## Install * npm install ## running in developer mode 1. npm run dev 2. you can test with "Advance Rest" for api. ## please change the bills module, this line: ![](./doc/bills.png) ## The symbolic model database ![](./doc/cms.jpg) ## Introduction FORMAT: 1A HOST: http://localhost:7000 VERSIÓN: 1.0 Welcome to the API documentation system Bottom content manager. Bottom API allows you to manage resources within the application Bottom a simple, programmatically using conventional HTTP requests. The endpoints are intuitive and powerful, allowing you to easily make calls to retrieve information or perform actions. All the functionality you are familiar with Bottom Control Panel is also available through the API, allowing you to script complex actions that his situation requires. The API documentation will start with an overview of the design and technology has been implemented, followed by background information on specific endpoints. ### Requests Any tool that is fluent in HTTP can communicate with the API simply by requesting the correct URI. Requests should be made using the HTTPS protocol so that traffic is encrypted. The interface responds to different methods depending on the action required. ### Responses When a request is successful, a response body will typically be sent back in the form of a JSON object. An exception to this is when a DELETE request is processed, which will result in a successful HTTP 204 status and an empty response body. Inside of this JSON object, the resource root that was the target of the request will be set as the key. This will be the singular form of the word if the request operated on a single object, and the plural form of the word if a collection was processed. ### HTTP Statuses Along with the HTTP methods that the API responds to, it will also return standard HTTP statuses, including error codes. In the event of a problem, the status will contain the error code, while the body of the response will usually contain additional information about the problem that was encountered. In general, if the status returned is in the 200 range, it indicates that the request was fulfilled successfully and that no error was encountered. Return codes in the 400 range typically indicate that there was an issue with the request that was sent. Among other things, this could mean that you did not authenticate correctly, that you are requesting an action that you do not have authorization for, that the object you are requesting does not exist, or that your request is malformed. If you receive a status in the 500 range, this generally indicates a server-side problem. This means that we are having an issue on our end and cannot fulfill your request currently. ## Routes for api ### Login Route [/login] This route allows authenticate to the content management system. #### Login [POST] + Request (application/json) + Headers Authorization: ABCDEF + Body ```javascript { "username": "myUsername", "password": "myPassword" } ``` + Response 200 (application/json) ```javascript [ { "status": "success", "err": null, "data": { token: token } } ] ``` + Response 500 (application/json) ```javascript [ { "status": "error", "err":[ { code: 500, message: "Internal server error" } ], "data": null } ] ``` + Response 401 (application/json) ```javascript [ { "status": "fail", "err":[ { code: 401, message: "The user who is trying entered does not exist in our database" } ], "data": null } ] ``` + Response 401 (application/json) ```javascript [ { "status": "fail", "err":[ { code: 401, message: "The user has not yet been confirmed with verification code" } ], "data": null } ] ``` + Response 401 (application/json) ```javascript [ { "status": "fail", "err":[ { code: 401, message: "The password does not match the specified user" } ], "data": null } ] ``` + Response 400 (application/json) ```javascript [ { "status": "fail", "err":[ { code: 400, message: "There are empty fields to sign the petition" } ], "data": null } ] ``` ### Account Route [/account] route allows the management of accounts in the application #### Account [GET] { "success": true "status": "success" "payload": [1] 0: { "_id": "56aaa018ea1aaf902083c230" "name": "Bottom" "user": "admin" "pass": "admin" "__v": 0 "date": "2016-01-28T23:09:32.167Z" "rol": [1] 0: "Visitor" - "verify": true "access": true "email": [1] 0: "e.juandav@gmail.com" - }- - "error": {} } ### Menu Route [/menu] allows to manage the menu #### Menu [GET] { "success": true "status": "success" "payload": [4] 0: { "_id": "56bd5b7b0e89a15f40035a2f" "title": "test3" "__v": 0 "date": "2016-02-12T02:09:25.364Z" }- 1: { "_id": "56bd5bdc0e89a15f40035a30" "title": "n ,m m," "__v": 0 "date": "2016-02-12T02:09:25.364Z" }- 2: { "_id": "56be51e37c7cb16748518b6d" "title": "test ahora" "__v": 0 "date": "2016-02-12T21:40:59.597Z" }- 3: { "_id": "56be52897c7cb16748518b6e" "title": "dadadadadada" "__v": 0 "date": "2016-02-12T21:40:59.597Z" }- - "error": {} } ### Page Route [/page] allows to manage the page #### Page [GET] { "success": true "status": "success" "payload": [1] 0: { "_id": "5699349932541788300e103f" "body": "test2" "label": "test2" "url": "test2" "menu_id": null "__v": 0 "last_modified_at": "2016-01-15T18:05:08.361Z" }- - "error": {} } ### Blog Route [/blog] allows to manage the blog #### Blog [GET] { "success": true "status": "success" "payload": [3] 0: { "_id": "56947dbaae851a3a16e67df2" "__v": 0 "date": "2016-01-12T04:14:33.442Z" }- 1: { "_id": "56a88a59f91a5bfe6c71a6a6" "__v": 0 "date": "2016-01-27T09:13:53.984Z" }- 2: { "_id": "56a88aaef91a5bfe6c71a6a7" "__v": 0 "date": "2016-01-27T09:13:53.984Z" }- - "error": {} } ### Post Route [/post] allows to manage the post #### Post [GET] { "success": true "status": "success" "payload": [0] "error": {} }
Java
UTF-8
249
1.585938
2
[]
no_license
/** * */ package org.herb.ui.pubsub; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JPanel; /** * @author herb * */ public class MyPanel extends JPanel { public MyPanel() { super(); } }
C++
UTF-8
366
3
3
[ "MIT" ]
permissive
https://www.interviewbit.com/problems/min-xor-value/ int Solution::findMinXor(vector<int> &A) { vector <int > arr(A) ; sort(arr.begin(), arr.end()); int minXor = INT_MAX; int val = 0; for (int i = 0; i < arr.size()- 1; i++) { val = arr[i] ^ arr[i + 1]; minXor = min(minXor, val); } return minXor; }
TypeScript
UTF-8
1,726
2.6875
3
[]
no_license
import {Pipe, PipeTransform} from '@angular/core'; import {UnidadeMedidaEnum} from '../../../item/model/unidade-medida.enum'; import {TipoPipeUnidadeMedidaEnum} from '../../models/tipo-pipe-unidade-medida.enum'; @Pipe({ name: 'unidadeMedida' }) export class UnidadeMedidaPipe implements PipeTransform { /** * @param unidadeMedidaEnum A ser percorrida para transformação * @param tipoPipe A ser percorrido para transformação * @returns String processada e transformada conforme unidadeMedidaEnum e tipoPipe */ transform(unidadeMedidaEnum: UnidadeMedidaEnum, tipoPipe: TipoPipeUnidadeMedidaEnum): string { switch (unidadeMedidaEnum) { case UnidadeMedidaEnum.UNIDADE: switch (tipoPipe) { case TipoPipeUnidadeMedidaEnum.DESCRICAO: return 'Unidade'; case TipoPipeUnidadeMedidaEnum.SIGLA: return 'UN'; case TipoPipeUnidadeMedidaEnum.MASK: return '0*'; } break; case UnidadeMedidaEnum.QUILOGRAMA: switch (tipoPipe) { case TipoPipeUnidadeMedidaEnum.DESCRICAO: return 'Quilograma'; case TipoPipeUnidadeMedidaEnum.SIGLA: return 'KG'; case TipoPipeUnidadeMedidaEnum.MASK: return '0*,000'; } break; case UnidadeMedidaEnum.LITRO: switch (tipoPipe) { case TipoPipeUnidadeMedidaEnum.DESCRICAO: return 'Litro'; case TipoPipeUnidadeMedidaEnum.SIGLA: return 'LT'; case TipoPipeUnidadeMedidaEnum.MASK: return '0*,000'; default: } break; default: return 'Unidade de medida não encontrada'; } } }
Java
UTF-8
9,994
2.609375
3
[]
no_license
package highway62.filefork; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; public class ContactDeviceDAO extends BaseDAO{ public ContactDeviceDAO(Context context) { super(context, DBContract.DB_NAME, null, DBContract.DB_VERSION); } public long addDevice(Device device) throws Exception { ContentValues values = new ContentValues(); values.put(DBContract.ContactDevicesTable._ID, device.getId()); values.put(DBContract.ContactDevicesTable.COLUMN_DEVICE_NAME, device.getDeviceName()); values.put(DBContract.ContactDevicesTable.COLUMN_DEVICE_TYPE, device.getDeviceType()); values.put(DBContract.ContactDevicesTable.COLUMN_ACCEPTED, 1); SQLiteDatabase db = this.getWritableDatabase(); long rowId = db.insert(DBContract.ContactDevicesTable.TABLE_NAME, null, values); db.close(); if (rowId <= 0) { throw new Exception("Error inserting device into Android DB"); } else { return rowId; } } public long addContact(Contact contact) throws Exception { ContentValues values = new ContentValues(); values.put(DBContract.ContactDevicesTable._ID, contact.getId()); values.put(DBContract.ContactDevicesTable.COLUMN_DEVICE_NAME, contact.getContactName()); values.put(DBContract.ContactDevicesTable.COLUMN_DEVICE_TYPE, contact.getContactType()); int isAccepted = contact.isAccepted() ? 1 : 0; values.put(DBContract.ContactDevicesTable.COLUMN_ACCEPTED, isAccepted); SQLiteDatabase db = this.getWritableDatabase(); long rowId = db.insert(DBContract.ContactDevicesTable.TABLE_NAME, null, values); db.close(); if (rowId <= 0) { throw new Exception("Error inserting contact into Android DB"); } else { return rowId; } } public void updateContactAccepted(long contactId) throws Exception { SQLiteDatabase db = this.getWritableDatabase(); String selection = DBContract.ContactDevicesTable._ID + "=?"; String[] selectionArgs = { String.valueOf(contactId) }; ContentValues values = new ContentValues(); values.put(DBContract.ContactDevicesTable.COLUMN_ACCEPTED,1); // update row int updatedRows = db.update(DBContract.ContactDevicesTable.TABLE_NAME,values,selection,selectionArgs); if(updatedRows == 0){ throw new Exception("DB Error: Cannot Update Contact Accepted"); } } public Device getDeviceById(long id) { // Columns to return String[] projection = { DBContract.ContactDevicesTable._ID, DBContract.ContactDevicesTable.COLUMN_DEVICE_NAME, DBContract.ContactDevicesTable.COLUMN_DEVICE_TYPE, }; // Columns for the where clause String selection = DBContract.ContactDevicesTable._ID + "=?"; // Values for the where clause String[] selectionArgs = { String.valueOf(id) }; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query( DBContract.ContactDevicesTable.TABLE_NAME, projection, // columns to return selection, // columns for where clause selectionArgs, // values for where clause null, // group by null, // having null); // order by if (cursor != null) { cursor.moveToFirst(); long dev_id = cursor.getLong(cursor.getColumnIndexOrThrow(DBContract.ContactDevicesTable._ID)); String dev_name = cursor.getString(cursor.getColumnIndexOrThrow(DBContract.ContactDevicesTable.COLUMN_DEVICE_NAME)); String dev_type = cursor.getString(cursor.getColumnIndexOrThrow(DBContract.ContactDevicesTable.COLUMN_DEVICE_TYPE)); cursor.close(); db.close(); if(!dev_type.equals(DBContract.DeviceTypes.CONTACT)){ return new Device(dev_id,dev_name,dev_type); } else { return null; } } else { return null; } } public ArrayList<Device> getAllDevices(){ ArrayList<Device> devices = new ArrayList<Device>(); // Columns to return String[] projection = { DBContract.ContactDevicesTable._ID, DBContract.ContactDevicesTable.COLUMN_DEVICE_NAME, DBContract.ContactDevicesTable.COLUMN_DEVICE_TYPE }; // Columns for the where clause String selection = DBContract.ContactDevicesTable.COLUMN_DEVICE_TYPE + "!=?"; // Values for the where clause String[] selectionArgs = { DBContract.DeviceTypes.CONTACT }; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query( DBContract.ContactDevicesTable.TABLE_NAME, projection, // columns to return selection, // columns for where clause selectionArgs, // values for where clause null, // group by null, // having null); // order by if (cursor.moveToFirst()) { do{ long dev_id = cursor.getLong(cursor.getColumnIndexOrThrow(DBContract.ContactDevicesTable._ID)); String dev_name = cursor.getString(cursor.getColumnIndexOrThrow(DBContract.ContactDevicesTable.COLUMN_DEVICE_NAME)); String dev_type = cursor.getString(cursor.getColumnIndexOrThrow(DBContract.ContactDevicesTable.COLUMN_DEVICE_TYPE)); devices.add(new Device(dev_id,dev_name,dev_type)); }while(cursor.moveToNext()); cursor.close(); db.close(); return devices; } else { return null; } } public Contact getContactById(long id) throws Exception { // Columns to return String[] projection = { DBContract.ContactDevicesTable._ID, DBContract.ContactDevicesTable.COLUMN_DEVICE_NAME, DBContract.ContactDevicesTable.COLUMN_DEVICE_TYPE, DBContract.ContactDevicesTable.COLUMN_ACCEPTED }; // Columns for the where clause String selection = DBContract.ContactDevicesTable._ID + "=?"; // Values for the where clause String[] selectionArgs = { String.valueOf(id) }; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query( DBContract.ContactDevicesTable.TABLE_NAME, projection, // columns to return selection, // columns for where clause selectionArgs, // values for where clause null, // group by null, // having null); // order by if (cursor != null) { cursor.moveToFirst(); long con_id = cursor.getLong(cursor.getColumnIndexOrThrow(DBContract.ContactDevicesTable._ID)); String con_name = cursor.getString(cursor.getColumnIndexOrThrow(DBContract.ContactDevicesTable.COLUMN_DEVICE_NAME)); String con_type = cursor.getString(cursor.getColumnIndexOrThrow(DBContract.ContactDevicesTable.COLUMN_DEVICE_TYPE)); int con_accepted_int = cursor.getInt(cursor.getColumnIndexOrThrow(DBContract.ContactDevicesTable.COLUMN_ACCEPTED)); boolean con_accepted = (con_accepted_int != 0); cursor.close(); db.close(); if(con_type.equals(DBContract.DeviceTypes.CONTACT)){ return new Contact(con_id,con_name,con_accepted); } else { throw new Exception("Supplied ID not a CONTACT"); } } else { return null; } } public ArrayList<Contact> getAllContacts(){ ArrayList<Contact> contacts = new ArrayList<Contact>(); // Columns to return String[] projection = { DBContract.ContactDevicesTable._ID, DBContract.ContactDevicesTable.COLUMN_DEVICE_NAME, DBContract.ContactDevicesTable.COLUMN_ACCEPTED }; // Columns for the where clause String selection = DBContract.ContactDevicesTable.COLUMN_DEVICE_TYPE + "=?"; // Values for the where clause String[] selectionArgs = { DBContract.DeviceTypes.CONTACT }; SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query( DBContract.ContactDevicesTable.TABLE_NAME, projection, // columns to return selection, // columns for where clause selectionArgs, // values for where clause null, // group by null, // having null); // order by if (cursor.moveToFirst()){ do{ long con_id = cursor.getLong(cursor.getColumnIndexOrThrow(DBContract.ContactDevicesTable._ID)); String con_name = cursor.getString(cursor.getColumnIndexOrThrow(DBContract.ContactDevicesTable.COLUMN_DEVICE_NAME)); int con_accepted_int = cursor.getInt(cursor.getColumnIndexOrThrow(DBContract.ContactDevicesTable.COLUMN_ACCEPTED)); boolean con_accepted = (con_accepted_int != 0); contacts.add(new Contact(con_id,con_name,con_accepted)); }while(cursor.moveToNext()); cursor.close(); db.close(); return contacts; } else { return null; } } }
C#
UTF-8
3,428
2.53125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; using System.Windows.Forms; namespace BUS { public class CTGD { public DataTable Show(string tenlop) { string sql = @"select mh.TenMon, gv.HoTen, NgayDay, Tiet from tblCTGD ct, tblMonHoc mh, tblLop l, tblGiaoVien gv where ct.MaLop=l.MaLop and gv.MaMon=mh.MaMon and ct.MaGV=gv.MaGV and l.tenlop='" + tenlop + "'"; DataTable dt = new DataTable(); SqlConnection con = new SqlConnection(ConnectDB.getconnect()); con.Open(); SqlDataAdapter da = new SqlDataAdapter(sql, con); da.Fill(dt); con.Close(); da.Dispose(); return dt; } public void ThemCTGD(string tenlop, string tengv, string tenmon, string ngayday, int tiet) { try { string sql = "ThemCTGD"; SqlConnection con = new SqlConnection(ConnectDB.getconnect()); con.Open(); SqlCommand cmd = new SqlCommand(sql, con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@tenlop", tenlop); cmd.Parameters.AddWithValue("@tengv", tengv); cmd.Parameters.AddWithValue("@tenmon", tenmon); cmd.Parameters.AddWithValue("@ngayday", ngayday); cmd.Parameters.AddWithValue("@tiet", tiet); cmd.ExecuteNonQuery(); cmd.Dispose(); con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } public void SuaCTGD(string tenlop, string tenmon, string tengv, string ngayday, int tiet) { try { string sql = "SuaCTGD"; SqlConnection con = new SqlConnection(ConnectDB.getconnect()); con.Open(); SqlCommand cmd = new SqlCommand(sql, con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@tenlop", tenlop); cmd.Parameters.AddWithValue("@tenmon", tenmon); cmd.Parameters.AddWithValue("@tengv", tengv); cmd.Parameters.AddWithValue("@ngayday", ngayday); cmd.Parameters.AddWithValue("@tiet", tiet); cmd.ExecuteNonQuery(); cmd.Dispose(); con.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } //Xoa public void XoaCTGD(string tenlop, string ngayday, string tiet) { string sql = "Xoa_CTDG"; SqlConnection con = new SqlConnection(ConnectDB.getconnect()); con.Open(); SqlCommand cmd = new SqlCommand(sql, con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@tenlop", tenlop); cmd.Parameters.AddWithValue("@ngayday", ngayday); cmd.Parameters.AddWithValue("@tiet", tiet); cmd.ExecuteNonQuery(); cmd.Dispose(); con.Close(); } } }
C++
UTF-8
954
2.609375
3
[]
no_license
#include<iostream.h> #include<stdiostr.h> #include<conio.h> #define size 5 int temp; int swap(int&a,int&b) {temp=a; a=b; b=temp; return (a,b);} struct stud { int rno; char name[10]; int marks; }stud[size]; int main() { clrscr(); for(int i=0;i<size;i++) { cout<<"Enter roll no :"; cin>>stud[i].rno; cout<<"Enter name :"; gets(stud[i].name); cout<<"Enter marks :"; cin>>stud[i].marks; } for(i=0;i<size;i++) { cout<<stud[i].rno<<endl; cout<<stud[i].name<<endl; cout<<stud[i].marks<<endl; } cout<<"Sorted"<<endl; for (i=0;i<size;i++) { for (int j=0;j<size;j++) { if(stud[i].marks[i+1] < stud[i].marks) { swap(stud[j],stud[j+1]); } } } for(i=0;i<size;i++) { cout<<stud[i].rno<<endl; cout<<stud[i].name<<endl; cout<<stud[i].marks<<endl; } getch(); return 0; }
C++
UTF-8
1,108
2.546875
3
[]
no_license
#include <SDL.h> #include "RenderEngine.h" #include "PhysicsEngine.h" const int windowWidth{1280}; const int windowHeight{720}; int main(int argc, char* argv[]) { RenderEngine render_engine {windowWidth, windowHeight}; PhysicsEngine physics_engine; physics_engine.g = {0, 1000}; PhysicalRect rect {{100, 100}, {100, 100}, 1.0f, {1000, -200}, 1}; PhysicalRect ground {{windowWidth / 2, windowHeight - 100}, {windowWidth - 100, 50}, 0.0f}; ground.immovable = true; render_engine.addObject( rect ); render_engine.addObject( ground ); physics_engine.addObject( rect ); physics_engine.addObject( ground ); bool running {true}; SDL_Event event; auto timerFreq {SDL_GetPerformanceFrequency()}; auto last {SDL_GetPerformanceCounter()}; while (running) { if (SDL_PollEvent( &event )) { switch(event.type) { case SDL_QUIT: running = false; break; default: break; } } auto current {SDL_GetPerformanceCounter()}; float delta {static_cast<float>(current - last) / timerFreq}; last = current; physics_engine.step( delta/10 ); render_engine.draw(); } return 0; }
JavaScript
UTF-8
4,418
2.953125
3
[]
no_license
import { buildChapter } from '../shared/build-chapter.js'; import { PhysicsBody } from '../shared/classes/physics-body.js'; import { Attractor } from '../shared/classes/attractor.js'; import { degToRad, random } from '../shared/utils.js'; const canvasWidth = 450; const canvasHeight = 500; const canvasBackground = 255; const bodies = []; const attractors = []; let time = 0; const Chapter = buildChapter('chapter-2'); Chapter.init = () => { createCanvas(canvasWidth, canvasHeight); background(canvasBackground); bodies.length = 0; attractors.length = 0; // _chGlobals.ball = new VectBouncingBall(_chGlobals.canvasWidth, _chGlobals.canvasHeight, 10); }; Chapter.beforeDraw = () => { attractors.forEach(attr => { bodies.forEach(body => { attr.attract(body); }); }); } Chapter.afterDraw = () => { background('rgba(150, 150, 150, 0.4)'); [...bodies, ...attractors].forEach(body => body.update()); time += 0; } Chapter.__subChapters = { attractors: [], bodies: [], 'one-object-with-static-attractor': { setup() { const newBody = new PhysicsBody(new p5.Vector(canvasWidth / 3, 2 * canvasHeight / 3), 10); const newAttractor = new Attractor(new p5.Vector(canvasWidth / 2, canvasHeight / 2), 250); newBody.velocity = new p5.Vector(-1.5, 5); newBody.draw = (function(){ fill('white'); stroke('rgba(150, 150, 150, 0)'); circle(this.position.x, this.position.y, 20); }).bind(newBody); newAttractor.draw = (function() { fill('rgba(100, 200, 255, 1)'); circle(this.position.x, this.position.y, 40); }).bind(newAttractor); bodies.push(newBody); attractors.push(newAttractor); }, draw() {}, }, 'one-object-with-oscillating-attractor': { setup() { const newBody = new PhysicsBody(new p5.Vector(canvasWidth / 3, 2 * canvasHeight / 3), 10); const newAttractor = new Attractor(new p5.Vector(canvasWidth / 2, canvasHeight / 2), 250); newBody.velocity = new p5.Vector(-1.5, 5); newBody.draw = (function(){ fill('white'); stroke('rgba(150, 150, 150, 0)'); circle(this.position.x, this.position.y, 20); }).bind(newBody); newAttractor.draw = (function() { fill('rgba(100, 200, 255, 1)'); circle(this.position.x, this.position.y, 40); }).bind(newAttractor); bodies.push(newBody); attractors.push(newAttractor); }, draw() { attractors[0].velocity = new p5.Vector( Math.sin(degToRad(Chapter.__lastTime) * (Math.PI / 16)), Math.cos(degToRad(Chapter.__lastTime) * (Math.PI / 32)) ); } }, 'objects-with-mutual-attraction': { setup() { const newBody = new Attractor(new p5.Vector(canvasWidth / 3, 2 * canvasHeight / 3), 125); const newAttractor = new Attractor(new p5.Vector(canvasWidth / 2, canvasHeight / 2), 250); // newBody.draw = (function(){ // fill('white'); // stroke('rgba(150, 150, 150, 0)'); // circle(this.position.x, this.position.y, 20); // }).bind(newBody); // newAttractor.draw = (function() { // fill('rgba(100, 200, 255, 1)'); // circle(this.position.x, this.position.y, 40); // }).bind(newAttractor); for (let i = 0; i < 4; i += 1) { const posX = random(10, canvasWidth - 10, Math.random); const posY = random(10, canvasHeight - 10, Math.random); const newAttractor = new Attractor(new p5.Vector(posX, posY), Math.random() * 250); newAttractor.G = 0.75 * Math.random(); const fillColor = Math.round(Math.random() * 265); newAttractor.draw = (function() { fill(fillColor); stroke(Math.abs(fillColor - 265)); circle(this.position.x, this.position.y, newAttractor.mass * .5); }); attractors.push(newAttractor); } }, draw() { // attractors[0].velocity = new p5.Vector( // Math.sin(degToRad(Chapter.__lastTime) * (Math.PI / 16)), // Math.cos(degToRad(Chapter.__lastTime) * (Math.PI / 32)) // ); for (let i = 0; i < attractors.length; i += 1) { for (let j = 0; j < attractors.length; j += 1) { if (i === j) { continue; } attractors[i].attract(attractors[j]); attractors[j].attract(attractors[i]); } } } } };
JavaScript
UTF-8
1,730
2.859375
3
[]
no_license
const Discord = require("discord.js"); const client = new Discord.Client(); require("dotenv").config(); // Notre préfixe de commande const prefixCmd = '!'; client.on("ready", () => { console.log("I'm ready !"); }); client.on("message", msg => { // Si le message n'est pas préfixé ou qu'il vient d'un autre bot, nous l'ignorons if (!msg.content.startsWith(prefixCmd) || msg.author.bot) return // Si nous arrivons jusque ici, alors c'est une commande // Nous convertissons la commande sous forme de tableau en prenant soin de retirer le préfixe const args = msg.content.slice(prefixCmd.length).trim().split(/ +/); // Extraction du premier élément de 'args', ce qui correspond à la commande const command = args.shift().toLowerCase(); // À ce stade, args est un tableau ne contenant que les arguments étant donné que la commande a été extraite de celui-ci // On se sert maintenant de la variable 'command' pour le test if (command === "ping") { msg.reply("pong"); } else if (command === "add") { let result = 0; let str = ">>> Je vois que tu n'es pas doué en math <@" + msg.author.id + ">, laisse-moi t'aider :\n"; args.forEach((element, index, arr) => { result += Number(element); if (Number(element) < 0) { element = "(" + element + ")"; } if (index !== arr.length - 1) { str += element + " + "; } else { str += element + " = "; } }); str += result.toString(); msg.channel.send(str); } }); client.login(process.env.BOT_TOKEN);
C++
UTF-8
11,396
3.375
3
[]
no_license
#include "evote.h" // ELECTION ACTIONS void evote::create(name election_name) { // Only TSE can create an election require_auth(name("tse")); // Instantiate multi-index table aka: Get the first row // (1) Owner of table. (2) Account name hits contract deployed to // get_self() gets the name of the contract (evote) elections_table elections(get_self(), get_first_receiver().value); // Next, query the table for the election. auto row = elections.find(election_name.value); // Check if election doesn't exists check(row == elections.end(), "Election name already exists."); // Create election info election_info info = {}; elections.emplace(get_self(), [&]( auto& row){ row.election_name = election_name; row.election_data = info; }); } void evote::erase(name election_name) { // Only tse can delete an election require_auth(name("tse")); // Get election row elections_table elections(get_self(), get_first_receiver().value); auto row = elections.find(election_name.value); check(row != elections.end(), "Election doesn't exists"); // Changes can only be made when election is in PREPARATION status election_info election_data = row->election_data; //check(election_data.status == PREPARATION, "Election is not longer in PREPARATION status."); // todo: UNCOMMENT THIS // Erase elections.erase(row); } void evote::newcat(name election_name, string category_name){ require_auth(name("tse")); // Get election row elections_table elections(get_self(), get_first_receiver().value); auto row = elections.find(election_name.value); check(row != elections.end(), "Election doesn't exists"); // Get election_data election_info election_data = row->election_data; // Assert election is in PREPARATION status check(election_data.status == PREPARATION, "Election must be in PREPARATION status to be changed."); // Assert category doesn't exists auto category = election_data.categories.find(category_name); check(category == election_data.categories.end(), "Category already exists"); // Create new category category_areas areas = {}; election_data.categories.insert({category_name, areas}); // Save to multi index table elections.modify(row, get_self(), [&](auto& row){ row.election_name = election_name; row.election_data = election_data; }); } void evote::delcat(name election_name, string category_name){ require_auth(name("tse")); // Get election row elections_table elections(get_self(), get_first_receiver().value); auto row = elections.find(election_name.value); check(row != elections.end(), "Election doesn't exists"); // Get election_data election_info election_data = row->election_data; // Assert election is in PREPARATION status check(election_data.status == PREPARATION, "Election must be in PREPARATION status to be changed."); // Assert category exists auto category = election_data.categories.find(category_name); check(category != election_data.categories.end(), "Category doesn't exists"); // Delete category election_data.categories.erase(category); // Save to multi index table elections.modify(row, get_self(), [&](auto& row){ row.election_name = election_name; row.election_data = election_data; }); } void evote::newarea(name election_name, string category_name, string area_name){ require_auth(name("tse")); // Get election row elections_table elections(get_self(), get_first_receiver().value); auto row = elections.find(election_name.value); check(row != elections.end(), "Election doesn't exists"); // Get election_data election_info election_data = row->election_data; // Assert election is in PREPARATION status check(election_data.status == PREPARATION, "Election must be in PREPARATION status to be changed."); // Assert category exists auto category = election_data.categories.find(category_name); check(category != election_data.categories.end(), "Category doesn't exists"); // Assert area doesnt exists map<string, candidates> category_area = category->second.area; auto area = category_area.find(area_name); check(area == category_area.end(), "Area already exists"); // Create new area candidates candidate_list = {}; category->second.area.insert({area_name, candidate_list}); // Save to multi index table elections.modify(row, get_self(), [&](auto& row){ row.election_name = election_name; row.election_data = election_data; }); } void evote::delarea(name election_name, string category_name, string area_name){ require_auth(name("tse")); // Get election row elections_table elections(get_self(), get_first_receiver().value); auto row = elections.find(election_name.value); check(row != elections.end(), "Election doesn't exists"); // Get election_data election_info election_data = row->election_data; // Assert election is in PREPARATION status check(election_data.status == PREPARATION, "Election must be in PREPARATION status to be changed."); // Assert category exists auto category = election_data.categories.find(category_name); check(category != election_data.categories.end(), "Category doesn't exists"); // Assert area exists map<string, candidates> category_area = category->second.area; auto area = category_area.find(area_name); check(area != category_area.end(), "Category doesn't exists"); // Delete area category->second.area.erase(area_name); // Save to multi index table elections.modify(row, get_self(), [&](auto& row){ row.election_name = election_name; row.election_data = election_data; }); } // CANDIDATES ACTIONS // This action adds a New Candidate to the blockchain in a given election. // Params: // - election_name // - candidate_type // - candidate_party void evote::newcand(name election_name, string category_name, string area_name, string candidate_party){ // Only tse can delete an election require_auth(name("tse")); // Get election row elections_table elections(get_self(), get_first_receiver().value); auto row = elections.find(election_name.value); check(row != elections.end(), "Election doesn't exists"); // Get election_data election_info election_data = row->election_data; // Assert election is in PREPARATION status check(election_data.status == PREPARATION, "Election must be in PREPARATION status to be changed."); // Assert category exists auto category = election_data.categories.find(category_name); check(category != election_data.categories.end(), "Category doesn't exists"); // Assert area exists map<string, candidates>* category_area = &category->second.area; auto area = category_area->find(area_name); check(area != category_area->end(), "Area doesn't exists"); // Assert candidate doesnt exists map<string, uint64_t> candidates = area->second.candidates; auto candidate = candidates.find(candidate_party); check(candidate == candidates.end(), "Candidate already exists"); // Create new candidate area->second.candidates.insert({candidate_party, 0}); // Save to multi index table elections.modify(row, get_self(), [&](auto& row){ row.election_name = election_name; row.election_data = election_data; }); } void evote::delcand(name election_name, string category_name, string area_name, string candidate_party){ // Only tse can delete an election require_auth(name("tse")); // Get election row elections_table elections(get_self(), get_first_receiver().value); auto row = elections.find(election_name.value); check(row != elections.end(), "Election doesn't exists"); // Get election_data election_info election_data = row->election_data; // Assert election is in PREPARATION status check(election_data.status == PREPARATION, "Election must be in PREPARATION status to be changed."); // Assert category exists auto category = election_data.categories.find(category_name); check(category != election_data.categories.end(), "Category doesn't exists"); // Assert area exists map<string, candidates>* category_area = &category->second.area; auto area = category_area->find(area_name); check(area != category_area->end(), "Area doesn't exists"); // Assert candidate exists map<string, uint64_t> candidates = area->second.candidates; auto candidate = candidates.find(candidate_party); check(candidate != candidates.end(), "Candidate doesn't exists"); // Delete candidate area->second.candidates.erase(candidate_party); elections.modify(row, get_self(), [&](auto& row){ row.election_name = election_name; row.election_data = election_data; }); } void evote::nextstatus(name election_name) { // Only tse can delete an election require_auth(name("tse")); // Get election row elections_table elections(get_self(), get_first_receiver().value); auto row = elections.find(election_name.value); check(row != elections.end(), "Election doesn't exists"); // Change status. Status can only move forward. election_info election_data = row->election_data; check(election_data.status != FINISHED, "Election is already FINISHED."); election_data.status++; // Save to multi index table elections.modify(row, get_self(), [&](auto& row){ row.election_name = election_name; row.election_data = election_data; }); } void evote::newvote(name election_name, string user_area, map<string, string> user_votes) { // Only tse can delete an election require_auth(name("voter")); // Get election row elections_table elections(get_self(), get_first_receiver().value); auto row = elections.find(election_name.value); check(row != elections.end(), "Election doesn't exists"); // Get election_data election_info election_data = row->election_data; // Update candidates votes string voter_area; for (auto const& candidate : user_votes){ // Assert category exists auto category = election_data.categories.find(candidate.first); check(category != election_data.categories.end(), "Category doesn't exists"); // Assert area exists map<string, candidates>* category_area = &category->second.area; if (candidate.first == "alcalde" || candidate.first == "diputado_regional") { voter_area = user_area; } else { voter_area = "nacional"; } auto area = category_area->find(voter_area); check(area != category_area->end(), "Area doesn't exists"); // Assert candidate exists map<string, uint64_t>* candidates = &area->second.candidates; auto party = candidates->find(candidate.second); check(party != candidates->end(), "Candidate doesn't exists"); // Add vote to candidate party->second++; } // Save to multi index table elections.modify(row, get_self(), [&](auto& row){ row.election_name = election_name; row.election_data = election_data; }); }
C#
UTF-8
1,005
2.828125
3
[]
no_license
using System.Configuration; using Serilog; using Task4.BL.Enum; namespace Task4.BL.Logger { public static class LoggerFactory { public static ILogger GetLogger(LoggerType type) { switch (type) { case LoggerType.Console: { return new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.Console() .CreateLogger(); } case LoggerType.File: { return new LoggerConfiguration() .MinimumLevel.Verbose() .WriteTo.File(ConfigurationManager.AppSettings.Get("loggerFile"), outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] {Message:lj}{NewLine}{Exception}") .CreateLogger(); } } return null; } } }
Java
UTF-8
1,960
2.4375
2
[]
no_license
package com.springangular.application.SpringAngular.controller; import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import com.springangular.application.SpringAngular.model.User; import com.springangular.application.SpringAngular.service.UserService; @Controller public class UserController { private static final Logger logger = LoggerFactory.getLogger(UserController.class); @Autowired UserService userService; /* * Endpoint to save a User bean in the Database * * @param User bean * * @return saved User bean in the Database */ @RequestMapping(value = "/saveUser", method = RequestMethod.POST, headers = "Accept=application/json") @ResponseBody public User saveUser(@RequestBody User user) { logger.info("Saving User Bean in the Database"); User responseUser = userService.saveUser(user); return responseUser; } /* * End point to retrieve a User bean from the Database * * @param User bean * * @return User bean from the database */ @RequestMapping(value = "/validateUser", method = RequestMethod.POST, headers = "Accept=application/json") @ResponseBody public Optional<User> getUser(@RequestBody User data) { logger.info("Validating User Bean in the Database" + data); Optional<User> user = userService.getUserByEmail(data.getEmail(), data.getPassword()); return user; } @RequestMapping(value = "/login") public ModelAndView login(ModelAndView model) { ModelAndView view = new ModelAndView(); view.setViewName("login"); return view; } }
C++
UTF-8
1,109
2.671875
3
[]
no_license
#include <iostream> #include <cstdlib> #include <cstdio> #include <memory> #include <gal/dll/helper.hpp> #include "myclass.hpp" using namespace std; //MyClass* (*create)(); //void (*destroy)(MyClass*); /* void load(void*& handle,char const * filename) { handle = dlopen(filename, RTLD_LAZY); if(handle == NULL) { cerr << dlerror() << endl; exit(0); } create = (MyClass* (*)())dlsym(handle, "create_object"); destroy = (void (*)(MyClass*))dlsym(handle, "destroy_object"); MyClass::create_ = (MyClass* (*)())dlsym(handle, "create_object"); } */ int main(int argc, char **argv) { typedef gal::dll::helper<MyClass> H; std::shared_ptr<MyClass> c1; { std::shared_ptr<H> h1(new H("test/dll/sh1/libtest_dll_sh1_0_so_db.so", "MyClass")); h1->open(); //c1.reset(h1->create(), gal::dll::deleter<H>(h1)); c1 = h1->make_shared(); } gal::dll::helper<MyClass> h2("test/dll/sh2/libtest_dll_sh2_0_so_db.so","MyClass");; h2.open(); //MyClass* c1 = h1.create(); //MyClass* c2 = h2.create(); c1->DoSomething(); //c2->DoSomething(); //h1.destroy(c1); //h2.destroy(c2); }
Java
UTF-8
984
1.804688
2
[]
no_license
package com.example.prana.openlibrary; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; public class Kddiarywimpy extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_kddiarywimpy); } public void buy14(View view) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.amazon.in/Playing-My-Way-Sachin-Tendulkar/dp/1473605172/ref=sr_1_1?s=books&ie=UTF8&qid=1507045901&sr=1-1&keywords=playing+it+my+way")); startActivity(browserIntent); } public void pdf14(View view) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.nudge-book.com/wp-content/uploads/2014/11/Read-an-extract-from-Playing-It-My-Way.pdf")); startActivity(browserIntent); } }
C
UTF-8
804
3.25
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<string.h> char *to_ascii(char *nul) { char *res = calloc(1,strlen(nul)*sizeof(char)); char *bis = res; int taille = strlen(nul); for(int i = 0 ; i < taille ; i++) { if (nul[i] == -30) { *res = (char)39; i+=2; res += 1; } else { *res = nul[i]; res += 1; } } return bis; } /*int main() { char test[45656] = "Queen Mary She’s my friend Yes, I believe I’ll go see her again Nobody has to guess That Baby can’t be blessed Till she sees finally that she’s like all the rest With her fog, her amphetamine and her pearls She takes just like a woman, yes She makes love just like a woman, yes, she does And she aches just like a woman But she breaks just like a little girl"; printf("res = %s\n",to_ascii(test)); }*/
Python
UTF-8
3,007
3.859375
4
[]
no_license
class Pose: def __init__(self, points): assert len(points) == 25, "Not enough points!" self.__points = points self.__nose = points[0] self.__neck = points[1] self.__right_shoulder = points[2] self.__right_elbow = points[3] self.__right_wrist = points[4] self.__left_shoulder = points[5] self.__left_elbow = points[6] self.__left_wrist = points[7] self.__mid_hip = points[8] self.__right_hip = points[9] self.__right_knee = points[10] self.__right_ankle = points[11] self.__left_hip = points[12] self.__left_knee = points[13] self.__left_ankle = points[14] self.__right_eye = points[15] self.__left_eye = points[16] self.__right_ear = points[17] self.__left_ear = points[18] self.__left_big_toe = points[19] self.__left_small_toe = points[20] self.__left_heel = points[21] self.__right_big_toe = points[22] self.__right_small_toe = points[23] self.__right_heel = points[24] @property def points(self): return self.__points @property def nose(self): return self.__nose @property def neck(self): return self.__neck @property def right_shoulder(self): return self.__right_shoulder @property def right_elbow(self): return self.__right_elbow @property def right_wrist(self): return self.__right_wrist @property def left_shoulder(self): return self.__left_shoulder @property def left_elbow(self): return self.__left_elbow @property def left_wrist(self): return self.__left_wrist @property def mid_hip(self): return self.__mid_hip @property def right_hip(self): return self.__right_hip @property def right_knee(self): return self.__right_knee @property def right_ankle(self): return self.__right_ankle @property def left_hip(self): return self.__left_hip @property def left_knee(self): return self.__left_knee @property def left_ankle(self): return self.__left_ankle @property def right_eye(self): return self.__right_eye @property def left_eye(self): return self.__left_eye @property def right_ear(self): return self.__right_ear @property def left_ear(self): return self.__left_ear @property def left_big_toe(self): return self.__left_big_toe @property def left_small_toe(self): return self.__left_small_toe @property def left_heel(self): return self.__left_heel @property def right_big_toe(self): return self.__right_big_toe @property def right_small_toe (self): return self.__right_small_toe @property def right_heel(self): return self.__right_heel
Shell
UTF-8
1,324
3.671875
4
[]
no_license
#!/bin/bash CONFIRMED_LIST="" if [ "x$1" = "x--sites" ]; then shift while [ "x$1" != "x" ]; do CONFIRMED_LIST="$CONFIRMED_LIST $1" shift done else YES=$([ "x$1" = "x-y" ] || [ "x$1" == "x--yes" ] && echo "1" || echo "0") for i in $(./ls.sh); do if [ $YES == 1 ]; then echo "$i..." CONFIRM=y elif [ "x$CONFIRM" != "xq" ]; then echo "Upgrade $i? [y/n/q]" read CONFIRM fi if [ "x$CONFIRM" = "xy" ]; then CONFIRMED_LIST="$CONFIRMED_LIST $i" fi done fi if [ "x$SKIP_DOCKER" != xYES ]; then for i in $(cat */docker-compose.yml | grep image | cut -d: -f2 | sort | uniq); do echo docker pull $i docker pull $i done docker pull $(cat docker/Dockerfile | grep FROM | cut -d\ -f2) docker pull $(cat phpmyadmin/Dockerfile | grep FROM | cut -d\ -f2) set -e docker build -t fovea/wordpress docker docker build -t fovea/phpmyadmin phpmyadmin else set -e fi echo echo "Let's go!" echo for i in $CONFIRMED_LIST; do ./upgrade.sh "$i" if [ "x$SLEEP_BETWEEN" != "x" ]; then sleep "$SLEEP_BETWEEN" fi if [ "x$UPDATE_WORDPRESS" = "xYES" ]; then SKIP_DOCKER=YES ./update.sh "$i" fi done # sudo service nginx reload
PHP
UTF-8
1,529
2.765625
3
[ "MIT" ]
permissive
<?php namespace App\Front\Forms; use Nette; use Nette\Application\UI\Form; class commentFormFactory extends Nette\Application\UI\Presenter { use Nette\SmartObject; /** @var FormFactory */ private $factory; private $database; private $user; private $productId; public function __construct(FormFactory $factory, Nette\Database\Context $database, \Nette\Security\User $user) { $this->factory = $factory; $this->database = $database; $this->user = $user; } /** * @return Form */ public function create($productId, callable $onSuccess) { $this->productId = $productId; $form = $this->factory->create(); $form->addTextArea('content', 'Komentář:') ->setRequired(); $form->addSubmit('send', 'Publikovat komentář'); $form->onSuccess[] = function (Form $form, $values) use ($onSuccess) { try { bdump($this->getUser()); bdump($this->productId); $this->database->table('recenzia')->insert([ 'cisloproduktu_id' => $this->productId, 'username' => $this->getUser()->getIdentity()->username, 'content' => $values->content, ]); } catch (Nette\Security\AuthenticationException $e) { $form->addError('We cannot add your post.'); return; } $onSuccess(); }; return $form; } }
Java
UTF-8
2,135
2.28125
2
[]
no_license
package com.example.myapplication.ui.fragment; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.TextView; import com.example.myapplication.R; import com.example.myapplication.adapter.BookAdapter; import com.example.myapplication.bean.Book; import com.example.myapplication.ui.MakeOrderActivity; import org.litepal.LitePal; import java.util.ArrayList; import java.util.List; /** * 首页 */ public class HomeFragment extends Fragment { private ArrayList<Book> mDate=new ArrayList<>(); private ListView mList; private BookAdapter adapter; private TextView mTvState; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View layout=inflater.inflate(R.layout.fragment_home,null); initview(layout); initdate(); initevent(); return layout; } private void initevent() { adapter.setOnBuyLitner(new BookAdapter.OnBuyLitner() { @Override public void buy(int pos) { startActivity(new Intent(getActivity(), MakeOrderActivity.class) .putExtra("data",mDate.get(pos))); } }); } public void initdate() { List<Book> bookList = LitePal.findAll(Book.class); mDate.clear(); if(bookList.size()==0){ mList.setVisibility(View.GONE); mTvState.setVisibility(View.VISIBLE); mTvState.setText("暂无数据"); }else { mDate.addAll(bookList); mList.setVisibility(View.VISIBLE); mTvState.setVisibility(View.GONE); } adapter.notifyDataSetChanged(); } public void initview(View layout) { mTvState = (TextView) layout.findViewById(R.id.tv_state); mList = (ListView) layout.findViewById(R.id.list); adapter = new BookAdapter(getActivity(),mDate); mList.setAdapter(adapter); } }
C
UTF-8
4,762
2.796875
3
[]
no_license
/* * Threads.c * =========================== * Exercise 2 * =========================== * Name: Assaf Ben Yishay * =========================== */ #include "Threads.h" int LaunchThreadsAndWait(char* file_path, char* log_path) { HANDLE threads_handles[NUM_OF_TESTS]; LPTHREAD_START_ROUTINE threads_routines[NUM_OF_TESTS]; DWORD threads_IDs[NUM_OF_TESTS]; DWORD threads_exitcodes[NUM_OF_TESTS]; ThreadArgument threads_arguments[NUM_OF_TESTS]; int i; int retVal=0; //put the routines into array for easier managments threads_routines[0]=(LPTHREAD_START_ROUTINE)GetFileExtesionRoutine; threads_routines[1]=(LPTHREAD_START_ROUTINE)GetFileSizeRoutine; threads_routines[2]=(LPTHREAD_START_ROUTINE)GetFileCreationTimeRoutine; threads_routines[3]=(LPTHREAD_START_ROUTINE)GetFileLastModifiedTimeRoutine; threads_routines[4]=(LPTHREAD_START_ROUTINE)GetFileFirstBytesRoutine; //launch the threads for(i=0;i<NUM_OF_TESTS;i++) { threads_arguments[i].file_path=file_path; threads_handles[i]=CreateThread(NULL, 0, threads_routines[i], &threads_arguments[i], 0, &threads_IDs[i]); } WaitForMultipleObjects(NUM_OF_TESTS,threads_handles,TRUE,INFINITE); //retrive exitcodes from all threads for(i=0;i<NUM_OF_TESTS;i++) { GetExitCodeThread(threads_handles[i],&threads_exitcodes[i]); if(ERROR_SUCCESS!=threads_exitcodes[i]) { retVal=threads_exitcodes[i]; } } LogTestsResults(file_path,log_path,threads_arguments,threads_exitcodes); //close handles and free the memory which was allocated for the threads strings results for(i=0;i<NUM_OF_TESTS;i++) { CloseHandle(threads_handles[i]); if(NULL!=threads_arguments[i].result) { free(threads_arguments[i].result); } } return retVal; } int GetFileExtesionRoutine(ThreadArgument* thread_arguments) { char *dot = NULL; char *extension = NULL; Sleep(DEFUALT_SLEEP_TIME); dot=strrchr(thread_arguments->file_path, '.'); if(!dot || dot == thread_arguments->file_path) { thread_arguments->result=NULL; return ErrorHandler(UNKNOWN_EXTENSION_ERR,thread_arguments->file_path); } extension=(char*)malloc(strlen(dot)+1); if(!extension) { thread_arguments->result=NULL; return ErrorHandler(MEMORY_ALLOCATION_ERR,NULL); } strcpy(extension,dot); thread_arguments->result=extension; return ERROR_SUCCESS; } int GetFileSizeRoutine(ThreadArgument* thread_arguments) { HANDLE *file_handle=NULL; DWORD file_size; char *size_string=NULL; Sleep(DEFUALT_SLEEP_TIME); file_handle=CreateFileHandle(thread_arguments->file_path); if(*file_handle == INVALID_HANDLE_VALUE) { thread_arguments->result=NULL; return ErrorHandler(CREATE_FILE_HANDLE_ERR,thread_arguments->file_path); } size_string=(char*)malloc(SIZE_STRING_LENGTH*sizeof(char)); if(!size_string) { //safely return CloseFileHandle(file_handle); thread_arguments->result=NULL; return ErrorHandler(MEMORY_ALLOCATION_ERR,NULL); } if(!(file_size=GetFileSize(*file_handle,NULL))) { //safely return free(size_string); CloseFileHandle(file_handle); thread_arguments->result=NULL; return ErrorHandler(GET_FILE_SIZE_ERR,NULL); } CloseFileHandle(file_handle); thread_arguments->result=FileSizeToString(file_size,size_string); return ERROR_SUCCESS; } int GetFileCreationTimeRoutine(ThreadArgument* thread_arguments) { Sleep(DEFUALT_SLEEP_TIME); thread_arguments->result=GetFileTimeString(thread_arguments->file_path,CREATED); return thread_arguments->result==NULL?GET_FILE_TIME_ERR:ERROR_SUCCESS; } int GetFileLastModifiedTimeRoutine(ThreadArgument* thread_arguments) { Sleep(DEFUALT_SLEEP_TIME); thread_arguments->result=GetFileTimeString(thread_arguments->file_path,MODIFIED); return thread_arguments->result==NULL?GET_FILE_TIME_ERR:ERROR_SUCCESS; } int GetFileFirstBytesRoutine(ThreadArgument* thread_arguments) { FILE *input_file=NULL; char *first_bytes=NULL; Sleep(DEFUALT_SLEEP_TIME); input_file = fopen(thread_arguments->file_path,"r"); if(!input_file) { //safely return thread_arguments->result=NULL; ErrorHandler(OPEN_FILE_ERR,thread_arguments->file_path); return OPEN_FILE_ERR; } first_bytes=(char*)malloc(NUM_OF_BYTES+1); //the number of bytes can be changed using the #define in the .h file if(!first_bytes) { //safely return fclose(input_file); thread_arguments->result=NULL; return ErrorHandler(MEMORY_ALLOCATION_ERR,NULL); } first_bytes[fread(first_bytes,1,NUM_OF_BYTES,input_file)]='\0'; fclose(input_file); thread_arguments->result=first_bytes; return ERROR_SUCCESS; }
Python
UTF-8
1,475
2.78125
3
[ "MIT" ]
permissive
from random import randint from time import sleep from src.utils import init_clients, init_dht from sys import argv if __name__ == '__main__': try: try: flag_idx = argv.index("--clients") clients = int(argv[flag_idx + 1]) except: clients = 1 try: flag_idx = argv.index("--iterMax") iterMax = int(argv[flag_idx + 1]) print(f"{iterMax} iterações (max)") except: iterMax = float('inf') print('Ctrl+C para sair') print('\nCarregando nós ...') DHT = init_dht(8) Clients = init_clients(clients) for node in DHT: node.join() for node in DHT: node.getNeighbors() print("Publicando") it = 0 while it < iterMax: for c in Clients: key = randint(0, pow(2,32)) c.put(key, str(randint(0, 1000))) c.get(key) sleep(0.5) it = it + 1 print("Aguarde desconexão") for node in DHT: node.disconnect() for c in Clients: c.disconnect() print("Programa finalizado!") except KeyboardInterrupt: print("Aguarde desconexão") for node in DHT: node.disconnect() for c in Clients: c.disconnect() print("Programa finalizado!")
Java
UTF-8
958
2.875
3
[ "MIT" ]
permissive
package seedu.address.model.person; import static java.util.Objects.requireNonNull; //@@author liliwei25 /** * Represents a profile picture for Person */ public class ProfilePicture { private final String imageLocation; /** * Validates given location of image. */ public ProfilePicture(String location) { requireNonNull(location); imageLocation = location; } public String getLocation() { return imageLocation; } @Override public String toString() { return imageLocation; } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof ProfilePicture // instanceof handles nulls && this.imageLocation.equals(((ProfilePicture) other).imageLocation)); // state check } @Override public int hashCode() { return imageLocation.hashCode(); } }
C
UTF-8
2,202
3.015625
3
[]
no_license
#include "stdio.h" #include "stdlib.h" #include "string.h" #define MAX_PATTERN_LEN (1*1024*1024) #define MAX_GENOME_LEN (1*1024*1024) #define MAX_SYMBOLS (27) const char possibleSyms[4] = {'A', 'C', 'G', 'T'}; int main(int argc, char** argv) { char* pattern; char* genome; pattern = (char* )malloc(sizeof(char)*MAX_PATTERN_LEN); memset(pattern, 0, sizeof(char)*MAX_PATTERN_LEN); genome = (char* )malloc(sizeof(char)*MAX_GENOME_LEN); memset(genome, 0, sizeof(char)*MAX_GENOME_LEN); scanf("%s",pattern); scanf("%s",genome); unsigned int* stateTable[MAX_SYMBOLS]; stateTable['A'-'A'] = (unsigned int* )malloc((strlen(pattern)+1)*sizeof(unsigned int)); memset(stateTable['A'-'A'], 0, ((strlen(pattern)+1)*sizeof(unsigned int))); stateTable['C'-'A'] = (unsigned int* )malloc((strlen(pattern)+1)*sizeof(unsigned int)); memset(stateTable['C'-'A'], 0, ((strlen(pattern)+1)*sizeof(unsigned int))); stateTable['G'-'A'] = (unsigned int* )malloc((strlen(pattern)+1)*sizeof(unsigned int)); memset(stateTable['G'-'A'], 0, ((strlen(pattern)+1)*sizeof(unsigned int))); stateTable['T'-'A'] = (unsigned int* )malloc((strlen(pattern)+1)*sizeof(unsigned int)); memset(stateTable['T'-'A'], 0, ((strlen(pattern)+1)*sizeof(unsigned int))); for (int i=0; i<strlen(pattern); i++) stateTable[pattern[i]-'A'][i] = (i+1); unsigned int prefixState=0; for (int i=1; i<strlen(pattern)+1; i++) { for (int j=0; j<4; j++) { if (pattern[i] == possibleSyms[j]) continue; stateTable[possibleSyms[j]-'A'][i] = stateTable[possibleSyms[j]-'A'][prefixState]; } if (i < strlen(pattern)) prefixState = stateTable[pattern[i]-'A'][prefixState]; } unsigned int nextState = 0; for (int i=0; i<strlen(genome); i++) { nextState = stateTable[genome[i]-'A'][nextState]; if (nextState == strlen(pattern)) printf("%d ",i-strlen(pattern)+1); } free(pattern); free(genome); free(stateTable['A'-'A']); free(stateTable['C'-'A']); free(stateTable['G'-'A']); free(stateTable['T'-'A']); return 0; }
C#
UTF-8
710
3.078125
3
[ "MIT" ]
permissive
namespace SixtyFiveOhTwo.Instructions.Encoding { public class ImmediateAddressInstructionEncoder : IInstructionEncoder { private readonly InstructionBase _instruction; private readonly byte _value; public ImmediateAddressInstructionEncoder(InstructionBase instruction, byte value) { _instruction = instruction; _value = value; } public void Write(ref ushort address, byte[] memory) { memory[address++] = _instruction.OpCode; memory[address++] = _value; } public string ToStringMnemonic() { return $"{_instruction.Mnemonic} #${_value:X2}"; } } }
Swift
UTF-8
1,324
2.9375
3
[]
no_license
// // ViewController.swift // customcell // // Created by Glen Jantz on 3/20/17. // Copyright © 2017 Glen Jantz. All rights reserved. // import UIKit class TableViewController: UITableViewController, CustomCellDelegate { var num = [0,2,3,4,5,6,7,8,9,10,11,12,13,14,15] var total = 0 @IBOutlet var totalLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MyCell", for: indexPath) as! BinaryTableViewCell let temp = (pow(10.0,num[indexPath.row])) cell.Label.text = String(describing: temp) // cell.number = Int(pow(10.0,num[indexPath.row])) cell.delegate = self return cell } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return num.count } func buttonPressed(withValue value: Int) { total += value totalLabel.text = String(total) } }
Java
UTF-8
33,659
1.75
2
[]
no_license
package hok.chompzki.hivetera.client.gui; import hok.chompzki.hivetera.HiveteraMod; import hok.chompzki.hivetera.api.IArticle; import hok.chompzki.hivetera.registrys.ReserchRegistry; import hok.chompzki.hivetera.research.data.Chapeter; import hok.chompzki.hivetera.research.data.DataHelper; import hok.chompzki.hivetera.research.data.PlayerResearch; import hok.chompzki.hivetera.research.data.PlayerResearchStorage; import hok.chompzki.hivetera.research.data.Research; import hok.chompzki.hivetera.research.data.network.PlayerStorageDelissenMessage; import hok.chompzki.hivetera.research.data.network.PlayerStorageFaveMessage; import hok.chompzki.hivetera.research.data.network.PlayerStoragePullMessage; import hok.chompzki.hivetera.research.data.network.PlayerStorageSyncHandler; import hok.chompzki.hivetera.research.logic.ResearchLogicNetwork; import java.awt.Rectangle; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.UUID; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.FontRenderer; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.gui.GuiScreen; import net.minecraft.client.renderer.RenderHelper; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.util.EnumChatFormatting; import net.minecraft.util.IIcon; import net.minecraft.util.ResourceLocation; import net.minecraft.util.StatCollector; import org.lwjgl.input.Keyboard; import org.lwjgl.input.Mouse; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; public class GuiResearchBook extends GuiScreen { public static final ResourceLocation bioBookBG = new ResourceLocation(HiveteraMod.MODID + ":textures/client/gui/GuiBioBookBG.png"); public static final ResourceLocation bioSidebarBG = new ResourceLocation(HiveteraMod.MODID + ":textures/client/gui/book_sidebar.png"); public static final ResourceLocation sparkleBG = new ResourceLocation(HiveteraMod.MODID + ":textures/client/gui/icons/sparkle.png"); private static final int cellSize = 28; private static final int guiMapTop = -7 * cellSize - 112; private static final int guiMapLeft = -7 * cellSize - 112; private static final int guiMapBottom = 16 * cellSize - 77; private static final int guiMapRight = 16 * cellSize - 77; protected int knowledgePaneWidth = 256; protected int knowledgePaneHeight = 202; protected double field_74117_m; protected double field_74115_n; protected double guiMapX; protected double guiMapY; protected int mouseX = 0; protected int mouseY = 0; private int isMouseButtonDown = 0; private int lastMouseButtonDown = 0; protected final float speed = 10.0f; ItemStack book = null; UUID player = null; Research tooltipResearch = null; static Random random = new Random(); private GuiArticle article = null; private EntityPlayer reader = null; private Chapeter selectedChapeter = Chapeter.chapeters.get(0); private Chapeter tooltipChapeter = null; public GuiResearchBook(EntityPlayer player) { this.reader = player; this.book = player.inventory.getCurrentItem(); this.player = UUID.fromString(DataHelper.getOwner(book)); short short1 = 141; short short2 = 141; this.field_74117_m = this.guiMapX = (double)(0 * cellSize - short1 / 2 - 12); this.field_74115_n = this.guiMapY = (double)(0 * cellSize - short2 / 2); this.article = GuiInventoryOverlay.craftingHelper.getBooked(); if(article != null){ article.setLast(this); article.setWorldAndResolution(Minecraft.getMinecraft(), width, height, null); }else{ article = new GuiArticle(reader, ReserchRegistry.tutorialResearch, this.player); article.setLast(this); article.setWorldAndResolution(Minecraft.getMinecraft(), width, height, null); } } @Override public void initGui(){ this.buttonList.clear(); this.buttonList.add(new GuiButton(0, calculateLeft() + knowledgePaneWidth - 95, calculateTop() + knowledgePaneHeight - 25, 80, 20, StatCollector.translateToLocal("gui.done"))); if(article != null) this.article.initGui(this.buttonList); } @Override public void setWorldAndResolution(Minecraft minecraft, int par2, int par3) { //this.guiParticles = new GuiParticle(minecraft); this.fontRendererObj = minecraft.fontRenderer; this.mc = minecraft; this.width = par2; this.height = par3; this.buttonList.clear(); this.initGui(); } @Override protected void actionPerformed(GuiButton button){ if (button.id == 0) { this.mc.displayGuiScreen((GuiScreen)null); this.mc.setIngameFocus(); }else if(1 <= button.id && button.id <= 3){ if(this.article != null){ this.article.actionPerformed(button); return; } } super.actionPerformed(button); } @Override protected void keyTyped(char par1, int par2) { if (par2 == this.mc.gameSettings.keyBindInventory.getKeyCode()) { this.mc.displayGuiScreen((GuiScreen)null); this.mc.setIngameFocus(); return; }else if(article != null){ if(par2 == Keyboard.KEY_1){ article.back(); return; }else if(par2 == Keyboard.KEY_2 && DataHelper.belongsTo(reader, reader.getCurrentEquippedItem())){ HiveteraMod.network.sendToServer(new PlayerStorageFaveMessage(reader.getGameProfile().getId().toString(), article.getArticle().getCode())); return; }else if(par2 == Keyboard.KEY_3){ article.next(); return; } } super.keyTyped(par1, par2); } @Override protected void mouseClicked(int x, int y, int btn) { if(btn == 0 && this.tooltipResearch != null){ //this.mc.displayGuiScreen(new GuiDescription(this, tooltipKnowledge.getDescription())); article = new GuiArticle(reader, tooltipResearch, player); article.setLast(this); article.setWorldAndResolution(mc, width, height, null); this.initGui(); }else if(btn == 1 && this.tooltipResearch != null && DataHelper.belongsTo(reader, reader.getCurrentEquippedItem())){ //TODO: if(tooltipResearch.getContent().getFaved() == null) // return; HiveteraMod.network.sendToServer(new PlayerStorageFaveMessage(reader.getGameProfile().getId().toString(), tooltipResearch.getCode())); //tooltipResearch.getContent().selected(!b); }else if(btn == 1 && this.tooltipChapeter != null){ this.selectedChapeter = this.tooltipChapeter; article = new GuiArticle(reader, tooltipChapeter, player); article.setLast(this); article.setWorldAndResolution(mc, width, height, null); this.initGui(); }else if(btn == 0 && this.tooltipChapeter != null){ this.selectedChapeter = this.tooltipChapeter; } else{ super.mouseClicked(x, y, btn); } } public void addToMapPos(double x, double y){ this.guiMapX += x; this.guiMapY += y; this.field_74117_m = this.guiMapX; this.field_74115_n = this.guiMapY; if (this.guiMapY-20 < (double)guiMapTop) { this.guiMapY = (double)guiMapTop + 20; } if (this.guiMapX-20 < (double)guiMapLeft) { this.guiMapX = (double)guiMapLeft + 20; } if (this.guiMapY >= (double)guiMapBottom) { this.guiMapY = (double)(guiMapBottom - 1); } if (this.guiMapX >= (double)guiMapRight) { this.guiMapX = (double)(guiMapRight - 1); } } @Override public void drawScreen(int par1, int par2, float par3) { GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); float speedY = 0.0f; float speedX = 0.0f; if(Keyboard.isKeyDown(this.mc.gameSettings.keyBindForward.getKeyCode())){ speedY -= speed * par3; } if(Keyboard.isKeyDown(this.mc.gameSettings.keyBindBack.getKeyCode())){ speedY += speed * par3; } if(Keyboard.isKeyDown(this.mc.gameSettings.keyBindLeft.getKeyCode())){ speedX -= speed * par3; } if(Keyboard.isKeyDown(this.mc.gameSettings.keyBindRight.getKeyCode())){ speedX += speed * par3; } this.addToMapPos(speedX, speedY); if (Mouse.isButtonDown(0)) { int k = calculateLeft(); int l = calculateTop(); int i1 = k + 8; int j1 = l + 17; if ((this.isMouseButtonDown == 0 || this.isMouseButtonDown == 1) && par1 >= i1 && par1 < i1 + 224 && par2 >= j1 && par2 < j1 + 155) { if (this.isMouseButtonDown == 0) { this.isMouseButtonDown = 1; } else { this.addToMapPos(-(double)(par1 - this.mouseX), -(double)(par2 - this.mouseY)); } this.mouseX = par1; this.mouseY = par2; } } else { this.isMouseButtonDown = 0; } GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); this.drawDefaultBackground(); GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); this.genBioBookBackground(par1, par2, par3); //Draw Relations GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); this.drawIcons(par1, par2, par3); GL11.glEnable(GL11.GL_BLEND); GL11.glPushMatrix(); GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); GuiArticle.drawBackground(mc, this, par1, par2, par3); GL11.glPopMatrix(); GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); this.drawOverlay(par1, par2, par3); GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); super.drawScreen(par1, par2, par3); GL11.glDisable(GL11.GL_BLEND); this.drawChapeterSidebar(par1, par2, par3); if(article != null){ GL11.glColor3f(1.0f, 1.0f, 1.0f); article.drawScreen(par1, par2, par3); GL11.glColor3f(1.0f, 1.0f, 1.0f); article.drawTooltip(); IArticle research = article.getArticle(); int k = this.calculateLeft() + this.getScreenWidth(); int b0 = this.calculateTop(); GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); this.renderTitle(research, k + 15, b0); GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); if(research instanceof Research) this.drawIcon((Research) research, k, b0 - 13, true, true); if(research instanceof Chapeter) this.drawIcon((Chapeter) research, k, b0 - 13, true, true); } if(tooltipResearch != null){ GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); this.drawTooltip(par1, par2, par3); } if(this.tooltipChapeter != null){ GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); this.drawChapeterTooltip(par1, par2, par3); } GL11.glColor4f(1.0f, 1.0f, 1.0f, 1.0F); } public void drawChapeterTooltip(int par1, int par2, float par3){ this.renderChapeterToolTip(this.tooltipChapeter, par1, par2); } protected void renderChapeterToolTip(Chapeter hoveringChapeter2, int p_146285_2_, int p_146285_3_) { List list = new ArrayList(); list.add(EnumChatFormatting.GOLD + hoveringChapeter2.getTitle()); list.add(hoveringChapeter2.getDesc()); drawHoveringText(list, p_146285_2_, p_146285_3_, Minecraft.getMinecraft().fontRenderer); } private void drawChapeterSidebar(int par1, int par2, float par3) { //TODO: WORK HERE! int i1 = calculateLeft() - 10; int j1 = calculateTop() + 14; int i = 1; PlayerResearch player = PlayerResearchStorage.instance(true).get(this.player); if(player == null){ HiveteraMod.network.sendToServer(new PlayerStoragePullMessage(this.player)); return; } boolean owner = this.player.equals(this.reader.getGameProfile().getId()); for(Chapeter chap : Chapeter.chapeters){ if(!ResearchLogicNetwork.instance().hasUnlocked(player, chap)) continue; this.mc.renderEngine.bindTexture(chap.getIcon()); this.func_146110_a(i1, j1, this.selectedChapeter == chap ? 26 : 0, 0, 26, 26, 52, 26); if(chap != this.selectedChapeter && owner && ResearchLogicNetwork.instance().hasNew(player, chap)){ this.mc.renderEngine.bindTexture(sparkleBG); this.func_146110_a(i1, j1, 0, 0, 26, 26, 26, 26); } Rectangle rect = new Rectangle(i1, j1, 26, 26); if(rect.contains(new Rectangle(par1, par2, 2, 2))){ this.tooltipChapeter = chap; } j1 += 26; } this.mc.renderEngine.bindTexture(this.bioBookBG); } @Override public void updateScreen() { super.updateScreen(); } protected void genBioBookBackground(int par1, int par2, float par3) { int k = (int) this.guiMapX; int l = (int) this.guiMapY; int i1 = calculateLeft(); int j1 = calculateTop(); int k1 = i1 + 16; int l1 = j1 + 17; //this.zLevel = 0.0F; GL11.glPushMatrix(); this.mc.renderEngine.bindTexture(TextureMap.locationBlocksTexture); int i2 = k + 288 >> 4; int j2 = l + 288 >> 4; int k2 = (k + 288) % 16; int l2 = (l + 288) % 16; int i3; int j3; int k3; for (i3 = 0; i3 * 16 - l2 < 155; i3++) { float f1 = 0.6F - (float)(j2 + i3) / 25.0F * 0.3F; GL11.glColor4f(f1, f1, f1, 1.0F); for (k3 = 0; k3 * 16 - k2 < 224; k3++) { random.setSeed((long)(1234 + i2 + k3)); random.nextInt(); j2 = Math.max(0, j2); i3 = Math.max(0, i3); j3 = random.nextInt(1 + j2 + i3) + (j2 + i3) / 2; IIcon icon = Blocks.sand.getIcon(0, 0); if (j3 <= 37 && j2 + i3 != 35) { if (j3 == 22) { if (random.nextInt(2) == 0) { icon = Blocks.sand.getIcon(0, 0); } else { icon = Blocks.gravel.getIcon(0, 0); } } else if (j3 == 10) { icon = Blocks.log.getIcon(2, 0); } else if (j3 == 8) { icon = Blocks.log.getIcon(0, 0); } else if (j3 > 4) { icon = Blocks.dirt.getIcon(0, 0); } else if (j3 > 0) { icon = Blocks.grass.getIcon(1, 0); } } else { icon = Blocks.stone.getIcon(0, 0); } GL11.glColor3f(1.0f, 1.0f, 1.0f); this.drawTexturedModelRectFromIcon(k1 + k3 * 16 - k2, l1 + i3 * 16 - l2, icon, 16, 16); } } GL11.glPopMatrix(); /* for (i3 = 0; i3 < knowledgeList.size(); ++i3) { Knowledge knowledge = knowledgeList.get(i3); if (knowledge.parentKnowledge != null && knowledgeList.contains(knowledge.parentKnowledge)) { k3 = knowledge.displayColumn * 24 - k + 11 + k1; j3 = knowledge.displayRow * 24 - l + 11 + l1; j4 = knowledge.parentKnowledge.displayColumn * 24 - k + 11 + k1; l3 = knowledge.parentKnowledge.displayRow * 24 - l + 11 + l1; boolean flag = KnowledgeAppedix.hasKnowledgeUnlocked(compound, knowledge); boolean flag1 = KnowledgeAppedix.canUnlockKnowledge(compound, knowledge); i4 = Math.sin((double)(Minecraft.getSystemTime() % 600L) / 600.0D * Math.PI * 2.0D) > 0.6D ? 255 : 130; int k4 = -16777216; if (flag) { k4 = -9408400; } else if (flag1) { k4 = 65280 + (i4 << 24); } this.drawHorizontalLine(k3, j4, j3, k4); this.drawVerticalLine(j4, j3, l3, k4); } } */ /* GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glEnable(GL11.GL_BLEND); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); this.mc.renderEngine.bindTexture("/mods/dnd91/minecraft/hivecraft/textures/gui/KnowledgesBG.png"); this.drawTexturedModalRect(i1, j1, 0, 0, this.knowledgePaneWidth, this.knowledgePaneHeight); GL11.glPopMatrix(); this.zLevel = 0.0F; GL11.glDepthFunc(GL11.GL_LEQUAL); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glEnable(GL11.GL_TEXTURE_2D); super.drawScreen(par1, par2, par3); if (knowledge1 != null) { String s = knowledge1.getTitle(); String s1 = knowledge1.getDesc(); j4 = par1 + 12; l3 = par2 - 4; if (KnowledgeAppedix.canUnlockKnowledge(compound, knowledge1)) { i5 = Math.max(this.fontRenderer.getStringWidth(s), 120); l4 = this.fontRenderer.splitStringWidth(s1, i5); if (KnowledgeAppedix.hasKnowledgeUnlocked(compound, knowledge1)) { l4 += 12; } this.drawGradientRect(j4 - 3, l3 - 3, j4 + i5 + 3, l3 + l4 + 3 + 12, -1073741824, -1073741824); this.fontRenderer.drawSplitString(s1, j4, l3 + 12, i5, -6250336); if (KnowledgeAppedix.hasKnowledgeUnlocked(compound, knowledge1)) { if(lastMouseButtonDown == 1 && this.isMouseButtonDown == 0 && this.mc.theWorld.isRemote){ System.out.println("Mouse up over a knowledge!"); player.openGui(HiveCraft.instance, knowledge1.myPage+500, player.worldObj, (int)player.posX, (int)player.posY, (int)player.posZ); } lastMouseButtonDown = isMouseButtonDown; this.fontRenderer.drawStringWithShadow(StatCollector.translateToLocal("knowledge.taken"), j4, l3 + l4 + 4, -7302913); } } else { i5 = Math.max(this.fontRenderer.getStringWidth(s), 120); String s2 = StatCollector.translateToLocalFormatted("achievement.requires", new Object[] {knowledge1.parentKnowledge.getTitle()}); i4 = this.fontRenderer.splitStringWidth(s2, i5); this.drawGradientRect(j4 - 3, l3 - 3, j4 + i5 + 3, l3 + i4 + 12 + 3, -1073741824, -1073741824); this.fontRenderer.drawSplitString(s2, j4, l3 + 12, i5, -9416624); } this.fontRenderer.drawStringWithShadow(s, j4, l3, KnowledgeAppedix.canUnlockKnowledge(compound, knowledge1) ? (knowledge1.getSpecial() ? -128 : -1) : (knowledge1.getSpecial() ? -8355776 : -8355712)); } */ //GL11.glEnable(GL11.GL_DEPTH_TEST); //GL11.glEnable(GL11.GL_LIGHTING); //RenderHelper.disableStandardItemLighting(); } public int calculateLeft(){ return (this.width - this.knowledgePaneWidth - GuiArticle.pageImageWidth) / 2; } public int calculateTop(){ return (this.height - this.knowledgePaneHeight) / 2; } public int getScreenWidth(){ return this.knowledgePaneWidth; } public int getScreenHeight(){ return this.knowledgePaneHeight; } public void drawIcons(int par1, int par2, float par3){ int k = (int) this.guiMapX; int l = (int) this.guiMapY; int i1 = calculateLeft(); int j1 = calculateTop(); int k1 = i1 + 16; int l1 = j1 + 17; //GL11.glDisable(GL11.GL_LIGHTING); //GL11.glEnable(GL12.GL_RESCALE_NORMAL); //GL11.glEnable(GL11.GL_COLOR_MATERIAL); int l4; int i5; tooltipResearch = null; tooltipChapeter = null; PlayerResearch res = PlayerResearchStorage.instance(true).get(player); if(res == null){ this.drawString(fontRendererObj, "Syncing...", k1, l1, 0xFFFFFF); HiveteraMod.network.sendToServer(new PlayerStoragePullMessage(player)); return; } for(Research knowledge : ResearchLogicNetwork.instance().getOpenResearches(this.selectedChapeter, res)){ int colum = knowledge.displayColumn * cellSize - k; int row = knowledge.displayRow * cellSize - l; if (colum >= -10 && row >= -10 && colum <= 224 && row <= 155) { i5 = k1 + colum; l4 = l1 + row; PlayerResearch r = PlayerResearchStorage.instance(true).get(player); if(res == null){ HiveteraMod.network.sendToServer(new PlayerStoragePullMessage(player)); return; } this.drawIcon(knowledge, i5, l4, r.hasCompleted(knowledge.getCode()), true); Rectangle rect = new Rectangle(i5, l4, 26, 26); if(rect.contains(new Rectangle(par1, par2, 2, 2))){ tooltipResearch = knowledge; } } } if(this.article != null && this.article.getArticle() instanceof Research){ Research knowledge = (Research)this.article.article; if(!knowledge.getChapeter().getCode().equals(this.selectedChapeter.getCode())) return; int colum = knowledge.displayColumn * cellSize - k; int row = knowledge.displayRow * cellSize - l; i5 = k1 + colum; l4 = l1 + row; if (!(colum >= -10 && row >= -10 && colum <= 224 && row <= 155)) return; Minecraft mc = Minecraft.getMinecraft(); RenderHelper.enableGUIStandardItemLighting(); GL11.glEnable(GL11.GL_BLEND); float f2 = 1.0F; GL11.glColor4f(f2, f2, f2, 1.0F); if (knowledge.getSpecial()) { mc.renderEngine.bindTexture(bioBookBG); GL11.glColor4f(1.0F, 0.0F, 0.0F, 1.0F); this.drawTexturedModalRect(i5 - 3, l4 - 3, 52, 202 + 26, 28, 28); GL11.glColor4f(f2, f2, f2, 1.0F); } else { mc.renderEngine.bindTexture(bioBookBG); GL11.glColor4f(1.0F, 0.0F, 0.0F, 1.0F); this.drawTexturedModalRect(i5 - 3, l4 - 2, 52, 202, 26, 26); GL11.glColor4f(f2, f2, f2, 1.0F); } RenderHelper.disableStandardItemLighting(); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } } public void drawIcon(Research research, int x, int y, boolean isCompleted, boolean notGreyed){ Minecraft mc = Minecraft.getMinecraft(); RenderItem renderitem = new RenderItem(); RenderHelper.enableGUIStandardItemLighting(); GL11.glEnable(GL11.GL_BLEND); float f2 = 1.0F; GL11.glColor4f(f2, f2, f2, 1.0F); //mc.renderEngine.bindTexture(bioBookBG); float f3 = 1.0F; if(!isCompleted || !notGreyed) f3 = 0.3F; GL11.glColor4f(f3, f3, f3, 1.0F); PlayerResearch res = PlayerResearchStorage.instance(true).get(player); if(res == null){ HiveteraMod.network.sendToServer(new PlayerStoragePullMessage(player)); return; } boolean owner = player.equals(this.reader.getGameProfile().getId()); if (research.getSpecial()) { this.mc.renderEngine.bindTexture(research.getCategory().getIcon()); this.func_146110_a(x - 2, y - 2, 26, 0, 26, 26, 52, 26); mc.renderEngine.bindTexture(bioBookBG); if(owner && PlayerStorageSyncHandler.totallyNew.contains(research.getCode())){ GL11.glColor4f(0.0F, 0.0F, 1.0F, 1.0F); this.drawTexturedModalRect(x - 3, y - 2, 52, 202 + 26, 28, 28); GL11.glColor4f(f3, f3, f3, 1.0F); } if(res != null && res.hasFaved(research.getCode())){ GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); this.drawTexturedModalRect(x - 2, y - 2, 26, 202 + 26, 26, 26); GL11.glColor4f(f3, f3, f3, 1.0F); } } else { this.mc.renderEngine.bindTexture(research.getCategory().getIcon()); this.func_146110_a(x - 2, y - 2, 0, 0, 26, 26, 52, 25); mc.renderEngine.bindTexture(bioBookBG); if(owner && PlayerStorageSyncHandler.totallyNew.contains(research.getCode())){ GL11.glColor4f(0.0F, 0.0F, 1.0F, 1.0F); this.drawTexturedModalRect(x - 3, y - 2, 52, 202, 26, 26); GL11.glColor4f(f3, f3, f3, 1.0F); } if(res != null && res.hasFaved(research.getCode())){ GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); drawTexturedModalRect(x - 2, y - 3, 0, 202 + 26, 26, 26); GL11.glColor4f(f3, f3, f3, 1.0F); } } renderitem.renderWithColor = true; renderitem.zLevel = -50.0f; GL11.glDisable(GL11.GL_LIGHTING); //Forge: Make sure Lighting is disabled. Fixes MC-33065 GL11.glEnable(GL11.GL_CULL_FACE); renderitem.renderItemAndEffectIntoGUI(this.mc.fontRenderer, this.mc.renderEngine, research.getIconStack(), x + 3, y + 3); GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GL11.glEnable(GL11.GL_ALPHA_TEST); RenderHelper.disableStandardItemLighting(); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } public void drawIcon(Chapeter chapeter, int x, int y, boolean isCompleted, boolean notGreyed){ Minecraft mc = Minecraft.getMinecraft(); RenderItem renderitem = new RenderItem(); RenderHelper.enableGUIStandardItemLighting(); GL11.glEnable(GL11.GL_BLEND); float f2 = 1.0F; GL11.glColor4f(f2, f2, f2, 1.0F); this.mc.renderEngine.bindTexture(chapeter.getIcon()); this.func_146110_a(x, y, 26, 0, 26, 26, 52, 26); RenderHelper.disableStandardItemLighting(); GL11.glDisable(GL11.GL_BLEND); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); } public void drawOverlay(int par1, int par2, float par3){ int i1 = calculateLeft(); int j1 = calculateTop(); //this.zLevel = 200.0f; GL11.glPushMatrix(); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glEnable(GL11.GL_BLEND); GL11.glColor3f(1.0f, 1.0f, 1.0f); this.mc.getTextureManager().bindTexture(bioBookBG); this.drawTexturedModalRect(i1, j1, 0, 0, 256, 202); this.zLevel = 0.0F; GL11.glDepthFunc(GL11.GL_LEQUAL); GL11.glDisable(GL11.GL_DEPTH_TEST); GL11.glEnable(GL11.GL_TEXTURE_2D); GL11.glPopMatrix(); //this.zLevel = 200.0f; GL11.glPushMatrix(); GL11.glColor3f(1.0f, 1.0f, 1.0f); GL11.glEnable(GL11.GL_BLEND); //TODO: WORK WORK! this.drawString(fontRendererObj, this.selectedChapeter.getTitle(), i1+20, j1+5, 0xFFFFFF); this.drawString(fontRendererObj, DataHelper.getOwnerName(player, Minecraft.getMinecraft().theWorld) + "'s book", i1 + 20, j1 + this.knowledgePaneHeight - 20, 0xFFFFFF); GL11.glDisable(GL11.GL_BLEND); GL11.glPopMatrix(); //this.zLevel = 0.0f; } public void drawTooltip(int par1, int par2, float par3){ this.renderToolTip(tooltipResearch, par1, par2); } protected void renderToolTip(Research tooltipKnowledge, int p_146285_2_, int p_146285_3_) { List list = new ArrayList(); list.add(EnumChatFormatting.GOLD + tooltipKnowledge.getTitle()); list.add(tooltipKnowledge.getDesc()); drawHoveringText(list, p_146285_2_, p_146285_3_, Minecraft.getMinecraft().fontRenderer); } protected void renderTitle(IArticle tooltipKnowledge, int p_146285_2_, int p_146285_3_) { List list = new ArrayList(); list.add(EnumChatFormatting.GOLD + tooltipKnowledge.getTitle()); list.add(tooltipKnowledge.getDesc()); drawHoveringTitle(list, p_146285_2_, p_146285_3_, Minecraft.getMinecraft().fontRenderer); } protected void drawHoveringTitle(List p_146283_1_, int p_146283_2_, int p_146283_3_, FontRenderer font) { if (!p_146283_1_.isEmpty()) { GL11.glDisable(GL12.GL_RESCALE_NORMAL); RenderHelper.disableStandardItemLighting(); GL11.glDisable(GL11.GL_LIGHTING); GL11.glDisable(GL11.GL_DEPTH_TEST); int k = 0; Iterator iterator = p_146283_1_.iterator(); while (iterator.hasNext()) { String s = (String)iterator.next(); int l = font.getStringWidth(s); if (l > k) { k = l; } } int j2 = p_146283_2_ + 12; int k2 = p_146283_3_ - 12; int i1 = 8; if (p_146283_1_.size() > 1) { i1 += 2 + (p_146283_1_.size() - 1) * 10; } this.zLevel = 300.0F; itemRender.zLevel = 300.0F; int j1 = -267386864; this.drawGradientRect(j2 - 3, k2 - 4, j2 + k + 3, k2 - 3, j1, j1); this.drawGradientRect(j2 - 3, k2 + i1 + 3, j2 + k + 3, k2 + i1 + 4, j1, j1); this.drawGradientRect(j2 - 3, k2 - 3, j2 + k + 3, k2 + i1 + 3, j1, j1); this.drawGradientRect(j2 - 4, k2 - 3, j2 - 3, k2 + i1 + 3, j1, j1); this.drawGradientRect(j2 + k + 3, k2 - 3, j2 + k + 4, k2 + i1 + 3, j1, j1); int k1 = 1347420415; int l1 = (k1 & 16711422) >> 1 | k1 & -16777216; this.drawGradientRect(j2 - 3, k2 - 3 + 1, j2 - 3 + 1, k2 + i1 + 3 - 1, k1, l1); this.drawGradientRect(j2 + k + 2, k2 - 3 + 1, j2 + k + 3, k2 + i1 + 3 - 1, k1, l1); this.drawGradientRect(j2 - 3, k2 - 3, j2 + k + 3, k2 - 3 + 1, k1, k1); this.drawGradientRect(j2 - 3, k2 + i1 + 2, j2 + k + 3, k2 + i1 + 3, l1, l1); for (int i2 = 0; i2 < p_146283_1_.size(); ++i2) { String s1 = (String)p_146283_1_.get(i2); font.drawStringWithShadow(s1, j2, k2, -1); if (i2 == 0) { k2 += 2; } k2 += 10; } this.zLevel = 0.0F; itemRender.zLevel = 0.0F; GL11.glEnable(GL11.GL_LIGHTING); GL11.glEnable(GL11.GL_DEPTH_TEST); RenderHelper.enableStandardItemLighting(); GL11.glEnable(GL12.GL_RESCALE_NORMAL); } } @Override public void onGuiClosed(){ UUID observer = reader.getGameProfile().getId(); UUID subject = UUID.fromString(DataHelper.getOwner(book)); if(observer.compareTo(subject) != 0){ HiveteraMod.network.sendToServer(new PlayerStorageDelissenMessage(observer, subject)); }else{ PlayerStorageSyncHandler.totallyNew.clear(); } } @Override public boolean doesGuiPauseGame() { return false; //IF TRUE YOU CANNOT FAVORISE STUFF!!! FFS! } public GuiResearchBook load() { GuiArticle a = GuiInventoryOverlay.craftingHelper.getBooked(); if(a != null){ article = a; article.setLast(this); article.setWorldAndResolution(Minecraft.getMinecraft(), width, height, null); } return this; } }
Python
UTF-8
781
3.203125
3
[]
no_license
import sys import time start_secs = time.time() # read in input file l1=[] my_file = open("inp.txt", "r") lines = my_file.readlines() for line in lines: l1.append(line.strip()) tmp = [None]*3 sa = 0 ribbon = 0 for i in range(0,len(l1)): arr = l1[i].split('x') l = int(arr[0]) w = int(arr[1]) h = int(arr[2]) tmp[0] = l*w tmp[1] = w*h tmp[2] = h*l x = l y = w small = tmp[0] if tmp[1] < tmp[0]: x = w y = h small = tmp[1] if tmp[2] < small: x = h y = l small = tmp[2] ribbon = ribbon + l*w*h + 2*x + 2*y sa = sa + 2*tmp[0] + 2*tmp[1] + 2*tmp[2] + small print('Part 1: ' + str(sa)) print('Part 2: ' + str(ribbon)) end_secs = time.time() print(str(end_secs-start_secs))
JavaScript
UTF-8
1,655
3.015625
3
[]
no_license
/** * @description : Component to create renderable input fields * @prop {String} : inputID, required * @prop {Number} : name, required * @prop {Number} : value, required */ import { Component, PropTypes } from "react"; class InputField extends Component { constructor(props, context){ super(props, context) this.handleChange = this.handleChange.bind(this); this.state = { inputID : this.props.inputID, // Required name : this.props.name, // Required value : this.props.value // Required }; } extract(str, pattern){ return (str.match(pattern) || []).pop() || '' } extractAlphanum(str){ return this.extract(str, "[0-9a-zA-Z]+") } extractNumber(str){ return this.extract(str, "[0-9.]+") } // Previously used regex [0-9.]+ handleChange(event) { let filterValue = this.extractNumber(event.target.value); this.setState({ value: filterValue }); this.props.handleChangeFault(filterValue,this.state.inputID); } componentWillReceiveProps(nextProps){ this.setState({ inputID : nextProps.inputID, name : nextProps.name, value : nextProps.value }) } render(){ return( <input id={this.state.inputID} name={this.state.name} className="testing" type="text" value={this.state.value} onChange={(e)=>this.handleChange(e)} /> ) } } InputField.propTypes = { inputID : PropTypes.string.isRequired, name : PropTypes.string.isRequired, value : PropTypes.number } export default InputField;
C
UTF-8
493
3.3125
3
[]
no_license
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "alphabetical_printing.h" #define MAX_LENGTH_WORDS 50 int file_size(FILE *fp); char **read_words(FILE *fp){ char **array; int size = 0; int i = 0; int j = 0; size = file_size(fp); array = malloc(sizeof(char *) * size); for (i=0; i < size; i++){ array[i] = malloc(sizeof(char) * MAX_LENGTH_WORDS); } while(fscanf(fp, "%s", array[j]) != EOF){ j++; } array[j+1] = NULL; return array; }
Java
UTF-8
3,370
2.015625
2
[]
no_license
package com.lk.savsiri.domain; import com.google.gson.annotations.SerializedName; public class User { @SerializedName("nick_name") String name; @SerializedName("id") String userId; @SerializedName("email") String email; @SerializedName("status") String status; @SerializedName("role") String role; @SerializedName("couple") String couple; @SerializedName("sex") String sex; @SerializedName("looking_for") String lookingFor; @SerializedName("date_of_birth") String birthDay; @SerializedName("description_me") String description; @SerializedName("female") String lookingForl; @SerializedName("contact_number") String contactNumber; @SerializedName("mobile_number") String mobileNumber; @SerializedName("relationship_status") String relationshipStatus; @SerializedName("education") String education; @SerializedName("description_expect") String descriptionExpect; @SerializedName("image_url") String thumbImage; @SerializedName("image_url_big") String profileImage; public String getProfileImage() { return profileImage; } public void setProfileImage(String profileImage) { this.profileImage = profileImage; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getRole() { return role; } public void setRole(String role) { this.role = role; } public String getCouple() { return couple; } public void setCouple(String couple) { this.couple = couple; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getLookingFor() { return lookingFor; } public void setLookingFor(String lookingFor) { this.lookingFor = lookingFor; } public String getBirthDay() { return birthDay; } public void setBirthDay(String birthDay) { this.birthDay = birthDay; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getLookingForl() { return lookingForl; } public void setLookingForl(String lookingForl) { this.lookingForl = lookingForl; } public String getContactNumber() { return contactNumber; } public void setContactNumber(String contactNumber) { this.contactNumber = contactNumber; } public String getMobileNumber() { return mobileNumber; } public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; } public String getRelationshipStatus() { return relationshipStatus; } public void setRelationshipStatus(String relationshipStatus) { this.relationshipStatus = relationshipStatus; } public String getEducation() { return education; } public void setEducation(String education) { this.education = education; } public String getDescriptionExpect() { return descriptionExpect; } public void setDescriptionExpect(String descriptionExpect) { this.descriptionExpect = descriptionExpect; } }
Swift
UTF-8
7,407
2.53125
3
[]
no_license
// // PhotoLocations.swift // Virtual Tourist // // Created by Aldin Fajic on 8/17/15. // Copyright (c) 2015 Aldin Fajic. All rights reserved. // import Foundation import UIKit import CoreData struct PhotoLocations { // get phtos from flickr static func getLocations(latitude: String, longitude: String, currPage: Int, pin: Pin?) { FlickrClient.sharedInstance().getPhotosForLocation(latitude, long: longitude, page: "\(currPage)") { (result, error) -> Void in if error == nil { if let photos = result { dispatch_async(dispatch_get_main_queue(), { var photosArr = photos.photoUrls.mutableCopy() as! NSMutableArray let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate appDelegate.photoUrls = photosArr if let pin = pin { self.savePhotosToCoreData(pin, imgUrls: photosArr) } else { self.saveToCoreData(latitude, longitude: longitude, imgUrls: photosArr) } }) } } else { println("error") } } } // save pin & photos to core dta static func saveToCoreData(latitude: String, longitude: String, imgUrls: NSMutableArray) { let appDel = UIApplication.sharedApplication().delegate as! AppDelegate let context = appDel.managedObjectContext var newPin = NSEntityDescription.insertNewObjectForEntityForName("Pin", inManagedObjectContext: context!) as! Pin newPin.latitude = latitude newPin.longitude = longitude savePhotosToCoreData(newPin, imgUrls: imgUrls) } // save photos to core data static func savePhotosToCoreData(newPin : Pin, imgUrls: NSMutableArray) { let appDel = UIApplication.sharedApplication().delegate as! AppDelegate let context = appDel.managedObjectContext let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! String for url in imgUrls { //println(url) let imgUrl = url["url_m"] as? String var id = url["id"] as? String var idNum = id?.toInt() // println(idNum) let newPhoto = NSEntityDescription.insertNewObjectForEntityForName("Photo", inManagedObjectContext: context!) as! Photo newPhoto.url = imgUrl newPhoto.id = idNum newPin.addPhotosObject(newPhoto) if let url = NSURL(string: imgUrl!) { if let data = NSData(contentsOfURL: url){ var documentsDir : String? var paths : [AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) if paths.count > 0 { documentsDir = paths[0] as? String let savePath = documentsDir! + "/\(idNum!).jpg" NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil) var image = UIImage(named: savePath) // println(image) } } } } context?.save(nil) } // remove phtos from core data static func removePhotosFromCoreData(pin: Pin, photos: Array<Photo>) { let appDel : AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate for photo in photos { pin.removePhotosObject(photo) pin.willSave() appDel.managedObjectContext?.save(nil) } } // remove photos from library static func removePhotosFromLibrary(pin: Pin, photos: Array<Photo>) { var documentsDir : String? var paths : [AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true) if paths.count > 0 { documentsDir = paths[0] as? String for photo in photos { let savePath = documentsDir! + "/\(photo.id).jpg" NSFileManager.defaultManager().removeItemAtPath(savePath, error: nil) } } } // get photos from flickr. Used in phtoAlbum view controller static func getPhotos(viewCntrl: PhotoAlbumViewController, spinner: UIActivityIndicatorView) { FlickrClient.sharedInstance().getPhotosForLocation(viewCntrl.pin!.latitude, long: viewCntrl.pin!.longitude, page: "\(viewCntrl.currPage)") { (result, error) -> Void in if error == nil { dispatch_async(dispatch_get_main_queue(), { if let photos = result { viewCntrl.photosArr = photos.photoUrls.mutableCopy() as? NSMutableArray PhotoLocations.savePhotosToCoreData(viewCntrl.pin!, imgUrls: viewCntrl.photosArr!) if viewCntrl.currPage <= viewCntrl.photosArr!.count { viewCntrl.currPage++ } else { viewCntrl.newCollectionBtn.enabled = false } } if viewCntrl.photosArr!.count > 0 { viewCntrl.noImagesLbl.hidden = true viewCntrl.collView.hidden = false viewCntrl.collView.reloadData() spinner.stopAnimating() viewCntrl.newCollectionBtn.enabled = true } else { viewCntrl.noImagesLbl.hidden = false viewCntrl.collView.hidden = true viewCntrl.newCollectionBtn.enabled = false } }) } else { println("error") } } } // get photos from core data static func getPhotosFromCoreData(viewCntrl: TravelLocationsMapViewController, latitude: String, longitude: String) -> Set<NSObject> { let request = NSFetchRequest(entityName: "Pin") request.returnsObjectsAsFaults = false let latPred = NSPredicate(format: "latitude = %@", latitude) let longPred = NSPredicate(format: "longitude = %@", longitude) var compound = NSCompoundPredicate.andPredicateWithSubpredicates([latPred, longPred]) request.predicate = compound var results : [Pin] results = viewCntrl.appDel.managedObjectContext?.executeFetchRequest(request, error: nil) as! [Pin] viewCntrl.selectedPin = results[0] return viewCntrl.selectedPin!.photos } }
Java
UTF-8
541
1.523438
2
[]
no_license
package cn.xinyuan.blog.service.impl; import cn.xinyuan.blog.entity.BlogRecommend; import cn.xinyuan.blog.mapper.BlogRecommendMapper; import cn.xinyuan.blog.service.IBlogRecommendService; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 推荐表 服务实现类 * </p> * * @author xinyuan * @since 2020-03-17 */ @Service public class BlogRecommendServiceImpl extends ServiceImpl<BlogRecommendMapper, BlogRecommend> implements IBlogRecommendService { }
TypeScript
UTF-8
1,279
3.671875
4
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
import isPlainObject from 'lodash/isPlainObject' const SEPARATOR = '__' const _innerFnFlattenNested = (innerProperties: any, prefix: string): any => { return Object.keys(innerProperties).reduce((acc, key) => { // if the key's value is an object, recurse into it const nestedValue = innerProperties[key] if (isPlainObject(nestedValue)) { return { ...acc, ..._innerFnFlattenNested(nestedValue, `${prefix}${SEPARATOR}${key}`), } } // ignore non-nested (aka top-level) keys: if no prefix, we're on the top level // of the original object. if (prefix === '') { return acc } else { return { ...acc, [`${prefix}${SEPARATOR}${key}`]: nestedValue } } }, {}) } // Mixpanel isn't as easy to query if you have nested properties. // Instead of hard-coding how to transform each nested field to flat ones, // this util does {a: {b: 1, c: 'ccc'}, d: 123, e: [1,2,3]} => {__a__b: 1, __a__c: 'ccc'}. // Note that non-nested properties are omitted from the result. // Also, the separator will not be escaped, so if you have a field already named '__foo__a' // and also have a {foo: {a: 123}}, they'll clash. export const flattenNestedProperties = (properties: any): any => _innerFnFlattenNested(properties, '')
Ruby
UTF-8
896
2.546875
3
[ "BSD-3-Clause", "MIT" ]
permissive
#Creates the two database tables, plus indexes, you'll need to use A/Bingo. class AbingoMigration<%= version -%> < ActiveRecord::Migration def self.up create_table "experiments", :force => true do |t| t.string "test_name" t.string "status" t.timestamps end add_index "experiments", "test_name" #add_index "experiments", "created_on" create_table "alternatives", :force => true do |t| t.integer :experiment_id t.string :content t.string :lookup, :limit => 32 t.integer :weight, :default => 1 t.integer :participants, :default => 0 t.integer :conversions, :default => 0 end add_index "alternatives", "experiment_id" add_index "alternatives", "lookup" #Critical for speed, since we'll primarily be updating by that. end def self.down drop_table :experiments drop_table :alternatives end end
Markdown
UTF-8
3,112
2.875
3
[]
no_license
## GPIO Stands for "General Purpose Input/Output." GPIO is a type of pin found on an integrated circuit that does not have a specific function. While most pins have a dedicated purpose, such as sending a signal to a certain component, the function of a GPIO pin is customizable and can be controlled by software. ## Connection of IOT devices Not all IOT devices have direct access to internet. Instead, there are several IOT devices which make use of a gateway in order to connect them to the internet because they don't implement technologies capable of establishing a direct connection to internet. ![protocols](https://imgur.com/xCyI8P8.jpg) ## MQTT MQTT stands for Message Queuing Telemetry Transport. It is a lightweight publish and subscribe system where you can publish and receive messages as a client, so producer and consumer are decoupled. MQTT uses TCP to establish the connection between the clients and the server. It's designed for constrained devices with low-bandwidth. So, it’s the perfect solution for Internet of Things applications. MQTT allows you to send commands to control outputs, read and publish data from sensor nodes and much more. In a publish and subscribe system, a device can publish a message on a topic, or it can be subscribed to a particular topic to receive messages. Topics are the way you register interest for incoming messages or how you specify where you want to publish the message and are represented with strings separated by a forward slash. Each forward slash indicates a topic level (`/home/office/lamp`, where `home` and `office` are topics). The broker is primarily responsible for receiving all messages, filtering the messages, decide who is interested in them and then publishing the message to all subscribed clients. MQTT has support for persistent messages stored on the broker. When publishing messages, clients may request that the broker persists the message. Only the most recent persistent message is stored. When a client subscribes to a topic, any persisted message will be sent to the client. ## CoAP CoAP stands for Constrained Application Protocol. Like HTTP, CoAP is a document transfer protocol. Unlike HTTP, CoAP is designed for the needs of constrained devices. CoAP packets are much smaller than HTTP TCP flows. CoAP runs over UDP, not TCP. Retries and reordering are implemented in the application stack. CoAP follows a client/server model. Clients make requests to servers, servers send back responses. Clients may `GET`, `PUT`, `POST` and `DELETE` resources. CoAP is designed to interoperate with HTTP and the RESTful web at large through simple proxies. Like HTTP, CoAP supports content negotiation. Clients use `Accept` options to express a preferred representation of a resource and servers reply with a `Content-Type` option to tell clients what they’re getting. As with HTTP, this allows client and server to evolve independently, adding new representations without affecting each other. CoAP requests may use query strings in the form `?a=b&c=d` . These can be used to provide search, paging and other features
PHP
UTF-8
1,042
2.75
3
[]
no_license
<?php /** * @license see LICENSE */ namespace UForm\Form\Element\Primary\Input; use UForm\Form\Element\Primary\Input; /** * input checkbox * @semanticType input:checkbox */ class Check extends Input { protected $value; public function __construct($name, $value = null, $attributes = null, $validators = null, $filters = null) { parent::__construct("checkbox", $name, $attributes, $validators, $filters); $this->value = $value; } protected function overridesParamsBeforeRender($params, $attributes, $value, $data, $prename = null) { if (isset($value[$this->getName()]) && $value[$this->getName()] == $this->value) { $params["checked"] = "checked"; } if ($this->value) { $params["value"] = $this->value; } else { unset($params["value"]); } return $params; } /** * Get the checkbox value * @return string */ public function getValue() { return $this->value; } }
Python
UTF-8
147
3.546875
4
[]
no_license
for i in range(0,21): print(i) for each in [1,2,3]: print("Each") #another loop for each in [1,2,3]: print(each) #this is another line
TypeScript
UTF-8
174
2.578125
3
[ "MIT" ]
permissive
export type Context = { filename: string; url: string; originalUrl: string; content: string | null; }; export type Processor = (input: Context) => Promise<Context>;
Java
UTF-8
4,287
2.515625
3
[]
no_license
package edu.ncsu.csc.itrust.server; import edu.ncsu.csc.itrust.action.EventLoggingAction; import edu.ncsu.csc.itrust.beans.ApptBean; import edu.ncsu.csc.itrust.beans.ReminderBean; import edu.ncsu.csc.itrust.dao.DAOFactory; import edu.ncsu.csc.itrust.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.dao.mysql.ReminderDao; import edu.ncsu.csc.itrust.enums.TransactionType; import edu.ncsu.csc.itrust.exception.DBException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; /** * Logs and returns reminders */ public class AppointmentDayServlet extends HttpServlet { private static final long serialVersionUID = 1L; private DAOFactory factory; private ReminderDao reminderDao; private PersonnelDAO personnelDAO; private static final String senderName = "System Reminder"; private static final DateFormat hmsFormatter = new SimpleDateFormat("HH:mm:ss"); private static final DateFormat dmyFormatter = new SimpleDateFormat("yyyy/MM/dd"); /** * Default Constructor */ public AppointmentDayServlet () { super(); factory = DAOFactory.getProductionInstance(); reminderDao = factory.getReminderDAO(); } /** * Dependency Injection Constructor * @param factory */ public AppointmentDayServlet (DAOFactory factory) { super(); this.factory = factory; reminderDao = factory.getReminderDAO(); personnelDAO = this.factory.getPersonnelDAO(); } /** * Services the request * @param request, needs "days" param and "mid" param * @param response, to be sent back * @throws ServletException, if invalid request * @throws IOException, if unable to write the request back */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = request.getParameter("days"); Integer days = Integer.parseInt(param); Long mid = Long.parseLong(request.getParameter("mid")); List<ApptBean> res; String names; try { res = factory.getApptDAO().getApptsFor(mid); names = personnelDAO.getName(mid); } catch (Exception e) { throw new ServletException(e); } Date now = (new Date()); Date later = new Date(now.getTime() + (1000 * 60 * 60 * 24 * days + 1)); List<ApptBean> filtered = new ArrayList<>(); for(ApptBean bean : res) { if(bean.getDate().before(later)) { filtered.add(bean); } } for(ApptBean bean : filtered) { sendNotification(mid, names, now, bean); } PrintWriter resp = response.getWriter(); resp.write("Success!"); } /** * sends a notification from "mid" named "names' from "now" and "bean * @param mid * @param names * @param now * @param bean */ private void sendNotification(Long mid, String names, Date now, ApptBean bean) { ReminderBean rb = new ReminderBean(); Date apptTime = bean.getDate(); int dayDiff = (int)((apptTime.getTime() - now.getTime()) / (1000*60*60*24)); rb.setMid((int)(bean.getPatient())); rb.setSenderName(senderName); rb.setSubject(String.format("Reminder: upcoming appointment in %d day(s)", dayDiff)); rb.setContent(String.format("You have an appointment on %s, %s with Dr. %s", hmsFormatter.format(apptTime), dmyFormatter.format(apptTime), names)); try { reminderDao.logReminder(rb); EventLoggingAction loggingAction = new EventLoggingAction(this.factory); loggingAction.logEvent(TransactionType.MESSAGE_SEND, mid, bean.getPatient() , "Sent appointment reminder with appt_id="+bean.getApptID()); } catch (SQLException | DBException e) { } } }
Java
UTF-8
2,214
2.53125
3
[ "Apache-2.0" ]
permissive
package net.mfinance.chatlib.view; import android.content.ClipboardManager; import android.content.Context; import android.text.Editable; import android.text.Spannable; import android.util.AttributeSet; import android.util.Log; import androidx.appcompat.widget.AppCompatEditText; import net.mfinance.chatlib.utils.EmojiUtils; /** * 自定义EditText,解决emoji的问题 */ public class EmojiEditText extends AppCompatEditText { private Context context; public EmojiEditText(Context context) { super(context); this.context = context; } public EmojiEditText(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; } public EmojiEditText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); this.context = context; } @Override public boolean onTextContextMenuItem(int id) { // boolean consumed = super.onTextContextMenuItem(id); // 监听 if (id == android.R.id.paste) { onTextPaste(); return true; } return super.onTextContextMenuItem(id); } /** * 粘贴操作 */ private void onTextPaste() { ClipboardManager clipboardManager = (ClipboardManager) getContext().getSystemService(Context.CLIPBOARD_SERVICE); //改变剪贴板中Content if (clipboardManager != null && clipboardManager.getText() != null) { // 粘贴一次后重置剪贴板的内容,避免第二次复制时携带重复数据 clipboardManager.setText(clipboardManager.getText()); // [):][):][):][):][):][):][):][):],把String转成Spannable String emoji = clipboardManager.getText().toString(); Spannable spannable = EmojiUtils.getEmojiText(context, emoji); Log.e("text", "复制的内容 = " + emoji); //改变文本内容,可以多次复制 this.append(spannable); //光标置到文本末尾 Editable text = getText(); if (text != null) { this.setSelection(text.toString().length()); } } } }
JavaScript
UTF-8
105
2.703125
3
[]
no_license
window.alert('This is an alert statement'); alert('Learning Javascript'); console.log('Jurassic World');
Markdown
UTF-8
3,362
3.203125
3
[]
no_license
# Brushing & Linking This example shows how to combine multiple views via [Brushing & Linking](https://en.wikipedia.org/wiki/Brushing_and_linking) in order to selectively visualise fish data queried via [FishBase](http://fishbase.org/). ## Usage Start the Cocoon editor from the root directory of this repository using: ```sh npm run example:brushing-and-linking ``` ![](screenshot.png) ## Highlight Sync Like in the [simple-api](../simple-api) example we query an open API, extract the data and visualise it in a scatter plot. So far, nothing new. We then visualise fish images in a gallery, using the built-in component (which is very similar to the one we custom-built in the [custom-nodes](../custom-nodes) example). But it gets interesting once we open both views. Put them side-by-side and hover an item in the scatter plot. The image of the fish will appear in the Gallery. This is a feature called "Highlight Sync". Cocoon broadcasts information about a highlighted item to all views, and each view can choose to respond with a meaningful action (which can, of course, be customised). ![](screenshot-sync.png) In this particular scenario, the trick is to choose the image attribute as part of the tooltip information: ```yml FishFilter: in: data: 'cocoon://ExtractData/out/data' type: FilterRanges view: Scatterplot viewState: color: Fresh tooltip: - FBname - image # <-- this contains the image URL x: Length y: Vulnerability ``` When the Gallery receives highlight information, it scans it for image URLs and shows them in an overlay, simple as that. ## Filtering via Brushing Note that at the top of the scatter plot you have some toolbox items that you can select. You might not have noticed, but those weren't available in the [simple-api](../simple-api) example. Choosing the first tool allows us to draw a rectangle and only the contained data points will be shown in the gallery. ![](screenshot-brush.png) What's going on? In order for nodes and views to be able to cooperate, the node specifies a set of features that it supports. The view, in turn, can enable certain features in response if it sees that the node supports them. In this particular instance, the `FilterRanges` nodes supports a view state attribute called `selectedRanges`, which it uses to make range selections on one or more attributes. As an experiment, you can try replacing the filter node with `FilterRows`. Note that you now have much more granular filtering tools, but the view state serialised in the `cocoon.yml` upon filtering is now a set of indices, not attribute ranges. ## In Summary Through view state attributes (which both nodes and views can access), views can change the way that nodes behave, which enables features such as visual filtering. Unlike with Highlight Sync there's no special communication between the two views, however, it is simply a consequence of the regular data flow in Cocoon. The reason there's an instant response when making selections in the scatter plot it simple: the change in view state causes the downstream nodes (`FishGallery` in this case) to invalidate. But invalidated nodes that have a view that is currently opened will cause Cocoon to instantly process the view nodes again. Try closing the Gallery view and note what happens when you make a selection now.
Java
UTF-8
5,074
2.390625
2
[]
no_license
package com.ssthouse.twopersonchat.lib.adapter; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.avos.avoscloud.im.v2.AVIMMessage; import com.avos.avoscloud.im.v2.AVIMTypedMessage; import com.avos.avoscloud.im.v2.messages.AVIMTextMessage; import com.ssthouse.twopersonchat.R; import com.ssthouse.twopersonchat.util.FileHelper; import com.ssthouse.twopersonchat.util.PreferenceHelper; import java.util.ArrayList; import java.util.List; /** * 聊天列表的适配器 * 需要区分不同种类的消息----填充不同的数据 * Created by ssthouse on 2015/8/9. */ public class ChatListAdapter extends BaseAdapter { private static final String TAG = "ChatListAdapter"; private Context context; private LayoutInflater inflater; //ListView要展现的数据 private List<AVIMTypedMessage> msgList; //缓存下来两个人的头像 private Bitmap meAvatarBitmap, taAvatarBitmap; public ChatListAdapter(Context context) { this.context = context; this.inflater = LayoutInflater.from(context); msgList = new ArrayList<>(); //填充本地数据 meAvatarBitmap = BitmapFactory.decodeFile(FileHelper.AVATAR_PATH_AND_NAME); taAvatarBitmap = BitmapFactory.decodeFile(FileHelper.TA_AVATAR_PATH_AND_NAME); } /** * 添加新消息 * * @param msg */ public void addMessage(AVIMTypedMessage msg, ListView lv) { msgList.add(msg); notifyDataSetChanged(); //滚动到最下方 lv.smoothScrollToPosition(this.getCount() - 1); // LogHelper.Log(TAG, "我刷新了listview"); } public void addMessage(List<AVIMMessage> msgList, ListView lv) { for(AVIMMessage msg : msgList){ //TODO if(((AVIMTypedMessage)msg).getMessageType() != 1) { addMessage((AVIMTypedMessage) msg, lv); } } notifyDataSetChanged(); //滚动到最下方 lv.smoothScrollToPosition(this.getCount() - 1); // LogHelper.Log(TAG, "我刷新了listview"); } @Override public int getCount() { // LogHelper.Log(TAG, "我现在有---" + msgList.size() + "个消息View"); return msgList.size(); } @Override public Object getItem(int position) { return msgList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { switch (msgList.get(position).getMessageType()) { //文本消息 case -1: AVIMTextMessage msg = (AVIMTextMessage) msgList.get(position); //判断是不是自己发的 if (msg.getFrom().equals(PreferenceHelper.getUserName(context))) { //inflate出View convertView = inflater.inflate(R.layout.chat_item_base_right, null); //填充头像 ImageView ivAvatar = (ImageView) convertView.findViewById(R.id.id_iv_avatar); ivAvatar.setImageBitmap(meAvatarBitmap); //填充文字内容 TextView tvContent = (TextView) inflater.inflate(R.layout.chat_item_text, null); tvContent.setTextColor(0xffffffff); tvContent.setText(msg.getText()); //文字内容放入View LinearLayout llContainer = (LinearLayout) convertView.findViewById(R.id.id_ll_content); llContainer.addView(tvContent); } else { //inflate出View convertView = inflater.inflate(R.layout.chat_item_base_left, null); //填充头像 ImageView ivAvatar = (ImageView) convertView.findViewById(R.id.id_iv_avatar); ivAvatar.setImageBitmap(taAvatarBitmap); //填充文字内容 TextView tvContent = (TextView) inflater.inflate(R.layout.chat_item_text, null); tvContent.setText(msg.getText()); //文字内容放入View LinearLayout llContainer = (LinearLayout) convertView.findViewById(R.id.id_ll_content); llContainer.addView(tvContent); } return convertView; case -2: //图像消息 return convertView; case -3: //音频消息 return convertView; case -5: //位置消息 return convertView; default: return convertView; } } }
C++
UTF-8
756
3.171875
3
[]
no_license
/** * @author Hansheng Zhang */ class Solution { public: string tables[8]={"abc","def","ghi","jkl","mno","pqrs","tuv","wxyz"}; void dfs(vector<string> & result, int n, int i, string & digits, string cur){ string str = tables[digits.at(i)-'2']; int len = str.length(); for (int j=0; j<len; j++){ string next = cur+str.at(j); if (i==n-1) result.push_back(next); else dfs(result,n,i+1,digits,next); } } vector<string> letterCombinations(string digits) { // Start typing your C/C++ solution below // DO NOT write int main() function vector<string> rlt; int len = digits.length(); if (len<=0){ rlt.push_back(""); return rlt; } dfs(rlt, len, 0, digits,""); return rlt; } };
Java
UTF-8
1,006
3.03125
3
[]
no_license
package Baidu; import Base.TreeNode; import java.util.ArrayList; import java.util.List; public class Solution113 { public List<List<Integer>> pathSum(TreeNode root, int targetSum) { List<List<Integer>> res = new ArrayList<>(); List<Integer> tmp = new ArrayList<>(); pathSum(res, tmp, root, targetSum); return res; } public void pathSum(List<List<Integer>> res, List<Integer> tmp, TreeNode root, int targetSum){ if (root == null) return; // 如果是叶子节点并且得到了目标值 if (root.left == null && root.right == null){ if (targetSum == root.val){ List<Integer> list = new ArrayList<>(tmp); list.add(root.val); res.add(list); } return; } tmp.add(root.val); pathSum(res, tmp, root.left, targetSum - root.val); pathSum(res, tmp, root.right, targetSum - root.val); tmp.remove(tmp.size() - 1); } }
Java
UTF-8
908
2.109375
2
[]
no_license
package com.example.springboot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DriverManagerDataSource; import javax.sql.DataSource; @SpringBootApplication public class Application { @Bean public DataSource dataSource() { DriverManagerDataSource ds = new DriverManagerDataSource(); ds.setDriverClassName("org.h2.Driver"); ds.setUrl("jdbc:h2:~/data"); ds.setUsername("Deepak"); ds.setPassword(""); return ds; } @Bean public JdbcTemplate jdbcTemplate() { return new JdbcTemplate(dataSource()); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
Java
UTF-8
1,244
2.015625
2
[ "Apache-2.0" ]
permissive
package org.appfuse.web; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.appfuse.service.UserManager; import org.jmock.Mock; import org.jmock.MockObjectTestCase; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.web.servlet.ModelAndView; public class UserControllerTest extends MockObjectTestCase { private UserController c = new UserController(); private Mock mockManager = null; protected void setUp() throws Exception { mockManager = new Mock(UserManager.class); c.setUserManager((UserManager) mockManager.proxy()); } public void testGetUsers() throws Exception { // set expected behavior on manager mockManager.expects(once()).method("getUsers") .will(returnValue(new ArrayList())); ModelAndView mav = c.handleRequest(new MockHttpServletRequest(), (HttpServletResponse) null); Map m = mav.getModel(); assertNotNull(m.get("users")); assertEquals(mav.getViewName(), "userList"); // verify expectations mockManager.verify(); } }
JavaScript
UTF-8
1,061
3
3
[]
no_license
var count = 0; function wave(){ if(count %2 == 0){ document.getElementById("droid").src="ic_launcher.png"; }else{ document.getElementById("droid").src="icon.png"; } count ++; } function show(jsondata){ //jsondata接收一个字符串 [{name:"xxx",amount:600,phone:"13988888"},{name:"bb",amount:200,phone:"1398788"}] var jsonobjs = eval(jsondata); var table = document.getElementById("personTable"); for(var y=0; y<jsonobjs.length; y++){ var tr = table.insertRow(table.rows.length); //添加一行 //添加三列,动态的往表格后面添加一行。 var td1 = tr.insertCell(0); var td2 = tr.insertCell(1); td2.align = "center"; var td3 = tr.insertCell(2); td3.align = "center"; //设置列内容和属性 td1.innerHTML = jsonobjs[y].name; td2.innerHTML = jsonobjs[y].amount; td3.innerHTML = "<a href='javascript:contact.call(\""+ jsonobjs[y].phone+ "\")'>"+ jsonobjs[y].phone+ "</a>"; } }
Java
WINDOWS-1252
2,133
2.09375
2
[]
no_license
package com.yl.domain; import java.util.Date; import java.util.Set; public class Person { private Integer id; private String password; private String sex; private String name; private Integer age; private String email; private Date dateLLastActived; private String photoName; private Integer postCount; private Integer replyCount; private Set<Board> boardAdministrated;// private Set<Post> posts;// private Set<Reply> replys;// public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Date getDateLLastActived() { return dateLLastActived; } public void setDateLLastActived(Date dateLLastActived) { this.dateLLastActived = dateLLastActived; } public Set<Board> getBoardAdministrated() { return boardAdministrated; } public void setBoardAdministrated(Set<Board> boardAdministrated) { this.boardAdministrated = boardAdministrated; } public Set<Post> getPosts() { return posts; } public void setPosts(Set<Post> posts) { this.posts = posts; } public Set<Reply> getReplys() { return replys; } public void setReplys(Set<Reply> replys) { this.replys = replys; } public String getPhotoName() { return photoName; } public void setPhotoName(String photoName) { this.photoName = photoName; } public Integer getPostCount() { return postCount; } public void setPostCount(Integer postCount) { this.postCount = postCount; } public Integer getReplyCount() { return replyCount; } public void setReplyCount(Integer replyCount) { this.replyCount = replyCount; } }
Java
UTF-8
584
1.84375
2
[]
no_license
package com; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.feign.EnableFeignClients; /** * @author zzg * @Description */ @EnableFeignClients @EnableEurekaClient @SpringBootApplication public class EurekaConsumerFeignRun { public static void main(String[] args) { new SpringApplicationBuilder(EurekaConsumerFeignRun.class) .web(true).run(args); } }
TypeScript
UTF-8
1,691
2.71875
3
[]
no_license
/* * File: WorkflowService.ts * Version: 1.0.0 * Date: Date: 2019-02-21 * Author: Stefano Zanatta * License: * * History: * Author || Date || Description * Stefano Zanatta || 2019-02-21 || Created file * Stefano Zanatta || 2019-02-24 || Implemented * Bianca Ciuche || 2019-02-27 || Verified * Matteo Depascale || 2019-03-02 || Approved */ import { Workflow } from "../Workflow"; const axios = require('axios'); import { blockJSON, WorkflowData } from "../JSONconfigurations/JSONconfiguration"; export class WorkflowService { public async create(userID: Promise<string>, workflowName: string, position: number, slot: string): Promise<Workflow> { let config: Promise<blockJSON[]> = this.workflowFromDatabase(userID,workflowName); return config.then(result => new Workflow(result, workflowName, position, slot)) .catch(function(error) { throw "error while creating the workflow: " + workflowName + ". £££ERROR: "+ error; }); } /** * @description download a workflow from the database using a GET */ private async workflowFromDatabase(userID: Promise<string>, workflowName: string): Promise<blockJSON[]> { let _userID: string = await userID; let headers = 'userID=' + _userID + '&workflowName=' + workflowName; const URL = 'https://m95485wij9.execute-api.us-east-1.amazonaws.com/beta/workflow?'+ headers; return axios.get(URL) .then(function(response: WorkflowData){ return response.data; }).catch(function(error: string){ throw 'exception while reading the user_id from database. £££ERROR: '+ error; }); } }
PHP
UTF-8
2,376
2.609375
3
[]
no_license
<?php // Début de la SESSION session_start(); // Inclusion des classes "lrs_management.php" et "lrs.php" require_once($_SERVER["DOCUMENT_ROOT"].'/lrs/src/model/lrs_manager.php'); require_once($_SERVER["DOCUMENT_ROOT"].'/lrs/src/model/lrs.php'); // Vérification pour savoir si le formulaire a bien été remplit if(empty($_POST['nom']) || empty($_POST['prenom']) || empty($_POST['phone'])>10 || empty($_POST['adresse']) || empty($_POST['email']) || empty($_POST['mdp'])) { getError('Formulaire incomplet','/lrs/index.php'); } else { ///////////////////ENVOIE DE MAIL A LA PERSONNE INSCRITE////////////////////// $to = $_POST['email']; $subject = 'Inscription au site des anciens étudiants'; $message = '<html> <head> </head> <body> <p>Bonjour '.$_POST['prenom'].' '.$_POST['nom'].'</p> <p>Bienvenue sur le site des anciens étudiants du Lycée Privé Robert Schuman !</p> <p>Grâce à ce site, vous aurez accès à différents évènements organisés par la direction !</P> <p>Vous pourrez aussi échanger avec d\'autres anciens étudiants grâce à notre forum.</P> <p>Si vous avez une question, vous pouvez contacter l\'administrateur à partir de l\'onglet "Contactez-nous" ou envoyer un mail à l\'adresse suivante :</p> <p style="font-weight: bold">cockpit.website@gmail.com</p> <p>Amusez-vous bien !</p><br> <p>Cordialement,</p> <p>L\'administrateur</p> </body> </html> '; // Pour envoyer un mail HTML, l'en-tête Content-type doit être défini $headers[] = 'MIME-Version: 1.0'; $headers[] = 'Content-type: text/html; charset=iso-8859-1'; // En-têtes additionnels $headers[] = 'From: cockpit.website@gmail.com'; mail($to,$subject,$message,implode("\r\n", $headers)); ///////////////////////////////////////////////////////////////////////////// // Creation d'un nouvel objet "user" de type "lrs" avec l'envoie des données $user = new lrs([ 'nom' => $_POST['nom'], 'prenom' => $_POST['prenom'], 'phone' => $_POST['phone'], 'adresse' => $_POST['adresse'], 'email' => $_POST['email'], 'mdp' => $_POST['mdp'], ]); // Creation d'un nouvel objet "add" de type "lrs_management" $add = new lrs_manager(); // Execution de la fonction addUser avec l'envoie des données de ($user) $add->addUser($user); }
C++
UTF-8
1,200
3.15625
3
[]
no_license
// https://leetcode.com/problems/letter-combinations-of-a-phone-number/ class Solution { public: vector<string> res; unordered_map<int, string> mymap; void createMap() { mymap[2] = "abc"; mymap[3] = "def"; mymap[4] = "ghi"; mymap[5] = "jkl"; mymap[6] = "mno"; mymap[7] = "pqrs"; mymap[8] = "tuv"; mymap[9] = "wxyz"; } void solve(string digits, string current, int iStart, int n) { if(n > digits.size()) return; if(n == digits.size()) { res.push_back(current); return; } for(int i = iStart; i < digits.size(); i++) { int k = digits[i] - '0'; string aux = mymap[k]; for(int j = 0; j < aux.size(); j++) { current += aux[j]; solve(digits, current, i+1, n+1); current.pop_back(); } } } vector<string> letterCombinations(string digits) { if(digits == "") { return res; } createMap(); solve(digits, "", 0, 0); return res; } };
Java
UTF-8
89
2.1875
2
[]
no_license
public interface Noeud { public abstract String toString(); public int getIdNoeud(); }
C++
UTF-8
326
2.75
3
[]
no_license
#include <iostream> #include <map> #include <string> using namespace std; int main() { int C; cin >> C; while (C--) { int N; cin >> N; map <string, int> mp; while (N--) { string a, b; cin >> a >> b; mp[b]++; } int res = 1; for (auto i : mp) res *= (i.second + 1); cout << res - 1 << "\n"; } }
Python
UTF-8
759
3.109375
3
[]
no_license
#------------------------------------------------------------------------------- # Name: module1 # Purpose: # # Author: anderson # # Created: 15/08/2017 # Copyright: (c) anderson 2017 # Licence: <your licence> #------------------------------------------------------------------------------- class Cola: def __init__(self): self.__datos = [] def meter(self,valor): self.__datos.append(valor) def primero(self): return self.__datos[0] def sacar(self): p_ult = len(self.__datos) if (p_ult > 0): self.__datos.pop(0) def getLista(self): return self.__datos def numElem(self): return int(len(self.__datos))
Rust
UTF-8
2,647
2.71875
3
[]
no_license
use crate::types::text::Text; use serde::{Deserialize, Serialize}; #[derive(Debug, Deserialize, Serialize)] pub struct VersionStatus { /// String name of the current version, e.g. "1.15.2" name: String, /// Protocol number of the current version protocol: i32, } impl VersionStatus { pub fn new(name: impl ToString, protocol: i32) -> Self { Self { name: name.to_string(), protocol, } } } #[derive(Debug, Deserialize, Serialize)] pub struct PlayerSample { name: String, /// Uuid of the player id: String, } impl PlayerSample { pub fn new(name: impl ToString, id: impl ToString) -> Self { Self { name: name.to_string(), id: id.to_string(), } } } #[derive(Debug, Deserialize, Serialize)] pub struct PlayerStatus { max: u32, online: u32, sample: Vec<PlayerSample>, } impl PlayerStatus { pub fn new(max: u32, online: u32, sample: Vec<PlayerSample>) -> Self { Self { max, online, sample, } } } #[derive(Debug, Deserialize, Serialize)] pub struct StatusPayload { version: VersionStatus, players: PlayerStatus, description: Text, #[serde(skip_serializing_if = "Option::is_none")] favicon: Option<String>, } impl StatusPayload { pub fn new(version: VersionStatus, players: PlayerStatus, description: Text, favicon: Option<String>) -> Self { Self { version, players, description, favicon, } } } pub mod serverbound { packets! { 0 => Request {}, 1 => Ping { val: i64 } } } pub mod clientbound { use super::StatusPayload; packets! { 0 => Response { status: StatusPayload; impl ProtoSerializable for Response { fn read<R: Read>(mut r: R) -> Result<Self> where Self: Sized { let s: String = proto::read(&mut r)?; let status = serde_json::from_str(&s)?; Ok(Self { status }) } fn write<W: Write>(&self, mut w: W) -> Result<()> { let s = serde_json::to_string(&self.status)?; s.write(&mut w) } } }, 1 => Pong { val: i64 } } }
PHP
UTF-8
3,260
2.671875
3
[]
no_license
<?php namespace App\Command; use App\Entity\Transaction; use App\Exception\ExporterNotFoundException; use App\Repository\TransactionRepository; use App\Adapter\TransactionAdapter; use App\Service\CurrencyConverter; use App\Service\Exporter\ExporterFactory; use App\Service\Exporter\ExporterInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class ReportCommand extends Command { protected static $defaultName = 'generate-report'; protected const CUSTOMER_ID_ARGUMENT = 'customerId'; /** @var TransactionRepository */ protected $transactionRepository; /** @var CurrencyConverter */ protected $currencyConverter; /** @var ExporterFactory */ protected $exporterFactory; /** @var TransactionAdapter */ protected $transactionAdapter; /** * ReportCommand constructor. * * @param TransactionRepository $transactionRepository * @param CurrencyConverter $currencyConverter * @param ExporterFactory $exporterFactory * @param TransactionAdapter $transactionAdapter * @param string|null $name */ public function __construct( TransactionRepository $transactionRepository, CurrencyConverter $currencyConverter, ExporterFactory $exporterFactory, TransactionAdapter $transactionAdapter, string $name = null) { parent::__construct($name); $this->currencyConverter = $currencyConverter; $this->transactionRepository = $transactionRepository; $this->exporterFactory = $exporterFactory; $this->transactionAdapter = $transactionAdapter; } protected function configure() { // available with "php bin/console list" $this->setDescription('Creates a new report by Customer Id.'); $this->addArgument(self::CUSTOMER_ID_ARGUMENT, InputArgument::REQUIRED, 'The customer id'); } /** * @param InputInterface $input * @param OutputInterface $output * * @return int * @throws ExporterNotFoundException */ protected function execute(InputInterface $input, OutputInterface $output) { $customerId = intval($input->getArgument(self::CUSTOMER_ID_ARGUMENT)); //Retrieve transactions by customer Id /** @var Transaction[] $transactions */ $transactions = $this->transactionRepository->getByCustomerId($customerId); if (empty($transactions)) { $output->writeln('Customer ' . $customerId . ' haven\'t transactions'); return Command::FAILURE; } //Convert transactions in Euro $transactions = array_map(function (Transaction $transaction) { return $this->currencyConverter->convert($transaction); }, $transactions); /** @var ExporterInterface $exporter */ $exporter = $this->exporterFactory->getExporter(ExporterFactory::CSV_EXPORT); $exporter->export($this->transactionAdapter->adapt($transactions), 'customer_' . $customerId . '_transactions'); $output->writeln('CSV was generated'); return Command::SUCCESS; } }
Java
UTF-8
643
2.921875
3
[]
no_license
/** * */ package poj; /** * @author chenxi * */ import java.util.*; public class Main { static int max(int a,int b) { return a>b?a:b; } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Scanner s= new Scanner(System.in); int n,m; n =s.nextInt();m=s.nextInt(); int i,j; int c[]= new int[n]; int w[] = new int[n]; for(i=0;i<n;i++) { c[i] =s.nextInt(); w[i] =s.nextInt(); } int dp[]= new int[m+1]; dp[0] = 0; for( i=0;i<n;i++) { for(j = m;j>=c[i];j--) { dp[j] = max(dp[j],dp[j-c[i]]+w[i]); } } System.out.println(dp[m]); } }
Python
UTF-8
339
3.078125
3
[]
no_license
import math from trapezoid_module import * def f(x): return math.sqrt(x) * math.cos(x) * 3 / 2 Iold = 0.0 for k in range(1, 21): Inew = trapezoid(f, 0.0, math.pi, Iold, k) if (k > 1) and (abs(Inew - Iold)) < 1.0e-6 : break Iold = Inew print("Integral =", Inew) print("nPanels =", 2 ** (k - 1)) input("\nPress return to exit")
Go
UTF-8
408
2.671875
3
[]
no_license
package main import ( "fmt" "os" "github.com/nlopes/slack" ) func main() { token := os.Getenv("SLACK_API_TOKEN") if token == "" { fmt.Fprintf(os.Stderr, "SLAC_API_TOKEN is not found.\n") return } api := slack.New(token) teams, err := api.GetChannels(false) if err != nil { fmt.Printf("%s\n", err) return } for _, team := range teams { fmt.Printf("%s %s\n", team.ID, team.Name) } }
Markdown
UTF-8
617
2.953125
3
[]
no_license
# Project Name Here is my basic website design for a blog post. I detail designing a bedroom for my daughter. The brief was to design a basic webpage, including images. ## The problem My approach was to use a design board I had previously designed, to illustrate how I designed a bedroom for my 8-year old daughter. I added internet links to sources for the items. I have used Adobe Illustrator jpg files, added a menu section and some styling. I would like to usee CSS Grid next time to style (I feel my website is a bit too basic and amateur-ish) ## View it live https://agitated-jepsen-383265.netlify.app
PHP
UTF-8
3,325
3.390625
3
[]
no_license
<?php $dbServer = "mysql:3306"; $dbName = "Users"; $dbUName = "root"; $dbPassword = "docker"; // Open a connection to the database server $mysqli = new mysqli($dbServer, $dbUName, $dbPassword, $dbName); /* * This is the "official" OO way to do it, * BUT $connect_error was broken until PHP 5.2.9 and 5.3.0. */ if ($mysqli->connect_error) { die("Connect Error (" . $mysqli->connect_errno . ")" . $mysqli->connect_error); } // Try another query $enteredName = "swz"; // Pretend the user entered this // Execute SQL query, for SELECT returns resource // on true or false if error $records = $mysqli->query("SELECT * FROM Students WHERE username LIKE '" . PreventSqlInjection($mysqli, $enteredName) . "'"); if($records == false) { die("Query contains error"); } // Prevent hacker typing something nasty into a Form // and performing an SQL injection attack. function PreventSqlInjection($mysqli, $text) { // Magic Quotes can be turned on in php.ini to protect // beginner PHP coders from SQL injection attacks. // e.g. "It's good" after applying magic quotes // becomes "It\'s good". // Not all GET and POST data needs to be escaped, // so experienced coders turn this off. // When writing to MySQL, remove if (get_magic_quotes_gpc()) // Is magic quotes on? { $text = stripslashes($text); // Remove the slashes added } // If using MySQL, escape special characters return $mysqli->real_escape_string($text); } // Fetch an array representing the result row. while($record = mysqli_fetch_array($records)) { echo "row: name=" . $record["username"] . " pwd " . $record["password"] . " info " . $record["information"] . "<br/>"; } $closed = $mysqli->close(); if($closed == false) { die("Connection closed failed " . mysqli_error()); } // Perform an INSERT query $enteredName = $_POST["nameTextBox"]; $enteredPwd = $_POST["pwdTextBox"]; $enteredInfo = $_POST["infoTextBox"]; $enteredId = $_POST["idTextBox"]; $mysqli = new mysqli($dbServer, $dbUName, $dbPassword, $dbName); if ($mysqli->connect_error) { die("Connect Error (" . $mysqli->connect_errno . ")" . $mysqli->connect_error); } //CREATE $result = $mysqli->query( "INSERT INTO Students(username, password, information, id) VALUES(" . "'" . PreventSqlInjection($mysqli, $enteredName) . "','" . PreventSqlInjection($mysqli, $enteredPwd) . "','" . PreventSqlInjection($mysqli, $enteredInfo) . "','" . PreventSqlInjection($mysqli, $enteredId) . "')" ); if($result == false) { die("Query contains error"); } else { echo "Create success!<br/>"; } echo "Rows added = " . $mysqli->affected_rows . "<br/>"; echo "Primary Key (int) ID of inserted row = " . $mysqli->insert_id . "<br/>"; //DELETE $result = $mysqli->query("DELETE FROM Students WHERE username = ''"); if($result == false) { die("Query contains error"); } else { echo "Delete success!<br/>"; } //UPDATE $result = $mysqli->query("UPDATE Students SET username = 3 WHERE username = 'swz'"); if($result == false) { die("Query contains error"); } else { echo "Update success!<br/>"; } $closed = $mysqli->close(); if($closed == false) { die("Connection closed failed " . mysqli_error()); } ?>
Ruby
UTF-8
1,123
2.796875
3
[ "BSD-3-Clause" ]
permissive
class BotDispatcher def initialize(chat, text, lang) @chat, @text, @lang = chat, text, lang I18n.locale = %w(pt ru).include?(@lang) ? @lang : 'en' end def process case @text when /\A\/((start)|(stop)|(commands))\z/i reply I18n.t @text[1..-1] when /\/t\b/, /\/т\b/, /\/traduzir/i, /\/translate/i @text.slice! $& # removing last matching text from string translate auto_detect_language when /\/(#{$SUPPORTED_LANGUAGES})\b/ @text.slice! $& translate({ from: '', to: $&[1..-1] }) when /\/ру\b/ @text.slice! $& translate({ from: '', to: 'ru' }) else translate auto_detect_language if @chat > 0 end end private def translate(languages) TranslationJob.perform_later @chat, @text, languages unless @text.empty? end def auto_detect_language if @text =~ /[а-я]+/ui lang1, lang2 = 'ru', 'pt' elsif @text =~ /[a-z]+/i lang1, lang2 = 'pt', 'ru' else lang1, lang2 = '', 'en' end { from: lang1, to: lang2 } end def reply(txt) BotConnector.new(@chat, txt).send_message end end
Java
UTF-8
18,647
1.84375
2
[]
no_license
/* * An XML document type. * Localname: Medline-rn * Namespace: http://www.ncbi.nlm.nih.gov * Java type: gov.nih.nlm.ncbi.www.MedlineRnDocument * * Automatically generated - do not modify. */ package gov.nih.nlm.ncbi.www; /** * A document containing one Medline-rn(@http://www.ncbi.nlm.nih.gov) element. * * This is a complex type. */ public interface MedlineRnDocument extends org.apache.xmlbeans.XmlObject { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(MedlineRnDocument.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s74A68D9904DCF749AED49DB11323D727").resolveHandle("medlinerna487doctype"); /** * Gets the "Medline-rn" element */ gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn getMedlineRn(); /** * Sets the "Medline-rn" element */ void setMedlineRn(gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn medlineRn); /** * Appends and returns a new empty "Medline-rn" element */ gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn addNewMedlineRn(); /** * An XML Medline-rn(@http://www.ncbi.nlm.nih.gov). * * This is a complex type. */ public interface MedlineRn extends org.apache.xmlbeans.XmlObject { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(MedlineRn.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s74A68D9904DCF749AED49DB11323D727").resolveHandle("medlinernfc02elemtype"); /** * Gets the "type" element */ gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type getType(); /** * Sets the "type" element */ void setType(gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type type); /** * Appends and returns a new empty "type" element */ gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type addNewType(); /** * Gets the "cit" element */ java.lang.String getCit(); /** * Gets (as xml) the "cit" element */ org.apache.xmlbeans.XmlString xgetCit(); /** * True if has "cit" element */ boolean isSetCit(); /** * Sets the "cit" element */ void setCit(java.lang.String cit); /** * Sets (as xml) the "cit" element */ void xsetCit(org.apache.xmlbeans.XmlString cit); /** * Unsets the "cit" element */ void unsetCit(); /** * Gets the "name" element */ java.lang.String getName(); /** * Gets (as xml) the "name" element */ org.apache.xmlbeans.XmlString xgetName(); /** * Sets the "name" element */ void setName(java.lang.String name); /** * Sets (as xml) the "name" element */ void xsetName(org.apache.xmlbeans.XmlString name); /** * An XML type(@http://www.ncbi.nlm.nih.gov). * * This is a complex type. */ public interface Type extends org.apache.xmlbeans.XmlObject { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(Type.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s74A68D9904DCF749AED49DB11323D727").resolveHandle("type8b58elemtype"); /** * Gets the "value" attribute */ gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type.Value.Enum getValue(); /** * Gets (as xml) the "value" attribute */ gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type.Value xgetValue(); /** * Sets the "value" attribute */ void setValue(gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type.Value.Enum value); /** * Sets (as xml) the "value" attribute */ void xsetValue(gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type.Value value); /** * An XML value(@). * * This is an atomic type that is a restriction of gov.nih.nlm.ncbi.www.MedlineRnDocument$MedlineRn$Type$Value. */ public interface Value extends org.apache.xmlbeans.XmlString { public static final org.apache.xmlbeans.SchemaType type = (org.apache.xmlbeans.SchemaType) org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(Value.class.getClassLoader(), "schemaorg_apache_xmlbeans.system.s74A68D9904DCF749AED49DB11323D727").resolveHandle("value2f1fattrtype"); org.apache.xmlbeans.StringEnumAbstractBase enumValue(); void set(org.apache.xmlbeans.StringEnumAbstractBase e); static final Enum NAMEONLY = Enum.forString("nameonly"); static final Enum CAS = Enum.forString("cas"); static final Enum EC = Enum.forString("ec"); static final int INT_NAMEONLY = Enum.INT_NAMEONLY; static final int INT_CAS = Enum.INT_CAS; static final int INT_EC = Enum.INT_EC; /** * Enumeration value class for gov.nih.nlm.ncbi.www.MedlineRnDocument$MedlineRn$Type$Value. * These enum values can be used as follows: * <pre> * enum.toString(); // returns the string value of the enum * enum.intValue(); // returns an int value, useful for switches * // e.g., case Enum.INT_NAMEONLY * Enum.forString(s); // returns the enum value for a string * Enum.forInt(i); // returns the enum value for an int * </pre> * Enumeration objects are immutable singleton objects that * can be compared using == object equality. They have no * public constructor. See the constants defined within this * class for all the valid values. */ static final class Enum extends org.apache.xmlbeans.StringEnumAbstractBase { /** * Returns the enum value for a string, or null if none. */ public static Enum forString(java.lang.String s) { return (Enum)table.forString(s); } /** * Returns the enum value corresponding to an int, or null if none. */ public static Enum forInt(int i) { return (Enum)table.forInt(i); } private Enum(java.lang.String s, int i) { super(s, i); } static final int INT_NAMEONLY = 1; static final int INT_CAS = 2; static final int INT_EC = 3; public static final org.apache.xmlbeans.StringEnumAbstractBase.Table table = new org.apache.xmlbeans.StringEnumAbstractBase.Table ( new Enum[] { new Enum("nameonly", INT_NAMEONLY), new Enum("cas", INT_CAS), new Enum("ec", INT_EC), } ); private static final long serialVersionUID = 1L; private java.lang.Object readResolve() { return forInt(intValue()); } } /** * A factory class with static methods for creating instances * of this type. */ public static final class Factory { public static gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type.Value newValue(java.lang.Object obj) { return (gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type.Value) type.newValue( obj ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type.Value newInstance() { return (gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type.Value) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type.Value newInstance(org.apache.xmlbeans.XmlOptions options) { return (gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type.Value) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); } private Factory() { } // No instance of this class allowed } } /** * A factory class with static methods for creating instances * of this type. */ public static final class Factory { public static gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type newInstance() { return (gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type newInstance(org.apache.xmlbeans.XmlOptions options) { return (gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn.Type) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); } private Factory() { } // No instance of this class allowed } } /** * A factory class with static methods for creating instances * of this type. */ public static final class Factory { public static gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn newInstance() { return (gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn newInstance(org.apache.xmlbeans.XmlOptions options) { return (gov.nih.nlm.ncbi.www.MedlineRnDocument.MedlineRn) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); } private Factory() { } // No instance of this class allowed } } /** * A factory class with static methods for creating instances * of this type. */ public static final class Factory { public static gov.nih.nlm.ncbi.www.MedlineRnDocument newInstance() { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, null ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument newInstance(org.apache.xmlbeans.XmlOptions options) { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newInstance( type, options ); } /** @param xmlAsString the string value to parse */ public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(java.lang.String xmlAsString) throws org.apache.xmlbeans.XmlException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, null ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(java.lang.String xmlAsString, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xmlAsString, type, options ); } /** @param file the file from which to load an xml document */ public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(java.io.File file) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, null ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(java.io.File file, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( file, type, options ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(java.net.URL u) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, null ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(java.net.URL u, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( u, type, options ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(java.io.InputStream is) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, null ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(java.io.InputStream is, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( is, type, options ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(java.io.Reader r) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, null ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(java.io.Reader r, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, java.io.IOException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( r, type, options ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(javax.xml.stream.XMLStreamReader sr) throws org.apache.xmlbeans.XmlException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, null ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(javax.xml.stream.XMLStreamReader sr, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( sr, type, options ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(org.w3c.dom.Node node) throws org.apache.xmlbeans.XmlException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, null ); } public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(org.w3c.dom.Node node, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( node, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static gov.nih.nlm.ncbi.www.MedlineRnDocument parse(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return (gov.nih.nlm.ncbi.www.MedlineRnDocument) org.apache.xmlbeans.XmlBeans.getContextTypeLoader().parse( xis, type, options ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, null ); } /** @deprecated {@link org.apache.xmlbeans.xml.stream.XMLInputStream} */ public static org.apache.xmlbeans.xml.stream.XMLInputStream newValidatingXMLInputStream(org.apache.xmlbeans.xml.stream.XMLInputStream xis, org.apache.xmlbeans.XmlOptions options) throws org.apache.xmlbeans.XmlException, org.apache.xmlbeans.xml.stream.XMLStreamException { return org.apache.xmlbeans.XmlBeans.getContextTypeLoader().newValidatingXMLInputStream( xis, type, options ); } private Factory() { } // No instance of this class allowed } }
C#
UTF-8
2,230
3.359375
3
[]
no_license
namespace Labyrinth.Core.PlayField { using System; using Labyrinth.Core.Common; using Labyrinth.Core.Helpers.Contracts; using Labyrinth.Core.PlayField.Contracts; /// <summary> /// This class represents the game cell /// </summary> public class Cell : ICell, ICloneableCell { private char valueChar; /// <summary> /// Constructor with 2 parameters /// </summary> /// <param name="position">Parameter of type IPosition</param> /// <param name="value">Parameter of type char</param> public Cell(IPosition position, char value = Constants.StandardGameCellEmptyValue) { this.Position = position; this.ValueChar = value; } /// <summary> /// Property of type IPosition /// </summary> public IPosition Position { get; set; } /// <summary> /// Property of type char /// </summary> public char ValueChar { get { return this.valueChar; } set { if ( value != Constants.StandardGameCellEmptyValue && value != Constants.StandardGameCellWallValue && value != Constants.StandardGamePlayerChar) { throw new ArgumentException("The value char must be in already defined ones!"); } this.valueChar = value; } } /// <summary> /// Method that checks if a cell is empty /// </summary> /// <returns>Bool value</returns> public bool IsEmpty() { if (this.ValueChar == Constants.StandardGameCellEmptyValue) { return true; } return false; } /// <summary> /// Method that clones the cell /// </summary> /// <returns>Returns value of type ICell</returns> public ICell Clone() { Cell newCell = (Cell)this.MemberwiseClone(); newCell.Position = newCell.Position.Clone(); return newCell; } } }
PHP
UTF-8
1,436
3.09375
3
[ "MIT" ]
permissive
<?php namespace OwAPI; use GuzzleHttp\ClientInterface; use Psr\Http\Message\ResponseInterface; /** * Class Response * @package OwAPI */ class Response { private $body; private $rawResponse; private $request; private $status; private $success; /** * Response constructor. * @param ClientInterface $request * @param $response */ public function __construct(ClientInterface $request, $response) { $this->request = $request; if ($response) { $this->body = json_decode($response->getBody(), true, 512); $this->rawResponse = $response; $this->status = $response->getStatusCode(); $this->success = floor($this->status / 100) == 2; } } /** * @return array|null */ public function getBody(): ?array { return $this->body; } /** * @return ResponseInterface */ public function getRawResponse(): ResponseInterface { return $this->rawResponse; } /** * @return int|null */ public function getStatus(): ?int { return $this->status; } /** * @return bool */ public function isSuccess(): bool { return $this->success; } /** * @return ClientInterface */ public function getRequest(): ClientInterface { return $this->request; } }
Java
UTF-8
3,839
1.804688
2
[ "Apache-2.0", "LicenseRef-scancode-elastic-license-2018" ]
permissive
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.client.ml.job.results; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.test.AbstractXContentTestCase; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; public class AnomalyRecordTests extends AbstractXContentTestCase<AnomalyRecord> { @Override protected AnomalyRecord createTestInstance() { return createTestInstance("foo"); } public static AnomalyRecord createTestInstance(String jobId) { AnomalyRecord anomalyRecord = new AnomalyRecord(jobId, new Date(randomNonNegativeLong()), randomNonNegativeLong()); anomalyRecord.setActual(Collections.singletonList(randomDouble())); anomalyRecord.setTypical(Collections.singletonList(randomDouble())); anomalyRecord.setProbability(randomDouble()); if (randomBoolean()) { anomalyRecord.setMultiBucketImpact(randomDouble()); } anomalyRecord.setRecordScore(randomDouble()); anomalyRecord.setInitialRecordScore(randomDouble()); anomalyRecord.setInterim(randomBoolean()); if (randomBoolean()) { anomalyRecord.setFieldName(randomAlphaOfLength(12)); } if (randomBoolean()) { anomalyRecord.setByFieldName(randomAlphaOfLength(12)); anomalyRecord.setByFieldValue(randomAlphaOfLength(12)); } if (randomBoolean()) { anomalyRecord.setPartitionFieldName(randomAlphaOfLength(12)); anomalyRecord.setPartitionFieldValue(randomAlphaOfLength(12)); } if (randomBoolean()) { anomalyRecord.setOverFieldName(randomAlphaOfLength(12)); anomalyRecord.setOverFieldValue(randomAlphaOfLength(12)); } anomalyRecord.setFunction(randomAlphaOfLengthBetween(5, 20)); anomalyRecord.setFunctionDescription(randomAlphaOfLengthBetween(5, 20)); if (randomBoolean()) { anomalyRecord.setCorrelatedByFieldValue(randomAlphaOfLength(16)); } if (randomBoolean()) { int count = randomIntBetween(0, 9); List<Influence> influences = new ArrayList<>(); for (int i=0; i<count; i++) { influences.add(new Influence(randomAlphaOfLength(8), Collections.singletonList(randomAlphaOfLengthBetween(1, 28)))); } anomalyRecord.setInfluencers(influences); } if (randomBoolean()) { int count = randomIntBetween(0, 9); List<AnomalyCause> causes = new ArrayList<>(); for (int i=0; i<count; i++) { causes.add(new AnomalyCauseTests().createTestInstance()); } anomalyRecord.setCauses(causes); } return anomalyRecord; } @Override protected AnomalyRecord doParseInstance(XContentParser parser) { return AnomalyRecord.PARSER.apply(parser, null); } @Override protected boolean supportsUnknownFields() { return true; } }
C++
UTF-8
1,660
3.359375
3
[]
no_license
#pragma once #define MATRIX_H #include <iostream> #include <Windows.h> #include <random> #include <ctime> class Matrix { private: int row; int col; int** matrix; public: //constructors and destructors Matrix() { matrix = NULL; row = 0; col = 0; } Matrix(const int size_row, const int size_col) { matrix = NULL; row = size_row; col = size_col; matrix = new int*[row]; for (int i = 0; i < row; i++) { matrix[i] = new int[col]; for (int j = 0; j < col; j++) { matrix[i][j] = 0; } } } ~Matrix() { for (int i = 0; i < row; i++) { delete matrix[i]; // matrix[i] = NULL // ? just wondering... } delete matrix; matrix = NULL; } // get/set stuff int get(int i, int j) { if (matrix != NULL && i >= 0 && i < row && j >= 0 && j < col) { return matrix[i][j]; } else { std::cout << "Index out of range"; } } void set(int i, int j, int num) { if (matrix != NULL && i >= 0 && i < row && j >= 0 && j < col) { matrix[i][j] = num; } else { std::cout << "Index out of range"; } } int get_row() { return row; } int get_col() { return col; } // print void print() { for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { printf("%d ", matrix[i][j]); } printf("\n"); } } void print_pretty() { srand(time(NULL)); char c = 219; for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if (matrix[i][j] == 1) { //SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), (rand() % 7) + 9); // random color (9-15) std::cout << c << c; } else { printf(" "); } } printf("\n"); } } };
Java
UTF-8
548
2.09375
2
[]
no_license
package com.example.parita.pplview; /** * Created by parita on 18-02-2018. */ public class DataAdapter { String heading; public String getHeading(){return heading;} public void setHeading(String heading){this.heading=heading;} String comment; String useremail; public String getComment(){return comment;} public void setComment(String comment){this.comment=comment;} public String getUseremail(){return useremail;} public void setUseremail(String useremail){this.useremail=useremail;} }
Java
UTF-8
188
1.664063
2
[]
no_license
package Exercicios.ExercicioFixacaoCap18.Services; public interface OnlineService { Double paymentTax (Double quantidade); Double paypalTax(Double quantidade, Integer date); }