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
623
1.992188
2
[]
no_license
package net.furikuri.web; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class BookController { private Logger logger = LoggerFactory.getLogger(BookController.class); @Value("${eureka.instance.metadataMap.instanceId:-}") private String name; @RequestMapping("/") public String simple() { logger.info("Got request"); return "{ \"name\" : \"" + name + "\"}"; } }
Java
UTF-8
2,294
2.546875
3
[]
no_license
package com.hsmdata.springTest.common.framework.filter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.core.NamedThreadLocal; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; public class StopWatchHandlerInterceptor implements HandlerInterceptor { private final Logger log = LoggerFactory.getLogger(LoginInterceptor.class); private NamedThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<>("StopWatch-StartTime"); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // TODO Auto-generated method stub log.info("==============执行顺序: 1、" + this.getClass().getName() + " preHandle================"); long startTime = System.currentTimeMillis();// 开始时间 startTimeThreadLocal.set(startTime);// 线程绑定变量(该数据只有当前请求的线程可见) return true;// 继续流程 } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // TODO Auto-generated method stub log.info("==============执行顺序: 2、" + this.getClass().getName() + " postHandle================"); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { // TODO Auto-generated method stub log.info("==============执行顺序: 3、" + this.getClass().getName() + " afterCompletion================"); long endTime = System.currentTimeMillis();// 结束时间 long startTime = startTimeThreadLocal.get();// 得到线程绑定的局部变量(开始时间) long consumeTime = endTime - startTime;// 3、消耗的时间 if (consumeTime > 500) {// 此处认为处理时间超过500毫秒的请求为慢请求 // TODO 记录到日志文件 System.out.println(String.format("%s consumes %d mills", request.getRequestURI(), consumeTime)); } else { System.out.println(request.getRequestURI() + " is fast."); } } }
Shell
UTF-8
609
3.46875
3
[]
no_license
#!/bin/bash mkdir -p Database; if [ $# -eq 0 ]; then echo "Expected argument: Path to the database."; echo "Optional argument: 1 for demo. 0 for default ie no demo" elif [ $# -eq 1 ]; then find $1/ -iname '*.mp4' -exec ./FaceDetector {} 0 \; elif [ $# -eq 2 ]; then find $1/ -iname '*.mp4' -exec ./FaceDetector {} $2 \; fi #python src/python/fulldbfile.py if [ $# -eq 0 ]; then echo -e "All the videos have been processed. The generation of the database is complete!\n"; echo -e "Now you can modify the labels of the file Database/Caffe_Files/full_database.txt. Then just launch ./trainandval.sh\n" fi
Python
UTF-8
1,991
3
3
[]
no_license
import gym import os from DQN import Deep_Q_Network import numpy as np env = gym.make('CartPole-v0') state_size = env.observation_space.shape[0] action_size = env.action_space.n print(state_size) batch_size = 32 n_episode = 100 OP_dir = 'cartpole_output/' if not os.path.exists(OP_dir): os.mkdir(OP_dir) agent = Deep_Q_Network(state_size, action_size) done =False for e in range(n_episode): state = env.reset() state = np.reshape(state, [1,state_size]) for time in range(10000): env.render() # select an action based on epsilon given a the last state the selection action is played using take_action method #which select random action from a given action set action = agent.take_action(state) #observe reward and next state #done is a boolean flag to tell if it either the end of the game by lossing or the end of the episodo next_state, reward, done, info = env.step(action) #storing the reward equal to the returned reward from the environment if we are not done reward = reward if not done else -10 #storing the received next state and saving it, the reshape is to transpose the next state to match our neural model next_state = np.reshape(next_state, [1, state_size]) #store our experiences in experience_table (replay_memory) agent.store_experience(state, action,reward, next_state, done) #mapping the next state to be the current state state = next_state #If the game is finish before our episodes as the agent lost break if done: print ("episode:{}/{}, score:{:}".format(e, n_episode, time, agent.epsilon)) break # sample a set of our experience replay according to the batch size if len(agent.experience_table) > batch_size : agent.replay(batch_size) if e % 50 == 0: agent.save(OP_dir + "weights" + "{:04d}.format(e)" + ".hdf5") env.close()
C#
UTF-8
1,198
3.734375
4
[]
no_license
using System; namespace _05_chain_of_responsibility { class Handler { Handler next; int id; public int Limit { get; set; } public Handler(int id, Handler handler) { this.id = id; this.Limit = id * 1000; this.next = handler; } public string HandleRequest(int data) { if (data < this.Limit) return "Request for " + data + " handled at level " + this.id; else if (this.next != null) return next.HandleRequest(data); else return ("Request for " + data + " handled BY DEFAULT at level " + this.id); } } class Program { static void Main() { Handler start = null; for (int i = 5; i > 0; i--) { Console.WriteLine("Handler " + i + " deals up to a limit of " + i * 1000); start = new Handler(i, start); } int[] a = { 50, 2000, 1500, 10000, 175, 4500 }; foreach (int i in a) { Console.WriteLine(start.HandleRequest(i)); } } } }
JavaScript
UTF-8
90
2.671875
3
[]
no_license
var a = "Amigo"; alert(a.toLowerCase()); alert(a.replace("A","a")); alert(a-("A"));
Java
UTF-8
4,319
1.8125
2
[]
no_license
package com.paladin.hf.controller.assess.quantificate; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.druid.util.StringUtils; import com.paladin.framework.core.ControllerSupport; import com.paladin.framework.web.response.CommonResponse; import com.paladin.hf.model.assess.quantificate.AssessItem; import com.paladin.hf.model.assess.quantificate.AssessItemExtra; import com.paladin.hf.model.assess.quantificate.AssessQuantitativeResult; import com.paladin.hf.service.assess.quantificate.AssessCycleTemplateService; import com.paladin.hf.service.assess.quantificate.AssessItemExtraService; import com.paladin.hf.service.assess.quantificate.AssessItemService; import com.paladin.hf.service.assess.quantificate.AssessQuantitativeResultService; import com.paladin.hf.service.org.OrgUserService; @Controller @RequestMapping("/assess/template/item") public class AssessItemController extends ControllerSupport{ @Autowired private AssessItemService assessItemService; @Autowired private AssessItemExtraService assessItemExtraService; @Autowired private AssessCycleTemplateService assessCycleTemplateService; @Autowired private OrgUserService orgUserService; @Autowired private AssessQuantitativeResultService assessQuantitativeResultService; @ResponseBody @RequestMapping(value = "/get") public Object getTemplateItems(@RequestParam(required = true) String id) { return CommonResponse.getSuccessResponse(assessItemService.findTemplateAssessItem(id)); } @RequestMapping("/save") @ResponseBody public Object save(@Valid AssessItem assessItem, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return this.validErrorHandler(bindingResult); } if(StringUtils.isEmpty(assessItem.getParentItemId())){ assessItem.setParentItemId(null); } return CommonResponse.getResponse(assessItemService.saveOrUpdate(assessItem)); } @RequestMapping("/delete") @ResponseBody public Object delete(@RequestParam(required = true) String id) { return CommonResponse.getResponse(assessItemService.removeByPrimaryKey(id)); } @ResponseBody @RequestMapping(value = "/extra/get") public Object getTemplateExtraItems(@RequestParam(required = true) String id) { return CommonResponse.getSuccessResponse(assessItemExtraService.findTemplateAssessExtraItem(id)); } @RequestMapping("/extra/save") @ResponseBody public Object saveExtra(@Valid AssessItemExtra assessItemExtra, BindingResult bindingResult) { if (bindingResult.hasErrors()) { return this.validErrorHandler(bindingResult); } if(AssessItemExtra.EXTRA_TYPE_VETO.equals(assessItemExtra.getExtraType())) { assessItemExtra.setAlterLower(null); assessItemExtra.setAlterUpper(null); assessItemExtra.setAccumulateUpper(null); } if(assessItemExtra.getId() == null || assessItemExtra.getId().length() == 0) { return CommonResponse.getResponse(assessItemExtraService.save(assessItemExtra)); } else { return CommonResponse.getResponse(assessItemExtraService.updateSelective(assessItemExtra)); } } @RequestMapping("/extra/delete") @ResponseBody public Object deleteExtra(@RequestParam(required = true) String id) { return CommonResponse.getResponse(assessItemExtraService.removeByPrimaryKey(id)); } @RequestMapping("/extra/cycle") @ResponseBody public Object getCycleExtraItems(@RequestParam String id, @RequestParam String userId) { AssessQuantitativeResult aqResult = assessQuantitativeResultService.getResult(userId, id); String unit = null; if(aqResult != null) { unit = aqResult.getUnitId(); } if(unit == null || unit.length() ==0){ unit = orgUserService.get(userId).getOrgUnitId(); } //OrgUser user = orgUserService.get(userId); return CommonResponse.getSuccessResponse(assessItemExtraService.findTemplateAssessExtraItem(assessCycleTemplateService.getTemplateByCycle(id, unit))); } }
Rust
UTF-8
13,693
2.65625
3
[ "Apache-2.0" ]
permissive
// Copyright 2018-2022 Cargill Incorporated // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //! A routing table for directing messages to nodes and services based on defined circuits. //! //! The routing table stores information required for routing messages to nodes and services that //! are a part of a circuit. The routing table is split into two traits, a reader and a writer. //! A writer is used to update the routing table with circuit, node, and service routing //! information. For example, the `AdminService` uses a writer when a new circuit has been added to //! Splinter state. Components that require routing information must use a reader. For example, //! the dispatch handlers use the reader to route messages to services or other nodes on a circuit. //! //! The public interface includes the traits [`RoutingTableReader`] and [`RoutingTableWriter`] and //! the structs [`Service`], [`ServiceId`], [`Circuit`], and [`CircuitNode`]. It also includes //! a RwLock implementation of the traits [`RoutingTable`]. //! //! [`Circuit`]: struct.Circuit.html //! [`CircuitNode`]: struct.CircuitNode.html //! [`RoutingTable`]: memory/struct.RoutingTable.html //! [`RoutingTableReader`]: trait.RoutingTableReader.html //! [`RoutingTableWriter`]: trait.RoutingTableWriter.html //! [`Service`]: struct.Service.html //! [`ServiceId`]: struct.ServiceId.html mod error; pub mod memory; use std::cmp::Ordering; use std::fmt; pub use self::error::RoutingTableReaderError; use crate::error::InternalError; use crate::error::InvalidStateError; use crate::peer::{PeerAuthorizationToken, PeerTokenPair}; use crate::public_key::PublicKey; /// Interface for updating the routing table pub trait RoutingTableWriter: Send { /// Adds a new service to the routing table /// /// # Arguments /// /// * `service_id` - The unique ServiceId for the service /// * `service` - The service to be added to the routing table fn add_service(&mut self, service_id: ServiceId, service: Service) -> Result<(), InternalError>; /// Removes a service from the routing table if it exists /// /// # Arguments /// /// * `service_id` - The unique ServiceId for the service fn remove_service(&mut self, service_id: &ServiceId) -> Result<(), InternalError>; /// Adds a new circuit to the routing table. Also adds the associated services and nodes. /// /// # Arguments /// /// * `circuit_id` - The unique ID for the circuit /// * `circuit` - The circuit to be added to the routing table /// * `nodes` - The list of circuit nodes that should be added along with the circuit fn add_circuit( &mut self, circuit_id: String, circuit: Circuit, nodes: Vec<CircuitNode>, ) -> Result<(), InternalError>; /// Adds a list of circuits to the routing table. Also adds the associated services. /// /// # Arguments /// /// * `circuits` - The list of circuits to be added to the routing table fn add_circuits(&mut self, circuits: Vec<Circuit>) -> Result<(), InternalError>; /// Removes a circuit from the routing table if it exists. Also removes the associated /// services. /// /// # Arguments /// /// * `circuit_id` - The unique ID for the circuit fn remove_circuit(&mut self, circuit_id: &str) -> Result<(), InternalError>; /// Adds a new node to the routing table /// /// # Arguments /// /// * `node_id` - The unique ID for the node /// * `node`- The node to add to the routing table fn add_node(&mut self, node_id: String, node: CircuitNode) -> Result<(), InternalError>; /// Adds a list of node to the routing table /// /// # Arguments /// /// * `nodes`- The list of nodes to add to the routing table fn add_nodes(&mut self, nodes: Vec<CircuitNode>) -> Result<(), InternalError>; /// Removes a node from the routing table if it exists /// /// # Arguments /// /// * `node_id` - The unique ID for the node that should be removed fn remove_node(&mut self, node_id: &str) -> Result<(), InternalError>; fn clone_boxed(&self) -> Box<dyn RoutingTableWriter>; } impl Clone for Box<dyn RoutingTableWriter> { fn clone(&self) -> Self { self.clone_boxed() } } /// Type returned by the `RoutingTableReader::list_nodes` method pub type CircuitNodeIter = Box<dyn ExactSizeIterator<Item = (String, CircuitNode)> + Send>; /// Type returned by the `RoutingTableReader::list_circuits` method pub type CircuitIter = Box<dyn ExactSizeIterator<Item = (String, Circuit)> + Send>; /// Interface for reading the routing table pub trait RoutingTableReader: Send { // ---------- methods to access service directory ---------- /// Returns the service with the provided ID /// /// # Arguments /// /// * `service_id` - The unique ID for the service to be fetched fn get_service( &self, service_id: &ServiceId, ) -> Result<Option<Service>, RoutingTableReaderError>; /// Returns all the services for the provided circuit /// /// # Arguments /// /// * `circuit_id` - The unique ID the circuit whose services should be returned fn list_services(&self, circuit_id: &str) -> Result<Vec<Service>, RoutingTableReaderError>; // ---------- methods to access circuit directory ---------- /// Returns the nodes in the routing table fn list_nodes(&self) -> Result<CircuitNodeIter, RoutingTableReaderError>; /// Returns the node with the provided ID /// /// # Arguments /// /// * `node_id` - The unique ID for the node to be fetched fn get_node(&self, node_id: &str) -> Result<Option<CircuitNode>, RoutingTableReaderError>; /// Returns the circuits in the routing table fn list_circuits(&self) -> Result<CircuitIter, RoutingTableReaderError>; /// Returns the circuit with the provided ID /// /// # Arguments /// /// * `circuit_id` - The unique ID for the circuit to be fetched fn get_circuit(&self, circuit_id: &str) -> Result<Option<Circuit>, RoutingTableReaderError>; fn clone_boxed(&self) -> Box<dyn RoutingTableReader>; } impl Clone for Box<dyn RoutingTableReader> { fn clone(&self) -> Self { self.clone_boxed() } } /// The routing table representation of a circuit. It is simplified to only contain the required /// values for routing. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Circuit { circuit_id: String, roster: Vec<Service>, members: Vec<String>, authorization_type: AuthorizationType, } impl Circuit { /// Creates a new `Circuit` /// /// # Arguments /// /// * `circuit_id` - The unique ID for the circuit /// * `roster` - The list of services in the circuit /// * `members` - The list of node IDs for the members of a circuit /// * `authorization_type` - The authorization type used for the circuit pub fn new( circuit_id: String, roster: Vec<Service>, members: Vec<String>, authorization_type: AuthorizationType, ) -> Self { Circuit { circuit_id, roster, members, authorization_type, } } /// Returns the ID of the circuit pub fn circuit_id(&self) -> &str { &self.circuit_id } /// Returns the list of service that are in the circuit pub fn roster(&self) -> &[Service] { &self.roster } /// Returns the list of node IDs that are in the circuit pub fn members(&self) -> &[String] { &self.members } /// Returns the authorization type pub fn authorization_type(&self) -> &AuthorizationType { &self.authorization_type } } #[derive(Clone, Debug, PartialEq, Eq)] pub enum AuthorizationType { Trust, Challenge, } /// The routing table representation of a node #[derive(Clone, Debug, PartialEq, Eq)] pub struct CircuitNode { node_id: String, endpoints: Vec<String>, public_key: Option<PublicKey>, } impl CircuitNode { /// Creates a new `CircuitNode` /// /// # Arguments /// /// * `node_id` - The unique ID for the circuit /// * `endpoints` - A list of endpoints the node can be reached at /// * `public_key` - The public key associated with the node pub fn new(node_id: String, endpoints: Vec<String>, public_key: Option<PublicKey>) -> Self { CircuitNode { node_id, endpoints, public_key, } } pub fn get_peer_auth_token( &self, auth_type: &AuthorizationType, ) -> Result<PeerAuthorizationToken, RoutingTableReaderError> { match auth_type { AuthorizationType::Trust => Ok(PeerAuthorizationToken::from_peer_id(&self.node_id)), AuthorizationType::Challenge => { let public_key = self.public_key.clone().ok_or_else(|| { RoutingTableReaderError::InvalidStateError(InvalidStateError::with_message( format!( "Circuit Node {} does not have public key and challenge authorization was requested", self.node_id ), )) })?; Ok(PeerAuthorizationToken::from_public_key( public_key.as_slice(), )) } } } } impl Ord for CircuitNode { fn cmp(&self, other: &Self) -> Ordering { self.node_id.cmp(&other.node_id) } } impl PartialOrd for CircuitNode { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } /// The routing table representation of a service #[derive(Clone, Debug, PartialEq, Eq)] pub struct Service { service_id: String, service_type: String, node_id: String, arguments: Vec<(String, String)>, local_peer_id: Option<PeerTokenPair>, } impl Service { /// Creates a new `Service` /// /// # Arguments /// /// * `service_id` - The unique ID for the service /// * `service_type` - The type of service this is /// * `node_id` - The node ID that this service can connect to /// * `arguments` - The key-value pairs of arguments that will be passed to the service pub fn new( service_id: String, service_type: String, node_id: String, arguments: Vec<(String, String)>, ) -> Self { Service { service_id, service_type, node_id, arguments, local_peer_id: None, } } /// Returns the ID of the service pub fn service_id(&self) -> &str { &self.service_id } /// Returns the service type of the service pub fn service_type(&self) -> &str { &self.service_type } /// Returns the node ID of the node the service can connect to pub fn node_id(&self) -> &str { &self.node_id } /// Returns the list of key/value arguments for the service pub fn arguments(&self) -> &[(String, String)] { &self.arguments } /// Returns the local peer ID for the service pub fn local_peer_id(&self) -> &Option<PeerTokenPair> { &self.local_peer_id } pub fn set_local_peer_id(&mut self, peer_id: PeerTokenPair) { self.local_peer_id = Some(peer_id) } pub fn remove_local_peer_id(&mut self) { self.local_peer_id = None } #[deprecated(since = "0.7.0", note = "please use `local_peer_id` instead")] pub fn peer_id(&self) -> &Option<PeerTokenPair> { self.local_peer_id() } #[deprecated(since = "0.7.0", note = "please use `set_local_peer_id` instead")] pub fn set_peer_id(&mut self, peer_id: PeerTokenPair) { self.set_local_peer_id(peer_id) } #[deprecated(since = "0.7.0", note = "please use `remove_local_peer_id` instead")] pub fn remove_peer_id(&mut self) { self.remove_local_peer_id() } } /// The unique ID of a service made up of a circuit ID and service ID #[derive(Clone, Debug, Hash, PartialEq)] pub struct ServiceId { circuit_id: String, service_id: String, } impl ServiceId { /// Creates a new `ServiceId` /// /// # Arguments /// /// * `circuit_id` - The unique ID for the circuit this service belongs to /// * `service_id` - The unique ID for the service pub fn new(circuit_id: String, service_id: String) -> Self { ServiceId { circuit_id, service_id, } } /// Returns the circuit ID pub fn circuit(&self) -> &str { &self.circuit_id } /// Returns the service ID pub fn service_id(&self) -> &str { &self.service_id } /// Decompose the service ID into a tuple of (<circuit ID>, <service ID>). pub fn into_parts(self) -> (String, String) { (self.circuit_id, self.service_id) } } impl fmt::Display for ServiceId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}::{}", self.circuit_id, self.service_id) } } impl Eq for ServiceId {}
Java
UTF-8
543
1.96875
2
[]
no_license
package com.longchang.www.entity; public class UserMinemachine { private Integer id; private Integer userid; private Integer mmid; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getUserid() { return userid; } public void setUserid(Integer userid) { this.userid = userid; } public Integer getMmid() { return mmid; } public void setMmid(Integer mmid) { this.mmid = mmid; } }
Java
UTF-8
561
2.109375
2
[]
no_license
package Test.Const; import java.awt.*; public class Const { public static String gameTitle="坦克大战"; public static int frameWidth= (int)(Toolkit.getDefaultToolkit().getScreenSize().getWidth()/2); public static int frameHeight=(int)(Toolkit.getDefaultToolkit().getScreenSize().getHeight()/2); public static String tankImageUp="Image/tank_up.jpg"; public static String tankImageDown="Image/tank_down.jpg"; public static String tankImageRight="Image/tank_right.jpg"; public static String tankImageLeft="Image/tank_left.jpg"; }
Python
UTF-8
1,022
4.4375
4
[ "MIT" ]
permissive
def selection_sort(arr): for x in range(len(arr)): min_index = find_min(arr, x) arr[x], arr[min_index] = arr[min_index], arr[x] return arr def find_min(arr, start): min = arr[start] index = start for x in range(start + 1, len(arr)): if arr[x] < min: min = arr[x] index = x return index print("\t\t**SELECTION SORT**") for x in range(5): print("*"*x) # worst case scenario. array is in descending order arr = [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] # or generate array using range(10, 0, -1) print(f"Worst case scenario with input arr = {arr}\nResult:\t{selection_sort(arr)}\n") # average case scenario. arr = [5, 4, 3, 2, 1, 10, 9, 8, 7, 6] print(f"Average case scenario with input arr = {arr}\nResult:\t{selection_sort(arr)}\n") # best case scenario. array is already sorted arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # or generate array using range(1, 11) print(f"Best case scenario with input arr = {arr}\nResult:\t{selection_sort(arr)}\n")
Python
UTF-8
432
3.234375
3
[]
no_license
x1, y1, r = [int(n) for n in input().split()] x2, y2, x3, y3 = [int(n) for n in input().split()] def sqdist(x1,y1,x2,y2): return (x1-x2)**2 + (y1-y2)**2 if x1 - x2 >= r and x3 - x1 >= r and y3 - y1 >= r and y1 - y2 >= r: print('NO') else: print('YES') if sqdist(x1,y1,x2,y2) <= r**2 and sqdist(x1,y1,x3,y3) <= r**2 and sqdist(x1,y1,x2,y3) <= r**2 and sqdist(x1,y1,x3,y2) <= r**2: print('NO') else: print('YES')
Java
UTF-8
306
2.71875
3
[]
no_license
package com.innovaccer.assignment.Interface; public class Implementation implements Int1,Int2 { public void show() { /*Int1.super.show(); Int2.super.show();*/ } public static void main(String arg[]) { Implementation ob=new Implementation(); ob.show(); Int1 o=new Implementation(); } }
Python
UTF-8
5,390
2.640625
3
[ "BSD-3-Clause" ]
permissive
import subprocess def numLinesInFile(fname): """ Counts the number of lines in the given file. """ with open(fname) as f: for i, l in enumerate(f): pass return i + 1 def lineIntoMap(ln): """id=1715 : name=March 7 2013\n""" pairs = ln.split(':') m = dict() for p in pairs: (key,eq,val) = p.partition('=') assert eq != '' m[key.strip()] = val.strip() return m def idnameMapIntoPairs(m): assert 'id' in m assert 'name' in m return (int(m['id']), m['name']) class StarExecCredentials: def __init__(self, starexeccommand, username, password, addr): self.secommand = starexeccommand self.seusername = username self.sepassword = password self.seaddr = addr def starexeccommand(self): return self.secommand def username(self): return self.seusername def password(self): return self.sepassword def address(self): return self.seaddr def __str__(self): s = 'StarExecCredentials(' s += repr(self.starexeccommand())+', ' s += repr(self.username())+', ' s += repr(self.password())+', ' s += repr(self.address())+')' return s class StarExecPipe: """A pipe to execute a sequence of star exec commands""" cmd_prompt='StarCom> ' blank_cmd_prompt=cmd_prompt+'\n' def __init__(self, cred, prefix = None): assert isinstance(cred, StarExecCredentials) self.prefix = prefix args = ['java','-jar', cred.starexeccommand()] self.pipe = subprocess.Popen(args, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, bufsize=1) ln = self.readLine() # consume Last update = .. ln = self.readLine() # consume <blankline> retids = self.prompt('returnids') if retids != []: print "retids", repr(retids) loginstr = 'login u='+cred.username()+' p='+cred.password()+' addr='+cred.address() resp = self.prompt(loginstr) if self.prefix is not None: print self.prefix, print "Logging", cred.username() , "into starexec ", cred.address(), if not self.loginResponseIsOkay(resp): print "login failed" print "resp", repr(resp) self.close() raise Exception("login failed", resp) else: print "login successful" def __enter__(self): assert self.is_open() return self; def __exit__(self, type, value, traceback): self.close() def is_open(self): return self.pipe.returncode == None def close(self): self.pipe.poll() if self.is_open(): resp = self.pipe.communicate("logout") if self.prefix is not None: print self.prefix, print "Logging out of star exec", resp def readLine(self): """Do not call this from outside of the class""" assert self.is_open() return self.pipe.stdout.readline() def writeLine(self, line): """Do not call this from outside of the class""" assert self.is_open() print >> self.pipe.stdin, line self.pipe.stdin.flush() def prompt(self, cmd): self.writeLine(cmd) # send the command #consume exactly one command prompt first = self.readLine() ind = first.find(StarExecPipe.cmd_prompt) assert ind == 0 pos = len(StarExecPipe.cmd_prompt) lines = [] line = first[pos:] #print "sub", pos, repr(line) #print "first", repr(first) while line != '\n': #print "read", len(lines), repr(line) # stop at the first empty line lines.append(line) #print lines line = self.readLine() return lines def lssubspaces(self, space_id): lines = self.prompt('lssubspaces id='+str(space_id)) #print lines return [ idnameMapIntoPairs(lineIntoMap(x)) for x in lines ] def lsbenchmarks(self, space_id): lines = self.prompt('lsbenchmarks id='+str(space_id)) #print lines return [ idnameMapIntoPairs(lineIntoMap(x)) for x in lines ] def lssolvers(self, space_id): """lssolvers id=14436 id=668 : name=test (recycled) id=669 : name=took2 (recycled) id=670 : name=took3 (recycled) id=671 : name=took4""" lines = self.prompt('lssolvers id='+str(space_id)) pair_list = [ idnameMapIntoPairs(lineIntoMap(x)) for x in lines ] rec = [(x,y) for x,y in pair_list if y.endswith("(recycled)")] notrec = [(x,y) for x,y in pair_list if not y.endswith("(recycled)")] return rec, notrec def getjobpair(self, jobpair, out, ow): query = 'getjobpair id='+str(jobpair)+' out='+out if ow is not None: query += ' ow=' #print "issuing", query resp = self.prompt(query) #print "getjobpair", resp def getjobinfo(self, job_id, out, ow): query = 'getjobinfo id='+str(job_id)+' out='+out query += ' incids=' if ow is not None: query += ' ow=' print query resp = self.prompt(query) print "getjobinfo", resp def loginResponseIsOkay(self, resp): return resp != 'ERROR: Invalid username and/or password\n'
Markdown
UTF-8
9,088
2.609375
3
[]
no_license
##Sodocan Modules for Angular Your Angular application can be constructed however you wish! Inside this directory there is a `sodocan.js` file you may want to include to get access to some helpful functions -- all you need to do is include 'sodocan' as a dependency to your app module, and pass-as-a-global `window.sodocanApp` name of your app (as string). Your app will be bootstrapped to the document after the initial load data has been received from the API server. For the moment, the `sodocanCtrl` controller must be left on the top level tag as well to properly populate the initial data and enable some helpful tools. But wait, why is that useful? The current version of the plain demo has a custom app, sure, but all the directives are still built on the `sodocan` module. The reason is to allow easy injection of other module-level dependencies. You can let `sodocan` sit at the top level and build under it, or take what it offers to integrate into a pre-existing (or new) design. Full documentation on these patterns, along with annotated source in ng-plain, coming soon. There's also a `sodocanRouter` factory available that will remain updated with the current view details. This tool is under heavy construction, but its current usage is available in the ng-plain demo. The router is mostly useful if you want your app to accept deep (specific) linking, as it will parse the project URL (slightly different from the API, mainly that 'all' is replaced with -1) to be a standardized reference request object. The built-in routers are not advised; you won't be able to take advantage of the pretty URL without hard coding or generating a lengthy config to handle the specific routes (or duplicating the given router's URL parsing). You'll likely want to have a top-level "content" directive that loops over `sodocanRouter` or `sodocanAPI.docs` to populate the main text display, depending upon the current view state. `angular-plain` is currently in progress to demonstrate this usage of the API, Router, and the various design patterns the sodocan module enables for you. A full annotated version of this source is incoming this Halloween! All features may not be available in the current version of this code. You can include any extra dependencies for your app inside of the blueprint project folder, a standard set of includes from our demos will also be available in this directory. ## sodocanAPI Quick Reference: #### Warning: some callbacks are still required, pass a noop to be safe! ### docs This is an object holding all the documentation for the loaded project, in the format: ```json { referenceName : { TODO:server_output_fix_this } } ``` ### referenceObject This is a term used in the followed guide to refer to an expected input format: ```json { ref : referenceName, context : { ref : [overall number of entries, overall number of comments], //optional contextName : [number of entries, number of comments], contextName : [number of entries, number of comments] } } ``` If the first `ref` is omitted, the entire project will be queried. If the second `context-ref` is _present_, any other contexts will be ignored. ### getReference(refObj,cb) ###### *Object* referenceObject, [optional: *Function* callback] Shorthand for getting varied entries on a given reference. Below functions provided are for convenience. If reference name is omitted from reference object, this function will pass to `refreshTop` (currently under review). ### getTips(ref,entryNum,commentNum,cb) ###### *String* reference name [optional: *Int* number of entries, *Int* number of comments, *Function* callback] Fetches and updates reference-specific tips in `docs` object. Convenience function around `getReference`. ### getExplanations(ref,entryNum,commentNum,cb) ###### *String* reference name [optional: *Int* number of entries, *Int* number of comments, *Function* callback] Fetches and updates reference-specific explanations in `docs` object. Convenience function around `getReference`. ### getExamples(ref,entryNum,commentNum,cb) ###### *String* reference name [optional: *Int* number of entries, *Int* number of comments, *Function* callback] Fetches and updates reference-specific examples in `docs` object. Convenience function around `getReference`. ### getComments(context,entryID,commentNum,cb) ###### *String* context name, *Int??* reference entryID, [optional: *Int* number of comments, *Function* callback] ### refreshTop(refObj,cb) ###### *Object* referenceObject, [optional: *Function* callback] ##### Warning: Function under review! The usefulness of this as a separate function is being reviewed, be careful using it. You will be able to easily swap it with `getReference` should that happen, just a friendly warning this is in danger of deprecation. Replaces entire documentation object -- this may be an expensive operation in both network costs and client rendering and should be avoided if possible. Intentionally separated from `getReference` for future optimizations and to encourage developers to work from requested references rather than the entire project set. If you're regularly refreshing the entire app's data, you may want to consider generating a static site or loading everything up front. ### editAnything() ##### editReference,editExplanation,editExample,editTip,editComment These are placeholder functions, editing/deleting entries not currently allowed by server. ### newReference(ref,text,cb) ###### *Object* referenceObject, [optional: *Function* callback] Generic version of specific helper functions below; would allow updating entire reference if/when support for that functionality is added. ### newTip(ref,text,cb) ###### *String* reference name, *String* entry text, [optional: *Function* callback] Creates new tip entry for given reference. Convenience function around `newReference`. ### newExplanation(ref,text,cb) ###### *String* reference name, *String* entry text, [optional: *Function* callback] Creates new explanation entry for given reference. Convenience function around `newReference`. ### newExample(ref,text,cb) ###### *String* reference name, *String* entry text, [optional: *Function* callback] Creates new example entry for given reference. Convenience function around `newReference`. ### newComment(entryID,ref,context,text,cb) ###### *Int??* reference entryID, *String* reference name, *String* context name, *String* text content, [optional: *Function* callback] Creates new comment (also labeled additions) for given entry. ### upvote(entryID,ref,context,addID,cb) ###### *Int??* reference entryID, *String* reference name, *String* context name, [optional: *Int??* additionID, *Function* callback] Adds upvote to given entry, or if given additionID (usually referred to as comments in these docs), upvotes the comment under that entry. ## Sodocan Router Quickguide Naming this a router may confuse some people, as it's not intended as a replacement for Angular's built-in routing functionality; rather, consider it as a convenient "parses the current URL state for me" helper utility. Usage is extremely simple, the `sodocanRouter` factory has a `route` object that is the same format as the reference objects you probably encountered with the API helper: ```js { ref : current_functionName_if_any, context : { tips: [#ofEntries,#ofComments], descriptions: [#ofEntries,#ofComments], examples: [#ofEntires,#ofComments], ref: [#topLevelEntries,#topLevelComments] } } ``` The router automatically converts prettyURL-style '-1's to 'all's - the URL specification calls for only numbers to avoid an ambiguous all reference, no such problem for the server API. You can watch for changes with this line: $scope.$watch('sodocanRoute()',respondToUrlChangeFunc); Add that to any relevant controller that needs to adjust with the URL, you can see an example of this in action in `angular-plain/content/contentCode.js`. The controller adds reference cards as the URL changes, not actually in response to the user clicks. *_Note:_ this has not been tested in non-HTML5-friendly browsers.* This means directly linking to the pretty URL (eg: `projectName/myFunc/2/1`) will directly display the appropriate reference. The actual demo code is for in-order display and to avoid duplication (which will throw an error due to the use of ng-repeat anyway!). To enable this behavior, the generated sidebar -- in addition to providing the correct href -- has an additional `ng-click` directive which updates the URL using Angular's built-in $location. This behavior will work correctly because the options are set in the sodocan module, and the index page has a dynamically generated BASE href tag that pulls the project name from the URL. If there's interest in a sodocanRouter wrapper or an option to have it enable this behavior on all A links that can be added, but is not currently a priority.
C
UTF-8
3,847
3.328125
3
[]
no_license
/* * @lc app=leetcode.cn id=1340 lang=c * * [1340] 跳跃游戏 V * * https://leetcode-cn.com/problems/jump-game-v/description/ * * algorithms * Hard (55.36%) * Likes: 67 * Dislikes: 0 * Total Accepted: 4.2K * Total Submissions: 7.3K * Testcase Example: '[6,4,14,6,8,13,9,7,10,6,12]\n2' * * 给你一个整数数组 arr 和一个整数 d 。每一步你可以从下标 i 跳到: * * * i + x ,其中 i + x < arr.length 且 0 < x <= d 。 * i - x ,其中 i - x >= 0 且 0 < x <= d 。 * * * 除此以外,你从下标 i 跳到下标 j 需要满足:arr[i] > arr[j] 且 arr[i] > arr[k] ,其中下标 k 是所有 i 到 j * 之间的数字(更正式的,min(i, j) < k < max(i, j))。 * * 你可以选择数组的任意下标开始跳跃。请你返回你 最多 可以访问多少个下标。 * * 请注意,任何时刻你都不能跳到数组的外面。 * * * * 示例 1: * * * * 输入:arr = [6,4,14,6,8,13,9,7,10,6,12], d = 2 * 输出:4 * 解释:你可以从下标 10 出发,然后如上图依次经过 10 --> 8 --> 6 --> 7 。 * 注意,如果你从下标 6 开始,你只能跳到下标 7 处。你不能跳到下标 5 处因为 13 > 9 。你也不能跳到下标 4 处,因为下标 5 在下标 4 和 * 6 之间且 13 > 9 。 * 类似的,你不能从下标 3 处跳到下标 2 或者下标 1 处。 * * * 示例 2: * * 输入:arr = [3,3,3,3,3], d = 3 * 输出:1 * 解释:你可以从任意下标处开始且你永远无法跳到任何其他坐标。 * * * 示例 3: * * 输入:arr = [7,6,5,4,3,2,1], d = 1 * 输出:7 * 解释:从下标 0 处开始,你可以按照数值从大到小,访问所有的下标。 * * * 示例 4: * * 输入:arr = [7,1,7,1,7,1], d = 2 * 输出:2 * * * 示例 5: * * 输入:arr = [66], d = 1 * 输出:1 * * * * * 提示: * * * 1 <= arr.length <= 1000 * 1 <= arr[i] <= 10^5 * 1 <= d <= arr.length * * */ // @lc code=start // 昨天晚上想30min没想到思路,以为是栈+某个算法。今天中午突然想到每次都是依赖他能跳到的最大值,有依赖关系可以dp或递归 int cmpmax(const void *a, const void *b) { int *tmpa = *((int **)a); int *tmpb = *((int **)b); if (tmpa[1] < tmpb[1]) { return -1; } if (tmpa[1] == tmpb[1]) { if (tmpa[0] < tmpb[0]) { return -1; } else { return 1; } } return 1; } #define MAX(a,b) ((a)>(b)?(a):(b)) int maxJumps(int* arr, int arrSize, int d){ int *dp = (int *)malloc(sizeof(int)*(arrSize)); int **new = (int *)malloc(sizeof(int*)*arrSize); for (int i = 0; i < arrSize; i++) { int *p = malloc(sizeof(int)*2); p[0] = i; p[1] = arr[i]; new[i] = p; dp[i] = 1; } qsort(new,arrSize,sizeof(int*),cmpmax); int max = 0; for (int i = 0; i < arrSize; i++) { int index = new[i][0]; // 往大的方向遍历 for (int j = index+1; j < arrSize && j <= index+d; j++) { if (arr[j] >= new[i][1]) // 错误:用了>,实际上应该是>= { break; } dp[index] = MAX(dp[index], dp[j]+1); } // 往小的方向遍历 for (int j = index-1; j >= 0 && j >= index-d; j--) { if (arr[j] >= new[i][1]) { break; } dp[index] = MAX(dp[index], dp[j]+1); } max = MAX(max, dp[index]); } free(dp); for (int i = 0; i < arrSize; i++) { if (new[i]!=NULL) { free(new[i]); } } free(new); return max; } // @lc code=end
PHP
UTF-8
449
2.65625
3
[ "MIT" ]
permissive
<?php namespace sndsgd\field\rule; use \sndsgd\Field; use \sndsgd\field\Collection; use \sndsgd\field\Error; /** * Ensure a value only contains alphabetical characters */ class AlphaRule extends \sndsgd\field\Rule { /** * {@inheritdoc} */ protected $message = 'contains non alphabetical characters'; /** * {@inheritdoc} */ public function validate() { return ctype_alpha($this->value); } }
C#
UTF-8
1,316
3.5625
4
[]
no_license
using System; using System.Linq; using System.Collections; using System.Collections.Generic; using static System.Console; using static Core.ConsoleHelper; namespace Collections.Lists.ArrayLists { static class Demo { /// <summary> /// Demonstrates usage of <see cref="ArrayList"/>. /// </summary> internal static void Run() { // ArrayList class requires casts. ArrayList al = new ArrayList(); al.Add("hello"); al.Add("world"); string first = (string)al[0]; Write(first); string[] strArr = (string[])al.ToArray(typeof(string)); DisplayBar(); Array.ForEach(strArr, DisplaySpaceVal); // `ArrayList` casts cannot be verified by the compiler, // the following compiles but fails at runtime. //int firstItem = (int)al[0]; // Using `System.Linq.Enumerable` extension methods `Cast` and // `ToList`, you can convert an `ArrayList` to a generic `List`. ArrayList numbers = new ArrayList(); numbers.AddRange(new[] { 1, 5, 9 }); List<int> list = numbers.Cast<int>().ToList(); DisplayBar(); list.ForEach(DisplaySpaceVal); } } }
PHP
UTF-8
4,384
2.75
3
[]
no_license
<?php $dates = getDateArray($G, TRUE); $currentYear = session('year'); $currentMonth = session('month'); $hasYears = TRUE; $yearDropdown = FALSE; $monthDropdown = TRUE; $monthsList = array( 1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April', 5 => 'May', 6 => 'June', 7 => 'July', 8 => 'August', 9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December' ); if (count($dates) > 1) { $yearDropdown = TRUE; } if (!isset($dates[$currentYear])) { $currentYear = date('Y', time()); //$currentMonth = date('n', time()); //session('year', $currentYear); //session('month', $currentMonth); $dates[$currentYear] = array(); } if (!isset($dates[$currentYear][$currentMonth])) { if ($currentMonth != 0) { //$currentMonth = 0; //session('month', $currentMonth); } } $currentName = 'All Months'; if ($currentMonth != 0) { $currentName = date('F', strtotime("2013-$currentMonth-01")); } $rightSeparatorFirst = FALSE; $rightMenu = array(); foreach ($menu as $url => $route) { if ($route['main_order'] == 100) { $rightMenu[$url] = $route; } } ?> <div class="nav-wrapper"> <?php if ($hasYears) { ?> <ul class="nav navbar-nav"> <li> <a id="monthSelector" class="<?php if ($monthDropdown) { ?>dropdown-toggle <?php } ?>" <?php if ($monthDropdown) { ?>data-toggle="dropdown" data-target="#"<?php } ?> href="<?php echo URL; ?>month/switch/<?php echo $currentMonth; ?>?rf=<?php echo $G->url->getUrl(); ?>"> <?php echo $currentName; ?><?php if ($monthDropdown) { ?> <span class="caret"></span><?php } ?> </a> <?php if ($monthDropdown) { ?><ul class="dropdown-menu" role="menu" aria-labelledby="monthSelector"> <?php if ($currentMonth != 0) { echo '<li><a href="'.URL.'month/switch/0?rf='.$G->url->getUrl().'">All Months</a></li>'; } foreach ($monthsList as $val => $name) { $hasStuff = NULL; if (isset($dates[$currentYear][$val])) { $hasStuff = 'hasItems'; } echo '<li class="'.$hasStuff.'"><a href="'.URL.'month/switch/'.$val.'?rf='.$G->url->getUrl().'">'.$name.'</a></li>'; } ?> </ul><?php } ?> </li> <li> <a id="yearSelector" class="<?php if ($yearDropdown) { ?>dropdown-toggle <?php } ?>" <?php if ($yearDropdown) { ?>data-toggle="dropdown" data-target="#"<?php } ?> href="<?php echo URL; ?>year/switch/<?php echo $currentYear; ?>?rf=<?php echo $G->url->getUrl(); ?>"> <?php echo $currentYear; ?><?php if ($yearDropdown) { ?> <span class="caret"></span><?php } ?> </a> <?php if ($yearDropdown) { ?><ul class="dropdown-menu" role="menu" aria-labelledby="yearSelector"> <?php foreach ($dates as $year => $months) { if ($year != $currentYear) { echo '<li><a href="'.URL.'year/switch/'.$year.'?rf='.$G->url->getUrl().'">'.$year.'</a></li>'; } } ?> </ul><?php } ?> </li> <li class="menu-right"><a href="<?php echo URL; ?>logout">Logout</a></li> <li class="menu-right"><a href="javascript:window.print();"><i class="fa fa-print"></i></a></li> <?php foreach ($rightMenu as $url => $route) { if (isset($route['separator']) && $route['separator']) { echo '<li class="divider"></li>'; } $active = NULL; $dropdown = NULL; if ($G->url->isCurrent($url)) { $active = 'active'; } if (isset($route['_children'])) { if (isset($route['separator']) && $route['separator']) { echo '<li class="divider"></li>'; } echo "<li class=\"dropdown menu-right $active\"><a href=\"".URL."$url\" class=\"dropdown-toggle\" data-toggle=\"dropdown\">Settings <b class=\"caret\"></b></a>"; ?><ul class="dropdown-menu on-hover"><?php foreach ($route['_children'] as $subUrl => $subRoute) { if (isset($subRoute['separator'])) { if ($subRoute['separator']) { if (TRUE === $rightSeparatorFirst) { echo '<li class="divider"></li>'; } $rightSeparatorFirst = TRUE; } if (TRUE !== $subRoute['separator']) { echo '<li class="dropdown-header">'.$subRoute['separator'].'</li>'; } } $active = NULL; if ($G->url->isCurrent($url.'/'.$subUrl)) { $active = 'active'; } echo "<li class=\"$active\"><a href=\"".URL."$url/$subUrl\">{$subRoute['name']}</a>"; } ?></ul></li><?php } else { echo "<li class=\"$active\"><a href=\"".URL."$url\">{$route['name']}</a></li>"; } } ?> </ul> <?php } ?> </div>
Ruby
UTF-8
657
3.953125
4
[]
no_license
#Hey! if you are trying to solve this excercise don't read on!! "Find the sum of all the multiples of 3 or 5 below 1000" multiples_3 = [] multiples_5 = [] multiples_addition = 0 counter = 0 while counter < 1000 multiple_5 = 5 * counter if multiple_5 < 1000 multiples_5 << multiple_5 end multiple_3 = 3 * counter if multiple_3 < 1000 if multiples_5.include?(multiple_3) puts "#{multiple_3} is included in multiples_5" else multiples_3 << multiple_3 end end counter += 1 end multiples_3.each do |m| multiples_addition += m end p multiples_addition multiples_5.each do |m| multiples_addition += m end p multiples_addition
PHP
UTF-8
2,074
2.5625
3
[]
no_license
<?php namespace Snake\Package\Qzone\Channel; Use \Snake\Package\Cms\CmsType; Use \Snake\Package\Cms\CmsManage; class QzoneAttribute { private $attrInfo = array(); private $typeInfo = array(); private $infos = array(); public function setQzoneType($selectFields = 'id, type_name, imgurl', $pageTpye = 501, $limit = 6) { $params = array( 'page_type' => $pageTpye, 'orderby' => 'sortno DESC', 'limit' => $limit ); $data = CmsType::getCmsData($params, $selectFields); $this->typeInfo = $data; return TRUE; } public function setQzoneAttribute($selectFields = "id, data_id, page_type, title, contents, linkurl, sortno, type_id", $pageType = 501, $limit = 100) { $params = array( 'page_type' => $pageType, 'orderby' => 'sortno DESC', 'limit' => $limit ); $data = CmsManage::getCmsData($params, $selectFields); $this->attrInfo = $data; return TRUE; } public function sortType() { $data = array(); foreach ($this->typeInfo AS $key => $value) { $typeId = $this->typeInfo[$key]['id']; $data[$typeId] = $this->typeInfo[$key]; unset($data[$typeId]['id']); } $this->infos = $data; return TRUE; } public function assembleQzoneAttribute() { foreach ($this->attrInfo AS $key => $value) { $attr = array(); $typeId = $this->attrInfo[$key]['type_id']; $attr['linkurl'] = $this->attrInfo[$key]['linkurl']; $attr['title'] = $this->attrInfo[$key]['title']; $attr['red'] = $this->attrInfo[$key]['ext_intfields']; $this->infos[$typeId]['words'][] = $attr; } for ($i = 0; $i < 6; $i++) { $data[$i]['type_name'] = rand(1,10); $data[$i]['imgurl'] = "http://imgst-office.meilishuo.net/ap/a/dc/08/be6317074df92036cf7b866c9bc7_108_107.jpg"; for ($j = 0; $j < 15; $j++) { $data[$i]['words'][$j]['linkurl'] = "www.meilishuo.com"; $data[$i]['words'][$j]['title'] = "针织damao毛衣"; $data[$i]['words'][$j]['red'] = rand(0,1); } } $this->infos = array_values($this->infos); $this->infos = $data; return TRUE; } public function getData() { return $this->infos; } }
PHP
UTF-8
1,943
2.78125
3
[]
no_license
<?php namespace App\Services; use App\DTO\IndexDTO; use App\DTO\ListItemsDTO; use App\Entity\Product; use App\Repository\ProductRepository; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\ORM\OptimisticLockException; use Doctrine\ORM\ORMException; /** * Class ProductService * @package App\Services */ final class ProductService { /** * Product repository instance * @var ProductRepository */ protected $repository; /** * File service instance * @var FileService */ protected $file_service; /** * ProductService constructor. * @param ProductRepository $repository * @param FileService $file_service */ public function __construct(ProductRepository $repository, FileService $file_service) { $this->repository = $repository; $this->file_service = $file_service; } /** * Create product * * @param array $data * @return Product * @throws ORMException * @throws OptimisticLockException */ public function create(array $data): Product { $product = new Product( $data['name'], $data['price'], $data['description'] ?? null ); $product->setProductCategory($data['product_category']); $product = $this->repository->store($product); if (isset($data['files'])) { $file_models = $this->file_service->createMultiple($data['files']); $product->setFiles( new ArrayCollection( $file_models ) ); } return $product; } /** * Get product categories * * @param array $parameters * @return ListItemsDTO */ public function index(array $parameters): ListItemsDTO { return $this->repository->index( (new IndexDTO())->fill($parameters) ); } }
PHP
UTF-8
660
3.25
3
[]
no_license
<?php class DatabaseUtil { private static $conn = null; public static function openConnection($dbName) { // Is a connection already open? if (self::$conn != null) { // Close it. self::closeConnection(); } $username = "fake username"; $password = "fake password"; try { self::$conn = new PDO("mysql:host=localhost;dbname=$dbName", $username, $password); } catch (PDOException $e) { die($e->getMessage()); } return self::$conn; } public static function closeConnection() { self::$conn = null; } } ?>
Python
UTF-8
590
2.953125
3
[]
no_license
products = ["mobile","mouse","moneypot","monitor","mousepad"] searchWord = "mouse" products = ["havana"] searchWord = "tatiana" temp_arr = [] final_arr =[] if len(products)==1 and products[0][0]!=searchWord[0]: for _ in range(len(searchWord)): final_arr.append([]) else: for id, _ in enumerate(range(len(searchWord)), start=1): st = searchWord[:id] for words in products: if words[:id] == st: temp_arr.append(words) temp_arr.sort() final_arr.append(temp_arr[:3]) temp_arr.clear() print(final_arr)
C++
UTF-8
994
3.375
3
[]
no_license
#include <iostream> using namespace std; struct Node{ int value; Node* left; Node* right; Node* parent; Node(){ left=NULL; right=NULL; parent=NULL; } }; void insert( Node* root, int key){ if(key<root->value) {if(!root->left){ Node*p=new Node; p->parent=root; root->left=p; p->value=key;} else insert(root->left, key);} else {if(!root->right){ Node*p=new Node; p->parent=root; root->right=p; p->value=key;} else insert(root->right, key);} } Node* search(Node* root,int key){ if(!root) {Node*p=new Node; p->value=-1; return p;} if(key==root->value) return root; else if(key<root->value) return search(root->left, key); else return search(root->right, key); } int main(){ int n; cin>>n; int a[n]; for(int i=0; i<n; i++) cin>>a[i]; Node *root = new Node; root->value=a[0]; for(int i=1; i<n; i++) insert(root, a[i]); int p; cin>>p; Node*q= new Node; q=search(root,p); if(q->value==-1 || q==root) cout<<-1; else while(q!=root){ cout<<q->parent->value<<" "; q=q->parent; } cout<<endl; return 0; }
Python
UTF-8
572
2.984375
3
[]
no_license
matriz = [] for x in range(3): matriz.append([int(input()), int(input()), int(input())]) soma = 0 delta = 0 somaNaoDiag = 0 qtdPost = 0 menor = matriz[0][0] for i in range(3): for j in range(3): if matriz[i][j] > 0: qtdPost +=1 soma += matriz[i][j] if matriz[i][j] < menor: menor = matriz[i][j] if menor % 2 == 0: delta = 1 else: delta = 0 if i != j: somaNaoDiag += matriz[i][j] print("{:.2f} {} {} {}".format(soma/qtdPost, menor, delta, somaNaoDiag))
C
UTF-8
4,240
3.015625
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #define SIZE 60 int a[SIZE][SIZE]; int row[SIZE], used_row[SIZE], row2[SIZE]; int column[SIZE], column2[SIZE]; int main( ) { int t, n, m, i, j, k, flag, row_sum, column_sum, tipu, row_max, r, l, counter = 1; scanf("%d",&t); while ( t-- ) { flag = row_sum = column_sum = 0; scanf("%d %d",&n, &m); for ( i = 0; i < n; i++ ) { scanf("%d",&row[i]); if ( row[i] > m ) flag = -1; row_sum += row[i]; row2[i] = row[i]; } for ( i = 0; i < m; i++ ) { scanf("%d",&column[i]); if ( column[i] > n ) flag = -1; column_sum += column[i]; } if ( column_sum != row_sum ) flag = -1; if ( flag == -1 ) { printf("TestCase #:%d\n",counter++); printf("-1\n"); } else { for ( i = 0; i < n; i++ ) { for ( j = 1; j <= row[i]; j++ ) { a[i][m-j] = 1; } } /* printf("\nprinting matrix after initializing\n"); for ( i = 0; i < n; i++ ) { for ( j = 0; j < m; j++ ) { printf("%d ",a[i][j]); } printf("\n"); } */ for ( i = 0; i < m; i++ ) { for ( j = 1; j <= column[i]; j++ ) { row_max = n-1; for ( k = n-1; k >= 0; k-- ) { if ( row[k] > row[row_max] && !used_row[k] ) // to prevent shifting the same row twice row_max = k; } if ( i != m-row[row_max] ) { a[row_max][i] = 1; a[row_max][m-row[row_max]] = 0; //shifting the maximum lower(in case of tie) 1 towards left } used_row[row_max] = 1; row[row_max]--; } /* printf("\nprinting matrix after column %d\n",i); for ( k = 0; k < n; k++ ) { for ( l = 0; l < m; l++ ) { printf("%d ",a[k][l]); } printf("\n"); } */ for ( k = 0; k < n; k++ ) used_row[k] = 0; } /* printf("\nprinting matrix\n"); for ( i = 0; i < n; i++ ) { for ( j = 0; j < m; j++ ) { printf("%d ",a[i][j]); } printf("\n"); } printf("\n"); */ tipu = 0; /* for ( i = 0; i < m; i++ ) { for ( j = 0; j < n; j++ ) { tipu = 0; if ( a[j][i] == 1 ) { for ( k = i+1; k < m; k++ ) { if ( a[j][k] == 0 ) { for ( l = j+1; l < n; l++ ) { if ( a[l][k] == 1 && a[l][i] == 0 ) { a[l][k] = 0, a[l][i] = 1; a[j][i] = 0, a[j][k] = 1; tipu = 1; break; } } if ( tipu ) { tipu = 0; break; } } } // breaking out of it due to if(tipu) } } } printf("TestCase #:%d\n",counter++); for ( i = 0; i < n; i++ ) { for ( j = 0; j < m; j++ ) { printf("%d",a[i][j]); } printf("\n"); } */ for ( i = 0; i < n; i++ ) { for ( j = 0; j < m; j++ ) { tipu = 0; if ( a[i][j] == 1 ) { for ( k = j+1; k < m; k++ ) { if ( a[i][k] == 0 ) { for ( l = i+1; l < n; l++ ) { if ( a[l][k] == 1 && a[l][j] == 0 ) { a[l][k] = 0, a[l][j] = 1; a[i][j] = 0, a[i][k] = 1; tipu = 1; break; } } if ( tipu ) { tipu = 0; break; } } } // breaking out of it due to if(tipu) } } } // printf("printing the matrix after sorting:\n"); /*for ( i = 0; i < n; i++ ) { row[i] = 0; } for ( i = 0; i < n; i++ ) { for ( j = 0; j < m; j++ ) { row[i] += a[i][j]; } } for ( i = 0; i < n; i++ ) { if ( row[i] != row2[i] ) { printf("damn\n"); } } for ( i = 0; i < m; i++ ) { for ( j = 0; j < n; j++ ) { column2[i] += a[j][i]; } } for ( i = 0; i < m; i++ ) if ( column[i] != column2[i] ) printf("oh! no\n"); */ printf("TestCase #:%d\n",counter++); for ( i = 0; i < n; i++ ) { for ( j = 0; j < m; j++ ) { printf("%d",a[i][j]); } printf("\n"); } // printf("\n"); } for ( i = 0; i < SIZE; i++ ) for ( j = 0; j < SIZE; j++ ) a[i][j] = 0; for ( i = 0; i < SIZE; i++ ) row[i] = column[i] = used_row[i] = row2[i] = column2[i] = 0; } return 0; }
Markdown
UTF-8
4,768
2.515625
3
[]
no_license
--- title: "Teningen - Splügenpass" slug: teningen-spluegenpass date: 2002-10-01 taxonomies: tags: ["Alpen", "Bad Bellingen", "Deutschland", "Kaiserstuhl", "Kreuzlingen", "Liechtenstein", "Passstraße", "Schaan", "Schweiz", "Teningen", "Vaduz", "Reisen"] categories: --- <em>Teningen – 82km – Bad Bellingen – 108km – Kaiserstuhl / CH – 84km – Kreuzlingen – 90km – Schaan – 90km - Andeer</em> Gestärkt durch das vermeintlich vorerst letzte ausgiebige Frühstück stiegen wir am Morgen des 4. August endlich in die Pedale. Schon auf dem Weg nach Freiburg verfuhren wir uns das erste mal (ich hatte die Karte..). Bis zum frühen Nachmittag hatten wir schönes Radlwetter. Durch das flache Rheintal ging es zum Rhein. Dort sind wir weitesgehend einem ufernahen Wirtschaftsweg flussaufwärts gefolgt. Der aufkommende Regen verschlechterte die Fahrbahnbeschaffenheit des sandigen Weges und ließ uns nicht gerade schnell vorankommen. Nach, gefühlsmäßig, viel zu wenigen Kilometern schlugen wir unser erstes Lager direkt am Rhein auf, so dass wir uns sowie unsere Räder waschen konnten. Die meisten Tage in der Schweiz hatten wir kühles, regnerisches Wetter. Von den Unwettern, die zu der Zeit in Bayern und Österreich wüteten, bekamen wir aber nichts ab. Die Strecke am Rhein entlang verläuft meistens recht flach. Die schönen Alpenpanoramen konnten wir mangels Sicht leider nur erahnen. <!--more--> Der nächste Tag brachte recht viel Sonnenschein. Nach einem kleinen Abstecher nach Frankreich erreichten wir Basel und somit die ausgeschilderten Veloland-Radwegen, denen wir bis nach Italien folgten. Die Rheinroute Nr.2 folgt dem Rhein, immer auf der Schweizer Seite, bis nach Andermatt. Bis auf ein paar Abkürzungen, beispielsweise von Kaiserstuhl nach Schaffhausen (-25km!), sind wir diesen Weg bis Chur gefahren, wo wir auf den Radweg Nr.6 abbogen, der uns bis nach Splügen brachte. Die erste Nacht in der Schweiz verbrachten wir auf einer Wiese neben einem Sonnenblumenfeld. Der Bauer verstand uns so wenig wie wir ihn, aber seine Tochter konnte übersetzen: Deutsch – Schweizerdeutsch. Zu dem Geräusch von Regen aufzuwachen ist nicht sehr motivierend. Da hilft erstmal nur ein gutes Frühstück und eine Tasse Kaffee. Beides fanden wir in einem Café im ersten deutschen Dorf das wir fanden. Eigentlich hatte nur die Konditorei geöffnet und das Café Betriebsferien. Doch wir sahen wohl sehr mitleidserregend aus in unseren Regensachen, so dass wir als einzige Gäste im Café bedient wurden. Richtung Bodensee wurden die Radfahrer immer zahlreicher, selbst bei dem miesen Wetter das wir hatten. Aufgrund des Regens und Alex´ beginnenden körperlichen Beschwerden verbrachten wir zwei Nächte in den tollen Schweizer Jugis. Das dort gebotene Frühstück sollte ein Vorbild für alle Jugendherbergen der Welt sein. Nur ganz billig ist das ganze leider nicht. Die letzte Nacht vor der Alpenhauptkammüberquerung lagerten wir auf dem Gelände einer Steinbruchfirma bei Andeer. Auf über 900 Meter über NN waren wir da schon gekommen. Ich war zwar letztes Jahr schon einmal auf den Brocken gefahren, allerdings ganz ohne Gepäck. So war der Verlauf des nächsten Tages eine große Unbekannte. Murphys Gesetz gilt auch auf dem Berg: Der Weg ist immer länger als man von unten denkt. Die nächste Kehre enthüllt meistens weitere. Und nach der Schweizer Zollstation geht es mindestens noch zwei weitere Kilometer bergauf. (Na gut, Murphy ist das wohl nicht ganz) Je näher wir der Sonne kamen, desto wärmer wurde es leider nicht. 16km und 500hm bis Splügen. 9km und 700hm bis zur Passhöhe des Splügenpasses. Etwas vergleichbar anstrengendes hatte ich bis dato nur beim Bund erlebt. Mit 30kg auf dem Rücken im Eiltempo durch die Märkische Heide. Der Unterschied dazu war, dass wir uns nicht einmal fragen konnten was das ganze für einen Sinn hätte. Es zählt nur, dass man immer weiterfährt, egal wie langsam. Hauptsache ankommen. Irgendwie. Erstaunlich ist es, wie viele Radfahrer man auf der Passhöhe trifft. Mehr als uns während des Aufstiegs entgegenkamen. Oben haben wir erstmal trockene Klamotten und alles, was wir an Wind- und Kälteschutz mithatten, angezogen, bevor es auf die lange Abfahrt ging. Bis Chiavenna waren es 30km auf denen es nur bergab ging. Eine dreiviertel Stunde mussten wir fast gar nicht pedalieren. Viele Serpentinen ließen nur eine Höchstgeschwindigkeit von 60,4 km/h zu, und das während einer Dorfdurchfahrt. Es war Donnerstag, und somit die Straße nicht allzu befahren. So konnten wir die teilweise grandiosen Aussichten genießen und erhielten eine angemessene Entschädigung für die vorherigen Qualen. <a href="../spluegenpass-adria">Weiter &gt;&gt; Splügenpass - Adria</a>
Swift
UTF-8
3,224
2.65625
3
[]
no_license
// // FriendsViewController.swift // MyFriends // // Created by Anna on 12/27/19. // Copyright © 2019 Anna. All rights reserved. // import UIKit class FriendsViewController: UIViewController { @IBOutlet weak var tableView: UITableView! var friends = [User]() override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addNewFriend)) tableView.registerCell(for: UserCell.self) } override func viewWillAppear(_ animated: Bool) { getFriends() } func getFriends() { DispatchQueue.global(qos: .background).async { CoreDataManager.fetchFriends { [weak self] (friends, error) in DispatchQueue.main.async { if let error = error { self?.showOkAlert(title: "Error", message: error.localizedDescription) } if let friends = friends { self?.friends = friends self?.tableView.reloadData() } } } } } @objc func addNewFriend() { if let randomVC = UIStoryboard.get(flow: .main).get(controller: .randomVC) as? RandomUsersViewController { self.navigationController?.pushViewController(randomVC, animated: true) } } func unfriendUser(at indexPath: IndexPath) { CoreDataManager.unfriendUser(user: friends[indexPath.row]) { [weak self] (success) in if success { self?.friends.remove(at: indexPath.row) self?.tableView.deleteRows(at: [indexPath], with: .bottom) } else { self?.showOkAlert(title: "Error", message: "Try again later") } } } } extension FriendsViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { friends.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: UserCell.self)) as! UserCell let user = friends[indexPath.row] cell.user = user return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 70 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) let user = friends[indexPath.row] if let userDetailsVC = UIStoryboard.get(flow: .main).get(controller: .userDetailsVC) as? UserDetailsViewController { userDetailsVC.user = user self.navigationController?.pushViewController(userDetailsVC, animated: true) } } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { unfriendUser(at: indexPath) } } }
Java
UTF-8
2,066
2.109375
2
[]
no_license
package com.example.michelle.littleprincesses.ui.seller; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.content.Intent; import android.view.View; import android.widget.Button; import com.example.michelle.littleprincesses.R; public class UpdateMenu extends Activity { Button submitUpdateMenu; Button cancelUpdateMenu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.ui_seller_activity_update_menu); submitUpdateMenu = (Button) findViewById(R.id.submit_update_menu); cancelUpdateMenu = (Button) findViewById(R.id.cancel_update_menu); submitUpdateMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { /*Intent intent = new Intent(UpdateMenu.this, UpdateMenu.class); startActivity(intent);*/ } }); cancelUpdateMenu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(UpdateMenu.this, MainActivitySeller.class); startActivity(intent); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_update_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
C++
UTF-8
1,079
2.828125
3
[]
no_license
#ifndef _MENU_HPP_ #define _MENU_HPP_ #include "rectangle.hpp" #include "list.hpp" class Menu : public Rectangle { private: //members List list; float spacing; //functions void calculateListPosition(); void calculateListParameters(); public: //ctor Menu(); //getters float getSpacing() const { return spacing; } unsigned int getSelected() const { return list.getSelected(); } //setters void setList(const List& theList); void setSpacing(const float theValue) { spacing = theValue; calculateListPosition(); } void setSize(const sf::Vector2f& theSize) { Rectangle::setSize(theSize); calculateListPosition(); } void setActive(const bool isActive) { Rectangle::setActive(isActive); list.setActive(isActive); } void setUpdateRate(const sf::Time theTime) { Rectangle::setUpdateRate(theTime); list.setUpdateRate(theTime); } void setSelected(const unsigned int theValue) { list.setSelected(theValue); } }; #endif // _MENU_HPP_
Python
UTF-8
23,699
2.71875
3
[]
no_license
''' >>> This file creates modules that can do forward, backward pass as well as bound propagation ''' import torch import torch.nn as nn import torch.nn.functional as F from torch.nn.parameter import Parameter from abc import ABCMeta, abstractmethod import math import numpy as np from .linearize import linearize_relu, linearize_sigd, linearize_tanh, linearize_arctan from .utility import reduced_m_bm, reduced_bm_bm, reduced_bv_bm, reduced_bm_bv, norm_based_bounds, merge_W_m_list class Layer(nn.Module, metaclass = ABCMeta): def __init__(self,): super(Layer, self).__init__() @abstractmethod def forward(self, x): ''' >>> do forward pass with a given input ''' raise NotImplementedError @abstractmethod def bound_quad(self, x, l, u, W_list, m1_list, m2_list, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None, is_certify = 0): ''' >>> do bound propagation based on quadratic algorithm >>> x: the input data point >>> l: the lower bound of the input, not flattened >>> u: the upper bound of the input, not flattened >>> W_list: the transformation matrix introduced by the previous layers, of shape [batch_size, current_dim, input_dim] >>> m1_list, m2_list: the bias introduced by the previous layers, of shape [batch_size, input_dim] >>> first_layer: boolean, whether or not this is the first layer of the model >>> ori_perturb_norm, ori_perturb_eps: the original perturbation, default is None >>> in_shape: the original shape of the input, used for convolutional kernel flatten >>> pixel_range: [min, max], the allowable pixel range, default is None >>> is_certify: whether or not in a certify mode >>> return the updated W_list, m1_list, m2_list ''' raise NotImplementedError @abstractmethod def bound_simp(self, x, l, u, W, m1, m2, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None, is_certify = 0): ''' >>> do bound propagation based on simple algorithm >>> x: the input data point >>> l: the lower bound of the input >>> u: the upper bound of the input >>> W, m1, m2: the linearized bounds of the input, Wx + m1 < input < Wx + m2 W have the shape [batch_size, out_dim, in_dim] m1, m2 have the shape [batch_size, out_dim] >>> first_layer: boolean, whether or not this is the first layer of the model >>> ori_perturb_norm, ori_perturb_eps: the original perturbation, default is None >>> in_shape: the original shape of the input, used for convolutional kernel flatten >>> pixel_range: [min, max], the allowable pixel range, default is None >>> is_certify: whether or not in a certify mode >>> return the lower and upper bound of the current layer and updated W1, W2, m1, m2 ''' raise NotImplementedError @abstractmethod def bound_ibp(self, x, l, u, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None): ''' >>> do IBP bound propagation >>> x: the input data point >>> l: the lower bound of the input >>> u: the upper bound of the input >>> first_layer: boolean, whether or not this is the first layer of the model >>> ori_perturb_norm, ori_perturb_eps: the original perturbation, default is None >>> in_shape: the original shape of the input, used for convolutional kernel flatten >>> pixel_range: [min, max], the allowable pixel range, default is None >>> return the lower and upper bound of the current layer ''' raise NotImplementedError @abstractmethod def shape_transfer(self, in_shape): ''' >>> given the input shape, return the output shape ''' raise NotImplementedError @abstractmethod def base(self,): ''' >>> return the base primitive pytorch model ''' raise NotImplementedError class FCLayer(Layer): def __init__(self, in_features, out_features): super(FCLayer, self).__init__() self.in_features = in_features self.out_features = out_features self.layer = nn.Linear(in_features, out_features) def forward(self, x): return F.linear(x, self.layer.weight, self.layer.bias) def bound_quad(self, x, l, u, W_list, m1_list, m2_list, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None, is_certify = 0): batch_size = in_shape[0] # if the bias term in the last iteration is the same, we can merge it with the current one max_var = torch.max(torch.abs(m1_list[-1] - m2_list[-1])) # Update the transition weight matrix update_list = W_list if max_var > 1e-4 or first_layer == True else W_list[:-1] for idx, W in enumerate(update_list): W_list[idx] = reduced_m_bm(self.layer.weight, W) # Add the contribution of this layer if max_var > 1e-4 or first_layer == True: W_list.append(torch.ones([batch_size, self.out_features], device = self.layer.weight.device)) m1_list.append(self.layer.bias.unsqueeze(0).repeat(batch_size, 1)) m2_list.append(self.layer.bias.unsqueeze(0).repeat(batch_size, 1)) else: W_list[-1] = torch.ones([batch_size, self.out_features], device = self.layer.weight.device) m1_list[-1] = torch.matmul(m1_list[-1], self.layer.weight.transpose(0, 1)) + self.layer.bias m2_list[-1] = torch.matmul(m2_list[-1], self.layer.weight.transpose(0, 1)) + self.layer.bias return W_list, m1_list, m2_list def bound_simp(self, x, l, u, W, m1, m2, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None, is_certify = 0): W_pos = torch.clamp(self.layer.weight, min = 0.) W_neg = torch.clamp(self.layer.weight, max = 0.) new_W = reduced_m_bm(self.layer.weight, W) new_m1 = torch.matmul(m1, W_pos.transpose(0, 1)) + torch.matmul(m2, W_neg.transpose(0, 1)) + self.layer.bias new_m2 = torch.matmul(m2, W_pos.transpose(0, 1)) + torch.matmul(m1, W_neg.transpose(0, 1)) + self.layer.bias return new_W, new_m1, new_m2 def bound_ibp(self, x, l, u, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None): if first_layer == True: transit_matrix = self.layer.weight.unsqueeze(0).repeat(x.size(0), 1, 1) l, u = norm_based_bounds(x.view(x.size(0), -1), W = transit_matrix, perturb_norm = ori_perturb_norm, perturb_eps = ori_perturb_eps, pixel_range = pixel_range) new_l = l + self.layer.bias new_u = u + self.layer.bias else: W_pos = torch.clamp(self.layer.weight, min = 0.) W_neg = torch.clamp(self.layer.weight, max = 0.) new_l = torch.matmul(l, W_pos.transpose(0, 1)) + torch.matmul(u, W_neg.transpose(0, 1)) + self.layer.bias new_u = torch.matmul(u, W_pos.transpose(0, 1)) + torch.matmul(l, W_neg.transpose(0, 1)) + self.layer.bias return new_l, new_u def shape_transfer(self, in_shape): assert np.prod(in_shape[1:]) == self.in_features, 'dimension mismatch, %d required but %d given' % (self.in_features, np.prod(in_shape[1:])) return [in_shape[0], self.out_features] def base(self,): layer = nn.Linear(self.in_features, self.out_features) layer.weight.data = self.layer.weight.data layer.bias.data = self.layer.bias.data return layer class Conv2dLayer(Layer): def __init__(self, in_channel, out_channel, kernel_size, stride = 1, padding = 0): super(Conv2dLayer, self).__init__() self.in_channel = in_channel self.out_channel = out_channel self.kernel_size = kernel_size self.stride = stride self.padding = padding self.layer = nn.Conv2d(in_channel, out_channel, kernel_size, stride, padding) self.flattened_weight = None # The matrix form of convolutional kernel self.flattened_bias = None # The vector form of convolutional bias self.flattened_shape = None # The input shape of the convolutional layer def flatten(self, in_shape): ''' >>> to obtain the flatten version of convolutional kernel and bias >>> in_shape: the shape of the input >>> Input/Output of ConvLayer: [batch_size, channel_idx, height, width] >>> Weight of ConvLayer: [channel_out, channel_in, kernel_height, kernel_width] >>> Size of output matrix: [out_dim, in_dim] ''' assert len(in_shape[1:]) == 3, 'the input shape should be [channel, height, width]' assert in_shape[1] == self.in_channel, 'the number of channels of the input should be aligned with the kernel, but they are %d and %d respectively' % (in_shape[1], self.in_channel) self.flattened_shape = in_shape[1:] out_height = (in_shape[2] + 2 * self.padding - self.kernel_size + 0) // self.stride + 1 out_width = (in_shape[3] + 2 * self.padding - self.kernel_size + 0) // self.stride + 1 in_dim = int(np.prod(in_shape[1:])) out_dim = int(np.prod([out_width, out_height, self.out_channel])) inp_I = torch.eye(in_dim).view(-1, *in_shape[1:]).to(self.layer.weight.device) outp_I = F.conv2d(inp_I, self.layer.weight, None, self.layer.stride, self.layer.padding, self.layer.dilation, self.layer.groups) outp_I = outp_I.view(in_dim, out_dim) self.flattened_weight = outp_I.t() self.flattened_bias = self.layer.bias.reshape(-1, 1).repeat(1, out_width * out_height).reshape(-1) return self.flattened_weight, self.flattened_bias def forward(self, x): return F.conv2d(x, self.layer.weight, self.layer.bias, self.layer.stride, self.layer.padding, self.layer.dilation, self.layer.groups) def bound_quad(self, x, l, u, W_list, m1_list, m2_list, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None, is_certify = 0): batch_size = in_shape[0] # Obtain the flattened weights and bias weight_matrix, bias_vector = self.flatten(in_shape = in_shape) out_dim = weight_matrix.shape[0] # For potential merge max_var = torch.max(torch.abs(m1_list[-1] - m2_list[-1])) # Update the transition weight matrix update_list = W_list if max_var > 1e-4 or first_layer == True else W_list[:-1] for idx, W in enumerate(update_list): W_list[idx] = reduced_m_bm(weight_matrix, W) # Add the contribution of this layer if max_var > 1e-4 or first_layer == True: W_list.append(torch.ones([batch_size, out_dim], device = weight_matrix.device)) m1_list.append(bias_vector.unsqueeze(0).repeat(batch_size, 1)) m2_list.append(bias_vector.unsqueeze(0).repeat(batch_size, 1)) else: W_list[-1] = torch.ones([batch_size, out_dim], device = weight_matrix.device) m1_list[-1] = torch.matmul(m1_list[-1], weight_matrix.transpose(0, 1)) + bias_vector.unsqueeze(0).repeat(batch_size, 1) m2_list[-1] = torch.matmul(m2_list[-1], weight_matrix.transpose(0, 1)) + bias_vector.unsqueeze(0).repeat(batch_size, 1) return W_list, m1_list, m2_list def bound_simp(self, x, l, u, W, m1, m2, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None, is_certify = 0): weight_matrix, bias_vector = self.flatten(in_shape = in_shape) W_pos = torch.clamp(weight_matrix, min = 0.) W_neg = torch.clamp(weight_matrix, max = 0.) new_W = reduced_m_bm(weight_matrix, W) new_m1 = torch.matmul(m1, W_pos.transpose(0, 1)) + torch.matmul(m2, W_neg.transpose(0, 1)) + bias_vector new_m2 = torch.matmul(m2, W_pos.transpose(0, 1)) + torch.matmul(m1, W_neg.transpose(0, 1)) + bias_vector return new_W, new_m1, new_m2 def bound_ibp(self, x, l, u, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None): weight_matrix, bias_vector = self.flatten(in_shape = in_shape) if first_layer == True: transit_matrix = weight_matrix.unsqueeze(0).repeat(x.size(0), 1, 1) l, u = norm_based_bounds(x = x.view(x.size(0), -1), W = transit_matrix, perturb_norm = ori_perturb_norm, perturb_eps = ori_perturb_eps, pixel_range = pixel_range) new_l = l + bias_vector new_u = u + bias_vector else: W_pos = torch.clamp(weight_matrix, min = 0.) W_neg = torch.clamp(weight_matrix, max = 0.) new_l = torch.matmul(l, W_pos.transpose(0, 1)) + torch.matmul(u, W_neg.transpose(0, 1)) + bias_vector new_u = torch.matmul(u, W_pos.transpose(0, 1)) + torch.matmul(l, W_neg.transpose(0, 1)) + bias_vector return new_l, new_u def shape_transfer(self, in_shape): assert len(in_shape) == 4, 'the in_shape of convolutional layer should be [batch_size, channel, height, width]' assert in_shape[1] == self.in_channel, 'in_channel dimension mismatch, %d required but %d given' % (self.in_channel, in_shape[1]) out_height = (in_shape[2] + 2 * self.padding - self.kernel_size + 0) // self.stride + 1 out_width = (in_shape[3] + 2 * self.padding - self.kernel_size + 0) // self.stride + 1 return [in_shape[0], self.out_channel, out_height, out_width] def base(self,): layer = nn.Conv2d(self.in_channel, self.out_channel, self.kernel_size, self.stride, self.padding) layer.weight.data = self.layer.weight.data layer.bias.data = self.layer.bias.data return layer class ReLULayer(Layer): def __init__(self,): super(ReLULayer, self).__init__() def forward(self, x): return F.relu(x, inplace = True) def bound_quad(self, x, l, u, W_list, m1_list, m2_list, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None, is_certify = 0): assert first_layer == False, 'activation layer cannot be the first layer' batch_size = in_shape[0] # Obtain D, m1, m2 D, m1, m2 = linearize_relu(l, u, is_certify) D = D.reshape(batch_size, -1) # of shape [batch_size, dim] m1 = m1.reshape(batch_size, -1) # of shape [batch_size, dim] m2 = m2.reshape(batch_size, -1) # of shape [batch_size, dim] out_dim = D.shape[1] # For potential merge max_var = torch.max(torch.abs(m1_list[-1] - m2_list[-1])) # Update update_list = W_list if max_var > 1e-4 else W_list[:-1] for idx, W in enumerate(update_list): W_list[idx] = reduced_bm_bm(D, W) # Add the contribution of this layer if max_var > 1e-4: W_list.append(torch.ones([batch_size, out_dim], device = D.device)) m1_list.append(m1) m2_list.append(m2) else: m1_list[-1] = m1_list[-1] * D + m1 m2_list[-1] = m2_list[-1] * D + m2 return W_list, m1_list, m2_list def bound_simp(self, x, l, u, W, m1, m2, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None, is_certify = 0): assert first_layer == False, 'activation layer cannot be the first layer' D_this_layer, m1_this_layer, m2_this_layer = linearize_relu(l, u, is_certify) # of shape [batch_size, out_dim] new_W = reduced_bm_bm(D_this_layer, W) new_m1 = m1 * D_this_layer + m1_this_layer new_m2 = m2 * D_this_layer + m2_this_layer return new_W, new_m1, new_m2 def bound_ibp(self, x, l, u, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None): assert first_layer == False, 'activation layer cannot be the first layer' l = self.forward(l) u = self.forward(u) return l, u def shape_transfer(self, in_shape): return in_shape def base(self,): return torch.nn.ReLU() class SigdLayer(Layer): def __init__(self,): super(SigdLayer, self).__init__() def forward(self, x): return F.sigmoid(x) def bound_quad(self, x, l, u, W_list, m1_list, m2_list, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None, is_certify = 0): assert first_layer == False, 'activation layer cannot be the first layer' batch_size = in_shape[0] # Obtain D, m1, m2 D, m1, m2 = linearize_sigd(l, u, is_certify) D = D.reshape(batch_size, -1) m1 = m1.reshape(batch_size, -1) m2 = m2.reshape(batch_size, -1) out_dim = D.shape[1] # For potential merge max_var = torch.max(torch.abs(m1_list[-1] - m2_list[-1])) # Update update_list = W_list if max_var > 1e-4 else W_list[:-1] for idx, W in enumerate(update_list): W_list[idx] = reduced_bm_bm(D, W) # Add the contribution of this layer if max_var > 1e-4: W_list.append(torch.ones([batch_size, out_dim], device = D.device)) m1_list.append(m1) m2_list.append(m2) else: m1_list[-1] = m1_list[-1] * D + m1 m2_list[-1] = m2_list[-1] * D + m2 return W_list, m1_list, m2_list def bound_simp(self, x, l, u, W, m1, m2, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None, is_certify = 0): assert first_layer == False, 'activation layer cannot be the first layer' D_this_layer, m1_this_layer, m2_this_layer = linearize_sigd(l, u, is_certify) # of shape [batch_size, out_dim] new_W = reduced_bm_bm(D_this_layer, W) new_m1 = m1 * D_this_layer + m1_this_layer new_m2 = m2 * D_this_layer + m2_this_layer return new_W, new_m1, new_m2 def bound_ibp(self, x, l, u, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None): assert first_layer == False, 'activation layer cannot be the first layer' l = self.forward(l) u = self.forward(u) return l, u def shape_transfer(self, in_shape): return in_shape def base(self,): return torch.nn.Sigmoid() class TanhLayer(Layer): def __init__(self,): super(TanhLayer, self).__init__() def forward(self, x): return torch.tanh(x) def bound_quad(self, x, l, u, W_list, m1_list, m2_list, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None, is_certify = 0): assert first_layer == False, 'activation layer cannot be the first layer' batch_size = in_shape[0] # Obtain D, m1, m2 D, m1, m2 = linearize_tanh(l, u, is_certify) D = D.reshape(batch_size, -1) m1 = m1.reshape(batch_size, -1) m2 = m2.reshape(batch_size, -1) out_dim = D.shape[1] # For potential merge max_var = torch.max(torch.abs(m1_list[-1] - m2_list[-1])) # Update update_list = W_list if max_var > 1e-4 else W_list[:-1] for idx, W in enumerate(update_list): W_list[idx] = reduced_bm_bm(D, W) # Add the contribution of this layer if max_var > 1e-4: W_list.append(torch.ones([batch_size, out_dim], device = D.device)) m1_list.append(m1) m2_list.append(m2) else: m1_list[-1] = m1_list[-1] * D + m1 m2_list[-1] = m2_list[-1] * D + m2 return W_list, m1_list, m2_list def bound_simp(self, x, l, u, W, m1, m2, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None, is_certify = 0): assert first_layer == False, 'activation layer cannot be the first layer' D_this_layer, m1_this_layer, m2_this_layer = linearize_tanh(l, u, is_certify) # of shape [batch_size, out_dim] new_W = reduced_bm_bm(D_this_layer, W) new_m1 = m1 * D_this_layer + m1_this_layer new_m2 = m2 * D_this_layer + m2_this_layer return new_W, new_m1, new_m2 def bound_ibp(self, x, l, u, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None): assert first_layer == False, 'activation layer cannot be the first layer' l = self.forward(l) u = self.forward(u) return l, u def shape_transfer(self, in_shape): return in_shape def base(self,): return torch.nn.Tanh() class ArctanLayer(Layer): def __init__(self,): super(ArctanLayer, self).__init__() def forward(self, x): return torch.atan(x) def bound_quad(self, x, l, u, W_list, m1_list, m2_list, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None, is_certify = 0): assert first_layer == False, 'activation layer cannot be the first layer' batch_size = in_shape[0] # Obtain D, m1, m2 D, m1, m2 = linearize_arctan(l, u, is_certify) D = D.reshape(batch_size, -1) m1 = m1.reshape(batch_size, -1) m2 = m2.reshape(batch_size, -1) out_dim = D.shape[1] # For potential merge max_var = torch.max(torch.abs(m1_list[-1] - m2_list[-1])) # Update update_list = W_list if max_var > 1e-4 else W_list[:-1] for idx, W in enumerate(update_list): W_list[idx] = reduced_bm_bm(D, W) # Add the contribution of this layer if max_var > 1e-4: W_list.append(torch.ones([batch_size, out_dim], device = D.device)) m1_list.append(m1) m2_list.append(m2) else: m1_list[-1] = m1_list[-1] * D + m1 m2_list[-1] = m2_list[-1] * D + m2 return W_list, m1_list, m2_list def bound_simp(self, x, l, u, W, m1, m2, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None, is_certify = 0): assert first_layer == False, 'activation layer cannot be the first layer' D_this_layer, m1_this_layer, m2_this_layer = linearize_arctan(l, u, is_certify) # of shape [batch_size, out_dim] new_W = reduced_bm_bm(D_this_layer, W) new_m1 = m1 * D_this_layer + m1_this_layer new_m2 = m2 * D_this_layer + m2_this_layer return new_W, new_m1, new_m2 def bound_ibp(self, x, l, u, first_layer = False, ori_perturb_norm = None, ori_perturb_eps = None, in_shape = None, pixel_range = None): assert first_layer == False, 'activation layer cannot be the first layer' l = self.forward(l) u = self.forward(u) return l, u def shape_transfer(self, in_shape): return in_shape def base(self,): class ArcTan(nn.modules): def __init__(self, ): super(ArcTan, self).__init__() def forward(self, x): return torch.atan(x) return ArcTan()
Python
UTF-8
266
2.90625
3
[]
no_license
from colorama import init init() ok = '\033[92m' fail = '\033[91m' close = '\033[0m' print(ok + '☑' + close, end=' ') # https://stackoverflow.com/questions/48445616/why-printing-in-color-in-a-windows-terminal-in-python-does-not-work # pip install colorama
Markdown
UTF-8
18,145
2.578125
3
[]
no_license
# Setup While programming, it is important to be aware of good pratices in order to avoid security issues down the line. To make this process easier, we will setup an environment for a C/C++ project with: * __Valgrind__ - to notify us of memory-related errors. * __CppCheck__ - to notify us of any security guidelines we are not following. * __GoogleTest__ - to write and run tests. * __Gcov__ - to ensure our tests cover the entire code. ## Project ### Structure The first thing we have to set is the project's folder structure. The following is a good structure for a medium-sized C/C++ project: ``` |-- Makefile |-- README.md |-- build | |-- app | |-- objects | `-- tests |-- include | |-- header_with_access_to_all_others.h | |-- module1/ | |-- module2/ | `-- module3/ |-- src | |-- module1/ | |-- module2 | `-- module3/ `-- tests |-- module1/ |-- module2/ `-- module3/ ``` * __`src/`__ - where we store `.c`/`.cpp` files for each module. * __`include/`__ - where we store `.h`/`.hpp` files for each module. * __`tests/`__ - where we store tests files for each module (will always be `.cpp` files, since googletest is written in C++). * __`src/`__ - where we store `.c`/`.cpp` files for each module. * __`build/`__ - where our objects and executables will be stored after compilation. * __`build/app/`__ - where our executable/library will be stored. ### Content As an example, this project could produce a single-linked list. It would have two modules: a `data/` module, where we will deal with storing data in a `void*` pointer, and a `list/` folder, where will implement the list using the `data/` module. Then the structure would look something like this: ``` |-- Makefile |-- README.md |-- build | |-- app | | `-- libds.so | |-- objects | | |-- data | | | `-- data.o | | `-- list_simple | | `-- list_simple.o | `-- tests | |-- data | | `-- data.o | `-- list_simple | `-- list_simple.o |-- include | |-- data | | `-- data.h | |-- ds.h | `-- list_simple | `-- list_simple.h |-- runner |-- src | |-- data | | `-- data.c | `-- list_simple | `-- list_simple.c `-- tests |-- data | `-- data.cpp `-- list_simple `-- list_simple.cpp ``` The `structs` and function declarations are in the header files, this allow any dependency between the modules to be dealt with by the compiler. ## Makefile First, we will write an `Makefile` that compile our modules into objects that later are compiled together to produce the desired executable/library. We can then add the relevant tools to our `Makefile`, integrating it to our development cycle. We will build upon [this `Makefile`](https://www.partow.net/programming/makefile/index.html) If you have some doubts about how this works, check [here for how Makefiles in general work](https://makefiletutorial.com/) and [here for how some of the tricks inside `$()` used here work](https://www.gnu.org/software/make/manual/html_node/Substitution-Refs.html) ``` # folders ROOT_DIR :=. SRC_DIR := $(ROOT_DIR)/src INCLUDE_DIR := $(ROOT_DIR)/include BUILD_DIR := $(ROOT_DIR)/build OBJ_DIR := $(BUILD_DIR)/objects APP_DIR := $(BUILD_DIR)/app TEST_OBJ_DIR := $(BUILD_DIR)/tests # targets and pre-requisites # change *.c to *.cpp for C++ projects SRC := $(wildcard $(SRC_DIR)/*/*.c ) # change %.c to %.cpp for C++ projects OBJECTS := $(SRC:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o) TARGET := libds.so # libraries (without -l) LIBS := # compiler settings CXX := g++ -std=c++17 CXXFLAGS := -pedantic-errors -Wall -Wextra -Werror -fPIC LDFLAGS := $(addprefix -l,$(LIBS)) INCLUDE := -I$(INCLUDE_DIR) # final preparations (don't change this) TARGET_FINAL := $(APP_DIR)/$(TARGET) .PHONY: all folders clean debug release test release: CXXFLAGS += -O3 release: all all: folders $(TARGET_FINAL) debug: CXXFLAGS += -DDEBUG -g debug: | test all folders: @mkdir -p $(APP_DIR) @mkdir -p $(OBJ_DIR) @mkdir -p $(TEST_OBJ_DIR) clean: -@rm -rvf $(OBJ_DIR)/* -@rm -rvf $(APP_DIR)/* -@rm -rvf $(TEST_OBJ_DIR)/* $(TARGET_FINAL): $(OBJECTS) @mkdir -p $(@D) $(CXX) $(CXXFLAGS) -o $(TARGET_FINAL) $^ $(LDFLAGS) -shared -fPIC # change $(SRC_DIR)/%.c to $(SRC_DIR)/%.cpp for C++ projects $(OBJECTS): $(OBJ_DIR)/%.o: $(SRC_DIR)/%.c @mkdir -p $(@D) $(CXX) $(CXXFLAGS) $(INCLUDE) -c $< -o $@ ``` Some important things to note here: we are calling `g++` instead of `gcc`. Even though we are going to write C code, googletest, which we will add shortly, is written in C++. To compile C code as you would with `gcc` in a C++ compiler, just put it inside a [`extern "C"` block](https://stackoverflow.com/questions/1041866/what-is-the-effect-of-extern-c-in-c). ## Adding tools ### Googletest The first tool we will add is googletest. With it we can write tests to make sure our code is behaving as expected. You can follow instructions on how to install and use googletest from their [README.md in github](https://github.com/google/googletest) or get a quick explanation and installation procedure from [one of my notes](googletest.md). We will add some lines to our `Makefile`, in order to compile the tests and run them if `make debug` is called. The idea of this `Makefile` is that if someone clones a repository with it, the only step to compile everything is to run `make`, which will only produce the final binary, with no tests and thus no need to have googletest installed: ``` # folders ROOT_DIR :=. SRC_DIR := $(ROOT_DIR)/src INCLUDE_DIR := $(ROOT_DIR)/include BUILD_DIR := $(ROOT_DIR)/build OBJ_DIR := $(BUILD_DIR)/objects APP_DIR := $(BUILD_DIR)/app TEST_OBJ_DIR := $(BUILD_DIR)/tests TEST_SRC_DIR := $(ROOT_DIR)/tests # targets and pre-requisites # change *.c to *.cpp for C++ projects SRC := $(wildcard $(SRC_DIR)/*/*.c ) # change %.c to %.cpp for C++ projects OBJECTS := $(SRC:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o) TESTS_SRC := $(wildcard $(TEST_SRC_DIR)/*/*.cpp) TESTS_OBJ := $(TESTS_SRC:$(TEST_SRC_DIR)/%.cpp=$(TEST_OBJ_DIR)/%.o) TARGET := libds.so TEST_TARGET := runner # libraries (without -l) LIBS := TEST_LIBS := gtest gtest_main pthread # compiler settings CXX := g++ -std=c++17 CXXFLAGS := -pedantic-errors -Wall -Wextra -Werror -fPIC LDFLAGS := $(addprefix -l,$(LIBS)) INCLUDE := -I$(INCLUDE_DIR) TEST_LIBS := $(addprefix -l,$(TEST_LIBS)) # final preparations (don't change this) TARGET_FINAL := $(APP_DIR)/$(TARGET) TEST_TARGET_FINAL := $(ROOT_DIR)/$(TEST_TARGET) .PHONY: all folders clean debug release test release: CXXFLAGS += -O3 release: all all: folders $(TARGET_FINAL) debug: CXXFLAGS += -DDEBUG -g debug: | $(TESTS_OBJ) test all test: LDFLAGS += $(TEST_LIBS) test: $(TESTS_OBJ) $(OBJECTS) $(CXX) $(CXXFLAGS) $(INCLUDE) -o $(TEST_TARGET_FINAL) $^ $(LDFLAGS) $(TEST_TARGET_FINAL) folders: @mkdir -p $(APP_DIR) @mkdir -p $(OBJ_DIR) @mkdir -p $(TEST_OBJ_DIR) clean: -@rm -rvf $(OBJ_DIR)/* -@rm -rvf $(APP_DIR)/* -@rm -rvf $(TEST_OBJ_DIR)/* -@rm -vf $(TEST_TARGET_FINAL) $(TARGET_FINAL): $(OBJECTS) @mkdir -p $(@D) $(CXX) $(CXXFLAGS) -o $(TARGET_FINAL) $^ $(LDFLAGS) -shared -fPIC # change $(SRC_DIR)/%.c to $(SRC_DIR)/%.cpp for C++ projects $(OBJECTS): $(OBJ_DIR)/%.o: $(SRC_DIR)/%.c @mkdir -p $(@D) $(CXX) $(CXXFLAGS) $(INCLUDE) -c $< -o $@ $(TESTS_OBJ): $(OBJECTS) $(TESTS_OBJ): $(TEST_OBJ_DIR)/%.o: $(TEST_SRC_DIR)/%.cpp @mkdir -p $(@D) $(CXX) $(CXXFLAGS) $(INCLUDE) -c $< -o $@ ``` Remember: googletest enable us to write and check our tests, but how confident we can be that our tests are good depend on us. ### Valgrind Before installing valgrind, mind that using `sudo apt install valgrind` may install an old version which produce false positives (at least in debian, other distributions may install more up-to-date versions). I personally recommend avoiding the trouble and downloding and compiling the source from [their site](https://www.valgrind.org/downloads/current.html). After that, adding the tool is pretty simple, we just have to run our tests using it. However, we give it some arguments to make sure `valgrind` give us a lot of details and also stops at the first error (`--exit-on-first-error=yes`). We set an non-zero error exit code (`--error-exitcode=1`) so the `Makefile` stops executing when `valgrind` finds an error. The idea is to compile with `make debug`, read the only error that may appear, fix it and do it all again. The cherry on top is the `-q` option. This means that valgrind will output nothing if no error occured: ``` # folders ROOT_DIR :=. SRC_DIR := $(ROOT_DIR)/src INCLUDE_DIR := $(ROOT_DIR)/include BUILD_DIR := $(ROOT_DIR)/build OBJ_DIR := $(BUILD_DIR)/objects APP_DIR := $(BUILD_DIR)/app TEST_OBJ_DIR := $(BUILD_DIR)/tests TEST_SRC_DIR := $(ROOT_DIR)/tests # targets and pre-requisites # change *.c to *.cpp for C++ projects SRC := $(wildcard $(SRC_DIR)/*/*.c ) # change %.c to %.cpp for C++ projects OBJECTS := $(SRC:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o) TESTS_SRC := $(wildcard $(TEST_SRC_DIR)/*/*.cpp) TESTS_OBJ := $(TESTS_SRC:$(TEST_SRC_DIR)/%.cpp=$(TEST_OBJ_DIR)/%.o) TARGET := libds.so TEST_TARGET := runner # libraries (without -l) LIBS := TEST_LIBS := gtest gtest_main pthread # compiler settings CXX := g++ -std=c++17 CXXFLAGS := -pedantic-errors -Wall -Wextra -Werror -fPIC LDFLAGS := $(addprefix -l,$(LIBS)) INCLUDE := -I$(INCLUDE_DIR) TEST_LIBS := $(addprefix -l,$(TEST_LIBS)) # final preparations (don't change this) TARGET_FINAL := $(APP_DIR)/$(TARGET) TEST_TARGET_FINAL := $(ROOT_DIR)/$(TEST_TARGET) .PHONY: all folders clean debug release test release: CXXFLAGS += -O3 release: all all: folders $(TARGET_FINAL) debug: CXXFLAGS += -DDEBUG -g debug: | $(TESTS_OBJ) test all test: LDFLAGS += $(TEST_LIBS) test: $(TESTS_OBJ) $(OBJECTS) $(CXX) $(CXXFLAGS) $(INCLUDE) -o $(TEST_TARGET_FINAL) $^ $(LDFLAGS) @valgrind -q --exit-on-first-error=yes --error-exitcode=1\ --tool=memcheck --show-reachable=yes --leak-check=yes --track-origins=yes $(TEST_TARGET_FINAL) folders: @mkdir -p $(APP_DIR) @mkdir -p $(OBJ_DIR) @mkdir -p $(TEST_OBJ_DIR) clean: -@rm -rvf $(OBJ_DIR)/* -@rm -rvf $(APP_DIR)/* -@rm -rvf $(TEST_OBJ_DIR)/* -@rm -vf $(TEST_TARGET_FINAL) $(TARGET_FINAL): $(OBJECTS) @mkdir -p $(@D) $(CXX) $(CXXFLAGS) -o $(TARGET_FINAL) $^ $(LDFLAGS) -shared -fPIC # change $(SRC_DIR)/%.c to $(SRC_DIR)/%.cpp for C++ projects $(OBJECTS): $(OBJ_DIR)/%.o: $(SRC_DIR)/%.c @mkdir -p $(@D) $(CXX) $(CXXFLAGS) $(INCLUDE) -c $< -o $@ $(TESTS_OBJ): $(OBJECTS) $(TESTS_OBJ): $(TEST_OBJ_DIR)/%.o: $(TEST_SRC_DIR)/%.cpp @mkdir -p $(@D) $(CXX) $(CXXFLAGS) $(INCLUDE) -c $< -o $@ ``` In the end, we only change one line of code from the previous `Makefile`. ### CppCheck `cppcheck` is a static analysis tool. This means that unlike `valgrind` that runs your program to analyse it, `cppcheck` only reads your source. We give `cppcheck` all the source files: test `.c` files, `.c` files and headers. Since we won't give the system header files to it (like `stdio.h`) we add `--suppress=missingIncludeSystem` We add `--quiet` to make `cppcheck` output nothing if no errors were found (just like in `valgrind`). The `--addon` arguments tell `cppcheck` to do extra checks. Mind the `--addon=cert`, it will check our code against the CERT C guidelines. The rest of the arguments just tell `cppcheck` to be thorough and take longer in the analysis if necessary: ``` # folders ROOT_DIR :=. SRC_DIR := $(ROOT_DIR)/src INCLUDE_DIR := $(ROOT_DIR)/include BUILD_DIR := $(ROOT_DIR)/build OBJ_DIR := $(BUILD_DIR)/objects APP_DIR := $(BUILD_DIR)/app TEST_OBJ_DIR := $(BUILD_DIR)/tests TEST_SRC_DIR := $(ROOT_DIR)/tests # targets and pre-requisites SRC := $(wildcard $(SRC_DIR)/*/*.c ) OBJECTS := $(SRC:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o) TESTS_SRC := $(wildcard $(TEST_SRC_DIR)/*/*.cpp) TESTS_OBJ := $(TESTS_SRC:$(TEST_SRC_DIR)/%.cpp=$(TEST_OBJ_DIR)/%.o) TARGET := libds.so TEST_TARGET := runner # libraries (without -l) LIBS := TEST_LIBS := gtest gtest_main pthread # compiler settings CXX := g++ -std=c++17 CXXFLAGS := -pedantic-errors -Wall -Wextra -Werror -fPIC LDFLAGS := $(addprefix -l,$(LIBS)) INCLUDE := -I$(INCLUDE_DIR) TEST_LIBS := $(addprefix -l,$(TEST_LIBS)) # final preparations (don't change this) TARGET_FINAL := $(APP_DIR)/$(TARGET) TEST_TARGET_FINAL := $(ROOT_DIR)/$(TEST_TARGET) # tests, static analysis and code coverage RUN_TESTS_COMMAND:=@valgrind -q --exit-on-first-error=yes --error-exitcode=1 --tool=memcheck\ --show-reachable=yes --leak-check=yes --track-origins=yes $(TEST_TARGET_FINAL) STATIC_ANALYSIS_COMMAND:=@cppcheck --addon=cert --addon=y2038 --addon=threadsafety --addon=naming \ $(INCLUDE) --suppress=missingIncludeSystem --bug-hunting --quiet --enable=all $(SRCS) $(TESTS_SRC) .PHONY: all folders clean debug release test release: CXXFLAGS += -O3 release: all all: folders $(TARGET_FINAL) debug: CXXFLAGS += -DDEBUG -g debug: | $(TESTS_OBJ) test all test: LDFLAGS += $(TEST_LIBS) test: $(TESTS_OBJ) $(OBJECTS) $(CXX) $(CXXFLAGS) $(INCLUDE) -o $(TEST_TARGET_FINAL) $^ $(LDFLAGS) $(RUN_TESTS_COMMAND) $(STATIC_ANALYSIS_COMMAND) folders: @mkdir -p $(APP_DIR) @mkdir -p $(OBJ_DIR) @mkdir -p $(TEST_OBJ_DIR) clean: -@rm -rvf $(OBJ_DIR)/* -@rm -rvf $(APP_DIR)/* -@rm -rvf $(TEST_OBJ_DIR)/* -@rm -vf $(TEST_TARGET_FINAL) $(TARGET_FINAL): $(OBJECTS) @mkdir -p $(@D) $(CXX) $(CXXFLAGS) -o $(TARGET_FINAL) $^ $(LDFLAGS) -shared -fPIC $(OBJECTS): $(OBJ_DIR)/%.o: $(SRC_DIR)/%.c @mkdir -p $(@D) $(CXX) $(CXXFLAGS) $(INCLUDE) -c $< -o $@ $(TESTS_OBJ): $(OBJECTS) $(TESTS_OBJ): $(TEST_OBJ_DIR)/%.o: $(TEST_SRC_DIR)/%.cpp @mkdir -p $(@D) $(CXX) $(CXXFLAGS) $(INCLUDE) -c $< -o $@ ``` ### Gcov If you are testing your software properly, you should be testing all of it. Although the percentage of lines tested is not a good metric to say if the code is well tested, it is certain that untested code is not good. With `gcov` we can check if our tests cover all the code. Mind that a 100% code coverage does not mean your code is good, secure and ready for production. In fact, if your tests only pass through each line of code once, it probably means they are not good enough, since you should test many input/output scenarios. To use `gcov`, we need to compile our code with `--coverage` and then run `gcov <object files>` The other arguments given tells `gcov` to don't output to a file (`-n`), only show results for the files given as argument only (`-r`) and demangle C++ names (`-m`, we are not going to use C++ though). The process will output some files related to `gcov` in the same directory as our objects files. We can just ignore them. In the following file, we also use `grep`, `paste` to ignore any output from `gcov` that shows a file with 100% code coverage, since we are looking for files with untested code: ``` # folders ROOT_DIR :=. SRC_DIR := $(ROOT_DIR)/src INCLUDE_DIR := $(ROOT_DIR)/include BUILD_DIR := $(ROOT_DIR)/build OBJ_DIR := $(BUILD_DIR)/objects APP_DIR := $(BUILD_DIR)/app TEST_OBJ_DIR := $(BUILD_DIR)/tests TEST_SRC_DIR := $(ROOT_DIR)/tests # targets and pre-requisites SRC := $(wildcard $(SRC_DIR)/*/*.c ) OBJECTS := $(SRC:$(SRC_DIR)/%.c=$(OBJ_DIR)/%.o) TESTS_SRC := $(wildcard $(TEST_SRC_DIR)/*/*.cpp) TESTS_OBJ := $(TESTS_SRC:$(TEST_SRC_DIR)/%.cpp=$(TEST_OBJ_DIR)/%.o) TARGET := libds.so TEST_TARGET := runner # libraries (without -l) LIBS := TEST_LIBS := gtest gtest_main pthread # compiler settings CXX := g++ -std=c++17 CXXFLAGS := -pedantic-errors -Wall -Wextra -Werror -fPIC LDFLAGS := $(addprefix -l,$(LIBS)) INCLUDE := -I$(INCLUDE_DIR) TEST_LIBS := $(addprefix -l,$(TEST_LIBS)) # final preparations (don't change this) TARGET_FINAL := $(APP_DIR)/$(TARGET) TEST_TARGET_FINAL := $(ROOT_DIR)/$(TEST_TARGET) # tests, static analysis and code coverage GCOV_COMMAND:=gcov -rnm $(TESTS_OBJ) $(OBJECTS) 2>/dev/null | grep -Eo "('.*'|[[:digit:]]{1,3}.[[:digit:]]{2}%)" | paste -d " " - - | sort -k2 -nr UNTESTED_DETECTOR_COMMAND:=$(GCOV_COMMAND) | grep -v "100.00%" | awk '{ print "\x1b[38;2;255;25;25;1m" $$1 " \x1b[0m\x1b[38;2;255;100;100;1m" $$2 "\x1b[0m" }' COVERAGE_COMMAND:=@$(UNTESTED_DETECTOR_COMMAND); $(GCOV_COMMAND) | awk '{ sum += $$2; count[NR] = $$2 } END { if(NR%2) { median=count[(NR+1)/2]; } else { median=count[NR/2]; } if( NR==0 ) { NR=1; } print "\x1b[32mCode Coverage\x1b[0m:\n\t\x1b[33mAverage\x1b[0m: " sum/NR "%\n\x1b[35m\tMedian\x1b[0m: " median }' RUN_TESTS_COMMAND:=@valgrind -q --exit-on-first-error=yes --error-exitcode=1 --tool=memcheck\ --show-reachable=yes --leak-check=yes --track-origins=yes $(TEST_TARGET_FINAL) STATIC_ANALYSIS_COMMAND:=@cppcheck --addon=cert --addon=y2038 --addon=threadsafety --addon=naming \ $(INCLUDE) --suppress=missingIncludeSystem --bug-hunting --quiet --enable=all $(SRC) $(TESTS_SRC) .PHONY: all folders clean debug release test release: CXXFLAGS += -O3 release: all all: folders $(TARGET_FINAL) debug: CXXFLAGS += -DDEBUG -g debug: COVERAGE = --coverage debug: | $(TESTS_OBJ) test all test: LDFLAGS += $(TEST_LIBS) test: $(TESTS_OBJ) $(OBJECTS) $(CXX) $(CXXFLAGS) $(INCLUDE) $(COVERAGE) -o $(TEST_TARGET_FINAL) $^ $(LDFLAGS) $(STATIC_ANALYSIS_COMMAND) $(RUN_TESTS_COMMAND) $(COVERAGE_COMMAND) folders: @mkdir -p $(APP_DIR) @mkdir -p $(OBJ_DIR) @mkdir -p $(TEST_OBJ_DIR) clean: -@rm -rvf $(OBJ_DIR)/* -@rm -rvf $(APP_DIR)/* -@rm -rvf $(TEST_OBJ_DIR)/* -@rm -vf $(TEST_TARGET_FINAL) $(TARGET_FINAL): $(OBJECTS) @mkdir -p $(@D) $(CXX) $(CXXFLAGS) -o $(TARGET_FINAL) $^ $(LDFLAGS) -shared -fPIC $(OBJECTS): $(OBJ_DIR)/%.o: $(SRC_DIR)/%.c @mkdir -p $(@D) $(CXX) $(CXXFLAGS) $(INCLUDE) $(COVERAGE) -c $< -o $@ $(TESTS_OBJ): $(OBJECTS) $(TESTS_OBJ): $(TEST_OBJ_DIR)/%.o: $(TEST_SRC_DIR)/%.cpp @mkdir -p $(@D) $(CXX) $(CXXFLAGS) $(INCLUDE) -c $< -o $@ ``` ## Conclusion You can also check a version of the final `Makefile` [here](https://gist.github.com/asimos-bot/dd3ac015efe8dcf2f08f8719e41153da). I hope this gives you an idea on how to integrate tools to help you write secure C code. If you intend on also doing a project in another language, looking for similar tools that work for them can really pay off. Happy Learning!
Markdown
UTF-8
8,838
3.65625
4
[ "BSD-2-Clause" ]
permissive
--- title: "特征和接口(Traits and Interfaces)" section: "类型系统(Types)" menu: toc: parent: "types" weight: 50 toc: true --- <!-- Like other object-oriented languages, Pony has __subtyping__. That is, some types serve as _categories_ that other types can be members of. --> 与其他面向对象的语言一样,Pony具有 __多态性(subtyping)__ 。也就是说,某些类型充当 _categories_ ,其他类型可以成为其成员。 <!-- There are two kinds of __subtyping__ in programming languages: __nominal__ and __structural__. They're subtly different, and most programming languages only have one or the other. Pony has both! --> 编程语言的实现上有两种 __多态(subtyping)__ 类型: __声明式(nominal)多态__ 和 __结构化(structural)多态__ 。它们有细微的不同,大多数编程语言只会选择一种实现。但是Pony两种都实现了! <!-- ## Nominal subtyping --> ## 声明式多态(Nominal subtyping) <!-- This kind of subtyping is called __nominal__ because it is all about __names__. --> 这种多态的实现被称为 __声明式__ ,因为它需要你明确指出你要实现的 __类型名__ 。 <!-- If you've done object-oriented programming before, you may have seen a lot of discussion about _single inheritance_, _multiple inheritance_, _mixins_, _traits_, and similar concepts. These are all examples of __nominal subtyping__. --> 如果你有过面向对象编程经验,你应该熟悉 _继承(单)_ 、 _多重继承_ 、 _组合_ 、 _特征_ 或类似的概念,所有的这些都属于 __声明式多态__ <!-- The core idea is that you have a type that declares it has a relationship to some category type. In Java, for example, a __class__ (a concrete type) can __implement__ an __interface__ (a category type). In Java, this means the class is now in the category that the interface represents. The compiler will check that the class actually provides everything it needs to. --> 核心思想是您有一个声明与某种类别类型有关系的类型。例如,在Java中,类(具体类型)可以实现某个接口(抽象类型)。在Java中,这表示这个类必须要实现指定抽象接口。编译器将检查该类是否实现了此抽象类型需要的所有接口。 <!-- ## Traits: nominal subtyping --> ## Pony的特征(Traits):声明式多态(Nominal subtyping) <!-- Pony has nominal subtyping, using __traits__. A __trait__ looks a bit like a __class__, but it uses the keyword `trait` and it can't have any fields. --> Pony使用 __特征(trait)__ 来实现声明式多态。__trait__ 的定义看上去有点像 __class__ ,但是它使用关键字trait,并且不能有任何字段。 ```pony trait Named fun name(): String => "Bob" class Bob is Named ``` <!-- Here, we have a trait `Named` that has a single function `name` that returns a String. It also provides a default implementation of `name` that returns the string literal "Bob". --> 上面代码中,我们定义了一个名为`Named`的特征,他又一个名为`name()`的成员函数,返回类型是字符串。它还提供了`name()`函数的默认实现,返回字符串"Bob"。 <!-- We also have a class `Bob` that says it `is Named`. This means `Bob` is in the `Named` category. In Pony, we say _Bob provides Named_, or sometimes simply _Bob is Named_. --> 接着定义了类名为`Bob`的类。`Bob在`明确的声明自己实现了`Named`特征。在Pony中,我们把这成为 _Bob拥有Named特征_ ,或者说 _Bob就是Named_ 。 <!-- Since `Bob` doesn't have its own `name` function, it uses the one from the trait. If the trait's function didn't have a default implementation, the compiler would complain that `Bob` had no implementation of `name`. --> 我们看到`Bob`并没有定义`name()`函数,所以它会使用特征中的默认实现。如果特征对`name()`函数没有做出默认实现,则编译器就会报一个错告知:`Bob`没有实现`name()`。 ```pony trait Named fun name(): String => "Bob" trait Bald fun hair(): Bool => false class Bob is (Named & Bald) ``` <!-- It is possible for a class to have relationships with multiple categories. In the above example, the class `Bob` _provides both Named and Bald_. --> 一个类可以同时具备多个特征。在上面的示例中,`Bob`类同时提供了Named和Bald特征。 ```pony trait Named fun name(): String => "Bob" trait Bald is Named fun hair(): Bool => false class Bob is Bald ``` <!-- It is also possible to combine categories together. In the example above, all `Bald` classes are automatically `Named`. Consequently, the `Bob` class has access to both hair() and name() default implementation of their respective trait. One can think of the `Bald` category to be more specific than the `Named` one. --> 特征是支持组合的。在上面的示例中,所有`Bald`特征类被声明为包含`Named`特征。因此,`Bob`类可以访问两个特征类中的hair()和name()函数的默认实现。从语义上来说,我们可以认为Bald是一个更加明确的特征:Named泛指一个人的基础特征拥有一个名字,Bald更加明确的去描述是否有头发,然后我们使用这套规则描述一个没有头发的老头`Bob`。 ```pony class Larry fun name(): String => "Larry" ``` <!-- Here, we have a class `Larry` that has a `name` function with the same signature. But `Larry` does __not__ provide `Named`! --> 这个示例中,我们定义了一个名为`Larry`的类,该类也具备`name()`函数。但是`Larry`不是一个`Named`。 <!-- __Wait, why not?__ Because `Larry` doesn't say it `is Named`. Remember, traits are __nominal__: a type that wants to provide a trait has to explicitly declare that it does. And `Larry` doesn't --> __等等,为什么不是呢?__ 因为它并没有声明自己具备`Named`特征! 请记住,特征需要 __声明(nominal)__ :想要提供特征的类型必须显式的声明。`Larry`确实没有声明。 <!-- ## Structural subtyping --> ## 结构化多态(Structural subtyping) <!-- There's another kind of subtyping, where the name doesn't matter. It's called __structural subtyping__, which means that it's all about how a type is built, and nothing to do with names. --> 多态还有另一种实现方式,无需明确声明,这种被称为 __结构化多态__ ,这意味着这与类型的构建方式有关,与名称无关。 <!-- A concrete type is a member of a structural category if it happens to have all the needed elements, no matter what it happens to be called. --> 结构化多态的实现思路是,如果一个类型A恰好具备一个结构类别B所有必需的成员,那么A就是B。 <!-- If you've used Go, you'll recognise that Go interfaces are structural types. --> 如果你用过Go语言,你会自然而然的想到Go的`interface`就是结构化多态的实现。 <!-- ## Interfaces: structural subtyping --> ## Pony的接口(Interfaces): 结构化多态(structural subtyping) <!-- Pony has structural subtyping too, using __interfaces__. Interfaces look like traits, but they use the keyword `interface`. --> Pony也支持结构化多态,用 _接口(interfaces)__ 就可以做到。接口看起来和特征差不多,不过它用`interface`定义。 ```pony interface HasName fun name(): String ``` <!-- Here, `HasName` looks a lot like `Named`, except it's an interface instead of a trait. This means both `Bob` and `Larry` provide `HasName`! The programmers that wrote `Bob` and `Larry` don't even have to be aware that `HasName` exists. --> 上面的示例中,我们看到`HasName`接口和之前的`Named`特征,除了定义用的关键字不同外,似乎没多大区别。还记得`Larry`吗?"`Larry`不是一个`Named`",但是"`Larry`却是是一个`HasName`","`Bob`也是一个`HasName`"。但是程序中没有任何地方声明`Bob`和`Larry`与`HasName`有什么关联。 <!-- Pony interfaces can have functions with default implementations as well. A type will only pick those up if it explicitly declares that it `is` that interface. --> Pony的接口也可以具有默认实现的功能。如果类型明确声明它是该接口,则该类型将仅接受这些类型。 <!-- __Should I use traits or interfaces in my own code?__ Both! Interfaces are more flexible, so if you're not sure what you want, use an interface. But traits are a powerful tool as well: they stop _accidental subtyping_. --> __我应该在自己的代码中使用特征还是接口?__ 相信我,你两种都用的着!接口更加灵活,因此,如果不确定自己想要什么,请使用接口。但是特征也是一个强大的工具:它可以帮你检查子类型实现的完整性。
C++
UTF-8
1,542
3.921875
4
[]
no_license
// 19_RemoveNthNodeFromEndOfList.cpp : Defines the entry point for the console application. // /* Given a linked list, remove the n-th node from the end of list and return its head. Example: Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5. Note: Given n will always be valid. Follow up: Could you do this in one pass? */ #include "stdafx.h" #include <vector> #include <iostream> using namespace std; /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* p1 = nullptr; ListNode* p2 = head; ListNode* p3 = head; for (int i = 0; i < n; i++) { p3 = p3->next; } while (p3 != nullptr) { p3 = p3->next; p1 = p2; p2 = p2->next; } if (p1 != nullptr) { p1->next = p2->next; delete p2; return head; } else { head = p2->next; delete p2; return head; } } }; int main() { ListNode* head = new ListNode(1); ListNode* tail = head; std::vector<int> nums = { 2, 3, 4, 5 }; for each (int var in nums) { tail->next = new ListNode(var); tail = tail->next; } Solution sln; head = sln.removeNthFromEnd(head, 5); while (head != nullptr) { cout << head->val << " "; head = head->next; } cout << endl; return 0; }
Java
UTF-8
495
2.296875
2
[]
no_license
package OODay07; /** * @author afeng * @date 2018/7/25 20:08 **/ public class CommonHandset extends HandSet implements PlayVideo { public CommonHandset(String brand, String type) { super(brand, type); } @Override public void playing() { System.out.println("开始播放音乐<<热雪>>"); } @Override public void sendInfo() { super.sendInfo(); } @Override public void call() { super.call(); } }
Java
UTF-8
1,930
3.71875
4
[]
no_license
package assignment05; public class Pizza { private String pizzaSize; private int cheese; private int pepperoni; private int bacon; public Pizza() { this.pizzaSize = ""; this.cheese = 0; this.pepperoni = 0; this.bacon = 0; } public Pizza(String pizzaSize, int cheese, int pepperoni, int bacon) { this.pizzaSize = pizzaSize; this.cheese = cheese; this.pepperoni = pepperoni; this.bacon = bacon; } public String getPizzaSize() { return pizzaSize; } public void setPizzaSize(String pizzaSize) { this.pizzaSize = pizzaSize; } public int getNumCheeseToppings() { return cheese; } public void setNumCheeseToppings(int cheese) { this.cheese = cheese; } public int getNumPepperoniToppings() { return pepperoni; } public void setNumPepperoniToppings(int pepperoni) { this.pepperoni = pepperoni; } public int getNumHmaToppings() { return bacon; } public void setNumHmaToppings(int bacon) { this.bacon = bacon; } public double calcCost() { if(pizzaSize.equalsIgnoreCase("Small")){ return 10 + (cheese + pepperoni + bacon) * 2;} else if(pizzaSize.equalsIgnoreCase("Medium")){ return 12 + (cheese + pepperoni + bacon) * 2;} else if(pizzaSize.equalsIgnoreCase("Large")){ return 14 + (cheese + pepperoni + bacon) * 2;} else{ return 0.0;} } public String getDescription() { return "Pizza Size: " + pizzaSize + "\n Number of Cheese toppings: " + cheese + "\n Number of Pepperoni toppings: " + pepperoni + "\n Number of Bacon toppings: " + bacon + "\n TOTAL COST: $" + calcCost() + "\n"; } }
C
UTF-8
1,636
3.4375
3
[]
no_license
#ifndef SEQUENCESTACK_H_INCLUDED #define SEQUENCESTACK_H_INCLUDED #include "./Status.h" #define STACK_INIT_SIZE 100 #define STACKINCREMENT 10 typedef int ElemType; typedef struct{ ElemType *base; ElemType *top; int stacksize; }SqStack; Status InitStack_Sq(SqStack *S){ S ->base = (ElemType *)malloc(STACK_INIT_SIZE *sizeof(ElemType)); if(!S->base) exit(OVERFLOW); S->top = S->base; S->stacksize = STACK_INIT_SIZE; return OK; } Status StackEmpty_Sq(SqStack S){ return S.top == S.base ? TRUE :FALSE; } Status ClearStack_Sq(SqStack *S){ S->top = S->base; return OK; } Status DestroyStack_Sq(SqStack *S){ ClearStack_Sq(S); free(S->base); S->base = NULL; return OK; } int StackLength_Sq(SqStack S){ return S.top - S.base; } Status Push_Sq(SqStack *S, ElemType e){ if(S->top - S->base >= S->stacksize){ S->base = (ElemType *) realloc(S->base,(S->stacksize +STACKINCREMENT)*sizeof(ElemType)); if(!S->base) exit(OVERFLOW); S->top =S->base+S->stacksize; S->stacksize += STACKINCREMENT; } *S->top = e; S->top ++; return OK; } Status Pop_Sq(SqStack *S, ElemType *e){ while(S->base == S->top) exit(ERROR); --S->top ; *e = *(S->top); return OK; } Status GetTop_Sq(SqStack S, ElemType *e){ if(S.base == S.top) return ERROR; *e = *(S.top - 1); return OK; } Status StackTraverse_Sq(SqStack S, void(Visit)(ElemType)){ ElemType *e = S.base; while(e<S.top){ Visit(*e); *e++; } return OK; } #endif // SEQUENCESTACK_H_INCLUDED
JavaScript
UTF-8
1,049
4.96875
5
[]
no_license
/* 피보나치 수 피보나치 수는 0과 1로 시작하며, 다음 피보나치 수는 바로 앞의 두 피보나치 수의 합이 된다. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765, 10946… 2 이상의 n이 입력되었을 때, n번째 피보나치 수를 반환하는 fibonacci 함수를 작성하라. 예를 들어 n = 3이라면 2를 반환한다. */ function fibonacci(n) { // const res = Array.from({ length: n + 1}); // const result = res.map((_, i, arr) => i > 1 ? arr[i] = arr[i - 2] + arr[i - 1] : arr[i] = i); // return result[n]; const res = [0, 1]; for (let i = 0; i < n+1; i++) { if (i > 1) { res.push(res[i-2] + res[i-1]); } } return res[n]; } console.log(fibonacci(2)); // 1 console.log(fibonacci(3)); // 2 console.log(fibonacci(4)); // 3 console.log(fibonacci(5)); // 5 console.log(fibonacci(6)); // 8 console.log(fibonacci(9)); // 34 console.log(fibonacci(13)); // 233 console.log(fibonacci(18)); // 2584 console.log(fibonacci(21)); // 10946
Java
UTF-8
1,657
3.734375
4
[]
no_license
package CodingInterviewGuide.demo.Chapter8; /** * 转圈打印矩阵 * 给定一个整数矩阵 matrix,请按照转圈的方式打印它。 */ public class SpiralOrderPrint { public void spiralOrderPrint(int[][] maxtrix) { int tR = 0; int tC = 0; int dR = maxtrix.length-1; int dC = maxtrix[0].length -1; while (tR <= dR && tC <= dC) { prinfEdge(maxtrix, tR++, tC++, dR--, dC--); } } private void prinfEdge(int[][] maxtrix, int tR, int tC, int dR, int dC) { if (tR == dR) { for (int i=0; i<= dC; i++) { System.out.print(maxtrix[tR][i] + " "); } } else if (tC == dC) { for (int i=0; i<= tC; i++) { System.out.print(maxtrix[i][tC] + " "); } } else { int curR = tR; int curC = tC; while (curC != dC) { System.out.print(maxtrix[curR][curC++] + " "); } while (curR != dC) { System.out.print(maxtrix[curR++][curC] + " "); } while (curC != tC) { System.out.print(maxtrix[curR][curC--] + " "); } while (curR != tR) { System.out.print(maxtrix[curR--][curC] + " "); } } } public static void main(String[] args) { int[][] matrix = new int[][]{ {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}, }; SpiralOrderPrint sop = new SpiralOrderPrint(); sop.spiralOrderPrint(matrix); } }
JavaScript
UTF-8
423
2.5625
3
[]
no_license
$().ready(function(){ $('.recommend-tag').click(function(){ var label = $(this).text(); $('#tag-input').val( $('#tag-input').val() + ' ' + label ); return false; }); $('#profile-delete').click(function(){ var ret = confirm('プロフィールを削除します。よろしいですか?'); if(ret == true) { }else{ return false; } }); });
C++
UTF-8
3,619
2.5625
3
[]
no_license
#include <OneWire.h> #include <DallasTemperature.h> #define ONE_WIRE_BUS 7 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&oneWire); float tempC = 0; #define NOTE_D0 -1 #define NOTE_D1 262 #define NOTE_D2 293 #define NOTE_D3 329 #define NOTE_D4 349 #define NOTE_D5 392 #define NOTE_D6 440 #define NOTE_D7 494 #define NOTE_DL1 147 #define NOTE_DL2 165 #define NOTE_DL3 175 #define NOTE_DL4 196 #define NOTE_DL5 221 #define NOTE_DL6 248 #define NOTE_DL7 278 #define NOTE_DH1 523 #define NOTE_DH2 586 #define NOTE_DH3 658 #define NOTE_DH4 697 #define NOTE_DH5 783 #define NOTE_DH6 879 #define NOTE_DH7 987 //以上部分是定义是把每个音符和频率值对应起来,这里用NOTE_D+数字表示音符,NOTE_DH+数字表示上面有点的那种音符,NOTE_DL+数字表示下面有点的那种音符。 #define WHOLE 1 #define HALF 0.5 #define QUARTER 0.25 #define EIGHTH 0.25 #define SIXTEENTH 0.625 //这部分是用英文对应拍子 int tune[] = { NOTE_DH1,NOTE_D6,NOTE_D5,NOTE_D6,NOTE_D0, NOTE_DH1,NOTE_D6,NOTE_D5,NOTE_DH1,NOTE_D6,NOTE_D0,NOTE_D6, NOTE_D6,NOTE_D6,NOTE_D5,NOTE_D6,NOTE_D0,NOTE_D6, NOTE_DH1,NOTE_D6,NOTE_D5,NOTE_DH1,NOTE_D6,NOTE_D0, NOTE_D1,NOTE_D1,NOTE_D3, NOTE_D1,NOTE_D1,NOTE_D3,NOTE_D0, NOTE_D6,NOTE_D6,NOTE_D6,NOTE_D5,NOTE_D6, NOTE_D5,NOTE_D1,NOTE_D3,NOTE_D0, NOTE_DH1,NOTE_D6,NOTE_D6,NOTE_D5,NOTE_D6, NOTE_D5,NOTE_D1,NOTE_D2,NOTE_D0, NOTE_D7,NOTE_D7,NOTE_D5,NOTE_D3, NOTE_D5, NOTE_DH1,NOTE_D0,NOTE_D6,NOTE_D6,NOTE_D5,NOTE_D5,NOTE_D6,NOTE_D6, NOTE_D0,NOTE_D5,NOTE_D1,NOTE_D3,NOTE_D0, NOTE_DH1,NOTE_D0,NOTE_D6,NOTE_D6,NOTE_D5,NOTE_D5,NOTE_D6,NOTE_D6, NOTE_D0,NOTE_D5,NOTE_D1,NOTE_D2,NOTE_D0, NOTE_D3,NOTE_D3,NOTE_D1,NOTE_DL6, NOTE_D1, NOTE_D3,NOTE_D5,NOTE_D6,NOTE_D6, NOTE_D3,NOTE_D5,NOTE_D6,NOTE_D6, NOTE_DH1,NOTE_D0,NOTE_D7,NOTE_D5, NOTE_D6, };//这部分就是整首曲子的音符部分,用了一个序列定义为tune,整数 float duration[]= { 1,1,0.5,0.5,1, 0.5,0.5,0.5,0.5,1,0.5,0.5, 0.5,1,0.5,1,0.5,0.5, 0.5,0.5,0.5,0.5,1,1, 1,1,1+1, 0.5,1,1+0.5,1, 1,1,0.5,0.5,1, 0.5,1,1+0.5,1, 0.5,0.5,0.5,0.5,1+1, 0.5,1,1+0.5,1, 1+1,0.5,0.5,1, 1+1+1+1, 0.5,0.5,0.5+0.25,0.25,0.5+0.25,0.25,0.5+0.25,0.25, 0.5,1,0.5,1,1, 0.5,0.5,0.5+0.25,0.25,0.5+0.25,0.25,0.5+0.25,0.25, 0.5,1,0.5,1,1, 1+1,0.5,0.5,1, 1+1+1+1, 0.5,1,0.5,1+1, 0.5,1,0.5,1+1, 1+1,0.5,0.5,1, 1+1+1+1 };//这部分是整首曲子的节拍部分,也定义个序列duration,浮点(数组的个数和前面音符的个数是一样的,一一对应么) int length;//这里定义一个变量,后面用来表示共有多少个音符 int tonePin=9;//蜂鸣器的pin void setup() { pinMode(tonePin,OUTPUT);//设置蜂鸣器的pin为输出模式 length = sizeof(tune)/sizeof(tune[0]);//这里用了一个sizeof函数,可以查出tone序列里有多少个音符 sensors.begin(); Serial.begin(9600); } void loop() { sensors.requestTemperatures(); tempC = sensors.getTempCByIndex(0); delay(1000); Serial.println(tempC); if(tempC>30) { for(int x=0;x<length;x++) { tone(tonePin,tune[x]);//此函数依次播放tune序列里的数组,即每个音符 delay(400*duration[x]);//每个音符持续的时间,即节拍duration,400是调整时间的越大,曲子速度越慢,越小曲子速度越快,自己掌握吧 noTone(tonePin);//停止当前音符,进入下一音符 } delay(5000);//等待5秒后,循环重新开始 } }
Java
UTF-8
10,290
2.140625
2
[ "Apache-2.0" ]
permissive
package com.aliyuncs.policy.retry; import com.aliyuncs.exceptions.ThrottlingException; import com.aliyuncs.policy.cache.ThrottlingPool; import com.aliyuncs.policy.retry.backoff.BackoffStrategy; import com.aliyuncs.policy.retry.backoff.EqualJitterBackoffStrategy; import com.aliyuncs.policy.retry.conditions.ExceptionsCondition; import com.aliyuncs.policy.retry.conditions.HeadersCondition; import com.aliyuncs.policy.retry.conditions.RetryCondition; import com.aliyuncs.policy.retry.conditions.StatusCodeCondition; import java.text.SimpleDateFormat; import java.util.*; public final class RetryPolicy { private final int maxNumberOfRetries; private final int maxDelayTimeMillis; private final BackoffStrategy backoffStrategy; private final Set<RetryCondition> retryConditions; private final Set<RetryCondition> throttlingConditions; private final Boolean enableAliyunThrottlingControl; private RetryPolicy(BuilderImpl builder) { this.maxNumberOfRetries = builder.maxNumberOfRetries; this.maxDelayTimeMillis = builder.maxDelayTimeMillis; this.backoffStrategy = builder.backoffStrategy; this.retryConditions = builder.retryConditions; this.throttlingConditions = builder.throttlingConditions; this.enableAliyunThrottlingControl = builder.enableAliyunThrottlingControl; } /** * Use default retry policy * * @param enableAliyunThrottlingControl use or not use aliyun gateway throttling * @return retryPolicy */ public static RetryPolicy defaultRetryPolicy(Boolean enableAliyunThrottlingControl) { return builder().enableAliyunThrottlingControl(enableAliyunThrottlingControl).build(); } public static RetryPolicy none() { return builder() .maxNumberOfRetries(0) .build(); } public Boolean shouldRetry(RetryPolicyContext context) { if (context.retriesAttempted() > maxNumberOfRetries) { return false; } if (throttlingConditions != null && !throttlingConditions.isEmpty()) { for (RetryCondition throttlingCondition : throttlingConditions) { if (throttlingCondition.meetState(context)) { if (throttlingCondition.escapeTime(context) <= RetryUtil.DEFAULT_ESCAPE_TIME) { return false; } if (enableAliyunThrottlingControl) { long current = System.currentTimeMillis(); int escapeTime = throttlingCondition.escapeTime(context); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); String endTime = df.format(new Date(current + escapeTime)); ThrottlingPool.put(context.coordinate(), endTime, escapeTime); if (context.exception() == null || !ThrottlingException.class.isAssignableFrom(context.exception().getClass())) { context.updateException(new ThrottlingException("SDK.TriggerThrottlingPolicy", "Client triggered throttling policy, server cannot be accessed before " + endTime + (context.exception() != null ? ". Error message: \n" + context.exception().getMessage() : "."), context.exception())); } } } } } if (getBackoffDelay(context) > maxDelayTimeMillis) { return false; } if (retryConditions != null && !retryConditions.isEmpty()) { for (RetryCondition retryCondition : retryConditions) { if (retryCondition.meetState(context)) { return true; } } } return context.retriesAttempted() == RetryUtil.FIRST_ATTEMPTED; } public int getBackoffDelay(RetryPolicyContext context) { if (context.retriesAttempted() == RetryUtil.FIRST_ATTEMPTED) { if (ThrottlingPool.get(context.coordinate()) != null) { long current = System.currentTimeMillis(); int escapeTime = ThrottlingPool.getExpire(context.coordinate()); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"); String endTime = df.format(new Date(current + escapeTime)); if (context.exception() == null || !ThrottlingException.class.isAssignableFrom(context.exception().getClass())) { context.updateException(new ThrottlingException("SDK.TriggerThrottlingPolicy", "Client triggered throttling policy, server cannot be accessed before " + endTime + (context.exception() != null ? ". Error message: \n" + context.exception().getMessage() : "."), context.exception())); } return escapeTime; } else { return RetryUtil.DEFAULT_ESCAPE_TIME; } } int delayTimeMillis = this.backoffStrategy.computeDelayBeforeNextRetry(context); if (throttlingConditions != null && !throttlingConditions.isEmpty()) { for (RetryCondition throttlingCondition : throttlingConditions) { if (throttlingCondition.meetState(context)) { delayTimeMillis = Math.max(delayTimeMillis, throttlingCondition.escapeTime(context)); } } } return delayTimeMillis; } public static Builder builder() { return new BuilderImpl(); } public int maxNumberOfRetries() { return maxNumberOfRetries; } public int maxDelayTimeMillis() { return maxDelayTimeMillis; } public BackoffStrategy backoffStrategy() { return backoffStrategy; } public Set<RetryCondition> retryConditions() { return retryConditions; } public Set<RetryCondition> throttlingConditions() { return throttlingConditions; } public Boolean enableAliyunThrottlingControl() { return enableAliyunThrottlingControl; } public Builder toBuilder() { return builder() .maxNumberOfRetries(maxNumberOfRetries) .maxDelayTimeMillis(maxDelayTimeMillis) .backoffStrategy(backoffStrategy) .retryConditions(retryConditions) .throttlingConditions(throttlingConditions) .enableAliyunThrottlingControl(enableAliyunThrottlingControl); } public interface Builder { Builder maxNumberOfRetries(int numRetries); Builder maxDelayTimeMillis(int delayTime); Builder backoffStrategy(BackoffStrategy backoffStrategy); Builder retryConditions(Set<RetryCondition> retryConditions); Builder throttlingConditions(Set<RetryCondition> throttlingConditions); Builder enableAliyunThrottlingControl(Boolean enableThrottlingControl); RetryPolicy build(); } public static final class BuilderImpl implements Builder { private int maxNumberOfRetries; private int maxDelayTimeMillis; private BackoffStrategy backoffStrategy; private Set<RetryCondition> retryConditions = new HashSet<RetryCondition>(); private Set<RetryCondition> throttlingConditions = new HashSet<RetryCondition>(); private Boolean enableAliyunThrottlingControl = false; private static RetryCondition aliyunThrottlingCondition = HeadersCondition.create(RetryUtil.THROTTLING_PATTERNS); private BuilderImpl() { this.maxNumberOfRetries = RetryUtil.DEFAULT_MAX_RETRIES; this.maxDelayTimeMillis = RetryUtil.MAX_BACKOFF; this.backoffStrategy = new EqualJitterBackoffStrategy(RetryUtil.BASE_DELAY, this.maxDelayTimeMillis, new Random()); this.retryConditions.add(ExceptionsCondition.create(RetryUtil.RETRYABLE_EXCEPTIONS)); this.retryConditions.add(StatusCodeCondition.create(RetryUtil.RETRYABLE_STATUS_CODES)); } @Override public Builder maxNumberOfRetries(int maxNumberOfRetries) { this.maxNumberOfRetries = maxNumberOfRetries; return this; } @Override public Builder maxDelayTimeMillis(int maxDelayTimeMillis) { this.maxDelayTimeMillis = maxDelayTimeMillis; return this; } @Override public Builder backoffStrategy(BackoffStrategy backoffStrategy) { this.backoffStrategy = backoffStrategy; return this; } @Override public Builder retryConditions(Set<RetryCondition> retryConditions) { this.retryConditions = retryConditions; return this; } public Builder retryConditions(RetryCondition... retryCondition) { this.retryConditions = new HashSet<RetryCondition>(Arrays.asList(retryCondition)); return this; } @Override public Builder throttlingConditions(Set<RetryCondition> throttlingConditions) { this.throttlingConditions = throttlingConditions; return this; } public Builder throttlingConditions(RetryCondition... throttlingCondition) { this.throttlingConditions = new HashSet<RetryCondition>(Arrays.asList(throttlingCondition)); return this; } @Override public Builder enableAliyunThrottlingControl(Boolean enableAliyunThrottlingControl) { this.enableAliyunThrottlingControl = enableAliyunThrottlingControl; if (this.enableAliyunThrottlingControl) { if (!this.throttlingConditions.contains(aliyunThrottlingCondition)) { this.throttlingConditions.add(aliyunThrottlingCondition); } } else { if (this.throttlingConditions.contains(aliyunThrottlingCondition)) { this.throttlingConditions.remove(aliyunThrottlingCondition); } } return this; } @Override public RetryPolicy build() { return new RetryPolicy(this); } } }
Java
UTF-8
7,992
1.5625
2
[]
no_license
package com.p280ss.android.ugc.aweme.music.adapter; import android.content.Context; import android.support.p029v7.widget.RecyclerView.C1262a; import android.support.p029v7.widget.RecyclerView.C1293v; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import butterknife.ButterKnife; import butterknife.Unbinder; import butterknife.internal.Utils; import com.bytedance.apm.agent.instrumentation.ClickInstrumentation; import com.bytedance.common.utility.collection.C6307b; import com.bytedance.ies.ugc.appcontext.C6399b; import com.bytedance.router.SmartRouter; import com.p280ss.android.ugc.aweme.app.p305g.C6869c; import com.p280ss.android.ugc.aweme.challenge.model.RelatedChallengeMusic; import com.p280ss.android.ugc.aweme.commercialize.utils.C25242ao; import com.p280ss.android.ugc.aweme.common.C6907h; import com.p280ss.android.ugc.aweme.common.MobClick; import com.p280ss.android.ugc.aweme.discover.model.Challenge; import com.p280ss.android.ugc.aweme.framework.services.ServiceManager; import com.p280ss.android.ugc.aweme.music.model.Music; import com.p280ss.android.ugc.aweme.music.service.IMusicService; import com.zhiliaoapp.musically.df_live_zego_link.R; import java.util.Collection; import java.util.List; /* renamed from: com.ss.android.ugc.aweme.music.adapter.MusicDetailRelatedAdapter */ public class MusicDetailRelatedAdapter extends C1262a<TagViewHolder> { /* renamed from: a */ List<RelatedChallengeMusic> f87978a; /* renamed from: b */ public String f87979b; /* renamed from: c */ public Context f87980c; /* renamed from: d */ public String f87981d; /* renamed from: com.ss.android.ugc.aweme.music.adapter.MusicDetailRelatedAdapter$TagViewHolder */ static class TagViewHolder extends C1293v { LinearLayout llRelated; TextView txtName; TagViewHolder(View view) { super(view); ButterKnife.bind((Object) this, view); } } /* renamed from: com.ss.android.ugc.aweme.music.adapter.MusicDetailRelatedAdapter$TagViewHolder_ViewBinding */ public class TagViewHolder_ViewBinding implements Unbinder { /* renamed from: a */ private TagViewHolder f87985a; public void unbind() { TagViewHolder tagViewHolder = this.f87985a; if (tagViewHolder != null) { this.f87985a = null; tagViewHolder.txtName = null; tagViewHolder.llRelated = null; return; } throw new IllegalStateException("Bindings already cleared."); } public TagViewHolder_ViewBinding(TagViewHolder tagViewHolder, View view) { this.f87985a = tagViewHolder; tagViewHolder.txtName = (TextView) Utils.findRequiredViewAsType(view, R.id.c37, "field 'txtName'", TextView.class); tagViewHolder.llRelated = (LinearLayout) Utils.findRequiredViewAsType(view, R.id.crc, "field 'llRelated'", LinearLayout.class); } } public int getItemCount() { if (C6307b.m19566a((Collection<T>) this.f87978a)) { return 0; } return this.f87978a.size(); } public int getItemViewType(int i) { RelatedChallengeMusic relatedChallengeMusic = (RelatedChallengeMusic) this.f87978a.get(i); if (relatedChallengeMusic != null) { int i2 = relatedChallengeMusic.categoryType; if (i2 == 1) { return 1; } if (i2 == 2) { return 2; } } return super.getItemViewType(i); } public MusicDetailRelatedAdapter(List<RelatedChallengeMusic> list, Context context) { this.f87978a = list; this.f87980c = context; } public /* synthetic */ C1293v onCreateViewHolder(ViewGroup viewGroup, int i) { return m108728a(viewGroup, i); } /* renamed from: a */ private static TagViewHolder m108728a(ViewGroup viewGroup, int i) { View view; LayoutInflater from = LayoutInflater.from(viewGroup.getContext()); if (i == 2) { view = from.inflate(R.layout.i_, viewGroup, false); } else { view = from.inflate(R.layout.afg, viewGroup, false); } return new TagViewHolder(view); } /* access modifiers changed from: private */ /* renamed from: a */ public void onBindViewHolder(TagViewHolder tagViewHolder, int i) { final int itemViewType = getItemViewType(i); final RelatedChallengeMusic relatedChallengeMusic = (RelatedChallengeMusic) this.f87978a.get(i); if (relatedChallengeMusic != null) { if (itemViewType == 2) { Challenge challenge = relatedChallengeMusic.challenge; if (challenge != null) { tagViewHolder.txtName.setText(challenge.getChallengeName()); } } else if (itemViewType == 1) { Music music = relatedChallengeMusic.music; if (music != null) { tagViewHolder.txtName.setText(music.getMusicName()); } } tagViewHolder.llRelated.setOnClickListener(new OnClickListener() { public final void onClick(View view) { ClickInstrumentation.onClick(view); if (itemViewType == 1) { Music music = relatedChallengeMusic.music; if (C6399b.m19944t() && music != null) { if (!((IMusicService) ServiceManager.get().getService(IMusicService.class)).checkValidMusic(music.convertToMusicModel(), MusicDetailRelatedAdapter.this.f87980c, true)) { return; } } if (music != null) { C6907h.onEvent(MobClick.obtain().setEventName("choose_music").setLabelName(MusicDetailRelatedAdapter.this.f87981d).setValue(music.getMid()).setJsonObject(new C6869c().mo16887a("host", MusicDetailRelatedAdapter.this.f87979b).mo16888b())); SmartRouter.buildRoute(view.getContext(), "aweme://music/detail/").withParam("id", music.getMid()).withParam("extra_music_from", "from_related_tag").open(); } return; } if (itemViewType == 2) { Challenge challenge = relatedChallengeMusic.challenge; if (challenge != null) { C25242ao.m82972a(challenge); C6907h.onEvent(MobClick.obtain().setEventName("choose_challenge").setLabelName(MusicDetailRelatedAdapter.this.f87981d).setValue(challenge.getCid()).setJsonObject(new C6869c().mo16887a("host", MusicDetailRelatedAdapter.this.f87979b).mo16888b())); if (C6399b.m19944t()) { SmartRouter.buildRoute(MusicDetailRelatedAdapter.this.f87980c, "//challenge/detail").withParam("aweme_id", "").withParam("id", challenge.getCid()).withParam("extra_challenge_from", "from_related_tag").withParam("com.ss.android.ugc.aweme.intent.extra.EXTRA_CHALLENGE_TYPE", 0).withParam("extra_challenge_is_hashtag", false).open(); return; } SmartRouter.buildRoute(MusicDetailRelatedAdapter.this.f87980c, "//challenge/detail").withParam("aweme_id", "").withParam("id", challenge.getCid()).withParam("extra_challenge_from", "from_related_tag").withParam("com.ss.android.ugc.aweme.intent.extra.EXTRA_CHALLENGE_TYPE", challenge.getSubType()).withParam("extra_challenge_is_hashtag", false).open(); } } } }); } } }
Rust
UTF-8
3,668
2.75
3
[]
no_license
use crate::{ accelerator::Accelerator, bsdf::{builder::Builder as BSDFBuilder, BSDFImpl}, camera::{builder::Builder as CameraBuilder, Cameras}, integrator::Integrator, interaction::SurfaceInteraction, light::Lights, shapes::{Builder as ShapeBuilder, Shapes}, spectrum::from_rgb, transform::Builder as TransformBuilder, }; use quick_maths::{Ray3, Vec3}; use std::collections::HashMap; // TODO add Serde for RawScene #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct RawScene { /// List of lights lights: Vec<Lights>, /// Camera camera: CameraBuilder, /// List of shapes with optional ids shapes: HashMap<String, ShapeBuilder>, /// List of BSDFs with optional ids bsdfs: HashMap<String, BSDFBuilder>, /// Mapping between shapes -> bsdf bsdf_mapping: HashMap<String, String>, } impl RawScene { /// Create an acceleration structure from a raw scene pub fn build<El, Acc: Accelerator>(self) -> Scene<El, Acc> { let RawScene { lights, camera, shapes, bsdfs, bsdf_mapping, } = self; let (id_to_idx, mut bsdfs): (HashMap<_, _>, Vec<_>) = bsdfs .into_iter() .enumerate() .map(|(i, (id, v))| ((id, i), v.into())) .unzip(); let shapes = shapes.into_iter().map(|(shape_id, shape_builder)| { let idx = id_to_idx[&bsdf_mapping[&shape_id]]; Shapes::new(shape_builder.into(), &mut bsdfs[idx]) }); Scene { lights, camera: camera.into(), env_light: None, accelerator: Acc::build(shapes), bsdfs, } } /// Creates an example pub fn example() -> Self { let lights = vec![Lights::Point(crate::light::point::Point::new( Vec3::new(0.0, 1.0, -1.0), 10.0, from_rgb(Vec3::new(0.3, 0.7, 0.9)), ))]; let mut shapes = HashMap::new(); shapes.insert(String::from("central_sphere"), ShapeBuilder { to_world: TransformBuilder::Identity, variant: crate::shapes::builder::Variant::Sphere { center: Vec3::new(0., 0., 10.), radius: 1.0, }, }); let mut bsdfs = HashMap::new(); bsdfs.insert( String::from("debug"), BSDFBuilder::Diffuse(from_rgb(Vec3::new(0.7, 0.8, 0.5))), ); let mut bsdf_mapping = HashMap::new(); bsdf_mapping.insert(String::from("central_sphere"), String::from("debug")); Self { lights, camera: CameraBuilder { film_builder: crate::film::builder::Builder { size: (512, 512) }, to_world: TransformBuilder::LookAt { origin: Vec3::of(0.0), towards: Vec3::new(0., 0., 1.), up: Vec3::new(0., 1., 0.), }, variant: crate::camera::builder::Variant::Perspective { x_fov: 30.0, near_clip: 1.0e-3, far_clip: 1.0e3, aspect: 1.0, }, sampler: None, }, // TODO fill in examples here shapes, bsdfs, bsdf_mapping, } } } #[derive(Debug)] pub struct Scene<EnvLight, Acc> { /// List of lights for this scene pub lights: Vec<Lights>, /// Camera for this scene pub camera: Cameras, /// Environment light pub env_light: Option<EnvLight>, /// List of BSDFs used in this implementation bsdfs: Vec<BSDFImpl>, /// Acceleration data structure accelerator: Acc, } impl<El, Acc> Scene<El, Acc> where Acc: Accelerator, { // TODO build something that creates a scene from iterators of shapes // pub fn new(items: Vec<Lights>, ...) pub fn render<I: Integrator>(&self, int: I) { int.render(self); } pub fn intersect_ray(&self, r: &Ray3) -> Option<(SurfaceInteraction, &Shapes)> { self.accelerator.intersect_ray(r) } }
Python
UTF-8
1,725
2.9375
3
[]
no_license
from review import Review class Recipe: _all = [] def __init__(self, recipe): self._recipe = recipe Recipe._all.append(self) @classmethod def all(cls): return cls._all @classmethod def top_three(cls): recipe_rating_dict = {review._recipe:[] for review in Review._all} for review in Review._all: recipe_rating_dict[review._recipe].append(review._rating) for recipe,list in recipe_rating_dict.items(): list = round(sum(list)/len(list),1) recipe_rating_dict[recipe] = list return sorted(recipe_rating_dict, key = recipe_rating_dict.get, reverse =True)[:3] # def avg_rating(self): # recipe_ratings = [review.rating for review in self.reviews()] # return (sum(recipe_ratings)/len(recipe_ratings)) @classmethod def bottom_three(cls): recipe_rating_dict = {review._recipe:[] for review in Review._all} for review in Review._all: recipe_rating_dict[review._recipe].append(review._rating) for recipe,list in recipe_rating_dict.items(): list = round(sum(list)/len(list),1) recipe_rating_dict[recipe] = list return sorted(recipe_rating_dict, key = recipe_rating_dict.get, reverse = False)[:3] @property def recipe(self): return self._recipe @recipe.setter def recipe(self, recipe): self._recipe = recipe def reviews(self): return [review for review in Review._all if review._recipe == self] def top_five_reviews(self): review_dict = {review: review._rating for review in self.reviews()} return sorted(review_dict, key = review_dict.get, reverse = True)[:5]
PHP
UTF-8
1,579
2.53125
3
[]
no_license
<?php namespace Work\Controller\Admin; use CoreWine\Http\Request; class ProfileController extends AdminController{ /** * ORM\Model * * @var */ public $model = 'Work\Model\Profile'; /** * Url * * @var */ public $url = 'admin/work/profiles'; /** * Url * * @var */ public $url_alias = 'work:admin.profiles'; /** * User data * * @var bool */ public $user_data = true; /** * Set views * * @param $views */ public function views($views){ $views -> all(function($view){ $view -> id('id'); $view -> text('fullname'); $view -> text('address'); $view -> text('vat'); $view -> text('tax_code'); $view -> text('iban'); }); $views -> form(function($view){ $view -> text('fullname'); $view -> text('address'); $view -> text('vat'); $view -> text('tax_code'); $view -> text('iban'); $view -> textarea('notes'); }); $views -> get(function($view){ $view -> id('id'); $view -> text('fullname'); $view -> text('address'); $view -> text('vat'); $view -> text('tax_code'); $view -> text('iban'); $view -> textarea('notes'); }); $views -> search(function($view){ $view -> id('id'); $view -> text('fullname'); $view -> text('address'); $view -> text('vat'); $view -> text('iban'); $view -> text('tax_code'); }); } /** * Index * * @return Response */ public function index(Request $request){ if(!\Auth::user() -> permission -> has(\Auth\Model\User::PEX_CHESS)) return abort(404); return parent::index($request); } } ?>
Java
UTF-8
17,651
1.859375
2
[]
no_license
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.servicelayer.config; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.bootstrap.config.ConfigUtil; import de.hybris.platform.servicelayer.config.impl.SecureConfigurationViewService; import de.hybris.platform.util.config.ConfigIntf; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.runners.MockitoJUnitRunner; import java.util.Collections; import java.util.Map; import java.util.Properties; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @UnitTest @RunWith(MockitoJUnitRunner.class) public class SecureConfigurationViewServiceTest { private static final String HIDDEN_VALUE = "*****"; @Test public void shouldNotDisplayBlacklistedPropertiesInRemoveMode() { // given final Map<String, String> properties = ImmutableMap.<String, String> builder() // .put("db.username", "admin") // .put("db.password", "nimda") // .put("password.encoder", "foo") // .put("password.encoder.keylength", "32") // .put("unaffected", "ok").build(); final Map<String, String> blacklist = ImmutableMap.<String, String> builder() // .put("db", "db.username,db.password") // .put("encoder", "password.encoder,password.encoder.keylength") // .build(); final ConfigurationViewService viewService = new SecureConfigurationViewService(() -> emptyMap(), () -> new Properties(), () -> mockRemoveConfiguration(blacklist, emptyMap(), properties)); // when final Map<String, String> safeProperties = viewService.readConfigParameters(); // then assertThat(safeProperties).containsOnly(entry("unaffected", "ok")); } @Test public void shouldShowAsterisksForBlacklistedPropertiesInHideMode() { // given final Map<String, String> properties = ImmutableMap.<String, String> builder() // .put("db.username", "admin") // .put("db.password", "nimda") // .put("unaffected", "ok").build(); final Map<String, String> blacklist = ImmutableMap.<String, String> builder() // .put("db", "db.username,db.password") // .put("encoder", "password.encoder.pbkdf2.iterations,password.encoder.pbkdf2.keylength") // .build(); final ConfigurationViewService viewService = new SecureConfigurationViewService(() -> emptyMap(), () -> new Properties(), () -> mockHideConfiguration(blacklist, emptyMap(), properties)); // when final Map<String, String> safeProperties = viewService.readConfigParameters(); // then assertThat(safeProperties).containsOnly( // entry("db.username", HIDDEN_VALUE), // entry("db.password", HIDDEN_VALUE), // entry("unaffected", "ok")); } @Test public void shouldNotDisplayBlacklistedByRegexInRemoveMode() { // given final Map<String, String> properties = ImmutableMap.<String, String> builder() // .put("ldap.username", "foo") // .put("ldap.password", "bar") // .put("db.user", "admin") // .put("db.password", "nimda") // .put("unaffected", "ok").build(); final Map<String, String> regexRules = ImmutableMap.<String, String> builder() // .put("configuration.view.regex.rule.test.username", "user") // .put("configuration.view.regex.rule.test.password", "password") // .build(); final ConfigurationViewService viewService = new SecureConfigurationViewService(() -> emptyMap(), () -> new Properties(), () -> mockRemoveConfiguration(emptyMap(), regexRules, properties)); // when final Map<String, String> safeProperties = viewService.readConfigParameters(); // then assertThat(safeProperties).containsOnly(entry("unaffected", "ok")); } @Test public void shouldBlankRegexBeIgnored() { // given final Map<String, String> properties = ImmutableMap.<String, String> builder() // .put("ldap.username", "foo") // .put("ldap.password", "bar") // .put("unaffected", "ok").build(); final Map<String, String> regexRules = ImmutableMap.<String, String> builder() // .put("configuration.view.regex.rule.blank", " ") // .build(); final ConfigurationViewService viewService = new SecureConfigurationViewService(() -> emptyMap(), () -> new Properties(), () -> mockRemoveConfiguration(emptyMap(), regexRules, properties)); // when final Map<String, String> safeProperties = viewService.readConfigParameters(); // then assertThat(safeProperties).containsOnly(entry("ldap.username", "foo"), entry("ldap.password", "bar"), entry("unaffected", "ok")); } @Test public void shouldShowAsterisksForBlacklistedPropertiesByRegexInHideMode() { // given final Map<String, String> properties = ImmutableMap.<String, String> builder() // .put("ldap.username", "foo") // .put("ldap.password", "bar") // .put("db.user", "admin") // .put("db.password", "nimda") // .put("unaffected", "ok").build(); final Map<String, String> regexRules = ImmutableMap.<String, String> builder() // .put("test.username", "user") // .put("test.password", "password") // .build(); final ConfigurationViewService viewService = new SecureConfigurationViewService(() -> emptyMap(), () -> asProperties(properties), () -> mockHideConfiguration(emptyMap(), regexRules, properties)); // when final Map<String, String> safeProperties = viewService.readConfigParameters(); // then assertThat(safeProperties).containsOnly( // entry("ldap.username", HIDDEN_VALUE), // entry("ldap.password", HIDDEN_VALUE), // entry("db.user", HIDDEN_VALUE), // entry("db.password", HIDDEN_VALUE), // entry("unaffected", "ok")); } @Test public void shouldNotDisplayBlacklistedEnvVarsAndSystemPropertiesInRemoveMode() { // given final Map<String, String> settings = ImmutableMap.<String, String> builder() // .put("y_ldap_username", "foo") // .put("y_ldap_password", "bar") // .put("y_db_user", "admin") // .put("y_db_password", "nimda") // .put("y_unaffected", "ok").build(); final Map<String, String> blacklist = ImmutableMap.<String, String> builder() // .put("ldap", "y_ldap_username,y_ldap_password") // .put("db", "y_db_user,y_db_password") // .build(); final ConfigurationViewService viewService = new SecureConfigurationViewService(() -> settings, () -> asProperties(settings), () -> mockRemoveConfiguration(blacklist, emptyMap(), Collections.emptyMap())); // when final Map<String, String> envVariables = viewService.readEnvVariables(); final Properties properties = viewService.readSystemProperties(); // then assertThat(envVariables).containsOnly(entry("y_unaffected", "ok")); assertThat(Maps.fromProperties(properties)).containsOnly(entry("y_unaffected", "ok")); } @Test public void shouldNotDisplayBlacklistedEnvVarsByRegexAndSystemPropertiesInRemoveMode() { // given final Map<String, String> settings = ImmutableMap.<String, String> builder() // .put("db.username", "admin") // .put("db.password", "nimda") // .put("y_db_user", "admin") // .put("y_db_password", "nimda") // .put("y_unaffected", "ok").build(); final Map<String, String> regexRules = ImmutableMap.<String, String> builder() // .put("configuration.view.regex.rule.db", "db\\.") .build(); final ConfigurationViewService viewService = new SecureConfigurationViewService(() -> settings, () -> asProperties(settings), () -> mockRemoveConfiguration(emptyMap(), regexRules, Collections.emptyMap())); // when final Map<String, String> envVariables = viewService.readEnvVariables(); final Properties properties = viewService.readSystemProperties(); // then assertThat(envVariables).containsOnly(entry("y_unaffected", "ok")); assertThat(Maps.fromProperties(properties)).containsOnly(entry("y_unaffected", "ok")); } @Test public void shouldShowAsterisksForBlacklistedEnvVarsByRegexAndSystemPropertiesInHideMode() { // given final Map<String, String> settings = ImmutableMap.<String, String> builder() // .put("db.username", "admin") // .put("db.password", "nimda") // .put("y_db_user", "admin") // .put("y_db_password", "nimda") // .put("y_unaffected", "ok").build(); final Map<String, String> regexRules = ImmutableMap.<String, String> builder() // .put("configuration.view.regex.rule.db", "db\\.") // .build(); final ConfigurationViewService viewService = new SecureConfigurationViewService(() -> settings, () -> asProperties(settings), () -> mockHideConfiguration(emptyMap(), regexRules, Collections.emptyMap())); // when final Map<String, String> envVariables = viewService.readEnvVariables(); final Properties properties = viewService.readSystemProperties(); // then assertThat(envVariables).containsOnly( // entry("db.username", HIDDEN_VALUE), // entry("db.password", HIDDEN_VALUE), // entry("y_db_user", HIDDEN_VALUE), // entry("y_db_password", HIDDEN_VALUE), // entry("y_unaffected", "ok")); assertThat(Maps.fromProperties(properties)).containsOnly( // entry("db.username", HIDDEN_VALUE), // entry("db.password", HIDDEN_VALUE), // entry("y_db_user", HIDDEN_VALUE), // entry("y_db_password", HIDDEN_VALUE), // entry("y_unaffected", "ok")); } @Test public void shouldShowAsterisksForBlacklistedEnvVarsAndSystemPropertiesInHideMode() { // given final Map<String, String> settings = ImmutableMap.<String, String> builder() // .put("y_ldap_username", "foo") // .put("y_ldap_password", "bar") // .put("y_db_user", "admin") // .put("y_db_password", "nimda") // .put("y_unaffected", "ok").build(); final Map<String, String> blacklist = ImmutableMap.<String, String> builder() // .put("ldap", "y_ldap_username,y_ldap_password") // .put("db", "y_db_user,y_db_password") // .build(); final ConfigurationViewService viewService = new SecureConfigurationViewService(() -> settings, () -> asProperties(settings), () -> mockHideConfiguration(blacklist, emptyMap(), Collections.emptyMap())); // when final Map<String, String> safeEnvVariables = viewService.readEnvVariables(); final Properties safeSystemProperties = viewService.readSystemProperties(); // then assertThat(safeEnvVariables).containsOnly( // entry("y_ldap_username", HIDDEN_VALUE), // entry("y_ldap_password", HIDDEN_VALUE), // entry("y_db_user", HIDDEN_VALUE), // entry("y_db_password", HIDDEN_VALUE), // entry("y_unaffected", "ok")); assertThat(Maps.fromProperties(safeSystemProperties)).containsOnly( // entry("y_ldap_username", HIDDEN_VALUE), // entry("y_ldap_password", HIDDEN_VALUE), // entry("y_db_user", HIDDEN_VALUE), // entry("y_db_password", HIDDEN_VALUE), // entry("y_unaffected", "ok")); } @Test public void shouldAdjustPropertiesBlacklistToMatchEnvironmentPropertyFormat() { // given final Map<String, String> settings = ImmutableMap.<String, String> builder() // .put("y_ldap_username", "foo") // .put("y_ldap_password", "bar") // .put("y_db_user", "admin") // .put("y_db_password", "nimda") // .put("y_unaffected", "ok").build(); final Map<String, String> blacklist = ImmutableMap.<String, String> builder() // .put("db", "db.user,db.password") // .put("ldap", "ldap.username,ldap.password") // .build(); final ConfigurationViewService viewService = new SecureConfigurationViewService(() -> settings, () -> asProperties(settings), () -> mockHideConfiguration(blacklist, emptyMap(), Collections.emptyMap())); // when final Map<String, String> safeEnvVariables = viewService.readEnvVariables(); final Properties safeSystemProperties = viewService.readSystemProperties(); // then assertThat(safeEnvVariables).containsOnly( // entry("y_ldap_username", HIDDEN_VALUE), // entry("y_ldap_password", HIDDEN_VALUE), // entry("y_db_user", HIDDEN_VALUE), // entry("y_db_password", HIDDEN_VALUE), // entry("y_unaffected", "ok")); assertThat(Maps.fromProperties(safeSystemProperties)).containsOnly( // entry("y_ldap_username", HIDDEN_VALUE), // entry("y_ldap_password", HIDDEN_VALUE), // entry("y_db_user", HIDDEN_VALUE), // entry("y_db_password", HIDDEN_VALUE), // entry("y_unaffected", "ok")); } @Test public void shouldIgnoreCaseForBlacklistEntries() { // given final Map<String, String> properties = ImmutableMap.<String, String> builder() // .put("db.username", "admin") // .put("db.password", "nimda") // .put("unaffected", "ok").build(); final Map<String, String> blacklist = ImmutableMap.<String, String> builder() // .put("db", "dB.UserName,db.Password") // .build(); final ConfigurationViewService viewService = new SecureConfigurationViewService(() -> emptyMap(), () -> new Properties(), () -> mockRemoveConfiguration(blacklist, emptyMap(), properties)); // when final Map<String, String> safeProperties = viewService.readConfigParameters(); // then assertThat(safeProperties).containsOnly(entry("unaffected", "ok")); } @Test public void shouldNotDisplayPropertiesWithUppercaseWhenBlacklisted() { // given final Map<String, String> properties = ImmutableMap.<String, String> builder() // .put("dB.UserNaMe", "admin") // .put("db.PASSWORD", "nimda") // .put("unaffected", "ok").build(); final Map<String, String> blacklist = ImmutableMap.<String, String> builder() // .put("db", "db.Username,db.Password") // .build(); final ConfigurationViewService viewService = new SecureConfigurationViewService(() -> emptyMap(), () -> new Properties(), () -> mockRemoveConfiguration(blacklist, emptyMap(), properties)); // when final Map<String, String> safeProperties = viewService.readConfigParameters(); // then assertThat(safeProperties).containsOnly(entry("unaffected", "ok")); } @Test public void shouldShowAsterisksForPropertiesWithUppercaseWhenBlacklisted() { // given final Map<String, String> properties = ImmutableMap.<String, String> builder() // .put("dB.UserNaMe", "admin") // .put("db.PASSWORD", "nimda") // .put("unaffected", "ok").build(); final Map<String, String> blacklist = ImmutableMap.<String, String> builder() // .put("db", "db.Username,db.Password") // .build(); final ConfigurationViewService viewService = new SecureConfigurationViewService(() -> emptyMap(), () -> new Properties(), () -> mockHideConfiguration(blacklist, emptyMap(), properties)); // when final Map<String, String> safeProperties = viewService.readConfigParameters(); // then assertThat(safeProperties).containsOnly( // entry("dB.UserNaMe", HIDDEN_VALUE), // entry("db.PASSWORD", HIDDEN_VALUE), // entry("unaffected", "ok")); } @Test public void shouldAllowCaseInsensitiveBlacklistRules() { // given final Map<String, String> properties = ImmutableMap.<String, String> builder() // .put("ldap.Password", "bar") // .put("db.passWord", "nimda") // .put("unaffected", "ok").build(); final Map<String, String> regexRules = ImmutableMap.<String, String> builder() // .put("configuration.view.regex.rule.test.password", "pass") // .build(); final ConfigurationViewService viewService = new SecureConfigurationViewService(() -> emptyMap(), () -> new Properties(), () -> mockRemoveConfiguration(emptyMap(), regexRules, properties)); // when final Map<String, String> safeProperties = viewService.readConfigParameters(); // then assertThat(safeProperties).containsOnly(entry("unaffected", "ok")); } private static Properties asProperties(final Map<String, String> properties) { final Properties props = new Properties(); props.putAll(properties); return props; } private ConfigIntf mockHideConfiguration(final Map<String, String> blacklist, final Map<String, String> regexRules, final Map<String, String> properties) { return mockConfiguration(blacklist, regexRules, properties, "hide"); } private ConfigIntf mockRemoveConfiguration(final Map<String, String> blacklist, final Map<String, String> regexRules, final Map<String, String> properties) { return mockConfiguration(blacklist, regexRules, properties, "remove"); } public static ConfigIntf mockConfiguration(final Map<String, String> blacklist, final Map<String, String> regexRules, final Map<String, String> properties, final String strategy) { final ConfigIntf config = mock(ConfigIntf.class); when(config.getParametersMatching(SecureConfigurationViewService.BLACKLIST_EXACT_MATCH, true)).thenReturn(blacklist); when(config.getParametersMatching(SecureConfigurationViewService.BLACKLIST_REGEX_RULE, true)).thenReturn(regexRules); when(config.getAllParameters()).thenReturn(properties); when(config.getString(SecureConfigurationViewService.CONFIGURATION_VIEW_STRATEGY, SecureConfigurationViewService.REMOVE_STRATEGY)).thenReturn(strategy); when(config.getString(ConfigUtil.ENV_PROPERTIES_PREFIX, "y_")).thenReturn("y_"); return config; } }
Java
UTF-8
963
2.8125
3
[]
no_license
package frc.robot.drive.motorcontrol.pathplanning; public class SplineCourseData { public double x; public double y; public double yaw; public double k; public double s; public static double[] vectorize(SplineCourseData[] course, String variable) { double[] vector = new double[course.length]; variable = variable.toLowerCase(); for (int i = 0; i < course.length; i++) { switch (variable) { case "x": vector[i] = course[i].x; break; case "y": vector[i] = course[i].y; break; case "yaw": vector[i] = course[i].yaw; break; case "k": vector[i] = course[i].k; break; case "s": default: vector[i] = course[i].s; break; } } return vector; } }
Java
UTF-8
1,159
3.21875
3
[]
no_license
package com.ctk0327.B1162; import java.util.Arrays; import java.util.PriorityQueue; import java.util.Scanner; public class Main { static int N, M, K; static int[][] dp; static int[][] input; public static void main(String[] args) { Scanner sc = new Scanner(System.in); N = sc.nextInt(); M = sc.nextInt(); K = sc.nextInt(); dp = new int[N + 1][K + 1]; input = new int[N + 1][N + 1]; PriorityQueue<Node> queue = new PriorityQueue<>(); for (int i = 0; i <= N; i++) { Arrays.fill(input[i], Integer.MAX_VALUE); } for (int i = 0; i < M; i++) { int from = sc.nextInt(); int to = sc.nextInt(); int value = sc.nextInt(); input[from][to] = value; input[to][from] = value; } // DP를 이용하여 다리 건설수에 따라서 을구하여야 겠다고 생각했으나 구현해내지 못함 } } class Node { int from; int to; int dist; public Node(int from, int to, int dist) { this.from = from; this.to = to; this.dist = dist; } }
Ruby
UTF-8
3,524
2.765625
3
[]
no_license
require 'birbl' describe Birbl::Client do let(:response) { stub('Response', body: '{"data": "{\"id\":1}"}') } let(:error_response) { stub('Response', body: '{"error_type": "badrequest"}') } context 'without initialization' do context '.instance' do it 'raises an error' do expect { Birbl::Client.instance }.to raise_error(RuntimeError, /No instance/) end end context '.instance?' do it 'is false' do expect(Birbl::Client.instance?).to be_false end end context '.new' do it 'takes one parameter' do expect { Birbl::Client.new }.to raise_error(ArgumentError, /\(0 for 1\)/) end end end context 'with initialization' do subject { Birbl::Client.new('the_key') } before do subject # create it end context '.instance' do it 'returns the instance' do expect(Birbl::Client.instance).to be(subject) end end context '.instance?' do it 'is true' do expect(Birbl::Client.instance?).to be_true end end context 'attributes' do [ [:use_sandbox, false], [:base_url, 'https://api.birbl.com'], [:dev_url, 'https://dev-api.birbl.com'], [:timeout, 10], ].each do |attribute, value| it "it has accessors for #{attribute}" do setter = "#{attribute}=".intern subject.send(setter, 'foo') expect(subject.send(attribute)).to eq('foo') end example "#{attribute} defaults to #{value}" do expect(subject.send(attribute)).to eq(value) end end end context '.url' do context 'when not sandboxed' do it 'returns production URL' do expect(subject.url).to eq('https://api.birbl.com') end end context 'when sandboxed' do it 'returns staging URL' do subject.use_sandbox = true expect(subject.url).to eq('https://dev-api.birbl.com') end end end context '#get' do before do RestClient.stub(get: response) end it 'proxies to RestClient' do RestClient.should_receive(:get). with('https://api.birbl.com/partners', BIRBL_KEY: 'the_key'). and_return(response) subject.get('partners') end it 'returns the parsed data' do expect(subject.get('partners')).to eq({'id' => 1}) end it 'fails on error responses' do RestClient.stub(get: error_response) expect { subject.get('partners') }.to raise_error(RuntimeError, /badrequest/) end end context '#post' do before do RestClient.stub(:post). with( 'https://api.birbl.com/partners', 'data=[]', BIRBL_KEY: 'the_key' ). and_return(response) end it 'proxies to RestClient' do RestClient.should_receive(:post). with( 'https://api.birbl.com/partners', 'data=[]', BIRBL_KEY: 'the_key' ). and_return(response) subject.post('partners') end it 'parses the response payload' do expect(subject.post('partners')).to be_a(Hash) end it 'returns a HashWithIndifferentAccess' do result = subject.post('partners') expect(result['id']).to eq(1) expect(result[:id]).to eq(1) end end end end
Shell
UTF-8
1,500
3.21875
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/env bash set -e cd $TRAVIS_BUILD_DIR ./tools/travis/scancode.sh make lint make build make test export PATH=$PATH:$TRAVIS_BUILD_DIR; make native_test; export OPENWHISK_HOME="$(dirname "$TRAVIS_BUILD_DIR")/incubator-openwhisk"; HOMEDIR="$(dirname "$TRAVIS_BUILD_DIR")" cd $HOMEDIR # Clone the OpenWhisk code git clone --depth 3 https://github.com/apache/incubator-openwhisk.git # Build script for Travis-CI. WHISKDIR="$HOMEDIR/incubator-openwhisk" cd $WHISKDIR ./tools/travis/setup.sh ANSIBLE_CMD="ansible-playbook -i environments/local -e docker_image_prefix=testing" TERM=dumb ./gradlew distDocker -PdockerImagePrefix=testing cd $WHISKDIR/ansible $ANSIBLE_CMD setup.yml $ANSIBLE_CMD prereq.yml $ANSIBLE_CMD couchdb.yml $ANSIBLE_CMD initdb.yml $ANSIBLE_CMD apigateway.yml cd $TRAVIS_BUILD_DIR TERM=dumb ./gradlew buildBinaries cd $WHISKDIR/ansible $ANSIBLE_CMD wipe.yml $ANSIBLE_CMD openwhisk.yml -e openwhisk_cli_home=$TRAVIS_BUILD_DIR # Copy the binary generated into the OPENWHISK_HOME/bin, so that the test cases will run based on it. mkdir -p $WHISKDIR/bin cp $TRAVIS_BUILD_DIR/bin/wsk $WHISKDIR/bin # Run the test cases under openwhisk to ensure the quality of the binary. cd $TRAVIS_BUILD_DIR ./gradlew :tests:test -Dtest.single=*ApiGwCliTests* sleep 30 ./gradlew :tests:test -Dtest.single=*ApiGwCliRoutemgmtActionTests* sleep 30 ./gradlew :tests:test -Dtest.single=*ApiGwCliEndToEndTests* sleep 30 ./gradlew :tests:test -Dtest.single=*Wsk*Tests* make integration_test
Ruby
UTF-8
1,836
2.640625
3
[]
no_license
# # Authentication helpers can be used anywhere in the site # Usually they'll be at the beginning of a method, or used as a before filter # helpers do # User must be signed in def auth_slicker unless session[:user] session[:flash] = 'You must be signed in to see that page.' redirect '/home' end end # User must have admin privileges def auth_admin(type = 'any') auth_slicker user = User.get(session[:user]) if type == 'any' unless user.admin? || user.salesman? || user.writer? session[:flash] = 'You must be an admin to see that page.' redirect '/home' end elsif type == 'admin' unless user.admin? session[:flash] = 'You must be an admin to see that page.' redirect '/home' end elsif type == 'salesman' unless user.salesman? session[:flash] = 'You must be a salesman to see that page.' redirect '/home' end elsif type == 'writer' unless user.writer? session[:flash] = 'You must be a writer to see that page.' redirect '/home' end end end def admin?(type = 'any') auth_slicker user = User.get(session[:user]) if type == 'any' user.admin? || user.salesman? || user.writer? ? true : false elsif type == 'admin' user.admin? ? true : false elsif type == 'salesman' user.salesman? ? true : false elsif type == 'writer' user.writer? ? true : false end end # Must be a merchant def auth_merchant unless session[:merchant] session[:flash] = 'You must be signed in as a merchant to see that page.' redirect '/home' end end end
Java
UTF-8
1,329
2.21875
2
[]
no_license
package com.dakim.collegeevent.model; import javax.persistence.*; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; @Entity @Table(name = "requests") public class Request { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @NotBlank private String name; @Column(name = "rso_description") private String description; @NotNull @ManyToOne @JoinColumn(name = "admin_username") private User admin; @NotNull @ManyToOne @JoinColumn(name = "university") private University university; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public User getAdmin() { return admin; } public void setAdmin(User admin) { this.admin = admin; } public University getUniversity() { return university; } public void setUniversity(University university) { this.university = university; } }
Markdown
UTF-8
2,616
2.53125
3
[]
no_license
--- copyright: years: 2017 lastupdated: "2018-11-12" --- {:shortdesc: .shortdesc} {:new_window: target="_blank"} {:codeblock: .codeblock} {:pre: .pre} {:screen: .screen} {:tip: .tip} {:download: .download} # Getting Started The Hardware Firewall (Shared) provides customers with an essential layer of security that is provisioned on demand without service interruptions. It prevents unwanted traffic from hitting your servers, reducing your attack surface, and allowing your server resources to be dedicated for their intended use. To order a Hardware Firewall (Shared), first navigate to the order page in the customer portal: 1. From your browser, open the [Customer Portal](https://control.softlayer.com/) and log into your account. 2. In the Customer Portal select **Security > Network Security > Firewalls**. 3. From the **Firewalls** page, select the **Order Multi VLAN Firewall** link in the top right corner. This link opens the Multi VLAN Firewall order page. If your account does not currently have any Multi VLAN Firewalls associated with it, a message displays with a link to the order page. From the Multi VLAN Firewall order page, you can order your FSA 1Gbps firewall: 1. Give the firewall a name. 2. Select the desired Datacenter and Pod from the dropdown menus. Availability is limited to select locations. 3. Choose the desired VLANs Configuration. 4. Choose to have a single firewall or enable failover protection with the High Availability option. 5. Choose from the list of Add-ons or bundle all of them together for a discounted price. The Order Summary box displays the updated information for your current order. 6. Select the **Master Service Agreement** checkbox once you review your order. 7. Submit your order by clicking **Place Order**. The Hardware Firewall (Shared) provides customers with an essential layer of security for your servers that is provisioned on demand without service interruptions. To add a firewall to a server: 1. From your browser, open [Customer Portal ![External link icon](../../icons/launch-glyph.svg "External link icon")](https://control.softlayer.com/){: new_window} and log into your account. 2. In the Customer Portal navigation, go to **Devices > Device List** and click on the server you want protected. 3. In the **Device Details** page, in the **Configuration** tab, scroll to the bottom of the page to the **Addons** section and click on the **Order Hardware Firewall** link. 4. In the **Order Hardware Firewall** dialog, choose from the options presented (if applicable) and press **Continue** to complete the ordering process.
Java
WINDOWS-1258
2,749
4.28125
4
[ "MIT" ]
permissive
/* 3. Sentence Capitalizer Write a method that accepts a String object as an argument and returns a copy of the string with the first character of each sentence capitalized. For instance, if the argument is hello. my name is Joe. what is your name? the method should return the string Hello. My name is Joe. What is your name? Demonstrate the method in a program that asks the user to input a string and then passes it to the method. The modified string should be displayed on the screen. Pseudo Code Algorithm 1.write a method name: Capitalizer agument: string parameters: string process: Convert the parameter to StringBuilder object if length of StringBuilder is >0, then capitalize the first letter Find the periods before the last character Capitalize the 2nd character after the peirods in Return the string */ import java.util.Scanner; public class SentenceCapitalizer { public static void main(String[]args) { String str; Scanner s = new Scanner(System.in); System.out.println("Enter your sentence: "); str = s.nextLine(); StringBuilder sb = new StringBuilder(str); //display System.out.println("Your sentence :" + Capitalizer(str)); //System.out.println("Your sentence :" + Capitalizer(sb)); System.out.println("Your sentence :" + Capitalizer(str)); }//end main method public static String Capitalizer(String s) { String[] str = s.split("\\."); String sentence = ""; sentence += Character.toUpperCase(str[0].charAt(0)); for(int j=1; j<str[0].length(); j++) sentence += str[0].charAt(j); for(int i=1; i<str.length; i++) sentence += Character.toUpperCase(str[i].charAt(1)) + str[i].substring(2)+ ". "; return sentence; } public static String Capitalizer(StringBuilder sb) { for(int i= 0; i<sb.length(); i++) { if(sb.charAt(i)=='.'|| sb.charAt(i)=='?'|| sb.charAt(i)=='!') sb.setCharAt((i+2),Character.toUpperCase(sb.charAt(i+2))); } return sb.toString(); } public static String sentenceCap(String str) { int i; StringBuilder temp = new StringBuilder(str); if(temp.length()>0) temp.setChartAt(0,Character.toUpperCase(temp.charAt(0))); i = tem.indexOf(". "); while(i != -1) { i++; while(i< temp.length() && temp.charAt(i) == ' ') i++; temp.setCharAt(i,Character.toUpperCase(temp.charAt(i))); i= temp.indexOf(". ",i); } return temp.toString(); } }
Markdown
UTF-8
1,813
2.859375
3
[]
no_license
## Mock Server End points: 1. All users: http://localhost:3000/users 2. All habits: http://localhost:3000/habits 3. User habits: http://localhost:3000/users/{userId}/habits 4. Habits trackers: http://localhost:3000/habits/{habitId}/trackers ### How to create a multi-dimensional table: a note to myself - Add `<tr></tr>` for each row you want - Let's say you have four categories horizontally and four categories vertically: - So for the horizontal categories you'll need one row - For the vertical categories you'll need another four - That gives you total five `tr`s. - Now because these categories are headers, use `<th></th>` instead of `<td></td>` because td stands for table data - Group all your headers in `<thead></thead>` ?? <table> <tr> <th></th> <th>col1</th> <th>col2</th> <th>col3</th> <th>col4</th> </tr> <tr> <th>row 1</th> <td>data 1</td> <td>data 2</td> <td>data 3</td> <td>data ?</td> <tr> <tr> <th>row 2</th> <td>data 5</td> <td>data 6</td> <td>data 7</td> </tr> <tr> <th>row 3</th> <td>data 8</td> <td>data 9</td> <td>data 10</td> </tr> </table> ### Next Tasks - <del>When a new habit is added, the page needs a manual refresh </del> - <del>When a task is clicked checked; there should be a entry for trackers</del> - Refactor existing code - Need to add find Tracker method. At the moment having asynchornous issues when trying to separate it out of the updateStatus method - Currently on page refresh, checked status is gone. need to fix that - If tracker created and status false; red checkbox/ cross - Add styling for checked unchecked status - Add tests - Add pipeline - Add backend ### Test cases #### Draft thoughts -
C#
UTF-8
3,922
2.65625
3
[]
no_license
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace CIMS { /// <summary> /// Interaction logic for ForgotPasswordPage.xaml /// </summary> public partial class ForgotPasswordPage : Window { public ForgotPasswordPage() { InitializeComponent(); } /*Logic for window loaded for adding item to combobox*/ private void Window_Loaded(object sender, RoutedEventArgs e) { cmbQuest.Items.Add(""); cmbQuest.Items.Add("In which city were you born?"); cmbQuest.Items.Add("What is the name of your first school?"); cmbQuest.Items.Add("Which is your favorite movie?"); } /*Logic for show password if administrator forgets the password*/ private void BtnShowpwd_Click(object sender, RoutedEventArgs e) { string configManager = ConfigurationManager.ConnectionStrings["databaseConnString"].ConnectionString; using (SqlConnection sqlCon = new SqlConnection(configManager)) { SqlCommand sqcmd = new SqlCommand("SELECT * FROM ADMIN WHERE UserName=@UserName AND SecurityQuestion=@SecurityQuestion AND Response=@Response", sqlCon); StringBuilder sb = new StringBuilder(); int invalid = 0; if (!(Regex.IsMatch(txtUname.Text, "\\w{5,}"))) { invalid = 1; sb.Append(Environment.NewLine + "UserName cannot be blank and size atleast be 5."); } else { sqcmd.Parameters.AddWithValue("@UserName", txtUname.Text); } if (cmbQuest.Text.ToString() == "") { invalid = 1; sb.Append(Environment.NewLine + "Please select Security Question."); } else { sqcmd.Parameters.AddWithValue("@SecurityQuestion", cmbQuest.SelectedValue); } if (txtResponse.Text.ToString() == "") { invalid = 1; sb.Append(Environment.NewLine + "Response can't be empty."); } else { sqcmd.Parameters.AddWithValue("@Response", txtResponse.Text); } if (invalid == 1) { MessageBox.Show(sb.ToString()); } try { sqlCon.Open(); SqlDataReader dr = sqcmd.ExecuteReader(); int login = 0; while (dr.Read()) { login = 1; MessageBox.Show("Your Password is " + dr[2]); } if (login == 0) { MessageBox.Show("Incorrect credentials."); } } catch { } finally { sqlCon.Close(); } } } //Logic for navigating to Login Page private void BtnSwitchToLogin_Click(object sender, RoutedEventArgs e) { LoginPage loginPage = new LoginPage(); loginPage.Show(); this.Close(); } } }
Java
UTF-8
481
2.15625
2
[]
no_license
package com.mx.atrium.androidatriumexample.models; import com.google.gson.annotations.SerializedName; import java.util.List; /** * Created by robmontgomery on 10/7/16. */ public class Institutions { @SerializedName(value="institutions") public List<Institution> Institution; public void setAccounts(List<Institution> Institution) { this.Institution = Institution; } public List<Institution> getAccounts() { return Institution; } }
Java
UTF-8
2,681
1.984375
2
[]
no_license
package co.jp.aoyama.macchinetta.app.maker; import java.io.Serializable; import java.util.Date; public class MakerForm implements Serializable { private static final long serialVersionUID = -6090284908261677467L; private String makerCode; private String makerName; private String makerId; private Date createdAt; private Date updatedAt; private String createdUserId; private String updatedUserId; private boolean delType; private String optionType; private String num; private String updateFlag; private String isNewData; private String version; private Boolean displayIdentify; public String getMakerCode() { return makerCode; } public void setMakerCode(String makerCode) { this.makerCode = makerCode; } public String getMakerName() { return makerName; } public void setMakerName(String makerName) { this.makerName = makerName; } public String getMakerId() { return makerId; } public void setMakerId(String makerId) { this.makerId = makerId; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } public boolean getDelType() { return delType; } public void setDelType(boolean delType) { this.delType = delType; } public String getUpdatedUserId() { return updatedUserId; } public void setUpdatedUserId(String updatedUserId) { this.updatedUserId = updatedUserId; } public String getCreatedUserId() { return createdUserId; } public void setCreatedUserId(String createdUserId) { this.createdUserId = createdUserId; } public String getOptionType() { return optionType; } public void setOptionType(String optionType) { this.optionType = optionType; } public String getNum() { return num; } public void setNum(String num) { this.num = num; } public String getIsNewData() { return isNewData; } public void setIsNewData(String isNewData) { this.isNewData = isNewData; } public String getUpdateFlag() { return updateFlag; } public void setUpdateFlag(String updateFlag) { this.updateFlag = updateFlag; } public Boolean getDisplayIdentify() { return displayIdentify; } public void setDisplayIdentify(Boolean displayIdentify) { this.displayIdentify = displayIdentify; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
Java
UTF-8
4,004
2.078125
2
[]
no_license
package com.Flanaria; import java.util.Date; import java.util.LinkedList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import twitter4j.DirectMessage; import twitter4j.Status; import twitter4j.URLEntity; public class Utils_TwitterElement { public static int getColor(TwitterElement elem) { if(elem.getType().equals(Enum_ElementType.DirectMessage)) { return R.color.TweetFrame_DirectMessage; } //Status if(Retentioner_Users.getInstance().isUserScreenName(elem.getUser().getScreenName())) { return R.color.TweetFrame_MyTweet; } if(StatusUtils.isMentionToMe(elem.getStatus())) { return R.color.TweetFrame_InReplyToMe; } return R.color.TweetFrame_Default; } public static TwitterElement[] getExtraElements(TwitterElement elem) { LinkedList<TwitterElement> list = new LinkedList<TwitterElement>(); switch(elem.getType()) { case Status: { Status status = elem.getStatus(); if(status.isRetweet()) { list.add(new TwitterElement(status.getRetweetedStatus())); } break; } case DirectMessage: { break; } } List<String> urls = getURLEntities(elem); for(String s : urls) { String result = null; if(result == null) result = getMatchedResult("(?=.*twitter.com/.*status/.*)[0-9]*$", s); if(result == null) result = getMatchedResult("(?=.*favstar.fm/.*)[0-9]*$", s); if(result != null) { try { Status status = Retentioner_Users.getInstance().getAPITwitter().showStatus(Long.valueOf(result).longValue()); list.add(new TwitterElement(status)); } catch(Exception e) { Logger.e(e); } } } TwitterElement[] result = list.toArray(new TwitterElement[list.size()]); return result; } private static String getMatchedResult(String regex, String s) { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(s); String result = null; if(matcher.find()) { result = matcher.group(); } return result; } private static List<String> getURLEntities(TwitterElement elem) { LinkedList<String> result = new LinkedList<String>(); URLEntity[] entities = null; switch(elem.getType()) { case Status: { entities = elem.getStatus().getURLEntities(); break; } case DirectMessage: { entities = elem.getDirectMessage().getURLEntities(); break; } } if(entities != null) { for(URLEntity url : entities) result.add(url.getExpandedURL()); } return result; } public static void insert(Adapter_TwitterElement adapter, Status status) { TwitterElement elem = new TwitterElement(status); insert(adapter, elem); } public static void insert(Adapter_TwitterElement adapter, DirectMessage msg) { TwitterElement elem = new TwitterElement(msg); insert(adapter, elem); } public static void insert(Adapter_TwitterElement adapter, TwitterElement elem) { if(FlanariaFilterController.getInstance().isShouldFilter(elem)) { return; } int i; TwitterElement elem1 = null; Date createdAt = elem.getCreatedAt(); Date _createdAt = null; int firstEqualsStatus = -1; for(i = 0; i < adapter.getCount(); i++) { elem1 = adapter.getItem(i); if(elem1 == null) { break; } _createdAt = elem1.getCreatedAt(); int var = _createdAt.compareTo(createdAt); if(var == 0) { if(firstEqualsStatus < 0) { firstEqualsStatus = i; } if(equalsElementsNeighbor(elem1, elem)) { return; } } if(var < 0) { break; } } if(firstEqualsStatus >= 0) { i = firstEqualsStatus; } adapter.insert(elem, i); adapter.notifyDataSetChanged(); CurrentTasks.getInstance().setInsertedNumber(i); } public static boolean equalsElementsNeighbor(TwitterElement elem, TwitterElement elem1) { if(elem == null) { return elem1 == null; } return elem1.getUser().getId() == elem.getUser().getId() && elem1.getText().equals(elem.getText()); } }
TypeScript
UTF-8
1,252
2.640625
3
[]
no_license
import { PrismaClient } from '@prisma/client' import { Schema } from '../schema' export const sleep = (ms = 1000) => new Promise((resolve) => setTimeout(resolve, ms)) export class Seeder { private prisma: PrismaClient constructor(private readonly schema: Schema) { if (process.env.DATABASE_URL) { this.prisma = new PrismaClient({ datasources: { db: { url: process.env.DATABASE_URL } }, }) console.log(`Connected to ${process.env.DATABASE_URL}`) } else { console.warn(`Please provide DATABASE_URL`) } } async createData(model: string, collection: any[], include?) { return Promise.all( collection.map((data) => this.prisma[model] .create({ data, include: include ? include : undefined }) .then((item) => console.debug(`Created ${model}: ${item.name || item.id}`)), ), ) } async removeData(models: string[]) { if (this.schema?.timeout > 0) { console.warn(`🚨 STARTING DATA REMOVAL IN ${this.schema?.timeout} SECONDS!`) await sleep(this.schema?.timeout * 1000) } for (const model of models) { const deleted = await this.prisma[model].deleteMany() console.warn(`Deleted ${deleted.count} ${model}`) } } }
Python
UTF-8
442
3.90625
4
[]
no_license
import random def coinflip(): heads = 0 tails = 0 unknown = 0 userinput = int(input("How times would you like to flip the coin? ")) for i in range(0,userinput): x = random.randrange(0, 3) if x == 0: heads = heads + 1 elif x == 1: tails = tails + 1 elif x == 2: unknown = unknown + 1 print(heads, "heads,", tails, "tails and", unknown, "unknowns") return coinflip()
TypeScript
UTF-8
1,281
2.625
3
[]
no_license
import { Component, OnInit } from '@angular/core'; //Este import regresa 2 subcarpetas atras ../ donde está app //y sirve para importar la clase creada en el archivo hero.ts //El Hero es el que se definió abajo en el export import {Hero} from '../hero'; //Se elimina esta línea xq ahora se inyectará a través de un "service" //import {HEROES} from '../mock-heroes'; import { HeroService } from '../hero.service'; @Component({ selector: 'app-heroes', templateUrl: './heroes.component.html', styleUrls: ['./heroes.component.scss'] }) export class HeroesComponent implements OnInit { //ESTE CÓDIGO MURIÓ +++RIP+++ //selectedHero: Hero; //onSelect(hero: Hero): void { // this.selectedHero = hero; // } //se actualiza esta línea //heroes = HEROES; heroes : Hero[]; //Aquí se inyecta con el constructor y parámetro privado constructor(private heroService: HeroService) { } //Uso el this.heroes de acuerdo al alias definido arriba getHeroes(): void { //Con esta subscripción se devolverá un Hero[] Observable (Emulando servidor de datos) this.heroService.getHeroes().subscribe(heroes => this.heroes = heroes); } //De esta manera se llama la función getHeroes del HeroService ngOnInit() { this.getHeroes(); } }
JavaScript
UTF-8
295
3.1875
3
[]
no_license
const button=document.querySelector(".like-btn") const buttonText=button.querySelector(".like-text") let isLiked=false; button.addEventListener('click',()=>{ isLiked=!isLiked; if(isLiked){ buttonText.innerHTML="取消"; }else{ buttonText.innerHTML="点赞"; } })
Python
UTF-8
2,787
3.578125
4
[ "MIT" ]
permissive
import pandas_flavor as pf import pandas as pd from typing import Union @pf.register_dataframe_method def move( df: pd.DataFrame, source: Union[int, str], target: Union[int, str], position: str = "before", axis: int = 0, ) -> pd.DataFrame: """ Move column or row to a position adjacent to another column or row in dataframe. Must have unique column names or indices. This operation does not reset the index of the dataframe. User must explicitly do so. Does not apply to multilevel dataframes. Functional usage syntax: ```python df = move(df, source=3, target=15, position='after', axis=0) ``` Method chaining syntax: ```python import pandas as pd import janitor df = ( pd.DataFrame(...) .move(source=3, target=15, position='after', axis=0) ) ``` :param df: The pandas Dataframe object. :param source: column or row to move :param target: column or row to move adjacent to :param position: Specifies whether the Series is moved to before or after the adjacent Series. Values can be either `before` or `after`; defaults to `before`. :param axis: Axis along which the function is applied. 0 to move a row, 1 to move a column. :returns: The dataframe with the Series moved. :raises ValueError: if `axis` is not `0` or `1``. :raises ValueError: if `position` is not `before` or `after``. :raises ValueError: if `source` row or column is not in dataframe. :raises ValueError: if `target` row or column is not in dataframe. """ df = df.copy() if axis not in [0, 1]: raise ValueError(f"Invalid axis '{axis}'. Can only be 0 or 1.") if position not in ["before", "after"]: raise ValueError( f"Invalid position '{position}'. Can only be 'before' or 'after'." ) if axis == 0: names = list(df.index) if source not in names: raise ValueError(f"Source row '{source}' not in dataframe.") if target not in names: raise ValueError(f"Target row '{target}' not in dataframe.") names.remove(source) pos = names.index(target) if position == "after": pos += 1 names.insert(pos, source) df = df.loc[names, :] else: names = list(df.columns) if source not in names: raise ValueError(f"Source column '{source}' not in dataframe.") if target not in names: raise ValueError(f"Target column '{target}' not in dataframe.") names.remove(source) pos = names.index(target) if position == "after": pos += 1 names.insert(pos, source) df = df.loc[:, names] return df
C#
UTF-8
13,008
2.8125
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Globalization; using System.Threading.Tasks; namespace App4 { public class Puissance4 { #region Propriétés public Jeu jeu { get; set; } public int?[,] matrice; // [x,y] : x => ligne et y => colonne public Joueur joueur { get; set; } public bool isJoueur1 { get; set; } public bool isJoueurAlphaBeta { get; set; } #endregion #region Constructeur public Puissance4(Jeu jeu, int?[,] matrice, Joueur joueur, bool isJoueur1) { this.jeu = jeu; this.matrice = matrice; this.joueur = joueur; this.isJoueur1 = isJoueur1; } #endregion public Statuts VerifierJeu() { if(CompteurPoints() == 100000) { jeu.Statut = Statuts.Perdu; } else if(CompteurPoints() == -100000) { jeu.Statut = Statuts.Gagne; } else if(EstComplet()) { jeu.Statut = Statuts.Nul; } return jeu.Statut; } /// <summary> /// Permet de vérifier si le jeu est terminé /// </summary> /// <param name="profondeur"></param> /// <param name="score"></param> /// <returns></returns> private bool EstTermine(int profondeur, int score) { if (profondeur == 0 || score == jeu.Score || score == -jeu.Score || EstComplet()) { return true; } return false; } /// <summary> /// Permet de placer dans la matrice un nouveau pion /// </summary> /// <param name="colonne"></param> /// <returns></returns> public Tuple<bool, int?> Placer(int colonne) { int? valeurRetourLigne = null; // On vérfie que la colonne sélectionné existe if (colonne < jeu.Colonne && matrice[0, colonne] == null && colonne >= 0) { /* Dans le puissance4 le [0,0] est en haut à gauche et le [5,6] en bas à droite * * Dans cette boucle on va vérifier pour une colonne une ligne non vide en décrémentant */ for (var ligne = jeu.Ligne - 1; ligne >= 0; ligne--) { if (matrice[ligne, colonne] == null) { matrice[ligne, colonne] = (int)joueur; valeurRetourLigne = ligne; break; } } // Récupération de l'autre joueur joueur = ChangementJoueur(joueur); return new Tuple<bool, int?>(true, valeurRetourLigne); } else { return new Tuple<bool, int?>(false, valeurRetourLigne); } } private int PointsParPosition(int ligne, int colonne, int axeY, int axeX) { var pointJoueur1 = 0; var pointJoueur2 = 0; for (var i = 0; i < jeu.NbrPointsGagnant; i++) { if (ligne >= 0 && ligne < jeu.Ligne && colonne >= 0 && colonne < jeu.Colonne && matrice[ligne, colonne] == 0) { pointJoueur1 = pointJoueur1 + 1; } else if (ligne >= 0 && ligne < jeu.Ligne && colonne >= 0 && colonne < jeu.Colonne && matrice[ligne, colonne] == 1) { pointJoueur2 = pointJoueur2 + 1; } ligne += axeY; colonne += axeX; } // Dans le cas ou le joueur1 ou le joueur 2 à 4 pions placés => Fin de la partie if (pointJoueur1 == jeu.NbrPointsGagnant) { if(isJoueur1) { return jeu.Score; } else { return -jeu.Score; } } else if (pointJoueur2 == jeu.NbrPointsGagnant) { if (isJoueur1) { return -jeu.Score; } else { return jeu.Score; } } else { return isJoueur1 ? pointJoueur1 : pointJoueur2; } //return joueur == Joueur.Joueur1 ? pointJoueur1 : pointJoueur2; } private Tuple<bool, int> VerifierScore(int score) { if (score == jeu.Score) { return new Tuple<bool, int>(true, jeu.Score); } if (score == -jeu.Score) { return new Tuple<bool, int>(true, -jeu.Score); } return new Tuple<bool, int>(false, score); } private int CompteurPoints() { int pointsVertical = 0, pointsHorizontal = 0, pointsDiagonal = 0, pointsDiagonal2 = 0; // On vérifie pour chaque ligne et pour chaque colonne for (var ligne = 0; ligne < jeu.Ligne; ligne++) { for (var colonne = 0; colonne < jeu.Colonne; colonne++) { #region Calcul des points // On compte les points vertical if (ligne < jeu.Ligne - 3) { var point = PointsParPosition(ligne, colonne, 1, 0); var scoreVerifie = VerifierScore(point); if (scoreVerifie.Item1) { return scoreVerifie.Item2; } pointsVertical += point; } // On compte les points horizontal if (colonne < jeu.Colonne - 3) { var point = PointsParPosition(ligne, colonne, 0, 1); var scoreVerifie = VerifierScore(point); if (scoreVerifie.Item1) { return scoreVerifie.Item2; } pointsHorizontal += point; } // On compte les points dans la diagonal if (ligne < jeu.Ligne - 3 && colonne < jeu.Colonne - 3) { var point = PointsParPosition(ligne, colonne, 1, 1); var scoreVerifie = VerifierScore(point); if (scoreVerifie.Item1) { return scoreVerifie.Item2; } pointsDiagonal += point; } // On compte les points dans l'autre diagonal if (ligne > 2 && colonne <= jeu.Colonne - 4) { var point = PointsParPosition(ligne, colonne, -1, +1); var scoreVerifie = VerifierScore(point); if (scoreVerifie.Item1) { return scoreVerifie.Item2; } pointsDiagonal2 += point; } #endregion } } // Retour du nombre de points total return pointsHorizontal + pointsVertical + pointsDiagonal + pointsDiagonal2; } /// <summary> /// Méthode qui retourne si le jeu est complet /// </summary> /// <returns></returns> private bool EstComplet() { for (var colonne = 0; colonne < jeu.Colonne; colonne++) { if (matrice[0, colonne] == null) { return false; } } return true; } /// <summary> /// Méthode qui retourne la colonne choisie par l'IA /// </summary> /// <returns></returns> /// <returns></returns> public async Task<int> DecisionIA(bool isJoueur1, int profondeur, bool isJoueurAlphaBeta) { // Récupération des valeurs en retour de l'IA if (isJoueur1) { this.isJoueur1 = true; } else { this.isJoueur1 = false; } this.isJoueurAlphaBeta = isJoueurAlphaBeta; List<int?> retourIA; retourIA = await Max(this, profondeur); return (int)retourIA[0].Value; } /// <summary> /// Méthode qui change de joueur /// </summary> /// <param name="round"></param> /// <returns></returns> public Joueur ChangementJoueur(Joueur round) { // Changement de joueur si Humain ou machine return round == Joueur.Joueur2 ? Joueur.Joueur1 : Joueur.Joueur2; } /// <summary> /// Méthode qui implémente le Max (minimax) /// </summary> /// <param name="puissance4"></param> /// <param name="profondeur"></param> /// <param name="a">Alpha</param> /// <param name="b">Beta</param> /// <returns></returns> private async Task<List<int?>> Max(Puissance4 puissance4, int profondeur, int? a = null, int? b = null) { var points = puissance4.CompteurPoints(); // Si le jeu est terminée on retour une liste null if (puissance4.EstTermine(profondeur, points)) { return new List<int?>() { null, points }; } var maximumPoints = new List<int?>() { null, -99999 }; for (var colonne = 0; colonne < puissance4.jeu.Colonne; colonne++) { // Création d'une copie du jeu (on doit clôner la matrice sinon il y a une référence) var copiePuissance4 = new Puissance4(puissance4.jeu, (int?[,])puissance4.matrice.Clone(), puissance4.joueur, puissance4.isJoueur1); // On essaye de positionner le pion dans une colonne de la copie du puissance4 if (copiePuissance4.Placer(colonne).Item1) { var prochainCoup = await Min(copiePuissance4, profondeur - 1, a, b); if (maximumPoints[0] == null || prochainCoup[1] > maximumPoints[1]) { maximumPoints[0] = colonne; maximumPoints[1] = prochainCoup[1]; a = prochainCoup[1]; } if(a >= b && isJoueurAlphaBeta) { return maximumPoints; } } } return maximumPoints; } /// <summary> /// Méthode qui implémente le min (minimax) /// </summary> /// <param name="puissance4"></param> /// <param name="profondeur"></param> /// <param name="a">Alpha</param> /// <param name="b">Beta</param> /// <returns></returns> private async Task<List<int?>> Min(Puissance4 puissance4, int profondeur, int? a = null, int? b = null) { var points = puissance4.CompteurPoints(); // Si le jeu est terminée on retour une liste null if (puissance4.EstTermine(profondeur, points)) { return new List<int?>() { null, points }; } var minimumPoints = new List<int?>() { null, 99999 }; for (var colonne = 0; colonne < puissance4.jeu.Colonne; colonne++) { // Création d'une copie du jeu (on doit clôner la matrice sinon il y a une référence) var copiePuissance4 = new Puissance4(puissance4.jeu, (int?[,])puissance4.matrice.Clone(), puissance4.joueur, puissance4.isJoueur1); // On essaye de positionner le pion dans une colonne de la copie du puissance4 if (copiePuissance4.Placer(colonne).Item1) { var prochainCoup = await Max(copiePuissance4, profondeur - 1, a, b); if (minimumPoints[0] == null || prochainCoup[1] < minimumPoints[1]) { minimumPoints[0] = colonne; minimumPoints[1] = prochainCoup[1]; b = prochainCoup[1]; } if(a >= b && isJoueurAlphaBeta) { return minimumPoints; } } } return minimumPoints; } } }
SQL
UTF-8
28,530
2.84375
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.2.11 -- http://www.phpmyadmin.net -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 26-02-2015 a las 09:36:36 -- Versión del servidor: 5.6.21 -- Versión de PHP: 5.6.3 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 */; -- -- Base de datos: `tiendaonline` -- -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `clientes` -- CREATE TABLE IF NOT EXISTS `clientes` ( `id` int(100) NOT NULL, `nombre` varchar(255) DEFAULT NULL, `apellidos` varchar(255) DEFAULT NULL, `email` varchar(255) DEFAULT NULL, `usuario` varchar(255) DEFAULT NULL, `contrasena` varchar(255) DEFAULT NULL, `telefono` int(12) DEFAULT NULL, `movil` int(12) DEFAULT NULL, `fax` varchar(12) DEFAULT NULL, `direccioncalle` varchar(255) DEFAULT NULL, `codigo_postal` varchar(255) DEFAULT NULL, `poblacion` varchar(255) DEFAULT NULL, `pais` varchar(255) DEFAULT NULL, `dninif` varchar(255) DEFAULT NULL ) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `clientes` -- INSERT INTO `clientes` (`id`, `nombre`, `apellidos`, `email`, `usuario`, `contrasena`, `telefono`, `movil`, `fax`, `direccioncalle`, `codigo_postal`, `poblacion`, `pais`, `dninif`) VALUES (1, 'jose vicente', 'carratala sanchez', '', 'jocarsa', 'jocarsa', 345348, 344123, NULL, NULL, NULL, NULL, NULL, NULL), (2, 'juan', 'lopez', 'info@info.com', 'juan', 'lopez', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL), (3, 'israel', 'aguirre', 'info@info.com', '', '', 0, 0, '', '', '', '', '', ''), (5, 'armando', 'lopez', 'neo@las.com', '', '', 0, 0, '', '', '', '', '', ''), (7, 'asd', 'qweqwe', 'qwe@wiqwe.com', 'dasd', 'asdas', 0, 0, '', '', '', '', '', ''), (8, 'jaime', 'garcia', '', 'jaime', 'garcia', 0, 0, '', '', '', '', '', ''), (9, '', '', '', '', '', 0, 0, '', '', '', '', '', ''), (10, 'c', 'd', 'e', 'a', 'b', 0, 0, '', '', '', '', '', ''), (11, 'aaa', 'aaa', 'aaa', 'aaa', 'aaa', 0, 0, '', '', '', '', '', ''), (14, 'hj', 'hjjh', 'hj', 'jocarsa2', 'kjsakj', 0, 0, '', '', '', '', '', ''), (15, 'nuevo', 'nuevo', 'nuevo', 'nuevo', 'nuevo', 0, 0, '', '', '', '', '', ''); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `imagenesproductos` -- CREATE TABLE IF NOT EXISTS `imagenesproductos` ( `id` int(100) NOT NULL, `id_producto` int(100) DEFAULT NULL, `imagen` varchar(255) DEFAULT NULL, `titulo` varchar(255) DEFAULT NULL, `descripcion` varchar(255) DEFAULT NULL ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `imagenesproductos` -- INSERT INTO `imagenesproductos` (`id`, `id_producto`, `imagen`, `titulo`, `descripcion`) VALUES (1, 1, 'lampara1a.png', 'titulo 1', 'descripcion 1'), (2, 1, 'lampara1b.png', 'titulo de la segunda imagen', 'descripcion'), (3, 2, 'lampara2a.png', 'titulo 2', 'descripcion de lampara 2'), (4, 2, 'lampara2b.png', 'titulo', 'descripcion'), (5, 3, 'lampara3a.png', 'titulo 3', 'descripcion de lamapara '), (6, 3, 'lampara3b.png', 'titulo ', 'descripcion'), (7, 7, '', '', ''), (8, 8, 'infantil2.jpg', '', ''), (9, 9, 'infantil2.jpg', '', ''); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `lineaspedido` -- CREATE TABLE IF NOT EXISTS `lineaspedido` ( `id` int(100) NOT NULL, `id_pedido` int(100) DEFAULT NULL, `id_producto` int(100) DEFAULT NULL, `unidades` int(100) DEFAULT NULL ) ENGINE=InnoDB AUTO_INCREMENT=115 DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `lineaspedido` -- INSERT INTO `lineaspedido` (`id`, `id_pedido`, `id_producto`, `unidades`) VALUES (3, 7, 1, 1), (4, 7, 2, 1), (5, 7, 3, 1), (6, 8, 1, 1), (7, 8, 2, 1), (8, 8, 3, 1), (9, 9, 1, 1), (10, 9, 2, 1), (11, 9, 3, 1), (12, 10, 1, 1), (13, 10, 2, 1), (14, 10, 3, 1), (15, 11, 1, 1), (16, 11, 2, 1), (17, 11, 3, 1), (18, 12, 1, 1), (19, 12, 2, 1), (20, 12, 3, 1), (21, 12, 1, 1), (22, 13, 1, 1), (23, 13, 2, 1), (24, 13, 3, 1), (25, 13, 1, 1), (26, 14, 1, 1), (27, 14, 2, 1), (28, 14, 3, 1), (29, 14, 1, 1), (30, 15, 1, 1), (31, 15, 1, 1), (32, 16, 1, 1), (33, 16, 1, 1), (34, 17, 1, 1), (35, 17, 2, 1), (36, 18, 1, 1), (37, 18, 2, 1), (38, 19, 1, 1), (39, 19, 2, 1), (40, 20, 3, 1), (41, 20, 3, 1), (42, 20, 3, 1), (43, 21, 3, 1), (44, 21, 3, 1), (45, 21, 3, 1), (46, 22, 3, 1), (47, 22, 3, 1), (48, 22, 3, 1), (49, 23, 3, 1), (50, 23, 3, 1), (51, 23, 3, 1), (52, 24, 1, 1), (53, 25, 1, 1), (54, 25, 2, 1), (55, 25, 3, 1), (56, 26, 2, 1), (57, 26, 2, 1), (58, 27, 3, 1), (59, 27, 3, 1), (60, 27, 3, 1), (61, 27, 3, 1), (62, 27, 3, 1), (63, 27, 3, 1), (64, 27, 3, 1), (65, 27, 3, 1), (66, 27, 3, 1), (67, 27, 3, 1), (68, 28, 1, 1), (69, 28, 2, 1), (70, 28, 3, 1), (71, 28, 3, 1), (72, 28, 3, 1), (73, 28, 3, 1), (74, 29, 2, 1), (75, 29, 1, 1), (76, 29, 1, 1), (77, 29, 2, 1), (78, 29, 3, 1), (79, 30, 1, 1), (80, 30, 1, 1), (81, 30, 1, 1), (82, 30, 1, 1), (83, 30, 1, 1), (84, 30, 1, 1), (85, 30, 2, 1), (86, 30, 2, 1), (87, 30, 2, 1), (88, 30, 3, 1), (89, 31, 1, 1), (90, 31, 1, 1), (91, 31, 1, 1), (92, 31, 1, 1), (93, 31, 1, 1), (94, 32, 2, 1), (95, 32, 1, 1), (96, 32, 3, 1), (97, 32, 2, 1), (98, 32, 1, 1), (99, 33, 1, 1), (100, 33, 2, 1), (101, 33, 3, 1), (102, 33, 2, 1), (103, 33, 1, 1), (104, 34, 1, 1), (105, 34, 2, 1), (106, 34, 3, 1), (107, 34, 2, 1), (108, 34, 1, 1), (109, 35, 2, 0), (110, 36, 2, 0), (111, 36, 3, 0), (112, 37, 2, 3), (113, 37, 3, 1), (114, 38, 2, 3); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `pedidos` -- CREATE TABLE IF NOT EXISTS `pedidos` ( `id` int(100) NOT NULL, `id_cliente` int(100) DEFAULT NULL, `fecha` varchar(255) DEFAULT NULL, `estado` varchar(255) DEFAULT NULL ) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `pedidos` -- INSERT INTO `pedidos` (`id`, `id_cliente`, `fecha`, `estado`) VALUES (2, 1, '1424406495', '0'), (3, 1, '1424406592', '2'), (4, 2, '1424406689', '2'), (5, 2, '1424407206', '0'), (6, 2, '1424407452', '1'), (7, 1, '1424408453', '1'), (8, 2, '1424413132', '1'), (9, 1, '1424413275', '2'), (10, 1, '1424413357', '0'), (11, 1, '1424413424', '0'), (12, 1, '1424413458', '1'), (13, 1, '1424413483', '0'), (14, 2, '1424413627', '1'), (15, 1, '1424413702', '0'), (16, 1, '1424413719', '0'), (17, 2, '1424413866', '2'), (18, 2, '1424414173', '1'), (19, 2, '1424414393', '0'), (20, 2, '1424414597', '1'), (21, 1, '1424414649', '0'), (22, 1, '1424414821', '0'), (23, 1, '1424415033', '1'), (24, 1, '1424415604', '0'), (25, 1, '1424415646', '1'), (26, 1, '1424424080', '0'), (27, 2, '1424424174', '0'), (28, 3, '1424424238', '0'), (29, 2, '1424510606', '0'), (30, 8, '1424925854', '1'), (31, 11, '1424930438', '0'), (32, 12, '1424931031', '0'), (33, 13, '1424931150', '0'), (34, 14, '1424931438', '0'), (35, 1, '1424933004', '0'), (36, 1, '1424933148', '0'), (37, 1, '1424933360', '0'), (38, 15, '1424933448', '0'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `productos` -- CREATE TABLE IF NOT EXISTS `productos` ( `id` int(100) NOT NULL, `nombre` varchar(255) DEFAULT NULL, `descripcion` varchar(255) DEFAULT NULL, `precio` decimal(30,2) DEFAULT NULL, `peso` int(255) DEFAULT NULL, `longitud` int(255) DEFAULT NULL, `anchura` int(255) DEFAULT NULL, `altura` int(255) DEFAULT NULL, `existencias` int(255) DEFAULT NULL, `activado` tinyint(1) DEFAULT NULL ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `productos` -- INSERT INTO `productos` (`id`, `nombre`, `descripcion`, `precio`, `peso`, `longitud`, `anchura`, `altura`, `existencias`, `activado`) VALUES (1, 'lampara icosaedro', 'descripcion de lampara icosaedro', '20.00', 1, 20, 20, 20, 14, 1), (2, 'lampara cubo', 'esta es la descripcion de lampara cubo', '25.00', 1, 25, 25, 25, 15, 1), (3, 'lampara estrella', 'descripcion de lampara estrella', '25.00', 1, 20, 20, 20, 6, 1), (9, 'Lampara Infantil', '', '20.00', 1, 11, 11, 11, 20, 1); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `registros` -- CREATE TABLE IF NOT EXISTS `registros` ( `utc` int(100) NOT NULL, `anio` int(4) NOT NULL, `mes` int(2) NOT NULL, `dias` int(2) NOT NULL, `hora` int(2) NOT NULL, `minuto` int(2) NOT NULL, `segundo` int(2) NOT NULL, `ip` varchar(255) NOT NULL, `navegador` varchar(255) NOT NULL, `pagina` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `registros` -- INSERT INTO `registros` (`utc`, `anio`, `mes`, `dias`, `hora`, `minuto`, `segundo`, `ip`, `navegador`, `pagina`) VALUES (1424840960, 2015, 2, 25, 6, 9, 20, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/'), (1424925832, 2015, 2, 26, 5, 43, 52, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/'), (1424925847, 2015, 2, 26, 5, 44, 7, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424925860, 2015, 2, 26, 5, 44, 20, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424926123, 2015, 2, 26, 5, 48, 43, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424926202, 2015, 2, 26, 5, 50, 2, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424926218, 2015, 2, 26, 5, 50, 18, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424926233, 2015, 2, 26, 5, 50, 33, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424926236, 2015, 2, 26, 5, 50, 36, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424926399, 2015, 2, 26, 5, 53, 19, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424926446, 2015, 2, 26, 5, 54, 6, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424926451, 2015, 2, 26, 5, 54, 11, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424926461, 2015, 2, 26, 5, 54, 21, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424926530, 2015, 2, 26, 5, 55, 30, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424926535, 2015, 2, 26, 5, 55, 35, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424926695, 2015, 2, 26, 5, 58, 15, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424926700, 2015, 2, 26, 5, 58, 20, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424926872, 2015, 2, 26, 6, 1, 12, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424926877, 2015, 2, 26, 6, 1, 17, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424926891, 2015, 2, 26, 6, 1, 31, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424930420, 2015, 2, 26, 7, 0, 20, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424930443, 2015, 2, 26, 7, 0, 43, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424930947, 2015, 2, 26, 7, 9, 7, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424930970, 2015, 2, 26, 7, 9, 30, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424930986, 2015, 2, 26, 7, 9, 46, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424931021, 2015, 2, 26, 7, 10, 21, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424931022, 2015, 2, 26, 7, 10, 22, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424931036, 2015, 2, 26, 7, 10, 36, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424931127, 2015, 2, 26, 7, 12, 7, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/producto.php?id=1'), (1424931129, 2015, 2, 26, 7, 12, 9, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424931138, 2015, 2, 26, 7, 12, 18, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424931155, 2015, 2, 26, 7, 12, 35, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424931313, 2015, 2, 26, 7, 15, 13, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424931320, 2015, 2, 26, 7, 15, 20, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424931329, 2015, 2, 26, 7, 15, 29, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424931407, 2015, 2, 26, 7, 16, 47, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424931425, 2015, 2, 26, 7, 17, 5, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424931443, 2015, 2, 26, 7, 17, 23, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424931607, 2015, 2, 26, 7, 20, 7, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424931665, 2015, 2, 26, 7, 21, 5, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424931777, 2015, 2, 26, 7, 22, 57, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424931832, 2015, 2, 26, 7, 23, 52, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424931949, 2015, 2, 26, 7, 25, 49, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932208, 2015, 2, 26, 7, 30, 8, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932209, 2015, 2, 26, 7, 30, 9, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932310, 2015, 2, 26, 7, 31, 50, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932321, 2015, 2, 26, 7, 32, 1, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932333, 2015, 2, 26, 7, 32, 13, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932352, 2015, 2, 26, 7, 32, 32, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932371, 2015, 2, 26, 7, 32, 51, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932373, 2015, 2, 26, 7, 32, 53, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932373, 2015, 2, 26, 7, 32, 53, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932374, 2015, 2, 26, 7, 32, 54, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932374, 2015, 2, 26, 7, 32, 54, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932375, 2015, 2, 26, 7, 32, 55, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932422, 2015, 2, 26, 7, 33, 42, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/producto.php?id=2'), (1424932424, 2015, 2, 26, 7, 33, 44, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932429, 2015, 2, 26, 7, 33, 49, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932548, 2015, 2, 26, 7, 35, 48, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932552, 2015, 2, 26, 7, 35, 52, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932598, 2015, 2, 26, 7, 36, 38, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932646, 2015, 2, 26, 7, 37, 26, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932655, 2015, 2, 26, 7, 37, 35, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932659, 2015, 2, 26, 7, 37, 39, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932706, 2015, 2, 26, 7, 38, 26, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/producto.php?id=2'), (1424932708, 2015, 2, 26, 7, 38, 28, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932796, 2015, 2, 26, 7, 39, 56, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932823, 2015, 2, 26, 7, 40, 23, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932824, 2015, 2, 26, 7, 40, 24, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932825, 2015, 2, 26, 7, 40, 25, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932825, 2015, 2, 26, 7, 40, 25, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932825, 2015, 2, 26, 7, 40, 25, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932984, 2015, 2, 26, 7, 43, 4, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932986, 2015, 2, 26, 7, 43, 6, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424932992, 2015, 2, 26, 7, 43, 12, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424933009, 2015, 2, 26, 7, 43, 29, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933123, 2015, 2, 26, 7, 45, 23, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933141, 2015, 2, 26, 7, 45, 41, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424933153, 2015, 2, 26, 7, 45, 53, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933253, 2015, 2, 26, 7, 47, 33, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933253, 2015, 2, 26, 7, 47, 33, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933254, 2015, 2, 26, 7, 47, 34, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933254, 2015, 2, 26, 7, 47, 34, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933254, 2015, 2, 26, 7, 47, 34, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933254, 2015, 2, 26, 7, 47, 34, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933275, 2015, 2, 26, 7, 47, 55, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933281, 2015, 2, 26, 7, 48, 1, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933316, 2015, 2, 26, 7, 48, 36, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933330, 2015, 2, 26, 7, 48, 50, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933344, 2015, 2, 26, 7, 49, 4, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933353, 2015, 2, 26, 7, 49, 13, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424933365, 2015, 2, 26, 7, 49, 25, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933435, 2015, 2, 26, 7, 50, 35, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/confirmar.php'), (1424933454, 2015, 2, 26, 7, 50, 54, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424933838, 2015, 2, 26, 7, 57, 18, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424934952, 2015, 2, 26, 8, 15, 52, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424935254, 2015, 2, 26, 8, 20, 54, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424935739, 2015, 2, 26, 8, 28, 59, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424935766, 2015, 2, 26, 8, 29, 26, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424935846, 2015, 2, 26, 8, 30, 46, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424935857, 2015, 2, 26, 8, 30, 57, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/producto.php?id=9'), (1424935867, 2015, 2, 26, 8, 31, 7, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424936610, 2015, 2, 26, 8, 43, 30, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424936672, 2015, 2, 26, 8, 44, 32, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'), (1424938799, 2015, 2, 26, 9, 19, 59, '127.0.0.1', 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36', '/x/index.php'); -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `clientes` -- ALTER TABLE `clientes` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `imagenesproductos` -- ALTER TABLE `imagenesproductos` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `lineaspedido` -- ALTER TABLE `lineaspedido` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `pedidos` -- ALTER TABLE `pedidos` ADD PRIMARY KEY (`id`); -- -- Indices de la tabla `productos` -- ALTER TABLE `productos` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `clientes` -- ALTER TABLE `clientes` MODIFY `id` int(100) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=16; -- -- AUTO_INCREMENT de la tabla `imagenesproductos` -- ALTER TABLE `imagenesproductos` MODIFY `id` int(100) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=10; -- -- AUTO_INCREMENT de la tabla `lineaspedido` -- ALTER TABLE `lineaspedido` MODIFY `id` int(100) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=115; -- -- AUTO_INCREMENT de la tabla `pedidos` -- ALTER TABLE `pedidos` MODIFY `id` int(100) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=39; -- -- AUTO_INCREMENT de la tabla `productos` -- ALTER TABLE `productos` MODIFY `id` int(100) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=10; /*!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,318
2.296875
2
[]
no_license
package dental_clinic; import dental_clinic.console_ui.ProgramMenu.ProgramMenu; import web_ui.config.SpringWebConfiguration; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration; import org.springframework.context.ConfigurableApplicationContext; @SpringBootApplication(exclude = HibernateJpaAutoConfiguration.class) public class WebDentalClinicApplication { public static void main(String[] args) { ConfigurableApplicationContext context = SpringApplication.run(SpringWebConfiguration.class); ProgramMenu programMenu = context.getBean(ProgramMenu.class); while (true) { programMenu.print(); int menuNumber = programMenu.inputValidInteger(); programMenu.executeMenuUIAction(menuNumber); } } } /*@SpringBootApplication - данная аннотация необходима для автоконфигурации библиотек Spring входящих в Spring Boot. ConfigurableApplicationContext context = SpringApplication.run(SpringWebConfiguration.class); Так можно запустить Spring Ioc контекст используя библиотеку Spring Boot.*/
Java
UTF-8
2,979
2.953125
3
[]
no_license
package project; import java.io.*; import java.math.RoundingMode; import java.net.*; import java.text.DecimalFormat; import java.util.concurrent.TimeUnit; import org.json.JSONException; import org.json.JSONObject; /** * This class defines the player object that is used in LiveGameData class. * NOTE: This class will only work for the duration of the 2017 season. It * will need updating for the next season. * * @author Richard Smith * */ public class Player { private String name; private int id; private int team; private double winRate; private double kda; private String apiKey; private String region; public Player(JSONObject playerJSON, String reg) throws JSONException, IOException, InterruptedException { apiKey = "be208bdf-d6d8-411c-96ac-8a205253d220"; this.region = reg; this.id = playerJSON.getInt("summonerId"); this.name = playerJSON.getString("summonerName"); this.team = playerJSON.getInt("teamId"); this.winRate = -1.0; this.kda = -1.0; findWR(); } public void findWR() throws IOException, JSONException, InterruptedException { URL url = new URL("https://" + region + ".api.riotgames.com/api/lol/" + region + "/v1.3/stats/by-summoner/" + id + "/ranked?season=SEASON2017&api_key=" + apiKey); boolean tooManyRequests = true; BufferedReader in = null; // Reader for the data while (tooManyRequests == true){ try { in = new BufferedReader(new InputStreamReader(url.openStream())); tooManyRequests = false; } catch (IOException e) { TimeUnit.SECONDS.sleep(3); } } String dataAsString = in.readLine(); JSONObject dataAsJSON = new JSONObject(dataAsString); int length = dataAsJSON.getJSONArray("champions").length(); JSONObject totalData = null; for (int killme = 0; killme < dataAsJSON.getJSONArray("champions").length(); killme++){ if (dataAsJSON.getJSONArray("champions").getJSONObject(killme).getInt("id") == 0){ totalData = dataAsJSON.getJSONArray("champions").getJSONObject(killme); } } if (totalData.getInt("id") != 0) { System.out.println("Error getting average data"); } //For rounding doubles to nearest hundredth DecimalFormat df = new DecimalFormat("#.##"); df.setRoundingMode(RoundingMode.CEILING); this.kda = ((double) (totalData.getJSONObject("stats").getInt("totalChampionKills") + totalData.getJSONObject("stats").getInt("totalAssists"))) / ((double) totalData.getJSONObject("stats").getInt("totalDeathsPerSession")); this.winRate = ((double) totalData.getJSONObject("stats").getInt("totalSessionsWon")) / ((double) totalData.getJSONObject("stats").getInt("totalSessionsPlayed")); this.kda = Double.parseDouble(df.format(this.kda)); this.winRate = Double.parseDouble(df.format(this.winRate)); } public String toString(){ String playerString = "<html><b>" + name + "</b><br>Win Ratio: " + winRate + "<br>KDA: " + kda + "</html>"; return playerString; } public int getTeam(){ return this.team; } }
C
UTF-8
1,485
3.859375
4
[]
no_license
// // main.c // Frazione ridotta ai minimi termini // // Created by Simone Cavicchioli on 22/11/15. // Copyright © 2015 Simone Cavicchioli. All rights reserved. // // Riempire la prima colonna di una tabella di 10 righe con interi pseudo-casuali compresi tra 10 e 100 e la seconda colonna della tabella con interi pseudo-casuali tali che l’intero sulla i-esima riga e seconda colonna della matrice è compreso tra l’intero sulla i-esima riga e prima colonna della matrice e 100. Successivamente interpretando la coppia di interi presenti su ciascuna riga della matrice come il numeratore ed il denominatore di una frazione visualizzare la frazione ridotta ai minimi termini. Per svolgere questo compito si definisca ed utilizzi una funzione C che produce il massimo comune divisore di due dati interi. #include <stdio.h> #define DIM_R 10 int MCD(int x, int y) { // MCD (12, 15) --> 3 int i, min, mcd = 1; if (x < y) min = x; else min = y; for (i = 1; i <= min; i++) { if (x % i == 0 && y % i == 0) mcd = i; } return mcd; } int main(void) { int a, b, r, x, tab[DIM_R][2]; for (r = 0; r < DIM_R; r++) { tab[r][0] = rand() % 91 + 10; tab[r][1] = rand() % (100 - tab[r][0] + 1) + tab[r][0]; } for (r = 0; r < DIM_R; r++) { x = MCD(tab[r][0], tab[r][1]); a = tab[r][0] / x; b = tab[r][1] / x; printf("%d\t %d\t (%d/%d)\t\n", tab[r][0], tab[r][1], a, b); } return 0; }
TypeScript
UTF-8
1,979
3.125
3
[ "Apache-2.0" ]
permissive
/** * Declares new "kinds" within TypeDoc. * * A "kind" is a way for TypeDoc to understand how to document something. Mostly, these have a 1:1 relationship with some sort of TypeScript concept. This is unsuitable for our purposes, since there's no notion of a "command" or "execute method" in TypeScript. To that end, we must create new ones. * * Note that _creating new `ReflectionKind`s is a hack_ and is not supported by TypeDoc. This is the reason you will see `as any` wherever a {@linkcode AppiumPluginReflectionKind} is used. * * @module */ /** * Adapted from `@knodes/typedoc-pluginutils` * @see https://github.com/knodescommunity/typedoc-plugins * Copyright (c) 2022 KnodesCommunity * Licensed MIT * @see https://github.com/KnodesCommunity/typedoc-plugins/blob/05717565fae14357b1c4be8122f3156e1d46d332/LICENSE * @module */ import {ReflectionKind} from 'typedoc'; const getHigherBitMask = () => Math.max( ...Object.values({...ReflectionKind, All: -1}) .filter((value) => typeof value === 'number') .map((v) => v.toString(2)) .filter((v) => v.match(/^0*10*$/)) .map((v) => parseInt(v, 2)) ); function addReflectionKind(name: string, value?: number | null) { const kindAny = ReflectionKind as any; const existingValue = kindAny[name]; if (existingValue !== null && existingValue !== undefined) { return existingValue; } const defaultedValue = value ?? getHigherBitMask() * 2; kindAny[name] = defaultedValue; kindAny[defaultedValue] = name; return defaultedValue; } /** * Extends the TypeDoc's `ReflectionKind` to add namespaced kinds */ export enum AppiumPluginReflectionKind { Driver = addReflectionKind('Driver'), Plugin = addReflectionKind('Plugin'), Command = addReflectionKind('Command'), ExecuteMethod = addReflectionKind('ExecuteMethod'), Extension = addReflectionKind('Extension', Driver | Plugin), Any = addReflectionKind('Any', Command | ExecuteMethod | Driver | Plugin), }
Java
UTF-8
1,407
2.0625
2
[]
no_license
package serviscepde.com.tr.Dialogs; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.EditText; import android.widget.TextView; import androidx.annotation.NonNull; import serviscepde.com.tr.R; public class DialogFiltreAd extends Dialog implements View.OnClickListener { public Activity c; public Dialog d; public TextView txtFiltreKayıtAdIptal , txtFiltreKayıtAdTamam; public EditText edtFiltreAd; public ViewGroup viewGroup; public DialogFiltreAd(@NonNull Activity a) { super(a); this.c = a; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.dialog_filtre_ad); txtFiltreKayıtAdIptal = findViewById(R.id.txtFiltreKayıtAdIptal); txtFiltreKayıtAdTamam = findViewById(R.id.txtFiltreKayıtAdTamam); edtFiltreAd = findViewById(R.id.edtFiltreAd); viewGroup = c.findViewById(R.id.content); Window window = this.getWindow(); window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); } @Override public void onClick(View v) { } }
PHP
UTF-8
2,484
2.640625
3
[]
no_license
<?php namespace red\addressbook\controls { use \red\EventArgument; use \red\web\ui\controls\Repeater; use \red\web\ui\controls\TemplateControl; use red\web\ui\controls\Button; use \red\web\ui\IThemable; /** * TemplateControl */ class AddressbookControl extends TemplateControl implements IThemable { /** * @var PeopleDatasource */ protected $datasource = null; /** * @var Repeater */ protected $cardList = null; /** * @var CardDetailView */ protected $cardDetail = null; /** * @var Button */ protected $btnEdit = null; /** * @var Button */ protected $btnDone = null; /** * @var Button */ protected $btnShare = null; /** * gets called when the control is finished loading from the template */ protected function templateLoaded() { parent::templateLoaded(); $this->cardList->registerEventListener( Repeater::EV_SELECTEDINDEX_CHANGED , 'onCardList_SelectedIndexChangerd', $this); $this->btnEdit->registerEventListener( Button::EV_CLICKED , 'onBtnEdit_Clicked', $this); $this->btnDone->registerEventListener( Button::EV_CLICKED , 'onBtnDone_Clicked', $this); } private function onCardList_SelectedIndexChangerd(Repeater $sender, EventArgument $argument) { $card = $this->datasource->objectValueForRepeaterAtRowIndex($sender, $sender->getSelectedIndex()); $this->cardDetail->bind($card); } private function onBtnEdit_Clicked(Button $sender, EventArgument $argument) { $this->cardDetail->setEditable(true); } private function onBtnDone_Clicked(Button $sender, EventArgument $argument) { $this->cardDetail->setEditable(false); } public function preRender() { if (!$this->cardDetail->isBound() && $this->cardList->getSelectedIndex() !== null) { $card = $this->datasource->objectValueForRepeaterAtRowIndex( $this->cardList, $this->cardList->getSelectedIndex()); $this->cardDetail->bind($card); } $editable = $this->cardDetail->isEditable(); $this->btnEdit->setVisible(!$editable); $this->btnDone->setVisible($editable); parent::preRender(); } /** * get an array of resource types to try and register. * * array should hold filename extensions to register as values * * example: * return array('css', 'js'); * * * * @return array */ static public function getThemeResourceTypes() { return array('css'); } } }
Java
UTF-8
345
2.375
2
[]
no_license
package propias.dominio.clases; /** Un usuari convidat. Es un tipus especial d'usuari. Aquest usuari té com a nom * convidat i no té contrasenya. * * @author Petru Rares Sincraian * */ public class UsuariConvidat extends UsuariGeneral { /** La constructora per defecte * */ public UsuariConvidat() { super("Convidat"); } }
TypeScript
UTF-8
1,298
2.84375
3
[]
no_license
class InstagramFollow { private ulList: HTMLElement; private scrollContainer: HTMLElement; private allButtons: HTMLElement[]; private followButtons: HTMLElement[]; constructor(private maxFollows: number = 0){ this.ulList = document.querySelector("div[role='dialog'] ul"); this.scrollContainer = this.ulList.parentElement; } public async start(): Promise<null>{ await this.scrollLoop(); await this.loopFollow(); alert(`Done following ${this.followButtons.length}`); return null; } private loopFollow(): Promise<null>{ return new Promise((resolve, reject) => { let idx = 0; const clickInterval = setInterval(() => { this.followButtons[idx].click(); idx++; if(idx >= this.followButtons.length) { clearInterval(clickInterval); resolve(); } }, 1000); }); } private scrollLoop(): Promise<null>{ return new Promise((resolve, reject) => { const scrollInterval = setInterval(() => { this.scrollContainer.scrollTo(0, this.ulList.scrollHeight); this.allButtons = [...this.ulList.querySelectorAll("button")]; this.followButtons = this.allButtons.filter(btn => btn.textContent === "Follow"); if(this.followButtons.length >= this.maxFollows) { clearInterval(scrollInterval); resolve(); } }, 1000) }); } }
C++
UTF-8
4,284
3
3
[]
no_license
#include "classes.h" #include <bits/stdc++.h> using namespace std; product::product() { name="unknown"; id=-1; } product::product(string s,int ID,int q,char b,int sh,bool t) { name=s; id=ID; quantity=q; block=b; shelf=sh; type=t; } string product::getname() const {return name;} int product::getid() const {return id;} int product::getquantity() const {return quantity;} loc product::getlocation() const { loc a; a.block=block; a.shelf=shelf; return a; } bool product::gettype() const {return type;} void product::setname(string n) {name=n;} void product::setid(int ID) {id=ID;} void product::changelocation(loc c) { block=c.block; shelf=c.shelf; } float product::calculate_total_price() const { if(type) return num_pieces*price_per_piece*quantity; else return ammount_in_liters*price_per_liter*quantity; } int product::getammount_in_liters() const {return ammount_in_liters;} float product::getprice_per_liter() const {return price_per_liter;} bool product::isflammable() const {return flammable;} void product::setters_liquids(int amm,float price,bool flam) { ammount_in_liters=amm; price_per_liter=price; flammable=flam; } int product::getnum_pieces() const {return num_pieces;} float product::getprice_per_piece() const {return price_per_piece;} bool product::isfragile() const {return fragile;} void product::setters_solids(int num,float price,bool frag) { num_pieces=num; price_per_piece=price; fragile=frag; } inventory::inventory() { size=0; } void inventory::load() { ifstream f; f.open("data.txt"); string s; int ID,q; loc l; bool t; int first; float second; bool flag; f>>s>>ID>>q>>l.block>>l.shelf>>t>>first>>second>>flag; while(!f.eof()) { list[size]=new product(s,ID,q,l.block,l.shelf,t); if(t) list[size]->setters_solids(first,second,flag); else list[size]->setters_liquids(first,second,flag); size+=1; f>>s>>ID>>q>>l.block>>l.shelf>>t>>first>>second>>flag; } f.close(); } void inventory::save() { ofstream f; f.open("saved_data.txt",ofstream::trunc); for(int i=0;i<size;i++) { f<<list[i]->getname()<<" "<<list[i]->getid()<<" "<<list[i]->getquantity()<<" "<<list[i]->getlocation().block<<" "<<list[i]->getlocation().shelf<<" "<<list[i]->gettype()<<" "; if(list[i]->gettype()) f<<list[i]->getnum_pieces()<<" "<<list[i]->getprice_per_piece()<<" "<<list[i]->isfragile()<<endl; else f<<list[i]->getammount_in_liters()<<" "<<list[i]->getprice_per_liter()<<" "<<list[i]->isflammable()<<endl; } f.close(); } void inventory::removeProduct(int x) { int index=-1; for(int i=0;i<size;i++) if(list[i]->getid()==x) {index=i; break;} if(index==-1) cout<<"Product with ID:"<<x<<" is not found!."<<endl; else if(index==size-1) { size-=1; delete(list[index]); } else { for(int i=index;i<size-1;i++) list[i]=list[i+1]; size-=1; } } void inventory::add(product& p) { list[size]=new product(p.getname(),p.getid(),p.getquantity(),p.getlocation().block,p.getlocation().shelf,p.gettype()); if(p.gettype()) list[size]->setters_solids(p.getnum_pieces(),p.getprice_per_piece(),p.isfragile()); else list[size]->setters_liquids(p.getammount_in_liters(),p.getprice_per_liter(),p.isflammable()); size+=1; } int inventory::getnewID() { srand(time(0)); int ID=rand()%1000+1; while(1) { int test=1; for(int i=0;i<size;i++) if(list[i]->getid()==ID) {test=0; break;} if(test) break; srand(time(0)); int ID=rand()%1000+1; } return ID; } int inventory::getProductCount(product& p) { int index=-1; for(int i=0;i<size;i++) if(list[i]->getid()==p.getid()) {index=i; break;} if(index==-1) return 0; return list[index]->getquantity(); } int inventory::getUnitCount() { int sum=0; for(int i=0;i<size;i++) sum+=list[i]->getquantity(); return sum; } float inventory::getInventoryValue() { float sum=0; for(int i=0;i<size;i++) sum+=list[i]->calculate_total_price(); return sum; } void inventory::clearInventory() { for(int i=0;i<size;i++) delete(list[i]); size=0; }
PHP
UTF-8
2,541
2.9375
3
[]
no_license
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <?php $connect = mysqli_connect("localhost", "root", "", "phpprojectbase"); if(isset($_POST['edit'])){ $query = " UPDATE persons SET First_name='$_POST[First_name]',Last_name='$_POST[Last_name]', Start_date='$_POST[Start_date]', End_date='$_POST[End_date]' WHERE ID='$_POST[ID]' "; mysqli_query($connect, $query); } if(isset($_POST['delete'])){ $query = " DELETE FROM persons WHERE ID='$_POST[ID]' "; mysqli_query($connect, $query); } if(isset($_POST['insert'])){ $query = "INSERT INTO persons (ID, First_name, Last_name, Start_date, End_date) VALUES (NULL, '$_POST[fname]', '$_POST[lname]', '$_POST[sdate]', '$_POST[edate]'); "; mysqli_query($connect, $query); } $table = mysqli_query($connect, "SELECT * FROM `persons`"); echo "<table> <tr> <th></th> <th>Imię</th> <th>Nazwisko</th> <th>Data od</th> <th>Data do</th> </tr>"; while($row = mysqli_fetch_array($table)){ echo "<form action=index.php method=post>"; echo "<tr>"; echo "<td>" . "<input type=hidden name=ID value=" . $row['ID'] . " </td>"; echo "<td>" . "<input type=text name=First_name value=" . $row['First_name'] . " </td>"; echo "<td>" . "<input type=text name=Last_name value=" . $row['Last_name']. " </td>"; echo "<td>" . "<input type=text name=Start_date value=" . $row['Start_date']. " </td>"; echo "<td>" . "<input type=text name=End_date value=" . $row['End_date']. " </td>"; echo "<td>" . "<input type=submit name=edit value=edytuj" . " </td>"; echo "<td>" . "<input type=submit name=delete value=usuń" . " </td>"; echo "</tr>"; echo "</form>"; } echo "<form action=index.php method=post>"; echo "<tr>"; echo "<td>" . "<input type=hidden name=ID value=" . $row['ID'] . " </td>"; echo "<td>" . "<input type=text name=fname value=''" . " </td>"; echo "<td>" . "<input type=text name=lname value=''" . " </td>"; echo "<td>" . "<input type=text name=sdate value=''" . " </td>"; echo "<td>" . "<input type=text name=edate value=''" . " </td>"; echo "<td>" . "<input type=submit name=insert value='dodaj'" . " </td>"; echo '</tr>'; echo "</form>"; echo "</table>"; mysqli_close($connect); ?> </body> </html>
Java
UTF-8
354
2.921875
3
[]
no_license
package clases; public class Contenedor<T> { private T dato; synchronized public T get() { T result = this.dato; this.dato = null; return result; } synchronized public void put(T valor) { this.dato = valor; } synchronized boolean datoDisponible() { return (this.dato != null); } }
C++
UTF-8
3,213
2.5625
3
[ "MIT" ]
permissive
#include <PubSubClient.h> //mqtt #include "DHT.h" #include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino //needed for library #include <ESP8266WebServer.h> #include <DNSServer.h> #include <WiFiManager.h> //https://github.com/tzapu/WiFiManager const char* mqtt_server = "192.168.0.5"; int val = 0; //value for storing moisture value int soilPin = A0;//Declare a variable for the soil moisture sensor const int button = 16; // pin D0 WiFiClient espClient; PubSubClient client(espClient); long lastHumedad = 0; char moisture[50]; char Temperature[50]; int value = 0; #define DHTPIN 2 // what digital pin the DHT22 is conected to #define DHTTYPE DHT22 // there are multiple kinds of DHT sensors DHT dht(DHTPIN, DHTTYPE); void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i=0;i<length;i++) { Serial.print((char)payload[i]); } Serial.println(); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { // Attempt to connect if (client.connect("Uma")) { // Once connected, publish an announcement... // ... and resubscribe Serial.print("OK connect \n"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.println("\n Starting"); pinMode(button, INPUT); dht.begin(); client.setServer("192.168.0.10", 1883); client.setCallback(callback); } int readmoisture() { val = analogRead(soilPin); //Read the SIG value form sensor return val; //send current moisture value } float readtemp(){ // Reading temperature or humidity takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) //float h = dht.readHumidity(); // Read temperature as Celsius (the default) float t = dht.readTemperature(); return(t); } void loop() { int Moisture = readmoisture(); int temp = readtemp(); //is configuration portal requested? if ( digitalRead(button) == LOW ) { // //WiFiManager // //Local intialization. Once its business is done, there is no need to keep it around WiFiManager wifiManager; // if (!wifiManager.startConfigPortal("Uma")) { Serial.println("failed to connect and hit timeout"); delay(3000); // reset and try again, or maybe put it to deep sleep ESP.reset(); delay(5000); } //if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); } { if (!client.connected()) { reconnect(); } client.loop(); delay (20000); snprintf (moisture, 50, ":" "%ld",Moisture); Serial.print("Publish message: \n"); client.publish("moisture", moisture); snprintf (Temperature, 50, ":" "%ld", temp); client.publish("Temperature", Temperature); } }
JavaScript
UTF-8
1,250
3.015625
3
[]
no_license
const validUrlUtf8 = require('valid-url-utf8') const { BASE_URL } = require('./config') class UrlShortener { constructor () { this.alphabet = '0123456789abcdefghijklmnopqrstuvwxyz' this.size = 1 this.generatedEntries = 0 this.shortenedUrls = {} this.shortUrls = {} } shorten(url) { if (!validUrlUtf8(url)) { throw new Error('Invalid URL') } if (this.shortenedUrls[url]) { this.shortenedUrls[url].hitCount++ return `${BASE_URL}${this.shortenedUrls[url].url}` } const shortenedUrl = this.encode(url) this.shortenedUrls[url] = {} this.shortenedUrls[url].hitCount = 1 this.shortenedUrls[url].url = shortenedUrl this.shortUrls[shortenedUrl] = url return `${BASE_URL}${shortenedUrl}` } getLongUrl(shortUrl) { return this.shortUrls[shortUrl] } encode(url) { const shortenedUrl = [] for (let i = 0; i < this.size; ++i) { let randIndex = Math.floor(Math.random() * (this.alphabet.length -1)) shortenedUrl.push(this.alphabet[randIndex]) } this.generatedEntries++ if (this.generatedEntries > this.size * this.alphabet.length) { this.size++ } return shortenedUrl.join('') } } module.exports = new UrlShortener()
C++
UTF-8
1,993
2.734375
3
[]
no_license
#include "../include/imageLoader.h" #include "../include/picoPNG.h" #include "../include/IOManager.h" #include "../include/Errors.h" namespace gameEngine{ GLtexture imageLoader::loadPNG(std::string filepath){ GLtexture texture = {}; std::vector<unsigned char> in; std::vector<unsigned char> out; if(IOManager::readFileToBuffer(filepath, in) == false) fatalError("Unable to load PNG file from " + filepath); unsigned long width, height; int errorCode = decodePNG(out, width, height, &(in[0]), in.size()); if(errorCode != 0) fatalError("deodePNG failed to work due to error : " + errorCode); //generates n texture ID(s). Here 1 texture id is generated and assigned to texture.id glGenTextures(1, &(texture.id)); //bounds the texture using texture ID to the target glBindTexture(GL_TEXTURE_2D, texture.id); //takes target, level, internal format, width, height, border size, format, pointer to output array and process the target texture and writes processed data to ouput array glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &(out[0])); //sets parameter for currently bound texture glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); //generated mipmaping for target texture //mipmaping means it generates high resolution image for the parts that are close to camera and low resolution image for points that are father away glGenerateMipmap(GL_TEXTURE_2D); //Unbinds the target texture glBindTexture(GL_TEXTURE_2D, 0); texture.height = height; texture.width = width; return texture; } }
C++
UTF-8
718
3.21875
3
[]
no_license
// Convert a given std::string (containing UTF-8 chars) to a unicode string and vice versa. #pragma once #include <iostream> #include <boost/noncopyable.hpp> namespace uberstealth { class StringToUnicode : public boost::noncopyable { public: StringToUnicode(const std::string& str) : s_(str), ws_(NULL) {} ~StringToUnicode() { delete[] ws_; } operator const wchar_t*(); private: const std::string& s_; wchar_t* ws_; }; class UnicodeToString : public boost::noncopyable { public: UnicodeToString(const std::wstring& str) : s_(str), as_(NULL) {}; ~UnicodeToString() { delete[] as_; } operator const char*(); operator std::string(); private: const std::wstring& s_; char* as_; }; }
C++
UTF-8
177
2.578125
3
[]
no_license
#ifndef CITY_H #define CITY_H class City { public: City(double x, double y); double distance(const City& src) const; private: double _x, _y; }; #endif // CITY_H
C#
UTF-8
974
2.859375
3
[]
no_license
using Base.Architecture.UserManagement; using System; using Base.Architecture.DatabaseManager; using Base.Architecture.UserManagement.Models; namespace LibraryManagementCore { public class Core { private User _currentUser; private readonly UserManagementCore _userManagement; public Core(string connectionString) { var dbManager = new DBManager(connectionString); _userManagement = new UserManagementCore(dbManager); } public void LogIn(string username, string password) { // Check if the given password checks against the stored password. _currentUser = _userManagement.LogIn(username, password) ?? throw new Exception("Username or Password invalid"); // Update the last accessed date time _currentUser.LastAccessed = DateTime.Now; _userManagement.UpdateUser(_currentUser); } } }
JavaScript
UTF-8
1,377
2.71875
3
[]
no_license
var randomStuff = require('../helper_routines/getRandomLineOfFile'); var createTopic = require('../domain/CreateTopic'); function generateTopic() { let mainTopic = randomStuff.getRandomLine('./public/resources/MainTopics.txt').trim(); let secondaryTopic = randomStuff.getRandomLine('./public/resources/SecondaryTopics.txt').trim(); let topicModifier = randomStuff.getRandomLine('./public/resources/TopicModifier.txt').trim(); let topicModifierWithSecondary = randomStuff.getRandomLine('./public/resources/TopicModifierWithSecondary.txt').trim(); if (mainTopic == 'Cute Cats' || mainTopic == 'Zoo Babies' || mainTopic == 'Precious Puppies' || mainTopic == 'Adorable Babies') { secondaryTopic = ''; } if (mainTopic == 'Temple Cats' && secondaryTopic.startsWith('from ')) { secondaryTopic = ''; } if (randomStuff.getRandomInt(8) != 0) { secondaryTopic = ''; } if (secondaryTopic != '') { topicModifier = topicModifierWithSecondary; if (randomStuff.getRandomInt(3) != 0) { topicModifier = ''; } } let topic = new createTopic(); topic.initModel({ mainTopic: mainTopic, secondaryTopic: secondaryTopic, topicModifier: topicModifier }); console.log(mainTopic + ":" + secondaryTopic + ":" + topicModifier); return topic; } module.exports = generateTopic;
Swift
UTF-8
2,662
2.8125
3
[ "MIT" ]
permissive
// // BasicTestScene.swift // SwiftSpriterExample // // Created by Matt on 8/28/16. // Copyright © 2016 BiminiRoad. All rights reserved. // import UIKit import SpriteKit import SwiftSpriter class BasicTestScene: SKScene, TextureLoader, AnimationNodeDelegate { var animationManager: AnimationManager! var animationNode: AnimationNode! var animationTimeLabel: SKLabelNode! required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } override init(size: CGSize) { super.init(size: size) self.commonInit() } func commonInit() { guard let parser = SconParser(fileName: "BasicTests"), let animationData = parser.animationData() else { fatalError("Failed to load file") } self.anchorPoint = CGPoint(x: 0.5, y: 0.5) animationManager = AnimationManager(animationData: animationData, textureLoader: self) animationNode = AnimationNode() guard animationNode.loadEntity("TestEntity", fromManager: animationManager) else { fatalError("Could not load entity") } self.addChild(animationNode) animationNode.animationNodeDelegate = self self.animationTimeLabel = SKLabelNode() self.animationTimeLabel.fontSize = 15 self.animationTimeLabel.position = CGPoint(x: 10-self.size.width/2, y: 10-self.size.height/2) self.addChild(self.animationTimeLabel) } override func didMove(to view: SKView) { super.didMove(to: view) let className = NSStringFromClass(type(of: self)) let ns = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String let animationName = className.replacingOccurrences(of: "\(ns).", with: "") guard self.animationNode.playAnimation(animationName) else { fatalError("Cannot play animation \(animationName)") } } override func update(_ currentTime: TimeInterval) { super.update(currentTime) self.animationManager.update(currentTime) self.animationTimeLabel.text = "Animation time (total \(self.animationNode.animationLength) sec): \(self.animationNode.currentAnimationTime)" } func textureNamed(_ textureName: String, path: String?) -> SKTexture? { //print("TextureLoader loads \(path) \(textureName)") return SKTexture(imageNamed: textureName) } func animationNodeDidFinishPlayback(animationNode: AnimationNode, looping: Bool) { //print("Animation did finish playback. Looping: \(looping)") } }
Java
UTF-8
1,929
1.726563
2
[]
no_license
package com.luckyun.base.user.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import com.luckyun.base.user.param.SysUserParam; import com.luckyun.base.user.service.SysUserSubAttrService; import com.luckyun.core.annotation.Pageable; import com.luckyun.core.annotation.UrlByPkgController; import com.luckyun.model.user.SysAccount; @UrlByPkgController public class SysUserSubAttrController { @Autowired private SysUserSubAttrService sysUserSubAttrService; @GetMapping("/readByPost") @Pageable public List<SysAccount> findUserByPostId(SysUserParam condition){ return sysUserSubAttrService.findByPost(condition); } @PostMapping("/addUserPost") public void addUserPost(@RequestBody SysUserParam condition) { sysUserSubAttrService.addUserPost(condition); } @PostMapping("/deleteUserPost") public void deleteUserPost(@RequestBody SysUserParam condition) { sysUserSubAttrService.deleteUserPost(condition); } @GetMapping("/readByRole") @Pageable public List<SysAccount> findUserByRoleId(SysUserParam condition){ return sysUserSubAttrService.findByRole(condition); } @GetMapping("/readByMajor") @Pageable public List<SysAccount> findUserByMajor(SysUserParam condition){ return sysUserSubAttrService.findByMajor(condition); } @PostMapping("/addUserRole") public void addUserRole(@RequestBody SysUserParam condition) { sysUserSubAttrService.addUserRole(condition); } @PostMapping("/deleteUserRole") public void deleteUserRole(@RequestBody SysUserParam condition) { sysUserSubAttrService.deleteUserRole(condition); } @PostMapping("/updateNk") public void updateNickname(@RequestBody SysAccount account) { sysUserSubAttrService.updateNk(account); } }
Ruby
UTF-8
889
3.5625
4
[]
no_license
class LinkedList attr_accessor :head, :tail, :size def initialize(items = []) @size = 0 append_nodes(items) end def append_nodes(items) items.each { |item| append_node(item) } end def append_node(item) if @head.item.nil? @head.item end tail_node = Node.new(item: item, _next: @tail) @tail.next = tail_node @tail = tail_node @size = @size + 1 end def find(value) node = @head binding.pry return if node.tail? return node if node.item == value until node.tail? node = node.next return node if node.item == value end false end # def delete(value) # delete_head if @head.value == value # end class Node def initialize(item: nil, _next: nil) @item = item @next = _next end def tail? @next.nil? end attr_accessor :item, :next end end
Java
UTF-8
656
3.078125
3
[]
no_license
public class TreeIntSet implements IntSet { IntegerTreeNode root; public void add(int n) { if(root == null) { root = new IntegerTreeNode(n); } else { root.add(n); } } public boolean contains(int n) { if(root == null) { return false; } return root.contains(n); } public boolean containsVerbose(int n) { if(root == null) { return false; } return root.containsVerbose(n); } public String toString() { if(root == null) { return ""; } return root.toString(); } }
Python
UTF-8
2,135
3.78125
4
[]
no_license
import unittest import random import Homework class HomeworkSequenceFunctions(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def test_exponentiate(self): expected = [1,2,4,8,16,32,64,128,256] actual = Homework.power_of_two(9) self.assertEqual(expected,actual) def test_choice(self): pass def test_distinct_numbers(self): expected = True actual = Homework.distinct_numbers([1,2,3,4,5]) self.assertEqual(expected,actual) expected_1 = False actual = Homework.distinct_numbers([1,1,2,3,4,5]) self.assertEqual(expected_1,actual) expected_2 = False actual = Homework.distinct_numbers([1,2,2,3,4,5]) self.assertEqual(expected_2,actual) def test_alphabet(self): expected = ['a','b','c','d','e','f','g','h','i','j', 'k','l','m','n','o','p','q','r','s','t', 'u','v','w','x','y','z'] actual = Homework.alphabet() self.assertEqual(expected,actual) def test_count_vowel(self): expected = 31 actual = Homework.count_vowel('If I have seen farther then other men, it is because I have stood on the shoulders of giants.') self.assertEqual(expected,actual) def test_factors_modify(self): expected = [1, 2, 5, 10] def factors_modify(): return [i for i in Homework.factors_modify(10)] self.assertEqual(expected, factors_modify()) def test_polynomial(self): """to pass this test please enter 12*x**2 + 2*x -5 and 2 for the input""" expected = 1.0000000000065512 actual = Homework.main() self.assertEqual(expected,actual) def test_split_file(self): expected = {'a': 17,'b': 2,'c': 7,'d': 3,'e': 12,'f': 3, 'g': 1, 'h': 10,'i': 4,'j': 0, 'k': 0,'l': 2,'m': 3,'n': 8, 'o': 8, 'p': 8, 'q': 1,'r': 9,'s': 4,'t': 18, 'u': 6,'v':0,'w': 1,'x':0,'y': 1,'z':0} actual = Homework.split_file() self.assertEqual(expected,actual)
C++
UTF-8
790
3.703125
4
[]
no_license
Write a smart pointer class. A smart pointer is a data type, usually implemented with templates, that simulates a pointer while also providing automatic garbage collec- tion. It automatically counts the number of references to a SmartPointer<T*> object and frees the object of type T when the reference count hits zero. In short, the smart pointer is the reference counter for the object, when constructor being called: pointer ++ when equal operater being called: pointer++ Then, if remove called, pointer++ - if *ref_count ==0: delete object SmartPointer(SmartPointer<T> & sptr) { ref = sptr.ref; ref_count = sptr.ref_count; ++(*ref_count); } void remove() { --(*ref_count); if(*ref_count ==0){ delete ref; free(ref_count); ref = NULL; ref_count = NULL; } }
Python
UTF-8
988
2.8125
3
[]
no_license
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ start = i = 0 while i<len(nums): nums[start] = nums[i] start +=1 i+=1 if i<len(nums): if nums[i] == nums[i-1]: nums[start] = nums[i] start +=1 i+=1 while i<len(nums) and nums[i] == nums[i-1]: i+=1 return start class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ count = start = 1 for i in range(1, len(nums)): if nums[i] != nums[i-1]: nums[start] = nums[i] start +=1 count = 1 elif count < 2: nums[start] = nums[i] start +=1 count+=1 return start
Java
UTF-8
8,984
3.125
3
[]
no_license
package fall2018.csc2017.gameCentre.slidingtiles; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Random; import fall2018.csc2017.gameCentre.LoginActivityController; import fall2018.csc2017.gameCentre.ScoreTuple; /** * Manage a board, including swapping tiles, checking for a win, and managing taps. */ public class BoardManager implements Serializable { public void setBoard(Board board) { this.board = board; } /** * The board being managed. */ private Board board; /** * The List of recentSteps. */ List<int[]> recentSteps; /** * The number of steps allowed to undo with default value of 3. */ static int numSteps = 3; /** * indicate whether the user has uploaded picture or not. */ static boolean SelfDefinedIndicator = false; /** * The final score. */ static ScoreTuple finalScore; /** * @return return time passed */ int getMTimeLeftInMillis() { return mTimeLeftInMillis; } /** * time passed */ void setMTimeLeftInMillis(int a) { mTimeLeftInMillis = a; } /** * add time */ void addTime() { this.mTimeLeftInMillis += 1000; } void SetMTimeLeftInMillis(int mTimeLeftInMillis) { this.mTimeLeftInMillis = mTimeLeftInMillis; } /** * The number of milliseconds. */ private int mTimeLeftInMillis; /** * reset number of undo to a specific number. */ void setNumUndo(int undo) { this.numUndo = undo; } /** * @return return number of UnDos. */ int getNumUndo() { return numUndo; } /** * the number of undo. */ private int numUndo; /** * indicator of whether or not the board is solved */ boolean isSolved = false; /** * Manage a board that has been pre-populated. * * @param board the board */ BoardManager(Board board) { this.board = board; recentSteps = new ArrayList<>(numSteps); } /** * Return the current board. */ Board getBoard() { return board; } /** * Manage a new shuffled board. */ BoardManager(int complexity) { List<STTile> tiles = new ArrayList<>(); final int numTiles = complexity * complexity; for (int tileNum = 0; tileNum != numTiles; tileNum++) { if (!SelfDefinedIndicator) { tiles.add(new STTile(tileNum, complexity)); } else { tiles.add(new SelfDefinedSTTile(tileNum, complexity)); } } this.board = new Board(tiles, complexity); shuffleboard(this.board); recentSteps = new ArrayList<>(numSteps); } /** * shuffle the board makes it always be solvable * * @param board: this board * Citation: java Random of selecting an random item from list * https://stackoverflow.com/questions/12487592/randomly-select-an-item-from-a-list * java Random of selecting a random number * https://stackoverflow.com/questions/5887709/getting-random-numbers-in-java */ private void shuffleboard(Board board) { // position of the white tile which is updated after every swap int position = board.getComplexity() * board.getComplexity() - 1; // randomly generate a number Random rand = new Random(); int n = rand.nextInt(100) + 2; int i = 1; while (i < n) { // get row,col number of the white tile. int row = position / board.getComplexity(); int col = position % board.getComplexity(); // check whether 4 of white tile's surrounding tiles are available STTile above = row - 1 == -1 ? null : board.getTile(row - 1, col); STTile below = row + 1 == board.getComplexity() ? null : board.getTile(row + 1, col); STTile left = col - 1 == -1 ? null : board.getTile(row, col - 1); STTile right = col + 1 == board.getComplexity() ? null : board.getTile(row, col + 1); // add available positions to the list List<Integer> positions = new ArrayList<>(); if (above != null) { positions.add(position - board.getComplexity()); } if (below != null) { positions.add(position + board.getComplexity()); } if (left != null) { positions.add(position - 1); } if (right != null) { positions.add(position + 1); } // random get a position to be swapped with the white tile. Random myRandom = new Random(); Integer random = positions.get(myRandom.nextInt(positions.size())); int NewRow = random / board.getComplexity(); int NewCol = random % board.getComplexity(); // swap two tiles and update white tile board.swapTiles(row, col, NewRow, NewCol); board.resetNumStep(); position = random; i++; } } /** * Return whether the tiles are in row-major order. */ boolean puzzleSolved() { int i = 0; Iterable<STTile> iterable = board; for (STTile tile : iterable) { ++i; if (tile.getId() != i) { return false; } } isSolved = true; return true; } /** * record this step * * @param thisStep the step to be recorded. */ private void recordStep(int[] thisStep) { if (recentSteps.size() < numSteps) { recentSteps.add(thisStep); } else { recentSteps.remove(0); recentSteps.add(thisStep); } } /** * Return whether any of the four surrounding tiles is the blank tile. * * @param position the tile to check * @return whether the tile at position is surrounded by a blank tile */ boolean isValidTap(int position) { int row = position / board.getComplexity(); int col = position % board.getComplexity(); int blankId = board.numTiles(); // Are any of the 4 the blank tile? STTile above = row == 0 ? null : board.getTile(row - 1, col); STTile below = row == board.getComplexity() - 1 ? null : board.getTile(row + 1, col); STTile left = col == 0 ? null : board.getTile(row, col - 1); STTile right = col == board.getComplexity() - 1 ? null : board.getTile(row, col + 1); return (below != null && below.getId() == blankId) || (above != null && above.getId() == blankId) || (left != null && left.getId() == blankId) || (right != null && right.getId() == blankId); } /** * Process a touch at position in the board, swapping tiles as appropriate. * * @param position the position */ void touchMove(int position) { int row = position / board.getComplexity(); int col = position % board.getComplexity(); int blankId = board.numTiles(); if (this.isValidTap(position)) { int[][] positionsSurrounded = {{row - 1, col}, {row + 1, col}, {row, col - 1}, {row, col + 1}}; for (int i = 0; i < 4; i++) { int selectedRow = positionsSurrounded[i][0]; int selectedCol = positionsSurrounded[i][1]; if (selectedRow < board.getComplexity() && selectedRow >= 0 && selectedCol < board.getComplexity() && selectedCol >= 0) { STTile tile = board.getTile(selectedRow, selectedCol); if (tile.getId() == blankId) { board.swapTiles(row, col, selectedRow, selectedCol); int[] thisStep = {row, col, selectedRow, selectedCol}; recordStep(thisStep); } } } } } /** * undo the previous step. * * @param steps the list of steps to undo. */ void undo(List<int[]> steps) { if (!steps.isEmpty()) { int[] lastStep = steps.get(steps.size() - 1); board.swapTiles(lastStep[0], lastStep[1], lastStep[2], lastStep[3]); steps.remove(steps.size() - 1); numUndo += 1; } } /** * calculate final score. */ void calculate() { finalScore = new ScoreTuple(LoginActivityController.session.getName(), get_score(), "Tiles"); } int get_score() { int total = 500; total += Math.round(-0.15 * getMTimeLeftInMillis() / 1000 - 0.25 * board.getNumStep() - 3 * numUndo - 10 * board.getComplexity()); return total; } }
Python
UTF-8
2,777
2.96875
3
[]
no_license
#!/usr/bin/env python import json from kafka import KafkaProducer from flask import Flask, request app = Flask(__name__) producer = KafkaProducer(bootstrap_servers='kafka:29092') # * Adds metadata such as Host/IP address, User-Agent to all generated events # * Encodes it (default: encoding='utf-8', #errors='strict') # * Produces event to Kafka def log_to_kafka(topic, event): event.update(request.headers) #Adding remote header in case IP addresses outside of my environment make requests to our server event.update({'remote_addr': request.remote_addr}) producer.send(topic, json.dumps(event).encode()) @app.route("/") def default_response(): """ * Default response if no specific API route is hit """ default_event = {'event_type': 'default'} log_to_kafka('game_events', default_event) return "This is the default response!\n" @app.route("/purchase_sword") def purchase_sword(): """ * GET message here can either be a default purchase_sword or pass query params * Both options get processed through via the log_to_kafka function while return back to the user the information of their purchase. """ #Data is passed via qury parameters, add the arguments to our JSON logged to Kafka result = {} for key, value in request.args.items(): result[key] = value #Condition to check if params were specified in request if len(result) == 0: sword_event = {'event_type': 'purchase_sword'} log_to_kafka('game_events', sword_event) return "Sword Purchased\n" else: sword_event = {'event_type': 'purchase_sword'} sword_event.update(result) log_to_kafka('game_events', sword_event) return "Sword Purchased: " + json.dumps(result) + "\n" @app.route("/join_a_guild") def join_a_guild(): """ * GET message here can either be a default join_a_guild or pass query params * Both options get processed through via the log_to_kafka function while return back to the user the information of their purchase. """ #Data is passed via qury parameters, add the arguments to our JSON logged to Kafka result = {} for key, value in request.args.items(): result[key] = value #Condition to check if params were specified in request if len(result) == 0: join_a_guild_event = {'event_type': 'join_a_guild'} log_to_kafka('game_events', join_a_guild_event) return "Joined a Guild!\n" else: join_a_guild_event = {'event_type': 'join_a_guild'} join_a_guild_event.update(result) log_to_kafka('game_events', join_a_guild_event) return "Joined a guild! " + json.dumps(result) + "\n"
Markdown
UTF-8
656
2.640625
3
[]
no_license
# HARPG-Pheno-Generator HARPG Pheno Generator used for ARPG (art role play game) on the platform DeviantArt. It is used to generate new foals (babies) based on the perferred colours of the user. Users can input and limit the number of genes included to be randomized, and choose to include or omit certain genes. The generator will follow the general HARPG standards when naming certain genetics combos. (For example, Tobiano (Tb) and Overo (O) will be named Tovero). There should be an HTML file (also includes light CSS) and the javascript file. # COMING SOON This will also be hosted on harpgtoolkit.com if anyone would like to test it themselves.
Python
UTF-8
483
3.546875
4
[]
no_license
# -*- coding: utf-8 -*- """ Created on Wed Mar 7 13:35:19 2018 @author: DS-Tm """ # -*- coding: utf-8 -*- def addition(a, b): c = a + b print(c) def soustraction(a, b): c = a - b print(c) def division(a, b): if (a == 0 and b == 0): print("Indermination") if b == 0: print("Division par 0") else: c = a/b print(c) addition(5, 7) soustraction(5, 7) division(4, 0) division(0, 0) division(4, 9)
Java
UTF-8
804
2.453125
2
[]
no_license
package rest.dtos.productlists; import java.util.List; import java.util.stream.Collectors; import model.products.ProductList; import rest.dtos.offers.OfferDTO; import util.Money; public class ProductListDTO { public int id; public String name; public Money totalAmount; public List<SelectedProductDTO> selectedProducts; public List<OfferDTO> appliedOffers; public ProductListDTO(){ } public ProductListDTO(ProductList pl) { id = pl.getId(); name = pl.getName(); totalAmount = pl.getMoneyOfProducts(); selectedProducts = SelectedProductDTO.createSelectedProducts(pl.getAllProducts()); } public static List<ProductListDTO> createProductLists(List<ProductList> productlists) { return productlists.stream().map(x -> new ProductListDTO(x)).collect(Collectors.toList()); } }
Java
UTF-8
15,942
2.109375
2
[]
no_license
/** * 项目名: eyah * 包名: com.sttri.eyah.controls.dialog * 版本信息: 1.0.0 * Copyright (c) -版权所有 */ package com.xiaoma.beiji.controls.dialog; import android.app.Activity; import android.app.Dialog; import android.os.Bundle; import android.view.Display; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.RelativeLayout; import android.widget.TextView; import com.common.android.lib.base.BaseActivity; import com.xiaoma.beiji.R; /** * 类名称: EyahDialog * 类描述: * 创建人: gang.shi * 修改人: gang.shi * 修改时间: 2015年06月08 15:10 * 修改备注: * * @version 1.0.0 */ public class SimpleDialog extends Dialog { private Activity activity; private CharSequence title; private CharSequence message; private View messageView; private RelativeLayout.LayoutParams messageViewLayoutParams; private CharSequence leftButtonTxt; private android.view.View.OnClickListener leftButtonClickListenerForView; private CharSequence centerButtonTxt; private android.view.View.OnClickListener centerButtonClickListenerForView; private CharSequence rightButtonTxt; private android.view.View.OnClickListener rightButtonClickListenerForView; private int leftButtonColor; private int centerButtonColor; private int rightButtonColor; public SimpleDialog(Activity activity) { super(activity, R.style.base_dialog); this.activity = activity; } public SimpleDialog setDialogTitle(CharSequence title) { this.title = title; this.flagTitleChanged = true; refresh(); return this; } public SimpleDialog setDialogMessage(CharSequence message) { this.message = message; this.flagMessageChanged = true; //如果设置文本,必须将messageView等相关的数据清空,否则如果messageView不为空,则message设置会无效 this.messageView = null; this.messageViewLayoutParams = null; refresh(); return this; } public SimpleDialog setDialogMessageView(View messageView, RelativeLayout.LayoutParams messageViewLayoutParams) { this.messageView = messageView; this.messageViewLayoutParams = messageViewLayoutParams; this.flagMessageChanged = true; this.message = null; refresh(); return this; } public SimpleDialog setDialogLeftButton(CharSequence leftButtonTxt) { this.leftButtonTxt = leftButtonTxt; this.flagBottomBtnChanged = true; refresh(); return this; } public SimpleDialog setDialogLeftButton(CharSequence leftButtonTxt, android.view.View.OnClickListener clickListener) { this.leftButtonTxt = leftButtonTxt; this.leftButtonClickListenerForView = clickListener; this.flagBottomBtnChanged = true; refresh(); return this; } public SimpleDialog setDialogCenterButton(CharSequence centerButtonTxt) { this.centerButtonTxt = centerButtonTxt; this.flagBottomBtnChanged = true; refresh(); return this; } public SimpleDialog setDialogCenterButton(CharSequence centerButtonTxt, android.view.View.OnClickListener clickListener) { this.centerButtonTxt = centerButtonTxt; this.leftButtonClickListenerForView = clickListener; this.flagBottomBtnChanged = true; refresh(); return this; } public SimpleDialog setDialogRightButton(CharSequence rightButtonTxt) { this.rightButtonTxt = rightButtonTxt; this.flagBottomBtnChanged = true; refresh(); return this; } public SimpleDialog setDialogRightButton(CharSequence rightButtonTxt, android.view.View.OnClickListener clickListener) { this.rightButtonTxt = rightButtonTxt; this.rightButtonClickListenerForView = clickListener; this.flagBottomBtnChanged = true; refresh(); return this; } public SimpleDialog setDialogLeftColor(int leftButtonColor) { this.leftButtonColor = leftButtonColor; this.flagBottomBtnChanged = true; refresh(); return this; } public SimpleDialog setDialogCenterColor(int centerButtonColor) { this.centerButtonColor = centerButtonColor; this.flagBottomBtnChanged = true; refresh(); return this; } public SimpleDialog setDialogRightColor(int rightButtonColor) { this.rightButtonColor = rightButtonColor; this.flagBottomBtnChanged = true; refresh(); return this; } private TextView DialogTitle; private View DialogMessageTextFrameLayout; private TextView DialogMessage; private RelativeLayout DialogMessageViewRelativeLayout; private View DialogBtnDividerLine; private View DialogBtnLayout; private TextView DialogButtonLeft; private View DialogLineLeftAndCenter; private TextView DialogButtonCenter; private View DialogLineCenterAndRight; private TextView DialogButtonRight; private boolean flagTitleChanged = true; private boolean flagMessageChanged = true; private boolean flagBottomBtnChanged = true; private boolean hasInitView = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); WindowManager.LayoutParams lp = getWindow().getAttributes(); lp.dimAmount = 0.5f; getWindow().setAttributes(lp); getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND); // 这句必须加上,要不然dialog上会有一段空白(标题栏) getWindow().requestFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.dialog_base_layout); DialogTitle = (TextView) findViewById(R.id.DialogTitle); DialogMessageTextFrameLayout = findViewById(R.id.DialogMessageTextFrameLayout); DialogMessage = (TextView) DialogMessageTextFrameLayout.findViewById(R.id.DialogMessage); DialogMessageViewRelativeLayout = (RelativeLayout) findViewById(R.id.DialogMessageViewRelativeLayout); DialogBtnDividerLine = findViewById(R.id.DialogBtnDividerLine); DialogBtnLayout = findViewById(R.id.DialogBtnLayout); DialogButtonLeft = (TextView) findViewById(R.id.DialogButtonLeft); DialogButtonCenter = (TextView) findViewById(R.id.DialogButtonCenter); DialogButtonRight = (TextView) findViewById(R.id.DialogButtonRight); DialogLineLeftAndCenter = findViewById(R.id.DialogLineLeftAndCenter); DialogLineCenterAndRight = findViewById(R.id.DialogLineCenterAndRight); hasInitView = true; } @Override protected void onStart() { refresh(); } /** * 设置Title相关的View */ private void setTitleView() { if (isNotEmpty(title)) { DialogTitle.setVisibility(View.VISIBLE); DialogTitle.setText(title); } else { DialogTitle.setVisibility(View.GONE); } } /** * 设置Message相关的View */ private void setMessageView() { if (messageView != null) { DialogMessageTextFrameLayout.setVisibility(View.GONE); DialogMessageViewRelativeLayout.setVisibility(View.VISIBLE); DialogMessageViewRelativeLayout.removeAllViewsInLayout(); if (messageViewLayoutParams == null) { DialogMessageViewRelativeLayout.addView(messageView); } else { DialogMessageViewRelativeLayout.addView(messageView, messageViewLayoutParams); } } else { DialogMessageTextFrameLayout.setVisibility(View.VISIBLE); DialogMessageViewRelativeLayout.setVisibility(View.GONE); DialogMessage.setText(message); } } /** * 设置底部按钮相关的View */ private void setBottomBtnView() { boolean showBtnLayout = false; if (isNotEmpty(leftButtonTxt)) { showBtnLayout = true; if (leftButtonColor != 0) { DialogButtonLeft.setTextColor(leftButtonColor); } DialogButtonLeft.setText(leftButtonTxt); DialogButtonLeft.setVisibility(View.VISIBLE); DialogButtonLeft.setOnClickListener(new android.view.View.OnClickListener() { @Override public void onClick(View v) { dismiss(); if (leftButtonClickListenerForView != null) { leftButtonClickListenerForView.onClick(v); } } }); } else { DialogButtonLeft.setVisibility(View.GONE); } if (isNotEmpty(centerButtonTxt)) { showBtnLayout = true; if (centerButtonColor != 0) { DialogButtonCenter.setTextColor(centerButtonColor); } DialogButtonCenter.setText(centerButtonTxt); DialogButtonCenter.setVisibility(View.VISIBLE); DialogButtonCenter.setOnClickListener(new android.view.View.OnClickListener() { @Override public void onClick(View v) { dismiss(); if (centerButtonClickListenerForView != null) { centerButtonClickListenerForView.onClick(v); } } }); } else { DialogButtonCenter.setVisibility(View.GONE); } if (isNotEmpty(rightButtonTxt)) { showBtnLayout = true; if (rightButtonColor != 0) { DialogButtonRight.setTextColor(rightButtonColor); } DialogButtonRight.setText(rightButtonTxt); DialogButtonRight.setVisibility(View.VISIBLE); DialogButtonRight.setOnClickListener(new android.view.View.OnClickListener() { @Override public void onClick(View v) { dismiss(); if (rightButtonClickListenerForView != null) { rightButtonClickListenerForView.onClick(v); } } }); } else { DialogButtonRight.setVisibility(View.GONE); } if (showBtnLayout == false) { DialogBtnDividerLine.setVisibility(View.GONE); DialogBtnLayout.setVisibility(View.GONE); } else { DialogBtnDividerLine.setVisibility(View.VISIBLE); DialogBtnLayout.setVisibility(View.VISIBLE); if (DialogButtonCenter.getVisibility() == View.VISIBLE && DialogButtonCenter.getVisibility() == View.VISIBLE) { DialogLineLeftAndCenter.setVisibility(View.VISIBLE); } else { DialogLineLeftAndCenter.setVisibility(View.GONE); } if (DialogButtonRight.getVisibility() == View.VISIBLE && (DialogButtonCenter.getVisibility() == View.VISIBLE || DialogButtonLeft.getVisibility() == View.VISIBLE)) { DialogLineCenterAndRight.setVisibility(View.VISIBLE); } else { DialogLineCenterAndRight.setVisibility(View.GONE); } } } public void refresh() { if (hasInitView == false) { return; } if (flagTitleChanged) { flagTitleChanged = false; setTitleView(); } if (flagMessageChanged) { flagMessageChanged = false; setMessageView(); } if (flagBottomBtnChanged) { flagBottomBtnChanged = false; setBottomBtnView(); } } private static boolean isNotEmpty(CharSequence text) { return text != null && text.length() > 0; } @Override public void show() { try { if ((activity instanceof BaseActivity && ((BaseActivity) activity).isActivityShowing()) || activity.isFinishing() == false) { super.show(); updateDialogWidth(activity, this); } } catch (Exception e) { } } /** * 将 dialog 的宽度设置为联连标准通用宽度 * @param context * @param dialog */ public static void updateDialogWidth(Activity context,Dialog dialog) { Display display = context.getWindowManager().getDefaultDisplay(); Window window = dialog.getWindow(); WindowManager.LayoutParams lp = window.getAttributes(); lp.width = (display.getWidth()) - display.getWidth()/10; //设置宽度 window.setAttributes(lp); } /** * @deprecated 不推荐使用,请使用 {@link #setDialogTitle(CharSequence)} */ public void setTitle(CharSequence title) { this.setDialogTitle(title); } /** * @deprecated 不推荐使用,请使用 {@link #setDialogMessage(CharSequence)} */ public void setMessage(CharSequence message) { this.setDialogMessage(message); } public static final SimpleDialog showDialog(Activity activity, CharSequence title, CharSequence message, CharSequence leftBtnTxt, CharSequence rightBtnTxt, android.view.View.OnClickListener leftBtnClickListener, android.view.View.OnClickListener rightBtnClickListener) { SimpleDialog d = new SimpleDialog(activity).setDialogTitle(title).setDialogMessage(message); d.setDialogLeftButton(leftBtnTxt, leftBtnClickListener); d.setDialogRightButton(rightBtnTxt, rightBtnClickListener); d.show(); return d; } /** * 只有一个按钮的Dialog,一般用作提示,无需处理用户点击的情况(例如:我知道了) * showDialog(这里用一句话描述这个方法的作用) * (这里描述这个方法是用条件 - 可选) * * @param activity * @param title * @param message * @param leftBtnTxt * @return LianLianDialog * @throws * @since 1.0.0 */ public static final SimpleDialog showDialog(Activity activity, String title, String message, String leftBtnTxt) { return showDialog(activity, title, message, leftBtnTxt, null, null, null); } public static final SimpleDialog showDialog(Activity activity, String title, View messageView, RelativeLayout.LayoutParams layoutParams, String leftBtnTxt) { SimpleDialog d = new SimpleDialog(activity).setDialogTitle(title).setDialogMessageView(messageView, layoutParams); d.setDialogLeftButton(leftBtnTxt, null); d.show(); return d; } public static final SimpleDialog showDialog(Activity activity, String title, String message, String leftBtnTxt, android.view.View.OnClickListener leftBtnClickListener) { return showDialog(activity, title, message, leftBtnTxt, null, leftBtnClickListener, null); } public static final SimpleDialog showDialogWithConfirmAndCancel(Activity activity, String title, String message, android.view.View.OnClickListener confirmClickListener) { return showDialog(activity, title, message, "取消", "确定", null, confirmClickListener); } public static final SimpleDialog showDialogWithIKnow(Activity activity, String title, String message) { return showDialog(activity, title, message, "我知道了", null, null, null); } /** * 无按钮的Dialog * showDialog(这里用一句话描述这个方法的作用) * (这里描述这个方法是用条件 - 可选) * * @param activity * @param title * @param message * @return LianLianDialog * @throws * @since 1.0.0 */ public static final SimpleDialog showDialog(Activity activity, String title, String message) { return showDialog(activity, title, message, null, null, null, null); } }