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
Shell
UTF-8
1,733
3.09375
3
[ "MIT" ]
permissive
#!/bin/bash # Copyright 2014 The Kubernetes Authors All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # used to install kubectl inside the build environment plus other tools these scripts leverage. # uncomment for troubleshooting if required # set -xv PKG_MANAGER=$( command -v yum || command -v apt-get ) || echo "Neither yum nor apt-get found" #make sure sudo is installed if [ ! -e "/usr/bin/sudo" ]; then ${PKG_MANAGER} install -y sudo fi # remove default setting of requiretty if it exists sed -i '/Defaults requiretty/d' /etc/sudoers #make sure wget is installed if [ ! -e "/usr/bin/wget" ]; then sudo ${PKG_MANAGER} install -y wget fi #make sure jq is installed if [ ! -e "/usr/bin/jq" ]; then sudo ${PKG_MANAGER} install -y jq fi #make sure envsubst is installed if [ ! -e "/usr/bin/envsubst" ]; then sudo ${PKG_MANAGER} install -y gettext fi # make the temp directory if [ ! -e ~/.kube ]; then mkdir -p ~/.kube; fi if [ ! -e ~/.kube/kubectl ]; then wget https://storage.googleapis.com/kubernetes-release/release/v1.2.0/bin/linux/amd64/kubectl -O ~/.kube/kubectl chmod +x ~/.kube/kubectl fi pwd ~/.kube/kubectl config use-context ${KUBECONTEXTQA} ~/.kube/kubectl version
C++
UTF-8
501
2.828125
3
[]
no_license
byte ADCpin = 0; int ADCvalue = 0; void setup(){ Serial.begin(9600); } void loop() { ADCvalue = analogRead(ADCpin); float voltage = ADCvalue * 5.0; voltage = voltage / 1024.0; Serial.print("voltage = "); Serial.print(voltage); Serial.print(" "); // The TMP36 outputs 10mV per degree Celsius, with a 500 mV // offset added to all values. float TemperatureC = (voltage - 0.5) * 100; Serial.print("TemperatureC = "); Serial.println(TemperatureC); delay(1000); }
Markdown
UTF-8
871
2.8125
3
[]
no_license
# Smart home app - mobile version This project is made as a part of a recruitment task. It was created with ReactJS with React Router (bootstrapped with [Create React App](https://github.com/facebook/create-react-app)). Main state is created as Class Object and is managed by reducer. [Live preview](https://olgamilczek.github.io/move-closer-recruitment/) ## Functionalities - Adding room - Deleting room (with double confirmation) - Toggle room (devices which cannot be toggle (like e.g. fridge are still running) ) - Adding device (from list) - Removing device (with double confirmation) - Toggle device - Set value for selected devices with range. - Saving to localStorage. ## Installing dependencies Run `$ npm install` from the project root (assuming `npm` installed). ## Available scripts Build the App by running `$ npm start` from the project root.
C#
UTF-8
1,549
3.125
3
[ "Apache-2.0" ]
permissive
namespace Core.Interfaces { /// <summary> /// Represents an interface for Factory Method patern /// </summary> /// <typeparam name="TKey"> /// A key type by which creator is registrated /// </typeparam> /// <typeparam name="TRegValue"> /// A creator type, which know how to create an instance of the object /// </typeparam> /// <typeparam name="TReturnValue"> /// An object type, which instance should be created /// </typeparam> public interface IFactory<in TKey, in TRegValue, out TReturnValue> { /// <summary> /// Registrate creator by key /// </summary> /// <param name="key"> /// A key by creator is registered /// </param> /// <param name="value"> /// A concrete creator /// </param> void Registrate(TKey key, TRegValue value); /// <summary> /// Unregistrate creator by key /// </summary> /// <param name="key"> /// A key by which creator should be unregistered /// </param> void UnRegistrate(TKey key); /// <summary> /// Returns an instance of the object by key /// </summary> /// <param name="key"> /// A key by which instance of the object should be created /// </param> /// <returns> /// An instance of the object, which creator was registered by current key /// </returns> TReturnValue MakeInstance(TKey key); } }
Python
UTF-8
2,999
2.546875
3
[]
no_license
''' # Other code import maya.OpenMaya as OpenMaya import maya.cmds as cmds import maya.OpenMayaAnim as OpenMayaAnim """--------------------------------------------------------------------""" #declare variables as types node = OpenMaya.MObject() selectionList = OpenMaya.MSelectionList() OpenMaya.MGlobal.getActiveSelectionList(selectionList) topNode = OpenMaya.MObject() selectionList.getDependNode(0,topNode) # node is MObject to your mesh itDG = OpenMaya.MItDependencyGraph(topNode,OpenMaya.MItDependencyGraph.kDownstream,OpenMaya.MItDependencyGraph.kPlugLevel) while not itDG.isDone(): oCurrentItem = itDG.currentItem() if oCurrentItem.hasFn(OpenMaya.MFn.kSkinClusterFilter): print('Found') itDG.next() ''' """--------------------------------------------------------------------""" def getSkinCluster(): #define the variables as the necessary classes. dagPath = openMaya.MDagPath() selectionList = openMaya.MSelectionList() skinCluster = [] #grab whatever is selected and put it in selectionList openMaya.MGlobal.getActiveSelectionList(selectionList) #take the first thing selected and grab its dagPath selectionList.getDagPath(0, dagPath) #use the path to grab the shape *note this will break if there are more shapes. Will need to add the .numberOfShapesDirectlyBelow to ensure it doesn't break. dagPath.extendToShape() #this creates the iterator that will be used to loop through everything. *note The *It* between the M and the D denote that this is an iterator. itDG = openMaya.MItDependencyGraph(dagPath.node(),openMaya.MItDependencyGraph.kDownstream,openMaya.MItDependencyGraph.kPlugLevel) while not itDG.isDone(): oCurrentItem = itDG.currentItem() #the iterator returns an MObject that we then check to see if it is a skinCluster. If it is, Save it. if oCurrentItem.hasFn(openMaya.MFn.kSkinClusterFilter): skinCluster = openAni.MFnSkinCluster(oCurrentItem) print (skinCluster.name() + " will be returned") break itDG.next() return skinCluster, dagPath, selectionList """--------------------------------------------------------------------""" def averageSelection(): #grab the skinCluster skinCluster, relatedShape, selectionList = getSkinCluster() #determine that there is or isn't a skin cluster. if not skinCluster: openMaya.MGlobal.displayError("No skinCluster found") else: infCount = openMaya.MScriptUtil() uInf = infCount.asUintPtr() skinInfluences = openMaya.MDagPathArray() oldSkinWeights = openMaya.MDoubleArray() compItr = openMaya.MItSelectionList(selectionList) #using the .influenceObjects to get all the joint influences. skinCluster.influenceObjects(skinInfluences) while not compItr.isDone(): skinCluster.getWeights(relatedShape,compItr,oldSkinWeights,uInf) compItr.next() print oldSkinWeights
Python
UTF-8
527
3
3
[]
no_license
import sys import math S = 1 P = 0 t = int(input()) for i in range(t): n = int(input()) H = [int(health) for health in input().split(' ')] H = H[:n] H.sort() flag = True eat_no_mandragoras = 0 new_P = 0 for i in range(n): total_hp = sum(map(int,H[eat_no_mandragoras:])) new_P = S * total_hp if(new_P > P): P = new_P S = S + 1 eat_no_mandragoras = eat_no_mandragoras + 1 else: break print(P)
Markdown
UTF-8
812
2.78125
3
[]
no_license
## Installation - Clone the repository with `git clone --recurse-submodules` to update submodules. - After cloning: - Run `npm install` to install packages. - Follow the [Node-Logger readme](https://github.com/thomasnorris/Node-Logger) for instructions on setting up the logger. - In the `config` folder: - Copy/rename `config_template.json` to `config.json`. - Configure `config.json`. - In the `scripts` folder: - Make sure that the scripts that these files call exist. ## Usage - Create a shortcut for `scripts/LAUNCH.bat` and place in a desired location. - Edit the shortcut: - In the `Target:` field, append the directory of the `node.exe` executable. - Run the shortcut to start. - Endpoints can be called using `curl`, [Postman](https://www.postman.com/), etc.
SQL
UTF-8
1,661
4.09375
4
[]
no_license
-- Where the lot area is zero but the geometry is not null -- compute the lot area from the geometry in sq feet -- Insert old and new values into tracking table INSERT INTO pluto_corrections SELECT DISTINCT a.bbl as bbl, 'lotarea' as field, a.lotarea as old_value, round(ST_Area(ST_Transform(a.geom,2263)))::text as new_value, '1' as type, 'Zero lot area' as reason, a.version as version FROM pluto a WHERE a.lotarea = '0' AND a.geom IS NOT NULL AND a.bbl NOT IN (SELECT bbl FROM pluto_corrections WHERE field = 'lotarea'); -- -- Redundant code -- -- Apply correction -- UPDATE pluto a -- SET lotarea = b.new_value, -- dcpedited = 't' -- FROM pluto_corrections b -- WHERE a.bbl = b.bbl -- AND b.field = 'lotarea' -- AND a.lotarea = '0' -- AND a.geom IS NOT NULL; -- Take researched lot area values from the research table INSERT INTO pluto_corrections SELECT DISTINCT a.bbl, 'lotarea' as field, a.lotarea as old_value, b.new_value as new_value, b.type as type, b.reason as reason, b.version as version FROM pluto a, pluto_input_research b WHERE a.bbl = b.bbl AND a.lotarea::numeric=b.old_value::numeric AND b.field = 'lotarea' AND a.bbl NOT IN (SELECT bbl FROM pluto_corrections WHERE field = 'lotarea'); -- Apply correction to PLUTO UPDATE pluto a SET lotarea = b.new_value, dcpedited = 't' FROM pluto_corrections b WHERE a.bbl = b.bbl AND b.field = 'lotarea' AND a.lotarea::numeric=b.old_value::numeric; -- recalculate builtfar UPDATE pluto SET builtfar = round(bldgarea::numeric / lotarea::numeric, 2) WHERE lotarea <> '0' AND lotarea IS NOT NULL AND bbl IN (SELECT bbl FROM pluto_corrections WHERE field = 'lotarea');
Java
UTF-8
647
2.078125
2
[]
no_license
package br.com.jorgerabellodev.eniacproject.api.services; import br.com.jorgerabellodev.eniacproject.api.models.entities.Address; import br.com.jorgerabellodev.eniacproject.api.repositories.AddressRepository; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class AddressService { private final AddressRepository repository; @Autowired public AddressService(AddressRepository repository) { this.repository = repository; } public void saveAll(List<Address> adresses) { repository.saveAll(adresses); } }
Swift
UTF-8
3,086
2.78125
3
[]
no_license
// // FaceDetector.swift // DemoAppTascentOwlBytes // // Created by Henrique Valcanaia on 12/09/17. // Copyright © 2017 None. All rights reserved. // import Foundation import UIKit.UIImage class FaceDetector { // static func getFaces(from image: UIImage) -> [UIImage]? { // guard let personciImage = CIImage(image: image) else { // return nil // } // // let accuracy = [CIDetectorAccuracy: CIDetectorAccuracyHigh] // guard let faceDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil, options: accuracy) else { // return nil // } // // guard let faces = faceDetector.features(in: personciImage) as? [CIFaceFeature] else { // return nil // } // // // For converting the Core Image Coordinates to UIView Coordinates // let ciImageSize = personciImage.extent.size // var transform = CGAffineTransform(scaleX: 1, y: -1) // transform = transform.translatedBy(x: 0, y: -ciImageSize.height) // //// let facesImages = faces.map({image.crop(to: $0.bounds)}) //// return facesImages // for face in faces { // print("Found bounds are \(face.bounds)") // // // Apply the transform to convert the coordinates // var faceViewBounds = face.bounds.applying(transform) // // // Calculate the actual position and size of the rectangle in the image view // let viewSize = personPic.bounds.size // let scale = min(viewSize.width / ciImageSize.width, // viewSize.height / ciImageSize.height) // let offsetX = (viewSize.width - ciImageSize.width * scale) / 2 // let offsetY = (viewSize.height - ciImageSize.height * scale) / 2 // // faceViewBounds = CGRectApplyAffineTransform(faceViewBounds, CGAffineTransformMakeScale(scale, scale)) // faceViewBounds.origin.x += offsetX // faceViewBounds.origin.y += offsetY // // let faceBox = UIView(frame: faceViewBounds) // // faceBox.layer.borderWidth = 3 // faceBox.layer.borderColor = UIColor.red.cgColor // faceBox.backgroundColor = UIColor.clear.cgColor // personPic.addSubview(faceBox) // // if face.hasLeftEyePosition { // print("Left eye bounds are \(face.leftEyePosition)") // } // // if face.hasRightEyePosition { // print("Right eye bounds are \(face.rightEyePosition)") // } // } // } } extension UIImage { func crop(to rect: CGRect) -> UIImage { var rect = rect rect.origin.x*=self.scale rect.origin.y*=self.scale rect.size.width*=self.scale rect.size.height*=self.scale let imageRef = self.cgImage!.cropping(to: rect) let image = UIImage(cgImage: imageRef!, scale: self.scale, orientation: self.imageOrientation) return image } }
Python
UTF-8
247
2.671875
3
[ "MIT" ]
permissive
class Solution: def canJump(self, nums: List[int]) -> bool: steps = nums[0] for n in nums[1:]: if not steps: return False steps -= 1 steps = max(steps, n) return True
Java
UTF-8
1,178
2.0625
2
[ "Apache-2.0" ]
permissive
package com.bpwizard.bpm.demo.task.send_receive; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.bpwizard.bpm.demo.task.send_receive.domain.Order; import com.bpwizard.bpm.demo.task.send_receive.message.Message; import com.bpwizard.bpm.demo.task.send_receive.message.MessageSender; import com.bpwizard.bpm.demo.task.send_receive.persistence.OrderRepository; @Component("retrievePaymentAdapter") public class RetrievePaymentAdapter implements JavaDelegate { @Autowired private MessageSender messageSender; @Autowired private OrderRepository orderRepository; @Override public void execute(DelegateExecution context) throws Exception { Order order = orderRepository.getOrder((String) context.getVariable("orderId")); String traceId = context.getProcessBusinessKey(); messageSender.send(new Message<RetrievePaymentCommandPayload>( "RetrievePaymentCommand", traceId, new RetrievePaymentCommandPayload().setRefId(order.getId()).setAmount(order.getTotalSum()))); } }
Java
UTF-8
3,002
2.046875
2
[ "MIT" ]
permissive
package org.haobtc.wallet.utils; import android.app.PendingIntent; import android.content.Intent; import android.content.IntentFilter; import android.nfc.NfcAdapter; import android.nfc.tech.IsoDep; import android.nfc.tech.Ndef; import android.nfc.tech.NfcF; import android.nfc.tech.NfcV; import android.provider.Settings; import android.util.Log; import android.widget.Toast; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.FragmentActivity; import org.haobtc.wallet.R; public class NfcUtils { //nfc public static NfcAdapter mNfcAdapter; public static IntentFilter[] mIntentFilter; public static PendingIntent mPendingIntent; public static String[][] mTechList; public static void nfc(FragmentActivity activity, boolean promote) { mNfcAdapter = nfcCheck(activity, promote); nfcInit(activity); } /** * check if NFC enabled */ public static NfcAdapter nfcCheck(FragmentActivity activity, boolean promote) { NfcAdapter mNfcAdapter = NfcAdapter.getDefaultAdapter(activity); if (mNfcAdapter == null) { Toast.makeText(activity, activity.getString(R.string.dont_use_nfc), Toast.LENGTH_SHORT).show(); return null; } else { if (!mNfcAdapter.isEnabled() && promote) { isToSet(activity); } else { Log.d("NFC", "NFC功能已打开!"); } } return mNfcAdapter; } /** * init nfc */ private static void nfcInit(FragmentActivity activity) { // tag tech_list mTechList = new String[][]{{Ndef.class.getName()}, {NfcV.class.getName()}, {NfcF.class.getName()}, {IsoDep.class.getName()}}; // PendingIntent,the intent processing the coming tag mPendingIntent = PendingIntent.getActivity(activity, 0, new Intent(activity, activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), PendingIntent.FLAG_UPDATE_CURRENT); try { // filters to filter the nice tag mIntentFilter = new IntentFilter[]{new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED, "*/*")}; } catch (Exception e) { e.printStackTrace(); } } // if private static void isToSet(final FragmentActivity activity) { AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setMessage("是否跳转到设置页面打开NFC功能"); // builder.setTitle("提示"); builder.setPositiveButton("确认", (dialog, which) -> { goToSet(activity); dialog.dismiss(); }); builder.setNegativeButton("取消", (dialog, which) -> dialog.dismiss()); builder.create().show(); } private static void goToSet(FragmentActivity activity) { // 进入设置系统应用权限界面 Intent intent = new Intent(Settings.ACTION_SETTINGS); activity.startActivity(intent); } }
Java
GB18030
1,824
4.15625
4
[]
no_license
package BasicClassTypeStu; import java.util.Arrays; public class Test { /** * @param args */ public static void main(String[] args) { /* * 23 9 -4 18 100 7 Сγַ ˼· 1.Ҫ飬ҪԪ * 2.ԪַУҪȡַݣҪString 3.ַȡֵ洢һintн * 4.źַ */ String numberString = "23 9 -4 18 100 7"; numberString = sortNumberString(numberString); System.out.println("numbers=" + numberString); } public static String sortNumberString(String numberString) { // ȡַе֣ͨոindexOfʹsubstringȡ // 鷳Щֵ֮ķָǿոͨոַ룬Ķݵַ // һַָͨ˶ַ String[] strs = numberString.split(" "); // ֱӶַдСΪִ󣬱ת // ַתint int[] nums = parseIntArray(strs); // Arrays.sort(nums); // תַ return toString(nums); } public static String toString(int[] nums) { //ַַ StringBuffer sb = new StringBuffer(); for (int i = 0; i < nums.length; i++) { if(i < nums.length-1){ sb.append(nums[i]+" "); } else { sb.append(nums[i]); } } return sb.toString(); } public static int[] parseIntArray(String[] strs) { // һint int[] arr = new int[strs.length]; for (int i = 0; i < strs.length; i++) { arr[i] = Integer.parseInt(strs[i]); } return arr; } }
Java
UTF-8
3,845
2.046875
2
[ "BSD-3-Clause" ]
permissive
package scratch.kevin.simulators.ruptures.subduction; import java.io.File; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.opensha.sha.simulators.RSQSimEvent; import org.opensha.sha.simulators.SimulatorElement; import org.opensha.sha.simulators.iden.ElementIden; import org.opensha.sha.simulators.iden.LogicalAndRupIden; import org.opensha.sha.simulators.iden.RuptureIdentifier; import org.opensha.sha.simulators.parsers.RSQSimFileWriter; import org.opensha.sha.simulators.srf.RSQSimStateTransitionFileReader; import org.opensha.sha.simulators.utils.RSQSimUtils; import com.google.common.base.Preconditions; import com.google.common.io.Files; import scratch.kevin.simulators.RSQSimCatalog; import scratch.kevin.simulators.RSQSimCatalog.Catalogs; public class BruceSubductionFilter { public static void main(String[] args) throws IOException { RSQSimCatalog catalog = Catalogs.BRUCE_5566.instance(); File catalogDir = catalog.getCatalogDir(); HashSet<Integer> subductionPatchIDs = new HashSet<>(); HashSet<Integer> crustalPatchIDs = new HashSet<>(); for (SimulatorElement elem : catalog.getElements()) { if (elem.getSectionName().trim().startsWith("nn1")) subductionPatchIDs.add(elem.getID()); else crustalPatchIDs.add(elem.getID()); } System.out.println("Found "+subductionPatchIDs.size()+" subduction elements"); System.out.println("Found "+crustalPatchIDs.size()+" crustal elements"); boolean includeOtherCorupturing = false; // RuptureIdentifier coruptureIden = null; RuptureIdentifier coruptureIden = new LogicalAndRupIden( new ElementIden("Subduction", new ArrayList<>(subductionPatchIDs)), new ElementIden("Crustal", new ArrayList<>(crustalPatchIDs))); List<RSQSimEvent> events = catalog.loader().magRange(6.5, 11d).load(); System.out.println("Loaded "+events.size()+" events"); if (coruptureIden != null) { int numMatches = 0; int numNuclCrustal = 0; int numNuclSubduction = 0; for (RSQSimEvent event : catalog.loader().minMag(6.5).matches(coruptureIden).iterable()) { SimulatorElement hypoEl = RSQSimUtils.getHypocenterElem(event); boolean subHypo = subductionPatchIDs.contains(hypoEl.getID()); if (subHypo) numNuclSubduction++; else numNuclCrustal++; numMatches++; } DecimalFormat pDF = new DecimalFormat("0.00%"); System.out.println(numNuclSubduction+"/"+numMatches+" (" +pDF.format((double)numNuclSubduction/(double)numMatches)+") nucleate on subduction"); System.out.println(numNuclCrustal+"/"+numMatches+" (" +pDF.format((double)numNuclCrustal/(double)numMatches)+") nucleate on crustal"); } System.exit(0); RSQSimStateTransitionFileReader trans = catalog.getTransitions(); File paramFile = new File(catalogDir, "multiparam.in"); File elemFile = new File(catalogDir, "zfault_Deepen.in"); for (boolean subduction : new boolean[] {false,true}) { String prefix; HashSet<Integer> includePatches; if (subduction) { prefix = "subduction"; includePatches = subductionPatchIDs; } else { prefix = "crustal"; includePatches = crustalPatchIDs; } if (coruptureIden != null) prefix += "_corupture"; System.out.println("Writing "+prefix); String dirName = catalogDir.getName()+"_"+prefix; File outputDir = new File(catalogDir.getParentFile(), dirName); Preconditions.checkState(outputDir.exists() || outputDir.mkdir()); RSQSimFileWriter.patchFilterCatalog(events, catalog.getElements(), includePatches, includeOtherCorupturing, coruptureIden, outputDir, prefix, false, trans); Files.copy(paramFile, new File(outputDir, paramFile.getName())); Files.copy(elemFile, new File(outputDir, elemFile.getName())); } } }
TypeScript
UTF-8
646
2.671875
3
[]
no_license
import Client, { Issue } from "../client"; import ParameterInput from "./parameterInput"; export default class StatusNameInput extends ParameterInput { private value: string; constructor(bareInput: string) { super(); this.value = bareInput; } public async toParams(client: Client, issue: Issue) { const statuses = await client.getStatuses({ urlParams: { projectIdOrKey: String(issue.projectId) }, }); const status = statuses.find((status) => status.name === this.value); if (!status) throw new Error(`status "${this.value}" is queried, but not found.`); return { statusId: status.id }; } }
Go
UTF-8
1,020
3.078125
3
[]
no_license
package main import ( "fmt" "net" "time" ) const MAIN_HOSTNAME = "init_testrun_1" const PORT = "3002" var ME Contact func main() { inits() time.Sleep(5 * time.Second) if ME.Address != getMainIP() { fmt.Println("Im not main") sendInit() } else { fmt.Println("Im main") } server(PORT) } /* Getting the local IP and checking if its the same IP as MAIN_HOSTNAME which will be the node that all connect to. Then if it isn't the main it will ping the main to make it self known. */ func inits() { // Makes sure everything is up before trying to do stuff localIPs, _ := net.InterfaceAddrs() // The IP comes with a /16 that needs to be removed ME.Address = localIPs[1].String()[:(len(localIPs[1].String()) - 3)] fmt.Println("Im " + ME.Address) } func getMainIP() string { ips, err := net.LookupIP(MAIN_HOSTNAME) if err != nil { return "error" } return ips[0].String() } func sendInit() { time.Sleep(5 * time.Second) go client(MAIN_HOSTNAME, PORT, Message{CMD: "PING", Contact: ME}) }
Python
UTF-8
3,358
2.65625
3
[]
no_license
from flask import Flask, Blueprint, render_template, request from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) bp = Blueprint('app', __name__) #database user = 'ciechjpy' password = 'JAGrOSsMPm2Ad1lQRB7tCX8A8CwTRdyQ' host = 'tuffi.db.elephantsql.com' database = 'ciechjpy' app.config['SQLALCHEMY_DATABASE_URI'] = f'postgresql://{user}:{password}@{host}/{database}' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) class Personagem(db.Model): id = db.Column(db.Integer, primary_key=True) nome_ = db.Column(db.String(255), nullable=False) imagem_url_ = db.Column(db.String(255), nullable=False) biografia_ = db.Column(db.String(), nullable=False) def __init__(self, nome_, imagem_url_, biografia_): self.nome_ = nome_ self.imagem_url_ = imagem_url_ self.biografia_ = biografia_ @staticmethod def read_all(): return Personagem.query.all() @staticmethod def read(personagem_id): return Personagem.query.get(personagem_id) def save(self): db.session.add(self) db.session.commit() def update(self, new_data): print(new_data) self.nome_ = new_data.nome_ self.imagem_url_ = new_data.imagem_url_ self.biografia_ = new_data.biografia_ self.save() def delete(self): db.session.delete(self) db.session.commit() @bp.route('/') def home(): return render_template( "home.html" ) @bp.route('/read') def listaDePersonagens(): personagem = Personagem.read_all() return render_template( "read.html", listaDePersonagens = personagem, personagem = personagem ) @bp.route('/read/<personagem_id>') def biografia(personagem_id,): personagem = Personagem.read(personagem_id) return render_template( 'biografia.html', personagem = personagem ) @bp.route('/create', methods=('GET', 'POST')) def create(): id_atribuido = None if request.method == 'POST': form = request.form personagem = Personagem(form['nome_'], form['imagem_url_'], form['biografia_']) personagem.save() id_atribuido = personagem.id return render_template( 'create.html', id_atribuido = id_atribuido ) @bp.route('/update/<personagem_id>', methods=('GET', 'POST')) def update(personagem_id): sucesso = None personagem = Personagem.read(personagem_id) if request.method == 'POST': form = request.form print(form) new_data = Personagem(form['nome_'], form['imagem_url_'], form['biografia_']) personagem.update(new_data) sucesso = True return render_template( 'update.html', personagem = personagem , sucesso = sucesso ) @bp.route('/delete/<personagem_id>') def delete(personagem_id): personagem = Personagem.read(personagem_id) return render_template( 'delete.html', personagem = personagem ) @bp.route('/delete/<personagem_id>/confirmed') def delete_confirmed(personagem_id): sucesso = None personagem = Personagem.read(personagem_id) if personagem: personagem.delete() sucesso = True return render_template( "delete.html", sucesso = sucesso, personagem=personagem ) @bp.route('/sobre') def sobre(): return render_template( "criadoras.html" ) app.register_blueprint(bp) if __name__ == '__main__': app.run(debug=True)
TypeScript
UTF-8
400
2.515625
3
[]
no_license
export class Settings { httpPort: number; reaperURI: string; lightingVenueURI: string; public load(data: SettingsData): void { this.httpPort = data.httpPort; this.reaperURI = data.reaperURI; this.lightingVenueURI = data.lightingVenueURI; } } export interface SettingsData { httpPort: number; reaperURI: string; lightingVenueURI: string; }
Markdown
UTF-8
1,961
2.9375
3
[]
no_license
## 数据库关系说明 - 房间 (room) 和资产 (asset) 是多对多的关系, 所以有 changes 这个中间实体. 一个房间有多个资产, 一个资产在不同时间段内可能在不同的房间 - changes 和 assets 之间不用实际的外键连接, 只有隐性的外键关系. 可以通过提交修改的资产编号查到 asset_id, 然后再加到 changes 表中. ## 表说明 - assetManager: 哪个负责人负责哪些资产的表 - users: 各级管理员和普通人的表 - ## 数据字典 ### userProfile | 字段 | 说明 | | --------- | --------------------------- | | is_staff | 值为1时才能登录后台管理系统 | | is_active | 如果为0表示用户已经被删除 | | | | | | | ### assetManager | 字段 | 说明 | | --------- | -------------------------------- | | status | 资产状态(使用, 维修, 损坏, 报废) | | change_id | xiu'gai | | | | | | | ### changes | 字段 | 说明 | | ------------ | -------------------------- | | status | 修改资产状态 | | asset_number | 隐式外键 | | manager_id | 审核的人 | | is_approved | 是否通过审核 | | summit_id | 提交变更申请的人的 user_id | ## 一些查询逻辑 - 查询一个部门的所有资产: 查询部门的所有负责人 -> 所有负责人负责的所有资产 - 查询一个资产的所有历史移动: 在 assets 表中查得资产的最近更新 change_id, 通过 change_id 在 changes 表中不断查到 last_change_id, 直到 last_change_id 为空, 得到所有历史记录. 使用changes 表中的 room_id 在 rooms 表中查询可得到具体的地址
Java
UTF-8
3,437
2.25
2
[]
no_license
/** * @author yuanhh1 * * @email yuanhh1@lenovo.com * */ package com.yhh.analyser.view.fragment; import android.annotation.SuppressLint; import android.app.Fragment; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import com.yhh.analyser.R; import com.yhh.analyser.utils.LogUtils; import com.yhh.analyser.widget.IndexableListView; import com.yhh.analyser.view.activity.LogReaderActivity; import com.yhh.androidutils.ArrayUtils; import com.yhh.androidutils.FileUtils; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class LogCurrentFragment extends Fragment { private static final String TAG = LogUtils.DEBUG_TAG+ "CurrentLogFragment"; private IndexableListView mLogLv; private List<String> mLogNameList = null; private Context mcontext; @SuppressLint("NewApi") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mcontext = this.getActivity(); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.log_current_fragment, container, false); mLogLv = (IndexableListView) view.findViewById(R.id.log_current_lv); mLogNameList = ArrayUtils.toList(FileUtils.listFolderOrFile(LogUtils.LOG_DIR)); if(mLogNameList != null && mLogNameList.size() >0){ Collections.sort(mLogNameList); IndexableListView.ContentAdapter adapter = mLogLv.new ContentAdapter(this.getActivity(), android.R.layout.simple_list_item_1, mLogNameList); mLogLv.setAdapter(adapter); mLogLv.setFastScrollEnabled(true); mLogLv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { Intent intent = new Intent(mcontext, LogReaderActivity.class); Bundle bundle = new Bundle(); bundle.putString("logPath", LogUtils.LOG_DIR + "/" + mLogNameList.get(arg2)); intent.putExtras(bundle); mcontext.startActivity(intent); } }); }else{ Log.i(TAG,"Not found Log"); } return view; } /** * 过滤log, 显示满足要求的log * @param filePath */ private List<String> filterLog(String filePath) { List<String> mLogNameList = new ArrayList<String>(); File f = new File(filePath); File[] files = f.listFiles(); if(files ==null){ Log.e(TAG,"filePath="+filePath+" is not exist"); return null; } for (int i = 0; i < files.length; i++) { String tmpName = files[i].getName(); for (String log : LogUtils.LOG_ALL) { if (tmpName.startsWith(log)) { mLogNameList.add(tmpName); } } } Collections.sort(mLogNameList); return mLogNameList; } }
TypeScript
UTF-8
1,975
3.59375
4
[]
no_license
class Oven { private _isOn : boolean; public lightGas() : void { setTimeout(function (){ document.getElementById('target').innerHTML += "<p>"+new Date().getHours()+":"+new Date().getMinutes()+" : THE GAS IS ON!</p>"; }, 1000); console.log("THE GAS IS ON!"); //insert fart humor here this._isOn = true; } public extinguishGas() : void { setTimeout(function (){ document.getElementById('target').innerHTML += "<p>"+new Date().getHours()+":"+new Date().getMinutes()+" : THE GAS IS OFF!</p><hr>"; }, 3000); console.log("THE GAS IS OFF!"); //insert fart humor here this._isOn = false; } public bake(item : string) { if(this._isOn) { setTimeout(function (){ document.getElementById('target').innerHTML += "<p>"+new Date().getHours()+":"+new Date().getMinutes()+" : Now baking " + item + " !</p>"; }, 2000); console.log("Now baking " + item + "!"); } else { setTimeout(function (){ document.getElementById('target').innerHTML += "<p>"+new Date().getHours()+":"+new Date().getMinutes()+" : there is no gas!</p>"; }, 2000); console.log("there is no gas!");//insert fart humor here } } } class Restaurant { private _name : string; private _oven : Oven = new Oven(); constructor(name : string) { this._name = name; } public Cook(item : string) { this._oven.lightGas(); this._oven.bake(item); this._oven.extinguishGas(); } } let bakery = new Restaurant("Bakery"); bakery.Cook("cookies"); //Now if we want to add a new restaurant with an ELECTRIC cooker, we are gonna be in a hot mess ... /* let bakery = new Restaurant("Bakery", new Oven()); bakery.Cook("cookies"); let crepery = new Restaurant("Crepery", new Stove()); crepery.Cook("crepes"); */
Java
UTF-8
1,484
4.03125
4
[]
no_license
package a1.secuenciales; /** *@author María Moreno Muñoz @Fecha 02/11/2019 Ejercicio 16. Dos vehículos viajan a diferentes velocidades (v1 y v2) y están distanciados por una distancia d. El que está detrás viaja a una velocidad mayor. Se pide hacer un algoritmo para ingresar la distancia entre los dos vehículos (km) y sus respectivas velocidades(km/h) y con esto determinar y mostrar en que tiempo (minutos) alcanzará el vehículo más rápido al otro. Variable a usar: * v1 y v2 = float = velocidad de los coches * distancia= float = distancia entre los dos * t= int = El tiempo en alcanzarse * tmin = int = tiempo en minutos **/ import java.util.*; public class Ej16{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); //declaro variables Float v1; Float v2; Float distancia; double t; double tmin; //pido variables System.out.println("Indique la velocidad del vehículo1, el mas rápido: "); v1 = sc.nextFloat(); System.out.println("Indique la velocidad del vehículo2, el mas lento: "); v2 = sc.nextFloat(); System.out.println("Indique la distancia entre los vehículos: "); distancia = sc.nextFloat(); //realizo operaciones t=distancia/(v1-v2); //pasar tiempo a minutos tmin=t*60; //muestro resultados System.out.printf("El tiempo en minútos es %f", tmin); } }
Markdown
UTF-8
740
3.109375
3
[]
no_license
# Cài đặt virtualenv Trước khi làm bước này, hãy đảm bảo rằng bạn đã cài Python 3.6 trở lên. ## 1. Tạo thư mục venv Tại thư mục gốc của dự án (thư mục `cuuhomientrung`), chạy lệnh sau: ``` $ python3 -m venv venv ``` Lệnh vừa rồi sẽ tạo thư mục `venv` trong thư mục `cuuhomientrung`. Tham khảo: - https://docs.python.org/3/library/venv.html ## 2. Bật/tắt venv Tại thư mục gốc của dự án (thư mục `cuuhomientrung`), chạy lệnh sau: Bật venv: ``` $ source venv/bin/activate ``` Kiểm tra: ``` $ pip -V pip 20.0.2 from /.../.../.../cuuhomientrung/venv/lib/python3.8/site-packages/pip (python 3.8) ``` Tắt venv: ``` $ deactivate ```
Java
UTF-8
10,067
2.40625
2
[ "Apache-2.0" ]
permissive
import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JLabel; import javax.swing.JTextField; import javax.swing.JComboBox; import javax.swing.ImageIcon; import javax.swing.JButton; import java.awt.event.ActionListener; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.awt.event.ActionEvent; import javax.swing.JList; import javax.swing.JOptionPane; public class IssueBookFaculty extends JFrame { private JPanel contentPane; private JTextField textField; private JTextField textField_1; private JTextField textField_2; private JTextField textField_3; private JTextField textField_4; private JTextField textField_5; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { IssueBookFaculty frame = new IssueBookFaculty(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public IssueBookFaculty() { super("Issue and Submit Faculty Book.."); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 450, 327); setLocationRelativeTo(this); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblFacultyName = new JLabel("Faculty Name"); lblFacultyName.setBounds(10, 59, 88, 14); contentPane.add(lblFacultyName); textField = new JTextField(); textField.setBounds(118, 56, 172, 20); contentPane.add(textField); textField.setColumns(10); JLabel lblEnrollId = new JLabel("Enroll Id"); lblEnrollId.setBounds(10, 91, 76, 17); contentPane.add(lblEnrollId); textField_1 = new JTextField(); textField_1.setBounds(118, 89, 172, 20); contentPane.add(textField_1); textField_1.setColumns(10); JLabel lblDepartment = new JLabel("Department"); lblDepartment.setBounds(10, 27, 88, 14); contentPane.add(lblDepartment); JComboBox comboBox = new JComboBox(); comboBox.setBounds(118, 24, 285, 20); comboBox.addItem("Select"); comboBox.addItem("Mathmatics Department"); comboBox.addItem("Physics Department"); comboBox.addItem("Social Health and Huminity Department"); comboBox.addItem("Mechanical Department"); comboBox.addItem("Civil Department"); comboBox.addItem("Chemical Department"); comboBox.addItem("Electrical Department"); comboBox.addItem("Electronics and Communication Department"); comboBox.addItem("Computer Science Department"); comboBox.addItem("Information Technology Department"); comboBox.addItem("Metalargical Department"); comboBox.addItem("Mining Department"); contentPane.add(comboBox); JLabel lblBookId = new JLabel("Book Id"); lblBookId.setBounds(10, 128, 88, 14); contentPane.add(lblBookId); textField_2 = new JTextField(); textField_2.setBounds(118, 122, 172, 20); contentPane.add(textField_2); textField_2.setColumns(10); JLabel lblSubject = new JLabel("Subject"); lblSubject.setBounds(10, 163, 76, 14); contentPane.add(lblSubject); textField_3 = new JTextField(); textField_3.setBounds(118, 157, 172, 20); contentPane.add(textField_3); textField_3.setColumns(10); JLabel lblAuthor = new JLabel("Author"); lblAuthor.setBounds(10, 196, 76, 14); contentPane.add(lblAuthor); textField_4 = new JTextField(); textField_4.setBounds(118, 193, 172, 20); contentPane.add(textField_4); textField_4.setColumns(10); JLabel lblPublication = new JLabel("Publication"); lblPublication.setBounds(10, 227, 88, 17); contentPane.add(lblPublication); textField_5 = new JTextField(); textField_5.setBounds(118, 224, 172, 20); contentPane.add(textField_5); textField_5.setColumns(10); JButton btnGoBack = new JButton("Go Back"); btnGoBack.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { Admin obj=new Admin(); obj.setVisible(true); dispose(); } }); btnGoBack.setBounds(9, 254, 89, 23); contentPane.add(btnGoBack); JButton btnIssue = new JButton("ISSUE"); btnIssue.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String FACULTY_NAME=textField.getText(); String ENROLL_NO=textField_1.getText(); String BOOK_ID=textField_2.getText(); String SUBJECT=textField_3.getText(); String AUTHOR=textField_4.getText(); String PUBLICATION=textField_5.getText(); String DEPARTMENT=(String)comboBox.getSelectedItem(); int flag=0; if(FACULTY_NAME.length()==0||ENROLL_NO.length()==0||BOOK_ID.length()==0||SUBJECT.length()==0||AUTHOR.length()==0||PUBLICATION.length()==0||DEPARTMENT.length()==0) { JOptionPane.showMessageDialog(getParent(),"plz fill required fields","Error",JOptionPane.ERROR_MESSAGE); } else { Connection con=DBInfo1.con; String Query="delete from addnewbook where bookname=? and author=?"; try { PreparedStatement ps = con.prepareStatement(Query); ps.setString(1,SUBJECT); ps.setString(2,AUTHOR); flag=ps.executeUpdate(); } catch (SQLException e2) { e2.printStackTrace(); } if(flag==1) { Connection con1=DBInfo1.con; String query="insert into issuebook values(?,?,?,?,?,?,?,?,?,?)"; try { PreparedStatement ps=con1.prepareStatement(query); ps.setString(1,FACULTY_NAME); ps.setString(2,ENROLL_NO); ps.setString(3,DEPARTMENT); ps.setString(4,"NN"); ps.setString(5,"NN"); ps.setString(6,BOOK_ID); ps.setString(7,SUBJECT); ps.setString(8,AUTHOR); ps.setString(9,PUBLICATION); ps.setString(10,"faculty"); ps.executeUpdate(); JOptionPane.showMessageDialog(getParent(),"Entry submitted to account"); } catch (SQLException e1) { e1.printStackTrace(); } } else { JOptionPane.showMessageDialog(getParent(),"book is not available in library","Error",JOptionPane.ERROR_MESSAGE); } } } }); btnIssue.setBounds(117, 255, 68, 23); contentPane.add(btnIssue); JButton btnSubmit = new JButton("SUBMIT"); btnSubmit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String FACULTY_NAME=textField.getText(); String ENROLL_NO=textField_1.getText(); String BOOK_ID=textField_2.getText(); String SUBJECT=textField_3.getText(); String AUTHOR=textField_4.getText(); String PUBLICATION=textField_5.getText(); String DEPARTMENT=(String)comboBox.getSelectedItem(); int flag=0; if(FACULTY_NAME.length()==0||ENROLL_NO.length()==0||BOOK_ID.length()==0||SUBJECT.length()==0||AUTHOR.length()==0||PUBLICATION.length()==0||DEPARTMENT.length()==0) { JOptionPane.showMessageDialog(getParent(),"plz fill required fields","Error",JOptionPane.ERROR_MESSAGE); } else { Connection con=DBInfo1.con; String Query="delete from issuebook where username=? and bookid=?"; try { PreparedStatement ps = con.prepareStatement(Query); ps.setString(1,FACULTY_NAME); ps.setString(2,BOOK_ID); flag=ps.executeUpdate(); if(flag==0) { String Query1="delete from issuebook where bookname=? and author=?"; try { PreparedStatement ps1 = con.prepareStatement(Query1); ps1.setString(1,SUBJECT); ps1.setString(2,AUTHOR); flag=ps1.executeUpdate(); } catch (SQLException e2) { e2.printStackTrace(); } } } catch (SQLException e2) { e2.printStackTrace(); } if(flag==1) { Connection con1=DBInfo1.con; String query="insert into submitbook values(?,?,?,?,?,?,?,?,?,?)"; try { PreparedStatement ps=con1.prepareStatement(query); ps.setString(1,FACULTY_NAME); ps.setString(2,ENROLL_NO); ps.setString(3,DEPARTMENT); ps.setString(4,"NN"); ps.setString(5,"NN"); ps.setString(6,BOOK_ID); ps.setString(7,SUBJECT); ps.setString(8,AUTHOR); ps.setString(9,PUBLICATION); ps.setString(10,"faculty"); ps.executeUpdate(); JOptionPane.showMessageDialog(getParent(),"Entry submitted to account"); } catch (SQLException e1) { e1.printStackTrace(); } } else { JOptionPane.showMessageDialog(getParent(),"book is not available in library","Error",JOptionPane.ERROR_MESSAGE); } } } }); btnSubmit.setBounds(198, 255, 92, 23); contentPane.add(btnSubmit); JButton btnReset = new JButton("RESET"); btnReset.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { textField.setText(null); textField_1.setText(null); textField_2.setText(null); textField_3.setText(null); textField_4.setText(null); textField_5.setText(null); comboBox.setSelectedIndex(0); } }); btnReset.setBounds(314, 254, 89, 23); contentPane.add(btnReset); JLabel lblNewLabel = new JLabel(new ImageIcon("mybk.jpg")); lblNewLabel.setBounds(314, 145, 89, 99); contentPane.add(lblNewLabel); } }
PHP
UTF-8
806
2.671875
3
[]
no_license
<?php // Timeout in seconds $timeout = 5; $fp = fsockopen("10.2.73.156", 80, $errno, $errstr, $timeout); if ($fp) { /* fwrite($fp, "GET /file.php HTTP/1.0\r\n"); fwrite($fp, "Host: www.server.com\r\n"); fwrite($fp, "Connection: Close\r\n\r\n"); stream_set_blocking($fp, TRUE); stream_set_timeout($fp,$timeout); $info = stream_get_meta_data($fp); while ((!feof($fp)) && (!$info['timed_out'])) { $data .= fgets($fp, 4096); $info = stream_get_meta_data($fp); ob_flush; flush(); } if ($info['timed_out']) { echo "Connection Timed Out!"; } else { echo $data; } */ } else { echo 'Not Connected'; } ?>
Markdown
UTF-8
1,359
2.765625
3
[ "MIT" ]
permissive
We show how substituting letters with their corresponding confusable tricks spam filters into classifying spam emails as ham emails. The data was used for this experiment below: - spam-classification: data downloaded from [spam-classification](https://github.com/subhashbylaiah/spam-classification) on November 24, 2019. - enron-spam: data downloaded from [enron-spam](http://www2.aueb.gr/users/ion/data/enron-spam/) on November 24, 2019. We also had a pre-process step to convert data from the "raw" format to the one used by the Python script. spam.sh and ham.sh were used to combine all spam emails together and all ham emails together. pre-process.py is used that each row is a full representation of an individual email’s information consisting of a “spam” or “ham” label, comma-separated from the email text. The reformatted file was parsed and converted to a pandas dataframe with no headers. The resulting dataframe is a simple framework that consists of two columns only: the email instance and the corresponding label, with the label appearing before the email instance. Each email message is a single space-delimited stream of words. It can be executed with following commands, as indicated in experiment.py: - ./experiment.py spam_ham_dataset.csv A - ./experiment.py spam_ham_dataset.csv B - ./experiment.py spam_ham_dataset.csv C
Markdown
UTF-8
958
3.09375
3
[]
no_license
Реализуйте и экспортируйте по умолчанию функцию, \ которая сравнивает объекты по совпадению данных,\ а не по ссылкам. Эта функция принимает на вход две компании и возвращает true, \ если их структура одинаковая, и false в обратном случае. \ Проверка должна проходить по свойствам name, state, website. ```js const company1 = { name: 'Hexlet', state: 'moderating', website: 'https://hexlet.io' }; const company2 = { name: 'CodeBasics', state: 'published', website: 'https://code-basics.com' }; is(company1, company2); // false const company11 = { name: 'Hexlet', state: 'published', website: 'https://hexlet.io' }; const company22 = { name: 'Hexlet', state: 'published', website: 'https://hexlet.io' }; is(company1, company2); // true ```
Ruby
UTF-8
966
3.265625
3
[]
no_license
# frozen_string_literal: true require 'basic_file_reader' adapters = BasicFileReader.lines(file_name: 'input').map(&:to_i).sort # Monkeypatch the [] for arrays so that the default value for an array will # be 0 instad of nil; this way we don't need to add .to_i or exatra checks class Array def [](index) at(index) || 0 end end def joltages(adapters) diffs = [0, 0, 1] current_jolt = 0 adapters.each do |adapter| diffs[adapter - current_jolt - 1] += 1 current_jolt = adapter end diffs[0] * diffs[2] end def adapters_arrangements(adapters) arrangements = [] arrangements[adapters.size - 1] = 1 (adapters.size - 2).downto(0).each do |index| arrangements[index] = 0 (index + 1).upto(index + 3) do |i| next if adapters[i] - adapters[index] > 3 arrangements[index] += arrangements[i] end end arrangements.first end p joltages(adapters) p adapters_arrangements([0] + adapters + [adapters.max + 3])
Swift
UTF-8
781
3.421875
3
[]
no_license
extension ListNode { func nextForRemovedDuplicates() -> ListNode? { var current = self var next = current.next while true { if next != nil, current.val == next!.val { current = next! next = current.next } else { break } } return next } } class Solution { func deleteDuplicates(_ head: ListNode?) -> ListNode? { var current = head while true { guard current?.next != nil else { break } current?.next = current?.nextForRemovedDuplicates() current = current?.next } return head } }
Java
UTF-8
1,660
2.234375
2
[]
no_license
/* * Remuco - A remote control system for media players. * Copyright (C) 2006-2010 by the Remuco team, see AUTHORS. * * This file is part of Remuco. * * Remuco is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Remuco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Remuco. If not, see <http://www.gnu.org/licenses/>. * */ package remuco.client.midp.ui.screens; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import javax.microedition.lcdui.List; public class ServiceSelectorScreen extends List { private final Vector urls; public ServiceSelectorScreen() { super("Media Players", List.IMPLICIT); urls = new Vector(); } /** * Get the selected service. * * @return the service URL */ public String getSelectedService() { final int index = getSelectedIndex(); return (String) urls.elementAt(index); } public void setServices(Hashtable services) { deleteAll(); urls.removeAllElements(); final Enumeration e = services.keys(); while (e.hasMoreElements()) { final String name = (String) e.nextElement(); append(name, null); urls.addElement(services.get(name)); } } }
Shell
UTF-8
1,715
3.78125
4
[]
no_license
#!/bin/bash OPENNMS_HOME="/usr/share/opennms" URL="" RESTURL=" -u admin:admin http://localhost:8980/opennms/rest/foreignSources/policies/Manage" foreignsource="ARSINFO" foreignid="" ip="" show_help () { cat <<END Usage: $0 -t <target ip address(optional)> -n <foreignid> -a <ip address to add> -d (opennms home directory default /usr/share/opennms) This script will generate a list of $PROVISION command to be executed to remove ipaddress to foreignid node in opennms END exit 1 } doRemoveIpSecondary() { # echo $PROVISION interface remove $foreignsource $foreignid $ip echo "curl -X DELETE -H \"Content-Type: application/xml\" $RESTURL$ip" } if [ "${1}" == "" ] ; then show_help fi while [ "${1}" != "" ] ; do case "${1}" in "-n") if [ "${2}" == "" ] ; then show_help; fi foreignid=$2 shift 2 ;; "-a") if [ "${2}" == "" ] ; then show_help; fi ip=$2 shift 2 ;; "-d") if [ "${2}" == "" ] ; then show_help; fi OPENNMS_HOME=$2 shift 2 ;; "-t") if [ "${2}" == "" ] ; then show_help; fi URL="--url http://$2:8980/opennms/rest" RESTURL=" -u admin:admin http://$2:8980/opennms/rest/foreignSources/policies/Manage" shift 2 ;; *) show_help ;; esac done PROVISION="$OPENNMS_HOME/bin/provision.pl $URL" if [ "$foreignid" == "" ]; then echo "foreign id not set. Exiting...." exit 2 fi if [ "$ip" == "" ]; then echo "ip address not set. Exiting...." exit 2 fi doRemoveIpSecondary
PHP
UTF-8
630
3.859375
4
[]
no_license
<!DOCTYPE html> <html> <head> <title>Ejercicio 6</title> </head> <body> <?php echo "<pre>"; for ($i=0; $i < 15 ; $i++) { $arreglo[]=rand(1,50); } $arreglo[0]=0; $arreglo[1]=0; echo "Arreglo original: <br>"; print_r($arreglo); /*echo "<br><br>arreglo sin duplicados:<br>"; $array = array_unique($array); foreach ($array as $value){ echo "$value\n";*/ foreach ($arreglo as $key => $value) { for ($i=0; $i < 15; $i++) { if ($arreglo2[$key]==$value) { continue; }else{ $arreglo2[$key]=$value; } } } print_r($arreglo2); echo "</pre>"; ?> </body> </html>
Java
UTF-8
2,310
2.015625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2008 Alin Dreghiciu * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. * * See the License for the specific language governing permissions and * limitations under the License. */ package org.ops4j.pax.exam.it; import static org.hamcrest.CoreMatchers.*; import org.junit.After; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.osgi.framework.BundleContext; import org.ops4j.pax.exam.junit.JUnit4TestRunner; /** * JUnit annotations tests. * * @author Alin Dreghiciu (adreghiciu@gmail.com) * @since 0.3.0, November 18, 2008 */ @RunWith( JUnit4TestRunner.class ) public class JunitAnnotationsTest { /** * True if the before01 method had been run. */ private boolean before01HadRun; /** * True if the before02 method had been run. */ private boolean before02HadRun; @Before public void before01() { before01HadRun = true; } @Before public void before02( final BundleContext bundleContext ) { before02HadRun = bundleContext != null; } @After public void after01() { } @After public void after02( final BundleContext bundleContext ) { } /** * An ignored test that should not be run. */ @Test @Ignore public void ignored() { fail( "This method was not supposed to be run" ); } @Test( expected = RuntimeException.class ) public void expected() { throw new RuntimeException( "This exception should not fail the test" ); } /** * test that before methods had been run. */ @Test public void beforesHadRun() { assertThat( "Method before01() had been called", before01HadRun, is( true ) ); assertThat( "Method before02() had been called", before02HadRun, is( true ) ); } }
C++
UTF-8
1,051
2.6875
3
[]
no_license
#include <iostream> #include <opencv2/opencv.hpp> #define IMAGE_WITH 2496 #define IMAGE_HEIGHT 1664 using namespace cv; int main() { Mat img; FILE *fp = NULL; char *imagedata = NULL; int framesize = IMAGE_WITH * IMAGE_HEIGHT; //Open raw Bayer image fp = fopen("bild.CR2", "rb"); //try{ //Memory allocation for bayer image data buffer. imagedata = (char*) malloc(sizeof(char) * framesize); //} //catch(...) //{ // return 0; //} //try { //Reade image data and store in buffer fread(imagedata, sizeof(char), framesize, fp); //} //catch (...) //{ // return 0; //} //Image diemension //imageSize.height = IMAGE_HEIGHT; //imageSize.with = IMAGE_WITH; //Create OpenCV mat structure for image dimension. For 8 bit bayer, type should be CV_8UC1. img.create(IMAGE_HEIGHT, IMAGE_WITH, CV_32F; memcpy(img.data, imagedata, framesize); free(imagedata); fclose(fp); imwrite("test.jpg", img); return 1; }
JavaScript
UTF-8
933
3.015625
3
[]
no_license
$("#creep-button").click( function(evt) { $.getJSON('/creepy', { your_age: $('input[name = "your_age"]').val(), other_age: $('input[name = "other_age"]').val() }, function(data){ if (data.is_creepy) { // tell user they a creep //alert("Straight creep"); $("#creep-result").text("Straight creep.") } else { $("#creep-result").text("You're alright.") } }); }); // $("#creep-button").click(function (event) { // // Make the URL for our AJAX request: this will be /result? follow by our form parameters // // We'll use the jQuery .serialize() method on our form object. // var url = "/result?" + $("#creep-form").serialize(); // // Print our URL to the JS console for debugging // console.log(url); // // Replace everything at #madlib-result with the result of our AJAX call // $("#creep-result").load(url); // });
Java
UTF-8
4,490
3.40625
3
[]
no_license
package ua.univer.javacore.Case.task18; import java.util.Scanner; public class SP18 { public static void task18() { Scanner in = new Scanner(System.in); System.out.println("Input the digit : "); int input = in.nextInt(); int odinitsy = input % 10; int desiatky = (input % 100-odinitsy)/10; int sotny = (input - (desiatky + odinitsy))/100; first :{ switch (sotny) { case 1: System.out.print("Cто "); break; case 2: System.out.print("Двісті "); break; case 3: System.out.print("Триста "); break; case 4: System.out.print("Чотириста "); break; case 5: System.out.print("П'ятсот "); break; case 6: System.out.print("Шістот "); break; case 7: System.out.print("Сімсот "); break; case 8: System.out.print("Вісімсот "); break; case 9: System.out.print("Дев'ятсот "); break; default: System.out.println("Digit is bigger than 1000!"); } if (desiatky < 2) { switch (odinitsy) { case 0: System.out.print("десять "); break; case 1: System.out.print("одинадцять"); break; case 2: System.out.print("дванадцять"); break; case 3: System.out.print("тринадцять"); break; case 4: System.out.print("чотирнадцять"); break; case 5: System.out.print("п'ятнадцять"); break; case 6: System.out.print("шістнадцять"); break; case 7: System.out.print("сімнадцять"); break; case 8: System.out.print("вісімнадцять"); break; case 9: System.out.print("дев'ятнадцять"); break; } break first; } switch (desiatky) { case 2: System.out.print("двадцять "); break; case 3: System.out.print("тридцять "); break; case 4: System.out.print("сорок "); break; case 5: System.out.print("п'ятдесят "); break; case 6: System.out.print("шістдесят "); break; case 7: System.out.print("сімдесят "); break; case 8: System.out.print("вісімдесят "); break; case 9: System.out.print("дев'яносто "); break; } switch (odinitsy) { case 1: System.out.print("один");break; case 2: System.out.print("два");break; case 3: System.out.print("три");break; case 4: System.out.print("чотири");break; case 5: System.out.print("п'ять");break; case 6: System.out.print("шість");break; case 7: System.out.print("сім");break; case 8: System.out.print("вісім");break; case 9: System.out.print("дев'ять");break; } } } }
C++
UTF-8
2,119
4.3125
4
[ "Apache-2.0" ]
permissive
/* C++ program for 3-way quick sort Contributor: Vatsalya Gupta */ #include <bits/stdc++.h> using namespace std; /* This function partitions a[] in three parts a) a[l..i] contains all elements smaller than pivot b) a[i+1..j-1] contains all occurrences of pivot c) a[j..r] contains all elements greater than pivot */ void partition(int a[], int l, int r, int& i, int& j) { i = l - 1, j = r; int p = l - 1, q = r; int v = a[r]; while (true) { // From left, find the first element greater than // or equal to v. This loop will definitely // terminate as v is last element while (a[++i] < v) ; // From right, find the first element smaller than // or equal to v while (v < a[--j]) if (j == l) break; // If i and j cross, then we are done if (i >= j) break; // Swap, so that smaller goes on left greater goes // on right swap(a[i], a[j]); // Move all same left occurrence of pivot to // beginning of array and keep count using p if (a[i] == v) { p++; swap(a[p], a[i]); } // Move all same right occurrence of pivot to end of // array and keep count using q if (a[j] == v) { q--; swap(a[j], a[q]); } } // Move pivot element to its correct index swap(a[i], a[r]); // Move all left same occurrences from beginning // to adjacent to arr[i] j = i - 1; for (int k = l; k < p; k++, j--) swap(a[k], a[j]); // Move all right same occurrences from end // to adjacent to arr[i] i = i + 1; for (int k = r - 1; k > q; k--, i++) swap(a[i], a[k]); } // 3-way partition based quick sort void quicksort(int a[], int l, int r) { if (r <= l) return; int i, j; // Note that i and j are passed as reference partition(a, l, r, i, j); // Recur quicksort(a, l, j); quicksort(a, i, r); } // A utility function to print an array void printarr(int a[], int n) { for (int i = 0; i < n; ++i) printf("%d ", a[i]); printf("\n"); } // Driver code int main() { int a[] = { 4, 9, 4, 4, 1, 9, 4, 4, 9, 4, 4, 1, 4 }; int size = sizeof(a) / sizeof(int); // Function Call printarr(a, size); quicksort(a, 0, size - 1); printarr(a, size); return 0; }
Markdown
UTF-8
2,215
3.0625
3
[ "MIT" ]
permissive
# 03 Webpack React ## Resumen Este ejemplo toma como punto de partida el ejemplo _02-webpack-boiler_. Vamos a ir paso a paso añdiendo la configuración necesaria para que integrar **React** en nuestro proceso de build. ## Paso a Paso - Primero copiamos el ejemplo anterior, y hacemos un _npm install_ ```bash npm install ``` - Vamos a instalar _react_ y _react-dom_ ```bash npm install react react-dom --save ``` - Vamos a instalarnos los typing de _react_ y _react-dom_ ```bash npm install @types/react @types/react-dom --save-dev ``` Así tenemos la librería de React y los bindings para que se integre con un navegador web. - En el index.html vamos a meter el _div_ que nos servirá como punto de entrada para instanciar nuestra aplicación React. _./src/index.html_ ```diff <body> - Hello World ! + <div id="root"></div> </body> ``` - Vamos a crear nuestro primero componente React. _./src/app.tsx_ ```tsx import React from "react"; export const App = () => { return ( <h1>Hello React !!</h1> ) } ``` - Es hora de instanciar ese compente principal, para poder integrarlo con el navegador tenemos que hacer uso a _ReactDOM.render_ _./src/index.tsx_ ```tsx import React from "react"; import ReactDOM from "react-dom"; import { App } from "./app"; ReactDOM.render( <div> <App /> </div>, document.getElementById("root") ); ``` - Vamos por buen camino, pero si intentamos ejecutar esto no va fallar, ya que _babel_ no sabe como transformar el _jsx_ (recordemos que esto era un azucar, que en realidad era un XML) a javaScript, para que babel sea capaz de entender esto tenemos que instalar el _preset_ _@babel/preset-react_ Primero lo instalamos ```bash npm install @babel/preset-react --save-dev ``` _.babelrc_ ```diff { "presets": [ "@babel/preset-env", "@babel/preset-typescript", + "@babel/preset-react" ] } ``` - Es hora de saltar al _webpack.config.js_ - Nos podemos asegurar de que tenemos como extension valida _ts_ y _tsx_ - También que en el loader aceptamos tanto _ts_ como _tsx_ - Y en el app tenemos como punto de entrada _index.tsx_ * Vamos a comprobar que hemos dejado todo funcionando: ```bash npm start ```
Java
UTF-8
1,425
3.484375
3
[]
no_license
import java.util.Scanner; class PasswordChecker { public static void main(String args[]) { int digitCount=0; int lowerCount=0; int upperCount=0; int spaceCount=0; Scanner scanner = new Scanner(System.in); System.out.print("Please enter your password:"); String password = scanner.nextLine(); System.out.println(password); //testing the password agaist the ciritea int length = password.length(); if (length < 8){ System.out.println("Password is too short"); return; } else{ System.out.println("Password length is fine"); char[] chars = password.toCharArray(); for (int i =0; i < chars.length; i++){ boolean upper = Character.isUpperCase(chars[i]); if (upper == true) upperCount++; boolean lower= Character.isLowerCase(chars[i]); if (lower == true) lowerCount++; boolean digit= Character.isDigit(chars[i]); if (digit == true) digitCount++; boolean space= Character.isSpace(chars[i]); if (space == true) spaceCount++; } System.out.println(upperCount+" uppercase"); System.out.println(lowerCount+" lowercase"); System.out.println(digitCount+" digits"); System.out.println(spaceCount+" whitespace"); if ((upperCount >0) && (lowerCount >0) && (digitCount >0) && (spaceCount == 0)){ System.out.println("Password is OK"); } else System.out.println("Password is invalid"); } } }
C
UTF-8
4,978
4.0625
4
[]
no_license
/** @file voronoi.c @author Brian Morris (bcmorri3) This program outputs a 100x100 pixel voronoi diagram by accepting 6 double values from standard input representing the (x, y) coordinates of 3 points on the diagram and fills in the remaining diagram coordinates with the appropriate colors. */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <stdbool.h> /** The valid number of coordinate tokens that must be read in by scanf. */ #define VALID_COUNT 6 /** The exit status of the program if invalid input is encountered. */ #define INVALID_INPUT 100 /** The number of pixels in the image. */ #define NUM_PIXELS 100 /** The maximum intensity of an RGB value. */ #define MAX_INTENSITY 255 /** The minimum intensity of an RGB value. */ #define MIN_INTENSITY 0 /** The power required to square values. */ #define SQUARE 2 /** The x coordinate of the first point. */ double p1x; /** The y coordinate of the first point. */ double p1y; /** The x coordinate of the second point. */ double p2x; /** The y coordinate of the second point. */ double p2y; /** The x coordinate of the third point. */ double p3x; /** The y coordinate of the third point. */ double p3y; /** This function returns true if the provided pixel (col, row) is the closest point in the diagram to the rounded integer coordinates of the given input point (x, y). @param col the column number of the pixel @param row the row number of the pixel @param x the x coordinate of the input point @param y the y coordinate of the input point @return true if the provided pixel is the closest point in the diagram to the rounded integer coordinates of the given input point. */ bool nearestPoint( int col, int row, double x, double y ) { // Rounded x coordinate for comparison. double roundedX = round( x ); // Rounded y coordinate for comparison. double roundedY = round( y ); // If the provided pixel is equal to the rounded coordinates, return true. if ( (double) col == roundedX && (double) row == roundedY ) { return true; } else { return false; } } /** This function accepts the provided pixel (col, row) and prints the pixel with the appropriate color. If it's the closest pixel to one of the 3 input points, it becomes white, if it's closest to the first point, it becomes red, if it's closest to the second point it becomes green, and if it's closest to the third point it becomes blue. @param col the column number of the pixel @param row the row number of the pixel */ void chooseColor ( int col, int row ) { // Determine if the given pixel column and row are closest to any of the given 3 // points. If so, print the pixel with white RGB values. bool nearP1 = nearestPoint( col, row, p1x, p1y ); bool nearP2 = nearestPoint( col, row, p2x, p2y ); bool nearP3 = nearestPoint( col, row, p3x, p3y ); if ( nearP1 || nearP2 || nearP3 ) { printf("%3d %3d %3d ", MAX_INTENSITY, MAX_INTENSITY, MAX_INTENSITY ); } else { // Determine distance between the 3 points. double p1Distance = sqrt( pow( (p1x - col), SQUARE ) + pow( (p1y - row), SQUARE ) ); double p2Distance = sqrt( pow( (p2x - col), SQUARE ) + pow( (p2y - row), SQUARE ) ); double p3Distance = sqrt( pow( (p3x - col), SQUARE ) + pow( (p3y - row), SQUARE ) ); if ( (p1Distance < p2Distance) && (p1Distance < p3Distance) ) { // Print pixel closest to point 1 in red. printf( "%3d %3d %3d ", MAX_INTENSITY, MIN_INTENSITY, MIN_INTENSITY ); } else if ( (p2Distance < p1Distance) && (p2Distance < p3Distance) ) { // Print pixel closest to point 2 in green. printf( "%3d %3d %3d ", MIN_INTENSITY, MAX_INTENSITY, MIN_INTENSITY ); } else { // Print pixel closest to point 3 in blue. printf( "%3d %3d %3d ", MIN_INTENSITY, MIN_INTENSITY, MAX_INTENSITY ); } } } /** The starting point of the program. Accepts 3 points from standard input in (x, y) coordinates and creates a 100x100 pixel voronoi diagram based on the position of the 3 points. Returns the exit status of the program. @return Exit status of the program. */ int main() { // Determine if 6 point coordinates were found in standard input and assign them to globals. int read_count = scanf( "%lf %lf %lf %lf %lf %lf", &p1x, &p1y, &p2x, &p2y, &p3x, &p3y ); // If the count is invalid, exit with error code 100. if ( read_count != VALID_COUNT ) { printf("Invalid input\n"); return INVALID_INPUT; } // Print header. printf("P3\n%d %d\n%d\n", NUM_PIXELS, NUM_PIXELS, MAX_INTENSITY ); // Print diagram pixels. for ( int i = 0; i < NUM_PIXELS; i++ ) { for (int j = 0; j < NUM_PIXELS; j ++ ) { chooseColor( j, i ); } printf("\n"); } return EXIT_SUCCESS; }
C#
UTF-8
2,472
2.625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Linq; public class CardIDs : MonoBehaviour { public static Dictionary<int, string > cards; [SerializeField] public List<cardID> cardList; [System.Serializable] public struct cardID { public int ID; public string Name; } private void OnValidate() { if(cardList.Count == 0) { GetIdsFromFile(); GetIdsFromCards(); } } private void Start() { cards = cardList.ToDictionary(cid => cid.ID, cid => cid.Name); } void GetIdsFromFile() { string[] lines = System.IO.File.ReadAllLines(@"C:\Users\bubbl\OneDrive\Documents\Unity Projects\Artifact 3.0\Assets\Scripts\Lobby\DeckCode\items_game.txt"); foreach(string line in lines) { if (line.Contains("\"name\"")) { string nameid = line.Replace("name", ""); nameid = nameid.Replace('"', ' '); nameid = nameid.Trim(); cardID id = new cardID(); id.Name = nameid.Substring(0, nameid.LastIndexOf('-')); id.ID = int.Parse(nameid.Substring(nameid.LastIndexOf('-')+1)); cardList.Add(id); } } } void GetIdsFromCards() { foreach(GameObject card in FindObjectOfType<CardList>().cards) { Card c = card.GetComponent<Card>(); if(!cardList.Exists(x => x.ID == c.ID)) { cardID id = new cardID(); id.Name = c.cardName; id.ID = c.ID; cardList.Add(id); } } foreach (GameObject card in FindObjectOfType<CardList>().hero) { Card c = card.GetComponent<Card>(); if (!cardList.Exists(x => x.ID == c.ID)) { cardID id = new cardID(); id.Name = c.cardName; id.ID = c.ID; cardList.Add(id); } } foreach (GameObject card in FindObjectOfType<CardList>().items) { Card c = card.GetComponent<Card>(); if (!cardList.Exists(x => x.ID == c.ID)) { cardID id = new cardID(); id.Name = c.cardName; id.ID = c.ID; cardList.Add(id); } } } }
Python
UTF-8
397
3.875
4
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """ Created on Wed Dec 27 13:41:53 2017 @author: User """ import math def compareArea(circum, width): circleA = (circum*circum)/(4*math.pi) squareA = width*width if circleA == squareA: print("tie") elif circleA >= squareA: print("circle") else: print("square") compareArea(0.0, 0.0) compareArea(10.4, 4.0)
Java
UTF-8
760
2.6875
3
[]
no_license
package DP; public class zeroOneBU { public static int table(int[] weight, int[] val, int w, int n) { int[][]t = new int[n+1][w+1]; for(int i =0;i<n+1;i++) { for(int j =0;j<w+1;j++) { t[i][0] = 0; } } for(int i =1;i<n+1;i++) { for(int j =0;j<w+1;j++) { if(weight[i-1] > w) { t[i][j] = t[i-1][j]; } else if(weight[i-1]<=w){ t[i][j] = Math.max(t[i-1][j] ,val[i-1]+ t[i-1][j-weight[i-1]]); } } } return t[n+1][w+1]; } public static void main(String[] args) { // TODO Auto-generated method stub int val[] = new int[] { 60, 100, 120 }; int wt[] = new int[] { 10, 20, 30 }; int W = 10; int n = val.length; System.out.println(table(wt, val,W, n)); } }
Python
UTF-8
274
3.484375
3
[]
no_license
if __name__ == '__main__': res_list = [] for x in range(1, 50): res = '' if x % 3 == 0: res += 'Fizz' if x % 5 == 0: res += 'Buzz' res_list.append(res if res != '' else str(x)) print(', '.join(res_list))
Java
UTF-8
733
2.046875
2
[ "MIT" ]
permissive
package net.ncguy.editor.modules.world.adapter; import com.kotcrab.vis.ui.widget.VisTable; import net.ncguy.editor.modules.world.adapter.widget.Layout; import net.ncguy.editor.modules.world.adapter.widget.StringInput; import net.ncguy.foundation.data.components.mesh.AssetMeshComponent; public class AssetMeshComponentAdapter extends SceneComponentAdapter<AssetMeshComponent> { @Override public void buildControls(VisTable table, AssetMeshComponent component) { Layout.section(table, "Asset Mesh", true, t -> { Layout.addLabeledWidget(t, "Reference", StringInput.textField("Path", component::getAssetPath, component::setAssetPath)); }); super.buildControls(table, component); } }
Markdown
UTF-8
15,454
2.984375
3
[]
no_license
My mostly unqualified observations of your SMB server ===================================================== This is a part of a note I recently send to my doctor regarding his data management system. I was prompted to send him this when I found out that he did not know about RAID disk arrays. As a general text it may be of interest to people who are using off-the-shelf computer equipment for critical business applications but who do not know about things like ECC memory and RAID. 1, Failures of primary storage. Most hardware manufacturers sell what might loosely be termed business computers and commodity computers. There is often a big price difference between the two, even though they are substantially the same in many ways. Other than obvious differences like quality control or the amount of power/cooling, there is normally only one significant area where business computers (especially servers) differ in functionality that I can think of. This is in how the primary memory system is designed to deal with a number of failures (mainly things like cosmic rays penetrating memory chips) which can change the contents of primary storage (e.g. DRAM). Cheap computers usually have no way to even detect these problems, but as they are comparatively rare, most people can live with these problems. For example, if a small error were to be introduced into document being edited (like an ‘a’ turning into a ‘b’) once every year or two, I expect most people would accept this rather than buying another computer at higher cost. In contrast, the information held on business class servers is normally considered too important to allow errors of this kind to go unchecked. So they normally use what is called ECC memory. This kind of memory will not only detect memory errors, they will, in most cases, automatically correct them. (This is not 100% perfect because it is still possible to have extreme cases of corruption which can go undetected. This is very rare, so ECC is generally seen as a significant improvement over non-ECC memory.) The problem with memory corruption is that it can go undetected for many years, and the consequences could be very bad. If, for example, in a medical application a code meaning a patent is allergic to Penicillin were changed to indicate the patient is allergic to dairy products, this might result in significant medical consequences (and this could easily occur with a single bit being changed if, say, the code for Penicillin was 1 and the code for dairy products was 65, or 513, or any other value that is 2^n + 1). Depending on how an application is written it is also quite possible for an entire record to become unreadable. Also any of these possibilities could occur for a record that was not being edited because such records are sometimes bound into groups for I/O operations, and while one record is being edited, a different one in the same group is corrupted, which is then written back to secondary storage when the changes are complete. The use of ECC memory considerably reduces the dangers of all these kinds of errors. Hardware manufacturers are normally a little coy about telling people what consumer hardware will support ECC memory, presumably because they want businesses to purchase a “business server,” at many times the consumer price. However, a little research can reveal some attractive solutions. For example, I built a server with 16GB of ECC memory and 18TB (6 x 3TB) of disk storage for about $2500 about a year ago. This is not to totally discredit the business option; the main reason people buy IBM equipment is that it comes with someone that has a big sign around his neck that says: “It was my fault,” and will fix things very quickly when they go wrong. For more on this subject please see: https://en.wikipedia.org/wiki/Soft_error and https://en.wikipedia.org/wiki/ECC_memory 2, Failures of secondary storage. Disks can exhibit similar errors despite the fact that even the cheapest hard drives are protected with an ECC at the sector level. This is a different kind of ECC than that used for primary storage, and it is not uncommon for users to encounter an uncorrectable ECC error from time to time. This is the reason people are told to backup their computers. Occasionally a disk may fail completely so that no part of the disk can be accessed. In some cases the disk can be repaired, but this is far from certain, can take a long time, and be quite expensive. All these problems can be solved by the use of a “Redundant Array of Inexpensive Disks” (or RAID). The simplest of these is called RAID 1, or mirroring, where every disk in the system is paired with another redundant disk that holds an “image copy” so that, if one were to fail, all the missing data could be found on the other. This kind of configuration will obviously double the cost of disk storage, and will also lengthen the time it takes to write to the secondary storage a little. However, this extra time may not be at all significant, because the time it takes to read from this kind of configuration will (in many systems) be faster, making it possible that the server, as a whole, could actually be faster on average (this depends on the average read/write ratio). There are also many other sorts of RAID configurations with various tradeoffs of performance and capacity. The big advantage of RAID is that in a very real sense you are backing up your whole system automatically and in real-time, every time something is updated. This is not to say that it should be seen as a replacement for normal backups, but it provides a good level of security for data that has been changed, but not yet backed up. If, for example, backups are done on a daily basis, this could prevent the loss of an entire day’s work, often for a very small capital cost, and no significant change in performance. For more on this subject please see: https://en.wikipedia.org/wiki/RAID 3, ZFS ZFS is a RAID system I use a lot. It can be found as part of a very solid and well respected server operating system called Solaris. The only big drawback with Solaris is that it requires considerable systems administration training to use, so as I do not have this training (meaning, incidentally, that you should be very cautious of any of my advice!!!) I use ZFS in a much easier system called NAS4Free, which has a simple web browser interface. The main disadvantage of NAS4Free is that it is never going to be as well tested as Solaris, meaning it must be a less-secure system with which to trust your data. I suspect this may not amount to big difference if you do not stray too far from the standard configurations, and I have never seen any critical problems personally. Many people like me use NAS4Free “for free,” but professional support is also an option as I recall. ZFS is nice for many reasons. It is does not have a “traditional” RAID-5 algorithm (with RAID-5 you lose less of your total disk capacity to redundancy). Instead, it uses several very clever ideas that directly address a significant performance issue with writes to RAID-5 arrays. This they call this RAID-Z. In my system I use a variation of this called RAID-Z2, which means (in my case) that two of the six disks are used for redundancy meaning that 2/3rds of my original capacity is useable for user data. The advantage of this configuration is that any two of the six disks can completely and permanently fail, and all the data will still be intact. The disadvantage of RAID-Z2 is that writing a little is slower. Another significant difference with ZFS is that unlike most RAID solutions, ZFS requires no special hardware. Commodity disks and disk controllers work very well, and do not compromise the integrity of the system. This comes with a small performance cost because various RAID functions that are often performed in specialized disk controllers must now be done using the CPU in the server. But as modern CPUs are now so fast, the computational time is small compared to the still very long mechanical latency inherent to all disk operations, so the additional time will often be completely insignificant (this is not true for newer "SSD" type disks, but I digress). What is significant is that it is possible to get ZFS to automatically perform a data integrity test on a regular basis that virtually guarantees that all the data is complete and correct at the systems level (so if an application messes things up---a very different kind or problem---this would not be detected). This is an operation called “scrubbing,” where all the data is read from the disk and checked to be correct using an independent and extra level of error checking. This will prove (to some large sigma) that the data is still as it should be. All the user data checked along with the redundant copies, and if anyting is wrong the data is rewritten (and hence scrubbed). This operation checks that various system componants worked correctly when the data was written. These includes the motherboard, the disk controller, the disks, and to some extent the memory (the undetected EEC error I previously had mentioned). Scrubbing can take a long time (currently, 9 hours on my system) and while this is being done the server’s performance is reduced (so I run it at night). If a failure is detected when scrubbing, then an email is send to the operator (i.e. me) to prompt for some action like loading data from a backup or whatever is needed (I set things up so I that I get the server to send a test email once a day, so that I will notice if this stops working.) Lastly, ZFS can be configured to make what are called “snapshots,” which are frozen versions of the file system taken at various times. I have my system configured to make one snapshot every hour (each of which are deleted after 24 hours), and one per day (each of which are deleted after a month). This pretty much guarantees I cannot ever do something really dumb like accidentally deleting all the files only to find I had lost everything (the worse would be that I would lose all the changes made over the previous hour). It is also very good protection for the very nasty “cryptolocker” type of virus. One can tune these parameters to suit your own needs. ZFS is a remarkably well designed system that I have now used on two different ECC-memory based consumer machines for around ten years. During this time I have never seen a single error or loss of data (that I know of). It should, however, be said that the fact that these systems always run 24/7 (i.e. are not routinely powered down) may be significant in this claim because many computer failures occur when they are powered on or off. 4, Disaster recovery rehearsals. It is not uncommon for people to setup their backup system and not test them to see if they work. The most spectacular example of this I came across was a company that religiously created tape backups of their mainframe computer and stored them offsite (like you should) only to discover (when it was too late) that on the other side of one wall of the tape store room was a large electricity substation, the magnetic flux of which proved more than sufficient to corrupt every tape in the room. So it is obvious to test that data can be restored correctly every so often. Big companies often will do this by forwarding a part of each tape store to a different facility, testing it on a weekly schedule. (This adds further geographical distribution, and tests that the backups can be read on a system that was not identical to those on which they were created.) For a SMB it is probably sufficient to return a backup once every three months or so to see that it can still be read. 5, Other equipment failures. Even when all of the above is done, and the data is safe, it may be important to consider what the effect of each component failing would be. As computer hardware is getting ever cheaper I’m assuming that the cost of replacement is not an issue (get insurance if it is), but the cost is in the downtime when, say, the power supply in the main server fails and the system is thus unusable while it is being repaired. In some cases adding extra levels of hardware redundancy may be worth considering. Although I’ve never done it, I understand that it is not hard to have one ZFS based server configured as a “hot standby”, so that it can take over quickly if the main server fails. (Also all this can also be done “In the cloud,” though we are now going into complex areas where I have no experience.) But hardware redundancy should be considered at all levels, i.e. routers and switches are cheap so having an extra router might be a good idea etc. Other things to consider would be battery based temporary power supplies (a UPS), and an alternative internet connation (which might be as simple as using a mobile phone). 6, Security You may wish to review: 1. That no one can get into your system from the internet. 2. Your virus/malware detection (Google “cryptolocker” if you want to see how nasty things are getting these days) 3. Should your data be encrypted 4. Do you hold credit card information that could be placed on a non-networked computer 5. How sure are you that the medical software you have is not secretly stealing confidential information (unlikely, but exactly the sort of thing a sufficiently disgruntled employee might try) 6. If the building were to be totally destroyed by fire, earthquake, or something like a major aviation accident, you could setup a replacement data system in a short enough time so as not to inconvenience anyone. 7. All data is maintained in accordance to any necessarily regulations. 8. Are your backups encrypted. This is especially important if you use "The Cloud" as your offsite storage. If you do this then a) you must use very strong encryption technology that you control and that they have no knowledge, b) never use any encryption technology you are offered by anyone (including me, your uncle Fred, or your old friend Sam from school) c) that you use at least two and probably better three, different suppliers (and you can prove these are not virtual fronts for one physical provider). so you know that if one were to fold, you could access the same data from the other. Personally, I might go for one copy at home and another in the cloud, or better still find a "data partner" where you keep each other's encrypted backups. In all cases I would seek out the best specialist advice because this is an area where some awful security mistakes are possible. Note also that many people employ computer security specialists to try to hack in to their systems in order to expose weaknesses. This may be worth considering, but you will have to satisfy yourself that they are completely trustworthy. 7, My configuration: * 1 x Supermicro X9SCM-F Server Motherboard - Intel C204 Chipset - Socket H2 LGA-1155 * 1 x Intel Pentium CPU G2120 @ 3.10GHz * 6 x Seagate Barracuda 7200.14 ST3000DM001 * 2 x Kingston 8GB 240-Pin DDR3 SDRAM DDR3 1600 ECC Unbuffered Server Memory w/TS Model KVR16E11/8 * 1 x Fractal Design Define R4 Black Pearl w/ USB 3.0 ATX Mid Tower Silent PC Computer Case * 1 x SeaSonic SSR-360GP 360W ATX12V v2.31 80 PLUS GOLD Certified Active PFC Power Supply (One nice feature of the motherboard is that it can be "headless," i.e. without a keyboard, mouse, or display.)
TypeScript
UTF-8
5,495
2.515625
3
[]
no_license
import { v4 as uuid } from 'uuid'; import { html, render } from 'lit-html'; import { DOTWALLET_API } from '../config'; const engButton = require('../../assets/dotwallet-pay-button-blue-138x48-en.svg'); const zhButton = require('../../assets/dotwallet-paybutton-blue-152x48-zh.svg'); export interface PayOptions { productName: string; orderAmount: number; createOrderEndpoint: string; receiveAddress: string; productDetail?: string; redirectURI?: string; notifyURL?: string; subject?: string; coinType?: string; fetchHeaders?: Record<string, string>; fetchOptions?: RequestInit; log?: boolean; lang?: 'en' | 'zh'; successCallback?: (orderData: any) => any; failureCallback?: (error: any) => any; } const validate = (options: PayOptions): string => { let result = ''; try { if (!options.productName) result += 'Must have productName. \n'; if (!options.orderAmount) result += 'Must have orderAmount. \n'; if (!options.createOrderEndpoint) result += 'Must have createOrderEndpoint. \n'; if (!options.receiveAddress) result += 'Must have receiveAddress. \n'; if (!options.notifyURL && !options.redirectURI) result += 'Must have either notifyURL or redirectURI. \n'; if (options.redirectURI) if ( !options.redirectURI.includes('http://') && !options.redirectURI.includes('https://') ) result += 'Invalid redirect URI. \n'; if (options.notifyURL) if ( !options.notifyURL.includes('http://') && !options.notifyURL.includes('https://') ) result += 'Invalid notifyURL. \n'; if ( !options.createOrderEndpoint.includes('http://') && !options.createOrderEndpoint.includes('https://') ) result += 'Invalid createOrderEndpoint. Please use your backend server endpoint URI. \n'; if (['en', 'zh'].indexOf(options.lang) === -1) result += 'Invalid language option \n'; if (['BSV', 'BTC', 'ETH'].indexOf(options.coinType) === -1) result += 'Invalid cointype option. \n'; if ( 25 > options.receiveAddress.length || options.receiveAddress.length > 36 ) result += 'Invalid address (length not between 25-36 characters). \n'; if (result === '') return 'valid'; else return result; } catch (error) { return JSON.stringify(error); } }; export function pay(elementID: string, options: PayOptions) { if (!options.lang) options.lang = 'en'; if (!options.coinType) options.coinType = 'BSV'; const valid = validate(options); if (valid !== 'valid') { if (options.log) console.log(valid); return; } const template = (buttonID: string, style: string) => html` <button id="dotwallet-pay${buttonID}"></button> <style> ${style} </style> `; const element = document.getElementById(elementID); const buttonID = uuid().slice(0, 10); // style template above does not accept string interpolation with ${ } const style = ` #dotwallet-pay${buttonID} { width: ${options.lang === 'zh' ? '152' : '138'}px; height: 48px; cursor: pointer; box-shadow: 0 0 10px gray; border: none; -webkit-appearance: none; -moz-appearance: none; background: url(${options.lang === 'en' ? engButton : zhButton}); transition: box-shadow 300ms ease-in-out; } #dotwallet-pay${buttonID}:hover { box-shadow: 0 0 10px rgb(40, 40, 40); } #dotwallet-pay${buttonID}:active { opacity: 0.7; }`; const pay = (options: PayOptions) => { const orderData: any = { out_order_id: uuid(), coin_type: options.coinType, to: [ { type: 'address', content: options.receiveAddress, amount: options.orderAmount, }, ], product: { id: uuid(), name: options.productName, detail: options.productDetail, }, }; if (options.notifyURL) orderData.notify_url = options.notifyURL; if (options.redirectURI) orderData.redirect_uri = options.redirectURI; if (options.subject) orderData.subject = options.subject; if (options.log) console.log('order data:\n', orderData); let requestOptions: RequestInit = { method: 'POST', body: JSON.stringify(orderData), }; if (options.fetchHeaders) requestOptions.headers = { ...options.fetchHeaders, }; else { requestOptions.headers = { 'Content-type': 'application/json; charset=UTF-8', }; } if (options.fetchOptions) requestOptions = { ...requestOptions, ...options.fetchOptions }; if (options.log) console.log('fetch options:\n', options); if (options.log) console.log('sending order', { request: requestOptions }); fetch(options.createOrderEndpoint, requestOptions) .then((orderResponse) => orderResponse.json()) .then((orderData) => { if (options.log) console.log('order response data:\n', orderData); if (orderData.order_id) { if (options.log) console.log({ orderData }); window.location.href = `${DOTWALLET_API}transact/order/apply_payment?order_id=${orderData.order_id}`; if (options.successCallback) options.successCallback(orderData); } else { if (options.failureCallback) options.failureCallback(orderData); if (options.log) console.log({ orderData }); } }) .catch((error) => { if (options.failureCallback) options.failureCallback(error); if (options.log) console.error({ error }); }); }; render(template(buttonID, style), element); const button = document.getElementById(`dotwallet-pay${buttonID}`); button.addEventListener('click', () => { try { if (options.log) console.log('pay called with', { options }); pay(options); } catch (error) { console.error({ error }); } }); }
Python
UTF-8
1,293
2.953125
3
[]
no_license
""" Builds a simple convolutional nerual network for MNIST similarity (quadruplet encoder). Output format of the Keras model: Embedding ; Output (Flatten) Needs to be trained with talos. """ import keras from keras.models import Model from keras.models import Sequential from keras.layers import Input, Dense, Dropout, Flatten, Reshape from keras.layers import Concatenate def build_model(input_shape, params): input_layer = Input(shape=input_shape) dense = Flatten()(input_layer) dense = Dense(params['neurons'], activation=params['activation'])(dense) dense = Dropout(params['dropout'])(dense) dense = Dense(params['neurons'], activation=params['activation'])(dense) encoder_output_layer = Dense(params['embeddings'], activation='sigmoid')(dense) decoder_dense = Dense(params['neurons'], activation=params['activation'])(encoder_output_layer) decoder_dense = Dropout(params['dropout'])(decoder_dense) decoder_dense = Dense(params['neurons'], activation=params['activation'])(decoder_dense) decoder_output_layer = Dense(784, activation='sigmoid')(decoder_dense) output_layer = Concatenate()([encoder_output_layer, decoder_output_layer]) model = Model(inputs=input_layer, outputs=output_layer) return model
Java
UTF-8
243
1.515625
2
[ "Apache-2.0" ]
permissive
/** * node è il package che raccoglie tutte le classi utili a definire un nodo nel contesto del dominio applicativo * dei Taxi * @author robertovecchio * @version 1.0 * @since 15/01/2021 * */ package com.robertovecchio.model.graph.node;
Java
UTF-8
1,087
1.914063
2
[]
no_license
package com.example.cities.presentation.cities_search; import androidx.paging.PagedList; import com.example.cities.model.CitiesSearchResultCode; import com.example.cities.model.data.CityData; public interface CitiesSearch { interface Presenter { void onViewReady(); void onSearchTextChanged(String searchText); void onSearchTextSubmitted(String searchText); void onCityClicked(CityData cityData); void onCityInfoClicked(CityData cityData); void onRetryClicked(); void onRequestStarted(); void onResult(CitiesSearchResultCode resultCode); void onAboutAppClicked(); void onDestroyView(); } interface View { void updateCityList(PagedList<CityData> cityList); void clearList(); void setSearchText(String currentSearchText); void showMapWithSelectedCity(); void showCityInfoForSelectedCity(); void showAboutApp(); void showError(); void hideError(); void showProgress(); void hideProgress(); } }
PHP
UTF-8
6,798
2.625
3
[]
no_license
<?php session_start (); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <link rel="stylesheet" type="text/css" href="style.css"> <title></title> </head> <body> <?php if ($_SERVER['REQUEST_METHOD'] == "POST") { // Creating array $_SESSION['users'][] = [ 'radio' => $_POST['radio'], 'name' => $_POST['name'], 'email' => $_POST['email'], 'checkbox' => $_POST['checkbox'], 'phone' => $_POST['phone'], 'city' => $_POST['city'], 'cat' => $_POST['cat'], 'title' => $_POST['title'], 'descr' => $_POST['descr'], 'price' => $_POST['price'], ]; echo '<div class="red">Информация внесена!</div>'; } else { echo '<div class="red">Заполните поля!</div>'; } $cities = [ 'c1' => 'Kiev', 'c2' => 'London', 'c3' => 'New York' ]; $cats = [ 'c1' => 'Black Unicorns', 'c2' => 'White Dragons', 'c3' => 'Abrakadabra' ]; ?> <form action="/dz_6.php" method="post"> <div class="anon"> <input type="radio" name="radio" id="r1" tabindex="2" value="r1" checked="checked"/> <label for="r1">Частное лицо</label> <input type="radio" name="radio" id="r2" tabindex="3" value="r2" /> <label for="r2">Компания</label> </div> <table class="anon"> <tbody> <tr> <td><label for="name">Ваше имя</label></td> <td><input type="text" name="name" id="name" value="" tabindex="1" /></td> </tr> <tr> <td><label for="name">Электронная почта</label></td> <td><input type="email" name="email" id="email" value="" tabindex="2" /></td> </tr> <tr> <td></td> <td> <input type="checkbox" name="checkbox" id="checkbox" /> <label for="checkbox">Я не хочу получать вопросы по объявлению по e-mail</label> </td> </tr> <tr> <td><label for="phone">Номер телефона</label></td> <td><input type="phone" name="phone" id="phone" value="" tabindex="3" /></td> </tr> <tr> <td><label for="city">Город</label></td> <td> <select name="city" id="city"> <?php foreach ($cities as $key => $city) { echo '<option value="'.$key.'">'.$city.'</option>'; } ?> </select> </td> </tr> <tr> <td><label for="cat">Категория</label></td> <td> <select name="cat" id="cat"> <?php foreach ($cats as $key => $cat) { echo '<option value="'.$key.'">'.$cat.'</option>'; } ?> </select> </td> </tr> <tr> <td><label for="title">Название объявления</label></td> <td><input type="text" name="title" id="title" tabindex="4" /></td> </tr> <tr> <td><label for="descr">Описание объявления</label></td> <td><textarea cols="40" rows="8" name="descr" id="descr"></textarea></td> </tr> <tr> <td><label for="price">Цена</label></td> <td><input type="text" name="price" id="price" value="0" tabindex="5" />руб.</td> </tr> <tr> <td></td> <td><input type="submit" value="Отправить" /></td> </tr> </tbody> </table> </form> <table class="tbl_goods"> <thead> <tr> <th>Название объявления</th> <th>Цена</th> <th>Имя</th> <th>Удалить?</th> </tr> </thead> <tbody> <?php if (isset($_SESSION['users'])) { foreach($_SESSION['users'] as $key => $user) { echo ' <tr> <td><a class="ttl" href="/dz_6.php?anon='.$key.'">'.$user['title'].'</a></td> <td>'.$user['price'].'</td> <td>'.$user['name'].'</td> <td><a href="/dz_6.php?id='.$key.'">Удалить</a></td> </tr> '; } } ?> </tbody> </table> <?php if (isset($_GET['id'])) { $id = (int)$_GET['id']; unset($_SESSION['users'][$id]); } if (isset($_GET['anon'])) { $id = (int)$_GET['anon']; $user = $_SESSION['users'][$id]; $user_city = ''; foreach ($cities as $key => $city) { if ($key == $user['city']) { $user_city .= '<option value="'.$key.'" selected="selected">'.$city.'</option>'; } else { $user_city .= '<option value="'.$key.'">'.$city.'</option>'; } } $user_cats = ''; foreach ($cats as $key => $cat) { if ($key == $user['city']) { $user_cats .= '<option value="'.$key.'" selected="selected">'.$cat.'</option>'; } else { $user_cats .= '<option value="'.$key.'">'.$cat.'</option>'; } } if ($user['radio'] == 'r1') { $r1 = 'checked="checked"'; $r2 = ''; } else { $r2 = 'checked="checked"'; $r1 = ''; } if ($user['checkbox'] == 'on') { $chk = 'checked="checked"'; } else { $chk = ''; } echo '<br><br> Here is radio: '.$user['radio'].' <br><br> Here is checkbox: '.$user['checkbox'].' <br><br> <div class="anon"> <input type="radio" name="radio" id="r1" tabindex="2" value="choice-1" '.$r1.' /> <label for="r1">Частное лицо</label> <input type="radio" name="radio" id="r2" tabindex="3" value="choice-2" '.$r2.' /> <label for="r2">Компания</label> </div> <table class="anon"> <tbody> <tr> <td><label for="name">Ваше имя</label></td> <td><input type="text" name="name" id="name" value="'.$user['name'].'" tabindex="1" /></td> </tr> <tr> <td><label for="name">Электронная почта</label></td> <td><input type="email" name="email" id="email" value="'.$user['email'].'" tabindex="2" /></td> </tr> <tr> <td></td> <td> <input type="checkbox" name="checkbox" id="checkbox" '.$chk.' /> <label for="checkbox">Я не хочу получать вопросы по объявлению по e-mail</label> </td> </tr> <tr> <td><label for="phone">Номер телефона</label></td> <td><input type="phone" name="phone" id="phone" value="'.$user['phone'].'" tabindex="3" /></td> </tr> <tr> <td><label for="city">Город</label></td> <td> <select name="city" id="city"> '.$user_city.' </select> </td> </tr> <tr> <td><label for="cat">Категория</label></td> <td> <select name="cat" id="cat"> '.$user_cats.' </select> </td> </tr> <tr> <td><label for="title">Название объявления</label></td> <td><input type="text" name="title" id="title" tabindex="4" value="'.$user['title'].'" /></td> </tr> <tr> <td><label for="descr">Описание объявления</label></td> <td><textarea cols="40" rows="8" name="descr" id="descr">'.$user['descr'].'</textarea></td> </tr> <tr> <td><label for="price">Цена</label></td> <td><input type="text" name="price" id="price" value="'.$user['price'].'" tabindex="5" />руб.</td> </tr> <tr> <td></td> <td><input type="submit" value="Отправить" /></td> </tr> </tbody> </table> '; } ?> </body> </html>
Java
UTF-8
3,737
2.578125
3
[]
no_license
/* * Copyright (c) 2013 NTB Interstate University of Applied Sciences of Technology Buchs. * All rights reserved. * * http://www.ntb.ch/inf * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the project's author nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ package ch.ntb.robotics.controleng.functions; import ch.ntb.robotics.scara.driver.Input; import ch.ntb.robotics.scara.driver.Output; /********************************************************** * File: Integrator.java * Created: 2012-10-07 dfrommelt * Changes: none * ------------------------------------------------------ * Description: * all-purpose integrator block * * +-----------------------+ * | | * >- in out -> * | | * +-----------------------+ * **********************************************************/ public class Integrator { public Input in = new Input(); public Output out; private double lastIn, lastOut; private double k; /*(non-Javadoc) * object constructor *@param Ts * Sampling time, the frequency of calling the run method must fit with this sampling time */ public Integrator(double Ts, double val0) { out = new Output(); out.setValue(val0); lastOut = val0; k = 0.5*Ts; } /*(non-Javadoc) * method for setting the actual value of the integrator *@param val * value to be taken as actual value for the integrator */ public void setValue(double val){ lastOut = val; } /*(non-Javadoc) * running method without using the Input and Output *@param in * value to be integrated *@return * integrated value */ public double getIntegral(double in){ lastOut += (in + lastIn) * k; lastIn = in; return lastOut; } /*(non-Javadoc) * running method -> calculates the integral value from the input and saves it in the output */ public void run() { if(Math.abs(in.getValue())<1000.0){ lastOut += (in.getValue() + lastIn)*k; out.setValue(lastOut); lastIn = in.getValue(); } } }
Markdown
UTF-8
10,370
2.640625
3
[]
no_license
--- layout: post title: "composer使用总结" date: 2017-02-16 11:51:00 categories: php composer excerpt: composer使用总结 --- * content {:toc} ## composer 安装 用法 --- ### 【安装】### 安装 Composer,只需要下载 composer.phar 可执行文件。 wget https://getcomposer.org/download/1.0.0-alpha11/composer.phar 在 https://getcomposer.org/download/ 可以获取不同的版本。 使用: a. php composer.phar -V 查看信息 查看是否安装正确 b. 在需要使用的目录(称root目录)下,创建composer.json文件 c. 执行 php composer.phar install Composer.json含义: 镜像的地址配置: "repositories": { "packagist": { "type": "composer", "url": "https://packagist.phpcomposer.com" } } 要求: "require": { //这里是告诉composer必须要安装的项目,相当于生产环境 "php": ">=5.5.9", "laravel/framework": "5.2.*", //require 需要一个 包名称,这个就是包名称 "laravelcollective/html": "5.2.*", "yuanchao/laravel-5-markdown-editor": "dev-master" }, 开发环境要求: "require-dev": { //这个是开发需要安装的项目,相当于开发环境,可以通过-no-dev来取消安装这个项目里面的包 "fzaninotto/faker": "~1.4", "mockery/mockery": "0.9.*", "phpunit/phpunit": "~4.0", "symfony/css-selector": "2.8.*|3.0.*", "symfony/dom-crawler": "2.8.*|3.0.*" }, 自动加载: composer的自动加载会生产这个文件vendor/autoload.php,然后调用这个文件就能够获得文件里面的类的自动加载 自动加载只支持 PSR-4和 PSR-0两种命名方式 基本用法: a. composer是通过读取composer.json和composer.lock文件来进行安装包的。 b. 在安装依赖后,Composer 将把安装时确切的版本号列表写入 composer.lock 文件。这将锁定改项目的特定版本。因为 install 命令将会检查锁文件是否存在,如果存在,它将下载指定的版本(忽略 composer.json 文件中的定义)。如果不存在 composer.lock 文件,Composer 将读取 composer.json 并创建锁文件。 一般的使用用法有: 1. composer install (install 命令从当前目录读取 composer.json 文件,处理了依赖关系,并把其安装到 vendor 目录下。) 2.composer install XXXX (这是单独安装某些包的时候使用) 3.composer update (为了获取依赖的最新版本,并且升级 composer.lock 文件,) 4.composer update XXX (类似) --prefer-source: 下载包的方式有两种: source 和 dist。对于稳定版本 composer 将默认使用 dist 方式。而 source 表示版本控制源 。如果 --prefer-source 是被启用的,composer 将从 source 安装(如果有的话)。如果想要使用一个 bugfix 到你的项目,这是非常有用的。并且可以直接从本地的版本库直接获取依赖关系。 --prefer-dist: 与 --prefer-source 相反,composer 将尽可能的从 dist 获取,这将大幅度的加快在 build servers 上的安装。这也是一个回避 git 问题的途径,如果你不清楚如何正确的设置。 --dry-run: 如果你只是想演示而并非实际安装一个包,你可以运行 --dry-run 命令,它将模拟安装并显示将会发生什么。 --dev: 安装 require-dev 字段中列出的包(这是一个默认值)。 --no-dev: 跳过 require-dev 字段中列出的包。 --no-scripts: 跳过 composer.json 文件中定义的脚本。 --no-plugins: 关闭 plugins。 --no-progress: 移除进度信息,这可以避免一些不处理换行的终端或脚本出现混乱的显示。 --optimize-autoloader (-o): 转换 PSR-0/4 autoloading 到 classmap 可以获得更快的加载支持。特别是在生产环境下建议这么做,但由于运行需要一些时间,因此并没有作为默认值。 5.composer require(require 命令增加新的依赖包到当前目录的 composer.json 文件中。但并不即可更新) 6.composer dump-autoload(某些情况下你需要更新 autoloader,例如在你的包中加入了一个新的类。) 7. composer show 8. php composer.phar validate 有效性检查 创建项目: • 要创建基于 Composer 的新项目,你可以使用 "create-project" 命令。传递一个包名,它会为你创建项目的目录。你也可以在第三个参数中指定版本号,否则将获取最新的版本。 • 如果该目录目前不存在,则会在安装过程中自动创建。 • php composer.phar create-project doctrine/orm path 2.2.* • 此外,你也可以无需使用这个命令,而是通过现有的 composer.json 文件来启动这个项目。 • 默认情况下,这个命令会在 packagist.org 上查找你指定的包。 • 参数: --repository-url: 提供一个自定义的储存库来搜索包,这将被用来代替 packagist.org。可以是一个指向 composer 资源库的 HTTP URL,或者是指向某个 packages.json 文件的本地路径。 --stability (-s): 资源包的最低稳定版本,默认为 stable。 --prefer-source: 当有可用的包时,从 source 安装。 --prefer-dist: 当有可用的包时,从 dist 安装。 --dev: 安装 require-dev 字段中列出的包。 --no-install: 禁止安装包的依赖。 --no-plugins: 禁用 plugins。 --no-scripts: 禁止在根资源包中定义的脚本执行。 --no-progress: 移除进度信息,这可以避免一些不处理换行的终端或脚本出现混乱的显示。 --keep-vcs: 创建时跳过缺失的 VCS 。如果你在非交互模式下运行创建命令,这将是非常有用的。 --- ### 【脚本】### 一个脚本,在 Composer 中,可以是一个 PHP 回调(定义为静态方法)或任何命令行可执行的命令。 事件名称 Composer 在运行过程中将会触发以下事件: 事件名称 详细说明 pre-install-cmd 在 install 命令执行前触发。 post-install-cmd 在 install 命令执行后触发。 pre-update-cmd 在 update 命令执行前触发。 post-update-cmd 在 update 命令执行后触发。 pre-status-cmd 在 status 命令执行前触发。 post-status-cmd 在 status 命令执行后触发。 pre-package-install 在资源包安装前触发。 post-package-install 在资源包安装后触发。 pre-package-update 在资源包更新前触发。 post-package-update 在资源包更新后触发。 pre-package-uninstall 在资源包被卸载前触发。 post-package-uninstall 在资源包被卸载后触发。 pre-autoload-dump 在自动加载器被转储前触发,无论是 install/update 还是 dump-autoload 命令都会触发。 post-autoload-dump 在自动加载器被转储后触发,无论是 install/update 还是 dump-autoload 命令都会触发。 post-root-package-install 在 create-project 命令期间,根包安装完成后触发。 post-create-project-cmd 在 create-project 命令执行后触发。 • pre-archive-cmd: occurs before the archive command is executed. • post-archive-cmd: occurs after the archive command is executed. *注意:**Composer 不会去执行任何依赖包中定义的 install 或 update 相关脚本。 --- ### 【例子】### { "name": "yiisoft/yii2-app-basic", //包的名称,它包括供应商名称和项目名称,使用 / 分隔 "description": "Yii 2 Basic Project Template", //一个包的简短描述 "keywords": ["yii2", "framework", "basic", "project template"] ,//该包相关的关键词的数组。这些可用于搜索和过滤 "homepage": "http://www.yiiframework.com/", //该项目网站的 URL 地址。 "type": "project", //包的安装类型,project: 表示当前包是一个项目,而不是一个库。 "license": "BSD-3-Clause", //包的许可协议 "support": { //获取项目支持的向相关信息 "issues": "https://github.com/yiisoft/yii2/issues?state=open", "forum": "http://www.yiiframework.com/forum/", "wiki": "http://www.yiiframework.com/wiki/", "irc": "irc://irc.freenode.net/yii", "source": "https://github.com/yiisoft/yii2" }, "minimum-stability": "stable",//定义了通过稳定性过滤包的默认行为。默认为 stable(稳定)。 "require": { //必须的软件包列表,除非这些依赖被满足,否则不会完成安装 "php": ">=5.4.0", "yiisoft/yii2": ">=2.0.5", "yiisoft/yii2-bootstrap": "*", "yiisoft/yii2-swiftmailer": "*" }, "require-dev": { //这个列表是为开发或测试等目的,额外列出的依赖。 "yiisoft/yii2-codeception": "*", "yiisoft/yii2-debug": "*", "yiisoft/yii2-gii": "*", "yiisoft/yii2-faker": "*" }, "config": { //仅用于项目的这一组composer配置 "process-timeout": 1800 //处理进程结束时间,例如:git 克隆的时间。Composer 将放弃超时的任务。如果你的网络缓慢或者正在使用一个巨大的包,你可能要将这个值设置的更高一些。 }, "scripts": { //在安装过程中的各个阶段挂接脚本 "post-create-project-cmd": [ "yii\\composer\\Installer::postCreateProject" ] }, "extra": { //任意的,供 scripts 使用的额外数据 本例中用于生成yii2的主要目录权限和CookieValidationKey "yii\\composer\\Installer::postCreateProject": { "setPermission": [ { "runtime": "0777", "web/assets": "0777", "yii": "0755" } ], "generateCookieValidationKey": [ "config/web.php" ] }, "asset-installer-paths": { "npm-asset-library": "vendor/npm", "bower-asset-library": "vendor/bower" } } } --- ### 【参考】### a. <http://blog.csdn.net/qq_16885135/article/details/52725570> b. <http://docs.phpcomposer.com/00-intro.html> c. <http://docs.phpcomposer.com/articles/scripts.html> d. <https://github.com/5-say/composer-doc-cn>
C
UTF-8
1,070
3.984375
4
[]
no_license
/** STRING4.C **/ # include<stdio.h> # include<malloc.h> void gets1 (char **, int ); void display ( char **, int); void input (char **, int ); /* gets1() function to read a string */ void gets1(char **s, int i ) { int j; char ch; ch = getchar(); while(ch != '\n') { s[i][j] = ch ; ch = getchar(); j++; } s[i][j]='\0'; } /* Output funtion */ void display(char **str, int n) { int i; printf("\nEntered strings are follows"); printf("\n***************************"); for(i = 0 ; i < n; i++ ) { printf("\n %s", str[i]); } printf("\n Press a key"); getchar(); } /* Input function */ void input( char **str, int n) { int i; int size; for ( i = 0 ; i < n ; i++ ) { fflush(stdin); printf("\n Enter Approximate size of string->"); scanf("%d", &size); fflush(stdin); str[i] = (char *) malloc(size); printf("\n Input the string: "); gets1(str,i); } } /* Function main */ void main() { int n; char *str[50]; printf("\n Input number of strings want to process:"); scanf("%d", &n); input(str, n); display(str, n); }
Shell
UTF-8
1,386
3.921875
4
[]
no_license
#!/bin/bash if [[ "$1" == "" || "$2" == "" ]]; then echo "error: You need to put paths of wordpress installation" exit fi SourceDir="$1" DestinationDir="$2" if [ ! -d "$SourceDir" ]; then echo "error: Source path either doesn't exists or it's not a directory" exit elif [ ! -d "$DestinationDir" ]; then echo "error: Destination path either doesn't exists or it's not a directory" exit fi if [ ! -f "$SourceDir/wp-config.php" ]; then echo "error: file not found wp-config.php on Source path" exit elif [ ! -f "$DestinationDir/wp-config.php" ]; then echo "error: file not found wp-config.php on Destination path" exit fi # Get Source database params S_DB_NAME=`cat $SourceDir/wp-config.php | grep DB_NAME | cut -d \' -f 4` S_DB_USER=`cat $SourceDir/wp-config.php | grep DB_USER | cut -d \' -f 4` S_DB_PASS=`cat $SourceDir/wp-config.php | grep DB_PASSWORD | cut -d \' -f 4` # Get Destination database params D_DB_NAME=`cat $DestinationDir/wp-config.php | grep DB_NAME | cut -d \' -f 4` D_DB_USER=`cat $DestinationDir/wp-config.php | grep DB_USER | cut -d \' -f 4` D_DB_PASS=`cat $DestinationDir/wp-config.php | grep DB_PASSWORD | cut -d \' -f 4` php -f SaveDB.php s[]=$S_DB_NAME s[]=$S_DB_USER s[]=$S_DB_PASS s[]=$SourceDir d[]=$D_DB_NAME d[]=$D_DB_USER d[]=$D_DB_PASS d[]=$DestinationDir if [ $? -eq 0 ]; then echo OK else echo FAIL fi
Java
UTF-8
440
2.09375
2
[]
no_license
package com.baidu.location.b; public class a { private String a; private String b; private boolean c; public a(String str, boolean z, String str2) { this.b = str; this.c = z; this.a = str2; } public String a() { return this.b; } public String toString() { return "SDCardInfo [label=" + this.a + ", mountPoint=" + this.b + ", isRemoveable=" + this.c + "]"; } }
Python
UTF-8
662
3.15625
3
[]
no_license
import os import pickle def to_pickel(pickle_name, dataframe, dir="../dataset"): """ save dataframe on pickle format :param dataframe: :param dir: :return: """ os.chdir(dir) pickle.dump(dataframe, open(pickle_name + '.pickle', 'wb')) def file_to_list(filename, dir="../resources"): """ Build list from file, where each row in file is saved as a string in list :param filename: :param dir: :return: list """ os.chdir(dir) vocabulary = [] f = open(filename, "r") lines = f.readlines() for line in lines: vocabulary.append(line.replace("\n", "")) return vocabulary
Java
UTF-8
828
1.976563
2
[]
no_license
package com.hardkernel.odroid.settings.display.position; import android.content.Context; import com.droidlogic.app.DisplayPositionManager; import com.hardkernel.odroid.settings.ConfigEnv; public class DisplayPositionReceiver { private final String TAG = "DisplayPositionReceiver"; public static void onReceive(Context context) { DisplayPositionManager mDisplayPositionManager; mDisplayPositionManager = new DisplayPositionManager (context); if (ConfigEnv.getAdjustScreenWay().equals("zoom")) mDisplayPositionManager.zoomByPercent(ConfigEnv.getDisplayZoomrate()); else { int[] alignment = ConfigEnv.getScreenAlignment(); mDisplayPositionManager.alignBy(alignment[0], alignment[1], alignment[2], alignment[3]); } } }
Java
UTF-8
551
2.4375
2
[ "Apache-2.0" ]
permissive
package edu.gy.personalmanagersystem.pojo; public class Role { private String number; private Integer roleid; public String getNumber() { return number; } public void setNumber(String number) { this.number = number == null ? null : number.trim(); } public Integer getRoleid() { return roleid; } public void setRoleid(Integer roleid) { this.roleid = roleid; } @Override public String toString() { return "[number : "+number+", roleid : "+roleid+"]"; } }
C++
UTF-8
2,111
2.984375
3
[]
no_license
#include<iostream> #include<cstdio> #include<string.h> using namespace std; long p,q,n,t,e,d; void printArray(long *x) { for(int i=0;x[i]!=-1;i++) cout<<"\t"<<x[i]; } /* void printArray(char *x) { int i; for(i=0;x[i]!='\0';i++) cout<<"\t"<<(int)x[i]; cout<<(int)x[i]; } */ long modPow(long x, long n,long mod) { if(x==0) return 0; else if(n==0) return 1; int res=1; for(int i=0;i<n;i++) { res*=x; res%=mod; } return res; } long gcd(int m,int n) { int r; while(n>0) { r=m%n; m=n; n=r; } return m; } void initKeys() { for(int i=2;i<t;i++) { if(gcd(t,i)==1 && i!=p && i!=q) { e=i; break; } } for(int i=1;;i++) { if((i*e)%t==1) { d=i; break; } } } void initialize() { cout<<"\nEnter values for p and q :"; cin>>p>>q; n=p*q; t=(p-1)*(q-1); initKeys(); } long* encrypt(char *msg) { int len=strlen(msg); long *m=new long[len+2]; //strcpy(m,msg[i]); //cout<<"\nin ecrypt(): ";printArray(msg); for(int i=0;i<len;i++) { //m[i]=((long)pow((long)msg[i],e)%n); m[i]=modPow(msg[i],e,n); //cout<<"\ni="<<i<<" msg[i]="<<(long)msg[i]<<" e="<<e<<" n="<<n<<" msg^e="<<(long)pow((long)msg[i],e)<<" m[i]="<<m[i]<<endl; } m[len+1]=-1; //cout<<"\nin ecrypt(): ";printArray(m); return m; } char* decrypt(long *ctext) { int len; for(len=0;ctext[len]!=-1;len++); char *m=new char[len]; //stpcpy(m,msg[i]); //cout<<"\nin decrypt(): ";printArray(ctext); for(int i=0;ctext[i]!=-1;i++) { //m[i]=((long int)pow(ctext[i],d)%n); m[i]=modPow(ctext[i],d,n); //cout<<"\ni="<<i<<" ctext[i]="<<(long)ctext[i]<<" d="<<d<<" n="<<n<<" ctext^d="<<(long)pow((long)ctext[i],d)<<" m[i]="<<m[i]<<endl; } //cout<<"\nin decrypt(): ";printArray(m); return m; } int main() { initialize(); char message[100]; cin>>message; long *encpt=encrypt(message); char *decpt=decrypt(encpt); cout<<"\np="<<p<<" q="<<q<<"\nn="<<n<<" t="<<t<<"\ne="<<e<<" d="<<d<<endl; cout<<"\nMSG: "<<message; //<<"\nInput message: ";printArray(message); cout<<"\nEncrypted: ";printArray(encpt); cout<<"\nDecrypted: "<<(decpt)<<endl; return 0; }
C
UTF-8
886
3.0625
3
[]
no_license
/******************************************************** *temp.h * * SER486 Assignment 4 * Spring 2020 * Written By: Thor Nielsen * Modified By: * * header file for function declarations * declarations: * void temp_init(void) * unsigned int temp_is_data_ready(void) * void temp_start(void) * signed int temp_get(void) */ #ifndef _TEMP_H #define _TEMP_H /* initialize temp - this function must be called once before the serial port can be used. */ void temp_init(void); /* temp ready to read- this function will return a 1 if the temp is ready to * read and 0 if it is not. */ unsigned int temp_is_data_ready(void); /* temp start- this function will start the process of reading registers. */ void temp_start(void); /* temp read- this function will return a signed integer of the * on board temp. */ signed int temp_get(void); #endif /* _TEMP_H */
TypeScript
UTF-8
482
2.609375
3
[]
no_license
// Action queue will be a firestore collection // each action representing a user action export type IDocumentSnapshot<T> = firebase.firestore.DocumentSnapshot<T>; export type IQuerySnapshot<T> = firebase.firestore.QuerySnapshot<T>; export type IUserID = string; export type IDisplayName = string; export interface IUser extends firebase.User { displayName: string; } // type FirebaseGame = { // actions: Action[], // users: Record<userID, true>, // host: userID, // };
C#
UTF-8
2,389
2.734375
3
[]
no_license
namespace Downloader.Core.Tests.Store { using System; using System.Linq; using System.Threading.Tasks; using Core.Store; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class JobStoreTests { private readonly IJobStore _jobStore; public JobStoreTests() { _jobStore = new JobStore(); } [TestMethod] public async Task Save_When_Job_Present_Should_Save() { var job = new Job(); var savedJod = await _jobStore.Save(job); var expetedJob = await _jobStore.Get(savedJod.Id); Assert.AreEqual(savedJod, expetedJob); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task Save_When_Null_Should_Throw_Argument_null_Exception() { await _jobStore.Save(null); } [TestMethod] public async Task Save_Concurrent_Should_Save() { var tasks = Enumerable.Range(0, 50) .Select(x => Task.Run(async () => await _jobStore.Save(new Job()))) .ToList(); var savedJobs = await Task.WhenAll(tasks); foreach (var savedJob in savedJobs) { Assert.AreEqual(savedJob, await _jobStore.Get(savedJob.Id)); } } [TestMethod] public async Task Get_When_Valid_Job_Should_Return() { var savedJob = await _jobStore.Save(new Job()); Assert.AreEqual(savedJob, await _jobStore.Get(savedJob.Id)); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task Get_When_Null_Should_Throw_ArgumentNullException() { await _jobStore.Get(null); } [TestMethod] public async Task Get_Concurrent_Should_Get() { var savedJobs = Enumerable.Range(0, 50) .Select(async x => await _jobStore.Save(new Job())) .Select(t=> t.Result) .ToList(); var getTasks = savedJobs .Select(job => Task.Run(async () => await _jobStore.Get(job.Id))) .ToList(); var getJobs = await Task.WhenAll(getTasks); CollectionAssert.AreEqual(savedJobs, getJobs); } } }
Java
UTF-8
1,108
2.15625
2
[]
no_license
package info.khyh.opengltest; import info.khyh.opengltest.DrawLibrary.DrawMain; import info.khyh.opengltest.Library.GLLoader.GLES; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import android.content.Context; import android.opengl.GLSurfaceView; import android.view.KeyEvent; import android.view.MotionEvent; public class GLRender implements GLSurfaceView.Renderer { private DrawMain d; public GLRender(Context cxt, DrawMain d) { GLES.cxt = cxt; this.d = d; } public boolean OnTouchEvent(MotionEvent e) {return d.OnTouchEvent(e);} public boolean OnKey(int keyCode, KeyEvent event) {return d.OnKey(keyCode, event);} public void onPause() {d.onPause();} public void onResume() {} @Override public void onDrawFrame(GL10 gl) {d.onDrawFrame((GL11)gl);} @Override public void onSurfaceChanged(GL10 gl, int w, int h) {d.OnSurfaceChanged((GL11)gl, w, h);} @Override public void onSurfaceCreated(GL10 gl, EGLConfig eglconfig) {d.onSurfaceCreated((GL11)gl, eglconfig);} }
Java
UTF-8
692
3.6875
4
[]
no_license
import java.util.*; public class Poj1862 { public static void main(String args[]) { Scanner cin = new Scanner(System.in); int n = cin.nextInt(); PriorityQueue<Double> heap = new PriorityQueue<Double>(10, new Comparator<Double>() { @Override public int compare(Double a, Double b) { return a < b ? 1 : -1; } }); for (int i = 0; i < n; i++) { heap.add(Double.valueOf(cin.nextInt())); } while (heap.size() > 1) { double a = heap.poll(); double b = heap.poll(); double c = 2 * Math.sqrt(a * b); heap.add(Double.valueOf(c)); } System.out.printf("%.3f\n", heap.poll()); } }
Java
UTF-8
7,208
3.375
3
[]
no_license
package madeexercises.MultiFormatCalculator.ui.model; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import madeexercises.MultiFormatCalculator.multiformat.*; import madeexercises.MultiFormatCalculator.ui.view.ModelView; /** * Model that holds all the logic for communicating with the Calculator class. */ public class CalculatorModel extends AbstractModel { // Predefined values: private static Map<String, Base> bases = new HashMap<>(); private static Map<String, Format> formats = new HashMap<>(); private static Map<String, Method> operators = new HashMap<>(); private Calculator calc = new Calculator(); private int calcCounter = 0; // Insert predefined values: static { // Bases: bases.put("bin", new BinaryBase()); bases.put("oct", new OctBase()); bases.put("hex", new HexBase()); bases.put("dec", new DecimalBase()); // Formats: formats.put("rat", new RationalFormat()); formats.put("fixed", new FixedPointFormat()); formats.put("float", new FloatingPointFormat()); // Operators: try { // ! - Can be vulnerable when method names are changing, // ! - but will save some code on a later stage at this moment. operators.put("+", Calculator.class.getMethod("add")); operators.put("-", Calculator.class.getMethod("subtract")); operators.put("/", Calculator.class.getMethod("divide")); operators.put("*", Calculator.class.getMethod("multiply")); } catch (NoSuchMethodException e) { e.printStackTrace(); } } /* Methods: */ /** * Adds a view to this model. This view will be invoked when setters of this model are called. * * @param view The view liked to be added to this model * @see ModelView */ public void addView(ModelView view) { if (view != null) { views.add(view); } } /** * Sets a Base for the calculator. The method will check if the given Base's name is valid and will thereby * set it in the calculator * * @param base Name of a Base */ public void setBase(String base) { Base foundBase = bases.get(base); if (foundBase != null) { calc.setBase(foundBase); } updateViews(); } /** * Sets a format for the calculator. This method will check if the given format is valid and will thereby add * it to the Calculator. * * @param format The format's name */ public void setFormat(String format) { Format foundFormat = formats.get(format); if (foundFormat != null) { calc.setFormat(foundFormat); } updateViews(); } /** * Method that is invoking a method that belongs to the given name of a Operator. When a method can be found, * this method will perform the action on the Calculator and will increment the calculation-counter. * * @param operator Name of an operator that the user liked to be invoked. */ public void setOperator(String operator) { Method method = operators.get(operator); if (method != null) { try { method.invoke(calc); calcCounter++; updateViews(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } /** * Sets a given string as a new operand in the calculator. The given String object will be parsed into a * Char array of each digit/letter. After that, the logic will loop through all the entries the ensure that * the given entries fit well in the also given Base object in the Calculator class. * * @param op The operand liked to be added into the Calculator. * @see Calculator * @see Base */ public void setOperand(String op) { try { char[] values = op.toCharArray(); String digits = calc.getBase().getDigits(); try { for (char c : values) { if ((digits.indexOf(c) == -1)) { throw new NumberBaseException(); } } } catch (NumberBaseException e) { e.printStackTrace(); } calc.addOperand(op); updateViews(); } catch (FormatException e) { e.printStackTrace(); } } /** * This method returns a Map containing the key (name of a base) and the * Base object itself. This map contains all the currently available * Base-objects that are supported by the calculator. * * @return map containing all the Base-objects * @see Base */ public Map<String, Base> getBases() { return bases; } /** * This method returns a Map containing the key (name of a format) and the * Format object itself. This map contains all the currently available * Format-objects that are supported by the calculator. * * @return map containing all the Format-objects * @see Format */ public Map<String, Format> getFormats() { return formats; } /** * This method returns a Map containing the key (name of a operator) and the method that * will invoke this action on the calculator. This map contains all the currently available * operators that are supported by the calculator. * <p> * They value of every entry in this Map, can be invoked as an method. * <p> * - Example: * <code> * method.invoke(calc); * </code> * <p> * 'calc' needs to be a already initialised object of Calculator. * * @return map containing all the Base-objects * @see Method * @see Calculator */ public Map<String, Method> getOperators() { return operators; } /** * Returns a String object with all the intresting values from the calculator. * This object is already nicely formatted, so can be used in a GUI. * * @return formatted Calculator-values-String */ public String getValues() { return ("\n[" + calc.getBase().getName() + "," + calc.getFormat().getName() + "," + calc.firstOperand() + ", " + calc.secondOperand() + "]"); } /** * Returns the counter of how many calculations the calculator already has made, according to this model. * * @return calculation-counter */ public int getCalcCounter() { return calcCounter; } /** * Returns the used Calculator object of this model. This Calculator is used to perform all the actions on that * where invoked by the controllers of this model. * * @return Calculator object that is used by this object * @see Calculator */ public Calculator getCalc() { return calc; } }
C++
UTF-8
366
3.125
3
[]
no_license
#include "GradeMap.h" #include <vector> GradeMap::GradeMap() { } char& GradeMap::operator[] (const std::string index) { for (StudentGrade &member : m_map) { if (index == member.studentName ) { return member.grade; } } StudentGrade temp {index, ' '}; m_map.push_back(temp); return m_map.back().grade; }
Python
UTF-8
8,195
2.734375
3
[ "Apache-2.0" ]
permissive
# ------------------------------------------------------------------------------ # Based on: # apex # Copyright (c) NVIDIA # Licence under The BSD 3-Clause "New" or "Revised" License # https://github.com/NVIDIA/apex # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the # following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following # disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided with the distribution. # # 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote # products derived from this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, # INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ------------------------------------------------------------------------------ # Copyright (c) Microsoft # Licensed under the MIT License. # Modified by Bowen Cheng # ------------------------------------------------------------------------------ import torch import torch.nn as nn from torch.autograd import Variable from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors class tofp16(nn.Module): """ Model wrapper that implements:: def forward(self, input): return input.half() """ def __init__(self): super(tofp16, self).__init__() def forward(self, input): return input.half() class tofp32(nn.Module): """ Model wrapper that implements:: def forward(self, input): return input.half() """ def __init__(self): super(tofp32, self).__init__() def forward(self, input): if isinstance(input, list): return list(map(lambda x: x.float(), input)) else: return input.float() def BN_convert_float(module): ''' Designed to work with network_to_half. BatchNorm layers need parameters in single precision. Find all layers and convert them back to float. This can't be done with built in .apply as that function will apply fn to all modules, parameters, and buffers. Thus we wouldn't be able to guard the float conversion based on the module type. ''' if isinstance(module, torch.nn.modules.batchnorm._BatchNorm): module.float() for child in module.children(): BN_convert_float(child) return module def network_to_half(network): """ Convert model to half precision in a batchnorm-safe way. """ return nn.Sequential(tofp16(), BN_convert_float(network.half()), tofp32()) def backwards_debug_hook(grad): raise RuntimeError("master_params recieved a gradient in the backward pass!") def prep_param_lists(model, flat_master=False): """ Creates a list of FP32 master parameters for a given model, as in `Training Neural Networks with Mixed Precision: Real Examples`_. Args: model (torch.nn.Module): Existing Pytorch model flat_master (bool, optional, default=False): Flatten the master parameters into a single tensor, as a performance optimization. Returns: A tuple (``model_params``, ``master_params``). ``model_params`` is a list of the model's parameters for later use with :func:`model_grads_to_master_grads` and :func:`master_params_to_model_params`. ``master_params`` is a list of FP32 master gradients. If ``flat_master=True``, ``master_params`` will be a list with one element. Example:: model_params, master_params = prep_param_lists(model) .. warning:: Currently, if ``flat_master=True``, all the model's parameters must be the same type. If the model has parameters of different types, use ``flat_master=False``, or use :class:`FP16_Optimizer`. .. _`Training Neural Networks with Mixed Precision: Real Examples`: http://on-demand.gputechconf.com/gtc/2018/video/S81012/ """ model_params = [param for param in model.parameters() if param.requires_grad] if flat_master: # Give the user some more useful error messages try: # flatten_dense_tensors returns a contiguous flat array. # http://pytorch.org/docs/master/_modules/torch/_utils.html master_params = _flatten_dense_tensors([param.data for param in model_params]).float() except: print("Error in prep_param_lists: model may contain a mixture of parameters " "of different types. Use flat_master=False, or use F16_Optimizer.") raise master_params = torch.nn.Parameter(master_params) master_params.requires_grad = True # master_params.register_hook(backwards_debug_hook) if master_params.grad is None: master_params.grad = master_params.new(*master_params.size()) return model_params, [master_params] else: master_params = [param.clone().float().detach() for param in model_params] for param in master_params: param.requires_grad = True return model_params, master_params def model_grads_to_master_grads(model_params, master_params, flat_master=False): """ Copy model gradients to master gradients. Args: model_params: List of model parameters created by :func:`prep_param_lists`. master_params: List of FP32 master parameters created by :func:`prep_param_lists`. If ``master_params`` was created with ``flat_master=True``, ``flat_master=True`` should also be supplied to :func:`model_grads_to_master_grads`. """ if flat_master: # The flattening may incur one more deep copy than is necessary. master_params[0].grad.data.copy_( _flatten_dense_tensors([p.grad.data for p in model_params])) else: for model, master in zip(model_params, master_params): if model.grad is not None: if master.grad is None: master.grad = Variable(master.data.new(*master.data.size())) master.grad.data.copy_(model.grad.data) else: master.grad = None def master_params_to_model_params(model_params, master_params, flat_master=False): """ Copy master parameters to model parameters. Args: model_params: List of model parameters created by :func:`prep_param_lists`. master_params: List of FP32 master parameters created by :func:`prep_param_lists`. If ``master_params`` was created with ``flat_master=True``, ``flat_master=True`` should also be supplied to :func:`master_params_to_model_params`. """ if flat_master: for model, master in zip(model_params, _unflatten_dense_tensors(master_params[0].data, model_params)): model.data.copy_(master) else: for model, master in zip(model_params, master_params): model.data.copy_(master.data) # Backward compatibility fixes def to_python_float(t): if hasattr(t, 'item'): return t.item() else: return t[0] TORCH_MAJOR = int(torch.__version__.split('.')[0]) TORCH_MINOR = int(torch.__version__.split('.')[1]) if TORCH_MAJOR == 0 and TORCH_MINOR <= 4: clip_grad_norm = torch.nn.utils.clip_grad_norm else: clip_grad_norm = torch.nn.utils.clip_grad_norm_
Java
UTF-8
510
2.109375
2
[]
no_license
package alokamMTOMClient; /** * Created by IntelliJ IDEA. * User: alokamve * Date: 28 Jul, 2011 * Time: 5:56:34 PM */ import javax.xml.ws.soap.MTOMFeature; public class MTOMClient { public static void main(String[] args) { String FOO = "7777745656"; MtomService service = new MtomService() ; MtomPortType port = service.getMtomPortTypePort(new MTOMFeature()); String result; result = port.echoBinaryAsString(FOO.getBytes()); System.out.println( "Got result: " + result ); } }
Markdown
UTF-8
639
2.703125
3
[]
no_license
Pour jouer à ce jeu, les règles sont simples : - Démarrez une nouvelle partie - Séléctionnez une des trois classes du jeu (Guerrier, Magicien, Paladin) - Entrez dans le donjon et essayez d'atteindre la salle 10 pour défier le titan ! Dans chaque salle : - Vous avez une chance sur deux de rencontrer un ennemi - Vous avez une chance sur deux de trouver un coffre - Vous trouverez entre 2 et 4 portes par salle, qui vous feront soit aller a la salle suivante où alors, la salle d'avant ! En combat : - Vous pouvez soit attaquer (stat. Attaque) soit incanter (stat. Magie) - Si vous avez une arme, les dégats de l'arme s'ajoutent.
Java
UTF-8
1,673
2.09375
2
[]
no_license
package sv.gob.mitur.application.configuration; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; @EnableWebSecurity public class Security extends WebSecurityConfigurerAdapter { @Autowired private UserDetailsService userDetailsService; // Dependency injection @Override protected void configure ( AuthenticationManagerBuilder auth ) throws Exception { auth.userDetailsService( userDetailsService ); } @Override protected void configure ( HttpSecurity http ) throws Exception { http.authorizeRequests() .antMatchers( "/users/**" ).hasAuthority( "ADMINISTRADOR" ) .antMatchers( "/types/**", "/travels/**", "/events/**", "/routes/**", "/locations/**", "/places/**", "/dashboard" ).authenticated() .antMatchers( "/" ).permitAll() .and().formLogin().loginPage( "/login" ).defaultSuccessUrl( "/dashboard" ) .and().csrf().disable(); } /** * Creates a bean with an encoder * @return {@link BCryptPasswordEncoder} */ @Bean public BCryptPasswordEncoder passwordEncoder () { return new BCryptPasswordEncoder(); } }
Python
UTF-8
783
3.9375
4
[ "MIT" ]
permissive
# 题意:一个长度为n-1的递增排序数组中的所有数字都是唯一的,并且每个数字都在范围0~n-1之内。在范围0~n-1内的n个数字中有且只有一个数字不在该数组中,请找出这个数字。 # 题解1: 位运算 # 题解2: 二分法,注意边界条件! class Solution: def missingNumber(self, nums): # 位运算 res = 0 for i in range(len(nums)+1): res ^= i for j in nums: res ^= j return res class Solution_2: def missingNumber(self, nums): # 二分法 l,r,res = 0,len(nums)-1,-1 while l<=r: mid = l + (r-l) // 2 if nums[mid] == mid: l = mid + 1 else: r = mid - 1 return l
Ruby
UTF-8
596
3.015625
3
[]
no_license
#--- # Excerpted from "Programming Ruby", # published by The Pragmatic Bookshelf. # Copyrights apply to this code. It may not be used to create training material, # courses, books, articles, and the like. Contact us if you are in doubt. # We make no guarantees that this code is fit for any purpose. # Visit http://www.pragmaticprogrammer.com/titles/ruby3 for more book information. #--- module Logger def log(msg) STDERR.puts Time.now.strftime("%H:%M:%S: ") + "#{self} (#{msg})" end end class Song include Logger end class Album include Logger end s = Song.new s.log("created")
JavaScript
UTF-8
356
2.65625
3
[]
no_license
var express = require('express'); var app = express(); app.get('/test', function (req, res) { console.log('api called successfully'); res.send("helloworld"); }) var server = app.listen(8000, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) })
C
UTF-8
719
3.59375
4
[]
no_license
#include <stdio.h> int ft_str_is_printable(char *str); int main(void) { char str1[] = " fdhhAAA | /%f1235`"; char str2[] = "ABCDE!á"; char str3[] = "aasr342AA433¬¬¬"; int validate; validate = 0; if (ft_str_is_printable(str1)) { printf ("1ª string has printable chars only : %s\n", str1); validate++; } if (ft_str_is_printable(str2)) { printf ("2ª string has printable chars only: %s\n", str2); validate++; } if (ft_str_is_printable(str3)) { printf ("3ª string has printable chars only: %s\n", str3); validate++; } if (validate == 1) printf ("%d string with printable chars only.\n", validate); else printf ("%d strings with printable chars only.\n", validate); return (0); }
PHP
UTF-8
753
2.71875
3
[]
no_license
<?php namespace netForum\xWeb\Xml\Generated; class GetVersionResponse { /** * @var xWebVersion $GetVersionResult */ protected $GetVersionResult = null; /** * @param xWebVersion $GetVersionResult */ public function __construct($GetVersionResult) { $this->GetVersionResult = $GetVersionResult; } /** * @return xWebVersion */ public function getGetVersionResult() { return $this->GetVersionResult; } /** * @param xWebVersion $GetVersionResult * @return \netForum\xWeb\Xml\Generated\GetVersionResponse */ public function setGetVersionResult($GetVersionResult) { $this->GetVersionResult = $GetVersionResult; return $this; } }
Java
UTF-8
4,590
2.4375
2
[ "Apache-2.0" ]
permissive
package com.seahorse.youliao.controller; import com.itextpdf.text.DocumentException; import com.itextpdf.tool.xml.exceptions.CssResolverException; import com.seahorse.youliao.utils.PDFUtils; import freemarker.template.Configuration; import freemarker.template.Template; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.apache.commons.io.IOUtils; import org.springframework.core.io.ClassPathResource; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.HashMap; import java.util.Map; /** * @description: pdf 预览下载 * @author: Mr.Song * @create: 2020-02-01 19:55 **/ @Api(value = "PdfController", tags = "pdf 预览下载") @RequestMapping("freemarker") @RestController public class PdfController { private static Configuration freemarkerCfg = null; @ApiOperation(value = "预览pdf") @GetMapping(value = "viewPdf") public void viewPdf(HttpServletResponse response) throws DocumentException ,CssResolverException{ //需要填充的数据 Map<String, Object> data = new HashMap<>(16); data.put("name", "李白"); String content = freeMarkerRender(data,"freemarker.ftl"); // 读取pdf readBytePdf(content,response); } @ApiOperation(value = "下载pdf") @GetMapping(value = "printPdf") public void printPdf(HttpServletResponse response) throws DocumentException ,CssResolverException{ //需要填充的数据 Map<String, Object> data = new HashMap<>(16); data.put("name", "张三"); String content = freeMarkerRender(data,"freemarker.ftl"); //下载pdf createPdf(content,response); } /** * freemarker渲染html */ public String freeMarkerRender(Map<String, Object> data, String htmlTmp) { Writer out = new StringWriter(); try { // 获取模板,并设置编码方式 setFreemarkerCfg(); Template template = freemarkerCfg.getTemplate(htmlTmp); //将合并后的数据和模板写入到流中,这里使用的字符流 template.process(data, out); out.flush(); return out.toString(); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException ex) { ex.printStackTrace(); } } return null; } /** * 设置freemarkerCfg */ private void setFreemarkerCfg() { freemarkerCfg = new Configuration(Configuration.VERSION_2_3_25); freemarkerCfg.setDefaultEncoding("UTF-8"); //freemarker的模板目录 try { freemarkerCfg.setDirectoryForTemplateLoading(new ClassPathResource("templates").getFile()); } catch (IOException e) { e.printStackTrace(); } } /** * 读取本地pdf,这里设置的是预览 */ private void createPdf(String content,HttpServletResponse response) throws DocumentException,CssResolverException{ response.reset(); response.setContentType("application/pdf"); try { OutputStream outputStream = response.getOutputStream(); // 强制浏览器下载 response.setHeader("content-disposition", "attachment;filename=" + "html.pdf"); IOUtils.write(PDFUtils.html2pdf(content), outputStream); outputStream.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } /** * 读取本地pdf,这里设置的是预览 */ private void readBytePdf(String content,HttpServletResponse response)throws DocumentException,CssResolverException { response.reset(); response.setContentType("application/pdf"); try { OutputStream outputStream = response.getOutputStream(); IOUtils.write(PDFUtils.html2pdf(content), outputStream); //浏览器预览 response.setHeader("Content-Disposition", "inline; filename= file"); outputStream.flush(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Java
UTF-8
296
1.789063
2
[]
no_license
package org.lxy.demo.mp.sharding.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import org.lxy.demo.mp.sharding.model.table.Book; /** * @author liuxinyi * @date 2019-06-12 */ public interface BookMapper extends BaseMapper<Book> { String queryNameByGuid(String guid); }
Java
UTF-8
5,654
3.3125
3
[]
no_license
package com.company; import java.io.File; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.util.Scanner; public class Pizza extends Product { private String size , name ,description;//big,medium,small public static String newline = System.getProperty("line.separator"); private String[] pArray; public void newPizza() { Scanner in = new Scanner(System.in); System.out.print("Въведете име на пицата:"); name = in.nextLine(); System.out.print("Въведете големина на пицата:"); size = in.nextLine(); System.out.print("Въведете описание на пицата:"); description = in.nextLine(); String[][] pizzaArray; pizzaArray = new String[128][8]; FileManage fM = new FileManage(); pizzaArray = fM.FileRead("pizza.txt"); Product pizza = new Product(); pizza.newOne(); String moneyBought = pizza.getMoneyBought(); String moneySold = pizza.getMoneySold(); String moneyInHand = pizza.getInHand(); int indx = fM.seeLenght(pizzaArray); pizzaArray[indx][0] = String.valueOf(indx + 1) + " " + name + " " + size; pizzaArray[indx][1] = description; pizzaArray[indx][2] = moneyBought; pizzaArray[indx][3] = moneySold; pizzaArray[indx][4] = moneyInHand; indx ++; fM.FileWrite("pizza.txt" , pizzaArray , indx); } public void EditPizza(int number){ String[][] pizzaArray; pizzaArray = new String [128][8]; FileManage fM = new FileManage(); pizzaArray = fM.FileRead("pizza.txt"); System.out.print("За да смените името и големината-въведете 1, за описание-2, за цена на купуване-3, за цена на продажба-4, за наличност-5:"); Scanner in = new Scanner(System.in); short menuChosen = in.nextShort(); Scanner babe = new Scanner(System.in); String changed; double p; switch(menuChosen) { case 1: System.out.print("Въведете номера на пицата, името и големината:"); changed = babe.nextLine(); break; case 2: System.out.print("Въведете описанието на пицата:"); changed = babe.nextLine(); break; case 3: System.out.print("Въведете цената на купуване:"); p = babe.nextDouble(); changed = String.valueOf(p); break; case 4: System.out.print("Въведете цената на продажба;"); p = babe.nextDouble(); changed = String.valueOf(p); break; case 5: System.out.print("Въведете наличност:"); int k = babe.nextInt(); changed = String.valueOf(k); break; default:changed = ""; } pizzaArray[number-1][menuChosen-1] = changed; int indx = fM.seeLenght(pizzaArray); fM.FileWrite("pizza.txt",pizzaArray,indx); } public void buyPizza() { String[][] pizzaArray; pizzaArray = new String[128][8]; FileManage fM = new FileManage(); pizzaArray = fM.FileRead("pizza.txt"); int indx = fM.seeLenght(pizzaArray); for(int i=0;i<indx;i++) for(int j=0;j<5;j++) System.out.println(pizzaArray[i][j]); System.out.print("Въведете номера на пицата, която ще поръчате:"); Scanner in = new Scanner(System.in); int numPizza = in.nextInt(); int nowValue = Integer.valueOf(pizzaArray[numPizza - 1][4]) - 1; pizzaArray[numPizza - 1][4] = String.valueOf(nowValue); fM.FileWrite("pizza.txt",pizzaArray,indx); double win = Double.valueOf(pizzaArray[numPizza - 1][3]) - Double.valueOf(pizzaArray[numPizza - 1][2]); double[] winning; int ind = 0; winning = new double[16]; winning = fM.FileReadMoney(); winning[0] += win; winning[3] += win; fM.FileWriteMoney(winning); } public void Wastage() { System.out.print("Въведете номер на пица:"); Scanner in = new Scanner(System.in); int numberPizza = in.nextInt(); System.out.print("Въведете брой пици фира от този номер:"); int cntPizza = in.nextInt(); double[] winning; int ind = 0; winning = new double[16]; FileManage fM = new FileManage(); winning = fM.FileReadMoney(); String[][] pizzaArray; pizzaArray = new String[128][8]; pizzaArray = fM.FileRead("pizza.txt"); int indx = fM.seeLenght(pizzaArray); int lost = Integer.valueOf(pizzaArray[numberPizza - 1][4])-cntPizza; pizzaArray[numberPizza - 1][4] = String.valueOf(lost); double lose = cntPizza*Double.valueOf(pizzaArray[numberPizza - 1][2]); winning[4] += lose; winning[7] += lose; winning[8] += lose; fM.FileWrite("pizza.txt" , pizzaArray , indx); fM.FileWriteMoney(winning); } }
Python
UTF-8
4,926
2.65625
3
[]
no_license
import requests import csv import json class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata import re value = unicode(value.decode("utf-8")) value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) value = unicode(re.sub('[-\s]+', '-', value)) return str(value) response = requests.get('https://docs.google.com/spreadsheets/export?id=1WJ1c9y8hHECdkVbBYULGR8XWrCv9YRtw2LoCM6LCAew&exportFormat=csv&gid=90145853') response.encoding = 'UTF-8' assert response.status_code == 200, 'failed to download csv file' text_file = open('tmp.csv', 'w') text_file.write(response.content) text_file.close() database = {'sites': {}, 'urls': {}} id = 0 col_nom = 0 col_desc = 1 col_decodex = 2 col_soumission = 3 col_proprietaire1 = 4 col_fortune1 = 5 col_marque1 = 6 col_influence1 = 7 col_proprietaire2 = 8 col_fortune2 = 9 col_marque2 =10 col_influence2 =11 col_proprietaire3 =12 col_fortune3 =13 col_marque3 =14 col_influence3 =15 col_subventions = 16 col_pub = 17 col_sources = 18 col_urls = 19 # colonne de la 1ere url with open('tmp.csv', 'rb') as csvfile: reader = csv.reader(csvfile, delimiter=',', quotechar='"') for row in reader: if len(row) < 4: continue id = id + 1 if id == 1: continue entry = [] note_soumission = -1 node_decodex = -1 try: if row[col_soumission] == '0-inconnu': note_soumission = 0 print bcolors.OKBLUE+"[ inconnu ] "+bcolors.ENDC+" "+row[col_nom] elif row[col_soumission] == '1-soumis-capital': note_soumission = 1 print "soumis au capital pour "+row[col_nom] print bcolors.OKGREEN+"[ capital ] "+bcolors.ENDC+" "+row[col_nom] elif row[col_soumission] == '2-soumis-etat': note_soumission = 2 print bcolors.OKBLUE +"[ etat ] "+bcolors.ENDC+" "+row[col_nom] elif row[col_soumission] == '4-insoumis-independant': note_soumission = 4 print bcolors.OKGREEN+"[ indep ] "+bcolors.ENDC+" "+row[col_nom] elif row[col_soumission] == '5-site-partisan-insoumis': note_soumission = 5 print bcolors.OKGREEN+"[ site fi ] "+bcolors.ENDC+" "+row[col_nom] else: print bcolors.FAIL+"[note fi manquante] "+bcolors.ENDC+" "+row[col_nom]+" (on met 0)" continue except: pass try: note_decodex = int(row[col_decodex]) except: print " "+bcolors.WARNING+" [note decodex manquante] "+bcolors.ENDC+" "+row[col_nom]+" (on met 0)" note_decodex = 0 pass entry.append(note_decodex) # 0 - note originale decodex entry.append(row[col_desc]) # 1 - Description originale entry.append(row[col_nom]) # 2 - Nom entry.append(slugify(row[col_nom])) # 3 - Nom normalise entry.append(note_soumission) # 4 - Notre note entry.append(row[col_pub]) # 5 - Pub ? entry.append(row[col_subventions]) # 6 - subventions entry.append(row[col_sources]) # 7 - Sources entry.append(row[col_proprietaire1]) # 8 entry.append(row[col_fortune1]) # 9 entry.append(row[col_marque1]) # 10 entry.append(row[col_influence1]) # 11 entry.append(row[col_proprietaire2]) # 12 entry.append(row[col_fortune2]) # 13 entry.append(row[col_marque2]) # 14 entry.append(row[col_influence2]) # 15 entry.append(row[col_proprietaire3]) # 16 entry.append(row[col_fortune3]) # 17 entry.append(row[col_marque3]) # 18 entry.append(row[col_influence3]) # 19 database['sites'][id] = entry for i in range(col_urls, len(row)-1): url = row[i] url = url.rstrip('/') url = url.rstrip('\n') url = url.rstrip(' ') if url: database['urls'][url] = id with open('database.json', 'wb') as outfile: json.dump(database, outfile, indent=4)
PHP
UTF-8
4,379
3.125
3
[]
no_license
<?php interface PizzaInterface { public function setMeet($newMeet); public function setCheese($newCheese); public function setExtra($newExtra); } class PizzaMaker implements PizzaInterface { public $meet; public $cheese; public $extra; public $resultingPizzaName; public function __construct($newIngredients) { $this->meet = $newIngredients->getMeet(); $this->cheese = $newIngredients->getCheese(); $this->extra = $newIngredients->getExtra(); $this->resultingPizzaName = $newIngredients->getResultingPizzaName(); } public function setMeet($newMeet) { $this->meet = $newMeet; } public function setCheese($newCheese) { $this->meet = $newMeet; } public function setExtra($newExtra) { $this->extra = $newExtra; } public function printOut() { print 'Pizza name: ' . $this->resultingPizzaName . "\n"; print 'Cheese: ' . (($this->cheese) ? ' yes ' : 'no') . "\n"; print 'Meet: ' . (($this->meet) ? ' yes ' : 'no') . "\n"; print 'Extra: ' . (($this->extra) ? $this->extra : 'no') . "\n"; } } interface PizzaIngredientsInterface { public function getResultingPizzaName(); public function getMeet(); public function getCheese(); public function getExtra(); } class MargheritaPizzaIngredients implements PizzaIngredientsInterface{ private $cheese; private $meet; private $extra; private $resultingPizzaName; public function __construct() { $this->resultingPizzaName = 'Margherita'; $this->cheese = true; $this->meet = true; $this->extra = 'Tomato souce'; } public function getResultingPizzaName() { return $this->resultingPizzaName; } public function getMeet() { return $this->meet; } public function getCheese() { return $this->cheese; } public function getExtra() { return $this->extra; } } class VegetarianPizzaIngredients implements PizzaIngredientsInterface{ private $cheese; private $meet; private $extra; private $resultingPizzaName; public function __construct() { $this->resultingPizzaName = 'Vegetarian'; $this->cheese = true; $this->meet = false; $this->extra = 'Rucola'; } public function getResultingPizzaName() { return $this->resultingPizzaName; } public function getMeet() { return $this->meet; } public function getCheese() { return $this->cheese; } public function getExtra() { return $this->extra; } } interface PizzaFactoryInterface{ public function create($type); } class PizzaFactory implements PizzaFactoryInterface{ public function create($type = null) { switch(strtolower($type)) { case 'vegetarian': return new PizzaMaker(new VegetarianPizzaIngredients()); break; case 'margherita': default: return new PizzaMaker(new MargheritaPizzaIngredients()); break; } } } // use this interpretation where mocking doesn't make sense. class PizzaStaticFactory { /* * @param strint $type * @return PizzaMaker */ public static function create($type = NULL) { switch(strtolower($type)) { case 'vegetarian': return new PizzaMaker(new VegetarianPizzaIngredients()); break; case 'margherita': default: return new PizzaMaker(new MargheritaPizzaIngredients()); break; } } } class FactoryTest extends \PHPunit_Framework_Testcase { private $basePizza; protected function setUp() { $this->basePizza = new PizzaFactory(); } // do this on after each test protected function assertPostConditions() { print "---------------------------------------------------------------- \n"; } public function testVegetarian() { $margherita = $this->basePizza->create('vegetarian'); $margherita->printOut(); } public function testMargherita() { $margherita = $this->basePizza->create('margherita'); $margherita->printOut(); } public function testDefault() { $margherita = $this->basePizza->create(); $margherita->printOut(); } public function testStaticMargherita() { $margherita = PizzaStaticFactory::create('margherita'); $margherita->printOut(); } public function testStaticVegetarian() { $margherita = PizzaStaticFactory::create('vegetarian'); $margherita->printOut(); } }
Markdown
UTF-8
886
3.171875
3
[ "MIT" ]
permissive
Read the following code. ```js var bar = "dance"; function foo() { bar = 10; var innerFoo = function() { var bar = 15; } console.log("2: " + bar); //2: What will bar be on this line? innerFoo(); console.log("3: " + bar); //3: What will bar be on this line? } console.log("1: " + bar); //1: What will bar be on this line? foo(); console.log("4: " + bar); //4: What will bar be on this line? ``` 1. What will be printed out when we first log `bar`(denoted by the `"1: "` prefix)? 2. What will be printed out on the second log of `bar`(denoted by the `"2: "` prefix)? 3. What will be printed out on the third log of `bar`(denoted by the `"3: "` prefix)? 4. What will be printed out on the fourth log of `bar`(denoted by the `"4: "` prefix)? After you've made your logical guesses, download the file `scope2.js` and run it. Were your guesses correct? Why or why not?
PHP
UTF-8
11,100
2.734375
3
[]
no_license
<?php require_once "common.php"; define('MYSQL_ERR_INSERT_','1062'); class MysqlException extends RuntimeException { public $logRefNum; public function __construct($logRefNum) { parent::__construct(); $this->logRefNum = $logRefNum; } } class MysqlQueryOneException extends MysqlException { public $recordCount; public function __construct($logRefNum, $recordCount) { parent::__construct($logRefNum); $this->recordCount = $recordCount; } } function MysqlArrayToWhere($conditions) { $count = count($conditions); if($count <= 0) {return '';} else {return ' WHERE '.implode(' AND ',$conditions);} } // // call: MysqlInit(); // throws MysqlException (error is logged in the function) // $mysqlException->logRegNum is the log reference number // function MysqlInit() { $mysql = mysql_connect('localhost', 'tank'); if($mysql === FALSE) { $logRefNum = error_log_with_ref('mysql_connect failed: '. mysql_error()); throw new MysqlException($logRefNum); } if(!mysql_select_db('tank')) { $logRefNum = error_log_with_ref('mysql_select_db(\'tank\') failed: '. mysql_error()); mysql_close($mysql); throw new MysqlException($logRefNum); } } // call: $result = MysqlQuery('query...'); // throws MysqlException on error function MysqlQuery($query) { $result = mysql_query($query); if($result === FALSE) { $logRefNum = code_error_with_ref(__FILE__,__LINE__,"MysqlQuery('$query') failed: ".mysql_error()); throw new MysqlException($logRefNum); } return $result; } // call: $count = MysqlCount($result); // throws MysqlException on error function MysqlCount($result) { $count = mysql_num_rows($result); if($count === FALSE) { $logRefNum = code_error_with_ref(__FILE__,__LINE__,"MysqlCount('$result') failed: ".mysql_error()); throw new MysqlException($logRefNum); } return $count; } function MysqlOneRow($query) { $result = mysql_query($query); if($result === FALSE) { $logRefNum = code_error_with_ref(__FILE__,__LINE__,"MysqlOneRow('$query') failed: ".mysql_error()); throw new MysqlException($logRefNum); } $count = mysql_num_rows($result); if($count === FALSE) { $logRefNum = code_error_with_ref(__FILE__,__LINE__,"mysql_num_rows after query '$query' failed: ".mysql_error()); throw new MysqlException($logRefNum); } if($count == 1) return mysql_fetch_row($result); $logRefNum = code_error_with_ref(__FILE__,__LINE__,"mysql_num_rows after query '$query' failed: ".mysql_error()); throw new MysqlQueryOneException($logRefNum, $count); } // if query does not return exactly one entry // then an exception is thrown // NOTE: you should probably only call this if you know for sure that mysql not returning // a single row is a bug in your code. If the condiitons depend on the client data you should // just use MysqlQueryOne instead and return a custom error if 1 row isn't returned function MysqlOne($query) { $row = MysqlOneRow($query); return $row[0]; } // $result = MysqlQueryOne('query'); // if($result === 0) { // query returned no records // } else { // array of columns // } function MysqlQueryOne($query) { $result = mysql_query($query); if($result === FALSE) { $logRefNum = code_error_with_ref(__FILE__,__LINE__,"MysqlQueryOne('$query') failed: ".mysql_error()); throw new MysqlException($logRefNum); } $count = mysql_num_rows($result); if($count === FALSE) { $logRefNum = code_error_with_ref(__FILE__,__LINE__,"mysql_num_rows after query '$query' failed: ".mysql_error()); throw new MysqlException($logRefNum); } if($count == 1) return mysql_fetch_row($result); if($count == 0) return 0; $logRefNum = code_error_with_ref(__FILE__,__LINE__,"mysql_num_rows after query '$query' failed: ".mysql_error()); throw new MysqlQueryOneException($logRefNum, $count); } // call: $count = MysqlRecordCount($table,$conditions); function MysqlRecordCount($table, $conditions = NULL) { if($conditions != NULl) { $conditions = " WHERE $conditions"; } // Check Email/Regcode combination $result = MysqlQueryOne("SELECT Count(*) FROM $table $conditions;"); if($result === 0) { $logRefNum = code_error_with_ref(__FILE__,__LINE__,"MysqlRecordCount($table, $conditions) expected to have 1 row but have ".$count); throw new MysqlException($logRefNum); } return $result[0]; } // call: MysqlIPLoginSession(); // list($ip,$genTime,$lastRequest,$logins) = MysqlIPLoginSession(); // throws RuntimeException, MysqlException (or MysqlQueryOneException) on error function MysqlIPLoginSession() { if(!isset($_SERVER["REMOTE_ADDR"])) throw new RuntimeException("Missing \$_SERVER['REMOTE_ADDR']"); $ip = ip2long($_SERVER["REMOTE_ADDR"]); if($ip === FALSE) throw new RuntimeException("The \$_SERVER['REMOTE_ADDR'] variable should be an ip address but it is '".$_SERVER["REMOTE_ADDR"]."'"); $result = MysqlQueryOne("SELECT * FROM IPSessions WHERE ip=$ip"); if($result === 0) { MysqlQuery("INSERT INTO IPSessions VALUES ('$ip',NOW(),NOW(),0);"); $result = MysqlQueryOne("SELECT * FROM IPSessions WHERE ip=$ip"); if($result === 0) { $logRefNum = code_error_with_ref(__FILE__,__LINE__,"created a new ipsession entry, and then failed to retrieve it"); throw new MysqlException($logRefNum); } return $result; } // update last request time MysqlQuery("UPDATE IPSessions SET lastRequest=NOW() WHERE ip=$ip;"); return $result; } // throws MysqlException on error function MysqlNewSession($ip,$uid) { // check if user already has a session $result = MysqlQueryOne("SELECT Sid,GenTime FROM Sessions WHERE Uid=$uid;"); if($result === 0) { $sid = ''; for($i = 0; $i < 5; $i++) { $sid = sha1($sid.rand()); } if(isset($_SERVER["REMOTE_ADDR"])) { $sid = sha1($sid.$_SERVER["REMOTE_ADDR"]); } if(isset($_SERVER["REMOTE_PORT"])) { $sid = sha1($sid.$_SERVER["REMOTE_PORT"]); } MysqlQuery("INSERT INTO Sessions VALUES('$sid',NOW(),$uid,NOW(),$ip);"); } else { list($sid,$genTime) = $result; // TODO: if genTime is too far in the past, then create a new sid (to help prevent hackers // from using sids that have been found) MysqlQuery("UPDATE Sessions SET LastRequest=NOW() WHERE Uid=$uid;"); } setcookie("Sid",$sid); } // call: $result = MysqlSession(); // if($result === 0) { session not found } // list($sid,$genTime,$uid,$lastRequest,$ip) = $result; // throws: MysqlException (or MysqlQueryOneException) on error function MysqlSession() { if(!isset($_COOKIE["Sid"])) return 0; $sid = $_COOKIE["Sid"]; return MysqlQueryOne("SELECT * FROM Sessions WHERE sid='".$sid."';"); } // // call: list($uid,$fname,$lname) = MysqlEmailLookup($email); // if(!$uid) { error } // function MysqlEmailLookup($email) { // Check Email/Regcode combination $result = mysql_query('SELECT uid,fname,lname FROM Users WHERE email="'.$email.'";'); if(!$result) { code_error(__FILE__,__LINE__,'MysqlEmailLookup('.$email.') mysql_query failed: '. mysql_error()); return null; } $count = mysql_num_rows($result); if($count === FALSE) { code_error(__FILE__,__LINE__,'MysqlEmailLookup('.$email.') mysql_num_rows failed returned null'); return null; } if($count == 1) return mysql_fetch_row($result); if($count != 0) { code_error(__FILE__,__LINE__,'MysqlUidLookup('.$uid.') expected mysql_num_rows to return 1 but returned '.$count); } return null; } // // call: list($isadmin,$email,$fname,$lname) = MysqlUidLookup($uid); // if(!$email) { then user not found } // function MysqlUidLookup($uid) { // Check Email/Regcode combination $result = mysql_query('SELECT isadmin,email,fname,lname FROM Users WHERE uid="'.$uid.'";'); if($result === FALSE) { code_error(__FILE__,__LINE__,'MysqlUidLookup('.$uid.') mysql_query failed: '. mysql_error()); return null; } $count = mysql_num_rows($result); if($count === FALSE) { code_error(__FILE__,__LINE__,'MysqlUidLookup('.$uid.') mysql_num_rows failed returned null'); return null; } if($count == 1) return mysql_fetch_row($result); if($count != 0) { code_error(__FILE__,__LINE__,'MysqlUidLookup('.$uid.') expected mysql_num_rows to return 1 but returned '.$count); } return null; } // call: list($groupName) = MysqlUidLookup($uid); // if(!$groupName) { then group not found } function MysqlGidLookup($gid) { $result = mysql_query('SELECT name FROM groups WHERE gid="'.$gid.'";'); if($result === FALSE) { code_error(__FILE__,__LINE__,'MysqlGidLookup('.$gid.') mysql_query failed: '. mysql_error()); return null; } $count = mysql_num_rows($result); if($count === FALSE) { code_error(__FILE__,__LINE__,'MysqlGidLookup('.$gid.') mysql_num_rows failed returned null'); return null; } if($count == 1) return mysql_fetch_row($result); if($count != 0) { code_error(__FILE__,__LINE__,'MysqlGidLookup('.$gid.') expected mysql_num_rows to return 1 (or even 0) but returned '.$count); } return null; } // return NULL on error and TRUE/FALSE otherwise function MysqlTableExists($table) { $result = mysql_query("SELECT count(*) FROM information_schema.tables where table_name='".$table."';"); if($result === FALSE) { code_error(__FILE__,__LINE__,"MysqlTableExists(".$table.") mysql_query returned FALSE: ".mysql_error()); return null; } $row = mysql_fetch_row($result); if($row === FALSE) { code_error(__FILE__,__LINE__,"MysqlTableExists(".$table.") mysql_fetch_row returned FALSE: ".mysql_error()); return null; } if($row[0] == 1) return TRUE; if($row[0] == 0) return FALSE; code_error(__FILE__,__LINE__,"MysqlTableExists(".$table.") mysql_fetch_row, expected first element to be 0 or 1 but was ".$row[0]); return null; } // call: $dataColumns = MysqlGetGroupDataColumns($gid); // foreach($dataColumns as $column) { // list($columnName,$columnType,$columnNullable,$columnDefault) = $column; // // ... // } function MysqlGetGroupDataColumns($gid) { // Print Data Columns $result = MysqlQuery("SELECT column_name,column_type,is_nullable,column_default FROM information_schema.columns WHERE table_name='group{$gid}data';"); $dataColumns = array(); while(TRUE) { $row = mysql_fetch_row($result); if(!$row) return $dataColumns; array_push($dataColumns, $row); } } // returns error if length of $keys is invalid function MysqlPrintResultAsJsonObjects($result, $keys) { echo '['; $atFirst = TRUE; while(TRUE) { $row = mysql_fetch_row($result); if(!$row) break; if($atFirst) { $atFirst = FALSE; } else { echo ','; } echo json_encode(array_combine($keys,$row)); } echo ']'; } function MysqlPrintResultAsJsonArrays($result) { echo '['; $row = mysql_fetch_row($result); if($row) { echo json_encode($row); while(TRUE) { $row = mysql_fetch_row($result); if(!$row) break; echo ','; echo json_encode($row); } } echo ']'; } ?>
Markdown
UTF-8
10,948
2.890625
3
[]
no_license
# Project 3: Create a Data Warehouse with AWS Redshift ## Summary * [Introduction](#Introduction) * [Data Warehouse Schema Definition](#Data-Warehouse-Schema-Definition) * [ETL Process](#ETL-Process) * [Project Structure](#Project-Structure) * [How To Run](#How-to-Run) -------------------------------------------- ### Introduction A music streaming startup, Sparkify, has grown their user base and song database and want to move their processes and data onto the cloud. Their data resides in S3, in a directory of JSON logs on user activity on the app, as well as a directory with JSON metadata on the songs in their app. As their data engineer, you are tasked with building an ETL pipeline that extracts their data from S3, stages them in Redshift, and transforms data into a set of dimensional tables for their analytics team to continue finding insights in what songs their users are listening to. You'll be able to test your database and ETL pipeline by running queries given to you by the analytics team from Sparkify and compare your results with their expected results In this project we are going to use two Amazon Web Services resources: * [S3](https://aws.amazon.com/en/s3/) * [AWS Redshift](https://aws.amazon.com/en/redshift/) The data sources to ingest into data warehouse are provided by two public S3 buckets: 1. Songs bucket (s3://udacity-dend/song_data), contains info about songs and artists. All files are in the same directory. 2. Event bucket (s3://udacity-dend/log_data), contains info about actions done by users, what song are listening, ... We have differents directories so we need a descriptor file (also a JSON) in order to extract data from the folders by path. We used a descriptor file (s3://udacity-dend/log_json_path.json) because we don't have a common prefix on folders The objects contained in both buckets are JSON files. The song bucket has all the files under the same directory but <br> the event ones don't, so we need a descriptor file (also a JSON) in order to extract data from the folders by path. We used a descriptor file because we don't have a common prefix on folders We need to ingest this data into AWS Redshift using COPY command. This command get JSON files from buckets and copy them into staging tables inside AWS Redshift. <b>Log Dataset structure:</b> ~~~~ {"artist":"Pavement", "auth":"Logged In", "firstName":"Sylvie", "gender", "F", "itemInSession":0, "lastName":"Cruz", "length":99.16036, "level":"free", "location":"Klamath Falls, OR", "method":"PUT", "page":"NextSong", "registration":"1.541078e+12", "sessionId":345, "song":"Mercy:The Laundromat", "status":200, "ts":1541990258796, "userAgent":"Mozilla/5.0(Macintosh; Intel Mac OS X 10_9_4...)", "userId":10} ~~~~ <b>Song dataset structure:</b> ~~~~ {"num_songs": 1, "artist_id": "ARJIE2Y1187B994AB7", "artist_latitude": null, "artist_longitude": null , "artist_location": "", "artist_name": "Line Renaud", "song_id": "SOUPIRU12A6D4FA1E1", "title": "Der Kleine Dompfaff", "duration": 152.92036, "year": 0} ~~~~ -------------------------------------------- ### Data Warehouse Schema Definition This is the schema of the database #### Staging tables ##### TABLE staging_songs | COLUMN | TYPE | FEATURES | | ------ | ---- | ------- | |num_songs| int| | |artist_id| varchar| | |artist_latitude | float | | |artist_longitude| float| | |artist_location| varchar| | |artist_name | varchar | | |song_id| varchar| | |title| varchar| | |duration | float | | |year | int | | ##### TABLE staging_events | COLUMN | TYPE | FEATURES | | ------ | ---- | ------- | |artist| varchar| | |auth| varchar| | |firstName | varchar | | |gender| varchar| | |itemInSession | int| | |lastName | varchar | | |length| decimal| | |level| varchar| | |location | varchar| | |method | varchar| | |page | varchar | | |registration| varchar| | |sessionId| int| | |song | varchar| | |status| int| | |ts| timestamp| | |userAgent| varchar| | |userId| int| | #### Dimension tables ##### TABLE users | COLUMN | TYPE | FEATURES | | ------ | ---- | ------- | |user_id| int| not null | SORTKEY , PRIMARY KEY, | |first_name| varchar| | |last_name | varchar | | |gender| varchar| | |level| varchar| | ##### TABLE songs | COLUMN | TYPE | FEATURES | | ------ | ---- | ------- | |song_id| varchar| not null |SORTKEY , PRIMARY KEY | |title| varchar| NOT NULL | |artist_id | varchar | NOT NULL| |duration| decimal| | ##### TABLE artists | COLUMN | TYPE | FEATURES | | ------ | ---- | ------- | |artist_id| varchar| not null |sortkey, PRIMARY KEY | |name| varchar| NOT NULL | |location | varchar | | |latitude| decimal| | |logitude| decimal| | ##### TABLE time | COLUMN | TYPE | FEATURES | | ------ | ---- | ------- | |start_time| timestamp| SORTKEY , PRIMARY KEY | |hour| int| | |day| int| | |week| int| | |month| int| | |year| int| | |weekday| int| | #### Fact table ##### TABLE songplays | COLUMN | TYPE | FEATURES | | ------ | ---- | ------- | |songplay_id| int| IDENTITY (0,1), PRIMARY KEY | |start_time| timestamp| NOT NULL SORTKEY DISTKEY| |user_id | int | users(user_id) distkey| |level| varchar| | |song_id| varchar| songs(song_id)| |artist_id | varchar | artists(artist_id)| |session_id| int| NOT NULL| |location| varchar| | |user_agent| varchar| | -------------------------------------------- ### ETL Process All the transformations logic (ETL) is done in SQL inside Redshift. There are 2 main steps: 1. Ingest data from s3 public buckets into staging tables: 2. Insert record into a star schema from staging tables #### Insert data into staging tables <b>Insert into staging events:</b> ~~~~ staging_events_copy = (""" COPY staging_events FROM {} iam_role {} region {} FORMAT AS JSON {} timeformat 'epochmillisecs' TRUNCATECOLUMNS BLANKSASNULL EMPTYASNULL; """).format(LOG_DATA, ARN, REGION, LOG_JSON_PATH) ~~~~ <b>Insert into staging songs:</b> ~~~~ staging_songs_copy = (""" COPY staging_songs FROM {} iam_role {} region {} FORMAT AS JSON 'auto' TRUNCATECOLUMNS BLANKSASNULL EMPTYASNULL; """).format(SONG_DATA, ARN, REGION) ~~~~ #### Insert data into star schema from staging tables <b>Insert Dimensions:</b> ~~~~ user_table_insert = (""" INSERT INTO users (user_id, first_name, last_name, gender, level) SELECT DISTINCT se.userId, se.firstName, se.lastName, se.gender, se.level FROM staging_events se WHERE se.userId IS NOT NULL; """) song_table_insert = (""" INSERT INTO songs (song_id, title, artist_id, year, duration) SELECT DISTINCT ss.song_id, ss.title, ss.artist_id, ss.year, ss.duration FROM staging_songs ss WHERE ss.song_id IS NOT NULL; """) artist_table_insert = (""" INSERT INTO artists (artist_id, name, location, latitude, logitude) SELECT DISTINCT ss.artist_id, ss.artist_name, ss.artist_location, ss.artist_latitude, ss.artist_longitude FROM staging_songs ss WHERE ss.artist_id IS NOT NULL; """) time_table_insert = (""" INSERT INTO time (start_time, hour, day, week, month, year, weekday) SELECT DISTINCT se.ts, EXTRACT(hour from se.ts), EXTRACT(day from se.ts), EXTRACT(week from se.ts), EXTRACT(month from se.ts), EXTRACT(year from se.ts), EXTRACT(weekday from se.ts) FROM staging_events se WHERE se.page = 'NextSong'; """) ~~~~ <b>Insert Facts table:</b> ~~~~ songplay_table_insert = (""" INSERT INTO songplays (start_time, user_id, level, song_id, artist_id, session_id, location, user_agent) SELECT DISTINCT se.ts, se.userId, se.level, ss.song_id, ss.artist_id, se.sessionId, se.location, se.userAgent FROM staging_events se INNER JOIN staging_songs ss ON se.song = ss.title AND se.artist = ss.artist_name WHERE se.page = 'NextSong'; """) ~~~~ -------------------------------------------- ### Project Structure The structure is: * <b> create_tables.py </b> - This script will drop old tables (if exist) ad re-create new tables * <b> etl.py </b> - This script orchestrate ETL. * <b> sql_queries.py </b> - This is the ETL. All the transformatios in SQL are done here. * <b> analytics.py </b> runs a few queries on the created star schema to validate that the project has been completed successfully. * <b> create_cluster.py </b> is where the AWS components for this project are created programmatically * <b> dwh.cfg </b> - configuration files to set all predefined parameters, including RedShift cluster information and s3 bucket location, the credentials an information about AWS resources named ### How to Run 1. To run this project you will need to fill the following information, in *dwh.cfg* in the project root folder. ``` [CLUSTER] HOST='' DB_NAME='' DB_USER='' DB_PASSWORD='' DB_PORT=5439 [IAM_ROLE] ARN= [S3] LOG_DATA='s3://udacity-dend/log_data' LOG_JSONPATH='s3://udacity-dend/log_json_path.json' SONG_DATA='s3://udacity-dend/song_data' [AWS] KEY= SECRET= [DWH] DWH_CLUSTER_TYPE = multi-node DWH_NUM_NODES = 4 DWH_NODE_TYPE = dc2.large DWH_CLUSTER_IDENTIFIER = DWH_DB = DWH_DB_USER = DWH_DB_PASSWORD = DWH_PORT = 5439 DWH_IAM_ROLE_NAME = ``` 2. Run the *create_cluster* script to set up the needed infrastructure for this project. This will create the cluster for the following steps. Keep cluster_node and IAM_ROLE_ARN `$ python create_cluster.py` 3. modify dwh.cfg file, and put host name and IAM_ROLE_ARN value with the cluster in step 2. 4 .Run the *create_tables* script to set up the database staging and analytical tables `$ python create_tables.py` 5. Finally, run the *etl* script to extract data from the files in S3, stage it in redshift, and finally store it in the dimensional tables. `$ python create_tables.py` 6. (Optional), run "analytics" script to get the count for each table in RedShift cluster . `$ python analytics.py` #### Queries and Results Number of rows in each table: | Table | rows | |--- | --: | | staging_events | 8056 | | staging_songs | 14896 | | artists | 10025 | | songplays | 333 | | songs | 14896 | | time | 8023 | | users | 105 |
C++
UTF-8
3,655
2.796875
3
[ "MIT" ]
permissive
#include "CommandAttack.h" #include "ComponentHealth.h" #include "ComponentLocation.h" #include "ComponentRegistry.h" #include "Constants.h" #include "Direction.h" #include "Game.h" #include "Point.h" #include <vector> CommandAttack::CommandAttack ( std::optional<int> characterId) : mCharacterId(characterId) { } std::unique_ptr<Command> CommandAttack::tryCreate ( std::string const & inputString) { if (inputString.empty() || inputString.size() > 2) { return nullptr; } std::optional<int> characterId; if (inputString.size() == 2) { if (inputString[0] < '1' || inputString[0] > '9') { return nullptr; } if (inputString[1] != 'X') { return nullptr; } characterId = std::stoi(std::string(1, inputString[0])); } else { if (inputString[0] != 'X') { return nullptr; } } return std::unique_ptr<Command>( new CommandAttack(characterId)); } std::vector<Point2i> attackLocations ( Point2i const & location, Direction direction) { std::vector<Point2i> result; switch (direction) { case Direction::North: result.push_back({ location.x - 1, location.y - 1}); result.push_back({ location.x, location.y - 1}); result.push_back({ location.x + 1, location.y - 1}); break; case Direction::South: result.push_back({ location.x - 1, location.y + 1}); result.push_back({ location.x, location.y + 1}); result.push_back({ location.x + 1, location.y + 1}); break; case Direction::West: result.push_back({ location.x - 1, location.y - 1}); result.push_back({ location.x - 1, location.y}); result.push_back({ location.x - 1, location.y + 1}); break; case Direction::East: result.push_back({ location.x + 1, location.y - 1}); result.push_back({ location.x + 1, location.y}); result.push_back({ location.x + 1, location.y + 1}); break; default: break; } return result; } GameState::StateAction CommandAttack::execute (Game * game) const { std::optional<int> characterId = mCharacterId ? mCharacterId : game->defaultCharacterId(); if (!characterId) { return GameState::Keep {}; } auto character = game->findItem(characterId.value()); if (character == nullptr) { return GameState::Keep {}; } auto location = ComponentRegistry::find<ComponentLocation>(); auto attacks = attackLocations( location->location(character), location->direction(character)); auto health = ComponentRegistry::find<ComponentHealth>(); for (auto item: game->findItems(TAGS::NPC)) { for (auto const & attack: attacks) { if (location->location(item) == attack) { if (game->randomPercent() > 80) { continue; } int damage = 4; health->setHealth(item, -damage, true); //creature.setAttackerId(characterId); game->addEvent(GameItemDamaged { item->instanceId(), damage}); } } } return GameState::Keep {}; }
JavaScript
UTF-8
762
2.78125
3
[]
no_license
var fs=require('fs'); function fetchAndCount(dirPath){ var countJs=0; var countTxt=0; var count=0; var totalCount=0; return new Promise((res,rej)=>{ fs.readdir(dirPath,(err,files)=>{ if(err){ rej("Error occured while reading directory"); } else{ var filesObj={}; //var totalCount=0; for(var i=0;i<files.length;i++){ var fileName=files[i]; totalCount=totalCount+1; var fileNameArray=fileName.split("."); var extension=fileNameArray[1]; if(String(extension)==='js'){ countJs=countJs+1; } else if(String(extension)==='txt'){ countTxt=countTxt+1; } } count=totalCount-countJs-countTxt; filesObj.countJs=countJs; filesObj.countTxt=countTxt; filesObj.count=count; filesObj.files=files; res(filesObj); } }); }); } module.exports=fetchAndCount;
C#
UTF-8
1,568
2.796875
3
[]
no_license
using MongoDB.Driver; using MongoDB.Driver.Linq; using PrisonersDilemma.Core.Helpers; using PrisonersDilemma.Core.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace PrisonersDilemma.Core.Repositories { public class StrategyRepository : IStrategyRepository { private readonly IMongoCollection<Strategy> _strategies; public StrategyRepository(IConnectionStringProvider connectionStringProvider) { var client = new MongoClient(connectionStringProvider.GetConnectionString()); var database = client.GetDatabase(connectionStringProvider.GetDatabase()); _strategies = database.GetCollection<Strategy>(connectionStringProvider.GetStrategyCollectionName()); } public async Task<string> AddAsync(Strategy strategy) { await _strategies.InsertOneAsync(strategy); return strategy.Id; } public async Task<List<Strategy>> GetAll() => await _strategies.AsQueryable().ToListAsync(); public async Task<Strategy> GetAsync(string id) => await _strategies.AsQueryable().FirstOrDefaultAsync(s => s.Id == id); public async Task<List<Strategy>> GetAsync(List<string> idList) => await _strategies.AsQueryable().Where(s => idList.Contains(s.Id)).ToListAsync(); public async Task<Strategy> GetByNameAsync(string strategyName) => await _strategies.AsQueryable().FirstOrDefaultAsync(s => s.Name == strategyName);//TODO:removable - only for testing } }
PHP
UTF-8
261
2.515625
3
[]
no_license
<?php namespace gossi\webform\validation; interface IValidatable { public function addTest(AbstractTest $test); public function removeTest(AbstractTest $test); public function addError($message); public function hasErrors(); public function getErrors(); }
Markdown
UTF-8
1,296
3.15625
3
[]
no_license
# [SCUFFLE](https://scuffle.online) <img src="http://heroku-badge.herokuapp.com/?app=angularjs-crypto&style=flat&svg=1" alt=""/> ##### About This is a <b>WIP</b> multiplayer game that I am making to play with my family from across the country. (My family's version of Bananagrams) Recommended 3-5 Players ### Play Now! [scuffle.online](https://scuffle.online) ## RULES Object: Be the player with the most letters by the end of the game This game starts with 144 letter tiles facedown in the center. #### HOW TO PLAY Each player takes turns flipping 1 letter at a time in the center. Whenever any player sees a word that can be made of <b>3 or more</b> flipped letters they must call it out and collect their word. At any time the player can transform their word into a longer (and different) one given they use all of the letters AND at least one from the center ##### STEALING LETTERS A word can be stolen from another player <b>at any time</b> provided that word can be turned into a different word using <b>ALL</b> of the letters <b>+ at least 1</b> letter from the center ##### WINNING When all of the letters from the center have been flipped and nobody has any steals/words to create using the center letters then the game is over. The player with the most letters wins the game.
Python
UTF-8
5,292
3.125
3
[]
no_license
import unittest import re import os, sys currentdir = os.path.dirname(os.path.realpath(__file__)) parentdir = os.path.dirname(currentdir) sys.path.append(parentdir) from candidatetesting import * class TestCandidateQuiz(unittest.TestCase): # PART 1 # question tests def test_question(self): self.assertIs(type(question), str) def test_question_correct(self): test = re.search("^(?:W|w)ho was the first (?:A|a)merican woman in space\? ", question) self.assertTrue(test) # self.assertEqual(question, "Who was the first American woman in space? ") # correct_answer tests def test_correct_answer(self): self.assertIs(type(correct_answer), str) def test_answer_correct(self): # self.assertEqual(correct_answer, "Sally Ride") test = re.search("^(?:S|s)ally.(?:R|r)ide$", correct_answer) self.assertTrue(test) # candidate_answer tests def test_candidate_answer(self): self.assertIs(type(candidate_answer), str) # PART 2 # questions tests def test_quiz_contains_5(self): self.assertEqual(len(questions), 5) def test_quiz_contains_question_1(self): test = "^(?:W|w)ho was the first (?:A|a)merican woman in space\? " question_check = False for q in questions: check = re.search(test, q) if check: question_check = True self.assertTrue(question_check) def test_quiz_contains_question_2(self): test = "^(?:T|t)rue or false: 5 kilometer == 5000 meters\? " question_check = False for q in questions: check = re.search(test, q) if check: question_check = True self.assertTrue(question_check) def test_quiz_contains_question_3(self): # (5 + 3)/2 * 10 = ? test = "\(5 \+ 3\)/2 \* 10 = \? " question_check = False for q in questions: check = re.search(test, q) if check: question_check = True self.assertTrue(question_check) def test_quiz_contains_question_4(self): test = "^(?:G|g)iven the list \[8, 'Orbit', 'Trajectory', 45\], what entry is at index 2\? " question_check = False for q in questions: check = re.search(test, q) if check: question_check = True self.assertTrue(question_check) def test_quiz_contains_question_5(self): test = "^(?:W|w)hat is the minimum crew size for the (?:I|i)(?:S|s)(?:S|s)\? " question_check = False for q in questions: check = re.search(test, q) if check: question_check = True self.assertTrue(question_check) def test_correct_answers_contains_5(self): self.assertEqual(len(correct_answers), 5) def test_quiz_contains_answer_1(self): test = "^(?:S|s)ally.(?:R|r)ide$" answer_check = False for a in correct_answers: check = re.search(test, a) if check: answer_check = True self.assertTrue(answer_check) def test_quiz_contains_answer_2(self): test = "^(?:T|t)rue" answer_check = False for a in correct_answers: check = re.search(test, a) if check: answer_check = True self.assertTrue(answer_check) def test_quiz_contains_answer_3(self): test = "40" answer_check = False for a in correct_answers: check = re.search(test, a) if check: answer_check = True self.assertTrue(answer_check) def test_quiz_contains_answer_4(self): test = "^(?:T|t)rajectory" answer_check = False for a in correct_answers: check = re.search(test, a) if check: answer_check = True self.assertTrue(answer_check) def test_quiz_contains_answer_5(self): test = "3" answer_check = False for a in correct_answers: check = re.search(test, a) if check: answer_check = True self.assertTrue(answer_check) # PART 3 # gradeQuiz tests def test_score_0_for_all_wrong(self): candidate_answers = ["foo", "bar", "baz", "lur", "man"] self.assertEqual(grade_quiz(candidate_answers), 0) def test_score_0_for_all_correct(self): candidate_answers = ["Sally Ride", "true", "40", "Trajectory", "3"] self.assertEqual(grade_quiz(candidate_answers), 100) def test_score_20_1_correct(self): candidate_answers = ["Sally Ride", "bar", "baz", "lur", "man"] self.assertEqual(grade_quiz(candidate_answers), 20) def test_score_40_2_correct(self): candidate_answers = ["Sally Ride", "bar", "baz", "lur", "3"] self.assertEqual(grade_quiz(candidate_answers), 40) def test_score_60_3_correct(self): candidate_answers = ["Sally Ride", "bar", "40", "lur", "3"] self.assertEqual(grade_quiz(candidate_answers), 60) def test_score_80_4_correct(self): candidate_answers = ["Sally Ride", "bar", "40", "Trajectory", "3"] self.assertEqual(grade_quiz(candidate_answers), 80) def test_case_insensitivity(self): candidate_answers = ["sally ride", "TRUE", "40", "TrAjEcToRy", "3"] self.assertEqual(grade_quiz(candidate_answers), 100) if __name__ == '__main__': unittest.main()
C++
SHIFT_JIS
3,390
2.6875
3
[ "MIT" ]
permissive
#include "stdafx.h" namespace basedx12 { //-------------------------------------------------------------------------------------- /// Q[zuIuWFNgeNX //-------------------------------------------------------------------------------------- GameObject::GameObject(const shared_ptr<Stage>& StagePtr) : ObjectInterface(), m_Stage(StagePtr) {} GameObject::~GameObject() {} shared_ptr<Stage> GameObject::GetStage(bool ExceptionActive) const { auto shptr = m_Stage.lock(); if (shptr) { return shptr; } else { if (ExceptionActive) { throw BaseException( L"Xe[WnullłBgXe[Wł͂܂񂩁H", L"if (!shptr)", L"GameObject::GetStage()" ); } else { return nullptr; } } // Xe[Wnull // gXe[W̉”\ return nullptr; } void GameObject::TransformInit() { auto Transptr = GetComponent<Transform>(); Transptr->SetToBefore(); } void GameObject::OnPreInit() { //TransformK{ AddComponent<Transform>(); } void GameObject::ComponentUpdate() { auto Transptr = GetComponent<Transform>(); auto RightPtr = GetComponent<Rigidbody>(false); //}bv؂Update list<type_index>::iterator it = m_CompOrder.begin(); while (it != m_CompOrder.end()) { map<type_index, shared_ptr<Component> >::const_iterator it2; it2 = m_CompMap.find(*it); if (it2 != m_CompMap.end()) { //w̌^̃R|[lg‚ if (it2->second->IsUpdateActive() && (it2->second != Transptr) && (it2->second != RightPtr) ) { it2->second->OnUpdate(); } } it++; } if (RightPtr && RightPtr->IsUpdateActive()) { RightPtr->OnUpdate(); } //TransformUpdate if (Transptr->IsUpdateActive()) { Transptr->OnUpdate(); } } void GameObject::ComponentDraw() { //TransformȂΗO auto Transptr = GetComponent<Transform>(); auto RightPtr = GetComponent<Rigidbody>(false); //}bv؂Draw list<type_index>::iterator it = m_CompOrder.begin(); while (it != m_CompOrder.end()) { map<type_index, shared_ptr<Component> >::const_iterator it2; it2 = m_CompMap.find(*it); //w̌^̃R|[lg‚ if (it2 != m_CompMap.end()) { if (it2->second->IsDrawActive() && (it2->second != Transptr) && (it2->second != RightPtr) ) { it2->second->OnDraw(); } } it++; } if (RightPtr && RightPtr->IsDrawActive()) { //RigidbodyDraw() RightPtr->OnDraw(); } if (Transptr->IsDrawActive()) { Transptr->OnDraw(); } } void GameObject::OnDraw() { ComponentDraw(); } void GameObject::ComponentDestroy() { auto Transptr = GetComponent<Transform>(); //}bv؂Update list<type_index>::iterator it = m_CompOrder.begin(); while (it != m_CompOrder.end()) { map<type_index, shared_ptr<Component> >::const_iterator it2; it2 = m_CompMap.find(*it); if (it2 != m_CompMap.end()) { //w̌^̃R|[lg‚ if (it2->second != Transptr) { it2->second->OnDestroy(); } } it++; } //TransformOnDestroy if (Transptr->IsUpdateActive()) { Transptr->OnDestroy(); } } } // end basedx12
Swift
UTF-8
1,248
4.46875
4
[]
no_license
import UIKit var distance: Int = 0 // MARK: - Function // func 이름() { 구현 } func moveForward() { distance = distance + 1 // distance += 1 } print(distance) // 반복하는 동작! moveForward() moveForward() moveForward() print(distance) // MARK: for 구문 distance = 0 for _ in 1...3 { // 1부터 3까지 _ 에 대하여 // 반복되는 구문이 여기에 moveForward() } print(distance) // 응용 let sports = ["Football", "Basketball", "Volleyball", "Golf"] print(sports[0]) print(sports[1]) print(sports[2]) for i in 0...3 { // i = 0, 1, 2, 3 // 반복되는 구문이 여기에 print(sports[i]) } // 함수 + for func moveThreeForeward() { for _ in 1...3 { // 반복되는 구문이 여기에 moveForward() } } // 파라미터 + for (count 만큼 1칸씩 앞으로) func moveForward(count: Int) { for _ in 1...count { // 반복되는 구문이 여기에 moveForward() } } // 파라미터 (한번에 step 만큼 앞으로) func move(step: Int) { distance = distance + step // distance += step } func jump() { move(step: 3) } jump() jump() jump() func jump(count: Int) { for _ in 1...count { jump() } } jump(count: 3)
Python
UTF-8
1,772
2.890625
3
[ "MIT" ]
permissive
from .base import Interface class Betriebsstellen(Interface): """Wrapper for Deutsche Bahn's Betriebsstellen API. Documentation at: https://developer.deutschebahn.com/store/apis/info?name=BahnPark&version=v1&provider=DBOpenData """ def __init__(self, token=None, key=None, secret=None, config=None): super(Betriebsstellen, self).__init__(key=key, secret=secret, token=token, config=config) self.address += 'betriebsstellen/v1/' def request(self, endpoint, verb=None, **req_kwargs): """Returns Data from Betriebsstellen endpoint as python object. Querys API using a super() call to Interface.request(), checks the HTTP status code and returns the response's json data as a python object. :param endpoint: str :param verb: str :param req_kwargs: kwargs accepted by requests.Request() :return: Dict or list """ req_kwargs['headers'] = {'Authorization': 'Bearer ' + self.token, 'Accept': 'application/json'} resp = super(Betriebsstellen, self).request(endpoint, verb=verb, **req_kwargs) resp.raise_for_status() return resp.json() def betriebsstellen(self, station_name, is_abbreviation=False): """Returns data on a operation station. :param station_name: :param is_abbreviation: :return: """ endpoint = 'betriebsstellen' if is_abbreviation: endpoint += '/' + station_name return self.request(endpoint) else: return self.request(endpoint, params={'name': station_name})
C++
SHIFT_JIS
1,649
2.78125
3
[]
no_license
#include "ActorGroundPlane.h" void ActorGroundPlane::Create(){ NxActorDesc actorDesc; ///actor Descriptor with Collection of Shapes. NxPlaneShapeDesc planeDesc; ///Plane Shape Descriptor //ʕ: ax + by + cz + d = 0; planeDesc.normal = NxVec3(0, 1, 0); //ʂ̖@Y() planeDesc.d = 0.0f; //Y = 0.0fɖʂ actorDesc.shapes.pushBack( &planeDesc ); //ActorPlaneo^ //NxScene Creates Actor and Returns a Pointer. _pActor = _pScene->createActor( actorDesc); _pActor->userData = NULL; //PhysXActor(Q[Ȃǂ)f[^Actorт‚ //Set the parameters for the Default Material //Physics"Material"Ƃ͖ڂɌ\ʍގł͂ȂĈ̕wI\ NxMaterial* defaultMaterial = _pScene->getMaterialFromIndex( 0 ); defaultMaterial->setRestitution( 0.3f ); //W defaultMaterial->setStaticFriction( 0.5f ); //Î~CW defaultMaterial->setDynamicFriction( 0.5f ); //CW } void ActorGroundPlane::draw() const{ glColor4f(0.0f, 0.8f, 0.0f, 1.0f); glDisable(GL_LIGHTING); glBegin(GL_LINES); for(int i=-_numGridLine;i<=_numGridLine;i++) { //Lines Parallel to Z Axis glVertex3f(i*_scaleGridLine, (GLfloat)_yGround, -_numGridLine * _scaleGridLine); glVertex3f(i*_scaleGridLine, (GLfloat)_yGround, _numGridLine * _scaleGridLine); //Lines Prallel to X Axis glVertex3f(_numGridLine * _scaleGridLine, (GLfloat)_yGround, i*_scaleGridLine); glVertex3f(-_numGridLine * _scaleGridLine, (GLfloat)_yGround, i*_scaleGridLine); } glEnd(); glEnable(GL_LIGHTING); }
C++
UTF-8
2,563
2.84375
3
[]
no_license
#include "kingBomb.h" #include "ground.h" #include "player.h" KingBomb* KingBomb::getInstance() { static KingBomb instance("King"); return &instance; } KingBomb::KingBomb(const std::string& name): Enemy(name), throwing(false), bombs(), freeBombs() { setY(Ground::getInstance().getGround(getX(), getY()) - height); } KingBomb::KingBomb(const KingBomb& k): Enemy(k), throwing(k.throwing), bombs({}), freeBombs({}) { } void KingBomb::clear(){ for(auto b: bombs){ delete b; } for(auto b: freeBombs){ delete b; } } void KingBomb::advanceFrame(Uint32 ticks){ timeSinceLastFrame+=ticks; if(throwing){ if(timeSinceLastFrame > frameInterval){ if(currentFrame == 2){ currentFrame = 1; }else if(currentFrame == 1){ currentFrame = 0; }else{ currentFrame = 2; throwing = false; if(freeBombs.empty()){ Bomb* newBomb = new Bomb("bomb"); newBomb->setY(getY() + 100); newBomb->setX(getX() + 20); newBomb->setVelocityX(-90); addToBombList(newBomb); newBomb->throwBomb(); Player::getInstance()->attach(newBomb); }else{ addToBombList(freeBombs.back()); freeBombs.back()->setY(getY() + 100); freeBombs.back()->setX(getX() + 2); freeBombs.back()->setVelocityX(-90); freeBombs.back()->throwBomb(); freeBombs.pop_back(); } } timeSinceLastFrame = 0; } }else{ currentFrame = 2; } } void KingBomb::update(Uint32 ticks) { advanceFrame(ticks); // Vector2f incr = getVelocity() * static_cast<float>(ticks) * 0.001; // setPosition(getPosition() + incr); static int timeSinceLastThrow = 0; static int comp = (rand() % 8) + 1; float distsq = (getX() - player.getX()) * (getX() - player.getX()); if(distsq < 250 * 250){ if(throwing){ timeSinceLastThrow = 0; }else{ timeSinceLastThrow += ticks; } if(timeSinceLastThrow > comp * 500){ timeSinceLastFrame = 0; throwing = true; comp = (rand() % 4) + 1; } } for(auto b: bombs){ b->update(ticks); } } void KingBomb::draw() const{ images[currentFrame]->draw(getX(), getY(), getScale()); for(auto b: bombs){ b->draw(); } } void KingBomb::addToBombList(Bomb* b){ bombs.push_back(b); } void KingBomb::addToFreeList(Bomb* b){ freeBombs.push_back(b); } void KingBomb::removeFromBombList(Bomb* b){ auto it = bombs.begin(); while(it != bombs.end()){ if(*it == b){ it = bombs.erase(it); }else{ it++; } } } int KingBomb::getNumBombs() const{ return bombs.size(); } int KingBomb::getNumFreeBombs()const { return freeBombs.size(); }
JavaScript
UTF-8
4,593
2.890625
3
[]
no_license
(function() { function easeOut(t, b, c, d, a, p) { if(t > d) return b + c; if(t == 0) return b; if((t /= d) == 1) return b + c; if(!p) p = d * .3; if(!a || a < Math.abs(c)) { a = c; var s = p / 4; } else { var s = p / (2 * Math.PI) * Math.asin(c / a); } return (a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b); } var canvas = document.getElementById("clock_canvas"); if(canvas.getContext) { var ctx = canvas.getContext('2d'); x = canvas.width; y = canvas.height; x_offset = 1; y_offset = 0; ctx.translate(x / 2 + x_offset, y / 2 + y_offset); var img = new Image(); img.src = "clock.png"; var d_m = 10; var d_h = 5; var t_m = d_m; var t_h = d_h; var min_last = (new Date).getMinutes(); var hour_last = ((new Date).getHours() % 12) + (new Date).getMinutes() / 60; var last_min_tick = (new Date).getMinutes() - 1; var spm = 58.5; function getTime() { ctx.clearRect(-250, -250, 500, 500); ctx.drawImage(img, -(x / 2 + x_offset), -(y / 2 + y_offset)); var date = new Date(); var h = (date.getHours() % 12) + date.getMinutes() / 60; var m = date.getMinutes(); var s = date.getSeconds() + date.getMilliseconds() / 1000; // // Hours // ctx.beginPath(); ctx.moveTo(0, 0); ctx.save(); if(h > 3 && h < 9) ctx.rotate(Math.sin(Math.PI * ((h - 3) / 6)) * 0.013); ctx.save(); ctx.rotate(easeOut(t_h, Math.PI * (((h - (m / 60)) - 3) / 6), Math.PI * ((h - 3) / 6) - Math.PI * (((h - (m / 60)) - 3) / 6), d_h)); if(hour_last != h) { t_h = 0; hour_last = h; } if(t_h <= d_h) t_h++; //ctx.shadowBlur = 10; //ctx.shadowOffsetX = 3; //ctx.shadowOffsetY = 6; //ctx.shadowColor = "rgba(0,0,0,0.4)"; ctx.fillStyle = "#eee"; ctx.moveTo(-45, -14); ctx.lineTo(130, -9); ctx.lineTo(130, 9); ctx.lineTo(-45, 14); ctx.fill(); ctx.restore(); ctx.restore(); // // Minutes // ctx.beginPath(); ctx.moveTo(0, 0); ctx.save(); if(m > 15 && m < 45) ctx.rotate(Math.sin(Math.PI * ((m - 15) / 30)) * 0.013); ctx.save(); ctx.rotate(easeOut(t_m, Math.PI * ((m - 16) / 30), Math.PI * ((m - 15) / 30) - Math.PI * ((m - 16) / 30), d_m)); if(min_last != m) { t_m = 0; min_last = m; } if(s > 59.75 && last_min_tick != m) { document.getElementById("clock_tick").play(); last_min_tick = m; } if(t_m <= d_m) t_m++; //ctx.shadowBlur = 20; //ctx.shadowOffsetX = 4; //ctx.shadowOffsetY = 8; //ctx.shadowColor = "rgba(0,0,0,0.4)"; ctx.fillStyle = "#eee"; ctx.moveTo(-45, -14); ctx.lineTo(180, -9); ctx.lineTo(180, 9); ctx.lineTo(-45, 14); ctx.fill(); ctx.restore(); ctx.restore(); // // Seconds // if(s > spm) s = spm; ctx.beginPath(); ctx.moveTo(0, 0); ctx.save(); ctx.rotate((2 * Math.PI * s) / spm - Math.PI / 2); //ctx.shadowBlur = 80; //ctx.shadowOffsetX = 6; //ctx.shadowOffsetY = 12; //ctx.shadowColor = "rgba(0,0,0,0.4)"; ctx.fillStyle = "#e2331e"; ctx.rect(-60, -3.5, 185, 7); ctx.moveTo(130, -3.5); ctx.arc(130, 0, 16, 0, Math.PI * 2, true); ctx.moveTo(130, 3.5); ctx.rect(-60, -3.5, 185, 7); ctx.fill(); //ctx.shadowBlur = 2; //ctx.shadowOffsetX = 0; //ctx.shadowOffsetY = 0; ctx.beginPath(); ctx.arc(0, 0, 7, 0, Math.PI * 2, true); ctx.fill(); ctx.restore(); } setInterval(getTime, 1000 / 35); } })();
Markdown
UTF-8
21,614
3.0625
3
[]
no_license
## mudou网络库解析 ### 写在前面 mudou网络库是我当时学习某个开源项目叫做[Flamingo](https://github.com/balloonwj/flamingo),这是一个纯c++开发的即时通讯软件,当时我并不知道mudou网络库,只是当初想要对c++服务器开发做一个深入了解,看看人家服务器端项目怎么写的,于是找到了这个项目。这个项目主要包括flamingoserver服务端,flamingoclient客户端两部分。其中flamingoserver服务端里面就包含了mudou库。其中的net和base文件夹就是属于mudou源码的大部分。我这里讲解的是mudou源码中关于整个网络库的一部分,我也去[mudou源码](https://github.com/chenshou/mudou)看过,核心这里还是讲解到的,所以我建议先看完本库的源码再去github上看陈硕老师的源码集合。 由于当时我看flamingo源码时也不知道这块是属于mudou源码,所以也没有查资料,当时自己也花了很多时间摸索如何去看flamingo源码(第一次看一个完整的源码也没有经验),后来看反复看了很久弄通了整个服务器模块的逻辑,整个flamingo服务器端包括: - 网络库底层逻辑 - 数据库逻辑 - 上层业务逻辑 这里的网络库底层逻辑就是这里的mudou网络库,上层业务就是实现flamingo即时通讯类似qq这样功能软件所有处理的业务,数据库当然就是连接数据库这块。 我也是通过阅读这个源码才了解到mudou库,这也是我学习到的第一个开源项目。所有写一遍文章,来记录自己对mudou库的理解,可能不是很到位,我会在给一张建议阅读mudou网络库的代码顺序,我觉得一个好的阅读顺序是学习源码的好方式。 ``` 1.首先是base文件夹 Singleton.h->Timestamp.h/cpp->ConfigFileReader.h/cpp->AsyncLog.h/cpp->Buffer.h/cpp->Endian.h->Callbacks.h->Sockets.h/cpp->InetAddress.h/cpp-> channel.h/cpp-> ``` 以上只是个人的阅读顺序,希望你能有一个大概的网络API概念,包括套接字,bind(),listen(),connect()等函数,知道是干什么用的。然后阅读源码时候你会发现大佬写的代码都是很规范很漂亮的,文件夹的命名和文件的命名都是很规范,都能给你一定信息。我会带着上述的代码阅读顺序,逐个解析各个文件的作用,包括函数,和如何和其他连接起来的。 ### 阅读源码 > 我觉得看懂一个类的作用和实现首先需要看的是类声明,先看类的成员变量,再看类的函数声明,再看类的成员函数的实现(细节),最后总结归纳出该类的作用和对外接口。所以我会一次解读每个文件中每个类。每个类的分析都会有,类声明分析、重要类函数实现分析、类作用和对外接口,三个部分。 ## Singleton.h **1.类声明分析** ``` template<typename T> class Singleton { public: static T& Instance() { //pthread_once(&ponce_, &Singleton::init); if (nullptr == value_) { value_ = new T(); } return *value_; } private: Singleton(); ~Singleton() = default; Singleton(const Singleton&) = delete; Singleton& operator=(const Singleton&) = delete; static void init() { value_ = new T(); //::atexit(destroy); } static void destroy() { delete value_; } private: //static pthread_once_t ponce_; static T* value_; }; //template<typename T> //pthread_once_t Singleton<T>::ponce_ = PTHREAD_ONCE_INIT; template<typename T> T* Singleton<T>::value_ = nullptr; ``` **2.重要类函数实现分析** 这个是看名字就知道是个单例模式的类,准确说是个模板类,由于类声明和实现都在一起所以在这里直接看各个函数的作用。这个模板类成员函数是静态,也只有一个静态成员,指向模板类型的指针,同时构造函数是私有的也就是不能直接构造这个类的对象。只能用类的静态成员函数。对外提供了一个实例化函数**Instance()** 只会返回至始至终在内存中的某个对象,如果该对象已经存在,再次调用只会返回该对象,如果还没有该对象则会new一个新的然后返回。 **3.类作用及对外接口总结** 作用:当使用该类去得某个对象的时候在程序中只会出现一个该类型对象。使用的方式是直接**Signleton\<ClassType>::Instance()** 就可以取得对象。以后会再使用该方式取的对象永远是那一个。 ## Timestamp.h和Timestamp.cpp **1.类声明分析** ![Timestamp](../Pictures/mudou_base-Timestamp1.png) 该类是一个保存自1970年1月1日到某一时间的微秒数,可以计算一下足够我们使用,因为是用一个64位的数表示。 **2.重要类函数实现分析** 构造函数默认的是一个微妙数是0的我们用来表示无效时间,还有一个显式构造函数。 ``` Timestamp& operator+=(Timestamp lhs) # 将lhs对象的时间数加到该对象上,并返回该对象 Timestamp& swap(Timestamp that) # 交换该对象和that对象的时间数 string toString() const; # 以 "秒数:微秒数" 的字符形式返回该对象表示的时间 string toFormattedString(bool showMicroseconds = true) const; # 以 "年月日 时:分:秒:w微秒" 的形式返回该对象所表示的时间(如果参数为true则显示微秒,否则不显示) static Timestamp now(); # 返回调用该函数时的当前时间对象 static Timestamp invalid(); # 返回一个无效的时间对象 ``` **3.类作用及对外接口总结** 该类就是一个表示时间的类,为网络库里面的定时器事件提供对象。对外一般用该对象保存时间,作为参数使用 ## ConfigFileReader.h和ConfigFileReader.cpp **1.类声明分析** ![ConfigFileReader](../Pictures/mudou_config.png) 读取配置文件然后将配置以map的形式保存到对象中。说白了就是能够解析配置文件 **2.重要类函数实现分析** ``` CConfigFileReader(const char* filename) # 构造对象的时候会自动调用loadFile()函数,加载对应的配置文件并把配置文件的配置以key,value的形式保存在该类的map中 char* getConfigName(const char* name); # 得到配置的某个key所对应的value int setConfigValue(const char* name, const char* value); # 设置对应的key,value的值,并且会调用writeFile()写入对应的文件中 ``` **3.类作用及对外接口总结** 这个类就是读取配置文件,把配置文件的每一行的=两步以字符串的形式读入map中,支持"#"作为注释,也支持空string左右空白,这是通过trimSpace()函数实现的。 对外的接口就是构造对象之后通过**getConfigName()** 获取相应的配置值,和**setConfigValue()** 设置相应的key,value。支持类似下面的配置文件 ![ConfigFileReader](../Pictures/mudou_config2.png) 其中#号是注释,而且空格是忽略的向 "listenip":"0.0.0.0" 会以这样的形式保存在map中,每行只以第一个=号为分隔key,value。 ## AsyncLog.h和AsyncLog.cpp **1.类声明分析** ![AsyncLog](../Pictures/mudou_AsyncLog1.png) ![AsyncLog](../Pictures/mudou_AsyncLog2.png) 可以看到又是一个静态类,其实静态类也是类似于单例模式,因为你只能有一组静态成员变量,可以看到里面的成员,其中m_hLogFile是一个打开文件句柄,,表示要写入日志到某个文件,m_bToFile是输出日志到文件还是控制台,m_bTruncateLongLog表示是否截断长日志,一般日志保存在文件中一行就表示写了一次日志信息,如果一行太长,这里是一行最长256个字节。m_nFileRollSize是表示一个日志文件最长为多少,这里默认为10MB如果超过了就换一个文件,m_listLinesToWrite是一个list双向链表保存着要写入的日志,因为,日志是采用异步的方式进行写入文件的,在主线程里,每条日志都是放入这个list中,然后会有一个单独的线程去将list中的日志写入文件中。init()函数需要使用前调用,然后就是3个output函数是供外部调用的。 **2.重要类函数实现分析** ![AsyncLog](../Pictures/mudou_AsyncLog3.png) 我们可以看到日志分了好多级别,只有高于当前日志级别也就是m_ncurrentLevel才能正常输入,但是最高级别CRITICAL除外,外部调用的时候我们只需要使用LOGT(...)之类的函数,支持格式化,也就是%s,%d,之类的,这是因为利用了宏定义,还有va_list。 - init() 初始化函数,这是我们能够正确使用LOGF(...)之前需要做的工作。在函数内部主要是如果有文件名或者正确的值,那么m_strFileName就有效,否则就是一个空的字符串。然后就是init()会保存当前的进程ID,然后就是新建一个线程用来处理m_listLinesTowrite中的日志信息写入对应的文件。新线程绑定的是writeThreadProc()内部私有函数,该函数就是不断的从m_listLinesToWrite链表中拿出数据写入对应的文件中,如果没有日志信息可写会睡眠该线程。 - uninit() 结束整个日志工作的函数,一旦调用,会等待写日志线程结束,然后关闭存储日志文件句柄,整个异步日志类停止工作。 - setLevel() 设置整个日志过程中的日志级别默认系统开始时日志时INFO级别 - isRunning() 判断写日志线程是否工作,当进入writeThreadPrco()工作线程绑定函数时m_bRunning设为True - output() 有3种日志输出文件,一种是普通信息,另外一种是加入了调用该函数的函数文件名,和行号,最后一种是日志信息的二进制写入文件。内部首先会调用makeLinePrefix()私有函数生成日志信息前缀形如"[日志级别][生成该日志时间][调用该函数的线程ID]"这样的前缀,后面才是真正的日志信息。然后处理日志正文,是通过va_list去读取格式字符串,得到一个完整的日志正文信息,然后如果开启了日志截断,则日志正文最多256个字符,如果是写入文件末尾追加一个换行符号,也就是日志文件每一行代表一个日志信息。然后利用锁和条件变量加入该信息到m_listLinesToWrite中,同时唤醒工作线程。如果日志级别是FATAL,那么会在工作台显示该日志,然后将该日志同步写入日志文件,然后终止整个程序。 ![AsyncLog](../Pictures/mudou_AsyncLog4.png) 这是我写的一个demo代码,下面的结果 ![AsyncLog](../Pictures/mudou_AsyncLog5.png) 可以看到默认的日志等级是INFO,低于INFO的DEBUG级别并没有输出,同时截断了过长的日志。 ![AsyncLog](../Pictures/mudou_AsyncLog6.png) 可以看到有一个日志文件以"文件名.日期.进程ID.log"的形式保存日志文件。 **3.类作用及对外接口总结** 这就是一个普通的异步日志类文件,对外的接口就是调用init()函数,然后使用宏定义,也就是 ![AsyncLog](../Pictures/mudou_AsyncLog3.png) 这里面的LOGI(...)等形式的函数就可以输出日志到对应的文件。里面的技术主要是一个异步日志,采用一个线程专门写日志到文件,在其他调用LOGI(...)函数中只是包装好日志信息到内存链表中,然后交给线程处理函数写日志到文件。 ## Buffer.h和Buffer.cpp **1.类声明分析** ![buffer](../Pictures/mudou_buffer1.png) 整个buffer其实就是由一个vector组成的空间,然后外加两个索引分别表示可读和可写 **2.重要类函数实现分析** ![buffer](../Pictures/mudou_buffer2.png) 一个vector被readerIndex_,writerIndex_分隔成3部分,第一部分为前置保留的区域[0,readerIndex_),然后就是[readerIndex_,writerIndex_)表示的可读部分,最后就是[writerIndex,size)可写部分。 通过移动可读和可写索引来向buffer中写或者读数据。 ``` explicit Buffer(size_t initialSize = kInitialSize) : buffer_(kCheapPrepend + initialSize), readerIndex_(kCheapPrepend), writerIndex_(kCheapPrepend) #显式构造函数,默认前置的空间大小是8字节,初始化空间为1024字节所以开始时buffer_大小为1032字节。 const char* peek() const #可读数据的指针 const char* findString(const char* targetStr) const #在可读区域查找字符串,找到返回,没找到返回nullptr const char* findCRLF() const #在可读范围内查找"\r\n" const char* findCRLF(const char* start) const #在start(必须在可读区域)到可读区域末尾查找"\r\n" bool retrieve(size_t len) #读取一定数量字节 std::string retrieveAsString(size_t len) #以字符串的形式读取一定字节 void append(const std::string& str) #写入字符串 void appendInt64(int64_t x) #以网络字节序写入buffer一个Int64 int64_t readInt64() #以从网络字节序读出一个Int64为主机字节序 bool prepend(const void* /*restrict*/ data, size_t len) #在可读区域前面写入数据 void shrink(size_t reserve) #调整整个buffer到合适大小 int32_t Buffer::readFd(int fd, int* savedErrno) #最重要的一个函数从fd中读数据到buffer中如果可写区域小于65536则开另外一个数组临时保存fd中的数据然后再写入buffer中,确保能读完不大于65536个自己的fd数据 ``` **3.类作用及对外接口总结** Buffer是整个mudou网络库用来存储数据的中间类,提供了很多适合网络编程的接口,向readFd()等,都是针对网络库设计的Buffer.其实也很简单就是一个vector,然后两个变量记录了索引,将整个区间可读,可写,还有前置区域都划分的很清楚。 ## Endian.h **1.类声明分析** ``` inline uint64_t hostToNetwork64(uint64_t host64) inline uint32_t hostToNetwork64(uint32_t host32) inline uint16_t hostToNetwork64(uint16_t host16) inline uint64_t networkToHost64(uint64_t net64) inline uint32_t networkToHost64(uint32_t net32) inline uint16_t networkToHost16(uint16_t net16) ``` **2.重要类函数实现分析** 为不同主机和网络字节序,统一了接口,有64位,32位,16位,主机字节序和网络字节序的互换。确保网络编程数据的正常交换。 **3.类作用及对外接口总结** 根据不同的数据需要调用不同的函数,跟后续的Socket联合使用。 ## Callbacks.h **1.类声明分析** ``` template<typename To, typename From> inline To implicit_cast(From const& f) { return f; } #隐式转化函数 template<typename To, typename From> inline To down_cast(From* f) #向下转化,内部是调用dynamic_cast emplate<typename To, typename From> inline std::shared_ptr<To> down_pointer_cast(const std::shared_ptr<From> & f) #指针向下转化,内部也是调用dynamic_cast ``` **2.重要类函数实现分析** ``` class Buffer; class TcpConnection; typedef std::shared_ptr<TcpConnection> TcpConnectionPtr; typedef std::function<void()> TimerCallback; typedef std::function<void(const TcpConnectionPtr&)> ConnectionCallback; typedef std::function<void(const TcpConnectionPtr&)> CloseCallback; typedef std::function<void(const TcpConnectionPtr&)> WriteCompleteCallback; typedef std::function<void(const TcpConnectionPtr&, size_t)> HighWaterMarkCallback; // the data has been read to (buf, len) typedef std::function<void(const TcpConnectionPtr&, Buffer*, Timestamp)> MessageCallback; void defaultConnectionCallback(const TcpConnectionPtr& conn); void defaultMessageCallback(const TcpConnectionPtr& conn, Buffer* buffer, Timestamp receiveTime); ``` 主要定义了一些回调函数类型,主要是建立连接的ConnectionCallback,定时器回调函数类型TimerCallback,关闭连接回调类型closeCallback,写数据完成WriteCompleteCallback,还有最重要的收发数据回调MessageCallback,然后有两个默认的回调函数。一个是建立连接的时候需要调用,另外一个是收发数据时候需要调用。 **3.类作用及对外接口总结** 整个文件定义了一些回调函数别名,和一些类型转化,类型转化主要有两个,还有一些回调函数,主要是建立连接和消息处理的回调函数。 ## Sockets.h和Sockets.cpp **1.类声明分析** 这个主要是对socket的封装 ``` explicit Socket(int sockfd) : sockfd_(sockfd) #显示构造函数 SOCKET fd() const { return sockfd_; } bool getTcpInfoString(char* buf, int len) const; #得到Tcp连接信息 void bindAddress(const InetAddress& localaddr) #socketFd绑定某个地址 void listen(); #socket转化为监听套接字 int accept(InetAddress* peeraddr); #accept()函数的包装,接收某个连接,返回连接套接字 void shutdownWrite(); #关闭套接字写 void setTcpNoDelay(bool on); #设置连接属性 void setReuseAddr(bool on); void setReusePort(bool on); void setKeepAlive(bool on); private: const SOCKET sockfd_; #唯一成员变量一个常量的普通socketFd ``` **2.重要类函数实现分析** ``` SOCKET createOrDie(); #创建非阻塞fd,失败就结束进程(函数名的OrDie就是这个意思) SOCKET createNonblockingOrDie(); #创建非阻塞fd,失败就结束进程 void setNonBlockAndCloseOnExec(SOCKET sockfd); #设置socket属性为非阻塞和在子程序中关闭 void setReuseAddr(SOCKET sockfd, bool on); #socket重复使用某个地址 void setReusePort(SOCKET sockfd, bool on); #socket重复使用某个端口 SOCKET connect(SOCKET sockfd, const struct sockaddr_in& addr); #连接某个地址 void bindOrDie(SOCKET sockfd, const struct sockaddr_in& addr); #绑定某个地址到socket SOCKET accept(SOCKET sockfd, struct sockaddr_in* addr); #接收连接到某个socket的连接 int32_t read(SOCKET sockfd, void *buf, int32_t count); #从套接字读数据 ssize_t readv(SOCKET sockfd, const struct iovec *iov, int iovcnt);#从套接字读数据到多个内存 int32_t write(SOCKET sockfd, const void *buf, int32_t count);#向套接字写数据 void close(SOCKET sockfd); #关闭套接字内部也是调用全局close() void shutdownWrite(SOCKET sockfd); #停止套接字数据传输,内部调用shutdown()函数 void toIpPort(char* buf, size_t size, const struct sockaddr_in& addr);#某个地址的ip和port转化为字符串 void toIp(char* buf, size_t size, const struct sockaddr_in& addr);#某个地址的ip转化为字符串 void fromIpPort(const char* ip, uint16_t port, struct sockaddr_in* addr);# 从字符串和port,生成一个地址 int getSocketError(SOCKET sockfd);#得打某个套接字相关的错误 const struct sockaddr* sockaddr_cast(const struct sockaddr_in* addr);#地址转化sockaddr和sockaddr_in之间的转化 struct sockaddr* sockaddr_cast(struct sockaddr_in* addr); const struct sockaddr_in* sockaddr_in_cast(const struct sockaddr* addr); struct sockaddr_in* sockaddr_in_cast(struct sockaddr* addr); struct sockaddr_in getLocalAddr(SOCKET sockfd);#得到本地地址 struct sockaddr_in getPeerAddr(SOCKET sockfd);#得到对端地址 bool isSelfConnect(SOCKET sockfd);#判断是不是自己连接自己 ``` 和网络Socket相关的一些函数。 **3.类作用及对外接口总结** 该类只是对普通socket的包装,然后就是对网络变成的bind(),listen(),connect(),accept()函数的封装。 ## InetAddress.h和InetAddress.cpp **1.类声明分析** ``` explicit InetAddress(uint16_t port = 0, bool loopbackOnly = false); InetAddress(const std::string& ip, uint16_t port); InetAddress(const struct sockaddr_in& addr); std::string toIp() const; std::string toIpPort() const; uint16_t toPort() const; const struct sockaddr_in& getSockAddrInet() const { return addr_; } void setSockAddrInet(const struct sockaddr_in& addr) { addr_ = addr; } uint32_t ipNetEndian() const { return addr_.sin_addr.s_addr; } uint16_t portNetEndian() const { return addr_.sin_port; } static bool resolve(const std::string& hostname, InetAddress* result); private: struct sockaddr_in addr_; ``` 该类只是sockaddr_in的包装 **2.重要类函数实现分析** 3种构造函数都可以构造一个网络地址,可以用本地地址,也可以从ip.port构造,也可以从一个sockaddr_in地址构造,resolve()是解析主机名然后生成一个地址。 **3.类作用及对外接口总结** 这个类主要是对地址的封装,方便一些接口和对象的统一使用 ------------------------------------------------------------------------ ------------------------------------------------------------------------ ------------------------------------------------------------------------ 现在才是整个网络库的基础,包括一些常用概念channel,EventLoop,Poller等。 ## Channel.h和Channel.cpp **1.类声明分析** **2.重要类函数实现分析** **3.类作用及对外接口总结**
C#
UTF-8
3,255
2.65625
3
[ "MIT" ]
permissive
// Copyright © 2014-2018 Stig Schmidt Nielsson. This file is Open Source and distributed under the MIT license - see LICENSE.txt or https://opensource.org/licenses/MIT. using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using static System.Math; namespace StigsDotNetLib.Caching { //TODO TEST! public class LruCache<TKey, TVal> { private readonly Dictionary<TKey, CacheItem> _items = new Dictionary<TKey, CacheItem>(); private readonly ConcurrentStack<CacheItem> _pool = new ConcurrentStack<CacheItem>(); private readonly ReaderWriterLockSlim _rwLock; private int _capacity; private CacheItem _first; private int _cacheItemTotalInstanceCount; private CacheItem _last; public LruCache(int capacity) { _rwLock = new ReaderWriterLockSlim(); Capacity = capacity; } public int Capacity { get => _capacity; set { _capacity = value; Trim(0); } } public int Count => _items.Count; public int CacheItemInstanceInPoolCount => _pool.Count; public int CacheItemTotalInstanceCount => _cacheItemTotalInstanceCount; public event EventHandler<LruCache<TKey, TVal>, (TKey key, TVal val)> ItemSetEvent; public event EventHandler<LruCache<TKey, TVal>, (TKey key, TVal val)> ItemRemovedEvent; public TVal Set(TKey key, TVal val) { try { _rwLock.EnterWriteLock(); if (!_items.TryGetValue(key, out var cacheItem)) { if (_items.Count >= Capacity) TrimCore(); cacheItem = GetFromPool(key, val); } _items[key] = SetAsFirstCacheItem(cacheItem); ItemSetEvent?.Invoke(this,(key,val)); return val; } finally { _rwLock.ExitWriteLock(); } } public void Trim(int count) { try { _rwLock.EnterWriteLock(); TrimCore(count); } finally { _rwLock.ExitWriteLock(); } } private void TrimCore(int countBelowCapacity = 0) { var count = Min(_items.Count, Max(_items.Count - Capacity, 0) + countBelowCapacity); for (var i = 0; i < count; i++) { _items.Remove(_last.Key); var tmp = _last; _last = _last.Prev; _last.Next = null; ReturnToPool(tmp); ItemRemovedEvent?.Invoke(this, (tmp.Key, tmp.Val)); } } private CacheItem SetAsFirstCacheItem(CacheItem cacheItem) { if (_first != null) _first.Prev = cacheItem; cacheItem.Next = _first; cacheItem.Prev = null; _first = cacheItem; return cacheItem; } public bool TryGet(TKey key, out TVal val) { try { _rwLock.EnterReadLock(); if (_items.TryGetValue(key, out var cacheItem)) { val = SetAsFirstCacheItem(cacheItem).Val; return true; } val = default(TVal); return false; } finally { _rwLock.ExitReadLock(); } } private CacheItem GetFromPool(TKey key, TVal val) { if (!_pool.TryPop(out var result)) { result = new CacheItem(); _cacheItemTotalInstanceCount++; } result.Key = key; result.Val = val; return result; } private void ReturnToPool(CacheItem cacheItem) { cacheItem.Key = default(TKey); cacheItem.Val = default(TVal); cacheItem.Next = null; cacheItem.Prev = null; _pool.Push(cacheItem); } private class CacheItem { public TKey Key; public CacheItem Next; public CacheItem Prev; public TVal Val; } } }
C#
UTF-8
1,257
2.640625
3
[]
no_license
using SmileWithStyleDB; using System; using System.Collections.Generic; using System.Linq; using System.Web; using SmileWithStyleDB; namespace pjct_webshop.Models { public class Produkt_model { public Produkt_model() { } public Produkt_model(Product p) { Name = p.Name; Description = p.Description; Price = p.Price; Type = p.Type; ImagePath = p.ImagePath; Quantity = p.Quantity; AvailableWhenSold = p.AvailableWhenSold; ArtNumber = p.ArtNumber; } public void SaveToDB() { Product p = new Product() { Name = this.Name }; Class1 c1 = new Class1(); //c1.saveNewProduct(p); } public string Type { get; set; } public string Name { get; set; } public string Description { get; set; } public string ArtNumber { get; set; } public int Quantity { get; set; } public string ImagePath { get; set; } public bool AvailableWhenSold { get; set; } public double Price { get; set; } public void saveProduct() { Product p =new Product() {Name = this.Name}; } } }