language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
962
2.5
2
[]
no_license
package com.cg.hcs.validation; import com.cg.hcs.exception.*; public class ValidateImplementation{ public static void TestNameValidate(String testName) throws TestNameException{ String pattern="[A-Za-z\\s]{1,20}"; if(!testName.matches(pattern)) throw new TestNameException(); } public static void DiagnosticCenterValidate(String centerName) throws DiagnosticCenterNameException{ String pattern="[A-Za-z\\s]{1,20}"; if(!centerName.matches(pattern)) throw new DiagnosticCenterNameException(); } public static void DiagnosticCenterIdValidate(String centerId) throws DiagnosticCenterIdException{ String pattern="[D]{1}[1-9]{1,5}"; if(!centerId.matches(pattern)) throw new DiagnosticCenterIdException(); } public static void optionChosenValidate(String option) throws WrongOptionChosenException{ String pattern="[1-9]{1}"; if(!option.matches(pattern)) throw new WrongOptionChosenException(); } }
Java
UTF-8
4,840
1.820313
2
[]
no_license
package com.fangzhurapp.technicianport.frag; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.RelativeLayout; import com.fangzhurapp.technicianport.R; import com.fangzhurapp.technicianport.activity.InComeActivity; import com.fangzhurapp.technicianport.adapter.BossSmsrAccountAdapter; import com.fangzhurapp.technicianport.bean.moneyDetailBean; import com.fangzhurapp.technicianport.http.CallServer; import com.fangzhurapp.technicianport.http.HttpCallBack; import com.fangzhurapp.technicianport.http.UrlConstant; import com.fangzhurapp.technicianport.http.UrlTag; import com.fangzhurapp.technicianport.utils.LogUtil; import com.fangzhurapp.technicianport.utils.SpUtil; import com.yolanda.nohttp.NoHttp; import com.yolanda.nohttp.RequestMethod; import com.yolanda.nohttp.rest.Request; import com.yolanda.nohttp.rest.Response; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by android on 2016/10/25. */ public class AccountIngFrag extends Fragment { private View view; private ListView lv_account; private Context mContext; private static final String TAG = "AccountIngFrag"; private List<moneyDetailBean> list; @Override public void onAttach(Context context) { super.onAttach(context); mContext = (InComeActivity)context; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { view = inflater.inflate(R.layout.frag_account, null); init(); return view; } private void init() { RelativeLayout rl_account_nodata = (RelativeLayout) view.findViewById(R.id.rl_account_nodata); lv_account = (ListView) view.findViewById(R.id.lv_account); lv_account.setEmptyView(rl_account_nodata); getAccountData(); } private void getAccountData() { if (SpUtil.getString(mContext,"ident","").equals("boss")){ Request<JSONObject> jsonObjectRequest = NoHttp.createJsonObjectRequest(UrlConstant.BOSS_SMSR, RequestMethod.POST); jsonObjectRequest.add("sid", SpUtil.getString(mContext, "sid", "")); jsonObjectRequest.add("type", "2"); CallServer.getInstance().add(mContext, jsonObjectRequest, callback, UrlTag.BOSS_SMSR, true, false, true); } } private HttpCallBack<JSONObject> callback = new HttpCallBack<JSONObject>() { @Override public void onSucceed(int what, Response<JSONObject> response) { if (what == UrlTag.BOSS_SMSR) { LogUtil.d(TAG, response.toString()); JSONObject jsonObject = response.get(); try { String sucess = jsonObject.getString("sucess"); if (sucess.equals("1")) { JSONObject data = jsonObject.getJSONObject("data"); JSONArray income = data.getJSONArray("income"); if (income.length() > 0) { list = new ArrayList<>(); for (int i = 0; i < income.length(); i++) { moneyDetailBean moneyDetailBean = new moneyDetailBean(); moneyDetailBean.setCname(income.getJSONObject(i).getString("cname")); moneyDetailBean.setMoney(income.getJSONObject(i).getString("money")); moneyDetailBean.setTime(income.getJSONObject(i).getString("time")); moneyDetailBean.setType(income.getJSONObject(i).getString("type")); moneyDetailBean.setPayment_onumber(income.getJSONObject(i).getString("payment_onumber")); moneyDetailBean.setSmoney(income.getJSONObject(i).getString("smoney")); moneyDetailBean.setPay_channel(income.getJSONObject(i).getString("pay_channel")); list.add(moneyDetailBean); } BossSmsrAccountAdapter adapter = new BossSmsrAccountAdapter(list, mContext); lv_account.setAdapter(adapter); } } } catch (JSONException e) { e.printStackTrace(); } } } @Override public void onFailed(int what, Response<JSONObject> response) { } }; }
C
UTF-8
1,005
3.296875
3
[ "MIT" ]
permissive
// %%cpp atomic_example3.c // %run gcc -fsanitize=thread atomic_example3.c -lpthread -o atomic_example3.exe // %run ./atomic_example3.exe > out.txt // %run cat out.txt #include <stdatomic.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> // ПЛОХОЙ КОД!!! _Atomic int* x; int main(int argc, char* argv[]) { int data[3] = {10, 20, 30}; int* one = data + 0; int* two = data + 1; int* three = data + 2; atomic_store(&x, (_Atomic int*) one); printf("%d\n", *(int*)atomic_load(&x)); int* i = two; // изменение не пройдет, так как x = 1, а i = 2, i станет равным x atomic_compare_exchange_strong(&x, (_Atomic int**) &i, (_Atomic int*) three); printf("%d\n", *(int*)atomic_load(&x)); i = one; // тут пройдет atomic_compare_exchange_strong(&x, (_Atomic int**) &i, (_Atomic int*) three); i = (int*) atomic_load(&x); printf("%d\n", *(int*)atomic_load(&x)); return 0; }
Shell
UTF-8
222
2.53125
3
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
#!/bin/bash function SafePwrCycle() { sync ; sync sudo umount -fa > /dev/null 2&>1 # Write CPLD register to initiate cold reboot sudo echo 0 > /sys/bus/i2c/devices/i2c-0/0-0041/cold_reset } SafePwrCycle
Python
UTF-8
1,190
2.859375
3
[]
no_license
""" These are rules about how to build IHME paths. A path has: 1) A base disk location for all data. /ihme, or J:/ihme. 2) A team location, such as /forecasting. 3) A role for a dataset, such as sev_data, or sev_forecasts. 4) A date an description, as YYYMMDD_whatever. 5) Subdirectories for results. """ import os import logging import re logger = logging.getLogger("provda.ihmepath") def build_path(host_type, team, role, date, description, subdirectory=None, filename=None): directory_stack = list() if host_type == "cluster": directory_stack.append("ihme") elif host_type == "windows": directory_stack.append("J:") else: logger.exception("Expect a host type of cluster or windows.") directory_stack.append(team) directory_stack.append(role) normalized = "".join(re.findall("[a-zA-Z0-9\.\-\_]", description.replace(" ", "_"))) directory_stack.append("{}_{}".format(date, normalized)) if subdirectory is not None: directory_stack.append(subdirectory) if filename is not None: directory_stack.append(filename) return os.path.join(*directory_stack)
Java
UTF-8
355
2.515625
3
[]
no_license
package Coocking; public class ChoiceRecepe { public Recepe recipe; public ChoiceRecepe(){ this.recipe=null; } public ChoiceRecepe(Recepe recipe){ this.recipe=recipe; } public String getStep(int step){ return recipe.getStrps().get(step); } public String getImagePath(int step){ return recipe.getListImagePath().get(step); } }
C++
UTF-8
841
3.296875
3
[]
no_license
#pragma once #include<iostream> using namespace std; template<typename T> class static_ctor_dtor{ public: struct helper { helper(){ cout<<"static_ctor_dtor helper constructor"<<endl; T::static_constructor(); } ~helper(){ cout<<"static_ctor_dtor helper destructor"<<endl; T::static_destructor(); } }; protected: static helper placeholder; protected: static_ctor_dtor(){ cout<<"static_ctor_dtor constructor"<<endl; } ~static_ctor_dtor(){ cout<<"static_ctor_dtor destruct"<<endl; } public: static helper* getHelper(){return &placeholder;} // static_ctor_dtor(){ // static helper placeholder; // } }; template<typename T> typename static_ctor_dtor<T>::helper static_ctor_dtor<T>::placeholder;
Python
UTF-8
6,122
3.484375
3
[]
no_license
import pygame from pygame.locals import * import random import time WHITE = (255, 255, 255) BLACK = (0, 0, 0) BACKGROUND_X = 700 BACKGROUND_Y = 400 SIZE = 20 SPEED_BALL = 2 SPEED_PLAYER = 2 class Ball: def __init__(self, surface): self.parent_screen = surface self.x = int(BACKGROUND_X / 2 - 50) self.y = int(BACKGROUND_Y / 2) self.radius = 8 self.direction_x = SPEED_BALL * (-1)**random.randint(0, 1) self.direction_y = SPEED_BALL * (-1)**random.randint(0, 1) def draw(self): pygame.draw.circle(self. parent_screen, WHITE, (self.x, self.y), self.radius) def walk(self): self.x += self.direction_x self.y += self.direction_y self.draw() class Player: def __init__(self, surface): self.score = 0 self.parent_screen = surface self.y = int(BACKGROUND_Y / 2) self.direction = 'up' def draw(self, x): # self.parent_screen.fill(BLACK) pygame.draw.rect(self.parent_screen, WHITE, [x, self.y, 8, SIZE * 3]) def move_up(self): self.direction = 'up' def move_down(self): self.direction = 'down' def walk(self, x): if self.direction == 'up': if self.y == 10: self.direction = 'down' else: self.y -= SPEED_PLAYER elif self.direction == 'down': if self.y + SIZE * 3 == BACKGROUND_Y - 10: self.direction = 'up' else: self.y += SPEED_PLAYER self.draw(x) class Background: def __init__(self): self.surface = pygame.display.set_mode((BACKGROUND_X, BACKGROUND_Y)) def draw(self): self.surface.fill(BLACK) pygame.draw.rect(self.surface, WHITE, [5, 5, BACKGROUND_X - 10, BACKGROUND_Y - 10], width=5) for i in range(int(BACKGROUND_Y / (SIZE + 10))): pygame.draw.rect(self.surface, WHITE, [int(BACKGROUND_X / 2) - 2, 10 + i * (SIZE + 10), 4, SIZE]) class Game: def __init__(self): pygame.init() self.background = Background() self.surface = self.background.surface self.player1 = Player(self.surface) self.player2 = Player(self.surface) self.player1.draw(20) self.player2.draw(BACKGROUND_X - 28) self.ball = Ball(self.surface) self.ball.draw() pygame.display.flip() def display_scores(self): font = pygame.font.SysFont('arial', 50) score1 = font.render(f"{self.player1.score}", True, WHITE) score2 = font.render(f"{self.player2.score}", True, WHITE) self.surface.blit(score1, (50, 50)) self.surface.blit(score2, (BACKGROUND_X - 75, 50)) def show_game_over(self): self.draw_all() pygame.draw.rect(self.surface, BLACK, [200, 100, 400, 150]) font = pygame.font.SysFont('arial', 30) line1 = font.render(f"Continue Press SPACE", True, WHITE) self.surface.blit(line1, (200, 100)) line2 = font.render("or restart game with ENTER", True, WHITE) self.surface.blit(line2, (200, 150)) line3 = font.render("or exit game with ESCAPE", True, WHITE) self.surface.blit(line3, (200, 200)) pygame.display.flip() def is_collision(self, xy, c): if abs(xy - c) <= self.ball.radius: return True return False def move_all(self): self.ball.walk() self.player1.walk(20) self.player2.walk(BACKGROUND_X - 28) def draw_all(self): self.background.draw() self.player1.draw(20) self.player2.draw(BACKGROUND_X - 28) self.ball.draw() self.display_scores() pygame.display.flip() def play(self): self.background.draw() self.move_all() if self.is_collision(10, self.ball.y) or self.is_collision(BACKGROUND_Y - 10, self.ball.y): self.ball.direction_y *= -1 if self.is_collision(10, self.ball.x): self.player2.score += 1 raise Exception("Point for 2") if self.is_collision(BACKGROUND_X - 10, self.ball.x): self.player1.score += 1 raise Exception("Point for 1") if self.is_collision(28, self.ball.x): if self.player1.y <= self.ball.y <= self.player1.y + SIZE * 3: self.ball.direction_x *= -1 if self.is_collision(BACKGROUND_X - 28, self.ball.x): if self.player2.y <= self.ball.y <= self.player2.y + SIZE * 3: self.ball.direction_x *= -1 self.display_scores() pygame.display.update() time.sleep(.01) def reset(self): self.player1 = Player(self.surface) self.player2 = Player(self.surface) self.ball = Ball(self.surface) def run(self): running = True pause = False while running: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: running = False if pause: if event.key == K_RETURN: self.reset() pause = False if event.key == K_SPACE: self.ball = Ball(self.surface) pause = False if not pause: if event.key == K_UP: self.player2.move_up() if event.key == K_DOWN: self.player2.move_down() if event.key == K_a: self.player1.move_up() if event.key == K_z: self.player1.move_down() elif event.type == QUIT: running = False try: if not pause: self.play() except Exception as e: self.show_game_over() pause = True if __name__ == '__main__': game = Game() game.run()
Swift
UTF-8
700
2.90625
3
[]
no_license
// // WindowRouter.swift // MovieDatabase // // Created by Oleksii Kalentiev on 11/28/18. // Copyright © 2018 Oleksii Kalentiev. All rights reserved. // import UIKit public protocol WindowRouterType: class { var window: UIWindow { get } init(window: UIWindow) func setRootModule(_ module: Presentable) } final public class WindowRouter: NSObject, WindowRouterType { public unowned let window: UIWindow public init(window: UIWindow) { self.window = window super.init() } public func setRootModule(_ module: Presentable) { let viewController = module.toPresentable() window.rootViewController = viewController window.makeKeyAndVisible() } }
SQL
UTF-8
1,067
2.609375
3
[]
no_license
/* Navicat MySQL Data Transfer Source Server : bendi Source Server Version : 50717 Source Host : 127.0.0.1:3306 Source Database : sqldemo Target Server Type : MYSQL Target Server Version : 50717 File Encoding : 65001 Date: 2017-10-20 09:19:12 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for demo -- ---------------------------- DROP TABLE IF EXISTS `demo`; CREATE TABLE `demo` ( `demo_id` int(11) NOT NULL AUTO_INCREMENT, `demo_one` varchar(255) DEFAULT NULL, `demo_two` varchar(255) DEFAULT NULL, PRIMARY KEY (`demo_id`) ) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8; -- ---------------------------- -- Records of demo -- ---------------------------- INSERT INTO `demo` VALUES ('8', '22', '44'); INSERT INTO `demo` VALUES ('10', '11', '22'); INSERT INTO `demo` VALUES ('11', '12', '30'); INSERT INTO `demo` VALUES ('12', '54', '66'); INSERT INTO `demo` VALUES ('13', '88', '99'); INSERT INTO `demo` VALUES ('14', '88', '99'); INSERT INTO `demo` VALUES ('15', '88', '99');
Java
UTF-8
1,757
2.171875
2
[]
no_license
package com.jju.yuxin.jokeformvp.bean; /** * ============================================================================= * Copyright (c) 2017 yuxin All rights reserved. * Packname com.jju.yuxin.jokeformvp.bean * Created by yuxin. * Created time 2017/6/4 0004 上午 9:36. * Version 1.0; * Describe : * History: * ============================================================================== */ public class ResultBean { /** * content : * hashId : 39F1B309144E7C378118EA1A66C569A2 * unixtime : 1494385240 * updatetime : 2017-05-10 11:00:40 */ private String content; private String hashId; private String unixtime; private String updatetime; public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getHashId() { return hashId; } public void setHashId(String hashId) { this.hashId = hashId; } public String getUnixtime() { return unixtime; } public void setUnixtime(String unixtime) { this.unixtime = unixtime; } public String getUpdatetime() { return updatetime; } public void setUpdatetime(String updatetime) { this.updatetime = updatetime; } @Override public String toString() { return "ResultBean{" + "content='" + content + '\'' + ", hashId='" + hashId + '\'' + ", unixtime='" + unixtime + '\'' + ", updatetime='" + updatetime + '\'' + '}'; } }
PHP
UTF-8
496
2.546875
3
[ "BSD-3-Clause" ]
permissive
<?php namespace app\modules\main\rbac; use yii\rbac\Rule; /** * Class CreateRule * Проверка прав на создание модели * @package app\modules\main\rbac * @author Churkin Anton <webadmin87@gmail.com> */ class CreateRule extends Rule { public $name = 'canCreate'; /** * @inheritdoc */ public function execute($user, $item, $params) { $perm = $params['model']->getPermission(); return $perm AND $perm->createModel($params['model']); } }
SQL
UTF-8
724
3.828125
4
[]
no_license
SELECT COUNT(first_name) FROM employees WHERE first_name is not null; SELECT COUNT(DISTINCT first_name) FROM employees; -- *** KEY *** 要注意 aggregate function 會 ignore NULL values unless told not to SELECT COUNT(*) FROM salaries WHERE salary >= 100000; show tables; SELECT COUNT(*) FROM dept_manager; SELECT count(*) FROM titles WHERE title IN ('Manager'); SELECT * FROM titles WHERE title LIKE 'Ass%' OR title like 'Senio%'; -- 但如果多個的時候還是用regex比較好用 SELECT * FROM titles WHERE title REGEXP 'Senior|^Ass' -- REGEXP 裡如果 單純是 senior 是會找到所有'包含' Senior的string
C#
UTF-8
3,809
2.546875
3
[ "MIT" ]
permissive
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; namespace Kaisa { public sealed class Archive : IEnumerable<ArchiveMember> { public ArchiveIndexV1 IndexV1 { get; } public ArchiveIndexV2? IndexV2 { get; } public ArchiveLongnames? Longnames { get; } public ImmutableArray<ArchiveMember> ObjectFiles { get; } public Archive(Stream stream) { string expectedFileSignature = "!<arch>\n"; if (stream.ReadAscii(expectedFileSignature.Length) != expectedFileSignature) { throw new ArgumentException("The library is malformed: Invalid file signature.", nameof(stream)); } ImmutableArray<ArchiveMember>.Builder filesBuilder = ImmutableArray.CreateBuilder<ArchiveMember>(); for (int i = 0; stream.Position < stream.Length; i++) { ArchiveMemberHeader header = new(stream); long expectedEnd = stream.Position + header.Size; if (i == 0) { if (header.Name != "/") { throw new ArgumentException("The library is malformed: Missing index file.", nameof(stream)); } IndexV1 = new ArchiveIndexV1(this, header, stream); } else if (i == 1 && header.Name == "/") { IndexV2 = new ArchiveIndexV2(this, header, stream); } else if (header.Name == "//") { if (Longnames is not null) { throw new ArgumentException("The library is malformed: Library contains multiple longnames files.", nameof(stream)); } Longnames = new ArchiveLongnames(this, header, stream); } else { ushort sig1 = stream.Read<ushort>(); ushort sig2 = stream.Read<ushort>(); if (ImportObjectHeader.IsImportObject(sig1, sig2)) { filesBuilder.Add(new ImportArchiveMember(this, header, new ImportObjectHeader(sig1, sig2, stream), stream)); } else { filesBuilder.Add(new CoffArchiveMember(this, header, new CoffHeader(sig1, sig2, stream), stream)); } } if (stream.Position != expectedEnd) { Debug.Fail($"File @ {i} {(stream.Position > expectedEnd ? "underran" : "overran")} its span!"); stream.Position = expectedEnd; } // If we're on an odd address, advance by 1 to get to an even address // "Each member header starts on the first even address after the end of the previous archive member." // (We do this here because the final file in the archive may have padding after it for the next file which doesn't exist.) if (stream.Position % 2 == 1) { stream.Position++; } } if (IndexV1 is null) { throw new ArgumentException("The library is malformed: Library is empty.", nameof(stream)); } filesBuilder.Capacity = filesBuilder.Count; ObjectFiles = filesBuilder.MoveToImmutable(); } public IEnumerator<ArchiveMember> GetEnumerator() { yield return IndexV1; if (IndexV2 is not null) { yield return IndexV2; } if (Longnames is not null) { yield return Longnames; } foreach (ArchiveMember objectFile in ObjectFiles) { yield return objectFile; } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } }
Java
UTF-8
405
2.828125
3
[]
no_license
package com.cadmus.multithreading.EvenOddThread; public class MainRunner { public static void main(String[] args) { Printer printer = new Printer(); Thread oddThread = new Thread(new TaskMaster(10, printer, true), "OddThread"); Thread evenThread = new Thread(new TaskMaster(10, printer, false), "EvenThread"); oddThread.start(); evenThread.start(); } }
Java
UTF-8
1,540
2.234375
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com; import com.globalalignment.AlignmentComparator; import com.globalalignment.ExperimentBean; import com.globalalignment.ResultBean; import com.model.AlignmentsReader; import com.model.scorematrix.ScoreMatrixReader; /** * * @author Yehia */ public class ControlUnit { ScoreMatrixReader smr = new ScoreMatrixReader(); AlignmentsReader ar = new AlignmentsReader(); ResultBean rb = new ResultBean(); @SuppressWarnings("CallToThreadDumpStack") public ResultBean handelExp(ExpBean exp) { exp = ar.read(exp.getAllignments(), exp.getStart(), exp.getEnd(), exp); //the controller will read the allignments try { exp = ar.creatProfileCharProfile(exp); rb.setProfile(exp.getProfile()); rb.setGapScore(exp.getGapScore()); } catch (Exception e) { e.printStackTrace(); } return rb; } @SuppressWarnings("CallToThreadDumpStack") public double getScore(ExpBean exp, char a, char b) { double score = 0; try { score = smr.getScore(a, b, exp.getScoreMatrixPath()); } catch (Exception e) { e.printStackTrace(); } return score; } public ResultBean compareAlignment(ExperimentBean exp) { AlignmentComparator ac = new AlignmentComparator(); ResultBean resultbean = ac.getResults(exp); return resultbean; } }
Swift
UTF-8
4,313
2.59375
3
[ "MIT" ]
permissive
// // ZInternet.Apple.swift // // Created by Tor Langballe on 11/15/18. // import Foundation class ZIPAddress { var ip4String = "127.0.0.1" func GetIp4String() -> String { return ip4String } init(ip4String:String = "") { self.ip4String = ip4String } } struct ZInternet { static func ResolveAddress(_ address:String) -> ZIPAddress { let ip = ZIPAddress(ip4String: "127.0.0.1") return ip } static func GetNetworkTrafficBytes(processId: Int64) -> Int64 { // https://stackoverflow.com/questions/7946699/iphone-data-usage-tracking-monitoring let info = DataUsage.getDataUsage() return Int64(info.lanReceived) + Int64(info.lanSent) + Int64(info.wirelessWanDataReceived) + Int64(info.wirelessWanDataSent) } static func PingAddressForLatency(_ ipAddress:ZIPAddress) -> Double? { return ZMath.Random1() + 0.1 } static func GetHardwareAddressAsString(_ address:UInt64) -> String { let str = ZStr.Format("%016lx", address) var out = "" for (i, c) in str.enumerated() { if i%2 == 0 && i > 0 { out += ":" } out += String(c) } return out } } class ZRateLimiter { let max:Int let durationSecs:Double var timeStamps = [ZTime]() init(max:Int, durationSecs:Double) { self.max = max self.durationSecs = durationSecs } func Add() { timeStamps.append(ZTime.Now()) } func IsExceded() -> Bool { timeStamps.removeIf { $0.Since() > durationSecs } return timeStamps.count >= max } } struct DataUsageInfo { var lanReceived: UInt64 = 0 var lanSent: UInt64 = 0 var wirelessWanDataReceived: UInt64 = 0 var wirelessWanDataSent: UInt64 = 0 mutating func updateInfoByAdding(_ info: DataUsageInfo) { lanSent += UInt64(info.lanSent) lanReceived += UInt64(info.lanReceived) wirelessWanDataSent += UInt64(info.wirelessWanDataSent) wirelessWanDataReceived += UInt64(info.wirelessWanDataReceived) } } class DataUsage { private static let wwanInterfacePrefix = "pdp_ip" private static let lanInterfacePrefix = "en" class func getDataUsage() -> DataUsageInfo { var ifaddr: UnsafeMutablePointer<ifaddrs>? var dataUsageInfo = DataUsageInfo() guard getifaddrs(&ifaddr) == 0 else { return dataUsageInfo } while let addr = ifaddr { guard let info = getDataUsageInfo(from: addr) else { ifaddr = addr.pointee.ifa_next continue } dataUsageInfo.updateInfoByAdding(info) ifaddr = addr.pointee.ifa_next } freeifaddrs(ifaddr) return dataUsageInfo } private class func getDataUsageInfo(from infoPointer: UnsafeMutablePointer<ifaddrs>) -> DataUsageInfo? { let pointer = infoPointer let name: String! = String(cString: pointer.pointee.ifa_name) let addr = pointer.pointee.ifa_addr.pointee guard addr.sa_family == UInt8(AF_LINK) else { return nil } return dataUsageInfo(from: pointer, name: name) } private class func dataUsageInfo(from pointer: UnsafeMutablePointer<ifaddrs>, name: String) -> DataUsageInfo { var networkData: UnsafeMutablePointer<if_data>? var dataUsageInfo = DataUsageInfo() if name.hasPrefix(lanInterfacePrefix) { networkData = unsafeBitCast(pointer.pointee.ifa_data, to: UnsafeMutablePointer<if_data>.self) if let data = networkData { dataUsageInfo.lanSent += UInt64(data.pointee.ifi_obytes) dataUsageInfo.lanReceived += UInt64(data.pointee.ifi_ibytes) } } else if name.hasPrefix(wwanInterfacePrefix) { networkData = unsafeBitCast(pointer.pointee.ifa_data, to: UnsafeMutablePointer<if_data>.self) if let data = networkData { dataUsageInfo.wirelessWanDataSent += UInt64(data.pointee.ifi_obytes) dataUsageInfo.wirelessWanDataReceived += UInt64(data.pointee.ifi_ibytes) } } return dataUsageInfo } }
C++
UTF-8
2,344
3.171875
3
[]
no_license
#include <string> #include <iostream> #include <fstream> #include "Player.h" #include "Team.h" using namespace std; Team::Team() { name = "City"; for (int i=0; i<25; i++) { players[i] = Player(); } } Team::Team(string s) { ifstream file(s); string f, l, con, pow, spe, glo, arm; int c, p, sp, g, a; getline (file, name, '\n' ); for (int i=0; file.good() && i<25; i++) { getline (file, f, ',' ); getline (file, l, ',' ); getline (file, con, ',' ); getline (file, pow, ',' ); getline (file, spe, ',' ); getline (file, glo, ',' ); getline (file, arm, '\n' ); c = stoi(con); p = stoi(pow); sp = stoi(spe); g = stoi(glo); a = stoi(arm); players[i] = Player(f,l,c,p,sp,g,a); } for (int i=0; i<9; i++) { order[i] = players[i]; pos[i] = players[i]; } } void Team::setOrder() { cout << *this; cout << "please select batting order" << endl; int temp; string s; for (int i=0; i<9; i++) { cout << "batting in slot number " << i+1 << ": "; cin >> s; if (!isdigit(s[0])) { cout << "sorry, please input a the player's number" << endl; i--; } else { temp = stoi(s); if (temp <1 || temp >25) { cout << "sorry, please input a the player's number (1-25) " << endl; i--; } else order[i] = players[temp-1]; } } } void Team::setPos() { cout << "please select postions" << endl; int temp; string s; for (int i=0; i<9; i++) { cout << "position number " << i+1 << ": "; cin >> s; if (!isdigit(s[0])) { cout << "sorry, please input a the player's batting position " << endl; i--; } else { temp = stoi(s); if (temp <1 || temp >9) { cout << "sorry, please input a the player's batting position (1-9) " << endl; i--; } else pos[i] = order[temp-1]; } } } void Team::printLineup() { for (int i=0; i<9; i++) { cout << i+1 << " " << order[i] << endl; } } void Team::printPos() { for (int i=0; i<9; i++) { cout << i+1 << " " << pos[i] << endl; } } string Team::getName() { return name; } Player Team::getBatter(int i) { return order[i]; } Player Team::getFielder(int i) { return pos[i]; } ostream &operator<<(ostream &out, const Team &t) { out << t.name<<endl;// << " " << p.last; for (int i=0; i< 25; i++) { cout << i+1 << " " << t.players[i] << endl; } return out; }
Java
UTF-8
341
2.328125
2
[]
no_license
package ee.netgroup.su.diagnostic.cli.disease; import java.util.List; public class DiseaseParser { public Disease getParsedDisease(List<String> rawDiseaseInfo) { Disease disease = new Disease(); disease.setName(rawDiseaseInfo.remove(0)); disease.setSymptoms(rawDiseaseInfo); return disease; } }
Markdown
UTF-8
1,829
3.484375
3
[]
no_license
## Что покажет приведенный ниже фрагмент кода? ```python s = 'abcdefg' print(s[2:5]) ``` ответ: `s = 'abcdefg' print(s[2:5])` ## Что покажет приведенный ниже фрагмент кода? ```python s = 'abcdefg' print(s[3:]) ``` ответ: `defg` ## Что покажет приведенный ниже фрагмент кода? ````python s = 'abcdefg' print(s[:3]) ```` ответ: `abc` ## Что покажет приведенный ниже фрагмент кода? ```python s = 'abcdefg' print(s[:]) ``` ответ: `abcdefg` ## Что покажет приведенный ниже фрагмент кода? ```python s = 'abcdefg' print(s[::-3]) ``` ответ: `gda` ## Дополните приведенный код, используя срезы, так чтобы он вывел первые 12 символов строки `s` ```python s = "In 2010, someone paid 10k Bitcoin for two pizzas." print(s[:12]) ``` ## Дополните приведенный код, используя срезы, так чтобы он вывел последние 9 символов строки `s`. ```python s = "In 2010, someone paid 10k Bitcoin for two pizzas." print(s[-9:]) ``` ## Дополните приведенный код, используя срезы, так чтобы он вывел каждый 7 символ строки `s` начиная от начала строки. ```python s = "In 2010, someone paid 10k Bitcoin for two pizzas." print(s[::7]) ``` ## Дополните приведенный код, используя срезы, так чтобы он вывел строку `s` в обратном порядке. ```python s = "In 2010, someone paid 10k Bitcoin for two pizzas." print(s[::-1]) ```
Python
UTF-8
343
3.4375
3
[]
no_license
import operator s=raw_input("Enter a sentence : ").split(" ") l1=dict() for i in range(0,len(s)): c=1 if(str(s[i]) not in l1.keys()): for j in range(i+1,len(s)): if(s[i]==s[j]): c=c+1 l1.update({str(s[i]):str(c)}) #print(str(s[i])+" "+str(c)) l= sorted(l1.items(), key=operator.itemgetter(0)) print(l)
Markdown
UTF-8
897
2.953125
3
[]
no_license
!SLIDE center # The Winner is *Javascript* ![Victory](VictoryFace2.png) !SLIDE center # *Jeff Atwood's Law* ## Any application that can be written in JavaScript, will eventually be written in JavaScript. !SLIDE bullets # Javascript ## Lisp in C clothing ![Lisp XKCD](xkcd-c224-lisp.jpg) !SLIDE # Y Combinator @@@ javaScript // Creates a recursive function // from one that isn't function Y(X) { return (function(procedure) { return X(function(arg) { return procedure(procedure)(arg); }); })(function(procedure) { return X(function(arg) { return procedure(procedure)(arg); }); }); } !SLIDE execute # Y Combinator (using) @@@ javaScript var factorial = Y(function(recurse) { return function(x) { return x == 0 ? 1 : x * recurse(x-1); }; }); result = factorial(6);
Markdown
UTF-8
4,712
2.65625
3
[ "MIT" ]
permissive
# Facebook-clone <!-- TABLE OF CONTENTS --> ## Table of Contents * [About the Project](#about-the-project) * [Built With](#built-with) * [Features](#features) * [Roadmap](#roadmap) * [Getting Started](#getting-started) * [Prerequisites](#prerequisites) * [Installation](#installation) * [Run](#run) * [License](#license) <!-- ABOUT THE PROJECT --> ## About The Project ![screenshot.png] A friend of mine gave me a challenge, "let's see who will make the best facebook clone in one weeks." Of course I accepted the challenge. So this is my MVP Facebook-Clone made in approximately one week. The Project was fun to do and made me combine my previous knowledge about image uploading, APIs, websocket and react into a working project. Am I proud of my end product? Yes, I am. ...Well not so proud about all the design, but I'm overall happy about how it turned out. ## What I learned - React's new useState and useHooks makes it faster and much more pleasant to make components. - CSS is still hard, Bootstrap saves my day everytime, but I have to practice UI-design - Small components makes it easy to reuse, but too small components makes it hard to integrate logic. - Streaming data from user to database through sharp image processor is still hard, but I'm getting the hang of it. - NodeJS is still treating me good, but I should make my next project in .net Core to expand my horizon. ### Built With * [React](https://reactjs.org/) - Starting to love React now <3 * [React-Router](https://reacttraining.com/react-router/) * [React-Bootstrap](https://react-bootstrap.github.io/) - Got to make it kinda pretty * [Node](https://nodejs.org/en/) - So fast to build backends, and used it for a long time * [Express](https://expressjs.com/) - REST API * [Socket.io](https://socket.io/) - Live chat messages * [MariaDB](https://mariadb.org/) - For all relational text data * [MongoDB](https://mongodb.org/) - To emulate a s3 bucket or similar, used for images. I chosed to save in database instead of on filesystem because I think that is more realistic in for future products, where you need backups and or saves the file in Azure Bucket or s3 storage or whatever those services are called. ## Features - Real time chat with socket.io. With annoying popup chat when friends message you. ![chat.gif] - Posts with multiple images ![posts.gif] - Liking, adding friends, multiple chat windows etc. - Custom profile picture - Images are processed with sharpjs to make large, medium and small copies in mongodb gridFsBucket - Dedicated space to ads, have to make the investors happy. - Passwords are encrypted with bcrypt of course. ## roadmap Things that I will add if I decide to spend more time on this: - [ ] Group messages - [ ] Friend requests, now the friend requests are automatically added - [x] Automatically open chat window when a friend sends message to you - [ ] Notify user on new posts, likes, comments - [ ] Comments on posts, needs front-end <!-- GETTING STARTED --> ## Getting Started ### Prerequisites * [NodeJS](https://nodejs.org/en/) * [MariaDB](https://downloads.mariadb.org/) or similar sql database * [MongoDB](https://www.mongodb.com/download-center/community) for storing images ### Installation 1. Clone the repo ```sh git clone https://github.com/mathiash98/facebook-clone.git ``` 3. Install NPM packages ```sh cd ./node-backend npm install cd .. cd ./react-client npm install ``` 4. Edit `config.js` to suit you example: ```JS module.exports = { db: { mariadb: { host: '127.0.0.1', user: 'root', password: '', database: 'facebook-clone' }, mongodb: { uri: 'mongodb://localhost:27017', dbName: 'facebook-clone' } }, jwt: { // used for encrypting and decoding the jwt-tokens, // make it a long an difficult string secret: 'Sup3rDup3rS3cr3tP@ssw0rdF0rJWTTôk£nAuthênticãtiõns' }, port: { development: 8888 } }; ``` 5. Run `./facebook-clone.sql` in your sql database to setup tables. 6. Procceed to [Run](#run) ### Run This is for development 1. Start mongodb and mariadb 2. start node-backend and react-client ```sh cd ./node-backend nodemon index ``` ```sh cd ./react-client npm start ``` 3. Make some users, search for the users you made, add them as friend and start chatting and posting. ### Extras #### Diagram for MariaDB ![er-diagram.png] <!-- LICENSE --> ## License Distributed under the MIT License. See `LICENSE` for more information. <!-- MARKDOWN LINKS & IMAGES --> [screenshot.png]: ./screenshot.png [chat.gif]: ./chat.gif [posts.gif]: ./posts.gif [er-diagram.png]: ./er-diagram.png
JavaScript
UTF-8
2,388
3.953125
4
[]
no_license
function zadanie2() { var tab = []; for (var i = 1; i <= 100000; i++) { //console.log("Nasza liczba to:",i); var x = i; var liczba = x % 10; var sum = 0 while (x>0) { sum += liczba; if ((i % liczba) != 0) {break;} if (liczba == 0) {break;} //Zakładam że nie dzielimy przez zero x = (x-liczba)/10 liczba = x % 10 } if (x==0) { if ((i % sum) == 0) { tab.push(i);} } } return tab; //return tab.toString(); } function zadanie3() { var primes = [2] for (var i=3; i<=100000; i++) { for (j=0; j<=primes.length; j++) { if (i%primes[j] == 0) {break;} if (j == primes.length) {primes.push(i); break;} } } return 'Ilość primes: ' + primes.length //return primes; } function fib_rek(n) { if (n == 0) { return 1; } if (n == 1) { return 1; } else { return fib_rek(n-2) + fib_rek(n-1); } } function fib_iter(n) { if (n == 0) { return 1; } if (n == 1) { return 1; } else { a = 1; b = 1; for (var i = 2; i<=n; i++) { c = a+b; a=b; b=c; } return c; } } function fib_rekord(n, time_rek, time_iter, zgodny) { this.n = n; this.rekurencyjne = time_rek; this.iterowane = time_iter; this.zgodnosc = zgodny; } function fib_table() { var tab = [10,15,20,25,30,35,40,41,42] for (var i=0; i<tab.length; i++) { //console.log("n =",i); //console.time("Czas dla rekurencyjnej"); var t1 = Date.now(); var a = fib_rek(tab[i]); var t2 = Date.now(); var t_1 = t2-t1 //console.timeEnd("Czas dla rekurencyjnej"); //console.time("Czas dla iteracyjnej"); var t1 = Date.now(); var b = fib_iter(tab[i]); var t2 = Date.now(); var t_2 = t2-t1 //console.timeEnd("Czas dla iteracyjnej"); var rekord = new fib_rekord(tab[i], t_1/1000, t_2/1000, a==b); tab[i] = rekord; //console.log("\n"); } console.table(tab); } // TESTY console.log('Koniec zadania 2:\n', zadanie2(), "\n"); console.log('Koniec zadania 3:\n', zadanie3(), "\n"); console.log('Koniec zadania 5:'); fib_table()
Python
UTF-8
115
3.375
3
[]
no_license
n = input() cnt = n.count('4') + n.count('7') if(cnt == 4 or cnt == 7): print("YES") else: print("NO")
Markdown
UTF-8
4,311
3.53125
4
[]
no_license
--- title: Retrieve a Fragment from a ViewPager --- ## 问题描述 ## 我们有一个ViewPager 里面有三个Fragment > * Fragment1 > * Fragment2 > * Fragment3 如果我们要在获取其中一个**Fragment**实例要怎么做? ### 一般情况下我们会这么做: ### 之前我的写法: ```java private List<Fragment> mFragments = new ArrayList<>(); private List<String> mFragmentTitles = new ArrayList<>(); private class TabIndexAdapter extends FragmentPagerAdapter { public TabIndexAdapter(FragmentManager fm) { super(fm); mFragments.clear(); mFragmentTitles.clear(); } public void addFragment(android.support.v4.app.Fragment fragment, String title) { mFragments.add(fragment); mFragmentTitles.add(title); } @Override public android.support.v4.app.Fragment getItem(int position) { return mFragments.get(position); } @Override public int getCount() { return mFragments.size(); } @Override public CharSequence getPageTitle(int position) { return mFragmentTitles.get(position); } } TabIndexAdapter mAdp = new TabIndexAdapter(getSupportFragmentManager()); mAdp.addFragment(new LessonSpeakFragment(), getString(R.string.Speak)); mAdp.addFragment(new LessonReadFragment(), getString(R.string.Read)); mAdp.addFragment(new LessonListenFragment(), getString(R.string.Listen)); mAdp.addFragment(new LessonDictationFragment(), getString(R.string.Dictation)); viewPager.setAdapter(mAdp); ``` 然后这么获取: ```java LessonSpeakFragment = (LessonSpeakFragment)mFragments.get(0); ``` 顿时觉得我好聪明啊 可是这么写是有问题的!!! > 因为我们没有考虑内存回收的问题 > 也就是说当当前页面被系统意外回收然后再恢复的时候 > 这个时候需要注意了,因为此时我们mFragments会重新创建,添加进去新的Fragment实例 > 但是!这个时候FragmentPagerAdapter 会获取之前自动保存的Fragment实例,而不是重新getItem()! > 所以问题就来,这个时候按照之前我的方法,得到的和现在展示的Fragment就不是同一个实例了! ## 解决方案 ## ### 一个比较简单的方法 :ViewPager.instantiateItem() ### ### 另一个可行的方法 :重写adapter ### ```java private class TabIndexAdapter extends FragmentPagerAdapter { private Class[] fragmentClasses = new Class[]{ PodLevelFragment.class, PodCategoryFragment.class, PodAllFragment.class}; private int[] fragmetTitles = new int[]{ R.string.LEVEL, R.string.CATEGORY, R.string.PODCAST_ALL }; private SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>(); public Fragment getRegisteredFragment(int position) { return registeredFragments.get(position); } @Override public Object instantiateItem(ViewGroup container, int position) { Fragment fragment = (Fragment) super.instantiateItem(container, position); registeredFragments.put(position, fragment); return fragment; } @Override public void destroyItem(ViewGroup container, int position, Object object) { registeredFragments.remove(position); super.destroyItem(container, position, object); } public TabIndexAdapter(FragmentManager fm) { super(fm); } @Override public android.support.v4.app.Fragment getItem(int position) { Log.i("TabLearnPage", "getItem : "+position); try{ return (android.support.v4.app.Fragment)fragmentClasses[position].newInstance(); }catch(Exception e){ throw new RuntimeException(e); } } @Override public int getCount() { return fragmentClasses.length; } @Override public CharSequence getPageTitle(int position) { return getString(fragmetTitles[position]); } } ``` 直接调用adapter 的 **getRegisteredFragment()**方法就Ok啦!
Java
UTF-8
987
2.890625
3
[ "Apache-2.0" ]
permissive
package ru.nik66.bot; import org.junit.Test; import static org.junit.Assert.assertThat; import static org.hamcrest.core.Is.is; public class DummyBotTest { @Test public void whenAskHiBotThenAnswerHiSmartAss() throws Exception { DummyBot bot = new DummyBot(); String expected = "Hi, smart ass."; String actual = bot.answer("Hi, bot"); assertThat(actual, is(expected)); } @Test public void whenAskByeThenAnswerSeeYouLater() throws Exception { DummyBot bot = new DummyBot(); String expected = "See you later."; String actual = bot.answer("bye"); assertThat(actual, is(expected)); } @Test public void whenAskSomethingThenAnsewrIDontKnow() throws Exception { DummyBot bot = new DummyBot(); String expected = "I don't know what you want! Please, ask another question."; String actual = bot.answer("something"); assertThat(actual, is(expected)); } }
Python
UTF-8
1,629
3.59375
4
[]
no_license
""" Basic class to visualize 3D images with numpy and matplotlib """ import numpy as np class SliceViewer(object): def __init__(self, ax, *X, **kwargs): """ Parameters ---------- self: type description ax: matplotlib.Axes axes where to show the images X: np.ndarray image, or series of images kwargs: dict arguments passed onto the plt.imshow function """ self.ax = np.array([ax]).flatten() self.ax[0].set_title('use scroll wheel to navigate images') self.X = X self.ind = 0 self.slices = X[0].shape[0] self.im = [] for i in range(len(self.ax)): self.im.append(self.ax[i].imshow(self.X[i][self.ind, ...], **kwargs)) self.update() def onscroll(self, event): """ Change slice number on mouse scroll event. Parameters ---------- self: type description event: matplotlib.MouseEvent the current event """ if event.button == 'up': self.ind = (self.ind + 1) % self.slices else: self.ind = (self.ind - 1) % self.slices self.update() def update(self): """ Update the image after event. Parameters ---------- self: type description """ for i in range(len(self.ax)): self.im[i].set_data(self.X[i][self.ind, ...]) self.ax[i].set_ylabel('slice %s' % self.ind) self.im[i].axes.figure.canvas.draw()
Python
UTF-8
963
2.5625
3
[]
no_license
from collections import defaultdict def solve(): n=int(input()) l=list(map(int,input().split())) o,e,r,lst=[],[],[],[] for i in range(len(l)): if l[i]&1: o.append(i) else: e.append(i) if len(o)&1: r.extend([o[0],e[0]]) else: if len(e): r.extend([e[0],e[1]]) else: r.extend([o[0],o[1]]) s=defaultdict(lambda:False) for i in range(2*n): if i==r[0] or i==r[1]: continue if s[i]: continue for j in range(i+1,2*n): if j==r[0] or j==r[1]: continue if s[j]: continue if (l[i]&1 and l[j]&1) or (l[i]%2==0 and l[j]%2==0): s[i]=True s[j]=True lst.append((i+1,j+1)) break for i,j in lst: print(i,j) for _ in range(int(input())): solve()
Python
UTF-8
762
3.703125
4
[]
no_license
html = """<table> <tbody> <tr> <th colspan="8"> <span> <a href="/link">Table Title</a> </span> </th> </tr> <tr> <th>Info1</th> <th>Info2</th> <th>Info3</th> <th>Info4</th> <th>Info5</th> </tr> <tr> <td>Value1</td> <td>Value2</td> <td>Value3</td> <td>Value4</td> <td>Value5</td> </tr> </tbody> </table>""" from bs4 import BeautifulSoup soup = BeautifulSoup(html, 'lxml') value = "Value4" trs = soup.find_all('tr') for td in trs: # print(td.text.strip()) if td.text.strip() == value: print(td)
Java
UTF-8
4,425
2.578125
3
[]
no_license
package gui; import java.util.Enumeration; import javax.swing.AbstractButton; import javax.swing.ButtonGroup; import rome2rio.Rome2Rio; public class GuiUtils { public GuiUtils() { } public static String getSelectedButtonText(ButtonGroup buttonGroup) { for (Enumeration<AbstractButton> buttons = buttonGroup.getElements(); buttons.hasMoreElements();) { AbstractButton button = buttons.nextElement(); if (button.isSelected()) { return button.getText(); } } return null; } public static void populateLocationsAndRoutes(Rome2Rio r2r) { r2r.changeToAdmin("default"); r2r.addLocation("Boston", "EUA", 42.35000, -71.06667); // 42°21′N 71°04′W r2r.addLocation("Cape Town", "South Africa", -33.93333, 18.41667); // 33°56′S 18°25′E r2r.addLocation("Pretoria", "South Africa", -25.75000, 28.18333); // 25°45′S 28°11′E r2r.addLocation("Geneva", "Switzerland", 46.20000, 6.15000); // 46°12′N 6°09′E r2r.addLocation("Zagreb", "Croatia", 45.81667, 15.98333); // 45°49′N 15°59′E r2r.addLocation("Messina", "Italy", 38.18333, 15.55000); // 38°11′N 15°33′E r2r.addLocation("Detroit", "EUA", 82.50000, -62.33333); // 82°30′N 62°20′W r2r.addLocation("São Paulo", "Brazil", -23.55000, -46.63333); // 23°33′S 46°38′W r2r.addLocation("Newcastle", "UK", 54.96667, -1.61667); // 54°58′N 1°37′W r2r.addLocation("Nantes", "France", 47.21667, -1.55000); // 47°13′N 1°33′W r2r.addLocation("Leipzig", "Germany", 51.33333, 12.38333); // 51°20′N 12°23′E r2r.addLocation("Prague", "Czech Republic", 50.08333, 14.41667); // 50°05′N 14°25′E r2r.addLocation("Birmingham", "UK", 52.48333, -1.90000); // 52°29′N 1°54′W r2r.addLocation("Sofia", "Bulgaria", 42.70000, 23.33333); // 42°42′N 23°20′E r2r.addLocation("Rotterdam", "Netherlands", 51.93333, 4.48333); // 51°56′N 4°29′E r2r.addLocation("Cork", "Ireland", 51.90000, -8.46667); // 51°54′N 8°28′W r2r.addLocation("Milwaukee", "EUA", 43.05000, -87.95000); // 43°03′N 87°57′W r2r.addLocation("Ponta Delgada", "Portugal", 37.81667, -25.75000); // 37°49′N 25°45′W r2r.addLocation("Rome", "Italy", 41.90000, 12.50000); // 41°54′N 12°30′E r2r.addLocation("Moscow", "Russia", 55.75000, 37.61667); // 55°45′N 37°37′E r2r.addLocation("Göteborg", "Sweden", 57.70000, 11.96667); // 57°42′N 11°58′E r2r.addLocation("Vancouver", "Canada", 49.25000, -123.10000); // 49°15′N 123°06′W r2r.addLocation("Las Vegas", "EUA", 36.18333, -115.13333); // 36°11′N 115°08′W r2r.addLocation("Beirut", "Lebanon", 33.88333, 35.51667); // 33°53′N 35°31′E r2r.addWayBetweenLocations("Boston", "Cape Town", rome2rio.quotes.PLANEQuote.getInstance(), 12, 123, 400); r2r.addWayBetweenLocations("Boston", "Vancouver", rome2rio.quotes.PLANEQuote.getInstance(), 12, 123, 440); r2r.addWayBetweenLocations("Vancouver", "Boston", rome2rio.quotes.PLANEQuote.getInstance(), 12, 123, 450); r2r.addWayBetweenLocations("Newcastle", "Birmingham", rome2rio.quotes.CARQuote.getInstance(), 12, 123, 20); r2r.addWayBetweenLocations("Las Vegas", "Boston", rome2rio.quotes.CARQuote.getInstance(), 12, 123, 400); r2r.addWayBetweenLocations("Detroit", "Boston", rome2rio.quotes.CARQuote.getInstance(), 12, 123, 400); r2r.addWayBetweenLocations("Boston", "Detroit", rome2rio.quotes.TRAINQuote.getInstance(), 12, 123, 440); r2r.addWayBetweenLocations("Milwaukee", "Boston", rome2rio.quotes.PLANEQuote.getInstance(), 12, 123, 450); r2r.addWayBetweenLocations("Newcastle", "Cork", rome2rio.quotes.FERRYQuote.getInstance(), 12, 123, 20); r2r.addNewTransportationType("Newcastle", "Cork", rome2rio.quotes.FERRYQuote.getInstance(), 12, 123, 27); r2r.addNewTransportationType("Newcastle", "Cork", rome2rio.quotes.BUSQuote.getInstance(), 12, 123, 50); r2r.addWayBetweenLocations("Pretoria", "Boston", rome2rio.quotes.BUSQuote.getInstance(), 2, 120, 5); r2r.addNewTransportationType("Boston", "Cape Town", rome2rio.quotes.BUSQuote.getInstance(), 2, 130, 5); r2r.addWayBetweenLocations("Pretoria", "Cape Town", rome2rio.quotes.BUSQuote.getInstance(), 2, 12, 35); r2r.addNewTransportationType("Pretoria", "Cape Town", rome2rio.quotes.TRAINQuote.getInstance(), 1, 12, 60); r2r.addNewTransportationType("Pretoria", "Cape Town", rome2rio.quotes.CARQuote.getInstance(), 1, 12, 70); r2r.changeToClient(); } }
Python
UTF-8
3,625
2.859375
3
[ "MIT" ]
permissive
import requests from bs4 import BeautifulSoup print() Movie_Content="" Movie_Content+="\n" #request the IMDB Movie search Page content page= requests.get("https://www.imdb.com/find?q="+inp+"&ref_=nv_sr_sm") soup = BeautifulSoup(page.content,'html.parser') #Fetch the Link to IMDB Movie Page soup=soup.find(class_='result_text').find('a').get('href') #IMDB Movie page Link imdb_movie_link="https://www.imdb.com/"+soup #Fetch Movie Page Content imdbpage=requests.get(imdb_movie_link) soup=BeautifulSoup(imdbpage.content,'html.parser') #movie_name Correct_Name = soup.find(class_="title_wrapper").find_all('h1')[0].getText().strip() print(Correct_Name+"\n") Movie_Content+=Correct_Name+"\n\n" #Fetch the Rating Rating= soup.find(class_="ratingValue") if(Rating==None): Movie_Content+="Not Rated\n\n" print("Not Rated\n") else: movie_rating = Rating.find('span').getText() #print(find_rating_class.prettify()) Movie_Content+="Rating : "+movie_rating+"/10\n\n" print("Rating : "+movie_rating+"/10\n") #Genre of the Movie Genre = soup.find(class_="subtext").find_all('a') #print(type(Genre)) #print(len(Genre)) Movie_Content+=("Genre : ") print("Genre :",end=" ") for index in range(0,len(Genre)-1): Movie_Content+=(Genre[index].getText()+" , ") print(Genre[index].getText(),end=" , ") Movie_Content+="\n\n" print("\n") #release year and date #release_year = soup.find(id="titleYear").find('a').getText() #print("Release Year : "+release_year) Movie_Content+= ("Release date : "+Genre[len(Genre)-1].getText().strip()+"\n\n") print("Release date : "+Genre[len(Genre)-1].getText().strip()+"\n") if(soup.find(class_="subtext").find_all('time')==[]): Movie_Content+="Time duration not avialable yet.\n\n" print("Time duration not avialable yet.\n") else: Run_Time = soup.find(class_="subtext").find_all('time')[0].getText().strip() Movie_Content+="Time Duration : "+Run_Time+"\n\n" print("Time Duration : "+Run_Time+"\n") #Gist of the Movie Movie_Content+=" Gist: " print("Gist :",end=" ") Gist= soup.find(class_="summary_text").getText().strip() print(Gist+"\n\n") Movie_Content+=Gist+"\n\n" #fetch director , writers and cast if(soup.find(class_="credit_summary_item").find('a')==None): Movie_Content+="Director data not avialable\n\n" print("Director data not avialable\n") else: director_name = soup.find(class_="credit_summary_item").find('a').getText().strip() Movie_Content+="Director : "+director_name+"\n\n" print("Director : "+director_name+"\n") if(len(soup.find_all(class_="credit_summary_item")) < 2): Movie_Content+="Writers data not avialable\n\n" print("Writers data not avialable\n") else: writers = soup.find_all(class_="credit_summary_item")[1].find_all('a') Movie_Content+="\nWriters : " print("Writers :",end=" ") for index in writers: Movie_Content+=index.getText().strip()+" , " print(index.getText().strip(), end=" , ") Movie_Content+="\n \n" print('\n') if(len(soup.find_all(class_="credit_summary_item")) < 3): Movie_Content+="StarCast data not avialable\n\n" print("StarCast data not avialable\n") else: starcast_names = soup.find_all(class_="credit_summary_item")[2].find_all('a') Movie_Content+="StarCast : " print("StarCast :",end=" ") for names in starcast_names: Movie_Content+=names.getText().strip()+" , " print(names.getText().strip(), end=" , ") Movie_Content+="\n\n" print('\n')
Java
UTF-8
1,695
2.109375
2
[]
no_license
package com.ptaas.controller; import java.util.Collection; import javax.validation.constraints.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import com.ptaas.repository.LoadGenerator; import com.ptaas.service.LoadGeneratorSvc; @Controller @RequestMapping("/loadgenerators") public class LoadGeneratorController { @Autowired private LoadGeneratorSvc loadGeneratorSvc; @RequestMapping(method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE,params="query=all") @ResponseBody public Collection<LoadGenerator> getAllLoadGenerators() { return loadGeneratorSvc.getAllLoadGenerators(); } @RequestMapping(method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE,params="query=available") @ResponseBody public Collection<LoadGenerator> getAllAvailableLoadGenerators() { return loadGeneratorSvc.getAllAvailableLgs(); } @RequestMapping(method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_VALUE,params="query=one") @ResponseBody public LoadGenerator getOneAvailableLoadGenerator() { return loadGeneratorSvc.getOneAvailableLg(); } @RequestMapping(method=RequestMethod.GET,value="/{name}", produces=MediaType.APPLICATION_JSON_VALUE) @ResponseBody public LoadGenerator getLgDetails(@NotNull @PathVariable String name) { return loadGeneratorSvc.getAvailability(name); } }
PHP
UTF-8
1,188
2.59375
3
[ "BSD-3-Clause" ]
permissive
<?php namespace common\models; use frontend\modules\store\models\StoreProductSize; use Yii; /** * This is the model class for table "{{%store_order_product}}". * * @property integer $id * @property integer $order_id * @property integer $product_id * @property integer $size_id * @property integer $cert_id * @property integer $qnt * @property string $sku * * @property StoreOrder $order * @property StoreProduct $product * @property StoreProductSize $size */ class StoreOrderProduct extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return '{{%store_order_product}}'; } /** * @return \yii\db\ActiveQuery */ public function getOrder() { return $this->hasOne(StoreOrder::className(), ['id' => 'order_id']); } /** * @return \yii\db\ActiveQuery */ public function getProduct() { return $this->hasOne(StoreProduct::className(), ['id' => 'product_id']); } /** * @return \yii\db\ActiveQuery */ public function getSize() { return $this->hasOne(StoreProductSize::className(), ['id' => 'size_id']); } }
JavaScript
UTF-8
4,443
2.515625
3
[]
no_license
var pool = require('./index'); var Topic = {}; Topic.getAll = (courseID, callback) => { pool.getConnection((err, connection) => { if (err) { console.log(err); return; } //?表示等待填充的数据,这种方式可以防止MYSQL注入攻击 var query = 'SELECT * from user, topic WHERE course_id = ? AND topic.creator_id = user.id ORDER BY last_reply_time'; //第二个参数就是一个填充数据的数组 connection.query(query, [courseID], (err, results, fields) => { //results是数据库操作返回的结果,是一个数组! if (err) { console.log(err); results = []; } connection.release(); callback(results); //由于查询数据库是异步的,所以用回调函数的方式,拿到结果之后再作为参数返回 }); }) }; Topic.getByID = (topicID, callback) => { pool.getConnection((err, connection) => { if (err) { console.log(err); return; } var query = 'SELECT * FROM user, topic WHERE topic.id = ? AND user.id = topic.creator_id'; connection.query(query, [topicID], (err, results, fields) => { if (err) { console.log(err); results = []; } callback(results[0]); connection.release(); }); }); }; Topic.getReply = (topicID, callback) => { pool.getConnection((err, connection) => { if (err) { console.log(err); return; } var query = 'SELECT * FROM topic_reply, user WHERE topic_reply.creator_id = user.id AND topic_id = ?'; connection.query(query, [topicID], (err, results, fields) => { if (err) { console.log(err); results = []; } connection.release(); callback(results); }) }) } Topic.add = (data, callback) => { pool.getConnection((err, connection) => { if (err) { console.log(err); return; } var query = 'INSERT INTO topic(creator_id, course_id, post_time, title, content, anonymity) \ VALUES (?, ?, NOW(), ?, ?, ?)'; connection.query( query, [data.creatorID, data.courseID, data.title, data.content, data.anonymity], (err, results, fields) => { if (err) { console.log(err); results = []; } connection.release(); //如果插入数据有自增的primery key,可以用results.insertId拿到值 //这里results.insertId就是reply_id callback(results.insertId); } ) }) } Topic.addReply = (data, callback) => { pool.getConnection((err, connection) => { if (err) { console.log(err); return; } var query = 'INSERT INTO topic_reply(topic_id, creator_id, post_time, content, anonymity) \ VALUES (?, ?, NOW(), ?, ?)'; connection.query( query, [data.topicID, data.creatorID, data.content, data.anoymity, data.topicID], (err, results, fields) => { if (err) { console.log(err); results = []; } callback(results.insertId); connection.query( 'UPDATE topic SET reply_num = reply_num + 1 WHERE id = ?', [data.topicID], (err, results, fields) => { if (err) { console.log(err); } connection.release(); } ) } ) }) } Topic.delete = (topicID, callback) => { pool.getConnection((err, connection) => { var query = 'DELETE FROM topic WHERE id = ?'; connection.query(query, [topicID], (err, result, fields) => { if (err) { console.log(err); } else if (result.affectedRow != 0) { callback(true); } else { callback(false); } connection.release(); }) }); } module.exports = Topic;
PHP
UTF-8
1,425
2.625
3
[ "MIT" ]
permissive
<?php use Illuminate\Support\Facades\Route; use App\Http\Controllers\WelcomeController; use App\Http\Controllers\UserController; use App\Http\Controllers\ContactController; /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | */ Route::get('/', function () { return view('welcome'); }); Route::get('{n}', function($n) { return 'Je suis la page ' . $n . ' !'; })->where('n','[1-3]'); Route::get('view1',function(){ return view('view1'); }); /* * Le renvoi des views à partir de ce fichier des routes n'est pas la bonne manière * Il faut plutot rediriger la requete vers le controlleur qui se chargera * de rendre le view à l'utilisateur * * L'exemple ci-dessous redirige la requette 'localhost:8000/home' vers le * controleur 'WelcomeController' qui va rendre la view */ Route::get('home', [WelcomeController::class, 'showHomePage']); Route::get('user', [UserController::class, 'create']); Route::post('user', [UserController::class, 'store']); Route::get('contact', [ContactController::class, 'create']); Route::post('contact', [ContactController::class, 'store']);
Python
UTF-8
2,456
3.4375
3
[]
no_license
import random from classmodule import Information def my_function(text_to_display): print('text from my_function :: {}'.format(text_to_display)) def random_events(person_info): scenarios = [{"event": "You got hit by a school bus, oh shit! You're down ", "$amount" : -8000 , "health" : -50, "mental_health" : -20, "grades" : 1.0}, {"event": "Wow! You went to all of the office hours and made dean's list this semester! You're up ", "$amount" : 0 , "health" : 10, "mental_health" : 15, "grades" : 1.3}, {"event": "Look at you, you're in L-O-V-E. Goddamn, you've never been this happy in your life!!\ You even put aside your schoolwork to spend time with that special someone. Your S.O had a birthday last weekend\ and DAMN you showed up with the party planning...using your own pocket money.", "$amount" : -50 , "health" : 20, "mental_health" : 25, "grades" : 0.85}, {"event": "HOLY SHIT YOU HAVE BEEN AN AMAZING STUDENT. You've been involved\ in extracurriculars and scored yourself an internship at Amazon! Go you.", "$amount" : 3000 , "health" : 10, "mental_health" : 15, "grades" : 1.5}, {"event": "YOU ate Top Ramen for the past 3 weeks and you feel sick all the time.", "$amount": -10, "health" : -20 , "mental_health": -15, "grades" : 0.84}, {"event": "You decided to go out partying all weekend instead of studying for you exam on Monday you moron", "$amount": -50, "health" : 10, "mental_health": 10, "grades" : -2.0}, {"event": "You decided to take a pot brownie from your friend, you fell asleep for 3 days, ate all of your food and missed and eam. Good going dumbass.", "$amount":0,"health" : -50, "mental_health": 10, "grades":-1.0}, { "event": "** ALARM ** ALARM ** .... You slept too late before an exam and had to drive to campus and park in a no-parking zone. Your car was towed.", "$amount": -200, "health": 0, "mental_health": -10, "grades": 0.7 } ] event = random.choice(scenarios) person_info.changeCash(event["$amount"]) person_info.changeHealth(event["health"],event["mental_health"]) person_info.changeGrade(event["grades"]) event_num = scenarios.index(event) print(event["event"],event["$amount"]) print("health :",person_info.health,"\nmental health :",person_info.mental_health,"\ngrades : ",person_info.grades, "\nmoney : ",person_info.money) return event_num
Java
UTF-8
316
2.15625
2
[]
no_license
package com.example.huangruqi.pattern.facade.sample; /** * @data: 2019/2/20 11:22 * @author: 黄汝琪 * @Email: * @Description: */ public class Client { public static void main(String[] args) { MobilePhone phone = new MobilePhone(); phone.takePicture(); phone.videoChat(); } }
Java
UTF-8
409
1.914063
2
[]
no_license
package com.cloudtravel.cloudtravelandroid.main.item; import lombok.Data; @Data public class PlaceRcmdItem { private String title; private String city; private int imageId; private String url; public PlaceRcmdItem(String title, String city, int imageId, String url) { this.title = title; this.city = city; this.imageId = imageId; this.url = url; } }
C++
GB18030
13,592
2.53125
3
[]
no_license
/* * Copyright 2001 LinkAge Co.,Ltd. Inc. All Rights Reversed */ /*********************************************************************************/ /*** Name : CONFIG.CPP ***/ /*** ***/ /*** Description : дļģ鹦ܺ ***/ /*** ***/ /*** Author : ***/ /*** Upate : ***/ /*** ***/ /*** Begin Time : 2001/11/03 ***/ /*** ***/ /*** Last Change Time : 2001/11/09 ***/ /*** ***/ /*********************************************************************************/ //modify:Ҫ޸˴˹ģͳĻͻ, bad smell. /*********************************************************************************/ /*** Class C_Config user include Compile body ***/ /*** Config encapsulate all methods(functions) ***/ /*********************************************************************************/ #include "rw_config.h" C_Config::C_Config() { iWriteFlag = 0; memset(chFileTemp, 0, sizeof(chFileTemp)); } /* * Function Name :Trim * Description :ȥַҵĿո * Input Param :Ҫȥոַ * Returns : * complete :2001/11/20 */ void C_Config::Trim(char * String) { char *Position = String; /*ҵһǿոλ*/ while(isspace((unsigned char)*Position)) { Position++; } /*Ϊһմ˳*/ if (*Position == '\0') { *String = '\0'; return; } /*ȥǰĿո*/ while(*Position) { *String = *Position; String++; Position++; } /*ȥĿո*/ do { *String = '\0'; String--; }while(isspace((unsigned char)*String)); } /* * Function Name : GetLine * Description : ļлһе * Input Param : * Line -----------> һеݣַ * Fd -----------> 򿪵ļ * Returns :õֽ. * complete :2001/11/09 */ int C_Config::GetLine(int Fd,char *Line) { int iByteRead = 0; for(;;) { if(read(Fd,Line,1) <= 0) { break; } iByteRead ++; if (*Line == '\n') { break; } Line++; } *Line='\0'; return iByteRead; } /* * Function Name : PutLine * Description : ļдһе * Input Param : * Line -----------> һеݣַ * Fd -----------> 򿪵ļ * Returns :дֽ. * complete :2001/11/09 */ int C_Config::PutLine(int Fd,char *Line) { char chLine[LINELENGTH]; sprintf(chLine, "%s\n", Line); return write(Fd,chLine,strlen(chLine)); } /* * Function Name : SetLockStatus * Description : ״̬ * Input Param : * Fd -----------> 򿪵ļ˵ * Cmd -----------> * Type -----------> ļ * Offset -----------> λ * Whence -----------> λ * Len -----------> ij * Returns :״̬ * complete :2002/11/19 */ int C_Config::SetLockStatus(int Fd, int Type, int Cmd, off_t Offset, int Whence, off_t Len) { struct flock Lock; Lock.l_type = Type; Lock.l_whence = Whence; Lock.l_start = Offset; Lock.l_len = Len; return fcntl(Fd, Cmd, &Lock); } /* * Function Name : GetParam * Description : ȡļļֵ * Input Param : * FileName -----------> ļ * Section -----------> ȡ * Key -----------> ȡĹؼ * Value -----------> ȡļֵ * Returns :͹ؼڣ򷵻trueõȷļֵ * 򷵻false * complete :2002/11/19 */ bool C_Config::GetParam(const char *FileName,const char *Section,const char *Key,char *Value) { if(-1 == access(FileName, F_OK|R_OK)) { return false; } int fd; int iCount,iLength; char chBuff[LINELENGTH],chTemp[LINELENGTH]; char chValueTemp[LINELENGTH]; char chSection[LINELENGTH],chKey[LINELENGTH]; char *pchPoint = NULL,*pchTemp = NULL,*pchEnv = NULL; string sLine,sSection; memset(chTemp, 0, sizeof(chTemp)); iCount = 0; if(strcmp(FileName,chFileTemp) != 0) { VRecord.clear(); strcpy(chFileTemp,FileName); if(-1 == (fd = open(FileName,O_RDONLY))) { return false; } //ļݷ for(;;) { memset(chBuff,0,sizeof(chBuff)); if ((iCount = GetLine(fd,chBuff)) == 0) { break; } Trim(chBuff); if ((';' == chBuff[0]) || ('#' == chBuff[0]) || ('\0' == chBuff[0])) { continue; } sLine = chBuff; VRecord.push_back(sLine); } close(fd); } iCount = 0; vector<string>::iterator it; it = VRecord.begin(); memset(chSection, 0, sizeof(chSection)); memset(chKey,0,sizeof(chKey)); //õSection memset(chTemp, 0, sizeof(chTemp)); sprintf(chTemp,"[%s]",Section); sSection = chTemp; while(it<VRecord.end()) { if (*it == sSection) { it++; iCount++; break; } it++; iCount++; if (iCount == VRecord.size()) { return false; } } //õKey while(it<VRecord.end()) { memset(chBuff, 0, sizeof(chBuff)); strcpy(chBuff, (*it).c_str()); //ڱҲؼ if ('[' == chBuff[0]) { return false; } pchPoint = chBuff; if ((pchTemp = strchr(pchPoint,'=')) != NULL) { strncpy(chKey, chBuff, pchTemp - pchPoint); chKey[pchTemp - pchPoint] = '\0'; Trim(chKey); } if (!strcmp(chKey,Key)) { it++; iCount++; break; } it++; iCount++; if (iCount == VRecord.size()) { return false; } } //õValue pchTemp++; strcpy(chValueTemp,pchTemp); Trim(chValueTemp);//20030424޸ģܲڴ沿֣ӦòԼڴ沿 chValueTemp[LINELENGTH-1] = 0; strcpy(Value, chValueTemp); //ļȽϳʱ,Ҫ,'\'ű־Ϊָ iLength = strlen(Value); if ('\\' == Value[iLength - 1]) { Value[iLength - 1] ='\0'; while(it<VRecord.end()) { memset(chBuff,0,sizeof(chBuff)); strcpy(chBuff,(*it).c_str()); iLength = strlen(chBuff); if (chBuff[iLength - 1] == '\\') { chBuff[iLength - 1] = '\0'; strcat(Value,chBuff); } else if (chBuff[iLength - 1] != '\\') { strcat(Value,chBuff); break; } it++; iCount++; if (iCount == VRecord.size()) { break; } } } if('$' == Value[0]) { pchPoint = Value; pchPoint++; if(((pchTemp = strchr(pchPoint,'.')) != NULL) && (strchr(pchPoint, '/') == NULL)) { strncpy(chSection,pchPoint,pchTemp - pchPoint); chSection[pchTemp - pchPoint] = '\0'; pchTemp++; strcpy(chKey,pchTemp); return GetParam(FileName,chSection,chKey,Value); } if(pchTemp = strchr(pchPoint,'/')) { strncpy(chTemp,pchPoint,pchTemp - pchPoint); chTemp[pchTemp - pchPoint] = '\0'; memset(Value,0,sizeof(Value)); if((pchEnv = getenv(chTemp)) != NULL) { if(('/' == *(pchEnv + strlen(pchEnv) - 1))&&('/' == *pchTemp)) { pchTemp++; } strcpy(chTemp,pchTemp); sprintf(Value,"%s%s",pchEnv,chTemp); return true; } else { return false; } } } return true; } /* * Function Name : SetParam * Description : ļ * Input Param : * Filename -----------> ļ * Section -----------> * Key -----------> Ĺؼ * Value -----------> ļֵ * Returns :ļڣfalse * ļڣ򷵻true * complete :2001/11/09 */ bool C_Config::SetParam(const char *FileName,const char *Section,const char *Key,const char *Value) { int fdt,fd; int iCount = 0; char chTemp[LINELENGTH], chTempName[LINELENGTH];; char chSection[LINELENGTH],chKey[LINELENGTH]; char *pchPoint = NULL,*pchTemp = NULL; string sLine; sprintf(chTempName,"%s.tmp",FileName); if(-1 == (fdt = open(chTempName,O_RDWR|O_CREAT|O_EXCL))) { if(-1 == (fdt = open(chTempName,O_RDWR|O_TRUNC))) { unlink(chTempName); return false; } } //ļд SetLockStatus(fdt,F_WRLCK); fchmod(fdt,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP); //ļд־ iWriteFlag = 1; // VRecord.clear(); if(-1 == (fd = open(FileName,O_RDONLY))) { SetLockStatus(fdt,F_UNLCK); close(fdt); iWriteFlag = 0; unlink(chTempName); return false; } //ļȫ for(;;) { memset(chTemp, 0, sizeof(chTemp)); if(0 == GetLine(fd, chTemp)) { break; } sLine = chTemp; VRecord.push_back(sLine); } close(fd); //ֹļնԭļȽΪ0 if (-1 == (fd = open(FileName,O_RDWR|O_CREAT|O_TRUNC))) { SetLockStatus(fdt,F_UNLCK); close(fdt); iWriteFlag = 0; unlink(chTempName); return false; } //ļΪֻ,ֹ޸ if (-1 == fchmod(fd,S_IRUSR|S_IRGRP)) { SetLockStatus(fdt,F_UNLCK); close(fdt); iWriteFlag = 0; unlink(chTempName); return false; } iCount = 0; vector<string>::iterator it; it = VRecord.begin(); memset(chSection, 0, sizeof(chSection)); memset(chKey,0,sizeof(chKey)); //õSection sprintf(chSection,"[%s]",Section); //2003-01-20޸ //ļΪ,½ѡ,дļ if (VRecord.size() == 0) { sprintf(chKey, "\t%s = %s", Key, Value); PutLine(fd, chSection); PutLine(fd, chKey); //ͷرļ SetLockStatus(fdt,F_UNLCK); fchmod(fd,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP); close(fdt); close(fd); unlink(chTempName); return true; } while(it<VRecord.end()) { memset(chTemp, 0, sizeof(chTemp)); strcpy(chTemp, (*it).c_str()); PutLine(fdt, chTemp); it++; iCount++; Trim(chTemp); if ((';' == chTemp[0]) || ('#' == chTemp[0])) { continue; } if (!strcmp(chTemp, chSection)) { break; } //Ѿļĩβ,ûи,ļĩβ½дֵ if (iCount == VRecord.size()) { for(it = VRecord.begin();it<VRecord.end();it++) { memset(chTemp, 0, sizeof(chTemp)); strcpy(chTemp, (*it).c_str()); PutLine(fd, chTemp); } sprintf(chKey, "\t%s = %s", Key, Value); PutLine(fd, chSection); PutLine(fd, chKey); //ͷرļ SetLockStatus(fdt,F_UNLCK); fchmod(fd,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP); close(fdt); close(fd); unlink(chTempName); return true; } } //2003-01-21޸ //ҵ˸,Ѿļһ,ļĩβдֵ if (iCount == VRecord.size()) { for(it = VRecord.begin();it<VRecord.end();it++) { memset(chTemp, 0, sizeof(chTemp)); strcpy(chTemp, (*it).c_str()); PutLine(fd, chTemp); } sprintf(chKey, "\t%s = %s", Key, Value); PutLine(fd, chKey); //ͷرļ SetLockStatus(fdt,F_UNLCK); fchmod(fd,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP); close(fdt); close(fd); unlink(chTempName); return true; } //õKey while(it<VRecord.end()) { memset(chTemp, 0, sizeof(chTemp)); strcpy(chTemp, (*it).c_str()); Trim(chTemp); //ûиùؼ,½ֵдļ if ('[' == chTemp[0]) { sprintf(chKey, "\t%s = %s", Key, Value); PutLine(fdt, chKey); PutLine(fdt, chTemp); it++; iCount++; break; } if ((';' == chTemp[0]) || ('#' == chTemp[0])) { it++; iCount++; PutLine(fdt, chTemp); continue; } pchPoint = chTemp; if ((pchTemp = strchr(pchPoint,'=')) != NULL) { strncpy(chKey, chTemp, pchTemp - pchPoint); chKey[pchTemp - pchPoint] = '\0'; Trim(chKey); } if (!strcmp(chKey,Key)) { it++; iCount++; sprintf(chKey, "\t%s = %s", Key, Value); PutLine(fdt, chKey); break; } sprintf(chTemp, "%s",(*it).c_str()); PutLine(fdt, chTemp); it++; iCount++; //Ѿļĩβ,Ӹòֵ if (iCount == VRecord.size()) { for(it = VRecord.begin();it<VRecord.end();it++) { memset(chTemp, 0, sizeof(chTemp)); strcpy(chTemp, (*it).c_str()); PutLine(fd, chTemp); } sprintf(chKey, "\t%s = %s", Key, Value); PutLine(fd, chKey); //ͷرļ SetLockStatus(fdt,F_UNLCK); fchmod(fd,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP); close(fdt); close(fd); unlink(chTempName); return true; } } while(it<VRecord.end()) { memset(chTemp, 0, sizeof(chTemp)); strcpy(chTemp, (*it).c_str()); PutLine(fdt, chTemp); it++; } //ʱļƶʱļͷ,дԭļ lseek(fdt,0,SEEK_SET); for(;;) { memset(chTemp, 0, sizeof(chTemp)); if(0 == GetLine(fdt, chTemp)) { break; } PutLine(fd, chTemp); } SetLockStatus(fdt,F_UNLCK); fchmod(fd,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP); close(fdt); close(fd); unlink(chTempName); return true; }
Python
UTF-8
3,790
3.640625
4
[]
no_license
#!/usr/bin/env python3 import csv contact_list = {} class Contact: def __init__(self, first, last, mail, silent=False): self.first = first self.last = last self.mail = mail self.silent = silent contact_list[self.first] = self if not self.silent: print('Contact created and added\n') def show_contact(self): print(' Name: {}'.format(self.first)) print(' Surname: {}'.format(self.last)) print(' Email: {}'.format(self.mail)) def delete_contact(self): del contact_list[self.first] self = None def edit_contact(self, first=None, last=None, mail=None): self.first = first or self.first self.last = last or self.last self.mail = mail or self.mail print('Contact updated\n') @classmethod def from_file(cls): """Create Contact objects from cvs lines """ with open('data.csv') as file: data_reader = csv.reader(file) for row in data_reader: first, last, mail = row cls(first, last, mail, True) @staticmethod def show_all(): print('Listing all contacts') for x, y in contact_list.items(): print('Contact {}'.format(x)) print(y.show_contact()) else: print('For a total of {} contacts'.format(len(contact_list.items()))) @staticmethod def write_to_file(): with open('data.csv', 'w') as file: output_writer = csv.writer(file) for x, y in contact_list.items(): output_writer.writerow([y.first, y.last, y.mail]) print('Contacts saved to disk\n') if __name__ == '__main__': print('Addressbook v0.1') try: Contact.from_file() print('Contacts file successfully loaded') except FileNotFoundError: pass while True: print('Select an option\n' '1 > Show all contacts\n' '2 > Add a contact\n' '3 > Delete a contact\n' '4 > Edit a contact\n' '5 > Save on disk' ) user_choice = input() if user_choice is '1': if len(contact_list.items()) > 0: Contact.show_all() else: print('You have no contacts\n') elif user_choice is '2': name = input('Type contact first name\n') last = input('Type contact last name\n') mail = input('Type contact mail\n') Contact(name, last, mail) elif user_choice is '3': if len(contact_list.items()) > 0: to_delete = input('Contact to delete\n') try: contact_list[to_delete].delete_contact() except KeyError: print('No such contact, try again\n') else: print('No contacts avaible for deletion yet\n') elif user_choice is '4': if len(contact_list.items()) > 0: to_edit = input('Contact to edit\n') try: contact_list[to_edit] name = input('Type contact first name\n') last = input('Type contact last name\n') mail = input('Type contact mail\n') contact_list[to_edit].edit_contact(name, last, mail) contact_list[name] = contact_list.pop(to_edit) except KeyError: print('No such contact, try again\n') else: print('No contacts to edit\n') elif user_choice is '5': Contact.write_to_file() else: print('Invalid option, try again\n')
Java
UTF-8
532
2.84375
3
[]
no_license
package org.cen.robot.control; public enum PIDMotionType { /** * The robot goes forward or backward. */ MOTION_TYPE_FORWARD_OR_BACKWARD(0x00), /** * The robot do a rotation. */ MOTION_TYPE_ROTATION(0x01), /** * The robot do a rotation with One Wheel */ MOTION_TYPE_ROTATION_ONE_WHEEL(0x02), /** * The robot must maintain a position. */ MOTION_TYPE_MAINTAIN_POSITION(0x03); private int index; private PIDMotionType(int index) { this.index = index; } public int getIndex() { return index; } }
Python
UTF-8
1,213
2.734375
3
[]
no_license
import cassandra from cassandra.cluster import Cluster from cql_queries import create_keyspace, drop_table_queries, create_table_queries def create_keyspace(): """ - connects to cluster on local machine - creates keyspace sparkifydb - creates session on keyspace sparkifydb """ cluster = Cluster(['127.0.0.1']) session = cluster.connect() session.execute("""CREATE KEYSPACE IF NOT EXISTS sparkifydb WITH REPLICATION = { 'class': 'SimpleStrategy', 'replication_factor' : 1}""") session.set_keyspace('sparkifydb') return session, cluster def drop_tables(session): """ - drops tables if they already exist """ for query in drop_table_queries: session.execute(query) def create_tables(session): """ - creates tables """ for query in create_table_queries: session.execute(query) def main(): """ - creates keyspace sparkifydb and connects to it - drops tables - creates tables - closes connection """ session, cluster = create_keyspace() drop_tables(session) create_tables(session) session.shutdown() cluster.shutdown() if __name__ == "__main__": main()
JavaScript
UTF-8
102
2.6875
3
[]
no_license
var ingredient = ["eggs", "milk", "butter"] console.log(ingredient [1]); console.log(ingredient [2]);
SQL
UTF-8
2,306
3.140625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.1.6 -- http://www.phpmyadmin.net -- -- Host: 127.0.0.1 -- Generation Time: Oct 30, 2016 at 10:17 AM -- Server version: 5.6.16 -- PHP Version: 5.5.9 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8 */; -- -- Database: `ecommerce_groovy` -- -- -------------------------------------------------------- -- -- Table structure for table `product` -- CREATE TABLE IF NOT EXISTS `product` ( `id` int(11) NOT NULL AUTO_INCREMENT, `seller` varchar(100) NOT NULL, `name` varchar(100) NOT NULL, `price` int(11) NOT NULL, `description` text NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `review` -- CREATE TABLE IF NOT EXISTS `review` ( `product` int(11) NOT NULL, `reviewer` varchar(100) NOT NULL, `rating` int(11) NOT NULL, `content` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -------------------------------------------------------- -- -- Table structure for table `transaction` -- CREATE TABLE IF NOT EXISTS `transaction` ( `id` int(11) NOT NULL AUTO_INCREMENT, `date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `buyer` varchar(100) NOT NULL, `seller` varchar(100) NOT NULL, `product` int(11) NOT NULL, `quantity` int(11) NOT NULL, `total_price` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; -- -------------------------------------------------------- -- -- Table structure for table `user` -- CREATE TABLE IF NOT EXISTS `user` ( `username` varchar(100) NOT NULL, `email` varchar(100) NOT NULL, `password` varchar(100) NOT NULL, `name` varchar(100) NOT NULL, `address` text NOT NULL, PRIMARY KEY (`username`), UNIQUE KEY `email` (`email`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Java
UTF-8
1,996
2.1875
2
[ "MIT" ]
permissive
package com.chenkh.vchat.client.frame.chat; import java.sql.Timestamp; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.chenkh.vchat.base.msg.ChatMsg; import com.chenkh.vchat.client.IContext; import com.chenkh.vchat.client.UserMgr; import com.chenkh.vchat.client.access.FrameTaskMgr; import com.chenkh.vchat.client.frame.ObjectContainer; public class ChatFrameMgr implements ChatAccess { private List<ChatFrame> frames = new ArrayList<ChatFrame>(); private int maxSize = 6; private Set<Integer> openIds = new HashSet<Integer>(); private ObjectContainer objc = new ObjectContainer(); private IContext context; public ChatFrameMgr( IContext context) { this.context=context; } public void addChat(int friendId) { for (ChatFrame frame : frames) { if (!frame.isFull()) { frame.addChat(friendId); return; } } ChatFrame frame = objc.getChatFrame(this, maxSize); frames.add(frame); frame.addChat(friendId); openIds.add(friendId); } public void removeOpenChat(int id) { openIds.remove(id); } public void removeOpenChat(Set<Integer> ids) { openIds.removeAll(ids); } @Override public void setSelect(int id) { for (ChatFrame frame : frames) { if (frame.isContain(id)) { frame.setSelect(id); return; } } } public void sendMsg(String msg, int friendId) { //mgr.putChatMsg(msg, friendId); int id = UserMgr.getInstance().getUser().getId(); ChatMsg chatMsg= new ChatMsg(id,friendId,msg,new Timestamp(System.currentTimeMillis())); context.getNetClient().sendChatMsg(chatMsg); } @Override public boolean isContain(int id) { // return this.openIds.contains(id); for (ChatFrame frame : frames) { if (frame.isContain(id)) { return true; } } return false; } @Override public void reciveMsg(int id) { for (ChatFrame frame : frames) { if (frame.isContain(id)) { frame.reciveMsg(id); return; } } } }
Java
UTF-8
453
1.640625
2
[]
no_license
package com.example.hanyan.hanee.dto.request; import lombok.Data; import java.io.Serializable; /** * @author vigo.xian */ @Data public class UserInfoAddVO implements Serializable { private static final long serialVersionUID = 4856696343700550078L; /** * 用户名 * */ private String username; /** * 用户密码 * */ private String password; /** * 角色ID * */ private Long roleId; }
Python
UTF-8
379
2.71875
3
[]
no_license
from pymongo import MongoClient def search(table_name, id_field, id, db_url='localhost', db_port=27017): client = MongoClient(db_url, db_port) db = client['northwind'] table = db[table_name] return [doc for doc in table.find({id_field: id})] def example_queries(): print(search('products', 'product_id', 20)) print(search('orders', 'order_id', 10248))
Java
UTF-8
2,258
2.359375
2
[]
no_license
package com.lk.lankabell.android.activity.tsr.activity; import java.util.ArrayList; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.lk.lankabell.android.activity.tsr.R; import com.lk.lankabell.android.activity.tsr.sqlite.SalesSynchReport; public class SalesSynchReportAdapter extends BaseAdapter { Context context; ArrayList<SalesSynchReport> synchReports; public SalesSynchReportAdapter(Context context, ArrayList<SalesSynchReport> list) { this.context = context; synchReports = list; } public int getCount() { return synchReports.size(); } public Object getItem(int position) { return synchReports.get(position); } public long getItemId(int position) { return position; } public View getView(int position, View convertView, ViewGroup group) { SalesSynchReport synchReportsItems = synchReports.get(position); if (convertView == null) { LayoutInflater inflater = (LayoutInflater) context .getSystemService(context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.salessynch_list_row, null); } TextView tvStatus = (TextView) convertView.findViewById(R.id.synchDate); if (synchReportsItems.getDate() != null) { tvStatus.setText(synchReportsItems.getDate().toString()); } else { tvStatus.setText("None"); } TextView tvComponent = (TextView) convertView.findViewById(R.id.textComponent); if (synchReportsItems.getComponent() != null) { tvComponent.setText(String.valueOf(synchReportsItems.getComponent())); } else { tvComponent.setText("None"); } TextView tvTotalRecords = (TextView) convertView.findViewById(R.id.totalRecords); if (synchReportsItems.getTotalCount() != null) { tvTotalRecords.setText("/ " +String.valueOf(synchReportsItems.getTotalCount())); } else { tvTotalRecords.setText("None"); } TextView tvSynchRecords = (TextView) convertView.findViewById(R.id.synchRecords); if (synchReportsItems.getSynchCount() != null) { tvSynchRecords.setText(String.valueOf(synchReportsItems.getSynchCount())); } else { tvSynchRecords.setText("None"); } return convertView; } }
Java
UTF-8
1,654
4.0625
4
[ "BSD-2-Clause" ]
permissive
import java.util.Stack; import java.util.EmptyStackException; /** Clas to hold two stacks and operate between them */ public class MultiStack<T> { private Stack<T> a = new Stack(); private Stack<T> b = new Stack(); /** Push onto the A Stack * * @param item */ public void PushA(T item) { a.push(item); } /** check if a is empty */ public boolean AEmpty() { return a.empty(); } /** check if a is empty */ public boolean BEmpty() { return b.empty(); } /** Push onto the B Stack * *@param item */ public void PushB(T item) { b.push(item); } /** Peek at the top of the A Stack */ public void PeekA() { System.out.println(a.peek()); } /** Peek at the top of the B stack */ public void PeekB() { System.out.println(b.peek()); } /** Pop multiple from A * *@param k */ public void MultiPopA(int k) { MultiPop(a, k); } /** Pop multiple from B * *@param k */ public void MultiPopB(int k) { MultiPop(b, k); } /** perform multiple (min(k, stack.size) pops on given stack */ private void MultiPop(Stack currentStack, int k) { int endIter = java.lang.Math.min(k, currentStack.size()); System.out.println("Popping " + endIter + " values"); for (int i=1; i<=endIter; i++) { System.out.println(currentStack.pop()); } } /** Transfer min(k, A.size) items from A onto B */ public void Transfer(int k) { for (int i=1; i<=k; i++) { if (a.empty() == false) { System.out.println("Moving " + a.peek() + " to b"); b.push(a.pop()); } } } }
Python
UTF-8
1,095
4.3125
4
[]
no_license
import random colors = 'orange pink indigo green red yellow blue magenta cyan' colorslist = colors.split() #Split a string into a list random.shuffle(colorslist) #Shuffle a list print ('The shuffled list:', colorslist) print ('The minimum is:', min(colorslist)) #Minimum of list print ('The maximum is:', max(colorslist)) #Maximum of list colorslist.sort() #Sort list from min to max print ('The sorted list:', colorslist) colorslist.insert (5, 'violet') #Insert a string at a certain position in list print ('Insert in list:',colorslist) colorslist.append ('brown') #Add string to the end of list print ('Appended list:',colorslist) print ('Count of red:', colorslist.count('red')) #Count how many times 'red' appears in list colorslist.pop (1) #Remove one string in a certain position of list print ('Pop from list:', colorslist) colorslist.remove ('green') #Remove certain string from list print ('Remove from list:', colorslist) colorslist.reverse() #Reverse the list print ('Reverse the list:', colorslist) list2 = ['A', 'B', [1, 2, 3], 'C'] print (list2[1]) print (list2[2][0])
Java
UTF-8
3,965
3.828125
4
[]
no_license
/** * This is a simple craps game, in which the user is asked if they want to play and see rules * * @author Kareem Ansari * @version 2021-2-2 */ import java.util.Scanner; public class Craps { public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.print("Would you like to play Craps (Y/n)?"); String playGame = in.nextLine(); if (playGame.equals("") || playGame.substring(0,1).equalsIgnoreCase("y")) { //checking to see if player wants to play System.out.print("Before we start the round, would you like instructions on how to play Craps (Y/n)?"); String getRules = in.nextLine(); //checking if player wants rules, only happens first time around if (getRules.equals("") || getRules.substring(0,1).equalsIgnoreCase("y")) { System.out.println("1. A player rolls two die"); System.out.println("2. If the sum of the numbers is 7 or 11 you win"); System.out.println("3. If the sum is 2, 3 or 12, you lose"); System.out.println("4. If none of these are rolled, the sum becomes the point"); System.out.println("5. From here on, you continue to roll the die "); System.out.println("6. If the sum is 7 you lose "); System.out.println("7. If the sum is the earlier determined point, you win"); } } while (playGame.equals("") || playGame.substring(0,1).equalsIgnoreCase("y")) { //the game has started System.out.print("Press <Enter> to roll..."); String pause = in.nextLine(); //insignficant variable, just to create pause Die person1 = new Die(); //create the dice from Die class person1.rollDice(); //roll System.out.println("You rolled a " + person1.getResult()); int point = person1.getResult(); //establishing the point if (person1.getResult() == 7 || person1.getResult() == 11) { System.out.println("You win!"); //instant win, game ends } else if(person1.getResult() == 2 || person1.getResult() == 3 || person1.getResult() == 12) { System.out.println("You lose"); //instant loss, game ends } else { System.out.println("The point is now " + point); System.out.print("Press <Enter> to roll..."); pause = in.nextLine(); //pause person1.rollDice(); while (person1.getResult() != 7 && person1.getResult() != point) { System.out.println("Your rolled a, " + person1.getResult()); System.out.print("Press <Enter> to roll..."); pause = in.nextLine(); person1.rollDice(); } if (person1.getResult() == point) { System.out.println("You rolled a " + person1.getResult()); System.out.println("You win!"); } else { System.out.println("You rolled a 7"); System.out.println("You lose"); } } System.out.print("Would you like to play Craps (Y/n)?"); playGame = in.nextLine(); } System.out.println("Goodbye!"); } } /* COMMENTS FROM THE INSTRUCTOR: This is a solid version of the game, Kareem, and very cleanly coded. You should feel free to break this up into a few smaller static methods to make it even easier to read through. But the gameplay is perfect, and you did a nice job of implementing the default (Y/n) feature as required. Outstanding! SCORE: 15/15 */
PHP
UTF-8
1,259
2.90625
3
[]
no_license
<?php class ListTest extends TestCase{ public function testStore() { $params = array( 'user_id' => '2', 'movie_id' => '1234' ); $favorite = new Favorite($params); $watchlist = new Watchlist($params); $seenlist = new Seenlist($params); $this->assertTrue($favorite->save(), 'Added to favorites!'); $this->assertTrue($watchlist->save(), 'Added to watchlist!'); $this->assertTrue($seenlist->save(), 'Added to seenlist!'); } public function testLists(){ $params = array( 'user_id' => '2', 'name' => 'favorites', 'private' => 0 ); $favoritelist = new Lists($params); $this->assertTrue($favoritelist->save()); } public function customlistTest(){ $params = array( 'user_id' => '3', 'name' => 'top inspirational movies', 'description' => 'movies that have inspired me!', 'private' => 0 ); //add list to the list of lists $list = new Lists($params); $this->assertTrue($list->save()); //adding a movie to the customlist pivot table $customlist_params = array( 'user_id' => '3', 'tmdb_id' => '123', 'list_id' => '234' ); $custom_list = new Customlist($customlist_params); $this->assertTrue($custom_list->save()); } }
Markdown
UTF-8
2,321
2.5625
3
[]
no_license
--- author: Jen Carlson date: February 21, 2012 4:36 PM title: One Of The Last Meals On The Titanic Revealed In Menu Being Auctioned Off --- <p><span class="mt-enclosure mt-enclosure-image" style="display: inline;"> <img alt="lgmenutitanic.jpeg" src="https://web.archive.org/web/20120222211336im_/http://gothamist.com/attachments/arts_jen/lgmenutitanic.jpeg" width="640" height="426" class="image-none"> </span></p> <p><span class="mt-enclosure mt-enclosure-image" style="display: inline;"> <img alt="smtitanicmenu.jpeg" src="https://web.archive.org/web/20120222211336im_/http://gothamist.com/attachments/arts_jen/smtitanicmenu.jpeg" width="250" height="354" class="image-right"> </span>What was one of the last meals for the first class passengers on board the Titanic? The lunch menu for the midday meal served on April 14th,1912 is now up on the auction block in the UK, and is expected to sell for $157,960 USD. <a href="https://web.archive.org/web/20120222211336/http://rt.com/art-and-culture/news/titanic-memorabilia-auction-menu-crash-day-867/">The menu</a> was on the table of Dr. Washington Dodge, a banker from San Francisco who was traveling with his wife and son. The entire family survived the tragic crash, and his wife Ruth had the menu from that afternoon, placing it in her handbag. It has been in the family since, and is one of the rarest pieces of Titanic memorabilia.</p> <p>The menu, adorned with the White Star Line logo, offered up 40 choices, including eggs Argenteuil, chicken, beef, grilled mutton chops, eight kinds of cheese, Norwegian anchovies, chicken a la Maryland, corned beef, vegetables, dumplings, and more. The third class passengers had a much different offering, which you can <a href="https://web.archive.org/web/20120222211336/http://titanicstation.blogspot.com/2007/02/third-class.html">see here</a>&#x2014;their choices were limited to bread &amp; butter, potatoes, Quaker oats, corned beef and cabbage, currant buns, pickles and cheese, and peaches and rice.</p> <p>The <a href="https://web.archive.org/web/20120222211336/http://www.henry-aldridge.co.uk/">Henry Aldridge and Son</a> auction house will be putting the first class menu on the block March 31st, at their annual spring Titanic sale&#x2014;they are a&#x2014;if not <em>the</em>&#x2014;leading auctioneers of Titanic memorabilia.</p>
Java
UTF-8
2,794
1.984375
2
[]
no_license
/* File generated by Magnet rest2mobile 1.1 - Sep 18, 2017 3:52:26 PM @see {@link http://developer.magnet.com} */ package kdmc_kumar.Webservices_NodeJSON.MastersRestAPI; import com.magnet.android.mms.MagnetMobileClient; import com.magnet.android.mms.controller.AbstractControllerSchemaFactory; import com.magnet.android.mms.controller.ControllerFactory; import com.magnet.android.mms.controller.RequestSchema; import java.util.Collections; import kdmc_kumar.Core_Modules.BaseConfig; public class Masters_RESTAPIFactory extends ControllerFactory<Masters_RESTAPI> { public Masters_RESTAPIFactory(MagnetMobileClient magnetClient) { super(Masters_RESTAPI.class, Masters_RESTAPIFactory.Masters_RESTAPISchemaFactory.getInstance().getSchema(), magnetClient); } // Schema factory for controller Masters_RESTAPI public static class Masters_RESTAPISchemaFactory extends AbstractControllerSchemaFactory { private static Masters_RESTAPIFactory.Masters_RESTAPISchemaFactory __instance; private Masters_RESTAPISchemaFactory() { } static Masters_RESTAPIFactory.Masters_RESTAPISchemaFactory getInstance() { synchronized (Masters_RESTAPIFactory.Masters_RESTAPISchemaFactory.class) { if (null == Masters_RESTAPIFactory.Masters_RESTAPISchemaFactory.__instance) { Masters_RESTAPIFactory.Masters_RESTAPISchemaFactory.__instance = new Masters_RESTAPIFactory.Masters_RESTAPISchemaFactory(); } return Masters_RESTAPIFactory.Masters_RESTAPISchemaFactory.__instance; } } protected final void initSchemaMaps() { synchronized (this) { if (null != this.schema) { return; } this.schema = new RequestSchema(); this.schema.setRootPath(""); //controller schema for controller method table1 RequestSchema.JMethod method1 = this.addMethod("table1", BaseConfig.AppNodeIP + "/Get_Masters_Tables", "GET", String.class, null, null, Collections.singletonList("text/plain")); method1.setBaseUrl(BaseConfig.AppNodeIP); method1.addParam("TableId", "QUERY", String.class, null, "", true); method1.addParam("IsUpdateMax", "QUERY", String.class, null, "", true); } } } }
C++
UTF-8
2,163
2.921875
3
[]
no_license
// data_structure_assignment.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include "pch.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #define Ok 0x01 #define MemoryOverFlow 0x02 #define OutOfIndex 0x03 #define TestFailed 0xfff #define MAX_SIZE 1000 typedef struct { /*从0编号到n-1*/ char elem[MAX_SIZE]; int size = 0; int max_size = MAX_SIZE; } CharStack; int popCharStack(CharStack *stack) { if (stack->size == 0) { exit(OutOfIndex); } stack->size--; return stack->elem[stack->size]; } int pushCharStack(CharStack *stack, char value) { if (stack->size == stack->max_size) { exit(OutOfIndex); } stack->elem[stack->size++] = value; return Ok; } int isHuiwen(char str[]) { CharStack stack; bool meet_andchar = false; for (int i = 0; i < strlen(str); i++) { if (str[i] == '&') { meet_andchar = true; continue; } if (str[i] == '@') { // 栈不为空也不行 if (stack.size != 0) { return 0; } break; } if (!meet_andchar) { pushCharStack(&stack, str[i]); } else { // 判断弹出的元素是否和当前字符相等 if (str[i] != popCharStack(&stack)) { return 0; } } } return 1; } int test_huiwen() { char str1[] = "a+b&b+a@"; printf("isHuiwen(%s) = %d\n", str1, isHuiwen(str1)); char str2[] = "a+b&b-a@"; printf("isHuiwen(%s) = %d\n", str2, isHuiwen(str2)); return Ok; } int main() { test_huiwen(); return Ok; } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门提示: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
TypeScript
UTF-8
2,946
3.671875
4
[]
no_license
import { nFromArray, oneFromArray, shuffle } from "./array-utils"; describe("array utils", () => { describe("shuffle", () => { // There's only so much that I can do to test this without monkeypatching Math.random it("works with empty array", () => { const result = shuffle([]); expect(result.length).toBe(0); }); it("returns all the items given", () => { const array = ["A", "B", "C", "D", "E"]; const result = shuffle(array); expect(result.length).toBe(array.length); array.forEach(el => expect(result.includes(el))); }); }); describe("oneFromArray", () => { it("empty array", () => { expect(() => oneFromArray([])).toThrowError(); }); it("removes the only item", () => { const result = oneFromArray(["A"]); expect(result[0]).toBe("A"); expect(result[1].length).toBe(0); }); it("removes one from three", () => { const array = ["A", "B", "C"]; const [item, remaining] = oneFromArray(array); expect(array.includes(item)).toBeTruthy(); expect(remaining.includes(item)).toBeFalsy(); expect(remaining.length).toBe(2); }); it("eventually removes all", () => { // This isn't a great test. It could fail while working correctly. // But it's extremely unlikely and the only other way would be to // re-implement Javascript's random function in a seedable way. const array = ["A", "B", "C"]; const removed: Record<string, boolean> = {A: false, B: false, C: false}; for (let i = 0; i < 1000; i++) { const [item] = oneFromArray(array); removed[item] = true; if (Object.values(removed).every(f => f)) { expect(true).toBeTruthy(); return; } } throw new Error("Not every item removed in 1000 tries: " + JSON.stringify(removed)); }); }); describe("nFromArray", () => { it("fails if N is too large", () => { expect(() => nFromArray(["A", "B"], 3)).toThrowError(); }); it("takes zero from an empty array", () => { const [items, remaining] = nFromArray([], 0); expect(items.length).toBe(0); expect(remaining.length).toBe(0); }); it("takes zero from a full array", () => { const array = ["A", "B", "C"]; const [items, remaining] = nFromArray(array, 0); expect(items.length).toBe(0); expect(remaining.length).toBe(3); }); it("takes one", () => { const array = ["A", "B", "C"]; const [items, remaining] = nFromArray(array, 1); expect(items.length).toBe(1); expect(array.includes(items[0])).toBeTruthy(); expect(remaining.includes(items[0])).toBeFalsy(); expect(remaining.length).toBe(2); }); it("takes two", () => { const array = ["A", "B", "C"]; const [items, remaining] = nFromArray(array, 2); expect(items.length).toBe(2); expect(remaining.length).toBe(1); }); it("takes all", () => { const array = ["A", "B", "C"]; const [items, remaining] = nFromArray(array, 3); expect(items.length).toBe(3); expect(remaining.length).toBe(0); }); }); });
Java
UTF-8
373
1.65625
2
[]
no_license
package com.springcloud.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor public class SysServiceProvide implements java.io.Serializable{ /** * */ private static final long serialVersionUID = 7263896357980069892L; private String sys_service_provider_id; }
C++
UTF-8
1,374
2.796875
3
[]
no_license
#include "tcpsocket.h" #include "udpsocket.h" int main(int argc, char* argv[]) { if (argc != 3) { cout << "ip port..." << endl; return -1; } string ip = argv[1]; unsigned short port = atoi(argv[2]); struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_addr.s_addr = inet_addr(ip.c_str()); addr.sin_port = htons(port); UdpSocket csock; csock.u_socket(); string data; cout << "client:"; cin >> data; if (!csock.u_send(data, addr)) { cout << "sendto error" << endl; return -1; } data.clear(); if (!csock.u_read(data, addr)) { cout << "readfrom error" << endl; return -1; } cout << "server:" << data << endl; return 0; } #if 0 int main(int argc, char* argv[]) { if (argc != 3) { cout << "ip port..." << endl; return -1; } string ip = argv[1]; unsigned short port = atoi(argv[2]); TcpSocket csock; if (!csock.t_socket()) { cout << "socket error" << endl; } if (!csock.t_connect(ip, port)) { cout << "connect error" << endl; } while (1) { string data; cout << "client:"; cin >> data; if (csock.t_send(data) == false) { cout << "send error" << endl; break; } if (csock.t_read(data) == false) { cout << "recv error" << endl; break; } cout << "client:" << data << endl; } csock.t_close(); return 0; } #endif
Markdown
UTF-8
784
2.609375
3
[]
no_license
# canaryleakdetection Simple Example Code How to use Canary Leak Detector ## Synopsis Simple implementation using Canary Leak Detector on Android App, which it's will give you notification and show which part of your code that causing memory leak. In this example code will give you memory leak when async task get interrupted (app destroyed when async process still not done). ## Libs 1. [Butterknife](https://github.com/JakeWharton/butterknife) for view injection 2. [LeakCanary](https://github.com/square/leakcanary) for Leak detector ## Notes 1. Canary need permission access r/w on your external storage, which it will use to write dumping memory report 2. When you run on device, it will install app called "Leak" on your device who will show you the Leak list from your app
Java
UTF-8
1,023
2.453125
2
[]
no_license
package club.kidgames.liquid.merge.filters.strings; import javax.swing.text.MaskFormatter; import liqp.filters.Filter; /** * */ public class USPhoneNumberFormatFilter extends Filter { public USPhoneNumberFormatFilter() { super("usphone"); } @Override public Object apply(Object o, Object... objects) { String rtn; if (o != null) { try { String phoneMask= "###-###-####"; String phoneNumber= String.valueOf(o).replace("+", ""); int extraLength = phoneNumber.length() - 10; phoneNumber = phoneNumber.substring(extraLength); MaskFormatter maskFormatter= new MaskFormatter(phoneMask); maskFormatter.setValueContainsLiteralCharacters(false); rtn = maskFormatter.valueToString(phoneNumber) ; } catch (Exception e) { rtn = o.toString(); } } else { rtn = null; } return rtn; } }
JavaScript
UTF-8
6,622
2.734375
3
[ "MIT" ]
permissive
import React, { Component} from 'react' import ReactDOM from 'react-dom' import Header from './Header.js' import Filter from './Filter.js' import Listings from './Listings.js' import listingsData from './listingsdata.js' class App extends Component { constructor () { super() this.state = { listingsData, city: 'All', homeType: 'All', bedrooms: 0, min_price: 0, max_price: 5000, min_floorspace: 0, max_floorspace: 5000, elevator: false, swimming_pool: false, finished_basement: false, gym: false, filteredData: listingsData, populateFormsData: '', sortby: 'price-dsc', view: 'box', search: '' } this.change = this.change.bind(this) this.filteredData = this.filteredData.bind(this) this.populateForms = this.populateForms.bind(this) this.changeView = this.changeView.bind(this) } componentWillMount(){ var listingsData = this.state.listingsData.sort((a,b) => { return a.price - b.price }) this.setState({ listingsData }) } change(event){ var name = event.target.name; var value = (event.target.type === 'checkbox') ? event.target.checked : event.target.value; this.setState({ [name]: value }, () => { console.log(this.state) this.filteredData()}) } changeView(viewName){ this.setState({ view: viewName }) } filteredData(){ var newData = this.state.listingsData.filter((item) => { return item.price >= this.state.min_price && item.price <= this.state.max_price && item.floorSpace >= this.state.min_floorspace && item.floorSpace <= this.state.max_floorspace && item.rooms >= this.state.bedrooms }) if(this.state.city != 'All'){ newData = newData.filter((item) => { return item.city == this.state.city }) } if(this.state.homeType != 'All'){ newData = newData.filter((item) => { return item.homeType == this.state.homeType }) } if(this.state.sortby == 'price-dsc'){ newData.sort((a,b) => { return a.price - b.price }) } if(this.state.sortby == 'price-asc'){ newData.sort((a,b) => { return b.price - a.price }) } if(this.state.elevator){ newData = newData.filter((item) => { return item.extras.includes('elevator') }) } if(this.state.swimming_pool){ newData = newData.filter((item) => { return item.extras.includes('swimming pool') }) } if(this.state.finished_basement){ newData = newData.filter((item) => { return item.extras.includes('finished basement') }) } if(this.state.gym){ newData = newData.filter((item) => { return item.extras.includes('gym') }) } if(this.state.search != ''){ newData = newData.filter((item) => { var city = item.city.toLowerCase() var address = item.address.toLowerCase() var state = item.state.toLowerCase() var searchText = this.state.search.toLowerCase() var cityMatch = city.match(searchText) var addressMatch = address.match(searchText) var stateMatch = state.match(searchText) if (cityMatch !=null || addressMatch !=null || stateMatch !=null){ return true } }) } this.setState({ filteredData: newData }) } populateForms(){ //City var cities = this.state.listingsData.map((item) => { return item.city }) cities = new Set(cities) cities = [...cities] cities = cities.sort() //HomeType var homeTypes = this.state.listingsData.map((item) => { return item.homeType }) homeTypes = new Set(homeTypes) homeTypes = [...homeTypes] homeTypes = homeTypes.sort() //Bedrooms var bedrooms = this.state.listingsData.map((item) => { return item.rooms }) bedrooms = new Set(bedrooms) bedrooms = [...bedrooms] bedrooms = bedrooms.sort() this.setState({ populateFormsData: { homeTypes, bedrooms, cities } }, console.log(this.state)) } render () { return (<div> <Header /> <section id="content-area"> <section className='landing'> <h3 className='positioningtext'>HomeVibes</h3> <h5 className='sub-positioningtext'>Find your next dream home</h5> <a class="smoothScroll" href='#content'> <i className="fas fa-chevron-down fa-3x"></i></a> </section> <div id='content'> <Filter change = {this.change} globalState= {this.state} populateAction = {this.populateForms}/> <Listings filteredData = {this.state.filteredData} change = {this.change} globalState= {this.state} changeView = {this.changeView} /> </div> </section> <footer> <section className='mobile'> <div className='container'> <h4>Download the HomeVibes App</h4> <button><i className="fab fa-google-play"></i> <p>Playstore</p> </button> <button> <i className="fab fa-apple"></i> <p>AppStore</p> </button> <p className='copyrighttext'>2006-2018 HomeVibes.com</p> </div> <img src='/img/localhomes.png'/> </section> <section className='additionalinfo'> <ul> <li><a href='#top'>HomeVibes.com</a></li> <li>About HomeVibes.com</li> <li>Meet the realtors</li> <li>HomeVibes App</li> <li>Work with Us</li> </ul> </section> </footer> </div>) } } const app = document.getElementById('app') ReactDOM.render(<App />, app)
PHP
UTF-8
1,080
2.75
3
[ "MIT" ]
permissive
<?php namespace Hail; /** * Class Output * * @package Hail * @property-read Output\Json $json * @property-read Output\Jsonp $jsonp * @property-read Output\File $file * @property-read Output\Text $text * @property-read Output\Template $template * @property-read Output\Redirect $redirect */ class Output { private $output = false; public function __get($name) { return $this->get($name); } public function get($name) { if ($this->output) { throw new \RuntimeException('Response Already Output'); } $this->output = true; $class = __NAMESPACE__ . '\\Output\\' . ucfirst($name); return new $class(); } public function json() { return $this->get('json'); } public function jsonp() { return $this->get('jsonp'); } public function file() { return $this->get('file'); } public function text() { return $this->get('text'); } public function template() { return $this->get('template'); } public function redirect() { return $this->get('redirect'); } }
Java
UTF-8
227
1.710938
2
[]
no_license
package com.lppz.exception; public class RestHttpLogException extends Exception { /** * */ private static final long serialVersionUID = 2283328026170246096L; public RestHttpLogException(String e) { super(e); } }
Java
UTF-8
9,102
2.53125
3
[]
no_license
package se.fluff.aoc; import java.io.*; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.*; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Scanner; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.GZIPInputStream; public class Main { private static final String projectPath = "/home/fluff/git/adventofcode2019/"; private static final String basePath = "/home/fluff/git/adventofcode2019/src/se/fluff/"; private static String prodInput; private static String testPath; private static String key; public static void main(String[] args) throws IOException { SimpleDateFormat dayformat = new SimpleDateFormat("dd"); SimpleDateFormat yearformat = new SimpleDateFormat("yyyy"); Date d = new Date(); String day = args.length > 0 ? args[0] : dayformat.format(d); String year = args.length > 1 ? args[1] : yearformat.format(d); String clazzname = "se.fluff.aoc" + year + ".days.Day" + day; prodInput = basePath + "aoc" + year + "/data/" + day + ".in"; testPath = basePath + "aoc" + year + "/tests/" + day + "/"; Scanner keyscanner = new Scanner(new File(projectPath + ".cookie")); key = keyscanner.nextLine(); keyscanner.close(); Class<?> clazz = null; try { clazz = Class.forName(clazzname); } catch (ClassNotFoundException e) { System.out.println("Class not found: " + e.getLocalizedMessage()); System.out.println("Should we create and fetch? [y/N]"); Scanner stdin = new Scanner(System.in); if(stdin.hasNext()) { String fetch = stdin.nextLine(); if (fetch.matches("[Yy]")) initDay(year, day); } stdin.close(); } try { if(clazz == null) throw new RuntimeException("Class not loaded"); System.out.println("Running " + clazzname); Constructor<?> constructor = clazz.getDeclaredConstructor(); AocDay aocDay = (AocDay) constructor.newInstance(); for(String puzzle : new String[] { "a", "b" }) { Method method = clazz.getDeclaredMethod(puzzle, Scanner.class, boolean.class); long starttime = System.currentTimeMillis(); if(runTests(testPath, aocDay, puzzle)) { long ttc = System.currentTimeMillis() - starttime; System.out.println("Puzzle " + puzzle + ": All tests successful, running production"); System.out.println("Tests execution took " + ttc + " ms"); Scanner in = new Scanner(new File(prodInput)); starttime = System.currentTimeMillis(); System.out.println("Puzzle " + puzzle + ", answer is: " + method.invoke(aocDay, in, false)); ttc = System.currentTimeMillis() - starttime; System.out.println("Puzzle execution took " + ttc + " ms"); in.close(); } else { System.out.println("Puzzle " + puzzle + ", testing failed, exiting"); System.exit(1); } System.out.println("======================================="); } } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { e.printStackTrace(); } } public static boolean runTests(String testPath, AocDay aocDay, String puzzle) throws IOException { File testDirectory = new File(testPath + puzzle); if(!testDirectory.exists() || !testDirectory.isDirectory()) { System.out.println("WARNING: Test directory not configured, not running tests"); return true; } else if(testDirectory.list().length == 0) { System.out.println("WARNING: Test directory is empty, not running tests"); return true; } Stream<Path> walk = Files.walk(Paths.get(testPath + puzzle)); List<String> infiles = walk.filter(Files::isRegularFile) .map(Path::toString) .filter(x -> x.endsWith(".in")) .sorted() .collect(Collectors.toList()); System.out.println("Running " + infiles.size() + " tests for puzzle " + puzzle); int success = 0; for(String infile : infiles) { File i = new File(infile); File o = new File(infile.replace(".in", ".out")); Scanner out = new Scanner(o); String expectedResult = ""; if(out.hasNext()) expectedResult = out.nextLine(); Scanner in = new Scanner(i); String res = ""; try { if (puzzle.equals("a")) res = aocDay.a(in, true); else res = aocDay.b(in, true); } catch(Exception e) { e.printStackTrace(); } if(expectedResult.equals(res)) { System.out.println("SUCCESS: Test " + i.getName() + " returned " + res); success++; } else { System.err.println("ERROR: Test " + i.getName() + " returned " + res + " expected result " + expectedResult); } } return success == infiles.size(); } public static void initDay(String year, String day) { fetchInput(year, day); copyTemplate(year, day); createTests(); System.out.println("Day initialized, happy coding"); System.exit(0); } public static void fetchInput(String year, String day) { try { URL url = new URL("https://adventofcode.com/" + year + "/day/"+ day.replaceFirst("^0", "") + "/input"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setDoInput(true); con.setRequestProperty("Accept", "text/plain;q=0.9"); con.setRequestProperty("Accept-Encoding", "gzip"); con.setRequestProperty("Cookie", "session=" + key); con.connect(); if(con.getResponseCode() == 200) { Writer fw = new FileWriter(prodInput); InputStream is; if("gzip".equals(con.getContentEncoding())) is = new GZIPInputStream(con.getInputStream()); else is = con.getInputStream(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is)); String in; while((in = bufferedReader.readLine()) != null) fw.write(in + "\n"); fw.close(); bufferedReader.close(); } else throw new RuntimeException("Retrieving input returned error: " + con.getResponseCode() + ": " + con.getResponseMessage()); con.disconnect(); } catch (IOException e) { e.printStackTrace(); } } public static boolean copyTemplate(String year, String day) { SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd"); Date d = new Date(); String javafile = basePath + "aoc" + year + "/days/Day" + day + ".java"; File fin = new File(projectPath + "java.template"); File fout = new File(javafile); if(fout.exists()) { System.out.println("Java file '" + javafile + "' already exists, not overwriting"); return false; } try { Writer fw = new FileWriter(javafile); BufferedReader finreader = new BufferedReader(new FileReader(fin)); String in; while((in = finreader.readLine()) != null) { in = in .replace("$year", year) .replace("$day", day) .replace("$today", dformat.format(d)); fw.write(in + "\n"); } fw.close(); finreader.close(); return true; } catch (IOException e) { e.printStackTrace(); } return false; } public static void createTests() { File f = new File(testPath + "a/"); if(f.mkdirs()) { try { f = new File(testPath + "a/1.in"); f.createNewFile(); f = new File(testPath + "a/1.out"); f.createNewFile(); f = new File(testPath + "b/"); f.mkdir(); } catch (IOException e) { e.printStackTrace(); } } } }
Python
UTF-8
4,302
3.640625
4
[]
no_license
import random import math from playing_cards import Card from playing_cards import Deck def blackjack(): deck_cards = Deck() deck_cards.shuffle() dealt_hands = deal_hand(deck_cards) player_hand = dealt_hands[0] dealer_hand = dealt_hands[1] if calculate_hand(player_hand) == 21: initial_blackjack(dealer_hand) return 21 while calculate_hand(player_hand) < 22: turn = input("Hit or stand? h/s ") if turn.lower() in ['h', 'hit']: new_card = deck_cards.give_top_card() player_hand.append(new_card) print("You got {}.".format(new_card)) elif turn.lower() in ['s', 'stand']: while calculate_hand(dealer_hand) < 17: add_card = deck_cards.give_top_card() dealer_hand.append(add_card) end = compare_hands(player_hand, dealer_hand) if end is True: show_both_hands(dealer_hand, player_hand) print("You win") break else: show_both_hands(dealer_hand, player_hand) print("The dealer is victorious") break else: print("Choose hit if you want another card. Choose stand if you don't.") if calculate_hand(player_hand) > 21: show_both_hands(dealer_hand, player_hand) print("You went over 21. The dealer is victorious") def deal_hand(deck_cards): player_hand = [] dealer_hand = [] player_hand.append(deck_cards.give_top_card()) dealer_hand.append(deck_cards.give_top_card()) player_hand.append(deck_cards.give_top_card()) dealer_hand.append(deck_cards.give_top_card()) print("Dealer has {}".format(dealer_hand[0])) print("You have {} and {}".format(player_hand[0], player_hand[1])) return [player_hand, dealer_hand] def initial_blackjack(dealer_hand): if calculate_hand(dealer_hand) == 21: print("The dealer had:") show_full_hand(dealer_hand) print("It's a tie! You both have blackjack!") else: print("The dealer had:") show_full_hand(dealer_hand) print("You win! You got blackjack!") def show_both_hands(dealer_hand, player_hand): print("You had:") show_full_hand(player_hand) print("The dealer had:") show_full_hand(dealer_hand) def show_full_hand(hand): for i in hand: print("{}".format(i)) def calculate_hand(hand): current_hand = hand hand_value = [] ace_count = 0 for card in current_hand: if card.value in ['jack', 'queen', 'king']: hand_value.append(10) elif card.value in [2, 3, 4, 5, 6, 7, 8, 9, 10]: hand_value.append(card.value) elif card.value == 'ace': ace_count += 1 total_minus_aces = sum(hand_value) if total_minus_aces >= 11: hand_value.append(ace_count) elif total_minus_aces == 10: if ace_count == 1: hand_value.append(11) elif ace_count > 1: hand_value.append(ace_count) elif total_minus_aces <= 9: if ace_count == 1: hand_value.append(11) elif ace_count == 2: hand_value.append(12) elif ace_count == 3: if total_minus_aces == 9: hand_value.append(ace_count) elif total_minus_aces <= 8: hand_value.append(13) elif ace_count == 4: if total_minus_aces > 7: hand_value.append(ace_count) elif total_minus_aces <= 7: hand_value.append(14) total = sum(hand_value) return total def compare_hands(hand1, hand2): points1 = calculate_hand(hand1) points2 = calculate_hand(hand2) if points2 < points1 <= 21: return True elif points1 > 21: return False elif points1 <= points2 <= 21: return False elif points1 <= 21 < points2: return True def main(): while True: question = input("Care to play a hand? y/n ") if question.lower() in ['y', 'yes']: blackjack() elif question.lower() in ['n', 'no']: print("Goodbye") quit() else: print("Please answer yes or no") if __name__ == "__main__": main()
C++
UTF-8
5,795
2.8125
3
[]
no_license
#pragma once #include <algorithm> #include <array> #include <iostream> #include <vector> #include "domain/tiles/defs.hpp" #include "util/debug.hpp" #include "util/permutation.hpp" namespace mjon661 { namespace tiles { //Stores tiles as array[position] = tile at that position. template<int H, int W> struct BoardState : public Permutation<H*W, H*W> { static_assert(H > 0 && W > 0, ""); using base_t = Permutation<H*W, H*W>; using packed_t = typename base_t::Rank_t; static const size_t Max_Packed = base_t::maxRankTrunc(); BoardState() = default; BoardState(std::array<tile_t, H*W> const& o) : base_t(o) { initBlankPos(); slow_assert(base_t::valid()); } BoardState(std::vector<tile_t> const& pVec) : base_t(pVec.begin(), pVec.end()) { initBlankPos(); slow_assert(base_t::valid()); } packed_t getPacked() const { return base_t::getRank(); } void fromPacked(packed_t const& pkd) { base_t::setRank(pkd); initBlankPos(); } void initBlankPos() { mBlankPos = find(0); } idx_t find(tile_t t) const { for(idx_t i=0; i<H*W; i++) if((*this)[i] == t) return i; gen_assert(false); return 0; } void swapTiles(idx_t a, idx_t b) { tile_t t = (*this)[a]; (*this)[a] = b; (*this)[b] = t; } void moveBlank(idx_t i) { (*this)[mBlankPos] = (*this)[i]; (*this)[i] = 0; mBlankPos = i; } idx_t getBlankPos() const { return mBlankPos; } void prettyPrint(std::ostream& out) const { for(unsigned i=0; i<H; i++) { for(unsigned j=0; j<W; j++) out << (*this)[i*W + j] << " "; out << "\n"; } } bool valid() { return (*this)[mBlankPos] == 0 && Permutation<H*W,H*W>::valid(); } idx_t mBlankPos; }; //Keeps a specification of how tiles are to be eliminated during abstraction. template<unsigned N> struct TilesAbtSpec { static const unsigned Null_Idx = (unsigned)-1; static const tile_t Null_Tile = (unsigned)-1; template<typename V> TilesAbtSpec(V const& pSpec) { fast_assert(pSpec.size() == N-1); for(unsigned i=0; i<N-1; i++) mAbtSpec[i] = pSpec[i]; std::vector<unsigned> checkVec(pSpec.begin(), pSpec.end()); std::sort(checkVec.begin(), checkVec.end()); for(unsigned i=0; i<N-1; i++) { if(i != 0) fast_assert(checkVec[i] != 0 && (checkVec[i] == checkVec[i-1] || checkVec[i] == checkVec[i-1]+1)); } mTopLevel = checkVec.back(); unsigned nullIdx = Null_Idx; tile_t nullTile = Null_Tile; std::fill(mIdxOfTile.begin(), mIdxOfTile.end(), nullIdx); std::fill(mTileAtIdx.begin(), mTileAtIdx.end(), nullTile); mIdxOfTile[0] = 0; mTileAtIdx[0] = 0; unsigned pos = 1; for(unsigned lvl=mTopLevel; lvl>=1; lvl--) { for(unsigned i=0; i<N-1; i++) { if(mAbtSpec[i] == lvl) { mIdxOfTile[i+1] = pos; mTileAtIdx[pos] = i+1; ++pos; } } } } unsigned tilesKeptAtLevel(unsigned pLevel) const { unsigned n=0; for(unsigned i=0; i<N-1; i++) if(mAbtSpec[i] > pLevel) ++n; return n; } unsigned idxOfTile(tile_t t) const { slow_assert((unsigned)t < N); return mIdxOfTile[t]; } tile_t tileAtIdx(unsigned i) const { slow_assert(i < N); tile_t t = mTileAtIdx[i]; slow_assert(t != Null_Tile); return t; } private: std::array<unsigned, N-1> mAbtSpec; std::array<unsigned, N> mIdxOfTile; std::array<tile_t, N> mTileAtIdx; unsigned mTopLevel; }; template<unsigned H, unsigned W, unsigned Nkept> struct SubsetBoardState : public BoardState<H, W> { using packed_t = typename Permutation<H*W, Nkept>::Rank_t; static const unsigned Null_Idx = (unsigned)-1; static const tile_t Null_Tile = (unsigned)-1; SubsetBoardState() = default; template<typename BS> SubsetBoardState(BS const& bs, TilesAbtSpec<H*W> const& pAbtSpec) { tile_t nullTile = Null_Tile; std::fill(this->begin(), this->end(), nullTile); for(unsigned i=0; i<H*W; i++) { tile_t t = bs[i]; if(t == Null_Tile) continue; unsigned idx = pAbtSpec.idxOfTile(t); if(idx < Nkept) (*this)[i] = t; else (*this)[i] = Null_Tile; if(t == 0) this->mBlankPos = i; } } packed_t getPacked(TilesAbtSpec<H*W> const& pAbtSpec) const { Permutation<H*W, Nkept> pkd; for(unsigned i=0; i<H*W; i++) { if((*this)[i] != Null_Tile) pkd[pAbtSpec.idxOfTile((*this)[i])] = i; } return pkd.getRank(); } void fromPacked(packed_t const& r, TilesAbtSpec<H*W> const& pAbtSpec) { tile_t nullTile = Null_Tile; std::fill(this->begin(), this->end(), nullTile); Permutation<H*W, Nkept> pkd; pkd.setRank(r); for(unsigned i=0; i<Nkept; i++) (*this)[pkd[i]] = pAbtSpec.tileAtIdx(i); this->initBlankPos(); } void prettyPrint(std::ostream& out) const { for(unsigned i=0; i<H; i++) { for(unsigned j=0; j<W; j++) { if((*this)[i*W + j] == Null_Tile) out << ". "; else out << (*this)[i*W + j] << " "; } out << "\n"; } } bool valid() const { unsigned n = 0; bool foundBlank = false; for(unsigned i=0; i<H*W; i++) { if((*this)[i] != Null_Tile) ++n; else if((*this)[i] >= H*W) return false; if((*this)[i] == 0) { if(foundBlank) return false; if(this->mBlankPos != i) return false; else foundBlank = true; } } return n == Nkept && foundBlank; } bool valid(TilesAbtSpec<H*W> const& pAbtSpec) const { if(!valid()) return false; for(unsigned i=0; i<H*W; i++) { if((*this)[i] != Null_Tile && pAbtSpec.idxOfTile((*this)[i]) >= Nkept) return false; } return true; } }; }}
Java
UTF-8
1,161
1.679688
2
[]
no_license
package com.cti.vpx.listener; import com.cti.vpx.controls.hex.MemoryViewFilter; import com.cti.vpx.model.BIST; import com.cti.vpx.model.VPX.PROCESSOR_LIST; public interface VPXCommunicationListener extends VPXUDPListener { public void updateExit(int val); public void updateTestProgress(PROCESSOR_LIST pType, int val); public void updateBIST(BIST bist); // Memory Window public void readMemory(MemoryViewFilter filter); public void populateMemory(String ip,int memID, long startAddress, int stride, byte[] buffer); public void reIndexMemoryBrowserIndex(); // Plot Window public void readPlot(MemoryViewFilter filter); public void readPlot(MemoryViewFilter filter1, MemoryViewFilter filter2); public void populatePlot(int plotID, int lineID, long startAddress, byte[] buffer); public void reIndexMemoryPlotIndex(); // Spectrum Window public void readSpectrum(String ip, int core, int id); public void populateSpectrum(String ip, int core, int id, float[] yAxis); public void sendSpectrumInterrupt(String ip, int core); public void reIndexSpectrumWindowIndex(String ip, int core); }
TypeScript
UTF-8
1,764
3.640625
4
[]
no_license
//---------------------------------------- function numeroPar(arrayN:number[]):boolean{ let i:number=0; let par:boolean=false; while(i<arrayN.length && !par){ if(arrayN[i]%2==0){ par=true; } i++; } return par; } let arrayN:number[] =[23,5,1,45,2]; console.log("\n Pregunta 6: Existe numero par?: "+numeroPar(arrayN)); //------------------------------------------ function empezarM(arrayNom:string[]){ let nombresM:boolean=true; let i=0; while(i<arrayNom.length && nombresM){ if(!arrayNom[i].includes("M",0)){ nombresM=false; } i++; } console.log("\n Pregunta 7: Empiezan n M "+nombresM); } let nombres=["Maria","Manuel","Mathias","Mario"]; empezarM(nombres); //-------------------------------------------- function sumaCaracteres(caracteres:String[]){ let suma:number=0; caracteres.forEach(element => { suma +=element.length; }); return suma; } let valores =["Maria","Sergio","Cleopatra","Luis miguel"]; console.log("\n Pregunta 8: Suma de caracteres "+sumaCaracteres(valores)); //-------------------------------------------- function imparPar(numero:number){ let mensaje:string; if(numero%2==0){ mensaje="El numero es par"; } else{ mensaje="El numero es impar"; } console.log(mensaje); } //---------------------------------------------------- let array1=["Casa","Coche","Ciudad","Cesta"]; let array2=["Barco","Baca","Bicicleta","Balon","Bisiesto","Brasil"]; let array3=["Venezuela","Veneno","Voltaje"]; console.log("\n Pregunta 10: "); imparPar(sumaCaracteres(array1)); imparPar(sumaCaracteres(array2)); imparPar(sumaCaracteres(array3));
C++
UTF-8
2,187
2.546875
3
[ "LicenseRef-scancode-public-domain", "BSD-2-Clause" ]
permissive
/* $Id: fbCore.cpp,v 1.20 2008/04/23 01:21:42 ctubbsii Exp $ */ /** * fbCore.cpp * @author Byron Heads * @date March 10, 2008 */ #include "global.h" #include "fbData.h" #include "fbDiskDetector.h" #include "fbScheduler.h" #include "fbHttpServer.h" volatile bool FlashBackRunning; void sigterm_handler(int s); /** * core * Flashbacks core running file, main calls core * @note This is another usable Thread */ void core() { //Local Settings Object fbData data; //data.debug(NONE, "Testing %s %d %f", "1",2,3.0f); //data.msg(NONE, "Testing %s %d %f", "1",2,3.0f); //data.warn(NONE, "Testing %s %d %f", "1",2,3.0f); //data.err(NONE, "Testing %s %d %f", "1",2,3.0f); data.debug(NONE, "Running Debug Mode"); //should only show in debug mode! data.msg(NONE, "Flashback Started"); //Scheduler data.debug(NONE, "Making Scheduler"); //should only show in debug mode! fbScheduler scheduler(&data); scheduler.startup(); data.debug(NONE, "Scheduler Made"); //should only show in debug mode! //DiskDetector //fbDiskDetector diskdetect(&data); //diskdetect.startup(); data.debug(NONE, "Making Web Server"); //should only show in debug mode! fbHttpServer http(&data); http.startup(); data.debug(NONE, "Web Server Running"); //should only show in debug mode! //global running varible FlashBackRunning = true; // Shutdown Detector signal(SIGTERM, sigterm_handler); // data.addBackupJob(new string("backup test"), new fbDate, new fbTime, new string("/var/log/")); //data.addRestoreJob(new string("something0.tar"), new string("/home/backups/something/")); //core loop while(FlashBackRunning) { //check for exit (every 10 seconds) #ifdef Win32 Sleep(1000 * 10); #else sleep(10); #endif } //shutdown data.debug(NONE, "Shutting Down Web Server"); //should only show in debug mode! http.shutdown(); //scheduler data.debug(NONE, "Shutting Down Scheduler"); //should only show in debug mode! scheduler.shutdown(); //diskdetector //skdetect.shutdown(); data.debug(NONE, "Flashback Exiting"); //should only show in debug mode! } void sigterm_handler(int s) { signal(SIGTERM, sigterm_handler); FlashBackRunning = false; }
Markdown
UTF-8
5,417
2.953125
3
[ "MIT" ]
permissive
# TICK Sandbox This repo is a quick way to get the entire TICK Stack spun up and working together. It uses [docker](https://www.docker.com/) to spin up the full TICK stack in a connected fashion. This is heavily tested on Mac and should mostly work on linux and Windows. To get started you need a running docker installation. If you don't have one, you can download Docker for [Mac](https://www.docker.com/docker-mac) or [Windows](https://www.docker.com/docker-windows), or follow the installation instructions for Docker CE for your [Linux distribution](https://docs.docker.com/engine/installation/#server). ### Running To run the `sandbox`, simply use the convenient cli: ```bash $ ./sandbox sandbox commands: up -> spin up the sandbox environment down -> tear down the sandbox environment restart -> restart the sandbox influxdb -> attach to the influx cli enter (influxdb||kapacitor||chronograf||telegraf) -> enter the specified container logs (influxdb||kapacitor||chronograf||telegraf) -> stream logs for the specified container delete-data -> delete all data created by the TICK Stack docker-clean -> stop and remove all running docker containers rebuild-docs -> rebuild the documentation container to see updates ``` To get started just run `./sandbox up`. You browser will open two tabs: - `localhost:8888` - Chronograf's address. You will use this as a management UI for the full stack - `localhost:3000` - Documentation server. This contains a simple markdown server for tutorials and documentation. > NOTE: Make sure to stop any existing installations of `influxdb`, `kapacitor` or `chronograf`. If you have them running the sandbox will run into port conflicts and fail to properly start. In this case stop the existing processes and run `./sandbox restart`. To configure the connection to InfluxDB from Chronograf just fill in `http://influxdb:8086` as the URL: ![Configure Influx](./documentation/static/images/configure-influxdb.png) Once you have configured the InfluxDB URL you should see your dashboard: ![Dashboard](./documentation/static/images/dashboard.png) Then click on the gear icon and select `Kapacitor`: ![Kapacitor Configuration](./documentation/static/images/kapacitor-config.png) Finally, enter `http://kapacitor:9092` as the URL and click `Connect Kapacitor`: ![Kapacitor Configuration](./documentation/static/images/configure-kapacitor.png) Then you are ready to get started with the TICK Stack! Visit `http:localhost:8888` and click the host to see your dashboard, then check out the tutorials at `http://localhost:3000/tutorials`. >Note: see [influx-stress](https://github.com/influxdata/influx-stress) to create data for your sandbox. > ![Dashboard](./documentation/static/images/sandbox_dashboard.jpg) # Restore the dashboard ![Sample Dashboard](./Sample_Dashboard.png) Easiest way to get the same dashboard in the above example is to follow the guide here https://www.influxdata.com/blog/chronograf-dashboard-definitions/ and populating your own dashboard from my json dump available in the all_dashboards.json file. ## Or you can also choose to create your own dashboard Following queries can be used to create a dashboard that is similar to the one shown above ### System and user cpu usage ```SELECT mean("usage_user") AS "mean_usage_user", mean("usage_system") AS "mean_usage_system" FROM "telegraf"."autogen"."cpu" WHERE time > :dashboardTime: AND "host"='raspberrypi' GROUP BY time(10s) FILL(null)``` ### Used&Available memory (percent) ```SELECT mean("available_percent") AS "mean_available_percent", mean("used_percent") AS "mean_used_percent" FROM "telegraf"."autogen"."mem" WHERE time > :dashboardTime: AND "host"='raspberrypi' GROUP BY time(10s) FILL(null)``` ### Disk usage (percent) ```SELECT mean("used_percent") AS "mean_used_percent" FROM "telegraf"."autogen"."disk" WHERE time > :dashboardTime: AND "host"='raspberrypi' GROUP BY :interval: FILL(null)``` ### Total disk space in MB ```SELECT mean("total") / 1000000 AS "mean_total" FROM "telegraf"."autogen"."disk" WHERE time > :dashboardTime: AND "host"='raspberrypi' GROUP BY time(10s) FILL(previous)``` ### Used disk space in MB ```SELECT last("used") / 1000000 AS "last_used" FROM "telegraf"."autogen"."disk" WHERE time > :dashboardTime: AND "host"='raspberrypi' GROUP BY time(10s) FILL(previous)``` ### Available RAM ```SELECT last("total") / 1000000 AS "last_total" FROM "telegraf"."autogen"."mem" WHERE time > :dashboardTime: GROUP BY time(10s) FILL(previous)``` ### Number of CPUs ```SELECT last("n_cpus") AS "last_n_cpus" FROM "telegraf"."autogen"."system" WHERE time > :dashboardTime: AND "host"='raspberrypi' GROUP BY time(10s) FILL(previous)``` ### System Load (1m) ```SELECT mean("load1") AS "mean_load1" FROM "telegraf"."autogen"."system" WHERE time > :dashboardTime: AND "host"='raspberrypi' GROUP BY :interval: FILL(null)``` ### Network ```SELECT derivative(sum("bytes_sent"), 1s) AS "bytes_sent_per_sec", derivative(sum("bytes_recv"), 1s) AS "bytes_recv_per_sec" FROM "telegraf"."autogen"."net" WHERE time > :dashboardTime: GROUP BY time(1s)``` ### Disk I/O in Mb/s ```SELECT derivative(sum("read_bytes"), 1s) AS "mean_read_mbps", derivative(sum("write_bytes"), 1s) AS "mean_write_mbps" FROM "telegraf"."autogen"."diskio" WHERE time > :dashboardTime: AND "host"='raspberrypi' GROUP BY time(1s)```
Java
UTF-8
569
2.21875
2
[]
no_license
package view; import java.util.List; import javax.annotation.PostConstruct; import javax.faces.bean.ManagedBean; import javax.faces.bean.ViewScoped; import controller.PersonagemController; import model.Personagem; @ManagedBean(name = "personagemView") @ViewScoped public class PersonagemView { private List<Personagem> personagens; public List<Personagem> getPersonagem() { return personagens; } @PostConstruct public void init() { try { personagens = new PersonagemController().Listar(); } catch (Exception e) { e.printStackTrace(); } } }
Swift
UTF-8
5,278
4.3125
4
[]
no_license
//-------------set of classes ---------------- class Person { var name: String var age: Int init(name: String, age: Int) { self.name = name self.age = age } } //var p1 = Set<Person>() // error - type person does not conformed to protocol Hashable var p2 = [Int: Person]() // no error bcoz default hashable for dictionay values print(type(of: p2)) //var p3 = [Person: Int]() // error - Dictionary requires that person conform to hashable //conclusion - so for set and dictionay key we cannot give struct or class as a type, we need to make them hashable explicitly //Extensions can add new functionality to a type, but they can’t override existing functionality. extension Person: Hashable { static func ==(lhs: Person, rhs: Person) -> Bool { return lhs.name == rhs.name && lhs.age == rhs.age } func hash(into hasher: inout Hasher) { hasher.combine(name) hasher.combine(age) } } var person1 = Person(name: "Nive", age : 70) var person3 = person1 var person2 = Person(name: "Abdul Kalam", age : 75) print(person1 == person3) print(person1.hashValue) print(person3.hashValue) person3.age = 50 print(person1 == person3) print(person1.hashValue) print(person3.hashValue) person1.age = 70 let allPerson = [person1,person2] let searchedPerson = Person(name: "Nive", age: 70) if allPerson[0] == searchedPerson { print(false) } else if allPerson[1] == searchedPerson { print(true) } if allPerson.contains(searchedPerson) { print(true) } print(allPerson[0].hashValue) print(searchedPerson.hashValue) var s = Set<Person> () s = [person1, person2, searchedPerson] // set of classes print(s.count) print(s) // person1 and searchedPerson are same so not added //--------------dictionary key as class------------- var d = [Person: String]() print(type(of: d)) d = [person1: "First Person", person2: "Second Person"] for (key,value) in d { print(key, value) } //-----------------------------------class inside struct - compound properties - property observers // Computed properties does not require storage allocation class Student{ var id = 10 var name = "Nive" init(id: Int, name: String) { self.id = id self.name = name } } struct Department { var deptName: String var stu = Student(id: 5, name: "Mala") // 100 var newStu: Student{ // 105 get{ return stu } set{ stu.id = newValue.id stu.name = newValue.name } } var newObs: Student{ // 110 willSet{ print("newvalue") print(newValue.id) } didSet { print("oldalue") print(oldValue.id) } } } var s1 = Student(id: 0, name: "Vimala") var s2 = Student(id: 9, name: "Vimala") var n1 = Department(deptName: "Cse", stu: s1, newObs: s2)// so for get and set we dont need initialisation //expln --> 100 { id = 0, name = "vimala"} 105 { id = 0, name = "vimala"} 110 { id = 9, name = "vimala} n1.stu = s2 print(n1.stu.id) print(s2.id) print(n1.newStu.id) withUnsafePointer(to: &n1.stu.id) { (address) in print("address of n1.stu.id = \(address)") } withUnsafePointer(to: &s2.id) { (address) in print("address of s2.id = \(address)") } withUnsafePointer(to: &n1.newStu.id) { (address) in print("address of n1.newStu.id = \(address)") } n1.stu = s1 //expln --> 100 { id = 6, name = "Vimala"} 105 { id = 6, name = "vimala"} 110 { id = 9, name = "vimala"} print(n1.newStu.id) print(n1.newStu.name) print(n1.stu.id) print(n1.stu.name) print(s2.id)// value changes since we set the value as 6 print(s2.name) withUnsafePointer(to: &n1.stu.id) { (address) in print("address of n1.stu.id = \(address)") } withUnsafePointer(to: &s2.id) { (address) in print("address of s2.id = \(address)") } withUnsafePointer(to: &n1.newStu.id) { (address) in print("address of n1.newStu.id = \(address)") } n1.newObs = Student(id: 0101, name: "Sheela") print("observer") // epln --> 100 { id = 101, name ="vimala"} 105 { id = 101, name = "vimala"} 110 { id = 101, name = "vimala" } print(n1.newObs.id) print(s2.id) //------------------------ class Foo { var name: String var age: Int init(name: String, age: Int) { self.name = name self.age = age } } class StuFoo{ var myFoo : Foo { willSet { print("my foo will be: \(newValue.name)") } didSet { print("my foo was: \(oldValue.name)") } } init(myFoo: Foo) { self.myFoo = myFoo } } var struct1 = StuFoo(myFoo: Foo(name: "James", age: 33)) var class1 = Foo(name: "John", age: 33) struct1.myFoo = class1 struct1.myFoo.name = "sachin" print(struct1.myFoo.name) print(class1.name) var class2 = Foo(name: " Sun", age: 33) struct1.myFoo = class2 print(class1.name) //-------------------very important---------- class Class { var i = 0 init(i: Int){ self.i = i } } var a = Class(i: 1) var b = Class(i: 2) var c = a print(c.i) c.i = 5 print(c.i) print(a.i) c = b // c is no more same as a's reference coz here a and b points to diff instance of the class c.i = 7 print(c.i) print(b.i) print(a.i)
Java
UTF-8
472
2.046875
2
[]
no_license
package com.kepler.jd.sdk.exception; public class KeplerNoThisCategoryException extends Exception { private static final long serialVersionUID = 1; public KeplerNoThisCategoryException() { } public KeplerNoThisCategoryException(String str, Throwable th) { super(str, th); } public KeplerNoThisCategoryException(String str) { super(str); } public KeplerNoThisCategoryException(Throwable th) { super(th); } }
Java
UTF-8
3,972
2.34375
2
[]
no_license
package com.pages; import com.WebDriverSingleton; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.List; /** * Created by VocaLink on 27/04/2017. */ public class FootballPage { private String odds; private Double odds_fractionToDecimalValue; public FootballPage(){ } public void clickonFootballButton(){ WebDriverWait wait = new WebDriverWait(WebDriverSingleton.getInstance().getDriver(), 20); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#nav-football > i"))); WebDriverSingleton.getInstance().getDriver().findElement(By.cssSelector("#nav-football > i")).click(); } public String getOdds(){ return odds; } public void selectFirstMatch(){ int numerator =0; int deominator =0; WebDriverWait wait = new WebDriverWait(WebDriverSingleton.getInstance().getDriver(), 20); wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("btmarket__selection"))); List<WebElement> betbutton__odds = WebDriverSingleton.getInstance().getDriver().findElements(By.className("btmarket__selection")); String[] split = betbutton__odds.get(0).getText().split("/"); numerator = Integer.parseInt(split[0]); deominator= Integer.parseInt(split[1]); // work out the odds odds_fractionToDecimalValue = (double)numerator / deominator; odds_fractionToDecimalValue = odds_fractionToDecimalValue +1; betbutton__odds.get(0).click(); } public Double getOdds_fractionToDecimalValue() { return odds_fractionToDecimalValue; } public void placebetAmount(String amount) { WebDriverWait wait = new WebDriverWait(WebDriverSingleton.getInstance().getDriver(), 20); wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("betslip-selection__stake-input"))); List<WebElement> betbutton__placeamount = WebDriverSingleton.getInstance().getDriver().findElements(By.className("betslip-selection__stake-input")); betbutton__placeamount.get(0).sendKeys(amount); } public void clickPlaceBet(){ // WebDriverWait wait = new WebDriverWait(WebDriverSingleton.getInstance().getDriver(), 20); // wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#place-bet-button"))); // WebDriverSingleton.getInstance().getDriver().findElement(By.cssSelector("#place-bet-button")).click(); } public Double getCurrentBalance(){ WebDriverWait wait = new WebDriverWait(WebDriverSingleton.getInstance().getDriver(), 20); wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#userBalance"))); String strAmount = WebDriverSingleton.getInstance().getDriver().findElement(By.cssSelector("#userBalance")).getText().substring(1); return Double.valueOf(strAmount); } public Double getBettoReuturn() { WebDriverWait wait = new WebDriverWait(WebDriverSingleton.getInstance().getDriver(), 20); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("total-to-return-price"))); return Double.valueOf(WebDriverSingleton.getInstance().getDriver().findElement(By.id("total-to-return-price")).getText().substring(1)); } public Double getTotalStake(){ //total-stake-price WebDriverWait wait = new WebDriverWait(WebDriverSingleton.getInstance().getDriver(), 20); wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("total-stake-price"))); return Double.valueOf(WebDriverSingleton.getInstance().getDriver().findElement(By.id("total-stake-price")).getText().substring(1)); } }
Java
UTF-8
651
1.78125
2
[]
no_license
package com.example.tanawatk.mvvmandroid.service.repo; import android.content.Context; import com.example.tanawatk.mvvmandroid.common.ResponseHandler; import com.example.tanawatk.mvvmandroid.di.qualifier.ApplicationContext; import com.example.tanawatk.mvvmandroid.service.model.ResponseModel; import javax.inject.Inject; public interface NewsDataSource { void getNews(int id, ResponseHandler<ResponseModel> responseHandler); void loadNews(ResponseHandler<ResponseModel> responseHandler); void loadDatabase(ResponseHandler<ResponseModel> responseHandler); void saveDatabase(ResponseModel model); void deleteDatabase(); }
C#
UTF-8
1,485
2.921875
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace lab_5 { public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { Form1 F1 = new Form1(); F1.Show(); this.Hide(); } private void button1_Click(object sender, EventArgs e) { try { double R = double.Parse(textBox1.Text); if (R < 0) { MessageBox.Show("Радиус не может быть отрицательными!"); textBox1.Focus(); } else { Сфера sph = new Сфера(); label4.Text = "" + string.Format("{0:f2}", sph.S(R)); label5.Text = "" + string.Format("{0:f2}", sph.V(R)); } } catch (FormatException) { MessageBox.Show("Необходимо радиус в виде числовом виде!"); textBox1.TabIndex = 0; return; } } } }
Markdown
UTF-8
4,169
2.984375
3
[ "Apache-2.0" ]
permissive
程序员最佳网站 ====== ![][1] 作为程序员,你经常会发现自己是某些网站的永久访问者。它们可以是教程、参考或论坛。因此,在这篇文章中,让我们看看给程序员的最佳网站。 ### W3Schools W3Schools 是为初学者和有经验的 Web 开发人员学习各种编程语言的最佳网站之一。你可以学习 HTML5、CSS3、PHP、 JavaScript、ASP 等。 更重要的是,该网站为网页开发人员提供了大量资源和参考资料。 [![w3schools logo][2]][3] 你可以快速浏览各种关键字及其功能。该网站非常具有互动性,它允许你在网站本身的嵌入式编辑器中尝试和练习代码。该网站是你作为网页开发人员经常访问的少数网站之一。 ### GeeksforGeeks GeeksforGeeks 是一个主要专注于计算机科学的网站。它有大量的算法,解决方案和编程问题。 [![geeksforgeeks programming support][4]][5] 该网站也有很多面试中经常问到的问题。由于该网站更多地涉及计算机科学,因此你可以找到很多编程问题在大多数著名语言下的解决方案。 ### TutorialsPoint 一个学习任何东西的地方。TutorialsPoint 有一些又好又简单的教程,它可以教你任何编程语言。我真的很喜欢这个网站,它不仅限于通用编程语言。 ![](http://www.theitstuff.com/wp-content/uploads/2017/12/tutorialspoint-programming-website.png) 你可以在这里上找到几乎所有语言框架的教程。 ### StackOverflow 你可能已经知道 StackOverflow 是遇到程序员的地方。你在代码中遇到问题,只要在 StackOverflow 问一个问题,来自互联网的程序员将会在那里帮助你。 [![stackoverflow linux programming website][6]][7] 关于 StackOverflow 最好的部分是几乎所有的问题都得到了答案。你可能会从其他程序员的几个不同观点获得答案。 ### HackerRank HackerRank 是一个你可以参与各种编码竞赛并检测你的竞争能力的网站。 [![hackerrank programming forums][8]][9] 这里有以各种编程语言举办的各种比赛,赢得比赛将增加你的分数。这个分数可以让你处于最高级别,并增加你获得一些软件公司注意的机会。 ### Codebeautify 由于我们是程序员,所以美不是我们所关心的。很多时候,我们的代码很难被其他人阅读。Codebeautify 可以使你的代码易于阅读。 ![](http://www.theitstuff.com/wp-content/uploads/2017/12/code-beautify-programming-forums.png) 该网站有大多数可以美化的语言。另外,如果你想让你的代码不能被某人读取,你也可以这样做。 这些是我选择的一些最好的程序员网站。如果你有经常访问的我没有提及的网站,请在下面的评论区让我知道。 -------------------------------------------------------------------------------- via: http://www.theitstuff.com/best-websites-programmers 作者:[Rishabh Kandari][a] 选题:[lujun9972](https://github.com/lujun9972) 译者:[geekpi](https://github.com/geekpi) 校对:[校对者ID](https://github.com/校对者ID) 本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译,[Linux中国](https://linux.cn/) 荣誉推出 [a]:http://www.theitstuff.com/author/reevkandari [1]:http://www.theitstuff.com/wp-content/uploads/2017/12/best-websites-for-programmers.jpg [2]:http://www.theitstuff.com/wp-content/uploads/2017/12/w3schools-logo-550x110.png [3]:http://www.theitstuff.com/wp-content/uploads/2017/12/w3schools-logo.png [4]:http://www.theitstuff.com/wp-content/uploads/2017/12/geeksforgeeks-programming-support-550x152.png [5]:http://www.theitstuff.com/wp-content/uploads/2017/12/geeksforgeeks-programming-support.png [6]:http://www.theitstuff.com/wp-content/uploads/2017/12/stackoverflow-linux-programming-website-550x178.png [7]:http://www.theitstuff.com/wp-content/uploads/2017/12/stackoverflow-linux-programming-website.png [8]:http://www.theitstuff.com/wp-content/uploads/2017/12/hackerrank-programming-forums-550x118.png [9]:http://www.theitstuff.com/wp-content/uploads/2017/12/hackerrank-programming-forums.png
Java
UTF-8
2,949
3.34375
3
[]
no_license
package com.java.hackerrank.trie; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; public class Contacts { private static Map<Character, Trie> contactsList = new HashMap<>(); private static final Scanner scanner = new Scanner(System.in); private static int[] contacts(String[][] queries) { List<Integer> result = new ArrayList<>(); for (int i = 0; i < queries.length; i++) { String ops = queries[i][0]; String data = queries[i][1]; if (contactsList.containsKey(data.charAt(0))) { Trie node = contactsList.get(data.charAt(0)); } else { if ("find".equals(ops)) { result.add(0); } else if ("add".equals(ops)) { Trie node = addContact(data, 0); contactsList.put(data.charAt(0), node); } } } return result.stream().mapToInt(Integer::intValue).toArray(); } private static int findContact(Trie trie, String partial, int index) { int length = 0; if (trie == null || partial == null) { return 0; } if (trie.getTries().isEmpty() && !trie.isLastLetter()) { return 0; } if (trie.getData() != partial.charAt(index)) { return 0; } for (Trie node : trie.getTries()) { length = 1 + findContact(node, partial.substring(index + 1, partial.length()), index + 1); } return length; } private static Trie addContact(String contact, int index) { if (contact == null || contact.isEmpty()) { return null; } Trie node = new Trie(contact.charAt(index)); Trie nextNode = addContact(contact.substring(index + 1, contact.length()), index + 1); if (nextNode == null) { List<Trie> tries = new ArrayList<>(); tries.add(nextNode); node.setTries(tries); } node.setLastLetter(true); return node; } public static void main(String[] args) throws IOException { int queriesRows = Integer.parseInt(scanner.nextLine().trim()); String[][] queries = new String[queriesRows][2]; for (int queriesRowItr = 0; queriesRowItr < queriesRows; queriesRowItr++) { String[] queriesRowItems = scanner.nextLine().split(" "); for (int queriesColumnItr = 0; queriesColumnItr < 2; queriesColumnItr++) { String queriesItem = queriesRowItems[queriesColumnItr]; queries[queriesRowItr][queriesColumnItr] = queriesItem; } } int[] result = contacts(queries); for (int resultItr = 0; resultItr < result.length; resultItr++) { System.out.println(result[resultItr]); } } } class Trie { private Character data; private boolean isLastLetter; private List<Trie> tries; public Trie(Character data) { this.data = data; } public Character getData() { return data; } public List<Trie> getTries() { return tries; } public boolean isLastLetter() { return isLastLetter; } public void setLastLetter(boolean isLastLetter) { this.isLastLetter = isLastLetter; } public void setTries(List<Trie> tries) { this.tries = tries; } }
Java
UTF-8
2,882
1.914063
2
[ "Unlicense" ]
permissive
package viaversion.viaversion.protocols.protocol1_13to1_12_2.providers.blockentities; import com.github.steveice10.opennbt.tag.builtin.CompoundTag; import com.github.steveice10.opennbt.tag.builtin.IntTag; import com.github.steveice10.opennbt.tag.builtin.ListTag; import com.github.steveice10.opennbt.tag.builtin.StringTag; import com.github.steveice10.opennbt.tag.builtin.Tag; import java.util.Iterator; import net.aYj; import net.cX; import viaversion.viaversion.api.Via; import viaversion.viaversion.api.data.UserConnection; import viaversion.viaversion.api.minecraft.Position; import viaversion.viaversion.protocols.protocol1_13to1_12_2.ChatRewriter; import viaversion.viaversion.protocols.protocol1_13to1_12_2.providers.BlockEntityProvider$BlockEntityHandler; public class BannerHandler implements BlockEntityProvider$BlockEntityHandler { private static final int WALL_BANNER_START = 7110; private static final int WALL_BANNER_STOP = 7173; private static final int BANNER_START = 6854; private static final int BANNER_STOP = 7109; public int transform(UserConnection var1, CompoundTag var2) { aYj.b(); cX var4 = (cX)var1.b(cX.class); Position var5 = new Position((int)this.getLong(var2.get("x")), (short)((int)this.getLong(var2.get("y"))), (int)this.getLong(var2.get("z"))); if(!var4.c(var5)) { Via.getPlatform().getLogger().warning("Received an banner color update packet, but there is no banner! O_o " + var2); return -1; } else { int var6 = var4.b(var5).getOriginal(); Tag var7 = var2.get("Base"); int var8 = 0; if(var7 != null) { var8 = ((Number)var2.get("Base").getValue()).intValue(); } if(var6 >= 6854 && var6 <= 7109) { var6 += (15 - var8) * 16; } if(var6 >= 7110 && var6 <= 7173) { var6 += (15 - var8) * 4; } Via.getPlatform().getLogger().warning("Why does this block have the banner block entity? :(" + var2); if(var2.get("Patterns") instanceof ListTag) { Iterator var9 = ((ListTag)var2.get("Patterns")).iterator(); if(var9.hasNext()) { Tag var10 = (Tag)var9.next(); if(var10 instanceof CompoundTag) { Tag var11 = ((CompoundTag)var10).get("Color"); if(var11 instanceof IntTag) { ((IntTag)var11).setValue(15 - ((Integer)var11.getValue()).intValue()); } } } } Tag var12 = var2.get("CustomName"); if(var12 instanceof StringTag) { ((StringTag)var12).setValue(ChatRewriter.legacyTextToJsonString(((StringTag)var12).getValue())); } return var6; } } private long getLong(Tag var1) { return ((Integer)var1.getValue()).longValue(); } }
C
ISO-8859-1
1,779
3.96875
4
[]
no_license
/* Fuente: ESPACIOS.C Programa: ELIMINA ESPACIOS POR LA DERECHA E IZQUIERDA Descripcin: Las funciones ELIMINA_ESPACIOS_IZQ y ELIMINA_ESPACIOS_DER, reciben una cadena de caracteres y devuelven la propia cadena una vez que han eliminado respectivamente los espacios en blanco de comienzo y final de la cadena */ #include <stdio.h> #include <stdlib.h> #include <string.h> void elimina_espacios_izq (char *); void elimina_espacios_der (char *); int main(void) { char cadena[] = " Texto para ejemplo de espaciado "; printf("\nCadena original:\n>>>%s<<<\n", cadena); elimina_espacios_izq(cadena); printf("\nSin espacios por la izquierda:\n>>>%s<<<\n", cadena); elimina_espacios_der(cadena); printf("\nSin espacios por la derecha:\n>>>%s<<<\n", cadena); printf ("\n\n"); system ("pause"); return 0; } void elimina_espacios_izq (char *cad) { const char BLANCO = ' '; int k, k2; /* localizamos el primer carcter no espacio */ k=0; while (cad[k] == BLANCO) k++; /* desplazamos todos los elementos hacia el principio de la cadena */ k2 = 0; while (cad[k] != '\0') cad[k2++] = cad[k++]; /* hemos terminado porque cadena[k] vale '\0', por lo que */ /* desplazamos este carcter tambin */ cad[k2] = cad[k]; } void elimina_espacios_der (char *cad) { const char BLANCO = ' '; int k; /* desde el final de la cadena vamos hacia atrs hasta localizar el */ /* primer carcter no espacio */ k = strlen(cad) - 1; while ( (cad[k] == BLANCO) && (k >= 0) ) k--; /* k apunta al primer carcter por la derecha no espacio, por lo que */ /* colocamos un \0 en el siguiente */ cad[++k] = '\0'; }
Ruby
UTF-8
944
2.546875
3
[ "MIT" ]
permissive
require "test_helper" class NebTest < Neb::TestCase def setup @account = Neb::Account.create @password = '123456' end def test_create_account_with_random_private_key assert_equal 64, @account.private_key.size assert_equal 128, @account.public_key.size assert_equal 35, @account.address.size end def test_create_account_from_exist_private_key another_account = Neb::Account.new(private_key: @account.private_key) assert_equal @account.private_key, another_account.private_key assert_equal @account.public_key, another_account.public_key assert_equal @account.address, another_account.address end def test_create_account_from_key_file @account.set_password(@password) key_file = @account.to_key_file another_account = Neb::Account.from_key_file(key_file: key_file, password: @password) assert_equal @account.private_key, another_account.private_key end end
PHP
UTF-8
3,496
2.96875
3
[]
no_license
<?php /** * Created by JetBrains PhpStorm. * User: wickb * Date: 07.08.13 * Time: 17:54 * To change this template use File | Settings | File Templates. */ namespace TechDivision\PhpTokenUsage\Entities; class Result { public $name = ''; public $labels = array(); public $fileCount = 0; public $duration = 0.0; public $data = array(); public $tokenCount = 0; /** * @return string */ public function createString() { // We pre-build the data part of our string, so we got the colors already for later (earlier) use $tmp = array(); $color = array(); foreach ($this->data as $token => $data) { $color[$token][1] = (int) rand(150, 255); $color[$token][2] = (int) rand(25, 150); $color[$token][3] = (int) rand(25, 150); $tmp[] = '{ fillColor : "rgba(' . $color[$token][1] . ',' . $color[$token][2] . ',' . $color[$token][3] . ',0.5)", strokeColor : "rgba(' . $color[$token][1] . ',' . $color[$token][2] . ',' . $color[$token][3] . ',1)", pointColor : "rgba(' . $color[$token][1] . ',' . $color[$token][2] . ',' . $color[$token][3] . ',1)", pointStrokeColor : "#fff", data : [' . implode(',', $data) . '] }'; } // Now as we as we got the different colors, we can create one for the headline $masterColor = array(); $masterColor[1] = $masterColor[2] = $masterColor[3] = 0; $tokenCount = count($this->data); foreach ($color as $colorAspect) { $masterColor[1] += $colorAspect[1] / $tokenCount; $masterColor[2] += $colorAspect[2] / $tokenCount; $masterColor[3] += $colorAspect[3] / $tokenCount; } $result = ''; $result .= ' <h3>For <span style="color:rgba(' . (int) $masterColor[1] . ',' . (int) $masterColor[2] . ',' . (int) $masterColor[3] . ',1);">'. $this->name . '</span></h3> <span>...we analyzed <span style="color:rgba(' . (int) $masterColor[1] . ',' . (int) $masterColor[2] . ',' . (int) $masterColor[3] . ',1);">'. $this->tokenCount . '</span> tokens within <span style="color:rgba(' . (int) $masterColor[1] . ',' . (int) $masterColor[2] . ',' . (int) $masterColor[3] . ',1);">'. $this->fileCount . '</span> files in <span style="color:rgba(' . (int) $masterColor[1] . ',' . (int) $masterColor[2] . ',' . (int) $masterColor[3] . ',1);">'. number_format($this->duration, 2) . '</span> seconds.</span> <canvas id="' . $this->name . '" width="450" height="350"></canvas> <script type="text/javascript">var ' . $this->name . 'Data = { labels : ["' . implode('","', $this->labels) . '"], datasets : ['; $result .= implode(',', $tmp); $result .= '] };'; // Create the code to initialize the graph $result .= ' var ' . $this->name . ' = document.getElementById("' . $this->name . '").getContext("2d"); var ' . $this->name . 'Chart = new Chart(' . $this->name . ').Line(' . $this->name . 'Data); </script>'; // Create the legend foreach ($this->data as $token => $data) { $result .= '<span class="push-left token" style="color:#fff; background-color: rgba(' . $color[$token][1] . ',' . $color[$token][2] . ',' . $color[$token][3] . ',1)">' . token_name($token) . '</span>'; } return $result; } }
Java
UTF-8
1,696
2.234375
2
[]
no_license
package Model; import java.util.ArrayList; public class LibModel { private String book_id; public ArrayList<String> branch_id= new ArrayList<String>(); public ArrayList<Integer> no_copies= new ArrayList<Integer>(); public ArrayList<Integer> available= new ArrayList<Integer>(); private int brid; private String card; public ArrayList<String> book_ids= new ArrayList<String>(); public ArrayList<String> book_titles= new ArrayList<String>(); public ArrayList<String> names= new ArrayList<String>(); public ArrayList<String> addresses= new ArrayList<String>(); public ArrayList<String> phones= new ArrayList<String>(); public ArrayList<String> cards= new ArrayList<String>(); public ArrayList<String> date_out= new ArrayList<String>(); public ArrayList<String> due_date= new ArrayList<String>(); private String fname; private String lname; private String address; private String phone; public String getBook_id() { return book_id; } public void setBook_id(String book_id) { this.book_id = book_id; } public String getCard() { return card; } public void setCard(String card) { this.card = card; } public int getBrid() { return brid; } public void setBrid(int brid) { this.brid = brid; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
Java
UTF-8
1,707
2.609375
3
[]
no_license
package com.sky.flow.exception; import java.util.Arrays; import java.util.List; import java.util.logging.Level; /** * 流程异常 * @author 王帆 * @date 2019年5月16日 下午3:30:55 */ public class FlowException extends Exception{ /***/ private static final long serialVersionUID = 1L; private Level level; private String code; private List<String> errorMessages; public FlowException(String message) { this(null, message,null); } public FlowException(String message,Level level) { this(null,message,level); } public FlowException(String code,String message,Level level) { this(null,message==null?null:Arrays.asList(message),level); } public FlowException(List<String> messages) { this(null,messages,null); } public FlowException(List<String> messages,Level level) { this(null,messages,level); } public FlowException(String code,List<String>messages,Level level) { super(messages.toString()); this.code=code==null?"flow_-1":code; this.setErrorMessages(messages); this.level=level==null?Level.INFO:level; } public FlowException(String message, Throwable e) { super(e); this.code=code==null?"flow_-1":code; this.setErrorMessages(Arrays.asList(message)); this.level=level==null?Level.INFO:level; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Level getLevel() { return level; } public void setLevel(Level level) { this.level = level; } public List<String> getErrorMessages() { return errorMessages; } public void setErrorMessages(List<String> errorMessages) { this.errorMessages = errorMessages; } }
C
UTF-8
378
2.53125
3
[]
no_license
#include <stdint.h> #include "joystick.h" #include "movement.h" action_t movementFromJoystick(){ uint16_t moves = 0; moves += readJoystick(JOYSTICK_MIDDLE) << 0; moves += readJoystick(JOYSTICK_LEFT) << 1; moves += readJoystick(JOYSTICK_RIGHT) << 2; moves += readJoystick(JOYSTICK_UP) << 3; moves += readJoystick(JOYSTICK_DOWN) << 4; return moves; }
C#
UTF-8
3,535
2.859375
3
[]
no_license
using System; using System.Linq; namespace OpenIRacingTools.Sdk { public static class Calculations { public static TimeSpan? CalculateDeltaBetweenCars(this Sdk sdk, int carIdxAhead, int carIdxBehind) { if (sdk.TelemetryData == null) { return null; } // First try to calculate with the estimated time to current location which is most precise but not always reliably available. var estTimeAhead = sdk.TelemetryData.CarIdxEstTime.Value[carIdxAhead]; var estTimeBehind = sdk.TelemetryData.CarIdxEstTime.Value[carIdxBehind]; if (estTimeAhead > 0 && estTimeBehind > 0 && estTimeAhead > estTimeBehind) { return TimeSpan.FromSeconds(estTimeAhead - estTimeBehind); } // Get the percentage and estimated time completed of this lap var percentageAhead = sdk.TelemetryData.CarIdxLapDistPct.Value[carIdxAhead]; var percentageBehind = sdk.TelemetryData.CarIdxLapDistPct.Value[carIdxBehind]; float percentageDiff; if (percentageAhead > percentageBehind) { // This is the usual case. Car ahead has a higher lap completion percentage than car behind. We can just use // the estimated time to current location on track. percentageDiff = percentageAhead - percentageBehind; } else { // Now that car behind seems to be further than car ahead means that car ahead already crossed the finish line // but car behind didn't. So let's use the car ahead's estimated time to location on track and the car behind's // estimated time left on this lap. percentageDiff = percentageAhead + 1 - percentageBehind; } // Calculate diff using the last lap time of the car behind var lastLapTime = sdk.TelemetryData.CarIdxLastLapTime.Value[carIdxBehind]; return lastLapTime > -1 ? TimeSpan.FromSeconds(lastLapTime * percentageDiff) : null; } public static TimeSpan? CalculateEstimatedTimeToFinishLine(this Sdk sdk, int carIdx) { if (sdk.TelemetryData == null) { return null; } // Get the percentage and estimated time completed of this lap var percentage = sdk.TelemetryData.CarIdxLapDistPct.Value[carIdx]; var estimate = sdk.TelemetryData.CarIdxEstTime.Value[carIdx]; // Try to get fastest lap time as a reference var fastestTime = sdk.SessionData?.SessionInfo?.CurrentSession?.ResultsPositions?.SingleOrDefault(x => x.CarIdx == carIdx)?.FastestTime; if (fastestTime.HasValue) { // Calculate a more accurate estimation using the fastest lap time if available. return fastestTime.Value * (1 - percentage); } // Use the current estimated time on this lap return TimeSpan.FromSeconds(estimate / percentage * (1 - percentage)); } public static TimeSpan? CalculateTimeFromFinishLine(this Sdk sdk, int carIdx) { // Get the percentage and estimated time completed of this lap var estimate = sdk.TelemetryData?.CarIdxEstTime.Value[carIdx]; return estimate.HasValue ? TimeSpan.FromSeconds(estimate.Value) : null; } } }
Markdown
UTF-8
631
3.546875
4
[]
no_license
# 1 https://www.careercup.com/question?id=5174694727647232 Given a 2D matrix of integers, sort it such that: - every row is sorted in ascending order from left to right - every column is sorted in ascending order from top to down - all items in the same row are unique You may assume the input matrix is always valid, meaning that such a sort is always possible. For example: for input matrix 1 3 5 3 2 4 the output could be any of the following: valid output #1: 1 3 4 2 3 5 valid output #2: 1 2 3 3 4 5 valid output #3: 1 3 4 2 3 5 Follow-up: What if all items in the same column are also required to be unique?
JavaScript
UTF-8
1,934
3.0625
3
[ "MIT" ]
permissive
/** * Status model builder class. * * @namespace status-model * @returns A status builder access object. */ function nonDataStatusResponse() { var util = require('util'); var constants = require('../constants'); /** * Build a blank status object. * <pre><code> * { * status: null, * info: null, * msg: null * } * </code></pre> * * @memberOf status-model * @returns A blank status object. */ function blank() { return { status: null, info: null, msg: null }; } /** * Build a populated status object. * <pre><code> * { * status: {status}, * info: {info}, * msg: {msg} * } * </code></pre> * * @memberOf status-model * @param {any} status The status to set (err|warn|ok) * @param {any} info Relevant status info. * @param {any} msg A short status message. * @returns A status object. */ function build(status, info, msg) { var st = blank(); st.status = status; st.info = info; if (arguments.length === 3) { st.msg = msg; } else if (arguments.length === 4 && typeof(arguments[3]) === 'string') { st.msg = util.format(msg, arguments[3]); } return st; } /** * Build a default OK status object. * * @memberOf status-model * @param {any} info Relevant information (optional). * @returns A default OK status object. */ function ok(info) { var st = blank(); st.status = constants.status.OK; if (info !== null) { st.info = info; } return st; } return { status: { blank: blank, build: build, ok: ok } }; } module.exports = nonDataStatusResponse();
C++
UTF-8
542
2.671875
3
[]
no_license
int main() { int a[5][5],i,j; int k,m,n,l,p=0,flag=0; for(i=0;i<=4;i++) { for(j=0;j<=4;j++) { scanf("%d",&a[i][j]); } } for(i=0;i<=4;i++) { k=a[i][0];m=i;n=0; for(j=1;j<=4;j++)//in a row { if(a[i][j]>k) { k=a[i][j]; m=i;n=j; } } for(l=0;l<=4;l++)//in the column. { if(a[l][n]<a[m][n]) { p++; break; } } if(p==0) { printf("%d %d %d\n",m+1,n+1,k); flag++; } p=0; } if(flag==0)printf("not found\n"); return 0; }
Markdown
UTF-8
1,865
4.28125
4
[]
no_license
# Binary Tree Level Order Traversal II **题目:** Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left to right, level by level from leaf to root). **翻译:** 给定一个二叉树,返回它的节点的值的自底向上的顺序遍历的结果。(即,从左到右,从叶子到根) **例子:** ``` Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its bottom-up level order traversal as: [ [15,7], [9,20], [3] ] ``` **思路:** * 首先,建立一个二维数组,将根节点放进去 * 然后循环,将每层的节点都放入一个数组中,然后将这个数组放入二维数组中 * 每次遍历一层的数组,来形成下一层的数组,然后直至最后一层 * 然后遍历二维数组,将节点替换成节点值 * 然后翻转二维数组 **代码实现:** ```javascript /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @return {number[][]} */ var levelOrderBottom = function(root) { const treeArr = []; if(!root) return treeArr; else treeArr.push([root]); let i = 0; while(true){ let arr = treeArr[i]; let nextArr = []; for(let j = 0; j < arr.length; j++){ let node = arr[j]; if(node.left) nextArr.push(node.left); if(node.right) nextArr.push(node.right); } if(!nextArr.length) break; treeArr.push(nextArr); i++; } for(let i = treeArr.length - 1; i >= 0; i--){ for(let j = 0; j < treeArr[i].length; j++){ treeArr[i][j] = treeArr[i][j].val; } } return treeArr.reverse(); }; ```
Java
UTF-8
2,827
2.59375
3
[]
no_license
package com.domain.admin; import com.domain.people.Learner; import org.springframework.boot.autoconfigure.domain.EntityScan; import java.util.Objects; import java.util.Set; @EntityScan public class Attendance { private String learnerID; private int noOfDaysAbsent; private String noOfDaysPresent; private Attendance(){} private Set<Class> classes; private Set<Learner> learners; private Attendance(Builder builder) { this.learnerID = builder.learnerID; this.noOfDaysPresent = builder.noOfDaysPresent; this.noOfDaysAbsent = builder.noOfDaysAbsent; } public String getLearnerID(){return learnerID;} public void setLearnerID(String learnerID) { this.learnerID = learnerID; } public void setNoOfDaysAbsent(int noOfDaysAbsent) { this.noOfDaysAbsent = noOfDaysAbsent; } public void setNoOfDaysPresent(String noOfDaysPresent) { this.noOfDaysPresent = noOfDaysPresent; } public int getNumberOfDaysAbsent() { return noOfDaysAbsent; } public String getNumberOfDaysPresent() { return noOfDaysPresent; } public static class Builder { private String learnerID; private int noOfDaysAbsent; private String noOfDaysPresent; private Set<Class> classes; private Set<Learner> learners; public Builder learnerID(String learnerID) { this.learnerID = learnerID; return this; } public Builder noOfDaysAbsent(int noOfDaysAbsent) { this.noOfDaysAbsent = noOfDaysAbsent; return this; } public Builder noOfDaysPresent(String noOfDaysPresent) { this.noOfDaysPresent = noOfDaysPresent; return this; } public Builder copy(Attendance attendance){ this.learnerID = attendance.learnerID; this.noOfDaysPresent = attendance.noOfDaysPresent; this.noOfDaysAbsent = attendance.noOfDaysAbsent; return this; } public Attendance build() { return new Attendance(this); } } @Override public String toString() { return "Attendance {" + "learnerID" + learnerID + '\'' + "numberOfDaysPresent" + noOfDaysPresent + '\'' + "numberOfDaysAbsent" + noOfDaysAbsent + '\'' + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Attendance attendance = (Attendance) o; return learnerID.equals(attendance.learnerID); } @Override public int hashCode() { return Objects.hash(learnerID); } }
Python
UTF-8
4,648
2.640625
3
[]
no_license
import numpy as np import pandas import tensorflow as tf import csv import os, time import matplotlib as mpl if os.environ.get('DISPLAY','') == '': print('no display found. Using non-interactive Agg backend') mpl.use('Agg') import matplotlib.pyplot as plt MAX_DOCUMENT_LENGTH = 100 MAX_LABEL = 15 HIDDEN_SIZE = 20 no_epochs = 1000 lr = 0.01 tf.logging.set_verbosity(tf.logging.ERROR) seed = 10 tf.set_random_seed(seed) def char_rnn_model(x): input_layer = tf.reshape( tf.one_hot(x, 256), [-1, MAX_DOCUMENT_LENGTH, 256]) cell = tf.nn.rnn_cell.GRUCell(HIDDEN_SIZE) _, encoding = tf.nn.dynamic_rnn(cell, input_layer, dtype=tf.float32) # Dropout - controls the complexity of the model, prevents co-adaptation of features keep_prob = tf.placeholder(tf.float32) encoding = tf.nn.dropout(encoding, keep_prob) logits = tf.layers.dense(encoding, MAX_LABEL, activation=None) return keep_prob, input_layer, logits def read_data_chars(): x_train, y_train, x_test, y_test = [], [], [], [] with open('train_medium.csv', encoding='utf-8') as filex: reader = csv.reader(filex) for row in reader: x_train.append(row[1]) print(row[1]) y_train.append(int(row[0])) with open('test_medium.csv', encoding='utf-8') as filex: reader = csv.reader(filex) for row in reader: x_test.append(row[1]) y_test.append(int(row[0])) x_train = pandas.Series(x_train) y_train = pandas.Series(y_train) x_test = pandas.Series(x_test) y_test = pandas.Series(y_test) char_processor = tf.contrib.learn.preprocessing.ByteProcessor(MAX_DOCUMENT_LENGTH) x_train = np.array(list(char_processor.fit_transform(x_train))) x_test = np.array(list(char_processor.transform(x_test))) y_train = y_train.values y_test = y_test.values return x_train, y_train, x_test, y_test def buildandrunmodel(x_train, y_train, x_test, y_test, keep_proba): # Create the model x = tf.placeholder(tf.int64, [None, MAX_DOCUMENT_LENGTH]) y_ = tf.placeholder(tf.int64) keep_prob, inputs, logits = char_rnn_model(x) # Optimizer entropy = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits_v2(labels=tf.one_hot(y_, MAX_LABEL), logits=logits)) correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(tf.one_hot(y_, MAX_LABEL), 1)) correct_prediction = tf.cast(correct_prediction, tf.float32) accuracy = tf.reduce_mean(correct_prediction) train_op = tf.train.AdamOptimizer(lr).minimize(entropy) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # training loss = [] test_acc = [] for e in range(no_epochs): input_layer_, _, loss_ = sess.run([inputs, train_op, entropy], {x: x_train, y_: y_train, keep_prob: keep_proba}) loss.append(loss_) test_acc.append(accuracy.eval(feed_dict={x: x_test, y_: y_test, keep_prob: keep_proba})) # print("input_layer_.shape", input_layer_.shape) # if e % 1 == 0: # print('iter: %d, entropy: %g' % (e, loss[e])) # print('iter: %d, test accuracy: %g' % (e, test_acc[e])) start = time.time() accuracy.eval(feed_dict={x: x_test, y_: y_test, keep_prob: keep_proba}) end = time.time() inference_dur = end - start print("Inference runtime: ", inference_dur) # plot learning curves plt.figure(1) plt.clf() plt.plot(range(no_epochs), loss, 'r', label='Training Loss') # plt.legend(loc='upper left') plt.xlabel('epochs') plt.ylabel('loss') plt.title('Training Loss for keep prop: ' + str(keep_proba)) plt.savefig('char_rnn_dropout_figs/loss_' + str(keep_proba) + '.png') plt.figure(2) plt.clf() plt.plot(range(no_epochs), test_acc, 'g', label='Test Accuracy') # plt.legend(loc='upper left') plt.xlabel('epochs') plt.ylabel('Accuracy') plt.title('Test Accuracy for keep prop: ' + str(keep_proba)) plt.savefig('char_rnn_dropout_figs/accuracy_' + str(keep_proba) + '.png' ) def main(): x_train, y_train, x_test, y_test = read_data_chars() print(len(x_train)) print(len(x_test)) for kp in range(1, 10, 2): print("Keep prob: ", kp/10) buildandrunmodel(x_train, y_train, x_test, y_test, kp/10) tf.reset_default_graph() print("=====================================================================") if __name__ == '__main__': main()
JavaScript
UTF-8
1,145
2.84375
3
[ "CC0-1.0" ]
permissive
fs = require('fs'); global.geocodelist = null; function loadGeocoder() { console.log("Loading Geocoder"); var res = fs.readFileSync('./api/helpers/countries_geocoded.json'); global.geocodelist = JSON.parse(res).data; return global.geocodelist; } module.exports = { geoCodeByISO3: function(ccc) { if(ccc.length !== 3 ) { return "Country code must only be three characters long"; } if(global.geocodelist == null) { loadGeocoder(); } for(var i = 0; i < global.geocodelist.length; i++) { if(global.geocodelist[i][10] === ccc.toUpperCase()) { return global.geocodelist[i]; } } }, geoCodeByISO2: function (cc) { if(cc.length !== 2) { return "Country code must only be two characters long"; } if(global.geocodelist == null) { loadGeocoder(); } for(var i = 0; i < global.geocodelist.length; i++) { if(global.geocodelist[i][9] === cc.toUpperCase()) { return global.geocodelist[i]; } } } };
JavaScript
UTF-8
522
2.546875
3
[]
no_license
// Hamburger Menu Open Close on Mobile document.querySelector('.toggle').addEventListener('click', () => { document.querySelector('.toggle').classList.toggle('active'); document.querySelector('nav').classList.toggle('active'); }); //Form Submit Response document.querySelector('form').addEventListener('submit', e => { e.preventDefault(); console.log('Form Submitted'); document.querySelector('.reaching-out').style.display = 'block'; document.querySelector('form').style.display = 'none'; });
Java
UTF-8
4,183
2.015625
2
[]
no_license
package com.yuanbao.park.shiro.VO; import java.util.Date; import java.util.List; import com.yuanbao.park.entity.UUser; public class UserVO { private Long id; private String name; private String password; private String salt; private String department; private String position; private Long parkId; private String email; private String deleteType; private Date createtime; private Date updatetime; private Date lastlogintime; private Long status; private List<String> roleStrlist; private List<String> perminsStrlist; public UserVO() { super(); // TODO Auto-generated constructor stub } public UserVO(UUser uUser, List<String> roleStrlist, List<String> perminsStrlist) { super(); this.id = uUser.getId(); this.name = uUser.getName(); this.password = uUser.getPassword(); this.salt = uUser.getSalt(); this.department = uUser.getDepartment(); this.position = uUser.getPosition(); this.parkId = uUser.getParkId(); this.email = uUser.getEmail(); this.deleteType = uUser.getDeleteType(); this.createtime = uUser.getCreatetime(); this.updatetime = uUser.getUpdatetime(); this.lastlogintime = uUser.getLastlogintime(); this.status = uUser.getStatus(); this.roleStrlist = roleStrlist; this.perminsStrlist = perminsStrlist; } public UserVO(Long id, String name, String password, String salt, String department, String position, Long parkId, String email, String deleteType, Date createtime, Date updatetime, Date lastlogintime, Long status, List<String> roleStrlist, List<String> perminsStrlist) { super(); this.id = id; this.name = name; this.password = password; this.salt = salt; this.department = department; this.position = position; this.parkId = parkId; this.email = email; this.deleteType = deleteType; this.createtime = createtime; this.updatetime = updatetime; this.lastlogintime = lastlogintime; this.status = status; this.roleStrlist = roleStrlist; this.perminsStrlist = perminsStrlist; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getSalt() { return salt; } public void setSalt(String salt) { this.salt = salt; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public Long getParkId() { return parkId; } public void setParkId(Long parkId) { this.parkId = parkId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getDeleteType() { return deleteType; } public void setDeleteType(String deleteType) { this.deleteType = deleteType; } public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } public Date getUpdatetime() { return updatetime; } public void setUpdatetime(Date updatetime) { this.updatetime = updatetime; } public Date getLastlogintime() { return lastlogintime; } public void setLastlogintime(Date lastlogintime) { this.lastlogintime = lastlogintime; } public Long getStatus() { return status; } public void setStatus(Long status) { this.status = status; } public List<String> getRoleStrlist() { return roleStrlist; } public void setRoleStrlist(List<String> roleStrlist) { this.roleStrlist = roleStrlist; } public List<String> getPerminsStrlist() { return perminsStrlist; } public void setPerminsStrlist(List<String> perminsStrlist) { this.perminsStrlist = perminsStrlist; } }
Markdown
UTF-8
815
2.515625
3
[]
no_license
titanium-formatted-field ================================================= This module returns extended TextField. It fixes [JIRA TIMOB-7637](https://jira.appcelerator.org/browse/TIMOB-7637) - inability to set field max length on Android. Entry may be restricted on length, content (numbers/phonenumbers/anychar) and numeric value (no larger than x…). Basic Usage: ------------ ```JavaScript var FF=require("formattedfield"); var textFieldForNumbersUpTo3CharsValueLessThan888 = FF.createFormattedTextField( {top:20, left:20, width:'60%', backgroundColor:'#bbb'}, length=3, type=FF.NUMBER_NO_LARGER_THAN, nolargerthan=888); win.add(textFieldForNumbersUpTo3CharsValueLessThan888); ```
Markdown
UTF-8
1,404
3.109375
3
[]
no_license
# lecture ## Swift(구조체와 클래스) ### 구조체선언법: struct 구조체이름{ 프로퍼티와 메서드 } ### 클래스선언법: class 클래스 이름 { 프로퍼티와 메서드들 } ### Class, Struct의 공통점 값을 저장할 프로퍼티를 선언할 수 있습니다. 함수적 기능을 하는 메서드를 선언 할 수 있습니다. 내부 값에. 을 사용하여 접근할 수 있습니다. 생성자를 사용해 초기 상태를 설정할 수 있습니다. extension을 사용하여 기능을 확장할 수 있습니다. Protocol을 채택하여 기능을 설정할 수 있습니 ### Class (클래스) 참조 타입입니다. ARC로 메모리를 관리합니다. 같은 클래스 인스턴스를 여러 개의 변수에 할당한 뒤 값을 변경시키면 할당한 모든 변수에 영향을 줍니다. (메모리만 복사) 상속이 가능합니다. 타입 캐스팅을 통해 런타임에서 클래스 인스턴스의 타입을 확인할 수 있습니다. deinit을 사용하여 클래스 인스턴스의 메모리 할당을 해제할 수 있습니다. ### Struct (구조체) 값 타입입니다. 구조체 변수를 새로운 변수에 할당할 때마다 새로운 구조체가 할당됩니다. 즉 같은 구조체를 여러 개의 변수에 할당한 뒤 값을 변경시키더라도 다른 변수에 영향을 주지 않습니다. (값 자체를 복사)
Java
UTF-8
1,702
2.515625
3
[]
no_license
package com.udacity.jwdnd.course1.cloudstorage.services; import com.udacity.jwdnd.course1.cloudstorage.mapper.FilesMapper; import com.udacity.jwdnd.course1.cloudstorage.model.BinaryFile; import com.udacity.jwdnd.course1.cloudstorage.model.Files; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.util.ArrayList; import java.util.Base64; import java.util.List; @Service public class FilesService { private final FilesMapper filesMapper; public FilesService(FilesMapper filesMapper) { this.filesMapper = filesMapper; } public BinaryFile getBinary(Files file){ String base64 = Base64.getEncoder().encodeToString(file.getFiledata()); String url = "data:"+file.getContenttype()+";base64"+base64; BinaryFile binaryFile = new BinaryFile(file.getFileid(),file.getFilename(),url); return binaryFile; } public List<BinaryFile> getNotesById(Integer userid) throws Exception { List<Files> list = filesMapper.getById(userid); List<BinaryFile> binaryFiles= new ArrayList<BinaryFile>(); if(list == null){ throw new Exception(); } Integer fileSize = list.size(); for(int i = 0; i<fileSize ; i++ ){ binaryFiles.add(getBinary(list.get(i))); } return binaryFiles; } public void insert(MultipartFile file, Integer userid) throws IOException { filesMapper.fileInsert(file.getOriginalFilename(),file.getContentType(),(int) file.getSize(),file.getBytes(),userid); } public void delete(Integer fileid){ filesMapper.fileDelete(fileid); } }
Java
UTF-8
287
1.554688
2
[]
no_license
package com.miduchina.wrd.api.mapper.heatanalysis; import com.miduchina.wrd.po.home.HeatShare; import org.apache.ibatis.annotations.Mapper; /** * @auther Administrator * @vreate 2019-05 16:43 */ @Mapper public interface HeatMapper { HeatShare findShareCode(String shareCode); }