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
1,920
2.234375
2
[]
no_license
package com.demo.service; import java.io.IOException; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Component; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import com.demo.model.Wrapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import lombok.extern.slf4j.Slf4j; @Slf4j @Component public class SampleJob implements Job { private ExchangeRateServiceImplementation service; private RestTemplate caller; XmlMapper xmlMapper; private String lbUrl; public SampleJob(ExchangeRateServiceImplementation service, RestTemplate caller, XmlMapper xmlMapper, @Value("${exchange-config.url}") String lbUrl) { this.service = service; this.caller = caller; this.xmlMapper = xmlMapper; this.lbUrl = lbUrl; } public void execute(JobExecutionContext context) throws JobExecutionException { log.info("Executing job"); Wrapper list; try { ResponseEntity<String> response = caller.getForEntity(lbUrl, String.class); list = xmlMapper.readValue(response.getBody(), Wrapper.class); list.getCard().stream().forEach(e -> e.setCurrency(e.getExchangeRates().get(1).getCurrencyCode())); service.addCurrencies(list.getCard()); } catch (RestClientException | IOException e) { try { Thread.sleep(15000); this.execute(context); } catch (InterruptedException e1) { log.error("failed : {}", e1); this.execute(context); } } } }
Java
UTF-8
2,259
2.265625
2
[]
no_license
package com.diki.idn.crudmovie.data; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Context; import android.os.Bundle; import android.util.Log; import com.diki.idn.crudmovie.R; import com.diki.idn.crudmovie.adapter.MainAdapter; import com.diki.idn.crudmovie.model.ResponseReadMovie; import com.diki.idn.crudmovie.model.UserItem; import com.diki.idn.crudmovie.network.InterfaceClient; import com.diki.idn.crudmovie.network.RetrofitConfig; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class ReadDataMovie extends AppCompatActivity { private MainAdapter mainAdapter; private InterfaceClient interfaceClient; private RecyclerView rvMovie; private List<UserItem> results = new ArrayList<>(); Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_read_data_movie); rvMovie = findViewById(R.id.rv_movie); interfaceClient = RetrofitConfig.creatService(InterfaceClient.class); mainAdapter = new MainAdapter(this, results); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); rvMovie.setLayoutManager(layoutManager); context = this; loadMovie(); } private void loadMovie() { Call<ResponseReadMovie> request = interfaceClient.getMovie("user", "read", "title", "description"); request.enqueue(new Callback<ResponseReadMovie>() { @Override public void onResponse(Call<ResponseReadMovie> call, Response<ResponseReadMovie> response) { results = response.body().getUser(); rvMovie.setAdapter(new MainAdapter(context,results)); mainAdapter.notifyDataSetChanged(); } @Override public void onFailure(Call<ResponseReadMovie> call, Throwable t) { Log.e("Connection Failed", t.toString()); } }); } }
JavaScript
UTF-8
3,885
3.5625
4
[]
no_license
const createBtnRequest = function () { let name; let ownerName; let ownerBalance; let newBankAccount; const processBtnRequest = function () { ownerBalance = 0; let output = document.getElementById('accName'); let validName = false; ownerName = output.textContent; let validUserInput = true; if (ownerName !== ""){ validName = true; newBankAccount = BankAccount(ownerName); } if (this.id === "nameBtn"){ name = prompt("Please enter your Bank Accout Name", "Harry Potter"); newBankAccount = BankAccount(name); validName = true; displayOutput(name, 0); } if ( this.id === "depositBtn" && validName === true){ let depositAmt = Number(prompt("Please enter the amount you want to deposit. Enter Only Numbers", "100")); validUserInput = checkUserInput(depositAmt); if (validUserInput === true){ newBankAccount.depositAmount(depositAmt); displayOutput(newBankAccount.getOwnerName(), newBankAccount.getBalance()); } } if ( this.id === "withdrawalBtn" && validName===true){ let withDrawAmt = Number(prompt("Please enter the amount you want to withdraw. Enter Only Numbers", "10" )); validUserInput = checkUserInput(withDrawAmt); if (validUserInput === true){ newBankAccount.withdrawAmount(withDrawAmt); displayOutput(newBankAccount.getOwnerName(), newBankAccount.getBalance()); } } if( validName === false){ alert("First Create account before any transaction"); } }; return processBtnRequest; }; displayOutput = function(name, amt){ let output = document.getElementById('accName'); let balId = document.getElementById('accBalance'); output.innerHTML = name; balId.innerHTML = amt; } checkUserInput = function(input){ let isNum = true; isNum = /^\d+$/.test(input); if (isNum === false){ alert("Must input numbers"); } return isNum; } const BankAccount = function(accountName) { let newBalance = 0; let name = accountName; return { depositAmount: function(depositAmt){ let balanceId = document.getElementById('accBalance'); let balance = document.getElementById('accBalance').textContent; if ( balance !== ""){ let num = parseFloat(balance); newBalance = depositAmt + num; } else { newBalance = depositAmt; } }, withdrawAmount: function(withdrawalAmt){ let balanceId = document.getElementById('accBalance'); let balance = document.getElementById('accBalance').textContent; if ( balance !== ""){ let num = parseFloat(balance); if ((num - withdrawalAmt) < 0) { newBalance = num; alert("Withdrawal not successful, Cannnot Over withdraw"); } else { newBalance = num - withdrawalAmt; } } else { alert("Withdrawal not successful. Balance is Not Set!!"); } }, getBalance: function(){ return newBalance; }, getOwnerName: function(){ return name; } }; }; window.addEventListener('load', () => { document.getElementById('nameBtn').onclick = createBtnRequest(); document.getElementById('depositBtn').onclick = createBtnRequest(); document.getElementById('withdrawalBtn').onclick = createBtnRequest(); });
C#
UTF-8
1,169
3
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.UI; namespace WebSimplify.Helpers { public class HtmlStringHelper { public static string LineBreak = "<br>"; public static string GenerateHtmlText(List<string> text) { StringWriter stringWriter = new StringWriter(); using (HtmlTextWriter wr = new HtmlTextWriter(stringWriter)) { wr.RenderBeginTag(HtmlTextWriterTag.Table); foreach (var str in text) AppendTableRow(wr, str); wr.RenderEndTag();//close table } return stringWriter.ToString(); } private static void AppendTableRow(HtmlTextWriter wr, string text) { wr.RenderBeginTag(HtmlTextWriterTag.Tr); AppendTableCell(wr, text); wr.RenderEndTag(); } private static void AppendTableCell(HtmlTextWriter wr, string text) { wr.RenderBeginTag(HtmlTextWriterTag.Td); wr.Write(text); wr.RenderEndTag(); } } }
Java
UTF-8
4,544
3.671875
4
[]
no_license
import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; /** * There are a total of n courses you have to take, labeled from 0 to n - 1. * Some courses may have prerequisites, for example to take course 0 you have to first take course 1, * which is expressed as a * pair: [0,1] * Given the total number of courses and a list of prerequisite pairs, is it possible for you to * finish all courses? * For example: 2, [[1,0]] * There are a total of 2 courses to take. To take course 1 you should have finished course 0. So * it is possible. * 2, [[1,0],[0,1]] * There are a total of 2 courses to take. To take course 1 you should have finished course 0, and * to take course 0 you should also * have finished course 1. So it is impossible. * Note: * 1. The input prerequisites is a graph represented by a list of edges, not adjacency matrices. Read * more about how a graph is * represented. * 2.You may assume that there are no duplicate edges in the input prerequisites. * * Tags: DFS, BFS, Graph, Topological Sort * @author wendi * */ public class CourseSchedule { /** * Method2: DFS: * @param int numCourses, int[][] prerequisites * @return boolean * Time: O() * Space: O() */ private Map<Integer, List<Integer>> graph = new HashMap<>(); private boolean[] visited = null; public boolean courseScheduleI(int numCourses, int[][] prerequisites) { if (prerequisites == null || prerequisites.length == 0) { return true; } graph = makeGraph(prerequisites); visited = new boolean[numCourses]; boolean[] visiting = new boolean[numCourses]; return true; } private boolean hasCycle(int node, boolean[] visiting) { if (!graph.containsKey(node)) { return false; } visiting[node] = true; // for (int nextNode: graph.get(node)) { // if (!visited[nextNode] && ) { // } return false; } private Map<Integer, List<Integer>> makeGraph(int[][] prerequisites) { Map<Integer, List<Integer>> graph = new HashMap<>(); for (int[] prerequisite: prerequisites) { int key = prerequisite[1]; int value = prerequisite[0]; if (graph.containsKey(key)) { List<Integer> list = graph.get(key); list.add(value); graph.put(key, list); } else { List<Integer> list = new ArrayList<>(); list.add(value); graph.put(key, list); } } // for (Entry entry: graph.entrySet()) { // System.out.println("key: " + entry.getKey() + ", Value: " + entry.getValue()); // } return graph; } /** * Method1: topological(BFS): use indegree of each node.Indegree means before you take this course, * you should take precourse. * Use graph loop to find 0 indegree course, means can take this course without any precourses * (or precourses has already been token). Then use this course as precourse, to update other * courses' indegree. * If the count of all 0 indegree courses is equal to numCourses, return true, * otherwise return false. * @param int numCourses, int[][] prerequisites * @return boolean * Time: O(n^2) n is the count of courses(can use a hash to build graph, then T=O(n), S=O(n)). * Space: O(n) */ public boolean courseSchedule(int numCourses, int[][] prerequisites) { if (prerequisites == null || prerequisites.length == 0) { return true; } int[] inDegree = new int[numCourses]; Map<Integer, Set<Integer>> graph = new HashMap<>(); // build graph and inDegree for (int[] p: prerequisites) { int u = p[1]; int v = p[0]; inDegree[v]++; if (!graph.containsKey(u)) graph.put(u, new HashSet<Integer>()); graph.get(u).add(v); } Queue<Integer> queue= new LinkedList<>(); for (int i = 0; i < inDegree.length; i++) { if (inDegree[i] == 0) queue.offer(i); } int count = 0; while (!queue.isEmpty()) { count++; int u = queue.poll(); if (!graph.containsKey(u)) continue; for (Integer v: graph.get(u)) { inDegree[v]--; if (inDegree[v] == 0) queue.offer(v); } } return count == numCourses; } public static void main(String[] args) { // TODO Auto-generated method stub CourseSchedule result = new CourseSchedule(); // System.out.println(result.courseSchedule(6, new int[][] {{4, 5}, {4, 0}, {1, 4}, {2, 1}, {2, 4}, {3, 2}})); System.out.println(result.courseScheduleI(6, new int[][] {{4, 5}, {4, 0}, {1, 4}, {2, 1}, {2, 4}, {3, 2}})); } }
Markdown
UTF-8
1,641
2.640625
3
[]
no_license
# Getting-Cleaning_data_assignment Getting-and-Cleaning-Data-Assignment ==================================== Coursera Course: Getting and Cleaning Data Assignment Submission Files - [run_analysis.R](https://github.com/gopalkrishan77/Getting-Cleaning_data_assignment/blob/master/run_analysis.R) - [README.md](https://github.com/gopalkrishan77/Getting-Cleaning_data_assignment/blob/master/README.md) - [codebook.md](https://github.com/gopalkrishan77/Getting-Cleaning_data_assignment/blob/master/codebook.md) Instructions 1. Checkout the code using 'git checkout https://github.com/rwstang/Getting-and-Cleaning-Data-Assignment.git YOURDIRECTORY' 2. Download the data set, https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip 3. Unzip the data set into a temporary folder and you should see a folder named UCI HAR Dataset. 4. Copy all folders and files from UCI HAR Dataset folder in to YOURDIRECTORY. You should now see test and train directory path as YOURDIRECTORY/test and YOURDIRECTORY/train 5. Load RStudio and set your working directory using setwd("YOURDIRECTORY") 6. Load the R script using source("run_analysis.txt") 7. Run the R script using run_analysis() and after execution of the function has finished, you will see that merged_tidy_data.txt and calculated_tidy_data.txt would have been replaced with the newest outputs. Dependencies 1. The R script assumes you have 'data.table' installed using install.packages("data.table") More Information For more information on the data set, please refer to http://archive.ics.uci.edu/ml/datasets/Human+Activity+Recognition+Using+Smartphones
PHP
UTF-8
763
2.640625
3
[]
no_license
<?php //update.php header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: PUT'); header('Content-Type: application/json'); header('Access-Control-Allow-Headers: Access-Control-Allow-Origin, Access-Control-Allow-Methods, Content-Type, Authorization, X-Requested-With'); //initializing the base files include_once('../../private/initialize.php'); //instantiate Sex file $sex = new Sex($dbh); //get posted data $data = json_decode(file_get_contents("php://input")); $sex->sexId = $data->sexId; $sex->longName = $data->longName; $sex->shortName = $data->shortName; //create Sex if($sex->update()){ echo json_encode(array('message' => 'Sex Updated Succesfully')); }else{ echo json_encode(array('message' => 'Sex Not Updated ')); } ?>
PHP
UTF-8
916
2.984375
3
[]
no_license
<?php //include_once ('../function.php'); include_once $_SERVER['DOCUMENT_ROOT']. 'function.php'; /** /** * Check du formulaire d'inscription * @param : nom, prenom, email, telephon, login, mot de passe * @return : Message d'erreur si l'url n'est pas saisie correctement */ class Logs{ private $message; public function __construct(string $message){ $this->message = $message; } public function GetMessage(){ return $this->message; } public function SaveLogs(){ $file = fopen( $_SERVER['DOCUMENT_ROOT']."/class/logs/logs.txt", "a+"); $ip = $_SERVER['REMOTE_ADDR']; $date = date("Y-m-d H:i:s"); $txt = "[".$ip."] [".$date."] ".$this->message.PHP_EOL; fwrite($file, $txt); fclose($file); } public function __toString(){ $out = "<------------------Logs-----------------><br>"; $out .= "<p> Message : ".$this->message."</p>"; return $out; } } ?>
C#
UTF-8
896
2.8125
3
[]
no_license
using System; using System.Linq; using ReactiveUI; using System.Text.RegularExpressions; using System.Drawing; namespace ReactiveExtensionExamples.ViewModels { public class ColorSlider : ReactiveObject { int _red; public int Red { get { return _red; } set { this.RaiseAndSetIfChanged (ref _red, value); } } int _green; public int Green { get { return _green; } set { this.RaiseAndSetIfChanged(ref _green, value); } } int _blue; public int Blue { get { return _blue; } set { this.RaiseAndSetIfChanged(ref _blue, value); } } ObservableAsPropertyHelper<Color> _color; public Color Color { get { return _color.Value; } } public ColorSlider () { this.WhenAnyValue ( x => x.Red, x => x.Green, x => x.Blue, (red, green, blue) => Color.FromArgb(255, red, green, blue) ) .ToProperty(this, v => v.Color, out _color); } } }
Python
UTF-8
1,399
2.765625
3
[]
no_license
# initialize DB for Blockchain # https://www.christopherlovell.co.uk/blog/2016/04/27/h5py-intro.html import h5py import numpy as np # # To create new DB # hf = h5py.File('database.h5', 'w') # hf.create_dataset('block_chain_db', data=[], compression="gzip", chunks=True, maxshape=(None,)) # hf.close() class transaction_data: def __init__(self,transaction): self.transaction = None self.verify_transaction_format(transaction) def verify_transaction_format(self,transaction): format = transaction.split('-') if len(format) == 3: self.transaction = transaction else: return "Transaction Format not correct" def add_block_to_db(transaction): new_data = np.array([transaction]) print("adding",new_data) print("datashape",new_data.shape[0]) with h5py.File('/Users/hssingh/PycharmProjects/block_chain/db/database.h5', 'a') as hf: hf["block_chain_db"].resize((hf["block_chain_db"].shape[0] + new_data.shape[0]), axis = 0) hf["block_chain_db"][-new_data.shape[0]:] = new_data hf.close() def view_db(): hf = h5py.File('/Users/hssingh/PycharmProjects/block_chain/db/database.h5', 'r') print(hf.keys()) np.set_printoptions(suppress=True, formatter={'float_kind': '{:f}'.format}) db = np.array(hf.get('block_chain_db')) return db
Java
UTF-8
779
2.359375
2
[]
no_license
package com.fyj.protobuf.nettybuf; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; public class TestClientHandler extends SimpleChannelInboundHandler<MyDataInfo.Person> { @Override protected void channelRead0(ChannelHandlerContext ctx, MyDataInfo.Person msg) throws Exception { } //从客户端发给服务器端,并且通过protobuf生成的序列化去发送过去 @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { MyDataInfo.Person person = MyDataInfo.Person.newBuilder() .setName("张三") .setAge(18) .setAddress("北京") .build(); ctx.channel().writeAndFlush(person); } }
Java
UTF-8
3,375
2.265625
2
[]
no_license
/** * */ package com.maohi.software.maohifx.samples.apachefop; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URISyntaxException; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.TransformerFactoryConfigurationError; import javax.xml.transform.sax.SAXResult; import javax.xml.transform.stream.StreamSource; import org.apache.fop.apps.FOPException; import org.apache.fop.apps.Fop; import org.apache.fop.apps.FopFactory; import org.apache.xmlgraphics.util.MimeConstants; import org.xml.sax.SAXException; /** * @author heifara * */ public class ApacheFOPSample { /** * @param args * @throws IOException * @throws SAXException * @throws TransformerException * @throws URISyntaxException * @throws TransformerFactoryConfigurationError */ public static void main(final String[] args) { new ApacheFOPSample().doMain(args); } /** * @param aArgs * @throws SAXException * @throws IOException * @throws FileNotFoundException * @throws FOPException * @throws TransformerFactoryConfigurationError * @throws TransformerConfigurationException * @throws TransformerException * @throws URISyntaxException */ private void doMain(final String[] aArgs) { try { // Step 1: Construct a FopFactory by specifying a reference to the configuration file // (reuse if you plan to render multiple documents!) final FopFactory iFopFactory = FopFactory.newInstance(this.getClass().getResource("fop.xconf").toURI()); // Step 2: Set up output stream. // Note: Using BufferedOutputStream for performance reasons (helpful with FileOutputStreams). final File iFile = new File("src/main/resources/myfile.pdf"); iFile.createNewFile(); try (final OutputStream iOutputStream = new BufferedOutputStream(new FileOutputStream(iFile));) { // Step 3: Construct fop with desired output format final Fop iFop = iFopFactory.newFop(MimeConstants.MIME_PDF, iOutputStream); // Step 4: Setup JAXP using identity transformer final TransformerFactory iTransformerFactory = TransformerFactory.newInstance(); final Transformer iTransformer = iTransformerFactory.newTransformer(); // identity transformer // Step 5: Setup input and output for XSLT transformation // Setup input stream final Source iSource = new StreamSource(new File(this.getClass().getResource("myfile.fo.xml").toURI())); // Resulting SAX events (the generated FO) must be piped through to FOP final Result iResult = new SAXResult(iFop.getDefaultHandler()); // Step 6: Start XSLT transformation and FOP processing iTransformer.transform(iSource, iResult); } catch (final Exception aException) { aException.printStackTrace(); } java.lang.Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + iFile.getAbsolutePath()); } catch (final Exception aException) { aException.printStackTrace(); } } }
JavaScript
UTF-8
574
2.640625
3
[ "MIT" ]
permissive
const amqp = require('amqplib'); async function consumer() { // 1. 创建链接对象 const connection = await amqp.connect('amqp://localhost:5672'); // 2. 获取通道 const channel = await connection.createChannel(); // 3. 声明参数 const queueName = 'helloworldQueue'; // 4. 声明队列,交换机默认为 AMQP default await channel.assertQueue(queueName); // 5. 消费 await channel.consume(queueName, msg => { console.log('Consumer:', msg.content.toString()); channel.ack(msg); }); } consumer();
Java
UTF-8
485
2.140625
2
[]
no_license
package com.entity; public class Config { private String paraname; private String paravalue; public String getParaname() { return paraname; } public void setParaname(String paraname) { this.paraname = paraname == null ? null : paraname.trim(); } public String getParavalue() { return paravalue; } public void setParavalue(String paravalue) { this.paravalue = paravalue == null ? null : paravalue.trim(); } }
Markdown
UTF-8
19,894
2.703125
3
[ "MIT", "CC-BY-4.0" ]
permissive
--- title: "Planning Step 4: Plan Application Security" author: rmcmurray description: "In this phase of building your website, consider the security needs of your ASP.NET application." ms.date: 04/14/2013 ms.assetid: fa53abca-5bda-4b1c-a35c-25610e76e78b msc.legacyurl: /learn/application-frameworks/scenario-build-an-aspnet-website-on-iis/planning-step-4-plan-application-security msc.type: authoredcontent --- # Planning Step 4: Plan Application Security by [Keith Newman and Robert McMurray](https://github.com/rmcmurray) In this phase of building your website, consider the security needs of your ASP.NET application. The following sections describe application security settings available in IIS 8: <a id="41"></a> ## 4.1. Isolate Web Applications One of the most effective ways to improve security for your web application is to isolate it from other applications on your web server. An application pool has its own worker process, which processes requests and runs application code. The worker process has a security identifier (SID). And each application pool has a unique application-pool identity. By default, when you create a web application, a new application pool is also created with the same name as the application. If you keep web applications in separate application pools, you can isolate them from one another. Web application isolation entails the following: - Site isolation: Separate different applications into different sites with different application pools. - Least privilege: Run your worker process as a low privileged identity (virtual application pool identity) that is unique per site. - Temp isolation: Set up a separate ASP.NET temp folder per site and only give access to appropriate process identity. - Content isolation: Make sure to set an ACL (access control list) on each site root to allow only access to the appropriate process identity. > [!TIP] > It is a good idea to host your website and web application content on a drive other than your system drive (C:). <a id="42"></a> ## 4.2. .NET Trust Levels An application *trust level* determines the permissions that the ASP.NET code access security (CAS) policy grants. CAS defines two trust categories: full trust and partial trust. An application that has full trust permissions can access all resource types on a server and perform privileged operations. Applications with full trust are affected only by the security settings of the operating system. Partial-trust web applications are applications that do not have full trust and have a restricted set of code access permissions. As a result, partial-trust applications are limited in their ability to access secured resources and perform other privileged operations. Certain permissions are denied to partial-trust applications, so resources that require those permissions cannot be directly accessed. Other permissions are granted in a restricted way, so resources that require those permissions might be accessible, but in a limited way. For example, restricted file IO permission give the application can access to the file system, but only in directories beneath the application's virtual directory root. By configuring a web application or web service for partial trust, you can restrict the application ability to access crucial system resources or resources that belong to other web applications. By granting only the permissions that the application requires and no more, you can build least privileged web applications and limit potential damage if the web application is compromised by a code injection attack. The following list shows the restrictions associated with each trust level: - Full trust applications have unrestricted access to all resource types and can perform privileged operations. - High, medium, low, or minimal trust applications are unable to call unmanaged code or serviced components, write to the event log, access Message Queuing queues, or access OLE DB data sources. - High trust applications have unrestricted access to the file system. - Medium trust applications have restricted file system access and can only access files in their own application-directory hierarchy. - Low or minimal trust applications cannot access SQL Server databases. - Minimal trust applications cannot access any resources. <a id="43"></a> ## 4.3. .NET Authentication Authentication helps you confirm the identity of clients who request access to your sites and applications. When authentication is enabled, IIS 8 uses the account credentials supplied by the user to determine what permissions the user has been granted and what resources the user can access. This section describes the authentication modes that are specific to ASP.NET applications. 1. [ASP.NET Forms Authentication](#431) 2. [ASP.NET Impersonation Authentication](#432) <a id="431"></a> ### ASP.NET Forms Authentication Forms authentication uses client-side redirection to forward unauthenticated users to an HTML form where they can enter their credentials, which are usually a user name and password. After the credentials are validated, users are redirected to the page they originally requested. Forms authentication often employs cookies to pass user credentials between the server and the client browser. The following sections describe what you need to know to plan adding forms authentication to your site: 1. [Forms authentication basics](#4311) 2. [Authentication cookies](#4312) <a id="4311"></a> #### Forms authentication basics ASP.NET Forms-based authentication works well for sites or applications on public web servers that receive many requests. This authentication mode lets you manage client registration and authentication at the application level, instead of relying on the authentication mechanisms the operating system provides. > [!IMPORTANT] > Because Forms authentication sends the user name and password to the web server as plaintext, use Secure Sockets Layer (SSL) encryption for the logon page and for all other pages in your application except the home page. For information about SSL, see [4.5. TLS/SSL Communication](#45). Forms authentication lets users log on by using identities from an ASP.NET membership database. This authentication method uses redirection to an HTML logon page to confirm the identity of the user. You can configure Forms authentication at the site or application levels. Forms authentication is convenient for the following reasons: - It allows either a custom data store, such as a SQL server database, or Active Directory to be used for authentication. - It integrates easily with a web user interface. - Clients can use any browser. If you want to use membership roles for authorization, use Forms authentication or a similar custom authentication method. > [!IMPORTANT] > If you select Forms authentication, you cannot use any of the challenge-based authentication methods at the same time. By default, the login URL for Forms authentication is Login.aspx. You can create a unique login page for clients who visit a site or application. For example, you might want to collect specific information from visitors, or offer membership to selected pages on the site or selected applications. The default time-out value for Forms authentication is 30 minutes. Consider changing the time-out value to a shorter period, to shorten the session lifetime and to reduce the chance of cookie replay attacks. <a id="4312"></a> #### Authentication cookies Authentication cookies are used as a token to verify that a client has access to some or all pages of an application. By contrast, personalization cookies contain user-specific settings that determine user experience on a specific site or application. Important: Because authentication cookies are passed between client and server together with every request, always secure authentication cookies using Secure Sockets Layer (SSL). For information about SSL, see [4.5. TLS/SSL Communication](#45). Cookies are a more efficient way to track visitors to a site than query strings, because they do not require redirection. However, they are browser-dependent, and some browsers do not support their use. In addition, the use of cookie-based authentication is not always effective because some users disable cookie support in their browsers. By default, the cookie name for ASP.NET applications is .ASPXAUTH. However, you can instead use a unique cookie name and path for each application. Doing so can prevent users who are authenticated for one application from being authenticated for other applications on a web server. You can choose one of the following cookie modes for your site or application: | Mode | Description | | --- | --- | | Use cookies | Cookies are always used regardless of device. | | Do not use cookies | Cookies are not used. | | Auto Detect | Cookies are used if the device profile supports cookies. Otherwise, no cookies are used. For desktop browsers that are known to support cookies, ASP.NET checks to determine whether cookies are enabled. This setting is the default. | | Use device profile | Cookies are used if the device profile supports cookies. Otherwise, no cookies are used. ASP.NET does not check to determine whether cookies are enabled on devices that support cookies. This setting is the default for IIS 8. | The cookie protection mode defines the function a Forms authentication cookie performs for a specific application. The following table shows the cookie protection modes that you can define: | Mode | Description | | --- | --- | | Encryption and validation | Specifies that the application use both data validation and encryption to help protect the cookie. This option uses the configured data validation algorithm (based on the machine key). If triple-DES (3DES) is available and if the key is long enough (48 bytes or more 3DES is used for encryption. This setting is the default (and recommended) value. | | None | Specifies that both encryption and validation are disabled for sites that are using cookies only for personalization and have weaker security requirements. We do not recommend that you use cookies in this manner; however, it is the least resource-intensive way to enable personalization by using the .NET Framework. | | Encryption | Specifies that the cookie is encrypted by using Triple-DES or DES, but data validation is not performed on the cookie. Cookies used in this manner might be subject to plaintext attacks. | | Validation | Specifies that a validation scheme verifies that the contents of an encrypted cookie have not been changed in transit. | > [!IMPORTANT] > For security reasons, consider keeping Encryption and Validation cookies separate from each other. The theft of encryption cookies would be a greater security exposure than the theft of validation cookies. If an application contains objects that clients request frequently, improve application performance by caching those objects. If the user accesses the cached object before the authentication cookie times out, IIS 8 allows the cached object to remain in the cache, and the timer is reset. However, if the user does not access the cached object during that time, IIS 8 removes the cached object from the cache. Consider enabling this setting under the following circumstances: - You have a limited amount of memory available for caching. - You have many objects to cache, because this setting allows only the most frequently requested objects to remain in the cache. > [!NOTE] > You specify the number of minutes before an authentication cookie times out with **Authentication cookie time-out (in minutes)**. <a id="432"></a> ### ASP.NET Impersonation Authentication Use ASP.NET impersonation when you want to run your ASP.NET application under a security context different from the default security context for ASP.NET applications. If you enable impersonation for an ASP.NET application, that application can run in one of two different contexts: either as the user authenticated by IIS 8 or as an arbitrary account that you set up. For example, if you use Anonymous authentication and choose to run the ASP.NET application as the authenticated user, the application would run under an account that is set up for anonymous users (typically, IUSR). Likewise, if you chose to run the application under an arbitrary account, it would run under whatever security context was set up for that account. By default, ASP.NET impersonation is disabled. If you enable impersonation, your ASP.NET application runs under the security context of the user authenticated by IIS 8. <a id="44"></a> ## 4.4. Machine Key Settings Machine keys help protect Forms authentication cookie data and page-level view state data. They also verify out-of-process session state identification. ASP.NET uses the following types of machine keys: - A *validation key* computes a Message Authentication Code (MAC) to confirm the integrity of the data. This key is appended to either the Forms authentication cookie or the view state for a specific page. - A *decryption key* is used to encrypt and decrypt Forms authentication tickets and view state. IIS 8 enables you to configure validation and encryption settings and generate machine keys for use with ASP.NET application services, such as view state, forms authentication, membership, roles, and anonymous identification. Before you generate machine keys for your application, make the following design decisions: - Decide what validation method to use: AES, MD5, SHA1 (default), TripleDES, HMACSHA256, HMACSHA384, or HMACSHA512. - Decide what encryption method to use: Auto (default), AES, TripleDES, or DES. - Decide whether to generate the validation key at runtime automatically. - Decide whether to generate a unique validation key for each application. - Decide whether to generate the decryption key at runtime automatically. - Decide whether to generate a unique decryption key for each application. <a id="45"></a> ## 4.5. TLS/SSL Communication Transport Layer Security (TLS) and its predecessor, Secure Sockets Layer (SSL) are protocols that provide communication security your website. You can use TLS/SSL to authenticate servers and clients and then use it to encrypt messages between the authenticated parties. In the authentication process, a TLS/SSL client sends a message to a TLS/SSL server, and the server responds with the information that the server needs to authenticate itself. The client and server perform an additional exchange of session keys, and the authentication dialog ends. When authentication is completed, SSL-secured communication can begin between the server and the client by using the symmetric encryption keys that are established during the authentication process. To configure TSL/SSL for your website, do the following: 1. Obtain a server certificate from a certification authority (CA). See [Server Certificates](#451). 2. Add SSL binding to the site. See [SSL Binding](#452). 3. Set IIS to require SSL on the site. See [Require SSL for Your Site](#453). 4. Consider using client certificates for your site. See [Client Certificates](#454). <a id="451"></a> ### Server Certificates You can obtain a server certificate from a certification authority (CA). Obtaining a server certificate from a certification authority is one step in configuring Secure Sockets Layer (SSL) or Transport Layer Security (TLS). You can obtain server certificates from a third-party CA. A third-party CA might require you to provide proof of identity before a certificate is issued. You can also issue your own server certificates by using an online CA, such as Microsoft Certificate Services. Digital certificates are electronic files that work like an online password to verify the identity of a user or a computer. They are used to create the SSL encrypted channel that is used for client communications. A certificate is a digital statement that is issued by a certification authority (CA) that vouches for the identity of the certificate holder and enables the parties to communicate in a secure manner by using encryption. Digital certificates do the following: - They authenticate that their holders-people, web sites, and even network resources such as routers-are truly who or what they claim to be. - They protect data that is exchanged online from theft or tampering. Digital certificates are issued by a trusted third-party CA or a Microsoft Windows public key infrastructure (PKI) using Certificate Services, or they can be self-signed. Each type of certificate has advantages and disadvantages. Each type of digital certificate is tamper-proof and can't be forged. Certificates can be issued for several uses. These uses include web user authentication, web server authentication, Secure/Multipurpose Internet Mail Extensions (S/MIME), Internet Protocol security (IPsec), Transport Layer Security (TLS), and code signing. A certificate contains a public key and attaches that public key to the identity of a person, computer, or service that holds the corresponding private key. The public and private keys are used by the client and the server to encrypt the data before it is transmitted. For Windows-based users, computers, and services, trust in a CA is established when there is a copy of the root certificate in the trusted root certificate store and the certificate contains a valid certification path. For the certificate to be valid, the certificate must not have been revoked and the validity period must not have expired. <a id="452"></a> ### SSL Binding You can assign multiple bindings to a site when you have site content that serves different purposes or for which you must use a different protocol. For example, a commerce site might have an application that requires that users log on to an account to purchase merchandise. The company hosts the site over HTTP, but users must log on to their account on an HTTPS page. In this example, the site would have two bindings: one for the HTTP portion and one for the HTTPS portion. Out of the box, you cannot add bindings for protocols other than HTTP and HTTPS by using IIS Manager. If you want to add a binding for a different protocol, such as a protocol supported by Windows Communication Foundation (WCF), use one of the other administration tools. However, if you install the IIS File Transfer Protocol (FTP) server, you can add FTP bindings by using IIS Manager. There might also be other modules or third-party functionality available for download that extend the UI. <a id="453"></a> ### Require SSL for Your Site Secure Sockets Layer (SSL) encryption protects confidential or personal information sent between a client and a server. When SSL is enabled, remote clients access your site by using URLs that start with https://. First configure a server certificate and create an HTTPS binding to enable any SSL settings. Then require Secure Sockets Layer (SSL) encryption in one or more of the following circumstances: 1. When confidential or personal content on your server must be protected by an encrypted channel. 2. When you want users to be able to confirm the identity of your server before they transmit personal information. 3. When you want to use client certificates to authenticate clients that access your server. <a id="454"></a> ### Client Certificates When you want clients to verify their identity before they access content on your web server, configure client certificates. By default, client certificates are ignored. Before you can configure client certificate on your website, configure a server certificate and create an HTTPS binding to enable any Secure Sockets Layer (SSL) settings. If you want all clients to verify their identity, specify that client certificates are required. If some clients can access content without first verifying their identity, specify that client certificates are accepted.
Python
UTF-8
18,534
2.65625
3
[]
no_license
import os import html import pymysql class Error(Exception): def __init__(self, e,msg): self.e = e self.msg = msg def __str__(self): return self.msg+':'+repr(self.e) class Model(object): """ python3 pymysql 操作MySQL数据库 """ config = { "host":'localhost', "user":'root', "passwd":'123456', "db":'boke', "port":3306, "charset":'utf8', "prefix" : '', "printSql":False } new = False init = False def __new__(cls,*args,**wkargs): if not cls.new: cls.new = super().__new__(cls) return cls.new def __init__(self,**kwargs): """初始化配置""" if self.init: return try: if kwargs: for k,v in kwargs.items(): self.config[k] = v self.config2 = self.config.copy() del self.config2['prefix'] del self.config2['printSql'] self.connect = pymysql.connect(**self.config2); self.cursor = self.connect.cursor(cursor=pymysql.cursors.DictCursor) self.STARTTRANS = False #默认关闭事务 self.init = True except Exception as e: raise Error(e,'数据库连接失败') def query(self,sql=''): """执行sql""" try: sql = sql or self.SQL self.cursor.execute(sql) fields_obj = self.cursor.fetchall() return fields_obj except Exception as e: raise Error(e,'查询错误sql:'+sql) def __table_as(self,tableName): """分离表面和别名""" tableName = tableName AS = tableName if ' as ' in tableName: table_as = tableName.split(' as ') tableName = table_as[0].strip() AS = table_as[1].strip() elif ' AS ' in tableName: table_as = tableName.split(' AS ') tableName = table_as[0].strip() AS = table_as[1].strip() return [tableName,AS] def table(self,tableName): """初始化表信息及查询条件""" try: self.WHERELIST = [] #存储多次wehre条件语句 self.WHERE = '' #存储完整的where条件语句 self.CONNECTION = "AND" #多条where条件连接符号(AND,OR) self.ORDERBY = '' #存储order by 语句 self.GROUPBY = '' #存储goup by 语句 self.LIMIT = '' #存储limit 语句 self.SQL = '' #完整SQL语句 tableName_as = self.__table_as(tableName) self.AS = self.config['prefix']+tableName_as[1] #表别名 self.tableName = self.config['prefix']+tableName_as[0] #表明 #查询表中的字段 self.COLUMN_NAME = [] #字段 self.COLUMN_COMMENT = [] #注释 self.COLUMN_KEY = [] #索引 self.SQL = "SELECT COLUMN_NAME,COLUMN_COMMENT,COLUMN_KEY from INFORMATION_SCHEMA.Columns where table_name='%s' and table_schema='%s'"%(self.tableName,self.config['db']); fields_obj = self.query(self.SQL) if not fields_obj: raise Error('Error','表 '+self.tableName+' 不存在') for row in fields_obj: self.COLUMN_NAME.append(row['COLUMN_NAME']) self.COLUMN_COMMENT.append(row['COLUMN_COMMENT']) self.COLUMN_KEY.append(row['COLUMN_KEY']) self.FIELDS = '`'+'`,`'.join(self.COLUMN_NAME)+'`' #默认查询字段(所有字段) except Exception as e: raise Error(e,'table') return self def field(self,fields=''): """指定查询字段""" if fields: fields = fields.split(',') fields_ = [] for f in fields: if f in self.COLUMN_NAME: fields_.append(f) if fields_: self.FIELDS = '`'+'`,`'.join(fields_)+'`' return self def connection(self,CONNECTION="AND"): """修改连接符号""" if CONNECTION.upper() == 'OR': self.CONNECTION == "OR" def where(self,conditions='',connection="AND"): ''' where条件 where("id=3") where({"id":2,"title":'test'}) where(['id',3]) where(['id|cid',3]) where(['id&cid',3]) ''' if not conditions: return self connection = " "+connection+" " WHERE = [] if isinstance(conditions,str):#字符串 self.WHERELIST.append(conditions) elif isinstance(conditions,dict):#字典 for k,v in conditions.items(): #只支持一层字典 if not isinstance(v,str) and not isinstance(v,int): continue if '|' in k: field = k.split('|') OR = [] for fd in field: if fd not in self.COLUMN_NAME: raise Error(fd+' 字段不存在','where') OR.append('`{}` = "{}"'.format(fd,str(v))) WHERE.append('('+' OR '.join(OR)+')') elif '&' in k: field = k.split('&') AND = [] for fd in field: if fd not in self.COLUMN_NAME: raise Error(fd+' 字段不存在','where') AND.append('`{}` = "{}"'.format(fd,str(v))) WHERE.append('( '+' AND '.join(AND)+' )') else: if k not in self.COLUMN_NAME: raise Error(k+' 字段不存在','where') WHERE.append('`{}` = "{}"'.format(k,str(v))) elif isinstance(conditions,list):#列表 lenght = len(conditions) if lenght < 2: return self elif lenght == 2: k = conditions[0] v = conditions[1] if '|' in k: field = k.split('|') OR = [] for fd in field: if fd not in self.COLUMN_NAME: raise Error(fd+' 字段不存在','where') OR.append('`{}` = "{}"'.format(fd,str(v))) WHERE.append('('+' OR '.join(OR)+')') elif '&' in k: field = k.split('&') AND = [] for fd in field: if fd not in self.COLUMN_NAME: raise Error(fd+' 字段不存在','where') AND.append('`{}` = "{}"'.format(fd,str(v))) WHERE.append('( '+' AND '.join(AND)+' )') else: if k not in self.COLUMN_NAME: raise Error(k+' 字段不存在','where') WHERE.append('`{}` = "{}"'.format(k,str(v))) elif lenght == 3: k = conditions[0] d = conditions[1] v = conditions[2] if '|' in k: field = k.split('|') OR = [] for fd in field: if fd not in self.COLUMN_NAME: raise Error(fd+' 字段不存在','where') OR.append('`{}` {} "{}"'.format(fd,d,str(v))) WHERE.append('('+' OR '.join(OR)+')') elif '&' in k: field = k.split('&') AND = [] for fd in field: if fd not in self.COLUMN_NAME: raise Error(fd+' 字段不存在','where') AND.append('`{}` {} "{}"'.format(fd,d,str(v))) WHERE.append('( '+' AND '.join(AND)+' )') else: if k not in self.COLUMN_NAME: raise Error(k+' 字段不存在','where') WHERE.append('`{}` {} "{}"'.format(k,d,str(v))) if WHERE: where_ = connection.join(WHERE) if len(WHERE) > 1: where_ = "( "+where_+" )" self.WHERELIST.append(where_) self.CONNECTION = " "+self.CONNECTION.strip()+" " self.WHERE = ' WHERE '+self.CONNECTION.join(self.WHERELIST) return self def order(self,orderby): """orderby的支持""" orderbylist = orderby.split(',') ORDERBY = [] for o in orderbylist: olist = o.split() if olist[0] not in self.COLUMN_NAME: raise Error(olist[0]+' 字段不存在','order') else: ORDERBY.append('`{}` {}'.format(olist[0],'' if olist[0] == olist[-1] else olist[-1])) self.ORDERBY = " ORDER BY "+','.join(ORDERBY) return self def group(self,groupby): """groupby的支持""" groupbylist = groupby.split(',') GROUPBY = [] for g in groupbylist: glist = g.split() if glist[0] not in self.COLUMN_NAME: raise Error(glist[0]+' 字段不存在','order') else: GROUPBY.append('`{}` {}'.format(glist[0],'' if glist[0] == glist[-1] else glist[-1])) self.GROUPBY = " GROUP BY "+','.join(GROUPBY) return self def limit(self,limit_): if isinstance(limit_,list): self.LIMIT = " limit {0},{1}".format(limit_[0],limit_[1]) elif isinstance(limit_,str): self.LIMIT = " limit "+limit_ elif isinstance(limit_,int): self.LIMIT = " limit "+str(limit_) else: raise Error(limit_,'limit 不支持的格式') return self def select(self): """查询数据""" self.SQL = "SELECT {FIELDS} FROM `{tableName}`{WHERE}{GROUPBY}{ORDERBY}{LIMIT}".format( FIELDS=self.FIELDS, tableName=self.tableName, WHERE=self.WHERE, GROUPBY=self.GROUPBY, ORDERBY=self.ORDERBY, LIMIT=self.LIMIT ) datas = self.query() return datas def find(self): """查询单条数据""" self.SQL = "SELECT {FIELDS} FROM `{tableName}`{WHERE}{GROUPBY}{ORDERBY}{LIMIT}".format( FIELDS=self.FIELDS, tableName=self.tableName, WHERE=self.WHERE, GROUPBY=self.GROUPBY, ORDERBY=self.ORDERBY, LIMIT='LIMIT 1' ) data = self.query() if not data: return {} return data[0] def value(self,field=""): """获取指定字段的值""" if not field: field = self.COLUMN_NAME[0] self.SQL = "SELECT {FIELDS} FROM `{tableName}`{WHERE}{GROUPBY}{ORDERBY}{LIMIT}".format( FIELDS=field, tableName=self.tableName, WHERE=self.WHERE, GROUPBY=self.GROUPBY, ORDERBY=self.ORDERBY, LIMIT=' LIMIT 1' ) data = self.query() if not data: return None return data[0][field] def column(self,fields=""): """返回数据中的指定列""" if not fields: fieldsList = self.COLUMN_NAME else: fieldsList = [] fields = fields.split(',') for f in fields: if f not in self.COLUMN_NAME: raise Error(f+' 字段不存在','column') else: fieldsList.append(f) fields = '`'+'`,`'.join(fieldsList)+'`' self.SQL = "SELECT {FIELDS} FROM `{tableName}`{WHERE}{GROUPBY}{ORDERBY}{LIMIT}".format( FIELDS=fields, tableName=self.tableName, WHERE=self.WHERE, GROUPBY=self.GROUPBY, ORDERBY=self.ORDERBY, LIMIT=self.LIMIT ) data = [] datas = self.query() if not datas: return {} if len(fieldsList) == 1: for v in datas: data.append(list(v.values())[0]) elif len(fieldsList) == 2: for v in datas: data.append({v[fieldsList[0]]:v[fieldsList[1]]}) else: for v in datas: data.append({v[fieldsList[0]]:v}) return data def count(self): self.SQL = "SELECT count(1) as count FROM `{tableName}`{WHERE}".format( tableName=self.tableName, WHERE=self.WHERE, ) data = self.query() return data[0]['count'] def max(self,field): self.SQL = "SELECT max(`{FIELD}`) as max FROM `{tableName}`{WHERE}".format( FIELD=field, tableName=self.tableName, WHERE=self.WHERE, ) data = self.query() return data[0]['max'] def min(self,field): self.SQL = "SELECT min(`{FIELD}`) as min FROM `{tableName}`{WHERE}".format( FIELD=field, tableName=self.tableName, WHERE=self.WHERE, ) data = self.query() return data[0]['min'] def avg(self,field): self.SQL = "SELECT avg(`{FIELD}`) as avg FROM `{tableName}`{WHERE}".format( FIELD=field, tableName=self.tableName, WHERE=self.WHERE, ) data = self.query() return data[0]['avg'] def sum(self,field): self.SQL = "SELECT sum(`{FIELD}`) as sum FROM `{tableName}`{WHERE}".format( FIELD=field, tableName=self.tableName, WHERE=self.WHERE, ) data = self.query() return data[0]['sum'] def startTrans(self): """开启事务""" self.STARTTRANS = True def commit(self): """提交事务""" self.connect.commit() self.STARTTRANS = False def rollback(self): """回滚事务""" self.connect.rollback() self.STARTTRANS = False def getAutoID(self): """获取自增ID""" self.SQL = "SELECT auto_increment FROM INFORMATION_SCHEMA.tables where table_name = '{tableName}' and table_schema = '{db}'".format(tableName=self.tableName,db=self.config['db']) return self.query()[0]['auto_increment'] def execute(self,sql=''): """执行sql""" try: sql = sql or self.SQL res = self.cursor.execute(sql) if res: if not self.STARTTRANS: self.connect.commit() insertid = self.cursor.lastrowid if insertid: return insertid else: return True else: self.connect.rollback() return False except Exception as e: raise Error(e,'column'+'sql执行错误:'+sql) def insert(self,datas=''): """添加数据""" if not datas: raise Error('没有任何数据可以添加','insert') valuesList = [] if isinstance(datas,dict):#添加一条 field = list(datas.keys()) valuesList.append(list(datas.values())) elif isinstance(datas,list):#添加多条 if not isinstance(datas[0],dict): raise Error('数据不合法','insert') field = list(datas[0].keys()) for v in datas: if not isinstance(v,dict): raise Error('数据不合法','insert') valuesList.append(list(v.values())) else: raise Error('数据不合法','insert') datas = [] for values in valuesList: d = [] for value in values: d.append(html.escape(str(value))) datas.append('("'+'","'.join(d)+'")') fields = '`'+'`,`'.join(field)+'`' self.SQL = "INSERT INTO `{tableName}`({fields}) values{values}".format(tableName=self.tableName,fields=fields,values=','.join(datas)) return self.execute() def update(self,datas): """修改数据""" filed_value = [] for k,v in datas.items(): filed_value.append('`{k}`="{v}"'.format(k=k,v=html.escape(str(v)))) filed_value = ','.join(filed_value) self.SQL = "UPDATE `{tableName}` SET {filed_value}{WHERE}".format(tableName=self.tableName,filed_value=filed_value,WHERE=self.WHERE) return self.execute() def delete(self,primarykey=""): """删除数据""" if primarykey: index = self.COLUMN_KEY.index('PRI') if isinstance(primarykey,list): values = ','.join([str(i) for i in primarykey]) elif isinstance(primarykey,str): values = primarykey self.WHERE = "WHERE {PRI} in({values})".format(PRI=self.COLUMN_NAME[index],values=values) self.SQL = "DELETE FROM `{tableName}`{WHERE}".format(tableName=self.tableName,WHERE=self.WHERE) return self.execute() def on(self,where): """on条件""" self.ON = where def ljoin(self): """left join""" def rjoin(self): """right join""" def join(self,tableName): """inner join""" tableName_as = self.__table_as(tableName) tableName = tableName_as[0] AS = tableName_as[1] self.SQL = "SELECT {FIELDS} FROM `{tableName}` AS {AS} INNER JOIN `{tableName2}` AS {AS2} ON {ON}{WHERE}{GROUPBY}{ORDERBY}{LIMIT}".format( FIELDS=self.FIELDS, tableName=self.tableName, tableName2=tableName, AS=self.AS, AS2=AS, ON=self.ON, WHERE=self.WHERE, GROUPBY=self.GROUPBY, ORDERBY=self.ORDERBY, LIMIT=self.LIMIT ) # datas = self.query() # return datas print(self.SQL) def __del__(self): try: if self.config['printSql']: print(self.SQL) self.cursor.colse() self.connect.colse() except Exception as e: pass model = Model().table('column as c').join('article as a').on('a.cid = c.cid') print(model)
Markdown
UTF-8
3,030
2.5625
3
[]
no_license
## Network ACL Is stateless ## Route propagation Allows a virtual private gateway to automatically propagate routes to the route tables. This means that you don't need to manually enter VPN routes to your route tables. It needs to enabled. ## Misc * There is no route connecting your VPC back to the on premise data center. * AD connector cannot change password from AWS SSO * Direct connect need redundent connection for HA * VPC advertise IP prefixes not VGW * BGP ASN * VGW can setup VPN from different region * Security groups blick traffic by default * NAT gateway in public subnet * PrivateLink (VPC endpoints) is to provide access to specific resource to multi VPCs, while VPC peering enable all resource to be accessiable across VPCs https://docs.aws.amazon.com/vpc/latest/userguide/vpc-endpoints.html * Ephemeral ports has to be allows in SG and NACL for ssh to work * S3 proxy is used to access S3 from outside VPC and not go through internet * ENI's MAC address is fixed * Once a VPC is set to Dedicated hosting, it can be changed back to default hosting via the CLI, SDK or API. Note that this will not change hosting settings for existing instances, only future ones. Existing instances can be changed via CLI, SDK or API but need to be in a stopped state to do so * VPC Flow Logs can be created at the VPC, subnet, and network interface levels. * The purpose of an "Egress-Only Internet Gateway" is to allow IPv6 based traffic within a VPC to access the Internet, whilst denying any Internet based resources the possibility of initiating a connection back into the VPC. ## VPC pearing * VPC peering doesn't have to be same region * Transitive routing is not supported, e.g. using another VPC's NAT gateway is not supported ## Direct Connection (DX) * Public virtual interface, private virtual interface * VPN has to use public vertual interface * It is defined as part of the AWS VPN configuration process. Direct Connect could be a carrier, but is not a VPN its self. ## VPN * Each VPN tunnel has two endpoints * ECMP (Equal Cost Multi Path) can be used to carry trffic on both VPN endpoints. * DX + VPN = hige performance + secure IPSEC * Hardware VPN is lower cost than software VPN * DNS Hostname should be enabled so EC2s lauched in the VPC has publis DNS name. * Secondary CIDR range can be added to VPC, route table will automatedly updated to allow this CIDR communicate internally within VPC * There are a number of ways to set up a VPN. AWS have a standard solution that makes use of a VPC with; a private subnet, Hardware VPN Access, a VPG, and an on-premise Customer Gateway. ## NAT * NAT gateway should be placed in publish subnet, it can be in private subnet, but internect connection won't work * You need to make sure routing table is route traffic correctly to NAT * NAT cannot work with IPv6, use Egress-only Internet Gateway instead ## Subnet * Each subnet reserves first 4 and last 1 IP https://docs.aws.amazon.com/whitepapers/latest/aws-vpc-connectivity-options/welcome.html
C++
UTF-8
1,750
3.3125
3
[]
no_license
// [contest] ABC 127 // [task] C // [URL] https://atcoder.jp/contests/abc127/tasks/abc127_c // [compiler] C++ 14 (GCC 5.4.1) // [status] https://atcoder.jp/contests/abc127/submissions/5817379 : TLE // [reference] // https://cpprefjp.github.io/reference/bitset/bitset.html #include <iostream> #include <bitset> #define num_cards_total_max 100000 int main (void) { // variables for main process int num_cards_total; int num_cards_passable; int num_gates; int index_card_left; int index_card_right; // STEP.01 // read out ... // 1. the number of the ID cards // 2. the number of the gates std::cin >> num_cards_total; std::cin >> num_gates; // STEP.02 // construct a status list of the cards whether they can pass through all gates alone std::bitset<num_cards_total_max> list; // STEP.03 // initialize the card status as all cards can pass through all gates independently for (size_t itr = 0; itr < num_cards_total; itr++) { list.set(itr); } // STEP.04 // judge whether the cards can pass through all gates alone for (size_t itr_gate = 0; itr_gate < num_cards_total; itr_gate++) { // STEP.04.01 // read out the data whether the cards can pass through the gate std::cin >> index_card_left; std::cin >> index_card_right; // STEP.04.02 // update the list of the cards whether they can pass through all gates alone for (size_t itr_card = 0; itr_card < index_card_left - 1; itr_card++) { list.reset(itr_card); } for (size_t itr_card = num_cards_total - 1; itr_card >= index_card_right; itr_card--) { list.reset(itr_card); } } // STEP.05 // output the number of cards which can pass through all gates alone std::cout << list.count() << std::endl; // STEP.END return 0; }
C++
UTF-8
664
3.21875
3
[]
no_license
class Solution { public: void rotate(vector<int>& nums, int k) { int size = nums.size(); if (k > size) { k = k % size; } if (k != 1){ /* 由于vector的insert的操作会使得迭代器失效,因此需要使用额外空间。 这里提高了代码空间复杂度 */ vector<int> extraSpace(nums.begin() + size - k, nums.end()); nums.insert(nums.begin(), extraSpace.begin(), extraSpace.end()); }else{ nums.insert(nums.begin(), nums[size - 1]); } nums.erase(nums.begin() + size, nums.end()); } };
Python
UTF-8
1,351
3.015625
3
[]
no_license
import pandas as pd import matplotlib.pyplot as plt import csv import numpy as np import pandas from bokeh.plotting import figure, show from bokeh.io import output_file from bokeh.models import ColumnDataSource machines = pd.read_csv("MachineData.csv") machines.head() machines.shape print(machines) """type(False) booleans = [] for l in machines.machineID: if l == 1: booleans.append(True) else: booleans.append(False) print(booleans[0:5])""" """type(False) booleans = [] for number in machines.machineID: if number == 1: booleans.append(True) else: booleans.append(False) print(booleans[0:5]) print(len(booleans)) machine_one = pd.Series(booleans) """ machine_one = (machines.machineID == 4) #print(machine_one.head()) print(machines[machine_one]) #print(machine_one) fig = plt.figure(1, figsize=(13, 6)) voltList = (machines[machine_one])['volt'].tolist() datetimeList = (machines[machine_one])['datetime'].tolist() machineList = (machines[machine_one])['machineID'].tolist() plt.plot(datetimeList, voltList, label='Voltage', color='y', marker='o', markerfacecolor='k', linestyle='-', linewidth=3) plt.xlabel('Date & time') plt.ylabel('Volt') plt.legend(loc='lower right') plt.title('Voltage measure machine 4') plt.xticks(size=4, rotation=45) plt.show() #machines.head()
TypeScript
UTF-8
1,245
2.65625
3
[ "MIT" ]
permissive
import { Injectable } from '@nestjs/common'; import { UserAlreadyRegisteredException } from '../../domain/exceptions/user.exception'; import { UserDto } from '../../presentation/dtos/user.dto'; import { UserModel } from '../models/user.model'; import { UserCRUDInfos } from '../interfaces/user.interface'; import { UserRepository } from '../../infrastructure/database/repositories/user.repository'; @Injectable() export class UserUseCase { constructor(private readonly userRepository: UserRepository) {} async findAll(): Promise<UserModel[]> { return await this.userRepository.findAll(); } async create(userDto: UserDto): Promise<UserCRUDInfos> { const user = await this.findOneByEmail(userDto.email); if (user) throw new UserAlreadyRegisteredException(); const createdUser: UserDto = await this.userRepository.create(userDto); return { userId: createdUser.id, message: `user successfully added` } as UserCRUDInfos; } async remove(id: string | number): Promise<UserCRUDInfos> { await this.userRepository.remove(id); return { userId: id, message: `user successfully deleted` } as UserCRUDInfos; } async findOneByEmail(email: string): Promise<UserModel> { return await this.userRepository.findOne({ email: email }); } }
Python
UTF-8
8,440
2.78125
3
[]
no_license
import os import cv2 import numpy as np from matplotlib import pyplot as plt from patchify import patchify from PIL import Image from sklearn.preprocessing import MinMaxScaler, StandardScaler # from tensorflow.keras.utils import to_categorical scaler = MinMaxScaler() def load_image(root_directory, patch_size=256): image_dataset = [] for path, subdirs, files in os.walk(root_directory): # print(path) dirname = path.split(os.path.sep)[-1] if dirname == 'images': # Find all 'images' directories images = sorted(os.listdir(path)) # List of all image names in this subdirectory for i, image_name in enumerate(images): if image_name.endswith(".jpg"): # Only read jpg images... image = cv2.imread(path + "/" + image_name, 1) # Read each image as BGR SIZE_X = (image.shape[1] // patch_size) * patch_size # Nearest size divisible by our patch size SIZE_Y = (image.shape[0] // patch_size) * patch_size # Nearest size divisible by our patch size image = Image.fromarray(image) image = image.crop((0, 0, SIZE_X, SIZE_Y)) # Crop from top left corner # image = image.resize((SIZE_X, SIZE_Y)) #Try not to resize for semantic segmentation image = np.array(image) # Extract patches from each image print("Now patchifying image:", path + "/" + image_name) patches_img = patchify(image, (patch_size, patch_size, 3), step=patch_size) # Step=256 for 256 patches means no overlap # print(patches_img.shape) for i in range(patches_img.shape[0]): for j in range(patches_img.shape[1]): single_patch_img = patches_img[i, j] # Use min-max scaler instead of just dividing by 255. single_patch_img = scaler.fit_transform( single_patch_img.reshape(-1, single_patch_img.shape[-1])).reshape(single_patch_img.shape) # single_patch_img = (single_patch_img.astype('float32')) / 255. single_patch_img = single_patch_img[ 0] # Drop the extra unecessary dimension that patchify adds. image_dataset.append(single_patch_img) return np.array(image_dataset, dtype=np.float32) # Now do the same as above for masks # For this specific dataset we could have added masks to the above code as masks have extension png def load_mask(root_directory, patch_size=256): mask_dataset = [] for path, subdirs, files in os.walk(root_directory): # print(path) dirname = path.split(os.path.sep)[-1] if dirname == 'masks': # Find all 'images' directories masks = sorted(os.listdir(path)) # List of all image names in this subdirectory for i, mask_name in enumerate(masks): if mask_name.endswith(".png"): # Only read png images... (masks in this dataset) mask = cv2.imread(path + "/" + mask_name, 1) # Read each image as Grey (or color but remember to map each color to an integer) mask = cv2.cvtColor(mask, cv2.COLOR_BGR2RGB) SIZE_X = (mask.shape[1] // patch_size) * patch_size # Nearest size divisible by our patch size SIZE_Y = (mask.shape[0] // patch_size) * patch_size # Nearest size divisible by our patch size mask = Image.fromarray(mask) mask = mask.crop((0, 0, SIZE_X, SIZE_Y)) # Crop from top left corner # mask = mask.resize((SIZE_X, SIZE_Y)) #Try not to resize for semantic segmentation mask = np.array(mask) # Extract patches from each image print("Now patchifying mask:", path + "/" + mask_name) patches_mask = patchify(mask, (patch_size, patch_size, 3), step=patch_size) # Step=256 for 256 patches means no overlap for i in range(patches_mask.shape[0]): for j in range(patches_mask.shape[1]): single_patch_mask = patches_mask[i, j] # single_patch_img = (single_patch_img.astype('float32')) / 255. # #No need to scale masks, but you can do it if you want single_patch_mask = single_patch_mask[ 0] # Drop the extra unecessary dimension that patchify adds. mask_dataset.append(single_patch_mask) mask_dataset = np.array(mask_dataset) labels = [] for i in range(mask_dataset.shape[0]): label = rgb_to_2d_label(mask_dataset[i]) labels.append(label) return labels # Sanity check, view few mages # image_number = np.random.randint(0, len(image_dataset)) # plt.figure(figsize=(12, 6)) # plt.subplot(121) # plt.imshow(np.reshape(image_dataset[image_number], (patch_size, patch_size, 3))) # plt.subplot(122) # plt.imshow(np.reshape(mask_dataset[image_number], (patch_size, patch_size, 3))) # plt.show() ########################################################################### """ RGB to HEX: (Hexadecimel --> base 16) This number divided by sixteen (integer division; ignoring any remainder) gives the first hexadecimal digit (between 0 and F, where the letters A to F represent the numbers 10 to 15). The remainder gives the second hexadecimal digit. 0-9 --> 0-9 10-15 --> A-F Example: RGB --> R=201, G=, B= R = 201/16 = 12 with remainder of 9. So hex code for R is C9 (remember C=12) Calculating RGB from HEX: #3C1098 3C = 3*16 + 12 = 60 10 = 1*16 + 0 = 16 98 = 9*16 + 8 = 152 """ # Convert HEX to RGB array # Try the following to understand how python handles hex values... # a = int('3C', 16) # 3C with base 16. Should return 60. # print(a) # Do the same for all RGB channels in each hex code to convert to RGB Building = '#3C1098'.lstrip('#') Building = np.array(tuple(int(Building[i:i + 2], 16) for i in (0, 2, 4))) # 60, 16, 152 Land = '#8429F6'.lstrip('#') Land = np.array(tuple(int(Land[i:i + 2], 16) for i in (0, 2, 4))) # 132, 41, 246 Road = '#6EC1E4'.lstrip('#') Road = np.array(tuple(int(Road[i:i + 2], 16) for i in (0, 2, 4))) # 110, 193, 228 Vegetation = 'FEDD3A'.lstrip('#') Vegetation = np.array(tuple(int(Vegetation[i:i + 2], 16) for i in (0, 2, 4))) # 254, 221, 58 Water = 'E2A929'.lstrip('#') Water = np.array(tuple(int(Water[i:i + 2], 16) for i in (0, 2, 4))) # 226, 169, 41 Unlabeled = '#9B9B9B'.lstrip('#') Unlabeled = np.array(tuple(int(Unlabeled[i:i + 2], 16) for i in (0, 2, 4))) # 155, 155, 155 # label = single_patch_mask # Now replace RGB to integer values to be used as labels. # Find pixels with combination of RGB for the above defined arrays... # if matches then replace all values in that pixel with a specific integer def rgb_to_2d_label(label): """ Suply our labale masks as input in RGB format. Replace pixels with specific RGB values ... """ label_seg = np.zeros(label.shape, dtype=np.uint8) label_seg[np.all(label == Building, axis=-1)] = 0 label_seg[np.all(label == Land, axis=-1)] = 1 label_seg[np.all(label == Road, axis=-1)] = 2 label_seg[np.all(label == Vegetation, axis=-1)] = 3 label_seg[np.all(label == Water, axis=-1)] = 4 label_seg[np.all(label == Unlabeled, axis=-1)] = 5 label_seg = label_seg[:, :, 0] # Just take the first channel, no need for all 3 channels return label_seg def label_2d_to_rgb(label): rgb_label = np.zeros((label.shape + (3,)), dtype=np.uint8) rgb_label[label == 0] = Building rgb_label[label == 1] = Land rgb_label[label == 2] = Road rgb_label[label == 3] = Vegetation rgb_label[label == 4] = Water rgb_label[label == 5] = Unlabeled return rgb_label # Another Sanity check, view few mages # image_number = np.random.randint(0, len(image_dataset)) # plt.figure(figsize=(12, 6)) # plt.subplot(121) # plt.imshow(image_dataset[image_number]) # plt.subplot(122) # plt.imshow(labels[image_number][:, :, 0]) # plt.show()
PHP
UTF-8
566
2.609375
3
[]
no_license
<?php include("includes/header.php"); include("includes/navbar.php"); include("database/dbconfig.php"); if(!empty($_POST['cat_id'])) { $id = intval($_POST['cat_id']); $query = mysqli_query($con , "SELECT * FROM subcategory WHERE categoryid=$id"); ?> <option value="">Select Subcategory</option> <?php while($row = mysqli_fetch_array($query)) {?> <option value=" <?php echo htmlentities($row['id']); ?>"> <?php echo htmlentities($row['subcategory']); ?> </option> <?php } } ?>
Python
UTF-8
4,505
3.28125
3
[ "MIT" ]
permissive
import logging import re from entity import Entity from entitylist import EntityList, KnnEntityList, PolynomialEntityList, \ ExponentialEntityList, SvrEntityList from errors import WarnValueError, KillValueError blank_matcher = re.compile("^\\s*$") logging.basicConfig() logger = logging.getLogger(__name__) class EntityListBuilder(object): """ An object that will construct a list of Entity objects from a string input line. """ def __init__(self, list_type, limit=None): """Initialise an EntityListBuilder""" from sys import maxsize self.__list_names = {} self.list_type = list_type self.limit = maxsize if limit is None else limit self._entity_dict = {} def build_list_from_string(self, string, limit=None): """ Build a new EntityList object from a supplied string of data The supplied string is assumed to contain the data in tab-delimited columns. The first column is the list category name. The second column is the list name. The third column describes the list's 'ranked' status. The fourth column is currently ignored. Columns subsequent to that are assumed to be the names of Entities within the list. If the string is too short, then the function throws an exception :param string: :param limit: The maximum number of entries to be contained in the list :return: """ columns = string.strip().split("\t") if len(columns) < 4: raise WarnValueError('Insufficient columns to create an ' 'EntityList') if columns[1] in self.__list_names: raise KillValueError('List with that name already exists') is_ranked = columns[2].strip().upper() == "RANKED" entity_list = self.get_appropriate_entitylist(is_ranked) entity_list.is_ranked = is_ranked entity_list.category_name = columns[0] entity_list.name = columns[1] self.__list_names[columns[1]] = entity_list if limit is None: limit = self.limit counter = 0 for x in range(4, len(columns)): m = blank_matcher.match(columns[x]) if m: logger.warning("Found an empty column - column %d in list '%s'" % (x + 1, columns[1])) else: if counter == limit: # warn if items are omitted? logger.warning("Some data in list '%s' was ignored due to " "a limit on list lengths (%s). Up to %d " "columns were skipped." % (columns[1], limit, len(columns) - x)) return entity_list entity = self.get_or_create_entity(columns[x]) entity_list.append(entity) counter = len(entity_list) return entity_list def get_appropriate_entitylist(self, ranked): """ Given the parameters of ranked and type then return an EntityList object of an appropriate type :param ranked: boolean - is this list a ranked list :return: an appropriate EntityList object """ assert ranked is not None # entity_list = None if not ranked or self.list_type == 'none': entity_list = EntityList() elif self.list_type == 'knn': entity_list = KnnEntityList() elif self.list_type == 'polynomial': entity_list = PolynomialEntityList() elif self.list_type == 'exponential': entity_list = ExponentialEntityList() elif self.list_type == 'svr': entity_list = SvrEntityList() else: logger.warning("Unrecognised EntityList Type ('%s'). Returning an " "unranked EntityList." % self.list_type) entity_list = EntityList() return entity_list def get_or_create_entity(self, entity_name): """ Return the Entity corresponding to the supplied entity_name, creating it if required. """ if entity_name not in self._entity_dict: self._entity_dict[entity_name] = Entity(entity_name) return self._entity_dict[entity_name] def entities(self): """Return a list of all the entities we have created""" return list(self._entity_dict.values())
Python
UTF-8
6,097
2.78125
3
[ "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause" ]
permissive
# Path Planner # Tung M. Phan # May 15th, 2018 # California Institute of Technology import os import sys sys.path.append('..') import time import random import prepare.queue as queue import prepare.car_waypoint_graph as waypoint_graph import primitives.tubes import numpy as np if __name__ == '__main__': visualize = True else: visualize = False collision_dictionary = np.load('prepare/collision_dictionary.npy').item() edge_to_prim_id = np.load('prepare/edge_to_prim_id.npy').item() def dijkstra(start, end, graph): ''' this function takes in a weighted directed graph, a start node, an end node and outputs the shortest path from the start node to the end node on that graph input: start - start node end - end node graph - weighted directed graph output: shortest path from start to end node ''' if start == end: # if start coincides with end return 0, [start] else: # otherwise score = {} predecessor = {} unmarked_nodes = graph._nodes.copy() # create a copy of set of nodes in graph if start not in graph._nodes or end not in graph._nodes: raise SyntaxError( "either the start or end node is not in the graph!") for node in graph._nodes: if node != start: score[node] = float('inf') # initialize all scores to inf else: score[node] = 0 # start node is initalized to 0 current = start # set currently processed node to start node while current != end: if current in graph._edges: for neighbor in graph._edges[current]: new_score = score[current] + \ graph._weights[(current, neighbor)] if score[neighbor] > new_score: score[neighbor] = new_score predecessor[neighbor] = current unmarked_nodes.remove(current) # mark current node min_node = None # find unmarked node with lowest score score[min_node] = float('inf') for unmarked in unmarked_nodes: # need equal sign to account to ensure dummy "None" value is replaced if score[unmarked] <= score[min_node]: min_node = unmarked current = min_node # set current to unmarked node with min score shortest_path = [end] if score[end] != float('inf'): start_of_suffix = end while predecessor[start_of_suffix] != start: shortest_path.append(predecessor[start_of_suffix]) start_of_suffix = predecessor[start_of_suffix] # add start node then reverse list shortest_path.append(start) shortest_path.reverse() else: shortest_path = [] return score[end], shortest_path def get_scheduled_times(path, current_time, primitive_graph): ''' this function takes in a path and computes the scheduled times of arrival at the nodes on this path input: path - the path whose nodes the user would like to compute the scheduled times of arrival for output: a tuple of scheduled times (of arrival) at each node ''' now = current_time scheduled_times = [now] for prev, curr in zip(path[0::1], path[1::1]): scheduled_times.append( scheduled_times[-1] + primitive_graph._weights[(prev, curr)]) return scheduled_times def time_stamp_edge(path, edge_time_stamps, current_time, primitive_graph): ''' given a weighted path, this function updates the edge_time_stamps set according to the given path. input: path - weighted path output: modifies edge_time_stamps ''' scheduled_times = get_scheduled_times( path=path, current_time=current_time, primitive_graph=primitive_graph) for k in range(0, len(path)-1): left = k right = k+1 # interval stamp stamp = (scheduled_times[left], scheduled_times[right]) # only get topographical information, ignoring velocity and orientation edge = (path[left], path[right]) try: edge_time_stamps[edge_to_prim_id[edge]].add(stamp) except KeyError: edge_time_stamps[(edge_to_prim_id[edge])] = {stamp} return edge_time_stamps def is_overlapping(interval_A, interval_B): ''' this subroutine checks if two intervals intersect with each other; it returns True if they do and False otherwise input : interval_A - first interval interval_B - second interval output: is_intersecting - True if interval_A intersects interval_B, False otherwise ''' is_disjoint = (interval_A[0] > interval_B[1]) or ( interval_B[0] > interval_A[1]) return not is_disjoint def is_safe(path, current_time, primitive_graph, edge_time_stamps): now = current_time scheduled_times = [now] for left_node, right_node in zip(path[0::1], path[1::1]): curr_edge = (left_node, right_node) curr_prim_id = edge_to_prim_id[curr_edge] scheduled_times.append( scheduled_times[-1] + primitive_graph._weights[curr_edge]) left_time = scheduled_times[-2] right_time = scheduled_times[-1] curr_interval = (left_time, right_time) # next interval to check for colliding_id in collision_dictionary[curr_prim_id]: if colliding_id in edge_time_stamps: # if current loc is already stamped for interval in edge_time_stamps[colliding_id]: # if the two intervals overlap if is_overlapping(curr_interval, interval): return False return True def print_state(): print('The current request queue state is') request_queue.print_queue() def generate_license_plate(): import string choices = string.digits + string.ascii_uppercase plate_number = '' for i in range(0, 7): plate_number = plate_number + random.choice(choices) return plate_number
Java
UTF-8
972
3.78125
4
[]
no_license
public abstract class Poly { public Poly() {} public abstract double [] poly(); public abstract double f(double x); public abstract void printSolution(); } class Poly8 extends Poly{ @Override public double[] poly() { //inverse order return new double[]{ 3, 131, 514, -209, -634, 280, 119, -55 }; } @Override public double f(double x) { return (-55 * Math.pow(x, 7)+119 * Math.pow(x, 6) + 280 * Math.pow(x, 5) -634 * Math.pow(x, 4) -209 * Math.pow(x, 3) +514 * Math.pow(x, 2) +131*x + 3); } @Override public void printSolution(){ LobachevskyMethod lobachevskyMethod = new LobachevskyMethod(); double [] x = lobachevskyMethod.Do(this); System.out.println("Решение полинома по методу Лобачевского:"); for (int i = 0; i < x.length; i++){ System.out.printf("\nx%d = %.3f", i, x[i]); } } }
Markdown
UTF-8
2,357
3.203125
3
[ "MIT" ]
permissive
# PHP-WordWrap ![GitHub](https://img.shields.io/github/license/kayw-geek/php-wordwrap)![php-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg)![GitHub top language](https://img.shields.io/github/languages/top/kayw-geek/php-wordwrap) Word wrapping, with a few features. - force-break option - wraps hypenated words - multilingual - wraps any language that uses whitespace for word separation. - custom symbol wrap mode - chain call - multi-format return ## Install ```shell composer require kayw-geek/php-wordwrap ``` ## Synopsis Wrap some text in a 20 character column. ```php > $wrap = new \KaywGeek\WordWrap(); > $text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; > $result = $wrap->text($text)->width(20)->wrap(); ``` `result` now looks like this: ``` Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ``` By default, long words will not break. Unless you set the `break` option. ```php > $text = "https://github.com/kayw-geek/php-wordwrap" > $wrap->text($text)->width(28)->break(false)->wrap(); https://github.com/kayw-geek/php-wordwrap > $wrap->text($text)->width(28)->break()->wrap(); https://github.com/kayw-geek /php-wordwrap ``` Punctuation wrap mode ```php > $text = "Of course,the first example appears to be the nicest one (or perhaps the fourth),but you may find that being able to use empty expressions in for loops comes in handy in many occasions."; > $wrap->text($text)->lfEnable()->wrap(); ``` `result` ``` Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions. ``` Format data ```php > $text = "Of course,the first example appears to be the nicest one (or perhaps the fourth),but you may find that being able to use empty expressions in for loops comes in handy in many occasions."; /** * Format List * \KaywGeek\WordWrap::FORMAT_JSON * \KaywGeek\WordWrap::FORMAT_STRING * \KaywGeek\WordWrap::FORMAT_ARRAY */ > $wrap->text($text) ->lfEnable() ->responseFormat(\KaywGeek\WordWrap::FORMAT_JSON) ->wrap(); ``` ## Inspiration [wordwrapjs](https://github.com/75lb/wordwrapjs)
Python
UTF-8
272
3.328125
3
[]
no_license
def sum_of_multiples(maxNum, factors): multiples = [] for factor in factors: if factor != 0: for num in range(factor, maxNum, factor): if num not in multiples: multiples.append(num) return sum(multiples)
C#
UTF-8
769
3.234375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileReader.Readers { class Inverts : IReader { public string Name() { return "inverts"; } public string Read(string path) { String cadena = ""; List<string> lista = new List<string>(); String[] lines = System.IO.File.ReadAllLines(path); for (int i = 0; i < lines.Length; i++) { lista.Add(lines[i]); } lista.Reverse(); foreach (string ili in lista) { cadena += ili + "\n"; } return cadena; } } }
JavaScript
UTF-8
13,088
2.6875
3
[]
no_license
import React from 'react'; import ReactDOM from 'react-dom'; import AddAnswer from './AddAnswer'; import Modal from 'react-modal'; import MyStatefulEditor from './MyStatefulEditor'; export default class AddQuestion extends React.Component { constructor(props) { super(props); this.handleChangeSelect = this.handleChangeSelect.bind(this); this.changeCategory = this.changeCategory.bind(this); this.addAnswer = this.addAnswer.bind(this); this.changePlusPoints = this.changePlusPoints.bind(this); this.addQuestion = this.addQuestion.bind(this); this.renderCategory = this.renderCategory.bind(this); this.changeEditorState = this.changeEditorState.bind(this); this.changeMinusPoints = this.changeMinusPoints.bind(this); //this.changeName = this.changeName.bind(this); this.changeQuestionName = this.changeQuestionName.bind(this); this.state = { options: ['/c', '/u', '/t'], //T je jedan a C vise categoryOptions: [], checkBoxVisibility: false, inputAnswerVisibility: false, answerList: [], plusPoints: '', expand: false, questionText : '', question : {} }; } componentDidMount() { var quizUrl = 'http://localhost:8080/categories'; fetch(quizUrl, { mode: 'cors', method: "GET", response: true }) .then(res => res.json()) .then(data => this.setState({ categoryOptions: data })); } changePlusPoints(event) { this.setState({ plusPoints: event.target.value }) } changeMinusPoints(event) { let question = Object.assign({}, this.state.question); //creating copy of object question.minusPoints = event.target.value; //updating value this.setState({question}); } changeQuestionName(event){ let question = Object.assign({}, this.state.question); //creating copy of object question.name = event.target.value; //updating value this.setState({question}); } handleChangeSelect(event) { let choosen = event.target.value; let question = Object.assign({}, this.state.question); //creating copy of object question.type = choosen; //updating value this.setState({question}); if (choosen === '/c') { console.log("c, need answers"); this.setState({ checkBoxVisibility: true, inputAnswerVisibility: true, expand: true }) } else if (choosen === '/t') { console.log('/t'); this.setState({ checkBoxVisibility: true, inputAnswerVisibility: true, expand: true }) } else if (choosen === '/u') { console.log('u'); this.setState({ checkBoxVisibility: false, inputAnswerVisibility: true, expand: true }) } } changeCategory(event) { event.preventDefault(); console.log(" i " + event.target.value); let choosen = event.target.value; let question = Object.assign({}, this.state.question); //creating copy of object question.category = choosen; //updating value this.setState({question}); if (choosen === "EASY") { this.setState({ plusPoints: 1.0 }) } else if (choosen === "MEDIUM") { this.setState({ plusPoints: 2.0 }) } else if (choosen === "HARD") { this.setState({ plusPoints: 3.0 }) } } addAnswer(answer) { var newArray = this.state.answerList.slice(); newArray.push(answer); this.setState({ answerList: newArray }); } /* addQuestion(e) { e.preventDefault(); const question = {}; question.name = e.target.elements.questionName.value; question.text = this.state.questionText; question.type = e.target.elements.questionType.value; question.category = e.target.elements.questionCategory.value; question.plusPoints = e.target.elements.questionPlusPoints.value; question.minusPoints = e.target.elements.questionMinusPoints.value; question.answerList = this.state.answerList; let sectionId = this.props.sectionId; const url = 'http://localhost:8080/addQuestion/' + sectionId; let fetchData = { method: 'POST', headers: { 'Content-Type': 'application/json', }, response: true, body: JSON.stringify(question) } fetch(url, fetchData) .then(res => res.json()) .then(data => this.setState({ answerList: [] })); e.target.elements.questionName.value = ''; //e.target.elements.questionText.value = ''; e.target.elements.questionType.value = ''; e.target.elements.questionPlusPoints.value = ''; e.target.elements.questionMinusPoints.value = ''; } */ addQuestion(){ const question = {}; question.name = this.state.question.name; question.text = this.state.questionText; question.type = this.state.question.type; question.category = this.state.question.category; question.plusPoints = this.state.plusPoints; question.minusPoints =this.state.question.minusPoints; question.answerList = this.state.answerList; let sectionId = this.props.sectionId; const url = 'http://localhost:8080/addQuestion/' + sectionId; let fetchData = { method: 'POST', headers: { 'Content-Type': 'application/json', }, response: true, body: JSON.stringify(question) } fetch(url, fetchData) .then(res => res.json()) .then(data => this.setState({ answerList: [] })); // e.target.elements.questionName.value = ''; //e.target.elements.questionText.value = ''; // e.target.elements.questionType.value = ''; //e.target.elements.questionPlusPoints.value = ''; // e.target.elements.questionMinusPoints.value = ''; } changeEditorState(editorText){ this.setState({ questionText: editorText }) } renderCategory(category) { if (category == "EASY") { return "Lak" } else if (category == "MEDIUM") { return "Srednje" } else if (category == "HARD") { return "Tezak" } } renderAnswers() { return this.state.answerList.map(answer => ( <tr key={answer.text}> {/* <td>{answer.text}</td> */} <td>{answer.text.substring(0,15) + "..."} <span className="spnTooltip"> {answer.text} </span> </td> <td>{answer.exactitude ? 'tačan' : 'netačan'}</td> </tr> )) } renderTableWithAnswers() { return ( <div className="scroll-answers row"> <div className = " offset-lg-1 col-lg-10"> <table className="table table-hover " > <thead> <tr > <th>Tekst</th> <th>Tačnost</th> </tr> </thead> <tbody> {this.renderAnswers()} </tbody> </table> </div> </div> ); } render() { return ( <Modal isOpen={this.props.canAddQuestionShow} contentLabel="Information" onRequestClose={this.props.closeAddQuestion} /* className={this.state.expand !== true ? 'create-question ' : 'create-question-expand'} */ > <div className="modal-header"> <label className= "text-color">Dodavanje novog pitanja </label> <button type="button" className="close" onClick={this.props.closeAddQuestion}>x</button> </div> <div className = "containter" > <div className="row" > <div className={this.state.expand !== true ? 'offset-lg-3 col-lg-6 modal-title-padding ' : 'col-lg-6 modal-title-padding '}> <div className = "row"> <div className = "col-lg-6 form-group"> <label className= "text-color">Naziv pitanja:</label> <input type="text" name="questionName" className="form-control form-control-lg" onBlur={this.changeQuestionName} /> </div> <div className = "col-lg-6 form-group"> <label className= "text-color">Tip pitanja:</label> <select className="form-control form-control-lg " name="questionType" onChange={this.handleChangeSelect} > {this.state.options.map(opt => { return ( <option key={opt} value={opt}>{opt}</option> ); })} </select> </div> </div> <div className="row"> <div className="col-lg-12 form-group"> <label className= "text-color">Tekst pitanja:</label> <MyStatefulEditor canChange = {true} changeEditorState = {this.changeEditorState}/> </div> </div> <div className="row"> <div className="form-group col-lg-4"> <label className= "text-color">Kategorija težine:</label> <select className="form-control form-control-lg " name="questionCategory" onChange={this.changeCategory} > {this.state.categoryOptions.map(opt => { return ( <option key={opt} value={opt}> { this.renderCategory(opt)} </option> ); })} </select> </div> <div className="form-group col-lg-4"> <label className= "text-color">Bodovi </label><label className = "small_word"> - tačan odgovor</label> <input type="text" name="questionPlusPoints" className="form-control form-control-lg " value={this.state.plusPoints} onChange={this.changePlusPoints} /> </div> <div className="form-group col-lg-4"> <label className= "text-color">Bodovi</label><label className = "small_word"> - netačan odgovor</label> <input type="text" name="questionMinusPoints" className="form-control form-control-lg" onBlur={this.changeMinusPoints} /> </div> </div> </div> {/*otvarajuci zatvr*/} <div className="col-lg-6 modal-title-padding"> {/* Odgovori */} {this.state.checkBoxVisibility && <div><p className= "text-color"> Odgovori :</p> {this.renderTableWithAnswers()}</div>} {this.state.inputAnswerVisibility && this.state.checkBoxVisibility && <div className = "offset-lg-1 col-lg-10"> <AddAnswer renderExactitude={true} addAnswer={this.addAnswer} /> </div>} {!this.state.checkBoxVisibility && this.state.inputAnswerVisibility && <div > <AddAnswer renderExactitude={false} addAnswer={this.addAnswer} /> </div>} </div> </div> {/* row */} <div className="row "> <div className={this.state.inputAnswerVisibility !== true ? 'offset-lg-3 col-lg-6 bottom ':'offset-lg-3 col-lg-6 bottom'}> {/* <button onClick={this.addQuestion} className='rounded-button btn button-primary-color '>Dodaj pitanje</button> */} <button className="btn button-primary-color btn-lg btn-block block " onClick={this.addQuestion} >Dodaj pitanje </button> </div> </div> </div>{/* containter */} </Modal > ); } }
Java
UTF-8
23,036
2.265625
2
[]
no_license
package gingrasf.campsiteManager; import gingrasf.campsiteManager.persistence.AvailableDateLockRepository; import gingrasf.campsiteManager.persistence.CampsiteRepository; import gingrasf.campsiteManager.model.CampsiteAvailability; import gingrasf.campsiteManager.model.CampsiteReservation; import gingrasf.campsiteManager.model.User; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.time.LocalDate; import java.util.Collections; import java.util.List; import java.util.NoSuchElementException; import static gingrasf.campsiteManager.TestUtil.buildValidUser; import static gingrasf.campsiteManager.TestUtil.generateMultiDayReservation; import static gingrasf.campsiteManager.TestUtil.generateOneDayReservationsBetween; import static java.time.temporal.ChronoUnit.DAYS; import static java.util.Optional.empty; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.when; public class CampsiteServiceTest { public static final int MAX_RESERVATION_DURATION = 3; @Mock CampsiteRepository repository; @Mock AvailableDateLockRepository availableDateLockRepository; @Mock CampsiteReservationValidator validator; CampsiteService service; @Before public void setup() { MockitoAnnotations.initMocks(this); service = new CampsiteService(repository, availableDateLockRepository, validator); when(availableDateLockRepository.lockAvailableDate(any(), any())).thenReturn(true); } // Get Availability Cases @Test public void whenQueryingAvailabilityWeGetBasicInfo() { final LocalDate now = LocalDate.now(); final LocalDate until = now.plusMonths(2); when(repository.findAll()).thenReturn(Collections.emptyList()); final CampsiteAvailability campsiteAvailability = service.getAvailabilityBetween(now, until); assertThat(campsiteAvailability).isNotNull(); assertThat(campsiteAvailability.getSearchPeriodStart()).isEqualTo(now); assertThat(campsiteAvailability.getSearchPeriodEnd()).isEqualTo(until); assertThat(campsiteAvailability.getAvailableDates()).isNotEmpty(); } @Test public void whenNoReservationReturnAllTheDates() { final LocalDate now = LocalDate.now(); final LocalDate until = now.plusMonths(2); final long expectedNbOfDays = DAYS.between(now, until); when(repository.findAll()).thenReturn(Collections.emptyList()); final CampsiteAvailability campsiteAvailability = service.getAvailabilityBetween(now, until); assertThat(campsiteAvailability.getAvailableDates().size()).isEqualTo(expectedNbOfDays); } @Test public void whenNoReservationTomorrowIsAvailable() { final LocalDate now = LocalDate.now(); final LocalDate until = now.plusMonths(2); final LocalDate tomorrow = now.plusDays(1); when(repository.findAll()).thenReturn(Collections.emptyList()); final CampsiteAvailability campsiteAvailability = service.getAvailabilityBetween(now, until); assertThat(campsiteAvailability.getAvailableDates()).contains(tomorrow); } @Test public void whenThereIsAReservationForTomorrowDoNotReturnThatDate() { final LocalDate now = LocalDate.now(); final LocalDate until = now.plusMonths(2); final LocalDate tomorrow = now.plusDays(1); final long expectedNbOfDays = DAYS.between(now, until) - 1; when(repository.findAll()).thenReturn(generateOneDayReservationsBetween(tomorrow, tomorrow.plusDays(1))); final CampsiteAvailability campsiteAvailability = service.getAvailabilityBetween(now, until); assertThat(campsiteAvailability.getAvailableDates().size()).isEqualTo(expectedNbOfDays); assertThat(campsiteAvailability.getAvailableDates()).doesNotContain(tomorrow); } @Test public void whenAllTheDatesAreReservedReturnNoAvailability() { final LocalDate now = LocalDate.now(); final LocalDate until = now.plusMonths(1); when(repository.findAll()).thenReturn(generateOneDayReservationsBetween(now, until)); final CampsiteAvailability campsiteAvailability = service.getAvailabilityBetween(now, until); assertThat(campsiteAvailability.getAvailableDates()).isEmpty(); } @Test public void whenThereIsAMultiDaysReservationThoseDatesAreNotAvailable() { final LocalDate now = LocalDate.now(); final LocalDate until = now.plusMonths(2); final LocalDate tomorrow = now.plusDays(1); final LocalDate dayAfterTomorrow = tomorrow.plusDays(1); final long expectedNbOfDays = DAYS.between(now, until) - 3; when(repository.findAll()).thenReturn(generateMultiDayReservation(now, 3)); final CampsiteAvailability campsiteAvailability = service.getAvailabilityBetween(now, until); assertThat(campsiteAvailability.getAvailableDates().size()).isEqualTo(expectedNbOfDays); assertThat(campsiteAvailability.getAvailableDates()).doesNotContain(now); assertThat(campsiteAvailability.getAvailableDates()).doesNotContain(tomorrow); assertThat(campsiteAvailability.getAvailableDates()).doesNotContain(dayAfterTomorrow); } @Test public void whenQueryingAvailabilityUntilTomorrowAndTodayIsFreeItShouldBeReturned() { final LocalDate now = LocalDate.now(); final LocalDate tomorrow = now.plusDays(1); when(repository.findAll()).thenReturn(Collections.emptyList()); final CampsiteAvailability campsiteAvailability = service.getAvailabilityBetween(now, tomorrow); assertThat(campsiteAvailability.getAvailableDates()).contains(now); } @Test(expected = IllegalArgumentException.class) public void whenQueryingAvailabilityUntilTodayThrowException() { final LocalDate now = LocalDate.now(); service.getAvailabilityBetween(now, now); } @Test(expected = IllegalArgumentException.class) public void whenQueryingAvailabilityForAPastDateThrowException() { final LocalDate now = LocalDate.now(); final LocalDate yesterday = now.minusDays(1); service.getAvailabilityBetween(yesterday, now); } @Test(expected = RuntimeException.class) public void whenRepositoryThrowsAnExceptionPropagateIt() { final LocalDate now = LocalDate.now(); final LocalDate until = now.plusMonths(2); doThrow(new RuntimeException("BOOM!")).when(repository.findAll()); service.getAvailabilityBetween(now, until); } // Get All Reservations Cases @Test public void whenRequestingAllReservationsWeGetThem() { final LocalDate start = LocalDate.now().plusDays(1); final LocalDate until = start.plusDays(1); final List<CampsiteReservation> existingCampsiteReservations = generateOneDayReservationsBetween(start, until); when(repository.findAll()).thenReturn(existingCampsiteReservations); final Iterable<CampsiteReservation> campsiteReservations = service.getAllReservation(); assertThat(campsiteReservations).isNotNull(); assertThat(campsiteReservations).isNotEmpty(); assertThat(campsiteReservations).containsExactly(existingCampsiteReservations.toArray(new CampsiteReservation[existingCampsiteReservations.size()])); } @Test public void whenRequestingAllReservationsAndThereAreNoneWeGetEmptyList() { when(repository.findAll()).thenReturn(Collections.emptyList()); final Iterable<CampsiteReservation> campsiteReservations = service.getAllReservation(); assertThat(campsiteReservations).isNotNull(); assertThat(campsiteReservations).isEmpty(); } @Test(expected = RuntimeException.class) public void whenWeGetAllReservationAndRepositoryThrowsAnExceptionPropagateIt() { doThrow(new RuntimeException("BOOM!")).when(repository.findAll()); service.getAllReservation(); } // Create cases @Test public void whenCreatingAOneDayReservationForTomorrowItShouldWork() { final LocalDate tomorrow = LocalDate.now().plusDays(1); final LocalDate dayAfterTomorrow = tomorrow.plusDays(1); final User validUser = buildValidUser(); when(repository.save(any())).thenAnswer(i -> i.getArguments()[0]); final CampsiteReservation campsiteReservation = service.createReservation(validUser, tomorrow, dayAfterTomorrow); assertThat(campsiteReservation).isNotNull(); assertThat(campsiteReservation.getStartDate()).isEqualTo(tomorrow); assertThat(campsiteReservation.getEndDate()).isEqualTo(dayAfterTomorrow); assertThat(campsiteReservation.getUser()).isEqualTo(validUser); assertThat(campsiteReservation.getId()).isNotEmpty(); } @Test public void whenCreatingAReservationForMaxDurationForTomorrowItShouldWork() { final LocalDate tomorrow = LocalDate.now().plusDays(1); final LocalDate until = tomorrow.plusDays(MAX_RESERVATION_DURATION); final User validUser = buildValidUser(); when(repository.save(any())).thenAnswer(i -> i.getArguments()[0]); final CampsiteReservation campsiteReservation = service.createReservation(validUser, tomorrow, until); assertThat(campsiteReservation).isNotNull(); assertThat(campsiteReservation.getStartDate()).isEqualTo(tomorrow); assertThat(campsiteReservation.getEndDate()).isEqualTo(until); assertThat(campsiteReservation.getUser()).isEqualTo(validUser); assertThat(campsiteReservation.getId()).isNotEmpty(); } @Test public void whenCreatingAReservationInOneMonthItShouldWork() { final LocalDate inOneMonth = LocalDate.now().plusMonths(1); final LocalDate start = inOneMonth; final LocalDate until = inOneMonth.plusDays(1); final User validUser = buildValidUser(); when(repository.save(any())).thenAnswer(i -> i.getArguments()[0]); final CampsiteReservation campsiteReservation = service.createReservation(validUser, start, until); assertThat(campsiteReservation).isNotNull(); assertThat(campsiteReservation.getStartDate()).isEqualTo(start); assertThat(campsiteReservation.getEndDate()).isEqualTo(until); assertThat(campsiteReservation.getUser()).isEqualTo(validUser); assertThat(campsiteReservation.getId()).isNotEmpty(); } @Test(expected = CampsiteReservationConflictException.class) public void whenCreatingAReservationForADayAlreadyReservedThrowConflictException() { final LocalDate tomorrow = LocalDate.now().plusDays(1); final LocalDate until = tomorrow.plusDays(1); final User validUser = buildValidUser(); when(repository.findAll()).thenReturn(generateOneDayReservationsBetween(tomorrow, tomorrow.plusDays(1))); when(repository.save(any())).thenAnswer(i -> i.getArguments()[0]); service.createReservation(validUser, tomorrow, until); } @Test(expected = CampsiteReservationConflictException.class) public void whenCreatingAReservationForMultiDaysWithOneAlreadyReservedThrowConflictException() { final LocalDate tomorrow = LocalDate.now().plusDays(1); final LocalDate until = tomorrow.plusDays(MAX_RESERVATION_DURATION); final User validUser = buildValidUser(); when(repository.findAll()).thenReturn(generateOneDayReservationsBetween(tomorrow, tomorrow.plusDays(1))); when(repository.save(any())).thenAnswer(i -> i.getArguments()[0]); service.createReservation(validUser, tomorrow, until); } @Test(expected = IllegalArgumentException.class) public void whenCreatingAnInvalidReservationThrowException() { final LocalDate tomorrow = LocalDate.now().plusDays(1); final LocalDate until = tomorrow.plusDays(MAX_RESERVATION_DURATION + 1); final User validUser = buildValidUser(); doThrow(new IllegalArgumentException("Invalid!")).when(validator).validateReservation(any(LocalDate.class), any(LocalDate.class)); when(repository.save(any())).thenAnswer(i -> i.getArguments()[0]); service.createReservation(validUser, tomorrow, until); } @Test(expected = CampsiteReservationConflictException.class) public void whenTheLockIsNotAcquiredOnAnInsertThrowConflictException() { final LocalDate tomorrow = LocalDate.now().plusDays(1); final LocalDate until = tomorrow.plusDays(MAX_RESERVATION_DURATION + 1); final User validUser = buildValidUser(); when(availableDateLockRepository.lockAvailableDate(any(), any())).thenReturn(false); service.createReservation(validUser, tomorrow, until); } @Test(expected = RuntimeException.class) public void whenWeCreateReservationAndRepositoryThrowsAnExceptionPropagateIt() { final LocalDate tomorrow = LocalDate.now().plusDays(1); final LocalDate until = tomorrow.plusDays(1); final User validUser = buildValidUser(); doThrow(new RuntimeException("BOOM!")).when(repository.save(any())); service.createReservation(validUser, tomorrow, until); } // Update cases @Test public void whenShiftingAnExistingReservationToAnotherAvailableTimeItShouldWork() { final LocalDate start = LocalDate.now().plusDays(1); final LocalDate end = start.plusDays(1); final User validUser = buildValidUser(); final String existingId = "some-test-unique-id"; final CampsiteReservation existingReservation = CampsiteReservation.builder().id(existingId).startDate(start).endDate(end).user(validUser).build(); final LocalDate newStart = start.plusDays(3); final LocalDate newEnd = end.plusDays(3); final CampsiteReservation newReservation = CampsiteReservation.builder().id(existingId).startDate(newStart).endDate(newEnd).user(validUser).build(); when(repository.findById(existingId)).thenReturn(ofNullable(existingReservation)); when(repository.save(any())).thenAnswer(i -> i.getArguments()[0]); final CampsiteReservation campsiteReservation = service.updateReservation(existingId, newReservation); assertThat(campsiteReservation.getStartDate()).isEqualTo(newStart); assertThat(campsiteReservation.getEndDate()).isEqualTo(newEnd); assertThat(campsiteReservation.getUser()).isEqualTo(validUser); assertThat(campsiteReservation.getId()).isEqualTo(existingId); } @Test(expected = CampsiteReservationConflictException.class) public void whenShiftingAnExistingReservationToANonAvailableTimeThrowConflictException() { final LocalDate start = LocalDate.now().plusDays(1); final LocalDate end = start.plusDays(1); final User validUser = buildValidUser(); final String existingId = "some-test-unique-id"; final CampsiteReservation existingReservation = CampsiteReservation.builder().id(existingId).startDate(start).endDate(end).user(validUser).build(); final LocalDate newStart = start; final LocalDate newEnd = newStart.plusDays(MAX_RESERVATION_DURATION); final CampsiteReservation newReservation = CampsiteReservation.builder().id(existingId).startDate(newStart).endDate(newEnd).user(validUser).build(); when(repository.findById(existingId)).thenReturn(ofNullable(existingReservation)); when(repository.findAll()).thenReturn(generateOneDayReservationsBetween(newStart.plusDays(1), newStart.plusDays(2))); when(repository.save(any())).thenAnswer(i -> i.getArguments()[0]); service.updateReservation(existingId, newReservation); } @Test(expected = NoSuchElementException.class) public void whenUpdatingAReservationThatDoesNotExistThrowNoSuchElementException() { final LocalDate start = LocalDate.now().plusDays(1); final User validUser = buildValidUser(); final String nonExistingId = "some-test-unique-id"; final LocalDate newStart = start; final LocalDate newEnd = newStart.plusDays(MAX_RESERVATION_DURATION); final CampsiteReservation newReservation = CampsiteReservation.builder().id(nonExistingId).startDate(newStart).endDate(newEnd).user(validUser).build(); when(repository.findById(nonExistingId)).thenReturn(empty()); when(repository.save(any())).thenAnswer(i -> i.getArguments()[0]); service.updateReservation(nonExistingId, newReservation); } @Test(expected = IllegalArgumentException.class) public void whenUpdatingAReservationWithADifferentUserThrowException() { final LocalDate start = LocalDate.now().plusDays(1); final LocalDate end = start.plusDays(1); final User validUser = buildValidUser(); final User newGuy = User.builder().email("newguy@test.com").fullName("New Guy").build(); final String existingId = "some-test-unique-id"; final CampsiteReservation existingReservation = CampsiteReservation.builder().id(existingId).startDate(start).endDate(end).user(validUser).build(); final LocalDate newStart = start; final LocalDate newEnd = newStart.plusDays(MAX_RESERVATION_DURATION); final CampsiteReservation newReservation = CampsiteReservation.builder().id(existingId).startDate(newStart).endDate(newEnd).user(newGuy).build(); doThrow(new IllegalArgumentException("Invalid!")).when(validator).validateReservation(any(LocalDate.class), any(LocalDate.class)); when(repository.findById(existingId)).thenReturn(ofNullable(existingReservation)); when(repository.save(any())).thenAnswer(i -> i.getArguments()[0]); service.updateReservation(existingId, newReservation); } @Test(expected = IllegalArgumentException.class) public void whenUpdatingAReservationWithInvalidDatesThrowException() { final LocalDate start = LocalDate.now().plusDays(1); final LocalDate end = start.plusDays(1); final User validUser = buildValidUser(); final String existingId = "some-test-unique-id"; final CampsiteReservation existingReservation = CampsiteReservation.builder().id(existingId).startDate(start).endDate(end).user(validUser).build(); final LocalDate newStart = start; final LocalDate newEnd = newStart.plusDays(MAX_RESERVATION_DURATION); final CampsiteReservation newReservation = CampsiteReservation.builder().id(existingId).startDate(newStart).endDate(newEnd).user(validUser).build(); doThrow(new IllegalArgumentException("Invalid!")).when(validator).validateReservation(any(LocalDate.class), any(LocalDate.class)); when(repository.findById(existingId)).thenReturn(ofNullable(existingReservation)); when(repository.save(any())).thenAnswer(i -> i.getArguments()[0]); service.updateReservation(existingId, newReservation); } @Test(expected = CampsiteReservationConflictException.class) public void whenTheLockIsNotAcquiredOnAnUpdateThrowConflictException() { final LocalDate start = LocalDate.now().plusDays(1); final LocalDate end = start.plusDays(1); final User validUser = buildValidUser(); final String existingId = "some-test-unique-id"; final CampsiteReservation existingReservation = CampsiteReservation.builder().id(existingId).startDate(start).endDate(end).user(validUser).build(); final LocalDate newStart = start.plusDays(3); final LocalDate newEnd = end.plusDays(3); final CampsiteReservation newReservation = CampsiteReservation.builder().id(existingId).startDate(newStart).endDate(newEnd).user(validUser).build(); when(availableDateLockRepository.lockAvailableDate(any(), any())).thenReturn(false); when(repository.findById(existingId)).thenReturn(ofNullable(existingReservation)); when(repository.save(any())).thenAnswer(i -> i.getArguments()[0]); service.updateReservation(existingId, newReservation); } @Test(expected = RuntimeException.class) public void whenWeUpdateReservationAndRepositoryThrowsAnExceptionPropagateIt() { final LocalDate start = LocalDate.now().plusDays(1); final LocalDate end = start.plusDays(1); final User validUser = buildValidUser(); final String existingId = "some-test-unique-id"; final CampsiteReservation existingReservation = CampsiteReservation.builder().id(existingId).startDate(start).endDate(end).user(validUser).build(); final LocalDate newStart = start.plusDays(3); final LocalDate newEnd = end.plusDays(3); final CampsiteReservation newReservation = CampsiteReservation.builder().id(existingId).startDate(newStart).endDate(newEnd).user(validUser).build(); when(availableDateLockRepository.lockAvailableDate(any(), any())).thenReturn(false); when(repository.findById(existingId)).thenReturn(ofNullable(existingReservation)); when(repository.save(any())).thenAnswer(i -> i.getArguments()[0]); doThrow(new RuntimeException("BOOM!")).when(repository.save(any())); service.updateReservation(existingId, newReservation); } // Delete cases @Test public void whenDeletingAnExistingReservationItShouldWork() { final LocalDate start = LocalDate.now().plusDays(1); final LocalDate end = start.plusDays(1); final User validUser = buildValidUser(); final String existingId = "some-test-unique-id"; final CampsiteReservation existingReservation = CampsiteReservation.builder().id(existingId).startDate(start).endDate(end).user(validUser).build(); when(repository.findById(existingId)).thenReturn(ofNullable(existingReservation)); service.deleteReservation(existingId); } @Test(expected = NoSuchElementException.class) public void whenDeletingAReservationThatDoesNotExistThrowNoSuchElementException() { final String nonExistingId = "some-test-unique-id"; when(repository.findById(nonExistingId)).thenReturn(empty()); service.deleteReservation(nonExistingId); } @Test(expected = RuntimeException.class) public void whenWeDeleteReservationAndRepositoryThrowsAnExceptionPropagateIt() { final LocalDate start = LocalDate.now().plusDays(1); final LocalDate end = start.plusDays(1); final User validUser = buildValidUser(); final String existingId = "some-test-unique-id"; final CampsiteReservation existingReservation = CampsiteReservation.builder().id(existingId).startDate(start).endDate(end).user(validUser).build(); when(repository.findById(existingId)).thenReturn(ofNullable(existingReservation)); doThrow(new RuntimeException("BOOM!")).when(repository).delete(any()); service.deleteReservation(existingId); } }
Java
UTF-8
1,564
2.453125
2
[]
no_license
package ohs.ml.neuralnet.layer; import ohs.math.VectorMath; import ohs.matrix.DenseMatrix; import ohs.matrix.DenseVector; public abstract class RecurrentLayer extends Layer { public static enum Type { LSTM, RNN } /** * */ private static final long serialVersionUID = 5913734004543729479L; protected DenseMatrix Wxh; protected DenseMatrix Whh; protected DenseVector b; protected DenseMatrix dWxh; protected DenseMatrix dWhh; protected DenseVector db; protected int shift_size = 1; protected int window_size = 1; /** * Semeniuta, S., Severyn, A., & Barth, E. (2016). Recurrent Dropout without * Memory Loss. Retrieved from http://arxiv.org/abs/1603.05118 * * @param X * @param p */ public static void dropout(DenseMatrix X, double p) { DenseMatrix M = X.copy(true); VectorMath.random(0, 1, M); VectorMath.mask(M, p); M.multiply(1f / p); // inverted drop-out VectorMath.multiply(X, M, X); } public RecurrentLayer() { } public DenseMatrix getDWhh() { return dWhh; } public DenseMatrix getDWxh() { return dWxh; } public int getShiftSize() { return shift_size; } public DenseMatrix getWhh() { return Whh; } public int getWindowSize() { return window_size; } public DenseMatrix getWxh() { return Wxh; } public abstract void resetH0(); public void setShiftSize(int shift_size) { this.shift_size = shift_size; } public void setWindowSize(int window_size) { this.window_size = window_size; } }
JavaScript
UTF-8
588
3.234375
3
[]
no_license
var Person = function(name){ this.name = name; this.orders = []; this.total = 0; //The individual tip gets defined from the mealModel; this.tip = null; } Person.prototype.addDishes = function(dish, quantity){ this.orders.push(dish); this.total += dish.price * quantity; } Person.prototype.getTotal = function(){ //Assuming that there is a fixed 10% tax on each meal //And assuming flat 8% gratuity on pre tax var total = 0 this.tip = this.total * 0.08; this.total += this.total * 0.1; total = this.tip + this.total; return total; } module.exports = Person;
C++
UTF-8
469
3.203125
3
[]
no_license
#if !defined(__DISPLY_LIST_H__) #define __DISPLY_LIST_H__ class RenderContext; /* Extremely simple display list implementation: each list node has a 'render()' function and a pointer to the next node */ namespace DisplayList { class Node { Node* next; public: Node() : next(0) {} virtual void Render( RenderContext* context ) = 0; virtual Node* Next() { return next; } virtual void SetNext( Node* n ) { next = n; } }; } #endif
Markdown
UTF-8
4,162
3.15625
3
[ "MIT" ]
permissive
# API Documentation # Mete responds to several requests. The API is REST-like (but not entirely). ## / ## * `GET /` - the same as `GET /users` ### /audits ### * `GET /audits` - returns statistics about previous transactions; possible paramters are: * `start_date[year]` - `integer` * `start_date[month]` - `integer` * `start_date[day]` - `integer` * `end_date[year]` - `integer` * `end_date[month]` - `integer` * `end_date[day]` - `integer` * `GET /audits.json` - the same as above, but in JSON format ### /drinks ### * `GET /drinks` - returns all drinks * `GET /drinks.json` - the same as above, but in JSON format * `GET /drinks/%did%` - returns information about the drink with the id `%did%` * `GET /drinks/%did%.json` - the same as above, but in JSON format * `GET /drinks/new` - displays a form for creating a new drink * `GET /drinks/new.json` - wat. This makes no sense. * `POST /drinks` - creates a new drink; parameters are: * `drink[name]` - `string` - the name of the new drink * `drink[price]` - `double` - the price of the new drink in € * `drink[bottle_size]` - `double` - the bottle size of the new drink in l * `drink[caffeine]` - `integer` - the amount of caffeine of the new drink in mg/100ml * `drink[active]` - `boolean` - whether the new drink is in stock * `drink[logo]` - `file` - the logo of the new drink * `POST /drinks.json` - the same as above, but in JSON format (What's the difference?) * `GET /drinks/%did%/edit` - displays a form for editing an existing drink * `PATCH /drinks/%did%` - modifys an existing drink; the parameters are the same as for creating a new drink * `PATCH /drinks/%did%.json` - the same as above, but in JSON format (What's the difference?) * `DELETE /drinks/%did%` - deletes the drink with the id `%did%` * `DELETE /drinks/%id.json` - the same as above, but in JSON format (What's the difference?) ### /users ### * `GET /users` - returns all users * `GET /users.json` - the same as above, but in JSON format * `GET /users/%uid%` - returns information about the user with the id `%uid%` * `GET /users/%uid%.json` - the same as above, but in JSON format * `GET /users/new` - displays a form for creating a new user * `GET /users/new.json` - wat. This makes no sense. * `POST /users` - creates a new user; parameters are: * `user[name]` - `string` - the name of the new user * `user[email]` - `string` - the email of the new user * `user[balance]`- `double` - the balance of the new user in € * `user[active]` - `boolean` - whether the new user is active * `POST /users.json` - the same as above, but in JSON format (What's the difference?) * `GET /users/edit` - display a form for editing an existing user * `PATCH /users/%uid%` - modifys an existing user; the parameters are the same as for adding a user * `PATCH /users/%uid%.json` - the same as above, but in JSON format (What's the difference?) * `DELETE /users/%uid%` - deletes the user with the id `%uid%` * `DELETE /users/%uid%.json` - the same as above, but in JSON format (What's the difference?) * `GET /users/%uid%/deposit?amount=%amount%` - adds the amount `%amount%` (in €) to the balance of the user with the id `%uid%` (**This GET request modifys data!**) * `GET /users/%uid%/deposit.json?amount%amount%` - the same as above, but in JSON format (What's the difference?) (**This GET request modifys data!**) * `GET /users/%uid%/pay?amount=%amount%` - removes the amount `%amount%` (in €) from the balance of the user with the id `%uid%` (**This GET request modifys data!**) * `GET /users/%uid%/pay.json?amount%amount%` - the same as above, but in JSON format (What's the difference?) (**This GET request modifys data!**) * `GET /users/%uid%/buy?drink=%did%` - buys the drink with the id `%did%` for the user with the id `%uid%` (**This GET request modifys data!**) * `GET /Users/%uid%/buy.json?drink=%did%` - the same as above, but in JSON format (What's the difference?) (**This GET request modifys data!**) * `GET /users/stats` - displays various statistics about the users * `GET /users/stats.json` - the same as above, but in JSON format
C++
UTF-8
1,642
2.890625
3
[]
no_license
#include "pch.h" #include "XStdUtil.h" #include <codecvt> std::wstring XStdUtil::xstring(const char* str) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> cvt; std::wstring value = cvt.from_bytes(str); return value; } std::string XStdUtil::xstring(const wchar_t* str) { std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> cvt; std::string value = cvt.to_bytes(str); return value; } void XStdUtil::xstring(const wchar_t* str, int& value) { std::string s = xstring(str); value = std::stoi(s.c_str(), NULL, 0); } void XStdUtil::xstring(const wchar_t* str, long& value) { value = std::wcstol(str, NULL, 0); } void XStdUtil::xstring(const wchar_t* str, unsigned long& value) { value = std::wcstoul(str, NULL, 0); } void XStdUtil::xstring(const wchar_t* str, long long& value) { value = std::wcstoll(str, NULL, 0); } void XStdUtil::xstring(const wchar_t* str, unsigned long long& value) { value = std::wcstoull(str, NULL, 0); } void XStdUtil::xstring(const wchar_t* str, double& value) { value = std::wcstod(str, NULL); } void XStdUtil::xstring(const wchar_t* str, long double& value) { value = std::wcstold(str, NULL); } void XStdUtil::xstring(const wchar_t* str, float& value) { value = std::wcstof(str, NULL); } void XStdUtil::xstring(const wchar_t* str, bool& value) { value = (std::wstring(str) == L"true"); } void XStdUtil::xstring(const wchar_t* str, wchar_t& value) { value = *str; } std::wstring XStdUtil::xstring(const bool& b) { std::wstring str = L"false"; if (b) str = L"true"; return str; } std::wstring XStdUtil::xstring(const wchar_t& c) { std::wstring str = L""; str += c; return str; }
C++
UTF-8
7,288
3
3
[]
no_license
/* * cm.std external library * Some small and complex essential methods for performing basic functions. * * cm-s (Charles Stevens) * Date created: July 5th * Revision: e061ad7 */ #include <iostream> #include <cstring> #include <cmath> using namespace std; struct SBUF { int *base10_counter = new int; float *input_surrogate = new float; string *base_value = new string; void scat(string input) { for (size_t head = 0; true; head++) { if (input[head] != 0) { *base_value += input[head]; } else { break; }; }; }; void ccat(char input) { *base_value += input; }; void ncat(int input) { if ((input - 10) < 0) { cb10(input); } else { *input_surrogate = input; while ((int) *input_surrogate != 0) { *base10_counter += 1; *input_surrogate /= 10; }; while (*base10_counter != 0) { *input_surrogate = input; *input_surrogate /= pow(10, *base10_counter); cb10( (int) ((*input_surrogate - (int)*input_surrogate ) * 10) ); *base10_counter -= 1; }; }; }; void bcat(bool input, bool bcase) { if (input) { if (bcase) { *base_value += 'T'; } else { *base_value += 't'; }; *base_value += 'r'; *base_value += 'u'; *base_value += 'e'; } else { if (bcase) { *base_value += 'F'; } else { *base_value += 'f'; }; *base_value += 'a'; *base_value += 'l'; *base_value += 's'; *base_value += 'e'; }; }; string val() { return *base_value; }; void clear() { *base_value = ""; }; // ConvertOR: What is being convertED. void cb10(int convertor) { switch (convertor) { case 1: *base_value += '1'; break; case 2: *base_value += '2'; break; case 3: *base_value += '3'; break; case 4: *base_value += '4'; break; case 5: *base_value += '5'; break; case 6: *base_value += '6'; break; case 7: *base_value += '7'; break; case 8: *base_value += '8'; break; case 9: *base_value += '9'; break; }; }; }; struct CMSTD { bool in(string subject, string whitelist[]) { for (int item = 0; item <= whitelist -> size(); item++) { if (whitelist[item] == subject) { return true; }; }; return false; }; bool in(char subject, char whitelist[]) { int *whitelist_size; whitelist_size = new int; for (size_t item = 0; false; item++) { if (whitelist[item] == 0) { break; }; whitelist_size++; }; for (size_t item = 0; item < *whitelist_size; item++) { if (whitelist[item] == subject) { return true; }; }; return false; }; int combineNum(string base, string addon) { string* buffer; buffer = new string; for (size_t head = 0; head < 40; head++) { if (base[head] != 0) { *buffer += base[head]; } else { break; }; }; for (size_t head = 0; head < 40; head++) { if (addon[head] != 0) { *buffer += addon[head]; } else { break; }; }; //combined both input strings... saving in buffer string refinedBuffer = *buffer; int* total; total = new int; int* cb; cb = new int; for (size_t head = 0; head < 40; head++) { if (refinedBuffer[head] != 0) { *cb += 1; } //interchange refinedBuffer with base for original fuctionallity else { break; }; }; //counted how many digits are in the buffer if (*cb > 9) { cout << "\nWarning: combineNum: Functionallity depreciates after more than nine digits are inputted." << endl; }; for (int i = 0; i < *cb; i++) { int subject = (int) refinedBuffer[i]; //interchange refinedBuffer with base for original fuctionallity switch (subject) { case 48: subject = 0; break; case 49: subject = 1; break; case 50: subject = 2; break; case 51: subject = 3; break; case 52: subject = 4; break; case 53: subject = 5; break; case 54: subject = 6; break; case 55: subject = 7; break; case 56: subject = 8; break; case 57: subject = 9; break; }; //converted keycode for given digit and holding in memory (stored in "subject") *total += (subject*pow(10,((*cb -i)-1))); //multiplying the current number being converted by how many place values(current val of *cb) are left to convert }; return *total; }; auto indexer(auto input, string type, int min, int max) { if (type == "int") { if (min < 2) { cout << "\nError: " << __FILE__ << ": indexer(): parameter three invalid. Minimum cancatenation index cannot be less than 2." << endl; exit(EXIT_SUCCESS); }; if (max < 1) { cout << "\nError: " << __FILE__ << ": indexer(): parameter four invalid. Maximum cancatenation index cannot be less than 1." << endl; exit(EXIT_SUCCESS); }; int* final; final = new int; int* point; point = new int; *point = 1; float* counter; counter = new float; *counter = input/10; while((int) *counter != 0) { *point += 1; *counter /= 10; };//determined length of input if (*point >= 9) { cout << "\nError: " << __FILE__ << ": indexer(): parameter one invalid. Calculaitons become interpolated when input is nine or more digits long." << endl; exit(EXIT_SUCCESS); }; *final = input; *counter = input/pow(10, *point - min + 1);//for some reason this math disregards digits at the end of an input long enough //but doesn't change the outcome //created decimaled value to count to int* min_threshold; min_threshold = new int; *min_threshold = 1; while (*min_threshold != (int) *counter) { *min_threshold += 1; }; //replicated the number before the "index" place of the given minimum *final -= *min_threshold*pow(10, *point - min + 1); int min_deduced_total = *final; //stored value with deducted min indexes *counter = input/pow(10, max - 1);//calculations become interpolated at more than eight digits *counter -= (int) *counter; *final = *counter*pow(10, max - 1); *final = min_deduced_total-*final; *final /=pow(10, max - 1); return *final; }; }; };
Python
UTF-8
138
3.734375
4
[]
no_license
def calculate_age(year): age = 2018 - year return age year = int(raw_input("Enter year of birth: ")) print(calculate_age(year))
JavaScript
UTF-8
5,305
3.15625
3
[ "MIT" ]
permissive
import Color from '../index' // Controls for hex values for functions like lighten/darken/mix etc… // come from: // https://www.sassmeister.com/ describe('Construct', () => { test('Generates initial color models, from hex', () => { expect(new Color('#000').getColor().hex).toEqual('#000000') expect(new Color('#000').getColor().rgb).toEqual({r: 0, g: 0, b: 0}) expect(new Color('#000').getColor().hsl).toEqual({h: 0, s: 0, l: 0}) }) test('Generates initial color models, from color name', () => { expect(new Color('black').getColor().hex).toEqual('#000000') expect(new Color('black').getColor().rgb).toEqual({r: 0, g: 0, b: 0}) expect(new Color('black').getColor().hsl).toEqual({h: 0, s: 0, l: 0}) }) }) describe('toString', () => { test('Can generate hex string', () => { expect(new Color('#000').hex().toString()).toEqual('#000000') expect(new Color('black').hex().toString()).toEqual('#000000') }) test('Can generate rgb string', () => { expect(new Color('#000').rgb().toString()).toEqual('rgb(0, 0, 0)') expect(new Color('black').rgb().toString()).toEqual('rgb(0, 0, 0)') }) test('Can generate rgba string', () => { expect(new Color('#000').rgba().toString()).toEqual('rgba(0, 0, 0, 1)') expect(new Color('black').rgba().toString()).toEqual('rgba(0, 0, 0, 1)') }) test('Can generate hsl string', () => { expect(new Color('#000').hsl().toString()).toEqual('hsl(0, 0, 0)') expect(new Color('black').hsl().toString()).toEqual('hsl(0, 0, 0)') }) test('Can generate hsla string', () => { expect(new Color('#000').hsla().toString()).toEqual('hsla(0, 0, 0, 1)') expect(new Color('black').hsla().toString()).toEqual('hsla(0, 0, 0, 1)') }) }) describe('Lighten', () => { test('Can lighten a color to a specified value', () => { expect( new Color('#000') .lighten(20) .hex() .toString(), ).toEqual('#333333') expect( new Color('black') .lighten(20) .hex() .toString(), ).toEqual('#333333') expect( new Color('#000') .lighten(10) .rgb() .toString(), ).toEqual('rgb(25, 25, 25)') }) test('Lightens to 20, by default', () => { expect( new Color('#000') .lighten(20) .hex() .toString(), ).toEqual('#333333') }) test('Can lighten a color to a 0 value', () => { expect( new Color('#000') .lighten(0) .hex() .toString(), ).toEqual('#000000') expect( new Color('black') .lighten(0) .hex() .toString(), ).toEqual('#000000') }) }) describe('Darken', () => { test('Can darken a color to a specified value', () => { expect( new Color('#fff') .darken(20) .hex() .toString(), ).toEqual('#cccccc') expect( new Color('white') .darken(20) .hex() .toString(), ).toEqual('#cccccc') expect( new Color('#fff') .darken(10) .rgb() .toString(), ).toEqual('rgb(229, 229, 229)') }) test('Darkens to 20, by default', () => { expect( new Color('#fff') .darken() .hex() .toString(), ).toEqual('#cccccc') }) test('Can darken a color to a 0 value', () => { expect( new Color('#fff') .darken(0) .hex() .toString(), ).toEqual('#ffffff') expect( new Color('white') .darken(0) .hex() .toString(), ).toEqual('#ffffff') }) }) describe('Shade', () => { test('Returns darkest for darkest shades', () => { expect(new Color('#000').shade()).toEqual('darkest') expect(new Color('#111').shade()).toEqual('darkest') expect(new Color('#103010').shade()).toEqual('darkest') }) }) describe('Mix', () => { test('Can mix using color names', () => { expect( new Color('red') .mix('yellow') .hex() .toString(), ).toEqual('#ff8000') expect( new Color('dodgerblue') .mix('yellow') .hex() .toString(), ).toEqual('#8fc880') expect( new Color('black') .mix('white') .hex() .toString(), ).toEqual('#808080') expect( new Color('red') .mix('white') .hex() .toString(), ).toEqual('#ff8080') }) test('Can mix with weight values', () => { expect( new Color('red') .mix('white', 0) .hex() .toString(), ).toEqual('#ffffff') expect( new Color('red') .mix('white', 0.1) .hex() .toString(), ).toEqual('#ffe6e6') expect( new Color('red') .mix('white', 0.2) .hex() .toString(), ).toEqual('#ffcccc') expect( new Color('red') .mix('white', 0.3) .hex() .toString(), ).toEqual('#ffb3b3') expect( new Color('red') .mix('white', 0.5) .hex() .toString(), ).toEqual('#ff8080') expect( new Color('red') .mix('white', 0.87) .hex() .toString(), ).toEqual('#ff2121') expect( new Color('red') .mix('white', 0.99) .hex() .toString(), ).toEqual('#ff0303') }) })
PHP
UTF-8
281
2.640625
3
[ "MIT" ]
permissive
<?php namespace Pirminis; final class Some extends Maybe { public function __construct($subject) { $this->subject = $subject; } public function is_some() { return true; } public function is_none() { return false; } }
Python
UTF-8
16,161
2.546875
3
[]
no_license
#-------------------------------------------------------------------------- # File and Version Information: # $Id: template!pyana-module!py 1095 2010-07-07 23:01:23Z ofte $ # # Description: # Pyana user analysis module pyana_fccd_delay: # Averages fccd images in bins of delay time, after selecting events based on ipimb intensity. # Delay time is determined from encoder ("crazy-scanner") and phase cavity fit time 1 # Originally made for sxr27211 (based on myana code from sxr20510). #------------------------------------------------------------------------ """User analysis module for pyana framework. This software was developed for the LCLS project. If you use all or part of it, please give an appropriate acknowledgment. Averages fccd images in bins of delay time, after selecting events based on ipimb intensity. Delay time is determined from encoder ('crazy-scanner') and phase cavity fit time 1 Originally made for sxr27211 (based on myana code from sxr20510). @see RelatedModule @version $Id: template!pyana-module!py 1095 2010-07-07 23:01:23Z ofte $ @author Ingrid Ofte @author Hubertus Bromberger """ #------------------------------ # Module's version from SVN -- #------------------------------ __version__ = "$Revision: 1095 $" # $Source$ #-------------------------------- # Imports of standard modules -- #-------------------------------- import sys import logging import time #----------------------------- # Imports for other modules -- #----------------------------- import numpy as np import scipy as spy import matplotlib.pyplot as plt from pypdsdata import xtc #---------------------------------- # Local non-exported definitions -- #---------------------------------- # local definitions usually start with _ #--------------------- # Class definition -- #--------------------- class pyana_fccd_delay (object) : """Class whose instance will be used as a user analysis module. """ #-------------------- # Class variables -- #-------------------- #---------------- # Constructor -- #---------------- def __init__ ( self, image_source = "SxrEndstation-0|Fccd-0", encoder_source = "SxrBeamline-0|Encoder-0", ipimb_source = "SxrBeamline-0|Ipimb-1", start_time = "300", end_time = "500", num_bins = "100", path = "data", ipimb_threshold_upper = "2.0", # 0.55 ipimb_threshold_lower = "0.02", # 0.35 ipimb_offset = "0", # 1.22 trim_images = False, ) : """Class constructor. The parameters to the constructor are passed from pyana configuration file. If parameters do not have default values here then the must be defined in pyana.cfg. All parameters are passed as strings, convert to correct type before use. @param image_source Address of FCCD image @param encoder_source Address of encoder @param ipimb_source Address of IPIMB @param start_time delay time first bin @param end_time delay time last bin @param num_bins delay time number of bins @param path path directory for output files @param ipimb_threshold_upper @param ipimb_threshold_lower @param ipimb_offset @param trim_images Show only the trimmed (480x480) images """ self.img_source = image_source self.enc_source = encoder_source self.ipimb_source = ipimb_source self.fStartTime = float(start_time) self.fEndTime = float(end_time) self.iNumBins = int(num_bins) self.FileFolder = path self.IpimbThrU = float(ipimb_threshold_upper) self.IpimbThrL = float(ipimb_threshold_lower) self.IpimbOffset = float(ipimb_offset) self.trim_images = trim_images # collect the total average (write to dark file if that is non-existent) self.avg_image = None self.nev = 0 self.eventNr = 0 self.badEvents = [] # Encoder Parameters to convert to picoseconds self.Delay_a = -80.0e-6; self.Delay_b = 0.52168; self.Delay_c = 299792458; self.Delay_0 = 0; # bitshift number for big positive encoder numbers self.bitshift = 2 << 24 self.FoundStartTime = 1e12; self.FoundEndTime = 0; self.DeltaTime = (self.fEndTime - self.fStartTime)/self.iNumBins; # histograms self.hTime = [] self.BinCounts = np.zeros(self.iNumBins, dtype=np.uint8) self.I0 = np.zeros(self.iNumBins) self.ImageArray = np.zeros((self.iNumBins, 500, 576)) # Raw image # load dark image file darkfile = self.FileFolder + "/dark.npy" self.dark_array = None try: self.dark_array = np.load( darkfile ) print "Dark array %s loaded from %s"%(self.dark_array.shape,darkfile) except: print "No dark file... " try: print "... will make one: %s/dark.npy"%(self.FileFolder) # if it doesn't exist... make one os.mkdir(self.FileFolder) print self.fileFolder except: pass #------------------- # Public methods -- #------------------- def beginjob( self, evt, env ) : """This method is called once at the beginning of the job. It should do a one-time initialization possible extracting values from event data (which is a Configure object) or environment. @param evt event data object @param env environment object """ # Preferred way to log information is via logging package logging.info( "pyana_fccd_delay.beginjob() called" ) self.timer_start = time.clock() def beginrun( self, evt, env ) : """This optional method is called if present at the beginning of the new run. @param evt event data object @param env environment object """ logging.info( "pyana_fccd_delay.beginrun() called" ) def begincalibcycle( self, evt, env ) : """This optional method is called if present at the beginning of the new calibration cycle. @param evt event data object @param env environment object """ logging.info( "pyana_fccd_delay.begincalibcycle() called" ) def event( self, evt, env ) : """This method is called for every L1Accept transition. @param evt event data object @param env environment object """ self.nev += 1 ##################### # Retreive the Ipimb information for normalization and filtering ##################### try: ipmRaw = evt.get(xtc.TypeId.Type.Id_IpimbData, self.ipimb_source) i0value = ipmRaw.channel1Volts() if i0value < self.IpimbThrL: print "Failed ipimb threshold", i0value, self.IpimbThrL self.badEvents.append(self.nev) return except: print "No %s found in shot#%d" %( self.ipimb_source, self.nev) self.badEvents.append(self.nev) return #################### # Get Encoder to determine DelayTime and BinNumber #################### try: encoder = evt.get(xtc.TypeId.Type.Id_EncoderData, self.enc_source ) Encoder_int = encoder.value() if Encoder_int > 5e6 : Encoder_int -= self.bitshift except: print "No encoder found in shot#", self.nev self.badEvents.append(self.nev) return ################### # Phase Cavity to determine DelayTime and BinNumber ################### try: pc = evt.getPhaseCavity() phasecav1 = pc.fFitTime1 #phasecav2 = pc.fFitTime2 #charge1 = pc.fCharge1 #charge2 = pc.fCharge2 except: print "No phase cavity found in shot#", self.nev self.badEvents.append(self.nev) return #################### # Calculate DelayTime and BinNumber #################### DelayTime = 2. * ((self.Delay_a * Encoder_int + self.Delay_b)*1.e-3 / self.Delay_c) \ / 1.e-12 + self.Delay_0 + phasecav1 if DelayTime < self.FoundStartTime: self.FoundStartTime = DelayTime elif DelayTime > self.FoundEndTime: self.FoundEndTime = DelayTime self.hTime.append( DelayTime ) if DelayTime >= self.fStartTime and DelayTime <= self.fEndTime: BinNumber = int((DelayTime-self.fStartTime)/self.DeltaTime) else: self.badEvents.append((self.nev, DelayTime)) return ################## # Process FCCD Frame ################## try: # data from FCCD camera (uint8) data = evt.getFrameValue(self.img_source).data() # data is now (500x2*576) except: print "No image, %s ev#%d" % (self.img_source,self.nev) self.badEvents.append(self.nev) return # read out as uint16 due to DAQ trick. data.dtype = np.uint16 # data is now 500x576 if self.avg_image is None: self.avg_image = np.float_(data) else: self.avg_image += data self.ImageArray[BinNumber] += data self.I0[BinNumber] += i0value self.BinCounts[BinNumber] += 1 def endcalibcycle( self, env ) : """This optional method is called if present at the end of the calibration cycle. @param env environment object """ logging.info( "pyana_fccd_delay.endcalibcycle() called" ) def endrun( self, env ) : """This optional method is called if present at the end of the run. @param env environment object """ logging.info( "pyana_fccd_delay.endrun() called" ) def endjob( self, env ) : """This method is called at the end of the job. It should do final cleanup, e.g. close all open files. @param env environment object """ logging.info( "pyana_fccd_delay.endjob() called" ) print "Starttime: %f" % self.FoundStartTime print "Endtime: %f" % self.FoundEndTime numImages = np.sum( self.BinCounts ) if numImages < 1 : print "No images found! " return # trimmed images (480x480) if self.trim_images: self.avg_image = self.trim_image( self.avg_image ) try: self.dark_array = self.trim_image( self.dark_array ) except: pass TrimmedImageArray = np.zeros((self.iNumBins, 480, 480)) # Trimmed images for bin in range (0, self.iNumBins): TrimmedImageArray[bin] = self.trim_image( self.ImageArray[bin] ) del self.ImageArray self.ImageArray = TrimmedImageArray timer_stop = time.clock() duration = timer_stop - self.timer_start print "Job duration ", duration print "Have collected average image %s from %d events: " %(self.avg_image.shape,numImages) if self.dark_array is not None: print "Dark array: ", self.dark_array.shape print "Have images from %d bins, number of entries in each: "%self.iNumBins, self.BinCounts # compute average self.avg_image = self.avg_image / numImages ##################################################### # Plotting ##################################################### plt.ion() if self.dark_array is not None: plt.figure(200) ax200 = plt.imshow(self.dark_array) colb200 = plt.colorbar(ax200, pad=0.01) plt.title("background") plt.draw() # subtract background self.avg_image -= self.dark_array else : darkfile = self.FileFolder + "/dark.npy" np.save(darkfile, self.avg_image) print "Average image has been saved to ", darkfile plt.figure(100) plt.title("average") ax100 = plt.imshow(self.avg_image) colb100 = plt.colorbar(ax100, pad=0.01) plt.draw() plt.figure(300) plt.title("I0 intensity") plt.plot(self.I0,'ro') plt.draw() ################ # Normalize the averaged images ################ spy.savetxt("%s/BinCounts.txt" % self.FileFolder, self.BinCounts) for bin in range (0, self.iNumBins): if self.BinCounts[bin] <= 0 : continue # skip to the next bin # normalize image to bin counts self.ImageArray[bin] = self.ImageArray[bin] / self.BinCounts[bin] if self.dark_array is not None: # background subtract image self.ImageArray[bin] -= self.dark_array # normalize i0 intensity to bin count self.I0[bin] = self.I0[bin] / self.BinCounts[bin] # normalize background-subtracted image to intensity if self.dark_array is not None: # if dark, the intensity is likely to be zero self.ImageArray[bin] = self.ImageArray[bin] / self.I0[bin] plt.figure(1) plt.clf() axim = plt.imshow( self.ImageArray[bin] ) colb = plt.colorbar(axim, pad=0.01) plt.title("bin %d"%bin) plt.draw() if self.dark_array is not None: self.ImageArray[bin] = self.ImageArray[bin] - self.dark_array saveeach = True if saveeach : fName = "%s/Image%04d.npy"%(self.FileFolder,bin) np.save( fName, self.ImageArray[bin] ) #plt.hist( np.float_(self.hTime), 100, histtype='stepfilled' ) plt.ioff() plt.show() print "Bad events: ", self.badEvents print "Total number of events: ", self.nev print "Bad events: ", len(self.badEvents) print "Good events: ", self.nev - len(self.badEvents) def trim_image(self, image): # return if already trimmed if image.shape == (480,480): print "Request to trim an already trimmed image... return original image" return image """ // Height: // 500 rows = 6 + 240 * 7 + 240 + 7 // Dark A: 6 Rows 0-5 // Data Top: 240 Rows 6-245 // Dark B: 7 Rows 246-252 // Data Bottom: 240 Rows 253-492 // Dark C: 7 Rows 493-249 // // Width (in 16-bit pixels): // 576 pixels = 12 * 48 outputs // Top: (10 image pixels followed by 2 info pixels) * 48 outputs // Bottom: (2 info pixels followed by 10 image pixels) * 48 outputs """ DataTop = image[6:246,:] DataBottom = image[253:493,:] slicesTop = np.split(DataTop,48,axis=1) slicesBottom = np.split(DataBottom,48,axis=1) slicesTopTrimmed = [] slicesBottomTrimmed = [] for i in range( 0, 48 ): slicesTopTrimmed.append( slicesTop[i][:,0:10] ) slicesBottomTrimmed.append( slicesBottom[i][:,2:12] ) DataTop = np.concatenate( slicesTopTrimmed, axis=1 ) DataBottom = np.concatenate( slicesBottomTrimmed, axis=1 ) newimage = np.concatenate( (DataTop,DataBottom) ) return newimage
Java
UTF-8
10,857
1.898438
2
[]
no_license
package cordova.plugin.LivePersonPlugin; import android.content.Context; import android.util.Log; import com.google.firebase.messaging.RemoteMessage; import com.liveperson.infra.model.MessageOption; import com.liveperson.infra.model.PushMessage; import com.liveperson.messaging.sdk.api.LivePerson; import com.liveperson.messaging.sdk.api.callbacks.LogoutLivePersonCallback; import com.liveperson.monitoring.sdk.responses.LPEngagementResponse; import org.apache.cordova.CallbackContext; import org.apache.cordova.CordovaPlugin; import org.json.JSONArray; import org.json.JSONException; import java.util.Collections; import java.util.List; import java.util.Map; /** * This class echoes a string called from JavaScript. */ public class LivePersonPlugin extends CordovaPlugin { private static final String TAG = "LivePersonPlugin"; // QMC private static String BRAND_ID = "70387001"; private static String APP_INSTALLATION_ID = "81be1920-b6cb-450d-87eb-d21b9c90e62f"; private String APP_ID = "com.quantummaterialscorp.healthid"; //It's the applicationId, which will be used for FCM. private String ISSUER = "QMC_Android"; private String firstName; private String LPResponse; LPEngagementResponse maintainResponse; private JSONArray entryPoints; @Override public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException { if (action.equals("instantiateLPMessagingSDK")) { firstName = args.getString(0); // BRAND_ID = args.getString(1); //TODO question: is it possible that we change the BRAND_ID? Can we hardcode it or no. // APP_INSTALLATION_ID = args.getString(2); //TODO save question as BRAND_ID // APP_ID = args.getString(3);//TODO save question as BRAND_ID // ISSUER = args.getString(4);//TODO save question as BRAND_ID // try { // JSONObject customEntryPoints = new JSONObject(); // customEntryPoints.put("entryPoint", args.getString(5)); // Log.d("Recieved Custom", customEntryPoints.toString()); // customEntryPoints.put("entryPointEnvironment", args.getString(6)); // customEntryPoints.put("entryPointCountry", args.getString(7)); // customEntryPoints.put("entryPointlanguage", args.getString(8)); // Log.d("Recieved Custom", customEntryPoints.toString()); // entryPoints = new JSONArray(); // entryPoints.put(args.getString(5)) // .put(args.getString(6)) // .put(args.getString(7)) // .put(args.getString(8)); // entryPoints = new JSONArray(); // entryPoints.put("android-default") // .put("dev") // .put("us") // .put("en"); this.ConnectToBot(firstName, callbackContext); // } catch (JSONException e) { // Log.d("Recieved Custom", e.toString()); // } return true; } else if(action.equals("ConnectToBot")){ entryPoints = new JSONArray(); entryPoints.put(args.get(0)) .put(args.get(1)) .put(args.get(2)) .put(args.get(3)); getEngagement(callbackContext); return true; } else { showConversation(firstName,maintainResponse,callbackContext); return true; } } private void coolMethod(String message, CallbackContext callbackContext) { if (message != null && message.length() > 0) { callbackContext.success(message); } else { callbackContext.error("Expected one non-empty string argument."); } } private void ConnectToBot(String message, CallbackContext callbackContext) { if (message != null && message.length() > 0) { callbackContext.success(message); initLpSDK(callbackContext); /*Context context = cordova.getActivity().getApplicationContext(); Intent intent = new Intent(context, cordova.plugin.LivePersonPlugin.LivePersonChatRoom.class); this.cordova.getActivity().startActivity(intent);*/ } else { callbackContext.error("Expected one non-empty string argument."); } } public void initLpSDK(CallbackContext callbackContext) { Context context = cordova.getActivity().getApplicationContext(); LpMessagingWrapper.initializeLPMessagingSDK(context, new LpMessagingWrapper.Listener() { @Override public void onSuccess() { callbackContext.success("pre_engagement"); Log.d(TAG, "pre_engagement"); // getEngagement(callbackContext); //TODO remove this line if want to call it from Ionic. // showConversationWithoutEngagement(firstName, callbackContext); } @Override public void onError(String error) { callbackContext.error(error); Log.e(TAG, error); } }); } public void getEngagement(CallbackContext callbackContext) { Context context = cordova.getActivity().getApplicationContext(); Log.d(TAG, "getEngagement with entry points: " + entryPoints); LpMessagingWrapper.getEngagement(context, entryPoints, new LpMessagingWrapper.GetEngagementListener() { @Override public void onSuccess(LPEngagementResponse response) { callbackContext.success("post Engagement"); maintainResponse = response; // showConversation(firstName, response, callbackContext); //TODO remove this line if want to call it from Ionic. } @Override public void onError(String error) { callbackContext.error(error); Log.e(TAG, error); } }); } public void showConversation(String firstName, LPEngagementResponse response, CallbackContext callbackContext) { //TODO Needs to set welcome message and optionItems from Ionic. String welcomeMessage = "Hi, I'm BELLA, your automated health assistant. I'll be guiding you through your at-home COVID-19 test."; List<MessageOption> optionItems = Collections.singletonList(new MessageOption("Start", "Start")); LpMessagingWrapper.showConversation(cordova.getActivity(), firstName, welcomeMessage, optionItems, response, new LpMessagingWrapper.Listener() { @Override public void onSuccess() { callbackContext.success(); //TODO register pusher either here or in Ionic. } @Override public void onError(String error) { callbackContext.error(error); Log.e(TAG, error); } }); } public void showConversationWithoutEngagement(String firstName, CallbackContext callbackContext) { //TODO Needs to set welcome message and optionItems from Ionic. String welcomeMessage = "Hi, I'm BELLA, your automated health assistant. I'll be guiding you through your at-home COVID-19 test."; List<MessageOption> optionItems = Collections.singletonList(new MessageOption("Start", "Start")); LpMessagingWrapper.showConversation(cordova.getActivity(), firstName, welcomeMessage, optionItems, new LpMessagingWrapper.Listener() { @Override public void onSuccess() { callbackContext.success(); //TODO register pusher either here or in Ionic. } @Override public void onError(String error) { callbackContext.error(error); Log.e(TAG, error); } }); } public void registerLpPusher(String deviceToken, CallbackContext callbackContext) { LpMessagingWrapper.registerLPPusher(deviceToken, new LpMessagingWrapper.Listener() { @Override public void onSuccess() { callbackContext.success(); } @Override public void onError(String error) { callbackContext.error(error); Log.e(TAG, error); } }); } /** * This is an example of how push notification works with SDK. * TODO The method below should show a notification banner. If the way Ionic work is different, you can simply ignore/delete this method. */ private void showPushNotification(Context context, PushMessage pushMessage) { } /** * Logout the SDK. Device will be unregistered from LP pusher. * All cached data will be deleted. */ public void logout(CallbackContext callbackContext) { Context context = cordova.getActivity().getApplicationContext(); LivePerson.logOut(context, BRAND_ID, APP_ID, new LogoutLivePersonCallback() { @Override public void onLogoutSucceed() { callbackContext.success("logout succeed"); } @Override public void onLogoutFailed() { callbackContext.error("Failed to logout"); } }); } /** * Clear conversation history. (Only closed conversation can be cleared) */ public void clearHistory() { LivePerson.clearHistory(); } public void resolveConversation() { LivePerson.resolveConversation(); } /** * Pass the data message received from {@link com.gae.scaffolder.plugin.MyFirebaseMessagingService#onMessageReceived(RemoteMessage)} * The message push notification received is * <br/> * <b>{payload={"badge":1,"sequence":8,"conversationId":"3e951ec7-a450-4a24-8058-b19cc9881c67","brandId":"61895277","backendService":"ams","originatorId":"61895277.1197179432","dialogId":"3e951ec7-a450-4a24-8058-b19cc9881c67"}, message=Mask Push Notification}</b> * <br/> * <p> * {@link LivePerson#handlePushMessage(Context, Map, String, boolean)} parses it to an {@link PushMessage} object. * TODO call this method when receive push notification. * * @param remoteMessageData It's the data message received from FCM. The value is RemoteMessage.getData(). */ public void showPushNotification(Map<String, String> remoteMessageData) { Context context = cordova.getActivity().getApplicationContext(); PushMessage message = LivePerson.handlePushMessage(context, remoteMessageData, BRAND_ID, false); if (message != null) { showPushNotification(context, message); } } }
C++
UTF-8
1,409
2.890625
3
[]
no_license
#include "doctest.h" #include "../game-source-code/BackEndSystems/UpdateGameObjectDisplay.h" #include "../game-source-code/FrontEndSystems/GameObject.h" #include "../game-source-code/FrontEndSystems/GraphicObject.h" #include <memory> TEST_CASE("1.0 The Sprite graphic is updated correctly according to the GameObject provided") { UpdateGameObjectDisplay updateObject; SUBCASE("1.1 Exception thrown when a graphic doesnt exist") { GraphicObject falseGraphic("FakeGraphic.jpeg", "FakeGraphic"); auto testGameObject = std::make_shared<GameObject>(falseGraphic); REQUIRE_THROWS_AS(updateObject.DetermineGameObjectChanges(testGameObject), FailedToLoadTexture); } SUBCASE("1.2 The position of the sprite is updated correctly") { Vector2D gamePosition; auto testGameObject = std::make_shared<GameObject>(gamePosition); auto testSprite = updateObject.DetermineGameObjectChanges(testGameObject); sf::Vector2f expectedPosition{960, 540}; auto recievedVector = testSprite.getPosition(); CHECK_EQ(recievedVector,expectedPosition); } SUBCASE("1.3 The scale of the Object is updated correctly") { xyVector objectScale{10,10}; auto testGameObject = std::make_shared<GameObject>(objectScale); auto testSprite = updateObject.DetermineGameObjectChanges(testGameObject); auto recievedScale = testSprite.getScale(); sf::Vector2f testScale{10,10}; CHECK_EQ(recievedScale, testScale); } }
Markdown
UTF-8
3,494
3.109375
3
[ "MIT" ]
permissive
# TypeScript typings for Google Mirror API v1 Interacts with Glass users via the timeline. For detailed description please check [documentation](https://developers.google.com/glass). ## Installing Install typings for Google Mirror API: ``` npm install @types/gapi.client.mirror@v1 --save-dev ``` ## Usage You need to initialize Google API client in your code: ```typescript gapi.load("client", () => { // now we can use gapi.client // ... }); ``` Then load api client wrapper: ```typescript gapi.client.load('mirror', 'v1', () => { // now we can use gapi.client.mirror // ... }); ``` Don't forget to authenticate your client before sending any request to resources: ```typescript // declare client_id registered in Google Developers Console var client_id = '', scope = [ // View your location 'https://www.googleapis.com/auth/glass.location', // View and manage your Glass timeline 'https://www.googleapis.com/auth/glass.timeline', ], immediate = true; // ... gapi.auth.authorize({ client_id: client_id, scope: scope, immediate: immediate }, authResult => { if (authResult && !authResult.error) { /* handle succesfull authorization */ } else { /* handle authorization error */ } }); ``` After that you can use Google Mirror API resources: ```typescript /* Inserts a new account for a user */ await gapi.client.accounts.insert({ accountName: "accountName", accountType: "accountType", userToken: "userToken", }); /* Deletes a contact. */ await gapi.client.contacts.delete({ id: "id", }); /* Gets a single contact by ID. */ await gapi.client.contacts.get({ id: "id", }); /* Inserts a new contact. */ await gapi.client.contacts.insert({ }); /* Retrieves a list of contacts for the authenticated user. */ await gapi.client.contacts.list({ }); /* Updates a contact in place. This method supports patch semantics. */ await gapi.client.contacts.patch({ id: "id", }); /* Updates a contact in place. */ await gapi.client.contacts.update({ id: "id", }); /* Gets a single location by ID. */ await gapi.client.locations.get({ id: "id", }); /* Retrieves a list of locations for the user. */ await gapi.client.locations.list({ }); /* Gets a single setting by ID. */ await gapi.client.settings.get({ id: "id", }); /* Deletes a subscription. */ await gapi.client.subscriptions.delete({ id: "id", }); /* Creates a new subscription. */ await gapi.client.subscriptions.insert({ }); /* Retrieves a list of subscriptions for the authenticated user and service. */ await gapi.client.subscriptions.list({ }); /* Updates an existing subscription in place. */ await gapi.client.subscriptions.update({ id: "id", }); /* Deletes a timeline item. */ await gapi.client.timeline.delete({ id: "id", }); /* Gets a single timeline item by ID. */ await gapi.client.timeline.get({ id: "id", }); /* Inserts a new item into the timeline. */ await gapi.client.timeline.insert({ }); /* Retrieves a list of timeline items for the authenticated user. */ await gapi.client.timeline.list({ }); /* Updates a timeline item in place. This method supports patch semantics. */ await gapi.client.timeline.patch({ id: "id", }); /* Updates a timeline item in place. */ await gapi.client.timeline.update({ id: "id", }); ```
Java
UTF-8
337
1.539063
2
[]
no_license
package com.example.apblue.jpahibernateexamples.serviceImpl; import com.example.apblue.jpahibernateexamples.service.StaffService; import com.example.apblue.jpahibernateexamples.model.Staff; import org.springframework.stereotype.Service; @Service public class StaffServiceImpl extends BaseServiceImpl<Staff> implements StaffService { }
Python
UTF-8
752
3.0625
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Mar 2 10:05:41 2019 @author: john """ from EvaluatedNetwork import EuclideanNetwork TestMap = EuclideanNetwork(8) TestMap.Connect(0,1,1) TestMap.Connect(1,2,1) TestMap.Connect(1,7,2) TestMap.Connect(7,4,1) TestMap.Connect(1,5,8) TestMap.Connect(2,3,1) TestMap.Connect(4,6,2) TestMap.Connect(5,4,3) TestMap.set_euc(0,6,6) TestMap.set_euc(1,6,5) TestMap.set_euc(2,6,6) TestMap.set_euc(3,6,7) TestMap.set_euc(4,6,2) TestMap.set_euc(5,6,1) TestMap.set_euc(6,6,0) TestMap.set_euc(7,6,3) print("Using Greedy Search:") path = TestMap.GreedySearch(0,6) if path[0] != -1: print(path[:-1]) print("\nUsing A* Search:") path2 = TestMap.Astar(0,6) if path[0] != -1: print(path2[:-1])
SQL
UTF-8
3,388
4.5625
5
[]
no_license
--------------------------------- 문제 --------------------------------- 1) department_id가 60인 부서의 도시명을 알아내는 SELECT문장을 기술하시오 SELECT city FROM locations WHERE location_id = (SELECT location_id FROM departments WHERE department_id = 60); 2)사번이 107인 사원과 부서가같고,167번의 급여보다 많은 사원들의 사번,이름(first_name),급여를 출력하시오. SELECT employee_id, first_name, salary FROM employees WHERE department_id = (SELECT department_id FROM employees WHERE employee_id = 107) AND salary > (SELECT salary FROM employees WHERE employee_id = 167); 3) 급여평균보다 급여를 적게받는 사원들중 커미션을 받는 사원들의 사번,이름(first_name),급여,커미션 퍼센트를 출력하시오. SELECT employee_id, first_name, salary, commission_pct FROM employees WHERE salary < (SELECT avg(salary) FROM employees) AND commission_pct is not null; 4)각 부서의 최소급여가 20번 부서의 최소급여보다 많은 부서의 번호와 그부서의 최소급여를 출력하시오. SELECT department_id, min(salary) FROM employees GROUP BY department_id HAVING min(salary) > (SELECT min(salary) FROM employees WHERE department_id = 20) ORDER BY department_id; 5) 사원번호가 177인 사원과 담당 업무가 같은 사원의 사원이름(first_name)과 담당업무(job_id)하시오. SELECT first_name, job_id FROM employees WHERE job_id = (SELECT job_id FROM employees WHERE employee_id=177); 6) 최소 급여를 받는 사원의 이름(first_name), 담당 업무(job_id) 및 급여(salary)를 표시하시오(그룹함수 사용). SELECT first_name, job_id, salary FROM employees WHERE salary = (SELECT min(salary) FROM employees); 7)7)업무별 평균 급여가 가장 적은 업무(job_id)를 찾아 업무(job_id)와 평균 급여를 표시하시오. SELECT job_id, AVG(salary) FROM employees GROUP by job_id HAVING AVG(salary) = (SELECT MIN(AVG(salary)) FROM employees GROUP BY job_id); 8) 각 부서의 최소 급여를 받는 사원의 이름(first_name), 급여(salary), 부서번호(department_id)를 표시하시오. SELECT first_name, salary, department_id FROM employees WHERE (department_id,salary) in (SELECT department_id,MIN(salary) FROM employees GROUP BY department_id) ORDER BY department_id; 9)담당 업무가 프로그래머(IT_PROG)인 모든 사원보다 급여가 적으면서 업무가 프로그래머(IT_PROG)가 아닌 사원들의 사원번호(employee_id), 이름(first_name), 담당 업무(job_id), 급여(salary))를 출력하시오. SELECT employee_id, first_name, job_id, salary FROM employees WHERE salary < (SELECT min(salary) FROM employees WHERE job_id='IT_PROG') AND job_id <> 'IT_PROG'; 10)부하직원이 없는 모든 사원의 이름을 표시하시오. SELECT employee_id, first_name FROM employees WHERE employee_id not in(SELECT e.employee_id FROM employees e, employees m WHERE e.employee_id=m.manager_id);
C
UTF-8
227
2.734375
3
[]
no_license
// function turns on the LED when the distance exceeds 100 meters. void led_out(unsigned char data) { if( data>=100) // checking if distance covered exceeded 100 meter {GPIO_PORTF_DATA_R |= 0x02} // turn on red led }
C++
UTF-8
4,686
2.8125
3
[]
no_license
#include "Common.h" #include "BuildOrderGoalManager.h" #include "BuildingManager.h" BuildOrderGoalItem::BuildOrderGoalItem(const MetaType & metaType, int count, int priority, bool blocking) : metaType(metaType), count(count), priority(priority), blocking(blocking) { if (priority != -1) return; // set priorities switch (metaType.type) { case MetaType::Tech: priority = 10000; break; case MetaType::Upgrade: priority = 0; break; case MetaType::Unit: priority = 0; break; default: priority = 0; break; } } bool BuildOrderGoalManager::isCompleted(const BuildOrderGoalItem & bogi, const BuildOrder & buildOrder) { if (bogi.count == 0) return true; int count = 0; BOOST_FOREACH(const ToBuild & toBuild, buildOrder) { if (toBuild.first == bogi.metaType) { ++count; } } if (bogi.metaType.type == MetaType::Unit) { count += BWAPI::Broodwar->self()->allUnitCount(bogi.metaType.unitType); // tanks can be multiple types if (bogi.metaType.unitType == BWAPI::UnitTypes::Terran_Siege_Tank_Tank_Mode) { count += BWAPI::Broodwar->self()->allUnitCount(BWAPI::UnitTypes::Terran_Siege_Tank_Siege_Mode); } // we definitely have enough units if (count >= bogi.count) return true; // check buildings under construction if (bogi.metaType.unitType.isBuilding()) { count += BuildingManager::Instance().buildingCount(bogi.metaType.unitType); } if (count >= bogi.count) return true; // not enough return false; } // if we have not researched that tech, return false else if (bogi.metaType.type == MetaType::Tech) { if (!BWAPI::Broodwar->self()->hasResearched(bogi.metaType.techType) && !BWAPI::Broodwar->self()->isResearching(bogi.metaType.techType) && count == 0 && bogi.count > 0) { return false; } } // if we have not upgraded to that level, return false else if (bogi.metaType.type == MetaType::Upgrade) { count += BWAPI::Broodwar->self()->getUpgradeLevel(bogi.metaType.upgradeType); if (BWAPI::Broodwar->self()->isUpgrading(bogi.metaType.upgradeType)) { ++count; } if (count < bogi.count) { return false; } } return true; } BuildOrderGoalManager::BuildOrderGoalManager(const BOGIVector & items) { BOOST_FOREACH(const BuildOrderGoalItem & item, items) { // see if an item with this priority already exists int existingIndex = -1; for (int i(0); i < (int)goals.size(); ++i) { if (goals[i].priority == item.priority) { existingIndex = i; break; } } // if it already exists, add it to that goal if (existingIndex != -1) { goals[existingIndex].addItem(item); } // otherwise create a new goal else { BuildOrderGoal temp(item.priority); temp.addItem(item); goals.push_back(temp); } } // sort by priority std::sort(goals.rbegin(), goals.rend()); } void BuildOrderGoalManager::getBuildOrder(BuildOrder & buildOrder) { // Determine supply provider BWAPI::UnitType supplyType = BWAPI::Broodwar->self()->getRace().getSupplyProvider(); int supplyPerProvider = supplyType.supplyProvided(); // Determine future supply int supplyRemaining = BWAPI::Broodwar->self()->supplyTotal(); supplyRemaining += BuildingManager::Instance().buildingCount(supplyType) * supplyPerProvider; supplyRemaining += BuildingManager::Instance().buildingCount(BWAPI::UnitTypes::Terran_Command_Center) * BWAPI::UnitTypes::Terran_Command_Center.supplyProvided(); int supplyUsed = BWAPI::Broodwar->self()->supplyUsed(); supplyRemaining -= supplyUsed; BOOST_FOREACH(BuildOrderGoal & bog, goals) { bool complete = false; // keep repeating to queue items of same priority in a round-robin fashion while (!complete) { complete = true; BOOST_FOREACH(BuildOrderGoalItem & bogi, bog.items) { // don't queue beyond max supply if (bogi.metaType.isUnit() && supplyUsed + bogi.metaType.unitType.supplyRequired() > 400) { continue; } // this item hasn't been completed, so add one to the build order if (!isCompleted(bogi, buildOrder)) { buildOrder.push_back(std::pair<MetaType, bool>(bogi.metaType, bogi.blocking)); // account for projected supply amount supplyRemaining -= bogi.metaType.supplyRequired(); if (bogi.metaType.isUnit()) supplyRemaining += bogi.metaType.unitType.supplyProvided(); supplyUsed += bogi.metaType.supplyRequired(); // build more supply providers if (supplyRemaining < supplyPerProvider) { buildOrder.push_back(std::pair<MetaType, bool>(supplyType, false)); supplyRemaining += supplyPerProvider; } complete = false; } else { // mark as complete bogi.count = 0; } } } } }
Shell
UTF-8
1,338
2.84375
3
[]
no_license
# copy files git init . # Look at .gitignore git commit -am "Initial commit" echo "There are 9 planets in the solar system" > planets.txt git add planets.txt git commit -m "Stated number of planets" echo "There are 8 planets in the solar system" > planets.txt git add planets.txt git commit -m "Reduced number of planets to 8. Pluto isn't a planet" git checkout -b star-test echo "There is a single star in our solar system" > stars.txt git add stars.txt git commit -m "Stated number of stars" git checkout master echo "There is also 1 dwarf planet in the solar system" >> planets.txt git add planets.txt git commit -m "Compromised on the status of Pluto" git merge star-test # Sometimes there are conflicts git checkout -b rethinking-planets echo "There are 9 planets in the solar system" > planets.txt git add planets.txt git commit -m "Changed my mind - Pluto is definitely a planet" git checkout master sed -i '2 d' planets.txt echo "There is also 1 dwarf planet in the solar system named Pluto" >> planets.txt git add planets.txt git commit -m "Named the dwarf planet Pluto" git merge rethinking-planets # In case of panic, use `git merge --abort` to go back to previous state # Clone a project cd .. git clone git@github.com:sebastian-c/r-group-code.git # Note that we now have bitbucket on https://sdlc.fao.org/bitbucket
C#
UTF-8
4,511
3.015625
3
[]
no_license
using System; using MySql.Data.MySqlClient; using System.Data.Common; namespace KPO_laba4 { class InsertDB: IDB { MySqlConnection connection; public InsertDB(MySqlConnection conn) { connection = conn; try { // Подключение к БД Console.WriteLine("Открывающееся соединение..."); conn.Open(); Console.WriteLine("Соединение успешно!"); } catch (Exception e) { Console.WriteLine("Error: " + e.Message); conn.Close(); conn.Dispose(); } } public void Insert_cabinet(string nameCabinet) { MySqlCommand cmd = new MySqlCommand(); string query = "INSERT INTO `cabinet` (`nameCabinet`) VALUES (@nameCabinet)"; cmd.Connection = connection; cmd.CommandText = query; MySqlParameter nameCabinet_param = new MySqlParameter("@nameCabinet", MySqlDbType.VarChar); nameCabinet_param.Value = nameCabinet; cmd.Parameters.Add(nameCabinet_param); try { cmd.ExecuteNonQuery(); } catch (Exception e) { Console.WriteLine(e.Message); connection.Close(); } } public void Insert_teacher(string surname, string name, string midname, int numPairs, int numStud) { MySqlCommand cmd = new MySqlCommand(); string query = "INSERT INTO `teacher` (`surname`, `name`, `midname`, `numPairs`, `numStud`) VALUES (@surname, @name, @midname, @numPairs, @numStud)"; cmd.Connection = connection; cmd.CommandText = query; MySqlParameter surname_param = new MySqlParameter("@surname", MySqlDbType.VarChar); surname_param.Value = surname; cmd.Parameters.Add(surname_param); MySqlParameter name_param = new MySqlParameter("@name", MySqlDbType.VarChar); name_param.Value = name; cmd.Parameters.Add(name_param); MySqlParameter midname_param = new MySqlParameter("@midname", MySqlDbType.VarChar); midname_param.Value = midname; cmd.Parameters.Add(midname_param); MySqlParameter numPairs_param = new MySqlParameter("@numPairs", MySqlDbType.Int32); numPairs_param.Value = numPairs; cmd.Parameters.Add(numPairs_param); MySqlParameter numStud_param = new MySqlParameter("@numStud", MySqlDbType.Int32); numStud_param.Value = numStud; cmd.Parameters.Add(numStud_param); try { cmd.ExecuteNonQuery(); } catch (Exception e) { Console.WriteLine(e.Message); connection.Close(); } } public void Insert_thing(string nameThing, int idWeek, int idCabinet, int idTeacher) { MySqlCommand cmd = new MySqlCommand(); string query = "INSERT INTO `thing` (`nameThing`, `idWeek`, `idCabinet`, `idTeacher`) VALUES (@nameThing, @idWeek, @idCabinet, @idTeacher)"; cmd.Connection = connection; cmd.CommandText = query; MySqlParameter nameThing_param = new MySqlParameter("@nameThing", MySqlDbType.VarChar); nameThing_param.Value = nameThing; cmd.Parameters.Add(nameThing_param); MySqlParameter idWeek_param = new MySqlParameter("@idWeek", MySqlDbType.Int32); idWeek_param.Value = idWeek; cmd.Parameters.Add(idWeek_param); MySqlParameter idCabinet_param = new MySqlParameter("@idCabinet", MySqlDbType.Int32); idCabinet_param.Value = idCabinet; cmd.Parameters.Add(idCabinet_param); MySqlParameter idTeacher_param = new MySqlParameter("@idTeacher", MySqlDbType.Int32); idTeacher_param.Value = idTeacher; cmd.Parameters.Add(idTeacher_param); try { cmd.ExecuteNonQuery(); } catch (Exception e) { Console.WriteLine(e.Message); connection.Close(); } } public void CloseConnection() { connection.Close(); } } }
Markdown
UTF-8
3,914
3.328125
3
[]
no_license
title: 工作和生活的游戏化 date: 2016-04-18 16:19:21 tags: [Work, Game] --- 今天会议的一个有趣的point,稍微记录一下: 很多人人愿意花时间到游戏中却不愿意花时间去更加努力地工作。游戏在人的工作和生活中不是必需的,但是为什么它这么吸引人? 简单来说有八大驱动力: - 史诗意义与使命感 - 进步与成就感 - 创意授权与反馈 - 所有权与拥有感 - 社交影响与关联性 - 稀缺性与渴望 - 未知性与好奇心 - 损失与逃避心 <!-- more --> 人生如戏,戏如人生。我觉得支持我们活着、工作和生活肯定也是这八个驱动力,有一点不一样的是游戏可以删档重来,人生不可以。可以说游戏的试错成本比人生少得多,所以游戏中会可能出现更多的创新和奇怪的东西,而真实世界人们做事都会估算后果才行动,大部分人会用评估出来的最高“期望值”去行动。 其实我们都活在游戏里面,规则的制定者叫政府,我们活在政府的法律规则下,所有人都不能打破这种规则,除非武装起义推翻政权,你成为了规则制定者。 我们想创造一个规则调动起我们的用户,其实我们是在建立一个帝国,我们是政府组织,这涉及到各种各样的规则,但是我觉得可以用一些简单的数学公式去描绘整个帝国的输入输出关系。 我们可以定义一个人在工作中的输入是时间TIME和技术Tech,每个人在社会中想得到的事物基本是钱MONEY、性SEX、爱好INTEREST和时间TIME。用户在使用我们系统的时候,会有以下的系统流程: TIME+Tech (INPUT) --> 系统 --> MONEY+SEX+INTEREST+TIME (OUTPUT) 我们可以计算用户投入期望和输出期望(期望这里是一个数学概念,我们不需要每次投入产出都按照下面规则,但是一段稍长时间的总体输入输出需要满足下面规则,不懂请百度): IF OUTPUT >= INPUT THEN 用户会重复使用系统 ELSE 用户觉得系统是坑爹的永远不会再来 我们可以用数据来标准杯INPUT和OUTPUT。INPUT简单来说可以是用户的时薪,每个用户都会有工资或者每年的产出利润,划算成为时薪就可以是INPUT。OUTPUT的计算有主观性,除了MONEY和TIME可以计算,SEX和INTERST可以用大量数据做量化,但是不能主观计算。 简单来说,一个用户投入时间和技术到系统,他肯定会期望得到些什么,我们可以提供SEX、MONEY、INTEREST和TIME,通俗来说,平台可以给他YP、赚钱、得到创意和在别的地方省了时间。我们可以用大量的数据来计算这个期望值。一个良性的输入输出系统就像金融系统,资本总是不断壮大的,因为人类的总体生产价值在不断提高,如何做好一个游戏需要一整套想法,但是需要尽快行动以得到反馈。 其实要看这个系统是否健康,就看这个期望值(OUTPUT-INPUT)是不是非负的,我们只要确保这个期望值是非负,用户就会拥戴我们,我们就可以慢慢建立起整个帝国。看似只是一个期望值,但是要做的东西可不是这么简单。 努力吧~骚年。 ---------------------以下是修正部分 后台我觉得我们做的事情不是建立一个国家,而是一种宗教信仰。宗教信仰是不是职业,信教的人也是业余信教的,只是这种思维贯穿了他们整个生活和工作。宗教是依靠一种价值观,一个巨大的故事背景,使信徒有使命感,利用教条去约束信徒的行为,并且要求信徒向宗教无私奉献。宗教是利用使命感驱动的,但是我们不是,我们是利用所谓的创造力驱动。我们是否可以建立这种使命感,还是别的东西,因为我觉得创造力始终不是能够使人信仰的东西。
Python
UTF-8
166
3.359375
3
[]
no_license
# Length of Last Word def lengthOfLastWord(self, s: str) -> int: words = s.split() if words == []: return 0 return len(words[-1])
C++
UTF-8
1,681
3.625
4
[ "MIT" ]
permissive
#pragma once #include <string> #include <cmath> template<typename T> struct Vec2 { T x, y; Vec2() : x{}, y{} {} Vec2(T x, T y) : x{x}, y{y} {} template<typename U> inline operator Vec2<U>() const { return Vec2<U>(x, y); } inline bool operator==(const Vec2<T>& other) const { return x == other.x && y == other.y; } inline bool operator!=(const Vec2<T>& other) const { return x != other.x || y != other.y; } inline Vec2<T> operator+(const Vec2<T>& other) const { return Vec2<T>(x + other.x, y + other.y); } inline void operator+=(const Vec2<T>& other) { x += other.x; y += other.y; } inline Vec2<T> operator-(const Vec2<T>& other) const { return Vec2<T>(x - other.x, y - other.y); } inline Vec2<T> operator-() const { return Vec2<T>(-x, -y); } inline void operator-=(const Vec2<T>& other) { x -= other.x; y -= other.y; } inline Vec2<T> operator*(T value) const { return Vec2<T>(x * value, y * value); } inline Vec2<T> operator*(Vec2<T> const& value) const { return Vec2<T>(x * value.x, y * value.y); } inline void operator*=(T value) { x *= value; y *= value; } inline Vec2<T> operator/(T value) const { return Vec2<T>(x / value, y / value); } inline Vec2<T> operator/(Vec2<T> const& value) const { return Vec2<T>(x / value.x, y / value.y); } inline void operator/=(T value) { x /= value; y /= value; } inline T size() const { return x * y; } inline T length_squared() const { return x * x + y * y; } inline T length() const { return sqrt(x * x + y * y); } std::string to_string() const { return std::string("(") + std::to_string(x) + ", " + std::to_string(y) + ")"; } }; typedef Vec2<int> Vec2i; typedef Vec2<double> Vec2d;
Python
UTF-8
3,416
2.953125
3
[ "MIT" ]
permissive
# -*- coding: utf-8 -*- """ Created on Thu Sep 25 15:41:33 2014 @author: dvalovcin """ import numpy as np from PyQt5 import QtWidgets, QtCore from ..curves.clickablePlotWidget import ClickablePlotWidget import pyqtgraph as pg class DoubleYPlot(ClickablePlotWidget): """ Often want to have a graph which has two independent y axes. it's a bit more work to always handle, so have a simple function with conveniences for easy calling and manipulating Add linear regions to plotItem1 or p2 """ def __init__(self, *args, **kwargs): super(DoubleYPlot, self).__init__(*args, **kwargs) self.plotOne = self.plot() self.plotItem1 = self.plotItem #http://bazaar.launchpad.net/~luke-campagnola/pyqtgraph/inp/view/head:/examples/MultiplePlotAxes.py #Need to do all this nonsense to make it plot on two different axes. #Also note the self.updatePhase plot which shows how to update the data. self.p1 = self.plotItem1.vb self.p2 = pg.ViewBox() self.plotItem1.showAxis('right') self.plotItem1.scene().addItem(self.p2) self.plotItem1.getAxis('right').linkToView(self.p2) self.p2.setXLink(self.plotItem1) self.plotTwo = pg.PlotDataItem() self.p2.addItem(self.plotTwo) #need to set it up so that when the window (and thus main plotItem) is #resized, it informs the ViewBox for the second plot that it must update itself. self.plotItem1.vb.sigResized.connect(lambda: self.p2.setGeometry(self.plotItem1.vb.sceneBoundingRect())) self.setY1Color('k') self.setY2Color('r') print(type(self.plotOne), type(self.plotTwo)) def setXLabel(self, label="X", units=""): self.plotItem1.setLabel('bottom',text=label, units=units) def setY1Label(self, label="Y1", units=""): self.plotItem1.setLabel('left', text=label, units=units, color = self.y1Pen.color().name()) def setY2Label(self, label="Y2", units=""): self.plotItem1.getAxis('right').setLabel(label, units=units, color=self.y2Pen.color().name()) def setTitle(self, title="Title"): self.plotItem1.setTitle(title) def setY1Data(self, *data): if len(data)==1: self.plotOne.setData(data[0]) elif len(data)==2: self.plotOne.setData(*data) else: raise ValueError("I don't know what you want me to plot {}".format(data)) def setY2Data(self, *data): if len(data)==1: self.plotTwo.setData(data[0]) elif len(data)==2: self.plotTwo.setData(*data) self.p2.setGeometry(self.plotItem1.vb.sceneBoundingRect()) def setY2Pen(self, *args, **kwargs): self.y2Pen = pg.mkPen(*args, **kwargs) self.plotItem1.getAxis("right").setPen(self.y2Pen) self.plotTwo.setPen(self.y2Pen) def setY1Color(self, color='k'): self.y1Pen = pg.mkPen(color) self.plotItem1.getAxis("left").setPen(self.y1Pen) self.plotOne.setPen(self.y1Pen) def setY1Pen(self, *args, **kwargs): self.y1Pen = pg.mkPen(*args, **kwargs) self.plotItem1.getAxis("left").setPen(self.y1Pen) self.plotOne.setPen(self.y1Pen) def setY2Color(self, color='r'): self.y2Pen = pg.mkPen(color) self.plotItem1.getAxis("right").setPen(self.y2Pen) self.plotTwo.setPen(self.y2Pen)
C#
UTF-8
2,839
2.765625
3
[]
no_license
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using AsteroidGame.VisualObjects.Interfaces; using AsteroidGame.Properties; namespace AsteroidGame.VisualObjects { class SpaceShip : ImageObject, ICollision { public const int MAX_ENERGY = 1000; private int _Energy = MAX_ENERGY; public int Energy => _Energy; private Weapon _Weapon; public bool IsMotionUp { get; set; } = false; public bool IsMotionDown { get; set; } = false; public bool IsMotionLeft { get; set; } = false; public bool IsMotionRight { get; set; } = false; public bool IsFiring { get; set; } = false; private const int _SPEED = 10; private int _Score = 0; public int Score => _Score; public SpaceShip(Point Position, Size Size, Weapon Weapon) : base(Position, Point.Empty, Size, Resources.Spaceship) { (_Sprite as Bitmap).MakeTransparent(); _Weapon = Weapon; } public override void Update() { _Direction = _GetNextDirection(); _Position = _GetNextPosition(); _Weapon.Position = _GetWeaponPosition(); if (IsFiring) _Weapon.Fire(); } public void ChangeEnergy(int delta) { _Energy = Math.Min(Math.Max(_Energy + delta, 0), MAX_ENERGY); if (_Energy == 0) Game.UnregisterGameObject(this); } private Point _GetWeaponPosition() { return new Point(_Position.X + _Size.Width, _Position.Y + _Size.Height / 2); } private Point _GetNextDirection() { var direction_x = 0; var direction_y = 0; if (IsMotionUp) direction_y -= _SPEED; if (IsMotionDown) direction_y += _SPEED; if (IsMotionLeft) direction_x -= _SPEED; if (IsMotionRight) direction_x += _SPEED; return new Point(direction_x, direction_y); } private Point _GetNextPosition() { var position_x = _Position.X + _Direction.X; var position_y = _Position.Y + _Direction.Y; if (position_x < 0) position_x = 0; else if (position_x + _Size.Width > Game.Width) position_x = Game.Width - _Size.Width; if (position_y < 0) position_y = 0; else if (position_y + _Size.Height > Game.Height) position_y = Game.Height - _Size.Height; return new Point(position_x, position_y); } public void Collision(ICollision obj) { } public void AddScore(int Points) { _Score += Points; } } }
Python
UTF-8
853
3.5
4
[]
no_license
class Solution(object): def partition(self, s): """ :type s: str :rtype: List[List[str]] """ if len(s) == 0: return [] self.res = [] def dfs(s, res): if len(s) == 0: self.res.append(res[:]) return # for i in range(1, len(s) + 1): if self.isPalindrome(s[:i]): # Backtracking res.append(s[:i]) dfs(s[i:], res) res.pop() dfs(s, []) return self.res def isPalindrome(self, s): i = 0 j = len(s) - 1 while i < j: if s[i] != s[j]: return False i += 1 j -= 1 return True test = Solution() print test.partition("aab")
Java
UTF-8
858
3.546875
4
[]
no_license
package recursive; import java.util.*; import java.util.Scanner; public class SortArray { public static void main(String[] args) { /* Type your code here. */ Scanner scnr = new Scanner(System.in); int element = scnr.nextInt(); int[] Myarr = new int[element]; for (int i = 0; i<element;i++) { Myarr[i] = scnr.nextInt(); } sortArray(Myarr,element); for (int each: Myarr){ System.out.print(each+" "); } System.out.println(); } public static void sortArray(int[] myArr, int arrSize) { int temp = 0; int smallest; for(int i=0;i<arrSize-1;i++) { smallest = i; for (int j=i+1;j<arrSize;j++) { if (myArr[smallest]>myArr[j]) { smallest = j; }//if }//for temp = myArr[i]; myArr[i] = myArr[smallest]; myArr[smallest]=temp; }//for }//method }//class
Python
UTF-8
1,043
3.8125
4
[]
no_license
#!/usr/bin/env python # *_* coding:utf-8 *_* # python learning, keep on! data=['0','1','2','3','4','5','6','7','8'] print(data) print(data[1]) print(data[2:5]) print(data[1:7:2]) print(data[5:]) print(data[-1]) print(data[-2:]) print(data[:3]) data.append('9') print(data) data.insert(2,'1.5')#插入 print(data) data[2]='2.8' print(data) del data[2]#删除 print(data) data.remove('9')#删除 print(data) data.pop() print(data)#删除最后一个 data.pop(5)#删除指定下标的元素 print(data) #找出一个值得位置 print(data.index('3')) print(data.count('3'))#统计一个值由多少个。 data.reverse() #反转 print(data) data.sort() #排序 print(data) data2=['11','12'] data.extend(data2) print(data) data.clear()#清空 print(data) del data2 #删除变量 print(data2) data2=data.copy() #复制列表,浅复制,只复制第一层,如果列表里有列表,则复制的时候只复制里边列表的地址。 print(data2) #如果要实现深copy,则要引入 import copy name2=copy.deepcopy(name)
JavaScript
UTF-8
234
3.515625
4
[]
no_license
let prim = false; let arr = [1, 2,]; function changeValues (primArg, arrArg) { primArg = true; arrArg = arrArg.pop(); } console.log(prim, arr); changeValues(prim, arr); console.log(prim, arr); // false, [1, 2,] // false, [1,]
Java
UTF-8
7,651
2.609375
3
[]
no_license
package com.koumamod.prevail; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Arrays; import com.stericson.RootTools.RootTools; import android.app.AlertDialog; import android.app.ListActivity; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.net.Uri; import android.os.Bundle; //import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.ListView; public class KoumaFileBrowser extends ListActivity { private enum DISPLAYMODE{ ABSOLUTE, RELATIVE; } private final DISPLAYMODE displayMode = DISPLAYMODE.RELATIVE; private List<String> directoryEntries = new ArrayList<String>(); private File currentDirectory = new File("/"); @Override public void onBackPressed(){ upOneLevel(); } /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); // setContentView() gets called within the next line, // so we do not need it here. browseToRoot(); } /** * This function browses to the * root-directory of the file-system. */ private void browseToRoot() { browseTo(new File("/")); } /** * This function browses up one level * according to the field: currentDirectory */ private void upOneLevel(){ if(this.currentDirectory.getParent() != null){ this.browseTo(this.currentDirectory.getParentFile()); } else { finish(); } } private void browseTo(final File aDirectory){ if (aDirectory.isDirectory()){ this.currentDirectory = aDirectory; List<String> recls = new ArrayList<String>(); List<String> ls = new ArrayList<String>(); ls.clear(); try { // Log.i("ls",aDirectory.getCanonicalPath()); RootTools.useRoot=true; recls = RootTools.sendShell("ls "+aDirectory.getCanonicalPath(), -1); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } for(int i=0;i<recls.size();i++){ File filetest =new File(recls.get(i)); // Log.i("recls",recls.get(i)); if(!(recls.get(i).isEmpty())&(recls.get(i)!=recls.get(recls.size()-1))){ ls.add(filetest.getAbsolutePath()); } } File[] testlist = new File[ls.size()]; for(int i=0;i<ls.size();i++) { testlist[i] = new File(aDirectory.getAbsolutePath()+"/"+ls.get(i)); } fill(testlist); }else{ OnClickListener okButtonListener = new OnClickListener(){ // @Override public void onClick(DialogInterface arg0, int arg1) { // Lets return an Intent containing the filename, that was clicked... Intent output = new Intent(); output.setData(Uri.parse(aDirectory.getAbsolutePath())); KoumaFileBrowser.this.setResult(RESULT_OK,output); finish(); } }; OnClickListener cancelButtonListener = new OnClickListener(){ // @Override public void onClick(DialogInterface arg0, int arg1) { // Do nothing } }; AlertDialog alertdialog = new AlertDialog.Builder(this).create(); alertdialog.setTitle("Are you sure?"); alertdialog.setMessage("Use this file as swap?\n"+ aDirectory.getName()); alertdialog.setButton("OK",okButtonListener); alertdialog.setButton2("Cancel", cancelButtonListener); alertdialog.show(); } } private void fill(File[] files) { Arrays.sort(files); this.directoryEntries.clear(); // Add the "<Current Directory>" and the "<Up One Level>" == 'Up one level' try { Thread.sleep(10); } catch (InterruptedException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } this.directoryEntries.add("<Current Directory>"); if(this.currentDirectory.getParent() != null){ this.directoryEntries.add("<Up One Level>"); } switch(this.displayMode){ case ABSOLUTE: for (File file : files){ this.directoryEntries.add(file.getPath()); } break; case RELATIVE: // On relative Mode, we have to add the current-path to the beginning int currentPathStringLenght = this.currentDirectory.getAbsolutePath().length(); for (File file : files){ this.directoryEntries.add(file.getAbsolutePath().substring(currentPathStringLenght)); } break; } ArrayAdapter<String> directoryList = new ArrayAdapter<String>(this, R.layout.file_row, this.directoryEntries); this.setListAdapter(directoryList); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { String selectedFileString = this.directoryEntries.get(position); if (selectedFileString.equals("<Current Directory>")) { // Refresh OnClickListener okButtonListener = new OnClickListener(){ // @Override public void onClick(DialogInterface arg0, int arg1) { AlertDialog swapsize =new AlertDialog.Builder(KoumaFileBrowser.this).create(); swapsize.setTitle("Creating new swapfile"); swapsize.setMessage("Enter size in MB"); final EditText input = new EditText(KoumaFileBrowser.this); input.setInputType(android.text.InputType.TYPE_CLASS_NUMBER); input.setText("100"); swapsize.setView(input); OnClickListener okNumberListener = new OnClickListener(){ public void onClick(DialogInterface arg0, int arg1) { //create swapfile and return filename String value = input.getText().toString(); File newSwap = new File(""); for(int i=0;i<255;i++) { newSwap = new File(KoumaFileBrowser.this.currentDirectory.getAbsolutePath()+ "/swapfile" + Integer.toString(i)); if(!newSwap.exists()) break; } Intent makefile = new Intent(KoumaFileBrowser.this, KoumaSwapCreate.class); Bundle bundle = new Bundle(); bundle.putString("filename", newSwap.getAbsolutePath()); bundle.putString("filesize",value); makefile.putExtras(bundle); startService(makefile); Intent output = new Intent(); output.setData(Uri.parse(newSwap.getAbsolutePath())); KoumaFileBrowser.this.setResult(RESULT_OK,output); finish(); } }; OnClickListener cancelNumberListener = new OnClickListener(){ public void onClick(DialogInterface arg0, int arg1) { KoumaFileBrowser.this.browseTo(KoumaFileBrowser.this.currentDirectory);// refresh } }; swapsize.setButton("OK", okNumberListener); swapsize.setButton2("Cancel", cancelNumberListener); swapsize.show(); } }; OnClickListener cancelButtonListener = new OnClickListener(){ // @Override public void onClick(DialogInterface arg0, int arg1) { KoumaFileBrowser.this.browseTo(KoumaFileBrowser.this.currentDirectory);// refresh } }; AlertDialog swapcreate = new AlertDialog.Builder(this).create(); swapcreate.setTitle("Question"); swapcreate.setMessage("Create Swapfile here?\n" + KoumaFileBrowser.this.currentDirectory.getAbsolutePath()); swapcreate.setButton("OK",okButtonListener); swapcreate.setButton2("Cancel", cancelButtonListener); swapcreate.show(); } else if(selectedFileString.equals("<Up One Level>")){ this.upOneLevel(); } else { File clickedFile = null; switch(this.displayMode){ case RELATIVE: clickedFile = new File(this.currentDirectory.getAbsolutePath() + this.directoryEntries.get(position)); break; case ABSOLUTE: clickedFile = new File(this.directoryEntries.get(position)); break; } if(clickedFile != null){ this.browseTo(clickedFile); } } } }
Java
UTF-8
1,092
2.015625
2
[]
no_license
package com.devsawe.demo.Service; import com.devsawe.demo.authentication.CustomUserDetails; import com.devsawe.demo.entities.User; import com.devsawe.demo.repositories.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import java.util.ArrayList; @Service public class MyUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { com.devsawe.demo.entities.User user = this.userRepository.findByUsername(username); return new CustomUserDetails(user.getId(), user.getUsername(), user.getPassword(), user.getUserType(), new ArrayList<>()); } }
Ruby
UTF-8
14,338
3.59375
4
[]
no_license
class Player attr_accessor :health, :items, :alive attr_reader :name def initialize(name) @name = name @health = 100 @items = [] @alive = true end def add_weapon(weapon) self.items.push(weapon) end def change_health(num) self.health += num if self.health <= 0 puts "You lost all of your health!" puts "GAME OVER.... \n Use the flying Delorean to go back to the begining of this game!" system("ruby rubyGame.rb") || system("ruby rubyGame.rb") end end end #///////////////////////////// class Weapon attr_reader :name def initialize(name= "nothing") @name = name @working = true end end weapon_one = Weapon.new("flamethrower") weapon_two = Weapon.new("spiked-bat") weapon_three = Weapon.new("flashlight") #////////////////////// class Villain attr_accessor :health, :items, :alive attr_reader :name def initialize(name,health) @name = name @health = health alive = true end def change_health(num) self.health += num if self.health <= 0 self.alive = false end end def attack(damage_amount,opponent) opponent.health -= damage_amount if opponent.health <=0 opponent.alive = false puts "****#{self.name} defeated #{opponent.name}****" end return -damage_amount end def evil_laugh puts "Muahahahah" end end #/////////////////////////// villain_thanos = Villain.new("Thanos",500) villain_trex = Villain.new("T-Rex",500) villain_freddy= Villain.new("Freddy Fazzbear",500) # ********************INTRO******************************************* puts "*********WELCOME*********\n PRESS ENTER\n TO BEGIN...".each_line {|c| sleep 0.20; } key = gets if key == "\n" system("xdg-open images/docBrownINtro.jpg") || system("open images/docBrownINtro.jpg") else while key != "\n" puts"WHAT ARE YOU CHICKEN? PRESS THE ENTER KEY!" key = gets if key == "\n" system("xdg-open images/docBrownINtro.jpg") || system("open images/docBrownINtro.jpg") end end end puts "EXCUSE ME!\n Whats your name?" # user_name = gets.chomp.capitalize # puts "I'm sorry #{user_name}, there is not much TIME for introductions. My name is Dr. Emmett Brown, and I need your help! It appears there has has been a cosmic collision between reality, fantasy, dreams, and chaos! We need to restore order before there is a MAJOR PARADOX, and the universe as we know it destroyed! I need you to explore the east, west, and south regions to figure out what is going on! Will you help me? \n\n YES OR NO?" player_one = Player.new(user_name) # choice_two = gets.chomp.downcase if choice_two == "yes" puts "\n\nGreat! Get going!" elsif choice_two == "no" puts "****GAME OVER**** \n Use the flying DeLorean to go back to the begining of this game!" system("ruby rubyGame.rb") || system("ruby rubyGame.rb") exit else end #**********************1st ACT*********************************************************** puts "The East Region: Dinosaurs Everywhere! \n \n \n".each_line{|c| sleep 0.40; } puts "\nYou begin your journey, and find your self in an amazon-like jungle. There is a rustle in the bushes!".each_line{|c| sleep 0.40; } system(" xdg-open images/raptor.png") || system("open images/raptor.png") puts " \nWhat will you do? Run or hide?" choice_three = gets.chomp.downcase case choice_three when "run" puts "\nYou ran and found a flamethrower placed next to a tree\n Will use it? Yes or no? ".each_line{|c| sleep 0.40; } choice_three_a = gets.chomp case choice_three_a when "yes" puts "\nThat flame-broiled raptor smells kind of good.." player_one.add_weapon(weapon_one) when "no" puts "\n\nYou managed to get away but fell pretty hard. Your leg is damaged and your limping." player_one.change_health(-20) else puts "\n\nWhy did you choose #{choice_three_a}?\n That raptor ate you alive. GAME OVER.\n TRY AGAIN" exit end when "hide" puts "You managed to hide but ended hiding in a pile of DINO POO, and might get sick from bacteria infection." player_one.change_health(-60) else puts" \n\nYou choose poorly. #{choice_three.capitalize} didn't work out for you. You fell and hit your head pretty hard." player_one.change_health(-40) end if player_one.items.length > 0 puts "\n\nYour health is at #{player_one.health} perecent. You collected a #{player_one.items[0].name}." else puts "\n\nYour health is at #{player_one.health} perecent." end #**************************ACT 2*********************************************************** puts "\n\n You finally made your way to the next region. Things are starting to get strange. There are vines & spores everywhere".each_line{|c| sleep 0.40; } puts "This is\n STRANGE".each_line{|c| sleep 0.40; } puts "\nYou noticed a treasure-chest. Will you open it?\n******YES OR NO*******".each_line{|c| sleep 0.40; } choice_four = gets.chomp.downcase case choice_four when "yes" puts "Great Scott! Is that Steve Harrington's spiked-bat?" player_one.add_weapon(weapon_two) when "no" puts "I just remembered I have some of my great aunt Nana's secret kale juice. It should give you some health." player_one.change_health(25) else puts "Why would you say #{choice_four}? Make better choices." end puts " \n#{player_one.name} watch out! I think thats a Demogorgon!\n Swing away #{player_one.name}! What are you going to do?\n ****ATTACK OR DANCE-OFF***** " choice_four_two = gets.chomp.downcase case choice_four_two when "attack" puts "Is that a waffle? Do you think we can use it?\n ****YES or NO****" choice_four_twob = gets.chomp case choice_four_twob when "yes" puts "\nGOOD JOB! YOU SUMMONED ELEVEN!\n *****Eleven destroyed the Demogorgon!*****" else puts "Looks like the Demogorgon was frighten by your #{choice_four_twob} and fled; but it layed a slug inside your intestines.\n" player_one.change_health(-30) end else puts "Looks like the Demogorgon was frighten by your #{choice_four_two} and fled; but it layed a slug inside your intestines.\n" player_one.change_health(-30) end if player_one.items.length >1 puts "\n#{player_one.name}, you managed to collect a #{player_one.items[0].name}, and a #{player_one.items[1].name}. Your health is at #{player_one.health} percent" else puts "\n#{player_one.name}, how are you holding up? Your health is at #{player_one.health} percent " end # ************#**********FINAl ACT****************************************************************** puts "Looks like we just barely made it out of the upside-down.\n I beleive this final region has been consumed by that frequently shut-down pizzeria with animatronics. \nIt seems that the black & white, checkered floor-pattern never ends. Do you see that restraunt over there? The lights are on!. Someone might be inside with answers!\n GREAT SCOTT!\n #{player_one.name}.".each_line{|c| sleep 0.40; } puts "I just remebered I have a small flashlight. Do you want it? \n ******ENTER YES OR NO******".each_line{|c| sleep 0.40; } choice_flashlight = gets.chomp.downcase case choice_flashlight when "yes" player_one.add_weapon(weapon_three) puts "That might come in handy" when "no" puts "You tripped from on an unseen animatronic part on the floor.".each_line{|c| sleep 0.40; } player_one.change_health(-20) puts "Your health is at #{player_one.health} percent.".each_line{|c| sleep 0.40; } else puts "I once said #{choice_flashlight} when I was offered a timeshare...\n Anyways, lets continue. ".each_line{|c| sleep 0.40; } end puts "Do you see those halls? Which way should we go? Left or right?".each_line{|c| sleep 0.40; } choice_five = gets.chomp.downcase case choice_five when "left" puts "The hallway is so dark...\n What was that noise?\n PRESS 1, 2, or 3".each_line{|c| sleep 0.40; } puts "1. Nothing \n 2. Pull out your bat. \n 3. Run the other way".each_line{|c| sleep 0.40; } choice_five_b = gets.chomp.downcase case choice_five_b when "1" player_one.change_health(-40) system("xdg-open images/Freddy.png") || system("open images/Freddy.png") puts "Your health is now at #{player_one.health} percent.".each_line{|c| sleep 0.40; } when "2" system("xdg-open images/Freddy.png") || system("open images/Freddy.png") puts "You managed to smash that animatronic to pieces.".each_line{|c| sleep 0.40; } player_one.change_health(-10) puts "Your health is now at #{player_one.health} percent.".each_line{|c| sleep 0.40; } else system("xdg-open images/Freddy.png") || system("open images/Freddy.png") end else puts "Do you hear music?\n Something is behind you! Do something!\n*********PRESS 1, 2, or 3**********".each_line{|c| sleep 0.40; } puts "1. Turn around \n 2. Pull out your bat. \n 3. Run ".each_line{|c| sleep 0.40; } choice_five_c = gets.chomp.downcase case choice_five_c when "1" player_one.change_health(-40) system("xdg-open images/Freddy.png") || system("open images/Freddy.png") puts "Your health is now at #{player_one.health} percent.".each_line{|c| sleep 0.40; } when "2" system("xdg-open images/Freddy.png") || system("open images/Freddy.png") puts "You managed to smash that animatronic to pieces.".each_line{|c| sleep 0.40; } player_one.change_health(-10) puts "Your health is now at #{player_one.health} percent.".each_line{|c| sleep 0.40; } else system("xdg-open images/Freddy.png") || system("open images/Freddy.png") puts "KEEP RUNNING...".each_line{|c| sleep 0.40; } end end puts "Looks like the light is coming from the security office up ahead!".each_line{|c| sleep 0.40; } puts "Go on now! Take a look through the office window.".each_line{|c| sleep 0.40; } puts " Are you going to look?\n *****PRESS 1 or 2******,".each_line{|c| sleep 0.40; } puts " 1. Okay Doc, watch my back!\n2.Doc, you should go take a peak" choice_six = gets.chomp case choice_six when "1" puts "You took a look..and your in shock!".each_line{|c| sleep 0.40; } system("xdg-open images/thanos.jpg") || system("open images/thanos.jpg") when "2" puts "Okay #{player_one.name},\nGREAT SCOTT!\n ITS #{villain_thanos.name.upcase}! He must have used the Infinity Stones to cause all these realities to collide!".each_line{|c| sleep 0.40; } system("xdg-open images/thanos.jpg") || system("open images/thanos.jpg") else puts "Let's take a look together!".each_line{|c| sleep 0.40; } puts "#{player_one.name}!\nGREAT SCOTT!\n ITS THANOS! He must have used the Infinity Stones to cause all these realities to cross!".each_line{|c| sleep 0.40; } system("xdg-open images/thanos.jpg") || system("open images/thanos.jpg") end puts "#{villain_thanos.name} saw you. He will erase you on Doc Brown if he gets the chance. \n#{villain_thanos.name} starts swinging his fists at you and the Doc. What will you do? \n********PRESS 1 OR 2******** \n1. dodge \n2. run".each_line{|c| sleep 0.40; } final_choice = gets.chomp case final_choice when "1" system("xdg-open images/trex.png") || system("open images/trex.png") puts "You dodged and managed to cause him to stumble. \n A T-Rex broke through the roof and swallowed Thanos alive. \nDoc Brown: Great Scott!\n You did it #{player_one.name}. \nThe universe should reset back to its natural order in any moment! \nThanks for all your help!".each_line{|c| sleep 0.40; } villain_trex.attack(600,villain_thanos) if player_one.items.length > 0 puts "You managed to collect a".each_line{|c| sleep 0.40; } player_one.items.each{|item| puts "- #{item.name} "} end puts "You finished the game your health at #{player_one.health} percent! \n GREAT JOB!".each_line{|c| sleep 0.40; } when "2" puts "Its over..As you and Doc ran, #{villain_thanos.name} snapped his fingers and you were all erased. \nThanks for playing...Try again..".each_line{|c| sleep 0.40; } if player_one.items.length > 0 puts "You managed to collect a".each_line{|c| sleep 0.40; } player_one.items.each{|item| puts "- #{item.name} "} end puts "You finished the game your health at #{player_one.health} percent.".each_line{|c| sleep 0.40; } player_one.change_health(villain_thanos.attack(300,player_one)) else puts " Great Scott!\n You cause a major paradox by choosing to #{final_choice}" puts "You finished the game with health at #{player_one.health} percent, and managed to collect a" player_one.items.each{|item| puts "- #{item.name}"} player_one.change_health(villain_thanos.attack(300,player_one)) end
Java
ISO-8859-2
1,125
3.484375
3
[]
no_license
import javax.swing.JOptionPane; public class Main { public static void main(String[] args) { float idade = 0, media = 0; int sexo, masc = 0, fem = 0, fem3045 = 0, pessoas = 0; do { idade = Float.valueOf(JOptionPane.showInputDialog("Insira sua idade:\n" + "(Digitar 0 ou negativo encerra o programa)")); if(idade > 0) { sexo = Integer.valueOf(JOptionPane.showInputDialog("Insira seu sexo:\n[0]Masculino\n[1]Feminino")); while(sexo != 0 && sexo != 1) { sexo = Integer.valueOf(JOptionPane.showInputDialog("Insira seu sexo:\n[0]Masculino\n[1]Feminino")); } switch(sexo) { case 0: masc++; break; case 1: fem++; break; }; //Idade Media media = media + idade; pessoas++; //Feminino entre 30 e 45 if(idade > 30 && idade < 45) { fem3045++; }; } }while(idade > 0); media = media / pessoas; JOptionPane.showMessageDialog(null, "RESULTADO\n" +"A mdia de idade "+media +"\nA quantidade de pessoas do sexo feminino\n" +"com idade entre 30 e 45 anos de "+fem3045 +"\nO total de pessoas do sexo masculino "+masc); } }
Python
UTF-8
395
3.5625
4
[]
no_license
def relation_to_luke(name): vals = { 'Darth Vader': 'father', 'Leia': 'sister', 'Han': 'brother in law', 'R2D2': 'droid' } return "Luke, I am your " + vals[name] + "." relation_to_luke("Darth Vader") # "Luke, I am your father." relation_to_luke("Leia") # "Luke, I am your sister." relation_to_luke("Han") # "Luke, I am your brother in law." relation_to_luke("R2D2") # "Luke, I am your droid."
JavaScript
UTF-8
5,001
2.5625
3
[ "MIT" ]
permissive
const { declare } = require("@babel/helper-plugin-utils"); function typeEval(node, params) { let checkType; if (node.checkType.type === "TSTypeReference") { checkType = params[node.checkType.typeName.name]; } else { checkType = resolveType(node.checkType); } const extendsType = resolveType(node.extendsType); if (checkType === extendsType || checkType instanceof extendsType) { return resolveType(node.trueType); } else { return resolveType(node.falseType); } } // 拿例子举例 targetType 是 Res<1> function resolveType(targetType, referenceTypesMap = {}, scope) { const tsTypeAnnotationMap = { TSStringKeyword: "string", TSNumberKeyword: "number", }; switch (targetType.type) { case "TSTypeAnnotation": if (targetType.typeAnnotation.type === "TSTypeReference") { return referenceTypesMap[targetType.typeAnnotation.typeName.name]; } return tsTypeAnnotationMap[targetType.typeAnnotation.type]; case "NumberTypeAnnotation": return "number"; case "StringTypeAnnotation": return "string"; case "TSNumberKeyword": return "number"; case "TSTypeReference": // typeAlias 是保存的 类型别名的香瓜信息 const typeAlias = scope.getData(targetType.typeName.name); // 获取别名的参数,这里获取到Res<1>中的为1 const paramTypes = targetType.typeParameters.params.map((item) => { return resolveType(item); }); // typeAlias.paramNames 为类型别名中的参数信息,这里为[Param] // 最后获取到的params为 {Param: 1} const params = typeAlias.paramNames.reduce((obj, name, index) => { obj[name] = paramTypes[index]; return obj; }, {}); // typeAlias.body 为类型别名右侧的表单式 return typeEval(typeAlias.body, params); // 字面量类型,直接返回值 case "TSLiteralType": return targetType.literal.value; } } function noStackTraceWrapper(cb) { const tmp = Error.stackTraceLimit; Error.stackTraceLimit = 0; cb && cb(Error); Error.stackTraceLimit = tmp; } const noFuncAssignLint = declare((api, options, dirname) => { api.assertVersion(7); return { pre(file) { file.set("errors", []); }, visitor: { // 遍历type别名表达式,这里的作用是把类型别名相关信息保存下来 TSTypeAliasDeclaration(path) { // path.get("id").toString() 获取type的名称 // 获取别名中泛型的名称 // 举例: type Res<Param> = Param extends 1 ? number : string; // path.get("id").toString() 为 Res // path.node.typeParameters.params.map((item) => { return item.name }) 为 别名的泛型参数名,这里为 [Param] path.scope.setData(path.get("id").toString(), { paramNames: path.node.typeParameters.params.map((item) => { return item.name; }), // 获取别名右侧表达式 也就是这一趴: Param extends 1 ? number : string; body: path.getTypeAnnotation(), }); // 暂时不知道 path.get("params") 是什么东西 // 后面也没看到用 path.scope.setData(path.get("params")); }, // 遍历函数调用表达式 CallExpression(path, state) { const errors = state.file.get("errors"); // path.node.typeParameters.params 获取泛型 // realTypes 保存获取到的计算后的泛型类型 // 拿 add<Res<1>>(1, '2'); 举例 // 得到 realTypes 为 类型别名的结果 [string] const realTypes = path.node.typeParameters.params.map((item) => { // Item 是这一趴: Res<1> return resolveType(item, {}, path.scope); }); const argumentsTypes = path.get("arguments").map((item) => { return resolveType(item.getTypeAnnotation()); }); const calleeName = path.get("callee").toString(); const functionDeclarePath = path.scope.getBinding(calleeName).path; const realTypeMap = {}; functionDeclarePath.node.typeParameters.params.map((item, index) => { realTypeMap[item.name] = realTypes[index]; }); const declareParamsTypes = functionDeclarePath .get("params") .map((item) => { return resolveType(item.getTypeAnnotation(), realTypeMap); }); argumentsTypes.forEach((item, index) => { if (item !== declareParamsTypes[index]) { noStackTraceWrapper((Error) => { errors.push( path .get("arguments." + index) .buildCodeFrameError( `${item} can not assign to ${declareParamsTypes[index]}`, Error ) ); }); } }); }, }, post(file) { console.log(file.get("errors")); }, }; }); module.exports = noFuncAssignLint;
Python
UTF-8
8,448
2.984375
3
[]
no_license
"""Base Module. ConfigTemplate ^^^^^^^^^^^^^^ Base class for the config template object. This template will process the YAML files. Subclasses are: Config and Compose classes InspectTemplate ^^^^^^^^^^^^^^^ Base class for the Inspector template object. This template will process docker and git status for compose services Subclasses are: DockerInspect and GitInspect """ import os import sys from abc import ABC, abstractmethod from datetime import datetime, timedelta from typing import Any, Dict, List, Tuple import yaml from buzio import console from cabrita.abc.utils import get_path, run_command class ConfigTemplate(ABC): """Abstract class for processing yaml files.""" def __init__(self) -> None: """Initialize class. :param compose_data_list: data parsed for each yaml :param _base_path: base path based on config file :param list_path: path list for each yaml :param full_path: full resolved path list for each yaml :param data: dictionary for resolved data from all yamls :param console: buzio instance :param manual_compose_paths: list of docker-compose paths informed on prompt """ self.compose_data_list = [] # type: List[dict] self._base_path = "" self.list_path = [] # type: List[Tuple[str, str]] self.full_path = "" # type: str self.data = {} # type: Dict[str, Any] self.console = console self.manual_compose_paths = [] # type: List[dict] @property def base_path(self) -> str: """Return base path for yaml file.""" return self._base_path @base_path.setter def base_path(self, value): self._base_path = value if "$" not in value else get_path(value, "") @property def version(self) -> int: """Return version value inside yaml file.""" return int(self.data.get("version", 0)) @property @abstractmethod def is_valid(self) -> bool: """Check if yaml is valid.""" pass def add_path(self, path: str, base_path: str = os.getcwd()) -> None: """Add new path for list for each yaml file.""" if path: if not self.base_path: self.base_path = os.path.dirname(os.path.join(base_path, path)) self.list_path.append((path, base_path)) def load_file_data(self) -> None: """Load data from yaml file. First file will be the main file. Every other file will override data, on reversed order list: Example: 1. docker-compose.yml (main file) 2. docker-compose-dev.yml (override main) 3. docker-compose-pycharm.yml (override dev) """ if self.list_path: for path, base_path in self.list_path: try: self.full_path = get_path(path, base_path) self.console.info("Reading {}".format(self.full_path)) with open(self.full_path, "r") as file: self.compose_data = yaml.safe_load(file.read()) for key in self.compose_data: # type: ignore self._convert_lists(self.compose_data, key) self.compose_data_list.append(self.compose_data) except FileNotFoundError as exc: console.error("Cannot open file: {}".format(exc)) sys.exit(127) except yaml.YAMLError as exc: console.error("Cannot read file: {}".format(exc)) sys.exit(1) except Exception as exc: console.error("Error: {}".format(exc)) raise exc self._upload_compose_list() def _convert_lists(self, data, key): """Convert list to dict inside yaml data. Works only for Key=Value lists. Example: environment: - DEBUG=false ports: - "8090:8080" Result: environment: {"DEBUG": "false"} ports: ['8090:8080'] """ if isinstance(data[key], list) and "=" in data[key][0]: data[key] = {obj.split("=")[0]: obj.split("=")[-1] for obj in data[key]} if isinstance(data[key], dict): for k in data[key]: self._convert_lists(data[key], k) def _upload_compose_list(self): """Reverse yaml list order and override data.""" reversed_list = list(reversed(self.compose_data_list)) self.data = reversed_list[-1] for index, override in enumerate(reversed_list): self.override = override if index + 1 == len(reversed_list): break for key in self.override: self._load_data_from_override(self.override, self.data, key) def _load_data_from_override(self, source, target, key): """Append override data in self.compose. Example Compose:: --------------- core: build: context: ../core image: core networks: - backend environment: - DEBUG=false ports: - "8080:80" Example override:: ---------------- core: build: dockerfile: Docker_dev depends_on: - api command: bash -c "python manage.py runserver 0.0.0.0" environment: DEBUG: "True" ports: - "9000:80" Final Result:: ------------ core: build: context: ../core dockerfile: Docker_dev depends_on: - api image: core command: bash -c "python manage.py runserver 0.0.0.0" environment: DEBUG: "True" networks: - backend ports: - "8080:80" - "9000:80" """ if target.get(key, None): if isinstance(source[key], dict): for k in source[key]: self._load_data_from_override( source=source[key], target=target[key], key=k ) else: if isinstance(target[key], list) and isinstance(source[key], list): target[key] += source[key] else: target[key] = source[key] else: if isinstance(target, list) and isinstance(source[key], list): target[key] += source[key] else: target[key] = source[key] class InspectTemplate(ABC): """Abstract class for compose service inspectors.""" def __init__(self, compose, interval: int) -> None: """Initialize class. :param run: running commands code. :param compose: Compose instance. :param _status: service status based on inspect data. :param interval: interval in seconds for new inspection :param last_update: last update for the inspector :param default_data: pydashing default widget """ self.run = run_command self.compose = compose self._status = {} # type: dict self.interval = interval self.last_update = datetime.now() - timedelta(seconds=self.interval) self.default_data = {} # type: dict @abstractmethod def inspect(self, service: str) -> None: """Run inspect code.""" pass @property def can_update(self) -> bool: """Check if inspector can inspect again.""" seconds_elapsed = (datetime.now() - self.last_update).total_seconds() return seconds_elapsed >= self.interval def status(self, service): """Return service status. If can update, start fetching new data calling self.inspect method. :param service: docker service name :return: dict or dashing obj. If not fetch data yet send default widget. """ if self.can_update: self.inspect(service) return self._status.get(service, self.default_data)
Rust
UTF-8
1,626
3.1875
3
[]
no_license
/// /// Задача 15 /// /// https://projecteuler.net/problem=15 /// /// Начиная в левом верхнем углу сетки 2×2 и имея возможность двигаться только вниз или вправо, /// существует ровно 6 маршрутов до правого нижнего угла сетки. /// /// Сколько существует таких маршрутов в сетке 20×20? /// /// Решение через Центральный биномиальный коэффициент /// /// Формула: /// (2n)!/(n!)^2 /// /// pub fn run(){ /// /// Т.к. числа большие необходимо произвести сокращение до перемножения /// /// Формула: /// (2n)!/(n!)^2 /// pub fn bin_kof(size:usize)->usize{ let mut a = (2..=size*2).collect::<Vec<usize>>(); let mut b = (2..=size).collect::<Vec<usize>>(); b.extend(2..=size ); for bnum in b.iter_mut().rev() { if let Some(index) = a.iter().position(|x|*x%*bnum==0) { a[index]/=*bnum; *bnum=1; } } a.iter().product::<usize>() / b.iter().product::<usize>() } let size:usize = 20; println!("result: {}", bin_kof(size) ); } /// /// Для проверки малых шагов к ответу нужно прибавить + 1 /// fn variant_step(m: (usize,usize), c:(usize,usize))->usize{ return if m.0>c.0 && m.1>c.1 { 1+variant_step(m,(c.0+1,c.1))+variant_step(m,(c.0,c.1+1)) }else{ 0 } }
Markdown
UTF-8
2,031
2.78125
3
[]
no_license
ETL Project Report Bic Vu EXTRACT Data was pulled from three separate sources, Kaggle, US Census Bureau and USDA. The Obesity CSV was shared with other team members while the Census data and USDA data on school lunch programs was pulled specific to my part of the analysis. The data was available in multiple formats and were normalized as three separate CSV files. TRANSFORMATION A lengthy process of cleaning, checking and formatting was required to transform the three files into data that could cross-reference each other. Utilizing Jupyter Notebook and panda libraries, the rows and columns had to be filtered for matching information. Starting with the Obesity data which was a survey spreadsheet, relevant questions and their ID needed to be identified and used as a filter. There was far more data than necessary for this study, so only relevant columns of information where kept. Upon cross referencing the data, I noticed that only three years (2013, 2015, and 2017) had corresponding data. The year was used as a groupby mechanism for smaller datasets that can be easily compared. The state was identified as the primary key for all three data chart and needed to be sorted alphabetically. The Census and School Lunches data were similarly filtered for states and quantity. The quantity of lunches were compared with state population for a very rough estimate of percentages of population in each state that received school lunches. The percentages were rounded to a corresponding decimal value as those in the Obesity Data. LOAD A final Comparison analysis merged all three datasets was saved onto a database using Postgres and also exported as a final CSV file. CONCLUSION The challenge of this project was constantly checking if I was working with apples or oranges. Values that appears as numbers may turn out to be strings, integers as floats, and NaN were always somewhere in the nether. Multiple debugging measures where added to the scripts to see if filtering mechanisms affected value formats.
C++
UTF-8
574
2.671875
3
[]
no_license
/* * version.hpp * * Created on: Feb 11, 2021 * Author: Nik Clark */ #include "packet_utils.hpp" namespace packet_utils { static constexpr uint16_t X25_INIT_CRC = 0xffff; static void crc_accumulate(uint8_t data, uint16_t *crcAccum) { uint8_t tmp; tmp = data ^ (uint8_t)(*crcAccum &0xff); tmp ^= (tmp<<4); *crcAccum = (*crcAccum>>8) ^ (tmp<<8) ^ (tmp <<3) ^ (tmp>>4); } uint16_t crc_calculate(const uint8_t* pBuffer, uint16_t length) { uint16_t crcTmp = X25_INIT_CRC; while (length--) { crc_accumulate(*pBuffer++, &crcTmp); } return crcTmp; } }
Markdown
UTF-8
2,173
3.078125
3
[]
no_license
--- title: "Inner Garden: connecting inner states to a mixed reality sandbox" project: "inner" image-teaser: "teaser_inner-garden.gif" order: 8 layout: project --- Mindfulness, the act of paying a deliberate and non-judgmental attention to the present moment, has been shown to have a positive impact on a person's health and subjective well-being. Based on an iterative process with meditation teachers and practitioners, we designed a new tool to support mindfulness practices. This tool takes the shape of an augmented sandbox, designed to inspire the user's self-motivation and curiosity. By shaping the sand, the user creates a living miniature world that is projected back onto the sand. The natural elements of the garden are connected to real-time physiological measurements, such as breathing, helping the user to stay focused on the body. Moreover, using a virtual reality headset, they can travel inside their garden for a dedicated meditation session. Preliminary results seem to indicate that the system is well suited for mindfulness and induces a calm and mindful state on the user. <iframe src="//player.vimeo.com/video/200217398" width="500" height="281" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen ></iframe> This project is a new iteration of the "introspectibles" that were first investigated with [Teegi](/projects/teegi/) and [Tobe](/projects/tobe/). The Inner Garden can be seen as a multi-modal biofeedback (visual, sounds, tactile). It helps users to be grounded to their body, in a playful and engaging way. ![Inner Garden: an augmented sandbox and a multi-modal biofeedback](/images/inner-garden/teaser.jpg) It was created by [Joan Sol Roo](http://people.bordeaux.inria.fr/jroo/) and [Renaud Gervais](http://renaudgervais.com/). I joined the adventure later on, helping with the design process -- with some ideas about the use of virtual reality gathered [during my stay in Montreal](http://vrrelated.com/thought-powered-vr-is-becoming-real/) -- and the experimental study. Now that we have validated the acceptability and the core principles of the Inner Garden, we are looking forward to test its effect on the long term.
Java
UTF-8
246
1.765625
2
[]
no_license
package com.serialization; public class MenuChoice { public static final int ADDEMPLOYEE = 1; public static final int DISPLAY = 2; public static final int SAVE = 3; public static final int LOAD = 4; public static final int QUIT = 5; }
Go
UTF-8
4,529
2.96875
3
[]
no_license
package commands import ( "darthmaul/templates" "fmt" "os" "sync" ) var ( path string ) type createAppCMD struct { AppName string } func NewCreateAppCMD(appName string) Command { return &createAppCMD{ AppName: appName, } } func (c createAppCMD) Execute() (err error){ fmt.Println("Executing command create-app " + c.AppName) // Create main folder (AppName) if err := c.CreateDir(c.AppName); err != nil { fmt.Println("Error creating folder", c.AppName) return err } // Create files and folders. if err := c.GenerateBoilerPlate(); err != nil { return err } return nil } func (c createAppCMD) GenerateBoilerPlate() (err error){ path = c.AppName fmt.Println("Generating boilerplate please wait...") // Create Files var wg sync.WaitGroup // Readme.md wg.Add(1) go c.CreateFile(path+"/Readme.md", templates.Readme, &wg) // go.mod wg.Add(1) go c.CreateFile(path+"/go.mod", fmt.Sprintf(templates.GoModule, c.AppName), &wg) // docker-compose.yml wg.Add(1) go c.CreateFile(path+"/docker-compose.yml", fmt.Sprintf(templates.DockerCompose, c.AppName, c.AppName), &wg) // docker-compose.yml wg.Add(1) go c.CreateFile(path+"/dev.Dockerfile", fmt.Sprintf(templates.DockerDev, c.AppName, c.AppName, c.AppName), &wg) // .gitignore wg.Add(1) go c.CreateFile(path+"/.gitignore", templates.GitIgnore, &wg) // Create folder cmd/api path = fmt.Sprintf("%s/cmd/api", c.AppName) fmt.Println("Changing path to", fmt.Sprintf("%s/cmd/api", c.AppName)) if err := os.MkdirAll(path, 0775); err != nil { fmt.Errorf("Error creating folder " + path, err) return err } // main.go wg.Add(1) go c.CreateFile(path+"/main.go", fmt.Sprintf(templates.MainTemplate, c.AppName), &wg) // Create App folder and file if err := c.CreateDir(path+"/app"); err != nil { fmt.Errorf("Error creating folder " + path+"/app", err) return err } wg.Add(1) go c.CreateFile(path+"/app/app.go", fmt.Sprintf(templates.AppFile, c.AppName), &wg) // Create Config folder and file if err := c.CreateDir(path+"/config"); err != nil { fmt.Errorf("Error creating folder " + path+"/config", err) return err } wg.Add(1) go c.CreateFile(path+"/config/settings.go", templates.Settings, &wg) // Create ping controller if err := c.CreateDir(path+"/controllers"); err != nil { fmt.Errorf("Error creating folder " + path+"/controllers", err) return err } wg.Add(1) go c.CreateFile(path+"/controllers/ping_controller.go", templates.PingControllerTemplate, &wg) wg.Add(1) go c.CreateFile(path+"/controllers/ping_controller_test.go", templates.PingControllerTest, &wg) // Create middlewares (cors.go) if err := c.CreateDir(path+"/middlewares"); err != nil { fmt.Errorf("Error creating folder " + path+"/middlewares", err) return err } wg.Add(1) go c.CreateFile(path+"/middlewares/cors.go", templates.CorsMiddleware, &wg) // Create folder cmd/api/router path = fmt.Sprintf("%s/cmd/api/router", c.AppName) fmt.Println("Changing path to", fmt.Sprintf("%s/cmd/api/router", c.AppName)) if err := os.MkdirAll(path+"/factory", 0775); err != nil { fmt.Errorf("Error creating folder " + path+"/factory", err) return err } // urls.go wg.Add(1) go c.CreateFile(path+"/urls.go", fmt.Sprintf(templates.UrlsMapping, c.AppName), &wg) // router.go wg.Add(1) go c.CreateFile(path+"/router.go", fmt.Sprintf(templates.RouterTemplate, c.AppName), &wg) // router_test.go wg.Add(1) go c.CreateFile(path+"/router_test.go", templates.RouterTest, &wg) // Change path to router/factory path = fmt.Sprintf("%s/cmd/api/router/factory", c.AppName) fmt.Println("Changing path to", fmt.Sprintf("%s/cmd/api/router/factory", c.AppName)) // controller_factory.go wg.Add(1) go c.CreateFile(path+"/controller_factory.go", fmt.Sprintf(templates.ControllerFactory, c.AppName), &wg) // controller_factory_test.go wg.Add(1) go c.CreateFile(path+"/controller_factory_test.go", templates.FactoryTest, &wg) wg.Wait() return err } func (c createAppCMD) CreateDir(path string) (err error) { // Create directory if it doesn't exist yet if _, err := os.Stat(path); os.IsNotExist(err) { os.Mkdir(path, 0775) } return err } func (c createAppCMD) CreateFile(path string, content string, wg *sync.WaitGroup) { defer wg.Done() f, err := os.Create(path) if err != nil { fmt.Errorf(fmt.Sprintf("Error creating file %s", path), err) return } defer f.Close() _, err = f.WriteString(content) if err != nil { fmt.Errorf(fmt.Sprintf("Error WriteString for file %s", path), err) } return }
Python
UTF-8
592
3.671875
4
[]
no_license
#coding: UTF-8 #Que hace import turtle def dibujarPoligono(lados,longitud,color,relleno): turtle.color(color) turtle.fillcolor(relleno) turtle.begin_fill() for i in range(lados): turtle.forward(longitud) turtle.left(360/lados) turtle.end_fill() def Main(): numeroLados=int(input("Ingrese el numero de lados")) longitudLado=float(input("Ingrese la longitud del lado")) colorpluma=str.lower(input("Ingrese el color del lado")) colorrelleno=str.lower(input("Ingrese el color de relleno")) dibujarPoligono(numeroLados,longitudLado,colorpluma,colorrelleno) Main()
Java
UTF-8
1,819
2.4375
2
[ "Apache-2.0" ]
permissive
package com.wenyu.danmuku.render; import android.graphics.Canvas; import android.graphics.Rect; import android.util.Log; import com.wenyu.danmuku.interfaces.IDanMa; import java.util.Iterator; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; /** * Created by jiacheng.li on 17/3/12. * Copyright © 2016年 扇贝网(shanbay.com). * All rights reserved. */ public class RenderManager { private static final int DEFAULT_MAX_DAN_MA = 500; private BlockingQueue<IDanMa> mDanMaBlockingQueue = null; private Rect mWindowBound = new Rect(); public RenderManager() { this(DEFAULT_MAX_DAN_MA); } public RenderManager(int danMaSize) { mDanMaBlockingQueue = new LinkedBlockingDeque<>(danMaSize); } public void render(Canvas canvas, int width, int height) { if (mDanMaBlockingQueue == null || mDanMaBlockingQueue.isEmpty()) { return; } mWindowBound.set(0, 0, width, height); Iterator<IDanMa> iterator = mDanMaBlockingQueue.iterator(); while (iterator.hasNext()) { IDanMa danMa = iterator.next(); if (checkInvalidate(danMa)) { danMa.render(canvas); } else { iterator.remove(); } } } private boolean checkInvalidate(IDanMa danMa) { Rect danMaBound = danMa.getBound(); Log.d("chan_debug", danMaBound.toString()); if (danMaBound.left > mWindowBound.right) { return false; } if (danMaBound.right < mWindowBound.left) { return false; } if (danMaBound.top > mWindowBound.bottom) { return false; } if (danMaBound.bottom < mWindowBound.top) { return false; } return true; } public void push(IDanMa danMa) { try { mDanMaBlockingQueue.add(danMa); } catch (Exception e) { //方式数据溢出 e.printStackTrace(); } } public void release() { mDanMaBlockingQueue = null; } }
C++
UTF-8
719
2.546875
3
[]
no_license
/* * IPDispatcher.h * * Created on: Aug 25, 2011 * Author: pajace */ #ifndef IPDISPATCHER_H_ #define IPDISPATCHER_H_ #include <string> #include "IPaddress.h" using std::string; class IPDispatcher { public: static IPDispatcher* getInstance(); IPaddress getIPAddress(string); bool backIPAddress(string); bool initIPAddressPool(); bool removeIPAddressPool(); string getIPPoolDataFile() const; ~IPDispatcher(); private: IPDispatcher(){ }; // private so that it can not be called IPDispatcher(IPDispatcher const&){}; // copy constructor is private // IPDispatcher operator=(IPDispatcher const&){}; // assignment operator is private static IPDispatcher* m_pInstance; }; #endif /* IPDISPATCHER_H_ */
Java
UTF-8
1,239
2.90625
3
[]
no_license
package com.example.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.Iterator; public class Client { public static void main(String[] args) { InvocationHandler handler = new InvocationHandler() { Image4K image4K; @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if(method.getName().equals("getImage")) { if (image4K == null) { System.out.println("Load image"); image4K = new Image4K(); } return method.invoke(image4K, args); } if(method.getName().equals("getMiniature")) { return "Miniature from proxy"; } return proxy; } }; Image proxy = (Image) Proxy.newProxyInstance(Image.class.getClassLoader(), new Class[]{Image.class}, handler); System.out.println(proxy.getMiniature()); System.out.println(proxy.getImage()); System.out.println(proxy.getImage()); } }
C++
UTF-8
2,276
2.5625
3
[]
no_license
//////////////////////////////////////////////////////////////////////////////////////// // Kara Jensen - mail@karajensen.com - SceneDataIDs.h //////////////////////////////////////////////////////////////////////////////////////// #pragma once /** * Avaliable meshes in the game */ namespace MeshID { enum ID { BACKDROP, BULLET, TANK, TANKGUN, GROUND, WALL, WALLBOX, TANKP1, TANKP2, TANKP3, TANKP4, MAX }; } /** * Avaliable effects in the game */ namespace EffectID { enum ID { TOONTEXT, MAX }; } /** * Avaliables convex hull meshes in the game */ namespace HullID { enum ID { GROUND, WALL, TANK, GUN, TANKP1, TANKP2, TANKP3, TANKP4, BULLET, MAX }; } /** * Available shaders to use */ namespace ShaderID { enum ID { TOON, NORMAL, PROXY, SHADOW, TEXTURE, POST, GRADIENT, MAX }; } /** * Available lights to use */ namespace LightID { enum ID { MAIN, MAX }; } /** * Collision Shapes avaliable for rigid bodies */ namespace ShapeID { enum ID { GROUND, WALL, TANK, GUN, BULLET, TANKP1, TANKP2, TANKP3, TANKP4, MAX }; } /** * Textures avaliable */ namespace TextureID { enum ID { BORDER, BOX, BUTTON_HIGH, BUTTON_LOW, DIFF_HIGH, DIFF_EASY, DIFF_HARD, DIFF_MED, GAME_OVER, GAME_OVER_MENU, GAME_OVER_REPLAY, GAME_OVER_P1, GROUND, TANK_GUN, TANK_BODY, TANK_NPC_GUN, TANK_NPC_BODY, TOON_TEXT, WALL, BULLET, HEALTH_BACK, HEALTH_BAR, HEALTH_STAR, MENU, PIXEL, MAX }; } /** * The amount of instances of each mesh */ namespace Instance { enum Amount { GROUND = 1, TANKS = 6, BULLETS = 50, WALLS = 4, ENEMIES = 5, TANK_PIECES = 4 }; enum ID { PLAYER = Amount::ENEMIES }; }
Java
UTF-8
426
3.046875
3
[]
no_license
import java.util.*; import java.io.*; import java.lang.*; class Program_10 { public static void main(String[] args) { char c = args[0].charAt(0); int c_; if((int)'A' <= (int)c && (int)c <= (int)'Z'){ c_ = (int)c + (int)'a'-(int)'A'; } else { c_ = (int)c + (int)'A'-(int)'a'; } char f = (char)c_; System.out.println(c+"->"+f); } }
JavaScript
UTF-8
798
2.921875
3
[]
no_license
const getTimePassed = (start, taskHrs, taskMin, taskSec) => { const date = parseInt((new Date().getTime()) / 1000) const end = date totalSec = end - start const hrs = parseInt(totalSec/3600) const min = parseInt((totalSec - (3600 * hrs))/60) const sec = (totalSec - (3600 * hrs) - (60 * min)) taskHrs += hrs taskMin += min taskSec += sec if (taskSec >= 60) { taskSec = taskSec - 60 taskMin++ } if (taskMin >= 60 ) { taskMin = taskMin - 60 taskHrs++ } const height = (((hrs * 60) + min) * 40) / 60 const atributes = { hrs, min, sec, end, height, taskHrs, taskMin, taskSec } return atributes } module.exports = getTimePassed
Markdown
UTF-8
70,213
2.75
3
[]
no_license
# 设计模式 <nav> 软件设计原则<br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#1-开闭原则">1. 开闭原则</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#2-里氏替换原则">2. 里氏替换原则</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#3-依赖倒置原则">3. 依赖倒置原则</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#4-单一职责原则">4. 单一职责原则</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#5-接口隔离原则">5. 接口隔离原则</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#6-迪米特法则-最少知道原则">6. 迪米特法则 (最少知道原则)</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#7-合成复用原则-组合复用原则">7. 合成复用原则 (组合复用原则)</a><br/> 创建型<br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#1-单例模式">1. 单例模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#2-简单工厂模式">2. 简单工厂模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#3-工厂模式">3. 工厂模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#4-抽象工厂模式">4. 抽象工厂模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#5-构建者模式">5. 构建者模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#6-原型模式">6. 原型模式</a><br/> 结构型<br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#1-代理模式">1. 代理模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#2-适配器模式">2. 适配器模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#3-桥接模式">3. 桥接模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#4-组合模式">4. 组合模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#5-装饰模式">5. 装饰模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#6-外观模式">6. 外观模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#7-享元模式">7. 享元模式</a><br/> 行为型<br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#1-观察者模式">1. 观察者模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#2-责任链模式">2. 责任链模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#3-模板方法模式">3. 模板方法模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#4-策略模式">4. 策略模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#6-状态模式">6. 状态模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#7-中介者模式">7. 中介者模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#8-迭代器模式">8. 迭代器模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#9-访问者模式">9. 访问者模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#10-备忘录模式">10. 备忘录模式</a><br/> &nbsp;&nbsp;&nbsp;&nbsp;<a href="#11-解释器模式">11. 解释器模式</a><br/> </nav> ## 软件设计的原则 ### 1. 开闭原则 定义:软件实体应当对扩展开放,对修改关闭。 ### 2. 里氏替换原则 定义:继承必须保证超类所拥有的性质在子类中仍然成立。即子类在继承父类时,除了添加新的方法来新增功能外,尽量避免重写父类方法,因为这会导致整个继承体系的复用性变差。 ### 3. 依赖倒置原则 定义:高层模块不应该依赖低层模块,两者都应该依赖其抽象;抽象不应该依赖细节,细节应该依赖抽象。其核心思想是要面向接口编程,而不是面向实现编程,这样可以降低耦合性,提高系统稳定性,提高代码的可读性和可维护性。 ### 4. 单一职责原则 定义:一个类应该有且仅有一个引起它变化的原则,否则类应该被拆分。其核心思想是控制类的粒度大小、提高类的内聚性。 ### 5. 接口隔离原则 定义:一个类对另一个类的依赖应该建立在最小的接口上。其核心思想是要为每个特定的功能建立对应的接口,而不是在一个接口中试图去包含所有功能,既要保证相对独立,也要避免过多接口所导致的臃肿。 ### 6. 迪米特法则 (最少知道原则) 定义:如果两个软件实体不需要直接通讯,那么就应该避免直接互相调用,而是通过第三方转发该调用,从而降低耦合度,保证模块的相对独立。 ### 7. 合成复用原则 (组合复用原则) 定义:应该优先使用组合、聚合等关联关系来实现复用,其次才是考虑使用继承关系。 **总结**:开闭原则是总纲,它告诉我们要对扩展开放,对修改关闭;里氏替换原则告诉我们不要破坏继承体系;依赖倒置原则告诉我们要面向接口编程;单一职责原则告诉我们实现类要职责单一;接口隔离原则告诉我们在设计接口的时候要精简单一;迪米特法则告诉我们要降低耦合度;合成复用原则告诉我们要优先使用组合或者聚合关系复用,少用继承关系复用。 # 创建型 ## 1. 单例模式 ### 1.1 饿汉式单例 饿汉式单例是最简单一种单例模式,它在类初始化时就完成相关单例对象的创建,可以通过静态代码块或静态内部类的方式来进行实现: 静态代码块方式: ```java public class HungrySingleton implements Serializable { private static final HungrySingleton instance; static { instance = new HungrySingleton(); } // 确保构造器私有 private HungrySingleton() {} // 获取单例对象 public static HungrySingleton getInstance() { return instance; } } ``` 静态内部类方式: ```java public class StaticInnerClassHungrySingleton { private static class InnerClass { private static StaticInnerClassHungrySingleton instance = new StaticInnerClassHungrySingleton(); } // 确保构造器私有 private StaticInnerClassHungrySingleton() {} // 获取单例对象 public static StaticInnerClassHungrySingleton getInstance() { return InnerClass.instance; } } ``` 饿汉式单例的优点在于其不存在线程安全问题,对象的唯一性由虚拟机在类初始化创建时保证;其缺点在于如果对象的创建比较消耗资源,并且单例对象不一定会被使用时就会造成资源的浪费。 ### 1.2 懒汉式单例 懒汉式单例的思想在于在需要使用单例对象时才进行创建,如果对象存在则直接返回,如果对象不存在则创建后返回,示例如下: ```java public class LazySingletonUnsafe { private static LazySingletonUnsafe instance = null; private LazySingletonUnsafe() { } public static LazySingletonUnsafe getInstance() { if (instance == null) { instance = new LazySingletonUnsafe(); } return instance; } } ``` 需要注意的是上面的代码在单线程环境下是没有问题的,但是在多线程环境下是线程不安全的,原因在于下面的创建代码是非原子性的: ```java if (instance == null) { instance = new LazySingletonUnsafe(); } ``` 想要保证创建操作的原子性,可以通过 synchronized 关键字来进行实现: ```java public synchronized static LazySingletonUnsafe getInstance() { if (instance == null) { instance = new LazySingletonUnsafe(); } return instance; } ``` 此时该方法是线程安全的,但是性能却存在问题。因为 synchronized 修饰的是静态方法,其锁住的是整个类对象,这意味着所有想要获取该单例对象的线程都必须要等待内部锁的释放。假设单例对象已经创建完成,并有 100 个线程并发获取该单例对象,则这 100 个线程都需要等待,显然这会降低系统的吞吐量,因此更好的方式是采用 **双重检查锁的机制** 来实现懒汉式单例: ```java public class DoubleCheckLazySingletonSafe { // 使用volatile来禁止指令重排序 private static volatile DoubleCheckLazySingletonSafe instance = null; private DoubleCheckLazySingletonSafe() { } // 双重检查 public static DoubleCheckLazySingletonSafe getInstance() { if (instance == null) { synchronized (DoubleCheckLazySingletonSafe.class) { if (instance == null) { instance = new DoubleCheckLazySingletonSafe(); } } } return instance; } } ``` 还是沿用上面的举例,假设单例对象已经创建完成,并有 100 个线程并发获取该单例对象,此时 `instance == null` 判断肯定是 false,所以所有线程都会直接获得该单例对象,而不会进入 synchronized 同步代码块,这减小了锁的锁定范围,用更小的锁粒度获得了更好的性能。但内部的 `if` 代码块仍然需要使用 synchronized 关键字修饰,从而保证整个 if 代码块的原子性。 需要注意的是这里的 instance 需要使用 volatile 关键修饰,用于禁止对象在创建过程中出现指令重排序。通常对象的创建分为以下三步: 1. 给对象分配内存空间; 2. 调用对象的构造器方法,并执行初始化操作; 3. 将变量指向相应的内存地址。 如果没有禁止指令重排序,则 2 ,3 步可能会发生指令重排序,这在单线程下是没有问题的,也符合 As-If-Serial 原则,但是如果在多线程下就会出现线程不安全的问题: ```java // 2. 由于线程1已经将变量指向内存地址,所以其他线程判断instance不为空,进而直接获取,但instance可能尚未初始化完成 if (instance == null) { synchronized (DoubleCheckLazySingletonSafe.class) { if (instance == null) { // 1. 假设线程1已经给对象分配了内存空间并将变量instance指向了相应的内存地址,但尚未初始化完成 instance = new DoubleCheckLazySingletonSafe(); } } } return instance; ``` 由于重排序的存在,其他线程可能拿到的是一个尚未初始化完成的 instance,此时就可能会导致异常,所以需要禁止其出现指令重排序。 ### 1.3 使用序列化破坏单例 饿汉式单例和双重检查锁的懒汉式单例都是线程安全的,都能满足日常的开发需求,但如果你是类库的开发者,为了防止自己类库中的单例在调用时被有意或无意地破坏,你还需要考虑单例模式的写法安全。其中序列化和反射攻击是两种常见的破坏单例的方式,示例如下: ```java public class SerializationDamage { public static void main(String[] args) throws IOException, ClassNotFoundException { HungrySingleton instance = HungrySingleton.getInstance(); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("SingletonFile")); outputStream.writeObject(instance); ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(new File("SingletonFile"))); HungrySingleton newInstance = (HungrySingleton) inputStream.readObject(); System.out.println(instance == newInstance); // false } } ``` 将 HungrySingleton 实现 Serializable 接口后,使用上面的代码将对象序列化写入文件,然后再反序列获取,你会发现两次得到的不是一个对象,这就代表单例模式受到了序列化和反序列化的破坏。想要解决这个问题,需要在对应的单例类中定义 `readResolve()` 方法: ```java public class HungrySingleton implements Serializable { ...... private Object readResolve() { return instance; } ...... } ``` 此时在反序列化时该方法就会被调用来返回单例对象,对应的 ObjectInputStream 类的源码如下: ```java // 在本用例中,readObject在内部最终调用的是readOrdinaryObject方法 private Object readOrdinaryObject(boolean unshared) throws IOException{ ....... if (obj != null && handles.lookupException(passHandle) == null && desc.hasReadResolveMethod()) //如果对应的对象中有readResolve方法 { // 则通过反射调用该方法来获取对应的单例对象 Object rep = desc.invokeReadResolve(obj); ........ handles.setObject(passHandle, obj = rep); } return obj; } ``` ### 1.4 使用反射破坏单例 使用反射也可以破坏单例模式,并且由于 Java 的反射功能过于强大,这种破坏几乎是无法规避的,示例如下: ```java public class ReflectionDamage { public static void main(String[] args) throws Exception { Constructor<HungrySingleton> constructor = HungrySingleton.class.getDeclaredConstructor(); // 获取私有构造器的访问权限 constructor.setAccessible(true); HungrySingleton hungrySingleton = constructor.newInstance(); HungrySingleton instance = HungrySingleton.getInstance(); System.out.println(hungrySingleton == instance); // false } } ``` 即便在创建单例对象时将构造器声明为私有,此时仍然可以通过反射修改权限来获取,此时单例模式就被破坏了。如果你采用的是饿汉式单例,此时可以通过如下的代码来规避这种破坏: ```java public class HungrySingleton implements Serializable { private static final HungrySingleton instance; static { instance = new HungrySingleton(); } // 由于instance在类创建时就已经初始化完成,所以当使用反射调用构造器时就会抛出自定义的RuntimeException异常 private HungrySingleton() { if (instance != null) { throw new RuntimeException("单例模式禁止反射调用"); } } ...... } ``` 以上是饿汉式单例防止反射攻击的办法,如果你使用的是懒汉式单例,此时由于无法知道对象何时会被创建,并且反射功能能够获取到任意字段,方法,构造器的访问权限,所以此时没有任何方法能够规避掉反射攻击。 那么有没有一种单例模式能够在保证线程安全,还能够防止序列化和反射功能呢?在 Java 语言中,可以通过枚举式单例来实现。 ### 1.5 枚举式单例 使用枚举实现单例的示例如下: ```java public enum EnumInstance { INSTANCE; private String field; public String getField() { return field; } public void setField(String field) { this.field = field; } public static EnumInstance getInstance() { return INSTANCE; } } ``` 想要实现一个单例枚举,对应的单例类必须要使用 enum 修饰,其余的字段声明(如:field), 方法声明(如:setField)都和正常的类一样。首先枚举类是线程安全的,这点可以使用反编译工具 Jad 对类的 class 文件进行反编译来验证: ```java // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.kpdus.com/jad.html // Decompiler options: packimports(3) // Source File Name: EnumInstance.java package com.heibaiying.creational.singleton; // 不可变的类 public final class EnumInstance extends Enum { public static EnumInstance[] values() { return (EnumInstance[])$VALUES.clone(); } public static EnumInstance valueOf(String name) { return (EnumInstance)Enum.valueOf(com/heibaiying/creational/singleton/EnumInstance, name); } // 私有构造器,枚举类没有无参构造器,Enum中只定义了Enum(String name, int ordinal) 构造器 private EnumInstance(String s, int i) { super(s, i); } // 自定义的方法 public String getField() { return field; } public void setField(String field) { this.field = field; } public static EnumInstance getInstance() { return INSTANCE; } // 静态不可变的实例对象 public static final EnumInstance INSTANCE; // 自定义字段 private String field; private static final EnumInstance $VALUES[]; // 在静态代码中进行初始化 static { INSTANCE = new EnumInstance("INSTANCE", 0); $VALUES = (new EnumInstance[] { INSTANCE }); } } ``` 通过反编译工具可以看到其和饿汉式单例模式类似,因此它也是线程安全的。另外它也能防止序列化攻击和反射攻击: ```java public class EnumInstanceTest { public static void main(String[] args) throws Exception { // 序列化攻击 EnumInstance instance = EnumInstance.getInstance(); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("EnumSingletonFile")); outputStream.writeObject(instance); ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(new File("EnumSingletonFile"))); EnumInstance newInstance = (EnumInstance) inputStream.readObject(); System.out.println(instance == newInstance); // 反射攻击,Enum类中只有一个两个参数的构造器:Enum(String name, int ordinal) Constructor<EnumInstance> constructor = EnumInstance.class.getDeclaredConstructor(String.class, int.class); constructor.setAccessible(true); EnumInstance enumInstance = constructor.newInstance("name", 0); System.out.println(instance == enumInstance); } } ``` 对于序列化与反序列化,枚举类单例能保证两次拿到的都是同一个实例。对于反射攻击,枚举类单例会抛出明确的异常: ```java Exception in thread "main" java.lang.IllegalArgumentException: Cannot reflectively create enum objects at java.lang.reflect.Constructor.newInstance(Constructor.java:417) at com.heibaiying.creational.singleton.EnumInstanceTest.main(EnumInstanceTest.java:18) ``` ## 2. 简单工厂模式 ### 2.1 定义 对于调用者来说,它无需知道对象的具体创建细节,只需要将自己所需对象的类型告诉工厂,然后由工厂自动创建并返回。 ### 2.2 示例 <div align="center"> <img src="../pictures/23_simple_factory.png"/> </div> 产品抽象类: ```java public abstract class Phone { public abstract void call(String phoneNum); } ``` 具体的产品: ```java public class HuaweiPhone extends Phone { public void call(String phoneNum) { System.out.println("华为手机拨打电话:" + phoneNum); } } ``` ```java public class XiaomiPhone extends Phone { public void call(String phoneNum) { System.out.println("小米手机拨打电话:" + phoneNum); } } ``` 手机工厂: ```java public class PhoneFactory { public Phone getPhone(String type) { if ("xiaomi".equalsIgnoreCase(type)) { return new XiaomiPhone(); } else if ("huawei".equalsIgnoreCase(type)) { return new HuaweiPhone(); } return null; } } ``` 调用工厂类获取具体的实例: ```java public class ZTest { public static void main(String[] args) { PhoneFactory phoneFactory = new PhoneFactory(); phoneFactory.getPhone("xiaomi").call("123"); phoneFactory.getPhone("huawei").call("321"); } } ``` ### 2.3 优缺点 简单工厂的优点在于其向用户屏蔽了对象创建过程,使得用户可以不必关注具体的创建细节,其缺陷在于违背了开闭原则。在简单工厂模式中,如果想要增加新的产品,就需要修改简单工厂中的判断逻辑,这就违背了开闭原则,因此其并不属于 GOF 经典的 23 种设计模式。在 Java 语言中,可以通过泛型来尽量规避这一缺陷,此时可以将创建产品的方法修改为如下所示: ```java public Phone getPhone(Class<? extends Phone> phoneClass) { try { return (Phone) Class.forName(phoneClass.getName()).newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { e.printStackTrace(); } return null; } ``` ## 3. 工厂模式 ### 3.1 定义 定义一个用于创建对象的工厂接口,但具体实例化哪一个工厂则由子类来决定。 ### 3.2 示例 <div align="center"> <img src="../pictures/23_factory_method.png"/> </div> 产品抽象类: ```java public abstract class Phone { public abstract void call(String phoneNum); } ``` 产品实现类: ```java public class HuaweiPhone extends Phone { public void call(String phoneNum) { System.out.println("华为手机拨打电话:" + phoneNum); } } ``` ```java public class XiaomiPhone extends Phone { public void call(String phoneNum) { System.out.println("小米手机拨打电话:" + phoneNum); } } ``` 工厂接口: ```java public interface Factory { Phone produce(); } ``` 工厂实现类: ```java public class HuaweiPhoneFactory implements Factory { @Override public Phone produce() { return new HuaweiPhone(); } } ``` ```java public class XiaomiPhoneFactory implements Factory { @Override public Phone produce() { return new XiaomiPhone(); } } ``` 由调用者来决定实例化哪一个工厂对象: ```java public class ZTest { public static void main(String[] args) { XiaomiPhoneFactory xiaomiPhoneFactory = new XiaomiPhoneFactory(); xiaomiPhoneFactory.produce().call("123"); HuaweiPhoneFactory huaweiPhoneFactory = new HuaweiPhoneFactory(); huaweiPhoneFactory.produce().call("456"); } } ``` ### 3.3 优点 工厂模式的优点在于良好的封装性和可扩展性,如果想要增加新的产品(如:OppoPhone),只需要增加对应的工厂类即可,同时和简单工厂一样,它也向用户屏蔽了不相关的细节,使得系统的耦合度得以降低。 ## 4. 抽象工厂模式 ### 4.1 定义 提供一个创建一系列相关或相互依赖对象的接口,而无需指定它们具体的实现类。抽象工厂模式是工厂模式的升级版本,它适用于存在多个产品的情况。接着上面的例子,假设每个工厂不仅生产手机,而且还需要生产对应的充电器,这样才能算一个可以出售的产品,相关的代码示例如下: ### 4.2 示例 <div align="center"> <img src="../pictures/23_abstract_factory.png"/> </div> 充电器抽象类: ```java public abstract class Charger { public abstract void Charge(Phone phone); } ``` 充电器实现类: ```java public class HuaiweiCharger extends Charger { @Override public void Charge(Phone phone) { System.out.println("华为充电器给" + phone + "充电"); } } ``` ```java public class XiaomiCharger extends Charger { @Override public void Charge(Phone phone) { System.out.println("小米充电器给" + phone + "充电"); } } ``` 工厂接口: ```java public interface Factory { Phone producePhone(); Charger produceCharger(); } ``` 工厂实现类: ```java public class HuaweiPhoneFactory implements Factory { @Override public Phone producePhone() { return new HuaweiPhone(); } @Override public Charger produceCharger() { return new HuaiweiCharger(); } } ``` ```java public class XiaomiPhoneFactory implements Factory { @Override public Phone producePhone() { return new XiaomiPhone(); } @Override public Charger produceCharger() { return new XiaomiCharger(); } } ``` 调用具体的工厂实现类: ```java public class ZTest { public static void main(String[] args) { XiaomiPhoneFactory xiaomiPhoneFactory = new XiaomiPhoneFactory(); xiaomiPhoneFactory.produceCharger().Charge(xiaomiPhoneFactory.producePhone()); HuaweiPhoneFactory huaweiPhoneFactory = new HuaweiPhoneFactory(); huaweiPhoneFactory.produceCharger().Charge(huaweiPhoneFactory.producePhone()); } } ``` ### 4.3 优缺点 抽象工厂模式继承了工厂模式的优点,能用于存在多个产品的情况,但其对应的产品族必须相对固定,假设我们现在认为 手机 + 充电器 + 耳机 才算一个可以对外出售的产品,则上面所有的工厂类都需要更改,但显然不是所有的手机都有配套的耳机,手机 + 充电器 这个产品族是相对固定的。 ## 5. 构建者模式 ### 5.1 定义 将一个复杂对象的构造与它的表示分离,使同样的构建过程可以创建不同的表示。它将一个复杂对象的创建过程分解为多个简单的步骤,然后一步一步的组装完成。 ### 5.2 示例 <div align="center"> <img src="../pictures/23_builder.png"/> </div> 产品实体类: ```java public class Phone { /*处理器*/ private String processor; /*摄像头*/ private String camera; /*屏幕*/ private String screen; } ``` 建造者抽象类: ```java public abstract class Builder { protected Phone phone = new Phone(); /*安装处理器*/ public abstract void addProcessor(); /*组装摄像头*/ public abstract void addCamera(); /*安装屏幕*/ public abstract void addScreen(); public Phone produce() { return phone; } } ``` 建造者实现类: ```java public class HuaweiBuilder extends Builder { @Override public void addProcessor() { phone.setProcessor("海思麒麟处理器"); } @Override public void addCamera() { phone.setCamera("莱卡摄像头"); } @Override public void addScreen() { phone.setScreen("OLED"); } } ``` ```java public class XiaomiBuilder extends Builder { @Override public void addProcessor() { phone.setProcessor("高通骁龙处理器"); } @Override public void addCamera() { phone.setCamera("索尼摄像头"); } @Override public void addScreen() { phone.setScreen("OLED"); } } ``` 定义管理者类(也称为导演类),由它来驱使具体的构建者按照指定的顺序完成构建过程: ```java public class Manager { private Builder builder; public Manager(Builder builder) { this.builder = builder; } public Phone buy() { builder.addCamera(); builder.addProcessor(); builder.addScreen(); return builder.produce(); } } ``` 调用管理者类获取产品: ```java public class ZTest { public static void main(String[] args) { Phone huawei = new Manager(new HuaweiBuilder()).buy(); System.out.println(huawei); Phone xiaomi = new Manager(new XiaomiBuilder()).buy(); System.out.println(xiaomi); } } // 输出: Phone(processor=海思麒麟处理器, camera=莱卡摄像头, screen=OLED) Phone(processor=高通骁龙处理器, camera=索尼摄像头, screen=OLED) ``` ### 5.3 优点 建造者模式的优点在于将复杂的构建过程拆分为多个独立的单元,在保证拓展性的基础上也保证了良好的封装性,使得客户端不必知道产品的具体创建流程。 ## 6. 原型模式 ### 6.1 定义 用原型实例指定创建对象的种类,并通过拷贝这些原型创建新的对象。 ### 6.2 示例 在 Java 语言中可以通过 `clone()` 方法来实现原型模式: ```java public class Phone implements Cloneable { private String type; Phone(String type) { System.out.println("构造器被调用"); this.type = type; } public void call() { System.out.println(type + "拨打电话"); } @Override protected Object clone() throws CloneNotSupportedException { System.out.println("克隆方法被调用"); return super.clone(); } } ``` 使用克隆来创建对象: ```java Phone phone = new Phone("3G手机"); Phone clonePhone = (Phone) phone.clone(); clonePhone.call(); ``` 在使用 clone 方法时需要注意区分深拷贝和浅拷贝:即如果待拷贝的对象中含有引用类型的变量,也需要对其进行拷贝,示例如下: ```java public class SmartPhone implements Cloneable { private String type; private Date productionDate; SmartPhone(String type, Date productionDate) { this.type = type; this.productionDate = productionDate; } public void call() { System.out.println(type + "拨打电话"); } @Override protected Object clone() throws CloneNotSupportedException { SmartPhone smartPhone = (SmartPhone) super.clone(); // 对引用对象进行拷贝 smartPhone.productionDate = (Date) smartPhone.productionDate.clone(); return smartPhone; } } ``` ### 6.3 适用场景 原型模式是直接在内存中进行二进制流的拷贝,被拷贝对象的构造函数并不会被执行,因此其性能表现非常优秀。如果对象的创建需要消耗非常多的资源,此时应该考虑使用原型模式。 # 结构型 ## 1. 代理模式 ### 1.1 定义 为目标对象提供一个代理对象以控制外部环境对其的访问,此时外部环境应访问该代理对象,而不是目标对象。通过代理模式,可以在不改变目标对象的情况下,实现功能的扩展。 在 Java 语言中,根据代理对象生成的时间点的不同可以分为静态代理和动态代理,其中动态代理根据实现方式的不同又可以分为 JDK 代理 和 Cglib 代理。 ### 1.2 静态代理 此时代理对象和目标对象需要实现相同的接口: ```java public interface IService { void compute(); } ``` 目标对象: ```java public class ComputeService implements IService { @Override public void compute() { System.out.println("业务处理"); } } ``` 在代理对象中注入目标对象的实例: ```java public class ProxyService implements IService { private IService target; public ProxyService(IService target) { this.target = target; } @Override public void compute() { System.out.println("权限校验"); target.compute(); System.out.println("资源回收"); } } ``` 调用时候应该访问代理对象,而不是目标对象: ```java ProxyService proxyService = new ProxyService(new ComputeService()); proxyService.compute(); ``` ### 1.3 JDK 代理 除了使用静态代理外,还可以利用 JDK 中的 Proxy 类和反射功能来实现对目标对象的代理: ```java ComputeService target = new ComputeService(); IService proxyInstance = (IService) Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), //代理类要实现的接口列表 (proxy, method, args1) -> { System.out.println("权限校验"); Object invoke = method.invoke(target, args1); System.out.println("资源回收"); return invoke; }); proxyInstance.compute(); ``` 静态代理和 JDK 动态代理都要求目标对象必须实现一个或者多个接口,如果目标对象不存在任何接口,此时可以使用 Cglib 方式对其进行代理。 ### 1.4 Cglib 代理 要想使用 Cglib 代理,必须导入相关的依赖: ```xml <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.3.0</version> </dependency> ``` 此时目标对象不需要实现任何接口: ```java public class ComputeService { public void compute() { System.out.println("业务处理"); } } ``` 使用 Cglib 进行代理: ```java public class Proxy implements MethodInterceptor { private Object target; public Proxy(Object target) { this.target = target; } public Object getProxyInstance() { // 创建用于生成生成动态子类的工具类 Enhancer enhancer = new Enhancer(); // 指定动态生成类的父类 enhancer.setSuperclass(target.getClass()); // 设置回调 enhancer.setCallback(this); // 动态生成子类 return enhancer.create(); } /** * 我们只需要实现此处的拦截逻辑,其他代码都是相对固定的 */ @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws InvocationTargetException, IllegalAccessException { System.out.println("权限校验"); Object invoke = method.invoke(target, args); System.out.println("资源回收"); return invoke; } } ``` 访问代理对象: ```java Proxy proxy = new Proxy(new ComputeService()); ComputeService service = (ComputeService) proxy.getProxyInstance(); service.compute(); ``` ## 2. 适配器模式 ### 2.1 定义 将一个类的接口转换成客户希望的另外一个接口,从而使得原本由于接口不兼容而无法一起工作的类可以一起工作。 ### 2.2 示例 将 220V 的电流通过适配器转换为对应规格的电流给手机充电: <div align="center"> <img src="..\pictures\23_adapter.png"/> </div> 电源类: ```java public class PowerSupply { private final int output = 220; public int output220V() { System.out.println("电源电压:" + output); return output; } } ``` 手机电压规格: ```java public interface Target { int output5V(); } ``` 适配器需要继承自源类,并实现目标类接口: ```java public class ChargerAdapter extends PowerSupply implements Target { @Override public int output5V() { int output = output220V(); System.out.println("充电头适配转换"); output = output / 44; System.out.println("输出电压:" + output); return output; } } ``` 测试: ```java public class ZTest { public static void main(String[] args) { Target target = new ChargerAdapter(); target.output5V(); } } // 输出: 电源电压:220 充电头适配转换 输出电压:5 ``` ## 3. 桥接模式 ### 3.1 定义 将抽象部分与它的实现部分分离,使它们都可以独立地变化。它使用组合关系来代替继承关系,从而降低了抽象和实现这两个可变维度的耦合度。 ### 3.2 优点 + 抽象和实现分离; + 优秀的扩展能力; + 实现细节对客户端透明,客户可以通过各种聚合来实现不同的需求。 ### 3.3 示例 将一个图形的形状和颜色进行分离,从而可以通过组合来实现的不同的效果: <div align="center"> <img src="..\pictures\23_bridge.png"/> </div> 颜色的抽象和实现: ```java public interface Color { String getDesc(); } public class Blue implements Color { @Override public String getDesc() { return "蓝色"; } } public class Red implements Color { @Override public String getDesc() { return "红色"; } } public class Yellow implements Color { @Override public String getDesc() { return "黄色"; } } ``` 图形的抽象和实现: ```java public abstract class Shape { private Color color; public Shape setColor(Color color) { this.color = color; return this; } public Color getColor() { return color; } public abstract void getDesc(); } public class Round extends Shape { @Override public void getDesc() { System.out.println(getColor().getDesc() + "圆形"); } } public class Square extends Shape { @Override public void getDesc() { System.out.println(getColor().getDesc() + "正方形"); } } ``` 通过聚合的方式来进行调用: ```java new Square().setColor(new Red()).getDesc(); new Square().setColor(new Blue()).getDesc(); new Round().setColor(new Blue()).getDesc(); new Round().setColor(new Yellow()).getDesc(); ``` ## 4. 组合模式 ### 4.1 定义 将对象组合成树形结构以表示 “部分-整体” 的层次结构,组合模式使得用户对单个对象和组合对象的使用具有一致性。 ### 4.2 优点 + 单个对象和组合对象具有一致性,这简化了客户端代码; + 可以在组合体类加入新的对象,而无需改变其源码。 ### 4.3 示例 模拟 Linux 文件系统: <div align="center"> <img src="..\pictures\23_composite.png"/> </div> 组件类,定义文件夹和文件的所有操作: ```java public abstract class Component { private String name; public Component(String name) { this.name = name; } public void add(Component component) { throw new UnsupportedOperationException("不支持添加操作"); } public void remove(Component component) { throw new UnsupportedOperationException("不支持删除操作"); } public void vim(String content) { throw new UnsupportedOperationException("不支持使用vim编辑器打开"); } public void cat() { throw new UnsupportedOperationException("不支持查看操作"); } public void print() { throw new UnsupportedOperationException("不支持打印操作"); } } ``` 文件夹类: ```java public class Folder extends Component { private List<Component> componentList = new ArrayList<>(); public Folder(String name) { super(name); } @Override public void add(Component component) { componentList.add(component); } @Override public void remove(Component component) { componentList.remove(component); } @Override public void print() { System.out.println(getName()); componentList.forEach(x -> System.out.println(" " + x.getName())); } } ``` 文件类: ```java public class File extends Component { private String content; public File(String name) { super(name); } @Override public void vim(String content) { this.content = content; } @Override public void cat() { System.out.println(content); } @Override public void print() { System.out.println(getName()); } } ``` 通过组合来实现层级结构: ```java Folder rootDir = new Folder("ROOT目录"); Folder nginx = new Folder("Nginx安装目录"); Folder tomcat = new Folder("Tomcat安装目录"); File startup = new File("startup.bat"); rootDir.add(nginx); rootDir.add(tomcat); rootDir.add(startup); rootDir.print(); startup.vim("java -jar"); startup.cat(); nginx.cat(); ``` ## 5. 装饰模式 ### 5.1 定义 在不改变现有对象结构的情况下,动态地给该对象增加一些职责或功能。 ### 5.2 优点 - 采用装饰模式扩展对象的功能比采用继承方式更加灵活。 - 可以通过设计多个不同的装饰类,来创造出多个不同行为的组合。 ### 5.3 示例 在购买手机后,你可能还会购买屏幕保护膜,手机壳等来进行装饰: <div align="center"> <img src="..\pictures\23_decorator.png"/> </div> 手机抽象类及其实现: ```java public abstract class Phone { public abstract int getPrice(); public abstract String getDesc(); } public class MiPhone extends Phone { @Override public int getPrice() { return 1999; } @Override public String getDesc() { return "MiPhone"; } } ``` 装饰器抽象类: ```java public abstract class Decorator extends Phone { private Phone phone; public Decorator(Phone phone) { this.phone = phone; } @Override public int getPrice() { return phone.getPrice(); } @Override public String getDesc() { return phone.getDesc(); } } ``` 手机壳装饰器: ```java public class ShellDecorator extends Decorator { public ShellDecorator(Phone phone) { super(phone); } @Override public int getPrice() { return super.getPrice() + 200; } @Override public String getDesc() { return super.getDesc() + " + 手机壳"; } } ``` 屏幕保护膜装饰器: ```java public class FilmDecorator extends Decorator { public FilmDecorator(Phone phone) { super(phone); } @Override public int getPrice() { return super.getPrice() + 100; } @Override public String getDesc() { return super.getDesc() + " + 钢化膜"; } } ``` 调用装饰器对目标对象进行装饰: ```java public class ZTest { public static void main(String[] args) { ShellDecorator decorator = new ShellDecorator(new FilmDecorator(new MiPhone())); System.out.println(decorator.getDesc() + " : " + decorator.getPrice()); } } // 输出: MiPhone + 钢化膜 + 手机壳 : 2299 ``` ## 6. 外观模式 ### 6.1 定义 在现在流行的微服务架构模式下,我们通常会将一个大型的系统拆分为多个独立的服务,此时需要提供一个一致性的接口来给外部系统进行调用,这就是外观模式的一种体现。 ### 6.2 优点 + 降低了子系统和客户端之间的耦合度; + 对客户端屏蔽了系统内部的实现细节。 ### 6.3 示例 模仿电商购物下单,此时内部需要调用支付子系统,仓储子系统,物流子系统,而这些细节对用户都是屏蔽的: <div align="center"> <img src="..\pictures\23_facade.png"/> </div> 安全检查系统: ```java public class EnvInspectionService { public boolean evInspection() { System.out.println("支付环境检查..."); return true; } } ``` 支付子系统: ```java public class AccountService { public boolean balanceCheck() { System.out.println("账户余额校验..."); return true; } } ``` 物流子系统: ```java public class LogisticsService { public void ship(Phone phone) { System.out.println(phone.getName() + "已经发货,请注意查收..."); } } ``` 下单系统(外观门面): ```java public class OrderService { private EnvInspectionService inspectionService = new EnvInspectionService(); private AccountService accountService = new AccountService(); private LogisticsService logisticsService = new LogisticsService(); public void order(Phone phone) { if (inspectionService.evInspection()) { if (accountService.balanceCheck()) { System.out.println("支付成功"); logisticsService.ship(phone); } } } } ``` 用户只需要访问外观门面,调用下单接口即可: ```java Phone phone = new Phone("XXX手机"); OrderService orderService = new OrderService(); orderService.order(phone); // 输出: 支付环境检查... 账户余额校验... 支付成功 XXX手机已经发货,请注意查收... ``` ## 7. 享元模式 ### 7.1 定义 运用共享技术来有效地支持大量细粒度对象的复用,线程池,缓存技术都是其代表性的实现。在享元模式中存在以下两种状态: + 内部状态,即不会随着环境的改变而改变状态,它在对象初始化时就已经确定; + 外部状态,指可以随环境改变而改变的状态。 通过享元模式,可以避免在系统中创建大量重复的对象,进而可以节省系统的内存空间。 ### 7.2 示例 这里以创建 PPT 模板为例,相同类型的 PPT 模板不再重复创建: <div align="center"> <img src="..\pictures\23_flyweight.png"/> </div> PPT 抽象类: ```java public abstract class PowerPoint { /*版权*/ private String copyright; private String title; /*这里的版权信息是一种内部状态,它在PPT对象第一次创建时就已经确定*/ public PowerPoint(String copyright) { this.copyright = copyright; } /*PPT标题是一种外部状态,它可以由外部环境根据不同的需求进行更改*/ public void setTitle(String title) { this.title = title; } abstract void create(); @Override public String toString() { return "编号:" + hashCode() + ": PowerPoint{" + "copyright='" + copyright + '\'' + ", title='" + title + '\'' + '}'; } } ``` PPT 实现类: ```java public class BusinessPPT extends PowerPoint { public BusinessPPT(String copyright) { super(copyright); } @Override void create() { System.out.println("商务类PPT模板"); } } public class SciencePPT extends PowerPoint { public SciencePPT(String copyright) { super(copyright); } @Override void create() { System.out.println("科技类PPT模板"); } } public class ArtPPT extends PowerPoint { public ArtPPT(String copyright) { super(copyright); } @Override void create() { System.out.println("艺术类PPT模板"); } } ``` 通过工厂模式来进行创建和共享: ```java public class PPTFactory { private HashMap<String, PowerPoint> hashMap = new HashMap<>(); public PowerPoint getPPT(Class<? extends PowerPoint> clazz) { try { String name = clazz.getName(); if (hashMap.keySet().contains(name)) { return hashMap.get(name); } Constructor<?> constructor = Class.forName(name).getConstructor(String.class); PowerPoint powerPoint = (PowerPoint) constructor.newInstance("PPT工厂版本所有"); hashMap.put(name, powerPoint); return powerPoint; } catch (Exception e) { e.printStackTrace(); } return null; } } ``` 调用工厂类来创建或获取享元对象: ```java public class ZTest { public static void main(String[] args) { PPTFactory pptFactory = new PPTFactory(); PowerPoint ppt01 = pptFactory.getPPT(BusinessPPT.class); ppt01.setTitle("第一季度工作汇报"); System.out.println(ppt01); PowerPoint ppt02 = pptFactory.getPPT(BusinessPPT.class); ppt02.setTitle("第二季度工作汇报"); System.out.println(ppt02); PowerPoint ppt03 = pptFactory.getPPT(SciencePPT.class); ppt03.setTitle("科技展汇报"); System.out.println(ppt03); } } // 输出: 编号:1744347043: PowerPoint{copyright='PPT工厂版本所有', title='第一季度工作汇报'} 编号:1744347043: PowerPoint{copyright='PPT工厂版本所有', title='第二季度工作汇报'} 编号:662441761: PowerPoint{copyright='PPT工厂版本所有', title='科技展汇报'} ``` # 行为型 ## 1. 观察者模式 ### 1.1 定义 定义对象间一对多的依赖关系,当一个对象的状态发生改变时,所有依赖于它的对象都得到通知并被自动更新。 ### 1.2 优点 降低了目标对象和观察者之间的耦合。 ### 1.3 示例 假设多个用户都关注某一个商家,当商家发出降价等通知时,所有用户都应该收到: <div align="center"> <img src="../pictures/23_observer.png"/> </div> 被观察者接口及商家实现类: ```java public interface Observable { // 接收观察者 void addObserver(Observer observer); // 移除观察者 void removeObserver(Observer observer); // 通知观察者 void notifyObservers(String message); } ``` ```java public class Business implements Observable { private List<Observer> observerList = new ArrayList<>(); @Override public void addObserver(Observer observer) { observerList.add(observer); } @Override public void removeObserver(Observer observer) { observerList.remove(observer); } @Override public void notifyObservers(String message) { for (Observer observer : observerList) { observer.receive(message); } } } ``` 观察者接口及用户实现类: ```java public interface Observer { void receive(String message); } ``` ```java public class User implements Observer { private String name; public User(String name) { this.name = name; } @Override public void receive(String message) { System.out.println(getName() + "收到消息:" + message); } } ``` 测试商户发送消息: ```java Business business = new Business(); business.addObserver(new User("用户1")); business.addObserver(new User("用户2")); business.addObserver(new User("用户3")); business.notifyObservers("商品促销通知"); // 输出: 用户1收到消息:商品促销通知 用户2收到消息:商品促销通知 用户3收到消息:商品促销通知 ``` ## 2. 责任链模式 ### 2.1 定义 使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这些对象连接成一条链,并沿着这条链传递该请求,直到有一个对象处理完它为止。 ### 2.2 优点 - 降低了对象之间的耦合度; - 增强了系统的可扩展性。可以根据需求增加新的处理类,满足开闭原则; - 增强了系统的灵活性。当工作流程发生变化,可以动态地新增,删除成员或修改其调动次序; - 每个对象只需保持一个指向其后继者的引用,而无需保持其他所有处理者的引用,从而可以避免了过多的条件判断语句; - 每个类只需要处理自己该处理的工作,不能处理的则传递给下一个对象完成,符合类的单一职责原则。 ### 2.3 示例 假设一个正常的流程,根据请假天数的不同,需要不同的领导共同审批: <div align="center"> <img src="..\pictures\23_chain_of_responsibility.png"/> </div> 申请单: ```java public class Application { private String title; /*请假天数*/ private int dayNum; } ``` 抽象的领导类: ```java public abstract class Leader { protected Leader leader; // 责任链模式的核心:其需要持有一个后继者 public Leader setNextLeader(Leader leader) { this.leader = leader; return leader; } public abstract void approval(Application application); } ``` 3天以下的请假只需要组长审核即可: ```java public class GroupLeader extends Leader { @Override public void approval(Application application) { System.out.println(application.getTitle() + "被组长审批通过"); if (application.getDayNum() >= 3) { leader.approval(application); } } } ``` 3天以上5天以下的请假则需要组长和部门经理共同审核: ```java public class DepartManager extends Leader { @Override public void approval(Application application) { System.out.println(application.getTitle() + "被部门经理审批通过"); if (application.getDayNum() >= 5) { leader.approval(application); } } } ``` 5 天以上的请假则还需要总经理审核: ```java public class President extends Leader { @Override public void approval(Application application) { System.out.println(application.getTitle() + "被总经理审批通过"); } } ``` 组建责任链并测试: ```java GroupLeader groupLeader = new GroupLeader(); DepartManager departManager = new DepartManager(); President president = new President(); groupLeader.setNextLeader(departManager).setNextLeader(president); groupLeader.approval(new Application("事假单", 3)); groupLeader.approval(new Application("婚假单", 10)); // 输出: 事假单被组长审批通过 事假单被部门经理审批通过 婚假单被组长审批通过 婚假单被部门经理审批通过 婚假单被总经理审批通过 ``` ## 3. 模板方法模式 ### 3.1 定义 定义一个操作的算法骨架,而将算法的一些步骤延迟到子类中,使得子类可以不改变该算法结构的情况下重定义该算法的某些特定步骤。它通常包含以下角色: **抽象父类** **(Abstract Class)**:负责给出一个算法的轮廓和骨架。它由一个模板方法和若干个基本方法构成: + 模板方法:定义了算法的骨架,按某种顺序调用其包含的基本方法。 + 基本方法:可以是具体的方法也可以是抽象方法,还可以是钩子方法(在抽象类中已经实现,包括用于判断的逻辑方法和需要子类重写的空方法两种)。 **具体子类** **(Concrete Class)**:实现抽象类中所定义的抽象方法和钩子方法。 ### 3.2 优点 + 父类定义了公共的行为,可以实现代码的复用; + 子类可以通过扩展来增加相应的功能,符合开闭原则。 ### 3.3 示例 手机一般都有电池,摄像头等模块,但不是所有手机都有 NFC 模块,如果采用模板模式构建,则相关代码如下: <div align="center"> <img src="..\pictures\23_template.png"/> </div> 抽象的父类: ```java public abstract class Phone { // 模板方法 public void assembling() { adCamera(); addBattery(); if (needAddNFC()) { addNFC(); } packaged(); } // 具体方法 private void adCamera() { System.out.println("组装摄像头"); } private void addBattery() { System.out.println("安装电池"); } private void addNFC() { System.out.println("增加NFC功能"); } // 钩子方法 abstract boolean needAddNFC(); // 抽象方法 abstract void packaged(); } ``` 具体的子类: ```java public class OlderPhone extends Phone { @Override boolean needAddNFC() { return false; } @Override void packaged() { System.out.println("附赠一个手机壳"); } } ``` ```java public class SmartPhone extends Phone { @Override boolean needAddNFC() { return true; } @Override void packaged() { System.out.println("附赠耳机一副"); } } ``` 测试与输出结果如下: ```java OlderPhone olderPhone = new OlderPhone(); olderPhone.assembling(); // 输出: 组装摄像头 安装电池 附赠一个手机壳 SmartPhone smartPhone = new SmartPhone(); smartPhone.assembling(); // 输出: 组装摄像头 安装电池 增加NFC功能 附赠耳机一副 ``` ## 4. 策略模式 ### 4.1 定义 定义一系列的算法,并将它们独立封装后再提供给客户端使用,从而使得算法的变化不会影响到客户端的使用。策略模式实际上是一种无处不在的模式,比如根据在 controller 层接收到的参数不同,调用不同的 service 进行处理,这也是策略模式的一种体现。 ### 4.2 示例 假设公司需要根据营业额的不同来选择不同的员工激励策略: <div align="center"> <img src="..\pictures\23_strategy.png"/> </div> 策略接口及其实现类: ```java public interface Strategy { void execute(); } public class TravelStrategy implements Strategy { @Override public void execute() { System.out.println("集体旅游"); } } public class BonusStrategy implements Strategy { @Override public void execute() { System.out.println("奖金激励"); } } public class WorkOvertimeStrategy implements Strategy { @Override public void execute() { System.out.println("奖励加班"); } } ``` 公司类: ```java public class Company { private Strategy strategy; public Company setStrategy(Strategy strategy) { this.strategy = strategy; return this; } public void execute() { strategy.execute(); } } ``` 客户端使用时,需要根据不同的营业额选择不同的激励策略: ```java public static void main(String[] args) { // 营业额 int turnover = Integer.parseInt(args[0]); Company company = new Company(); if (turnover > 1000) { company.setStrategy(new BonusStrategy()).execute(); } else if (turnover > 100) { company.setStrategy(new TravelStrategy()).execute(); } else { company.setStrategy(new WorkOvertimeStrategy()).execute(); } } ``` ## 6. 状态模式 ### 6.1 定义 对有状态的对象,把复杂的判断逻辑提取到不同的状态对象中,允许状态对象在其内部状态发生改变时改变其行为。 ### 6.2 优点 - 状态模式将与特定状态相关的行为局部化到一个状态中,并且将不同状态的行为分割开来,满足单一职责原则; - 将不同的状态引入到独立的对象中,使得状态转换变得更加明确,且减少对象间的相互依赖; - 有利于程序的扩展,通过定义新的子类很容易地增加新的状态和转换。 ### 6.3 示例 假设我们正在开发一个播放器,它有如下图所示四种基本的状态:播放状态,关闭状态,暂停状态,加速播放状态。这四种状态间可以相互转换,但存在一定的限制,比如在关闭或者暂停状态下,都不能加速视频,采用状态模式来实现该播放器的相关代码如下: <div align="center"> <img src="..\pictures\23_state.png"/> </div> 定义状态抽象类: ```java public class State { private Player player; public void setPlayer(Player player) { this.player = player; } public void paly() { player.setState(Player.PLAY_STATE); } public void pause() { player.setState(Player.PAUSE_STATE); } public void close() { player.setState(Player.CLOSE_STATE); } public void speed() { player.setState(Player.SPEED_STATE); } } ``` 定义四种状态的具体实现类,并限制它们之间的转换关系: ```java public class PlayState extends State { } ``` ```java public class CloseState extends State { @Override public void pause() { System.out.println("操作失败:视频已处于关闭状态,无需暂停"); } @Override public void speed() { System.out.println("操作失败:视频已处于关闭状态,无法加速"); } } ``` ```java public class PauseState extends State { @Override public void speed() { System.out.print("操作失败:暂停状态下不支持加速"); } } ``` ```java public class SpeedState extends State { @Override public void paly() { System.out.println("系统提示:你当前已处于加速播放状态"); } } ``` 组装播放器: ```java public class Player { private State state; public final static PlayState PLAY_STATE = new PlayState(); public final static PauseState PAUSE_STATE = new PauseState(); public final static CloseState CLOSE_STATE = new CloseState(); public final static SpeedState SPEED_STATE = new SpeedState(); public State getState() { return state; } public void setState(State state) { this.state = state; this.state.setPlayer(this); } Player() { // 假设播放器初始状态为关闭 this.state = new CloseState(); this.state.setPlayer(this); } public void paly() { System.out.println("播放视频"); state.paly(); } public void pause() { System.out.println("暂停视频"); state.pause(); } public void close() { System.out.println("关闭视频"); state.close(); } public void speed() { System.out.println("视频加速"); state.speed(); } } ``` 调用我们自定义的播放器: ```java Player player = new Player(); player.speed(); player.paly(); player.speed(); player.paly(); player.pause(); player.close(); player.speed(); // 输出: 视频加速 操作失败:视频已处于关闭状态,无法加速 播放视频 视频加速 播放视频 系统提示:你当前已处于加速播放状态 暂停视频 关闭视频 视频加速 操作失败:视频已处于关闭状态,无法加速 ``` ## 7. 中介者模式 ### 7.1 定义 定义一个中介对象来封装一系列对象之间的交互,使原有对象之间的耦合松散,且可以独立地改变它们之间的交互。 ### 7.2 优点 降低了对象之间的耦合度。 ### 7.3 示例 这里以房屋中介为例,定义一个抽象的中介类,负责接收客户以及在客户间传递消息: ```java abstract class Mediator { public abstract void register(Person person); public abstract void send(String from, String message); } ``` 具体的房屋中介,它会将卖方的出售消息广播给所有人: ```java public class HouseMediator extends Mediator { private List<Person> personList = new ArrayList<>(); @Override public void register(Person person) { if (!personList.contains(person)) { personList.add(person); person.setMediator(this); } } @Override public void send(String from, String message) { System.out.println(from + "发送消息:" + message); for (Person person : personList) { String name = person.getName(); if (!name.equals(from)) { person.receive(message); } } } } ``` 定义用户类,它可以是买方也可以是卖方,它们都是中介的客户: ```java public class Person { private String name; private Mediator mediator; public Person(String name) { this.name = name; } public void send(String message) { mediator.send(this.name, message); } public void receive(String message) { System.out.println(name + "收到消息:" + message); } } ``` 最后买卖双方通过中介人就可以进行沟通: ```java public class ZTest { public static void main(String[] args) { HouseMediator houseMediator = new HouseMediator(); Person seller = new Person("卖方"); Person buyer = new Person("买方"); houseMediator.register(seller); houseMediator.register(buyer); buyer.send("价格多少"); seller.send("10万"); buyer.send("太贵了"); } } // 输出: 买方发送消息:价格多少 卖方收到消息:价格多少 卖方发送消息:10万 买方收到消息:10万 买方发送消息:太贵了 卖方收到消息:太贵了 ``` ## 8. 迭代器模式 ### 8.1 定义 提供了一种方法用于顺序访问一个聚合对象中的各个元素,而又不暴露该对象的内部表示。 ### 8.2 示例 假设现在对书架中的所有书籍进行遍历,首先定义书籍类: ```java public class Book { private String name; public Book(String name) { this.name = name; } } ``` 定义书柜接口及其实现类: ```java public interface Bookshelf { void addBook(Book book); void removeBook(Book book); BookIterator iterator(); } public class BookshelfImpl implements Bookshelf { private List<Book> bookList = new ArrayList<>(); @Override public void addBook(Book book) { bookList.add(book); } @Override public void removeBook(Book book) { bookList.remove(book); } @Override public BookIterator iterator() { return new BookIterator(bookList); } } ``` 定义迭代器接口及其实现类: ```java public interface Iterator<E> { E next(); boolean hasNext(); } public class BookIterator implements Iterator<Book> { private List<Book> bookList; private int position = 0; public BookIterator(List<Book> bookList) { this.bookList = bookList; } @Override public Book next() { return bookList.get(position++); } @Override public boolean hasNext() { return position < bookList.size(); } } ``` 调用自定义的迭代器进行遍历: ```java BookshelfImpl bookshelf = new BookshelfImpl(); bookshelf.addBook(new Book("Java书籍")); bookshelf.addBook(new Book("Python书籍")); bookshelf.addBook(new Book("Go书籍")); BookIterator iterator = bookshelf.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } ``` ## 9. 访问者模式 ### 9.1 定义 表示一个作用于某对象结构中各个元素的操作,它使得用户可以在不改变各个元素所对应类的前提下定义对这些元素的操作。 ### 9.2 优缺点 优点: - 扩展性好:能够在不修改对象结构中的元素的情况下,为对象结构中的元素添加新的功能。 - 复用性好:可以通过访问者来定义整个对象结构通用的功能,从而提高系统的复用程度。 - 灵活性好:访问者模式将数据结构与作用于结构上的操作解耦,使得操作可相对自由地演化而不影响系统的数据结构。 缺点: + 增加新的元素类很复杂; + 实现相对繁琐。 ### 9.3 示例 通常不同级别的员工对于公司档案的访问权限是不同的,为方便理解,如下图所示假设只有公开和加密两种类型的档案,并且只有总经理和部门经理才能进入档案室: <div align="center"> <img src="..\pictures\23_visitor.png"/> </div> 定义档案类及其实现类: ```java public interface Archive { // 接受访问者 void accept(Visitor visitor); } public class PublicArchive implements Archive { @Override public void accept(Visitor visitor) { visitor.visit(this); } } public class SecretArchive implements Archive { @Override public void accept(Visitor visitor) { visitor.visit(this); } } ``` 定义访问者接口及其实现类: ```java public interface Visitor { // 访问公开档案 void visit(PublicArchive publicArchive); // 访问加密档案 void visit(SecretArchive secretArchive); } ``` ```java public class DepartManager implements Visitor { @Override public void visit(PublicArchive publicArchive) { System.out.println("所有公开档案"); } @Override public void visit(SecretArchive secretArchive) { System.out.println("三级以下权限的加密档案"); } } ``` ```java public class President implements Visitor { @Override public void visit(PublicArchive publicArchive) { System.out.println("所有公开档案"); } @Override public void visit(SecretArchive secretArchive) { System.out.println("所有加密档案"); } } ``` 通过公司类来管理访问: ```java public class Company { private List<Archive> archives = new ArrayList<>(); // 接收档案 void add(Archive archive) { archives.add(archive); } // 移除档案 void remove(Archive archive) { archives.remove(archive); } // 接待访问者 void accept(Visitor visitor) { for (Archive archive : archives) { archive.accept(visitor); } } } ``` 测试及输出结果: ```java Company company = new Company(); company.add(new SecretArchive()); company.add(new PublicArchive()); company.accept(new DepartManager()); // 输出: 三级以下权限的加密档案 所有公开档案 company.accept(new President()); // 输出: 所有加密档案 所有公开档案 ``` ## 10. 备忘录模式 ### 10.1 定义 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,以便在需要时能将该对象恢复到原有状态。 ### 10.2 优缺点 优点是能够用于异常情况下的恢复,能够提高系统的安全性;缺点是需要额外的存储空间来保存历史状态。 ### 10.3 示例 编辑器的撤销功能,数据库的快照功能都是备忘录模式的一种典型实现,这里我们以 Git 保存历史版本信息为例,进行演示: 文章类: ```java public class Article { private String title; private String content; } ``` 根据业务需求的不同,你可能只需要保存数据的部分字段,或者还需要额外增加字段(如保存时间等),所以在保存时需要将目标对象转换为备忘录对象: ```java // 备忘录对象 public class Memorandum { private String title; private String content; private Date createTime; // 根据目标对象来创建备忘录对象 public Memorandum(Article article) { this.title = article.getTitle(); this.content = article.getContent(); this.createTime = new Date(); } public Article toArticle() { return new Article(this.title, this.content); } } ``` 管理者类: ```java public class GitRepository { private List<Memorandum> repository = new ArrayList<>(); // 保存当前数据 public void save(Article article) { Memorandum memorandum = new Memorandum(article); repository.add(memorandum); } // 获取指定版本类的数据 public Article get(int version) { Memorandum memorandum = repository.get(version); return memorandum.toArticle(); } // 撤销当前操作 public Article back() { return repository.get(repository.size() - 1).toArticle(); } } ``` 测试类: ```java GitRepository repository = new GitRepository(); Article article = new Article("Java手册", "版本一"); repository.save(article); article.setContent("版本二"); repository.save(article); article.setContent("版本三"); repository.save(article); System.out.println(repository.back()); System.out.println(repository.get(0)); ``` ## 11. 解释器模式 给分析对象定义一种语言,并定义该语言的文法表示,然后设计一个解析器来解释语言中的语句,用编译语言的方式来分析应用中的实例。解释器模式的实现比较复杂,在通常的开发也较少使用,这里就不提供示例了。 以上所有示例的源码见:[design-pattern](https://github.com/heibaiying/Full-Stack-Notes/tree/master/code/Java/design-pattern) ## 参考资料 1. Erich Gamma / Richard Helm / Ralph Johnson / John Vlissides . 设计模式(可复用面向对象软件的基础). 机械工业出版社 . 2000-9 2. 秦小波 . 设计模式之禅(第2版). 机械工业出版社 . 2014-2-25 3. [Java 设计模式](http://c.biancheng.net/view/1317.html) 4. [Java 设计模式精讲 Debug 方式 + 内存分析](https://coding.imooc.com/class/270.html)
JavaScript
UTF-8
6,357
2.515625
3
[ "MIT", "Apache-2.0" ]
permissive
xdescribe('QiitaのStaticプロパティへのアクセス', function() { return it('指定のurlプロパティにアクセスした場合に値が一致する', function() { var Qiita, qiita, url; Qiita = require('qiita'); qiita = new Qiita(); url = "https://qiita.com/api/v1/users/h5y1m141@github/stocks"; return expect(qiita.parameter.stocks.url).toBe(url); }); }); describe('Qiitaクラスのためのテスト', function() { beforeEach(function() { var Qiita, qiita; Qiita = require('qiita'); return qiita = new Qiita(); }); describe('ネットワークの接続確認:正常系', function() { return it('ネットワーク利用できる状況にある', function() { return expect(qiita.isConnected()).toBe(true); }); }); describe('Qiitaのストック情報', function() { var async, content, lastPage, lastPageContents, nextPage, postFail, postItem, putStockFail; content = null; nextPage = null; lastPage = null; lastPageContents = null; async = new AsyncSpec(this); async.beforeEach(function(done) { return runs(function() { return qiita.getMyStocks(function(result, links) { var link, _i, _len; for (_i = 0, _len = links.length; _i < _len; _i++) { link = links[_i]; if (link["rel"] === "next") { nextPage = link["url"]; } else if (link["rel"] === "last") { lastPage = link["url"]; qiita.getNextFeed(lastPage, function(result, links) { return lastPageContents = result; }); } else { Ti.API.info(link["url"]); } } content = result; return done(); }); }); }); waits(1000); it('投稿情報取得出来る', function() { return runs(function() { return expect(content).not.toBeNull(); }); }); it('投稿情報の件数が一致する', function() { return runs(function() { return expect(content.length).toBe(20); }); }); it('最終ページに移動できる', function() { return runs(function() { return expect(lastPageContents instanceof Array).toBe(true); }); }); it('原因がわからないが自分のアカウントで最終ページに到達すると投稿情報空になるので、その確認', function() { return runs(function() { return expect(lastPageContents.length).toBe(0); }); }); waits(1000); postItem = { uuid: "1d65e3fc04ee4693122c", title: "MySQLで秘密のトークンなんかを0と比較したらちょい危険" }; xit('ストックに成功する', function() { return runs(function() { return expect(qiita.putStock(postItem.uuid)) === true; }); }); putStockFail = null; postFail = { uuid: "1", title: "MySQLで秘密のトークンなんかを0と比較したらちょい危険" }; async.beforeEach(function(done) { return runs(function() { qiita.putStock(postFail.uuid); return done(); }); }); return xit('存在しないストックをポストした場合にはErrorになる', function() { return runs(function() { putStockFail = Ti.App.Properties.getString('QiitaPutStockFail'); return expect(putStockFail) === "error"; }); }); }); xdescribe('Qiitaのフィード情報', function() { var async, feed, lastPage, nextPage; feed = null; nextPage = null; lastPage = null; async = new AsyncSpec(this); async.beforeEach(function(done) { return runs(function() { return qiita.getFeed(function(result, links) { var link, _i, _len; feed = result; for (_i = 0, _len = links.length; _i < _len; _i++) { link = links[_i]; if (link["rel"] === "next") { nextPage = link["url"]; } else if (link["rel"] === "last") { lastPage = link["url"]; } else { Ti.API.info(link["url"]); } } return done(); }); }); }); it('フィード情報が取得できる', function() { return runs(function() { return expect(feed).not.toBeNull(); }); }); waits(1000); it('フィード情報の次のページのURLが取得できる', function() { return runs(function() { return expect(nextPage).toBe("https://qiita.com/api/v1/items?page=2"); }); }); waits(1000); return it('フィード情報の最後のページのURLが取得できる', function() { return runs(function() { return expect(lastPage).not.toBeNull(); }); }); }); return xdescribe('認証処理', function() { var async, asyncToken, noToken, token; noToken = null; token = null; async = new AsyncSpec(this); async.beforeEach(function(done) { return runs(function() { var failParam; failParam = { url_name: "h5y1m141@github", password: "failpassword" }; qiita._auth(failParam); noToken = Ti.App.Properties.getString('QiitaTokenFail'); return done(); }); }); it('パスワードが違うのでtoken取得出来ない', function() { var errorMessage; errorMessage = 'Error Domain=ASIHTTPRequestErrorDomain Code=3 "Authentication needed" UserInfo=0xa3f1470 {NSLocalizedDescription=Authentication needed}'; return expect(noToken).toBe(errorMessage); }); asyncToken = new AsyncSpec(this); asyncToken.beforeEach(function(done) { return runs(function() { var collectParam, config, configJSON, file; configJSON = Titanium.Filesystem.getFile(Titanium.Filesystem.resourcesDirectory, 'config/login.json'); file = configJSON.read().toString(); config = JSON.parse(file); collectParam = { url_name: config.url_name, password: config.password }; qiita._auth(collectParam); token = Ti.App.Properties.getString('QiitaToken'); return done(); }); }); return it('tokenが取得できる', function() { return expect(token.length).toBe(32); }); }); });
C#
UTF-8
14,742
2.546875
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows.Forms; using System.Xml.Serialization; namespace ModManagerCommon { [XmlRoot(Namespace = "http://www.sonicretro.org")] public class CodeList { static readonly XmlSerializer serializer = new XmlSerializer(typeof(CodeList)); public static CodeList Load(string filename) { if (Path.GetExtension(filename).Equals(".xml", StringComparison.OrdinalIgnoreCase)) using (FileStream fs = File.OpenRead(filename)) return (CodeList)serializer.Deserialize(fs); else using (StreamReader sr = File.OpenText(filename)) { CodeList result = new CodeList(); Stack<Tuple<List<CodeLine>, List<CodeLine>>> stack = new Stack<Tuple<List<CodeLine>, List<CodeLine>>>(); int linenum = 0; while (!sr.EndOfStream) { ++linenum; string line = sr.ReadLine().Trim(' ', '\t'); if (line.Length == 0) continue; if (line.StartsWith(";")) continue; string[] split = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); Code code = null; switch (split[0]) { case "Code": if (stack.Count > 1) throw new FormatException($"Invalid code line \"{line}\" in {filename}:line {linenum}"); if (stack.Count == 1) stack.Pop(); code = new Code(); ProcessCodeLine(filename, linenum, split, code); result.Codes.Add(code); stack.Push(new Tuple<List<CodeLine>, List<CodeLine>>(code.Lines, null)); break; case "Patch": if (stack.Count > 1) throw new FormatException($"Invalid code line \"{line}\" in {filename}:line {linenum}"); if (stack.Count == 1) stack.Pop(); code = new Code() { Patch = true }; ProcessCodeLine(filename, linenum, split, code); result.Codes.Add(code); stack.Push(new Tuple<List<CodeLine>, List<CodeLine>>(code.Lines, null)); break; default: if (Enum.TryParse(split[0], out CodeType type)) { switch (type) { case CodeType.@else: if (stack.Peek().Item2 == null) throw new FormatException($"Invalid code line \"{line}\" in {filename}:line {linenum}"); stack.Push(new Tuple<List<CodeLine>, List<CodeLine>>(stack.Pop().Item2, null)); continue; case CodeType.endif: if (stack.Count < 2) throw new FormatException($"Invalid code line \"{line}\" in {filename}:line {linenum}"); stack.Pop(); continue; case CodeType.newregs: throw new FormatException($"Invalid code line \"{line}\" in {filename}:line {linenum}"); default: break; } CodeLine cl = new CodeLine() { Type = type }; string address = split[1]; if (address.StartsWith("p")) { cl.Pointer = true; string[] offs = address.Split('|'); cl.Address = offs[0].Substring(1); if (offs.Length > 1) { cl.Offsets = new List<int>(); for (int i = 1; i < offs.Length; i++) cl.Offsets.Add(int.Parse(offs[i], System.Globalization.NumberStyles.HexNumber)); } } else cl.Address = address; int it = 2; switch (type) { case CodeType.s8tos32: case CodeType.s16tos32: case CodeType.s32tofloat: case CodeType.u32tofloat: case CodeType.floattos32: case CodeType.floattou32: cl.Value = "0"; break; default: cl.Value = split[it++]; break; } if (it < split.Length && !split[it].StartsWith(";")) cl.RepeatCount = uint.Parse(split[it++].Substring(1)); stack.Peek().Item1.Add(cl); if (cl.IsIf) stack.Push(new Tuple<List<CodeLine>, List<CodeLine>>(cl.TrueLines, cl.FalseLines)); } else throw new FormatException($"Invalid code line \"{line}\" in {filename}:line {linenum}"); break; } } return result; } } private static void ProcessCodeLine(string filename, int linenum, string[] split, Code code) { var sb = new System.Text.StringBuilder(split[1].TrimStart('"')); int i = 2; if (!split[1].EndsWith("\"")) for (; i < split.Length; i++) { sb.AppendFormat(" {0}", split[i]); if (split[i].EndsWith("\"")) { ++i; break; } } code.Name = sb.ToString().TrimEnd('"'); if (i < split.Length) for (; i < split.Length; i++) { if (split[i].StartsWith(";")) break; switch (split[i]) { case "Required": code.Required = true; break; default: throw new Exception($"Unknown attribute {split[i]} in code \"{code.Name}\" in {filename}:line {linenum}"); } } } public void Save(string filename) { if (Path.GetExtension(filename).Equals(".xml", StringComparison.OrdinalIgnoreCase)) using (FileStream fs = File.Create(filename)) serializer.Serialize(fs, this); else using (StreamWriter sw = File.CreateText(filename)) { foreach (Code code in Codes) { sw.Write("{0} \"{1}\"", code.Patch ? "Patch" : "Code", code.Name); if (code.Required) sw.Write(" Required"); sw.WriteLine(); List<CodeLine> lines = code.Lines; SaveCodeLines(sw, lines, 0); sw.WriteLine(); } } } private static void SaveCodeLines(StreamWriter sw, List<CodeLine> lines, int indent) { foreach (CodeLine line in lines) { sw.Write("{0}{1} ", new string('\t', indent), line.Type); if (line.Pointer) sw.Write("p"); sw.Write(line.Address); if (line.Offsets != null) foreach (int off in line.Offsets) sw.Write("|{0:X}", off); switch (line.ValueType) { case ValueType.hex: sw.Write(" 0x{0}", line.Value); break; default: sw.Write(" {0}", line.Value); break; } if (line.RepeatCount.HasValue) sw.Write(" x{0}", line.RepeatCount.Value); sw.WriteLine(); if (line.IsIf) { if (line.TrueLines != null && line.TrueLines.Count > 0) SaveCodeLines(sw, line.TrueLines, indent + 1); if (line.FalseLines != null && line.FalseLines.Count > 0) { sw.WriteLine("{0}else", new string('\t', indent)); SaveCodeLines(sw, line.FalseLines, indent + 1); } sw.WriteLine("{0}endif", new string('\t', indent)); } } } [XmlElement("Code")] public List<Code> Codes { get; set; } = new List<Code>(); public static void WriteDatFile(string path, IList<Code> codes) { using (FileStream fs = File.Create(path)) using (BinaryWriter bw = new BinaryWriter(fs, System.Text.Encoding.ASCII)) { bw.Write(new[] { 'c', 'o', 'd', 'e', 'v', '5' }); bw.Write(codes.Count); foreach (Code item in codes) { if (item.IsReg) bw.Write((byte)CodeType.newregs); WriteCodes(item.Lines, bw); } bw.Write(byte.MaxValue); } } private static void WriteCodes(List<CodeLine> lines, BinaryWriter bw) { foreach (CodeLine line in lines) { bw.Write((byte)line.Type); uint address; if (line.Address.StartsWith("r")) address = uint.Parse(line.Address.Substring(1), System.Globalization.NumberStyles.None, System.Globalization.NumberFormatInfo.InvariantInfo); else address = uint.Parse(line.Address, System.Globalization.NumberStyles.HexNumber); if (line.Pointer) address |= 0x80000000u; bw.Write(address); if (line.Pointer) if (line.Offsets != null) { bw.Write((byte)line.Offsets.Count); foreach (int off in line.Offsets) bw.Write(off); } else bw.Write((byte)0); if (line.Type == CodeType.ifkbkey) bw.Write((int)(Keys)Enum.Parse(typeof(Keys), line.Value)); else switch (line.ValueType) { case null: if (line.Value.StartsWith("0x")) bw.Write(uint.Parse(line.Value.Substring(2), System.Globalization.NumberStyles.HexNumber, System.Globalization.NumberFormatInfo.InvariantInfo)); else if (line.IsFloat) bw.Write(float.Parse(line.Value, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo)); else bw.Write(unchecked((int)long.Parse(line.Value, System.Globalization.NumberStyles.Integer, System.Globalization.NumberFormatInfo.InvariantInfo))); break; case ValueType.@decimal: if (line.IsFloat) bw.Write(float.Parse(line.Value, System.Globalization.NumberStyles.Float, System.Globalization.NumberFormatInfo.InvariantInfo)); else bw.Write(unchecked((int)long.Parse(line.Value, System.Globalization.NumberStyles.Integer, System.Globalization.NumberFormatInfo.InvariantInfo))); break; case ValueType.hex: bw.Write(uint.Parse(line.Value, System.Globalization.NumberStyles.HexNumber, System.Globalization.NumberFormatInfo.InvariantInfo)); break; } bw.Write(line.RepeatCount ?? 1); if (line.IsIf) { WriteCodes(line.TrueLines, bw); if (line.FalseLines.Count > 0) { bw.Write((byte)CodeType.@else); WriteCodes(line.FalseLines, bw); } bw.Write((byte)CodeType.endif); } } } } public class Code { [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("required")] public bool Required { get; set; } [XmlAttribute("patch")] public bool Patch { get; set; } [XmlElement("CodeLine")] public List<CodeLine> Lines { get; set; } = new List<CodeLine>(); [XmlIgnore] public bool IsReg { get { return Lines.Any((line) => line.IsReg); } } } public class CodeLine { public CodeType Type { get; set; } [XmlElement(IsNullable = false)] public string Address { get; set; } public bool Pointer { get; set; } [XmlIgnore] public bool PointerSpecified { get { return Pointer; } set { } } [XmlIgnore] public List<int> Offsets { get; set; } [XmlArray("Offsets")] [XmlArrayItem("Offset")] public string[] OffsetStrings { get { return Offsets?.Select((a) => a.ToString("X")).ToArray(); } set { Offsets = value.Select((a) => int.Parse(a, System.Globalization.NumberStyles.HexNumber)).ToList(); } } [XmlIgnore] public bool OffsetStringsSpecified { get { return Offsets != null && Offsets.Count > 0; } set { } } [XmlElement(IsNullable = false)] public string Value { get; set; } public ValueType? ValueType { get; set; } public uint? RepeatCount { get; set; } [XmlIgnore] public bool RepeatCountSpecified { get { return RepeatCount.HasValue; } set { } } [XmlArray] public List<CodeLine> TrueLines { get; set; } = new List<CodeLine>(); [XmlIgnore] public bool TrueLinesSpecified { get { return TrueLines.Count > 0 && IsIf; } set { } } [XmlArray] public List<CodeLine> FalseLines { get; set; } = new List<CodeLine>(); [XmlIgnore] public bool FalseLinesSpecified { get { return FalseLines.Count > 0 && IsIf; } set { } } [XmlIgnore] public bool IsFloat { get { switch (Type) { case CodeType.writefloat: case CodeType.addfloat: case CodeType.subfloat: case CodeType.mulfloat: case CodeType.divfloat: case CodeType.ifeqfloat: case CodeType.ifnefloat: case CodeType.ifltfloat: case CodeType.iflteqfloat: case CodeType.ifgtfloat: case CodeType.ifgteqfloat: case CodeType.addregfloat: case CodeType.subregfloat: case CodeType.mulregfloat: case CodeType.divregfloat: case CodeType.ifeqregfloat: case CodeType.ifneregfloat: case CodeType.ifltregfloat: case CodeType.iflteqregfloat: case CodeType.ifgtregfloat: case CodeType.ifgteqregfloat: return true; default: return false; } } } [XmlIgnore] public bool IsIf { get { return (Type >= CodeType.ifeq8 && Type <= CodeType.ifkbkey) || (Type >= CodeType.ifeqreg8 && Type <= CodeType.ifmaskreg32); } } [XmlIgnore] public bool IsReg { get { if (IsIf) { if (TrueLines.Any((line) => line.IsReg)) return true; if (FalseLines.Any((line) => line.IsReg)) return true; } if (Address.StartsWith("r")) return true; if (Type >= CodeType.readreg8 && Type <= CodeType.ifmaskreg32) return true; return false; } } } public enum CodeType { write8, write16, write32, writefloat, add8, add16, add32, addfloat, sub8, sub16, sub32, subfloat, mulu8, mulu16, mulu32, mulfloat, muls8, muls16, muls32, divu8, divu16, divu32, divfloat, divs8, divs16, divs32, modu8, modu16, modu32, mods8, mods16, mods32, shl8, shl16, shl32, shru8, shru16, shru32, shrs8, shrs16, shrs32, rol8, rol16, rol32, ror8, ror16, ror32, and8, and16, and32, or8, or16, or32, xor8, xor16, xor32, writenop, writejump, writecall, writeoff, ifeq8, ifeq16, ifeq32, ifeqfloat, ifne8, ifne16, ifne32, ifnefloat, ifltu8, ifltu16, ifltu32, ifltfloat, iflts8, iflts16, iflts32, ifltequ8, ifltequ16, ifltequ32, iflteqfloat, iflteqs8, iflteqs16, iflteqs32, ifgtu8, ifgtu16, ifgtu32, ifgtfloat, ifgts8, ifgts16, ifgts32, ifgtequ8, ifgtequ16, ifgtequ32, ifgteqfloat, ifgteqs8, ifgteqs16, ifgteqs32, ifmask8, ifmask16, ifmask32, ifkbkey, readreg8, readreg16, readreg32, writereg8, writereg16, writereg32, addreg8, addreg16, addreg32, addregfloat, subreg8, subreg16, subreg32, subregfloat, mulregu8, mulregu16, mulregu32, mulregfloat, mulregs8, mulregs16, mulregs32, divregu8, divregu16, divregu32, divregfloat, divregs8, divregs16, divregs32, modregu8, modregu16, modregu32, modregs8, modregs16, modregs32, shlreg8, shlreg16, shlreg32, shrregu8, shrregu16, shrregu32, shrregs8, shrregs16, shrregs32, rolreg8, rolreg16, rolreg32, rorreg8, rorreg16, rorreg32, andreg8, andreg16, andreg32, orreg8, orreg16, orreg32, xorreg8, xorreg16, xorreg32, writenopreg, ifeqreg8, ifeqreg16, ifeqreg32, ifeqregfloat, ifnereg8, ifnereg16, ifnereg32, ifneregfloat, ifltregu8, ifltregu16, ifltregu32, ifltregfloat, ifltregs8, ifltregs16, ifltregs32, iflteqregu8, iflteqregu16, iflteqregu32, iflteqregfloat, iflteqregs8, iflteqregs16, iflteqregs32, ifgtregu8, ifgtregu16, ifgtregu32, ifgtregfloat, ifgtregs8, ifgtregs16, ifgtregs32, ifgteqregu8, ifgteqregu16, ifgteqregu32, ifgteqregfloat, ifgteqregs8, ifgteqregs16, ifgteqregs32, ifmaskreg8, ifmaskreg16, ifmaskreg32, s8tos32, s16tos32, s32tofloat, u32tofloat, floattos32, floattou32, @else, endif, newregs } public enum ValueType { @decimal, hex } }
Java
UTF-8
802
3.140625
3
[]
no_license
package Random; import java.util.Random; public class Randomizer { public static Random theInstance = null; public Randomizer(){ } public static Random getInstance() { if(theInstance == null) { theInstance = new Random(); } return theInstance; } public static boolean nextBoolean() { return Randomizer.getInstance().nextBoolean(); } public static int nextInt() { return Randomizer.getInstance().nextInt(); } public static int nextInt(int n) { return Randomizer.getInstance().nextInt(n); } public static int nextInt(int min, int max) { return min + Randomizer.nextInt(max - min + 1); } }
Markdown
UTF-8
1,382
3.140625
3
[]
no_license
# CPSC353 ## Project 1 Text In Image Author: Thomas Ngo <br /> Instructor: Reza Nikoopour <br /> California University State, Fullerton ## Project Description The design of this program is divided into two main parts that are encode and decode. Following these main functions, there are also 3 helper functions that do the change of the last significant bit(LSB), conversion between text and binary and vice versa. The scripting language is python3. ## How to execute Make sure you change user permission to execute the program ``` $ chmod u+x project.py ``` ### To encode: <br /> Write the secret text/message on file.txt. Then, execute following commands ``` $ ./project.py -e <image> -r <file>.txt -o <output>.png ``` or ``` $ python3 project.py -e <image> -r <file>.txt -o <output>.png ``` ### To decode: ``` $ ./project.py -d <image>.png ``` or ``` $ python3 project.py -d <image>.png ``` ### Summary of the usage ``` usage: project.py [-h] (-d | -e) [-r READ] [-o OUTPUT] image Stegenography Project CPSC353 positional arguments: image location of the image optional arguments: -h, --help show this help message and exit -d, --decode decode on an image mode RGB -e, --encode encode on an image mode RGB -r READ, --read READ human-readable file -o OUTPUT, --output OUTPUT Name of output file ```
C++
UTF-8
1,321
2.765625
3
[]
no_license
#include <iostream> #include "sphere.h" #include "circle.h" #include "polygon.h" #include "reuleauxtriangle.h" #include "geom.h" #include "reuleauxtetrahedron.h" #include "cube.h" ReuleauxTetrahedron::ReuleauxTetrahedron(Point3D vertices[4]) { vertices_ = vertices; } int ReuleauxTetrahedron::vertexCount() { return 4; } Point3D ReuleauxTetrahedron::getVertex(int i) { if(i == 1) return vertices_[0]; else if(i == 2) return vertices_[1]; else if(i == 3) return vertices_[2]; else return vertices_[3]; } /* * If distance between centers is less than difference between the radius of containing * circle and the radius of this circle, this circle is not contained */ bool ReuleauxTetrahedron::containedWithin(Sphere &sphere) { return false; } /* * If circle intersects with any polygon edge, circle is not contained * If line between centers intersects with any polygon edge, circle is not contained * Only other possibility is that the circle is contained */ bool ReuleauxTetrahedron::containedWithin(Cube &cube) { return false; } //https://opencast-player-1.lt.ucsc.edu:8443/engage/theodul/ui/core.html?id=956436f9-b748-4ab7-b7b7-2e27605f1667 bool ReuleauxTetrahedron::containedWithin(ReuleauxTetrahedron &rt) { return false; }
Java
UTF-8
645
2.78125
3
[]
no_license
package com.codisimus.plugins.codsperms; /** * PermissionNode represents a Minecraft Permission node and it's value * * @author Codisimus */ public class PermissionNode { private final String name; private boolean value; public PermissionNode(String name) { this.name = name; value = true; } public PermissionNode(String name, boolean value) { this.name = name; this.value = value; } public String getName() { return name; } public boolean getValue() { return value; } public void setValue(boolean value) { this.value = value; } }
Java
UTF-8
543
2.5
2
[ "Apache-2.0" ]
permissive
package ru.job4j.homeworks.tasks; import org.junit.Test; import static org.hamcrest.Matchers.is; import static org.junit.Assert.*; public class Task1110Test { Task1110 test = new Task1110(); @Test public void whenPutANumberThenReturnItTurnedAndInArray() { assertThat(test.makeArray(23434), is(new int[]{4, 3, 4, 3, 2, 0})); } @Test public void whenPutANumberThenReturnItTurnedAndInArrayStringVercion() { assertThat(test.makeStringArray(423), is(new String[]{"3", "2", "4", "0", "0", "0"})); } }
Python
UTF-8
679
3.765625
4
[]
no_license
""" This solution is same as the first solution but did not use a helper function. """ class Node: def __init__(self, val=None, children=None): self.val = val self.children = children class Solution: def max_depth(self, root: "Node") -> int: # check if the node exist if not root: return 0 # set the max depth to 0 maximum = 0 # proceed to every child of the node and get the max depth if root.children: maximum = max(self.max_depth(child) for child in root.children) # return the max depth plus 1 (the current node) return maximum + 1
Java
UTF-8
6,292
1.773438
2
[]
no_license
/** * SYMGF * Derechos Reservados Mauricio Lopez Barba * Este software es propiedad de Mauricio Lopez Barba, y no puede ser * utilizado, distribuido, copiado sin autorizacion expresa por escrito. * * @author Mauricio Lopez Barba * @version 2013-10 */ package com.flexwm.client.op; import com.symgae.shared.BmFilter; import com.symgae.shared.BmObject; import com.symgae.shared.sf.BmoUser; import com.flexwm.shared.cm.BmoOpportunity; import com.flexwm.shared.op.BmoConsultancy; import com.google.gwt.user.client.ui.Panel; import com.symgae.client.ui.UiList; import com.symgae.client.ui.UiParams; import com.symgae.client.ui.UiSuggestBox; public class UiConsultancyActiveList extends UiList { BmoConsultancy bmoConsultancy; UiSuggestBox userSuggestBox; protected BmFilter userFilter = new BmFilter(); BmoUser bmoUser = new BmoUser(); public UiConsultancyActiveList(UiParams uiParams, Panel defaultPanel) { super(uiParams, defaultPanel, new BmoConsultancy()); bmoConsultancy = (BmoConsultancy)getBmObject(); super.titleLabel.setHTML(getSFParams().getProgramListTitle(getBmObject()) + " Activas"); } public UiConsultancyActiveList(UiParams uiParams, Panel defaultPanel, BmoUser bmoUser) { super(uiParams, defaultPanel, new BmoConsultancy()); bmoConsultancy = (BmoConsultancy)getBmObject(); this.bmoUser = bmoUser; super.titleLabel.setHTML(getSFParams().getProgramListTitle(getBmObject()) + " Activas"); // Elimina el filtro forzado, por ser llamado como SLAVE getUiParams().getUiProgramParams(getBmObject().getProgramCode()).removeForceFilter(); } @Override public void postShow() { // Filtro de Pedidos En Revision BmFilter revisionFilter = new BmFilter(); revisionFilter.setValueFilter(bmoConsultancy.getKind(), bmoConsultancy.getStatus(), "" + BmoOpportunity.STATUS_REVISION); getUiParams().getUiProgramParams(getBmObject().getProgramCode()).addFilter(revisionFilter); // // Preparar filtro default de usuario loggeado // BmoUser bmoUser = new BmoUser(); // BmFilter bmFilter = new BmFilter(); // userSuggestBox = new UiSuggestBox(new BmoUser()); // // if (getUiParams().getSFParams().restrictData(bmoOrder.getProgramCode()) == BmoSFComponentAccess.DISCLOSURE_ALL) { // bmFilter.setValueLabelFilter(bmoOrder.getKind(), // bmoOrder.getUserId().getName(), // bmoOrder.getUserId().getLabel(), // "=", // "" + getSFParams().getLoginInfo().getUserId(), // getSFParams().getLoginInfo().getEmailAddress()); // getUiParams().getUiProgramParams(bmoOrder.getProgramCode()).addFilter(bmFilter); // // // Filtrar por vendedores // BmoProfileUser bmoProfileUser = new BmoProfileUser(); // BmFilter filterSalesmen = new BmFilter(); // int salesGroupId = ((BmoFlexConfig)getUiParams().getSFParams().getBmoAppConfig()).getSalesProfileId().toInteger(); // filterSalesmen.setInFilter(bmoProfileUser.getKind(), // bmoUser.getIdFieldName(), // bmoProfileUser.getUserId().getName(), // bmoProfileUser.getProfileId().getName(), // "" + salesGroupId); // // userSuggestBox.addFilter(filterSalesmen); // // // Filtrar por vendedores activos // BmFilter filterSalesmenActive = new BmFilter(); // filterSalesmenActive.setValueFilter(bmoUser.getKind(), bmoUser.getStatus(), "" + BmoUser.STATUS_ACTIVE); // userSuggestBox.addFilter(filterSalesmenActive); // // addFilterSuggestBox(userSuggestBox, new BmoUser(), bmoOrder.getUserId()); // } else { // // Preparar filtro default de usuario loggeado // bmFilter.setValueLabelFilter(bmoOrder.getKind(), // bmoOrder.getUserId().getName(), // bmoOrder.getUserId().getLabel(), // "=", // "" + getSFParams().getLoginInfo().getUserId(), // getSFParams().getLoginInfo().getEmailAddress()); // getUiParams().getUiProgramParams(bmoOrder.getProgramCode()).addFilter(bmFilter); // } if (bmoUser.getId() > 0) { userFilter.setValueLabelFilter(bmoConsultancy.getKind(), bmoConsultancy.getUserId().getName(), bmoConsultancy.getUserId().getLabel(), BmFilter.EQUALS, bmoUser.getIdField().toString(), bmoUser.listBoxFieldsToString()); getUiParams().getUiProgramParams(getBmObject().getProgramCode()).addFilter(userFilter); } } @Override public void create() { UiConsultancy uiConsultancy = new UiConsultancy(getUiParams()); uiConsultancy.create(); } @Override public void open(BmObject bmObject) { bmoConsultancy = (BmoConsultancy)bmObject; getUiParams().setUiType(new BmoConsultancy().getProgramCode(), UiParams.MASTER); // Si esta asignado el tipo de proyecto, envia directo al dashboard if (bmoConsultancy.getWFlowTypeId().toInteger() > 0) { UiConsultancyDetail uiConsultancyDetail = new UiConsultancyDetail(getUiParams(), bmoConsultancy.getId()); uiConsultancyDetail.show(); } } // @Override // public void displayList() { // int col = 0; // // listFlexTable.addListTitleCell(0, col++, "Abrir"); // listFlexTable.addListTitleCell(0, col++, "Clave"); // listFlexTable.addListTitleCell(0, col++, "Nombre"); // listFlexTable.addListTitleCell(0, col++, "Cliente"); // listFlexTable.addListTitleCell(0, col++, "Fase"); // listFlexTable.addListTitleCell(0, col++, "Avance"); // // int row = 1; // while (iterator.hasNext()) { // // BmoOrder cellBmObject = (BmoOrder)iterator.next(); // // Image clickImage = new Image(GwtUtil.getProperUrl(getUiParams().getSFParams(), "/icons/edit.png")); // clickImage.setTitle("Abrir registro."); // clickImage.addClickHandler(rowClickHandler); // listFlexTable.setWidget(row, 0, clickImage); // listFlexTable.getCellFormatter().addStyleName(row, 0, "listCellLink"); // // col = 1; // listFlexTable.addListCell(row, col++, cellBmObject.getCode()); // listFlexTable.addListCell(row, col++, cellBmObject.getName()); // listFlexTable.addListCell(row, col++, cellBmObject.getBmoCustomer().getDisplayName()); // listFlexTable.addListCell(row, col++, cellBmObject.getBmoWFlow().getBmoWFlowPhase().getCode()); // listFlexTable.addListCell(row, col++, cellBmObject.getBmoWFlow().getProgress()); // listFlexTable.formatRow(row); // row++; // } // } }
C
UTF-8
281
3.03125
3
[]
no_license
/* used to change all characters in *s to lower case */ void locase(char *s); /* returns the size of the file indicated by *name */ int filesize(char *name); /* determines if the extension in *ext matches a lower case version *filename*/ int extMatch(char *filename, char *ext);
Java
UTF-8
4,136
2.8125
3
[]
no_license
package com.ekomera.gox.todoservice.database; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.ekomera.gox.todoservice.models.User; public final class UserDataBase { private static Connection connect = null; static { try { connect = DatabaseConnector.getConnection(); // ResultSet resultset=statement.executeQuery("select*from // todo_service_db.users"); // while (resultset.next()) { // // It is possible to get the columns via name // // also possible to get the columns via the column number // // which starts at 1 // // e.g. resultSet.getSTring(2); // String userid = resultset.getString("UserID"); // String username = resultset.getString("username"); // String password = resultset.getString("password"); // // System.out.println("User: " + userid); // System.out.println("name: " + username); // System.out.println("pass: " + password); // // } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void addNewUser(User user) { try { CallableStatement statement = connect.prepareCall("{Call add_new_user(?, ?, ?)}"); statement.setString(1, user.getId()); statement.setString(2, user.getName()); statement.setString(3, user.getPassword()); statement.execute(); statement.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static boolean removeUserWithId(String id) { boolean result = false; try { CallableStatement statement = connect.prepareCall("{Call remove_user_with_id(?)}"); statement.setString(1, id); statement.execute(); statement.close(); result=true; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return result; } public static boolean isUsernameValid(String username) { boolean result = false; try { CallableStatement statement = connect.prepareCall("{Call is_username_taken(?,?)}"); statement.setString(1, username); statement.registerOutParameter(2, java.sql.Types.CHAR); statement.execute(); if (statement.getString(2) != null && statement.getString(2).equals("1")) result = true; statement.close(); } catch (SQLException e) { e.printStackTrace(); } return result; } public static boolean isUserValidWithId(String id) { boolean result = false; try { CallableStatement statement = connect.prepareCall("{Call is_userid_taken(?,?)}"); statement.setString(1, id); statement.registerOutParameter(2, java.sql.Types.CHAR); statement.execute(); if (statement.getString(2) != null && statement.getString(2).equals("1")) result = true; statement.close(); } catch (SQLException e) { e.printStackTrace(); } return result; } public static User getUserWithId(String id) { User user = null; try { PreparedStatement statement = connect .prepareStatement("select*from todo_service_db.users where userid=? ;"); statement.setString(1, id); ResultSet resultset = statement.executeQuery(); if (resultset.next()) { user = new User(resultset.getString(2)); user.setId(id); user.setPassword(resultset.getString(3)); } statement.close(); } catch (SQLException e) { e.printStackTrace(); } return user; } public static User getUserWithUsername(String username) { User user = null; try { PreparedStatement statement = connect .prepareStatement("select*from todo_service_db.users where username=? ;"); statement.setString(1, username); ResultSet resultset = statement.executeQuery(); if (resultset.next()) { user = new User(resultset.getString(2)); user.setId(resultset.getString(1)); user.setPassword(resultset.getString(3)); } statement.close(); } catch (SQLException e) { e.printStackTrace(); } return user; } }
Python
UTF-8
1,472
2.96875
3
[ "MIT" ]
permissive
import tensorflow as tf import numpy as np tf.enable_eager_execution() width = 3 # 1.4031373262405396 total time for inital condition # 1.0077402591705322 best time def compute_ramp(y): g = tf.constant(9.8) dx = x[1] - x[0] # Fix the endpoints y = tf.concat([[1.0], y, [0.0]], axis=0) # Conservation of energy U=K, mgh=(1/2)mv**2 v = tf.sqrt(2 * g * (y[0] - y)) dy = y[:-1] - y[1:] avg_v = (v[1:] + v[:-1]) / 2 h = tf.sqrt(dx ** 2 + dy ** 2) total_time = tf.reduce_sum(h / avg_v) return total_time def train_step(y): with tf.GradientTape() as tape: time = compute_ramp(y) variables = [y] grads = tape.gradient(time, variables) optimizer.apply_gradients(zip(grads, variables)) return time.numpy() N = 500 n_steps = 5000 #y = np.linspace(0.5, 0.01, N) y = np.random.uniform(-1,0.5,size=(N,),) y = tf.Variable(y, dtype=tf.float32) x = tf.linspace(0.0, 1.0, N + 2) * width optimizer = tf.train.AdamOptimizer(learning_rate=0.01) print(f"Starting time {compute_ramp(y)}") import pylab as plt import seaborn as sns plt.figure(figsize=(7,4)) for i in range(n_steps): t = train_step(y) if i % 100 == 0 and i >= 200: print(f"{i} {t:0.16f}") yx = np.hstack([[1], y.numpy(), [0]]) plt.plot(x.numpy(), yx, color='b',alpha=i/n_steps) plt.plot(x.numpy(), yx,'r',lw=1) plt.plot(x.numpy(), 0*x.numpy(),'k',lw=2) sns.despine() plt.tight_layout() plt.show()
Python
UTF-8
950
3.796875
4
[]
no_license
import random user_action = input("Enter rock, paper, or scissors:") possible_actions = ["rock","paper","scissors"] computer_action = random.choice(possible_actions) lose_insult_list = ["wow u lost to a computer", "how r u gonna lost to a machine","stop losing"] win_insults = ["the computer let u win, you\'re welcome"] print(f"\nYou chose {user_action} and your opponent chose {computer_action}") if user_action == computer_action: print("its a tie") elif user_action == "rock": if computer_action == "paper": print(random.choice(lose_insult_list)) else: print(random.choice(win_insults)) elif user_action == "paper": if computer_action == "rock": print(random.choice(win_insults)) else: print(random.choice(lose_insult_list)) elif user_action == "scissors": if computer_action == "rock": print(random.choice(lose_insult_list)) else: print(random.choice(win_insults))
Python
UTF-8
437
2.71875
3
[]
no_license
#!/usr/bin/python #coding=utf-8 # from random import * import random # l = [] # i = 0 # # while i <= 5: # i += 1 # b = random.randint(1, 33) # print b # l.append(b) # print l # l.sort() # a = random.randint(1,16) # l.append(a) # print l #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ l = random.sample(range(1,34),6) l.sort() # l.append(random.randint(1,17)) # print l print l, random.randint(1,16)
Java
UTF-8
569
2.59375
3
[ "Apache-2.0" ]
permissive
package net.carti.participants; import org.junit.Test; /** * Add Description HERE * * @author Mihai Matache mihmatache@luxoft.com * @since 10/1/2019 */ public class DealerTests { //Static variables //Instance variables //Constructors //Methods @Test public void shuffleTest(){ Dealer dealer = new Dealer("Mimi"); dealer.giveCards().forEach(System.out::println); dealer.shuffle(); System.out.println("################### Shuffled cards ##################"); dealer.giveCards().forEach(System.out::println); } }
Java
UTF-8
1,580
2.078125
2
[]
no_license
package com.acmvit.acm_app.ui.invites; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import com.acmvit.acm_app.R; import com.acmvit.acm_app.databinding.FragmentEventsBinding; import com.acmvit.acm_app.ui.invites.adapters.EventsPageAdapter; import com.google.android.material.tabs.TabLayout; import com.google.android.material.tabs.TabLayoutMediator; public class EventsFragment extends Fragment { private FragmentEventsBinding binding; private static final String[] TAB_TEXT = { "Notifications", "Requests" }; @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState ) { binding = FragmentEventsBinding.inflate(inflater, container, false); return binding.getRoot(); } @Override public void onViewCreated( @NonNull View view, @Nullable Bundle savedInstanceState ) { super.onViewCreated(view, savedInstanceState); setupViewPager(); } private void setupViewPager() { EventsPageAdapter adapter = new EventsPageAdapter(this); binding.eventViewpager.setAdapter(adapter); new TabLayoutMediator( binding.eventsTabLayout, binding.eventViewpager, (tab, position) -> { tab.setText(TAB_TEXT[position]); } ) .attach(); } }
Java
UTF-8
7,731
1.945313
2
[ "Apache-2.0" ]
permissive
package net.mgsx.gltf.scene3d.shaders; import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Texture.TextureFilter; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.g3d.Renderable; import com.badlogic.gdx.graphics.g3d.Shader; import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute; import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute; import com.badlogic.gdx.graphics.g3d.shaders.DefaultShader; import com.badlogic.gdx.graphics.g3d.utils.DefaultShaderProvider; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.utils.GdxRuntimeException; import net.mgsx.gltf.scene3d.attributes.PBRCubemapAttribute; import net.mgsx.gltf.scene3d.attributes.PBRFlagAttribute; import net.mgsx.gltf.scene3d.attributes.PBRTextureAttribute; import net.mgsx.gltf.scene3d.shaders.PBRShaderConfig.SRGB; public class PBRShaderProvider extends DefaultShaderProvider { public static PBRShaderProvider createDefault(int maxBones){ PBRShaderConfig config = new PBRShaderConfig(); config.numBones = maxBones; return createDefault(config); } public static PBRShaderProvider createDefault(PBRShaderConfig config){ String mode = "gdx-pbr"; config.vertexShader = Gdx.files.classpath("net/mgsx/gltf/shaders/" + mode + ".vs.glsl").readString(); config.fragmentShader = Gdx.files.classpath("net/mgsx/gltf/shaders/" + mode + ".fs.glsl").readString(); return new PBRShaderProvider(config); } public PBRShaderProvider(PBRShaderConfig config) { super(config); } public int getShaderCount(){ return shaders.size; } protected Shader createShader(Renderable renderable) { PBRShaderConfig config = (PBRShaderConfig)this.config; String prefix = DefaultShader.createPrefix(renderable, config); String version = config.glslVersion; final boolean openGL3 = Gdx.graphics.getGLVersion().isVersionEqualToOrHigher(3, 0); if(openGL3){ if(Gdx.app.getType() == ApplicationType.Desktop){ if(version == null) version = "#version 130\n" + "#define GLSL3\n"; }else if(Gdx.app.getType() == ApplicationType.Android){ if(version == null) version = "#version 300 es\n" + "#define GLSL3\n"; } } if(version != null){ prefix = version + prefix; } if(Gdx.app.getType() == ApplicationType.WebGL || !openGL3){ prefix += "#define USE_DERIVATIVES_EXT\n"; } for(VertexAttribute att : renderable.meshPart.mesh.getVertexAttributes()){ for(int i=0 ; i<8 ; i++){ if(att.alias.equals(ShaderProgram.POSITION_ATTRIBUTE + i)){ prefix += "#define " + "position" + i + "Flag\n"; }else if(att.alias.equals(ShaderProgram.NORMAL_ATTRIBUTE + i)){ prefix += "#define " + "normal" + i + "Flag\n"; }else if(att.alias.equals(ShaderProgram.TANGENT_ATTRIBUTE + i)){ prefix += "#define " + "tangent" + i + "Flag\n"; } } } // Lighting if(renderable.material.has(PBRFlagAttribute.Unlit)){ prefix += "#define unlitFlag\n"; }else{ if(renderable.material.has(PBRTextureAttribute.MetallicRoughnessTexture)){ prefix += "#define metallicRoughnessTextureFlag\n"; } if(renderable.material.has(PBRTextureAttribute.OcclusionTexture)){ prefix += "#define occlusionTextureFlag\n"; } // IBL options PBRCubemapAttribute specualarCubemapAttribute = null; if(renderable.environment.has(PBRCubemapAttribute.SpecularEnv)){ prefix += "#define diffuseSpecularEnvSeparateFlag\n"; specualarCubemapAttribute = renderable.environment.get(PBRCubemapAttribute.class, PBRCubemapAttribute.SpecularEnv); }else if(renderable.environment.has(PBRCubemapAttribute.DiffuseEnv)){ specualarCubemapAttribute = renderable.environment.get(PBRCubemapAttribute.class, PBRCubemapAttribute.DiffuseEnv); }else if(renderable.environment.has(PBRCubemapAttribute.EnvironmentMap)){ specualarCubemapAttribute = renderable.environment.get(PBRCubemapAttribute.class, PBRCubemapAttribute.EnvironmentMap); } if(specualarCubemapAttribute != null){ prefix += "#define USE_IBL\n"; boolean textureLodSupported; if(Gdx.app.getType() == ApplicationType.WebGL){ textureLodSupported = Gdx.graphics.supportsExtension("EXT_shader_texture_lod"); }else if(Gdx.app.getType() == ApplicationType.Android){ if(openGL3){ textureLodSupported = true; }else if(Gdx.graphics.supportsExtension("EXT_shader_texture_lod")){ prefix += "#define USE_TEXTURE_LOD_EXT\n"; textureLodSupported = true; }else{ textureLodSupported = false; } }else{ textureLodSupported = true; } TextureFilter textureFilter = specualarCubemapAttribute.textureDescription.minFilter != null ? specualarCubemapAttribute.textureDescription.minFilter : specualarCubemapAttribute.textureDescription.texture.getMinFilter(); if(textureLodSupported && textureFilter.equals(TextureFilter.MipMap)){ prefix += "#define USE_TEX_LOD\n"; } if(renderable.environment.has(PBRTextureAttribute.BRDFLUTTexture)){ prefix += "#define brdfLUTTexture\n"; } } // TODO check GLSL extension 'OES_standard_derivatives' for WebGL // TODO check GLSL extension 'EXT_SRGB' for WebGL if(renderable.environment.has(ColorAttribute.AmbientLight)){ prefix += "#define ambientLightFlag\n"; } // SRGB if(config.manualSRGB != SRGB.NONE){ prefix += "#define MANUAL_SRGB\n"; if(config.manualSRGB == SRGB.FAST){ prefix += "#define SRGB_FAST_APPROXIMATION\n"; } } } // DEBUG if(config.debug){ prefix += "#define DEBUG\n"; } // multi UVs int maxUVIndex = 0; { TextureAttribute attribute = renderable.material.get(TextureAttribute.class, TextureAttribute.Diffuse); if(attribute != null){ prefix += "#define v_diffuseUV v_texCoord" + attribute.uvIndex + "\n"; maxUVIndex = Math.max(maxUVIndex, attribute.uvIndex); } } { TextureAttribute attribute = renderable.material.get(TextureAttribute.class, TextureAttribute.Emissive); if(attribute != null){ prefix += "#define v_emissiveUV v_texCoord" + attribute.uvIndex + "\n"; maxUVIndex = Math.max(maxUVIndex, attribute.uvIndex); } } { TextureAttribute attribute = renderable.material.get(TextureAttribute.class, TextureAttribute.Normal); if(attribute != null){ prefix += "#define v_normalUV v_texCoord" + attribute.uvIndex + "\n"; maxUVIndex = Math.max(maxUVIndex, attribute.uvIndex); } } { TextureAttribute attribute = renderable.material.get(TextureAttribute.class, PBRTextureAttribute.MetallicRoughnessTexture); if(attribute != null){ prefix += "#define v_metallicRoughnessUV v_texCoord" + attribute.uvIndex + "\n"; maxUVIndex = Math.max(maxUVIndex, attribute.uvIndex); } } { TextureAttribute attribute = renderable.material.get(TextureAttribute.class, PBRTextureAttribute.OcclusionTexture); if(attribute != null){ prefix += "#define v_occlusionUV v_texCoord" + attribute.uvIndex + "\n"; maxUVIndex = Math.max(maxUVIndex, attribute.uvIndex); } } if(maxUVIndex >= 0){ prefix += "#define textureFlag\n"; } if(maxUVIndex == 1){ prefix += "#define textureCoord1Flag\n"; }else if(maxUVIndex > 1){ throw new GdxRuntimeException("multi UVs > 1 not supported"); } PBRShader shader = new PBRShader(renderable, config, prefix); String shaderLog = shader.program.getLog(); Gdx.app.log("Shader compilation", shaderLog.isEmpty() ? "success" : shaderLog); // prevent infinite loop if(!shader.canRender(renderable)){ throw new GdxRuntimeException("cannot render with this shader"); } return shader; }; }
Python
UTF-8
1,573
2.5625
3
[]
no_license
# Adapted from https://github.com/PyTorchLightning/pytorch-lightning/blob/master/pl_examples/basic_examples/mnist.py import torch import pytorch_lightning as pl from torch.nn import functional as F from torch.utils.data import DataLoader, random_split try: from torchvision.datasets.mnist import MNIST from torchvision import transforms except Exception as e: from tests.base.datasets import MNIST class SimpleClassifier(pl.LightningModule): def __init__(self, **hparams): super().__init__() self.hparams = hparams self.save_hyperparameters() self.l1 = torch.nn.Linear(28 * 28, self.hparams.hidden_dim) self.l2 = torch.nn.Linear(self.hparams.hidden_dim, 10) def forward(self, x): x = x.view(x.size(0), -1) x = torch.relu(self.l1(x)) x = torch.relu(self.l2(x)) return x def training_step(self, batch, batch_idx): x, y = batch y_hat = self(x) loss = F.cross_entropy(y_hat, y) self.log('train_loss', loss, on_step=True, on_epoch=True, prog_bar=True, logger=True) return loss def validation_step(self, batch, batch_idx): x, y = batch y_hat = self(x) loss = F.cross_entropy(y_hat, y) self.log('valid_loss', loss) def test_step(self, batch, batch_idx): x, y = batch y_hat = self(x) loss = F.cross_entropy(y_hat, y) self.log('test_loss', loss) def configure_optimizers(self): return torch.optim.Adam(self.parameters(), lr=self.hparams.learning_rate)
Java
UTF-8
658
2.3125
2
[]
no_license
package com.webjjang.board.service; import java.util.List; import com.webjjang.board.dao.BoardDAO; import com.webjjang.board.dto.BoardDTO; import com.webjjang.main.Service; public class BoardListService implements Service{ private BoardDAO dao; public BoardListService(BoardDAO dao) { this.dao = dao; } public List<BoardDTO> service(Object[] objs) throws Exception{ // 데이터 처리부분에 해당된다. System.out.println("BoardListService.service()"); // 데이터를 오라클에서 가져오기 위해서 객체를 생성하고 호출한다. // BoardController - BoardListService - [BoardDAO] return dao.list(); } }