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
Markdown
UTF-8
3,681
2.828125
3
[]
no_license
--- title: ci 自动部署 date: 2017-10-31T07:44:00.000Z tags: - ci - docker - deploy lastmod: 2017-10-31T07:44:00.000Z categories: - deploy slug: ci-auto-deploy draft: false --- ## 前言 很久没写博文了,最近正好公司内部需要进行 ci 自动部署,就写一篇 ci 自动部署。其中分为两种,公开项目,私有项目 <!--more--> ## 一、自动部署原理 现在的 git 自动部署都是通过推送钩子,触发第三方 ci 执行脚本,然后在脚本中进行部署。 1. git push 2. 触发 git hooks 去调用 ci 3. ci 执行 shell,自动拉取代码,build,部署 但是这样会缺少每次更新的代码,无法做到回滚。 所以正常的做法是每次 ci 执行更新时做一个打包当前代码,并存到一个地方。 现在有了另一种做法,那就是直接打包 docker 镜像,通过私有或者公开 docker 仓库保存 1. git push 2. 触发 git hooks 去调用 ci 3. ci 执行 shell,自动拉取代码,build,打包 docker,推送 docker 镜像部署 这样的好处就是完全保证,代码,环境一致,并能快速回滚 ## 二、ci ci(Continuous integration)的中文是持续集成,常用于自动测试。 在每次提交代码时自动的执行项目中的测试用例。 这里我公司内部使用的`gitlab`所以直接使用内置的 ci `.gitlab-ci.yml` ```yaml image: xxxx:latest # gitlab-ci支持自定义docker镜像 variables: DOCKER_DRIVER: overlay BUILD_TAG: 0.1.0 # 设置下面shell环境中的变量 stages: - build_test build_test: stage: build_test only: - ci # 只在ci分支变化时触发 script: - cnpm install - npm run build # 编译 - npm run test # 测试 ``` 除了需要自己部署的私有 ci:`gitlab-ci` 常见的公开的有`travis-ci`,`circle-ci`,`appveyor`,一般都为私有项目收费,开源项目免费。 然后 ci 的环境一般都是`docker`的,然后执行的命令都是`shell`,所以实际上就是编写一个一键部署脚本。 ```yaml image: xxxx:latest # gitlab-ci支持自定义docker镜像 variables: DOCKER_DRIVER: overlay BUILD_TAG: 0.1.0 # 设置下面shell环境中的变量 stages: - build_test build_test: stage: build_test only: - ci # 只在ci分支变化时触发 script: - cnpm install - npm run build # 编译 - npm run test # 测试 - tar -Jcf dist.tar.xz dist - scp dist.tar.xz xxxx@xxx:~/ - ssh xxxx@xxx - cd ~ && tar -xf dist.tar.xz && cp -R ./dist/* /data/www/ - systemctl reload nginx # docker restart xxx - exit ``` 以上是一个自动部署脚本的`ci`示例,但是以上要正常的跑起来需要`open-ssh`,以及连接部署机的 ssh 密钥。 但是这里有一个问题,`ssh`密钥必须在`ci`环境中,而`ci`环境每次运行都会重置,如果写在代码中就暴露的部署机的密钥。 如果`ci`和代码仓库都是私有的那倒是没问题,但是使用`github` + `travis-ci`明显都是公开的。 `travis-ci` 提供了一个后台来配置私有变量和文件。 我公司的做法是使用一个内网`docker`仓库来存放要部署的代码,然后通知`Rancher`管理的内网部署机更新镜像,并运行。 然后把内网的镜像推送到外网手动的操作`Rancher`更新, 其中代码的数据库配置使用`ZooKeeper`获取,切换`ZooKeeper`节点通过环境变量。 ![ci-auto-docker-flow](/public/img/ci-auto-deploy/ci-auto-docker-flow.svg) 以上使用`GitLab` + `GitLab-ci` + `Harbor` + `Rancher` + `ZooKeeper` 感觉有点多。
Java
UTF-8
3,151
3.0625
3
[]
no_license
import java.awt.Color; import java.util.*; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.WindowConstants; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.XYPlot; import org.jfree.data.xy.XYDataset; import org.jfree.data.xy.XYSeries; import org.jfree.data.xy.XYSeriesCollection; import org.jfree.data.xy.XYZDataset; /** * @author Isiah Abad and Chad Crum * * The Plot class plots the List Entries into a Scatter Plot for the user to see. */ @SuppressWarnings("serial") public class Plot extends JFrame { protected LinkedList<ListEntry> entries = new LinkedList<ListEntry>(); /** * @param entries * * is the linked list of names, ID's, programs, asurite, * and levels of each students in the roster, and * is stored within a temp linked list. */ void plotNow(LinkedList<ListEntry> temp) { XYDataset dataset = makePlot(temp); JFreeChart chart = ChartFactory.createScatterPlot( "Student Attendance", "Attendance %", "Count", dataset); XYPlot plot = (XYPlot)chart.getPlot(); plot.setBackgroundPaint(new Color(255,228,196)); ChartPanel panel = new ChartPanel(chart); setContentPane(panel); plotEverything(); } /** * plotEverything will plot and display * all the extracted data points when * Plot Data button is selected. */ private void plotEverything() { SwingUtilities.invokeLater(() -> { setTitle("CSE 360 Final Project"); setSize(800, 400); setLocationRelativeTo(null); setVisible(true); }); } /** * @param temp is the list of student data * * The makePlot function will create * the scatter plot using a series of * data points. * * @return dataset is the XYSeries collection of times */ private XYDataset makePlot(LinkedList<ListEntry> temp) { entries = temp; XYSeriesCollection dataset = new XYSeriesCollection(); int dateCount = entries.get(0).getNumDates(); double percentage = 0; String date; LinkedList<XYSeries> seriesList = new LinkedList<XYSeries>(); int[] percents = new int[21]; for(int ind = 0; ind < dateCount; ind++) { date = entries.get(0).dates.get(ind); XYSeries ser = new XYSeries(date); seriesList.add(ser); for(int pos = 0; pos < 21; pos++) percents[pos] = 0; for(int jnd = 0; jnd < entries.size(); jnd++) { if(Double.parseDouble(entries.get(jnd).getTime(date)) >= 75) { percentage = 100; } else { percentage = ((Double.parseDouble(entries.get(jnd).getTime(date)))/75.00) * 100.00; } int loc = ((int)percentage) / 5; int val = percents[loc]; percents[loc] = val + 1; } for(int loc = 0; loc < 21; loc++) { if(percents[loc] != 0) seriesList.get(ind).add(loc * 5, percents[loc]); } dataset.addSeries(seriesList.get(ind)); } return dataset; } }
JavaScript
UTF-8
1,275
2.8125
3
[]
no_license
var assert = require("assert"); var ReviewProcess = require("../processes/review"); var MembershipApplication = require("../membership_application"); var moment = require("moment"); //MomentJS module describe("The review process test", function(){ describe("Receiving a valid application", function(){ //Application decision: var decision, validApp; //Arrange the data before the test //Before state: done => marks it as async test before(function(done){ //Create a valid applicant validApp = new MembershipApplication({ first: "Test", last: "User", email: this.first + "@" + this.last + ".com", age: 30, height: 66, weight: 180, validUntil: moment().add(10, 'days') }); //Process the application and get the result var review = new ReviewProcess(); review.processApplication(validApp, function(err, result){ decision = result; done(); }); }); //Assertion it("return success", function(){ assert(decision.success, decision.message); }); }); });
Java
UTF-8
479
2.546875
3
[]
no_license
package jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class _ConnectToDatabase { public static void main(String[] args) { try { Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databank", "root", "root"); try { /** * Do whatever you want here */ } finally { conn.close(); } } catch (SQLException e1) { e1.printStackTrace(); } } }
C#
UTF-8
943
3.015625
3
[]
no_license
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; namespace Planzy.Models.Util { class MyConverter : IValueConverter { public const string RED_COLOR = "#FFE05050"; public const string WHITE_COLOR = "#FFFFFF"; public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { switch (value.ToString().ToLower()) { case "false": return WHITE_COLOR; default: return RED_COLOR; } } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (value.ToString() == RED_COLOR) return true; else return false; } } }
Go
UTF-8
610
3.109375
3
[]
no_license
package main func numIslands(grid [][]byte) int { num := 0 for rowIndex, row := range grid { for colIndex := range row { if grid[rowIndex][colIndex] == '1' { num++ dfs(rowIndex, colIndex, grid) } } } return num } func dfs(rowIndex, colIndex int, grid [][]byte) { if rowIndex < 0 || colIndex < 0 || rowIndex >= len(grid) || colIndex >= len(grid[rowIndex]) { return } if grid[rowIndex][colIndex] != '1' { return } grid[rowIndex][colIndex] = '0' dfs(rowIndex+1, colIndex, grid) dfs(rowIndex-1, colIndex, grid) dfs(rowIndex, colIndex+1, grid) dfs(rowIndex, colIndex-1, grid) }
Python
UTF-8
440
2.78125
3
[]
no_license
import sys sys.path.append('../') import map_object class Tower(map_object.Map_Object): def _init_(self): self.damage = 0 self.range = 0 self.position = [0,0] #GET AND SET METHODS def setDamage(self, nDamage): self.damage = nDamage def getDamage(self): return self.damage def setRange(self, nRange): self.range = nRange def getRange(self): return self.range
Python
UTF-8
814
3.65625
4
[]
no_license
class student: '''documentation''' totalStd = 0 # class attribute #constructor def __init__(self,name,marks=0): self.name = name #object attributes self.__marks = marks #private object attribute student.totalStd += 1 #class methods def calculateGrade(self): if self.__marks > 80: return 'A' if self.__marks > 60: return 'B' if self.__marks > 40: return 'C' return 'D' #static method @staticmethod def getTotalStudents(): return student.totalStd a = student('ankur') b = student('ankur',88) a.totalStd=10 print(a.totalStd) # 10 print(student.getTotalStudents()) # 2 print(a.calculateGrade()) # D print(b.calculateGrade()) # A
C++
UTF-8
3,489
2.9375
3
[]
no_license
// (c) Michael Schoeffler 2018, http://www.mschoeffler.de #include <SoftwareSerial.h> const int BUFFER_SIZE = 14; // RFID DATA FRAME FORMAT: 1byte head (value: 2), 10byte data (2byte version + 8byte tag), 2byte checksum, 1byte tail (value: 3) const int DATA_SIZE = 10; // 10byte data (2byte version + 8byte tag) const int DATA_VERSION_SIZE = 2; // 2byte version (actual meaning of these two bytes may vary) const int DATA_TAG_SIZE = 8; // 8byte tag const int CHECKSUM_SIZE = 2; // 2byte checksum long currentTag = ""; const int reset = 2; // the number of the pushbutton pin const int swap = 3; // the number of the pushbutton pin int counter = 0; int swapState = 0; SoftwareSerial ssrfid = SoftwareSerial(6, 8); uint8_t buffer[BUFFER_SIZE]; // used to store an incoming data frame int buffer_index = 0; bool doneReading = false; void setup() { pinMode(reset, INPUT); pinMode(swap, INPUT); Serial.begin(9600); ssrfid.begin(9600); ssrfid.listen(); } void loop() { swapState = digitalRead(swap); readTags(); // check if the pushbutton is pressed. If it is, the buttonState is HIGH: if ( digitalRead(reset) == HIGH) { // turn LED on: counter = 0; } } void readTags() { if (ssrfid.available() > 0) { bool call_extract_tag = false; int ssvalue = ssrfid.read(); // read if (ssvalue == -1) { // no data was read return; } if (ssvalue == 2) { // RDM630/RDM6300 found a tag => tag incoming buffer_index = 0; } else if (ssvalue == 3) { // tag has been fully transmitted call_extract_tag = true; // extract tag at the end of the function call } if (buffer_index >= BUFFER_SIZE) { // checking for a buffer overflow (It's very unlikely that an buffer overflow comes up!) Serial.println("Error: Buffer overflow detected!"); return; } buffer[buffer_index++] = ssvalue; // everything is alright => copy current value to buffer if (call_extract_tag == true) { if (buffer_index == BUFFER_SIZE) { unsigned tag = extract_tag(); } else { // something is wrong... start again looking for preamble (value: 2) buffer_index = 0; return; } } } } unsigned extract_tag() { uint8_t msg_head = buffer[0]; uint8_t *msg_data = buffer + 1; // 10 byte => data contains 2byte version + 8byte tag uint8_t *msg_data_version = msg_data; uint8_t *msg_data_tag = msg_data + 2; uint8_t *msg_checksum = buffer + 11; // 2 byte uint8_t msg_tail = buffer[13]; long tag = hexstr_to_value(msg_data_tag, DATA_TAG_SIZE); if (tag == currentTag && doneReading == false) { return; } String dataString = ""; if (counter < 4) { dataString = "add:"; counter++; } else if (swapState == HIGH) { dataString = "swap:"; doneReading = true; } else { dataString = "sequence:"; doneReading = true; } currentTag = tag; dataString += currentTag; Serial.println(dataString); return tag; } long hexstr_to_value(char *str, unsigned int length) { // converts a hexadecimal value (encoded as ASCII string) to a numeric value char* copy = malloc((sizeof(char) * length) + 1); memcpy(copy, str, sizeof(char) * length); copy[length] = '\0'; // the variable "copy" is a copy of the parameter "str". "copy" has an additional '\0' element to make sure that "str" is null-terminated. long value = strtol(copy, NULL, 16); // strtol converts a null-terminated string to a long value free(copy); // clean up return value; }
Markdown
UTF-8
4,932
3.0625
3
[]
no_license
--- title: "Re-streaming video to a multicast address with VLC" excerpt: "How to stream just about anything to a multicast address using VLC" --- [VLC](https://www.videolan.org) is such a powerful tool. Excuse my ignorance but I have always seen it as just a media player that can play anything I throw at it. But it is capable of so much more! Ever since coming across [dvblast](https://www.videolan.org/projects/dvblast.html), which turns out to be a VLC project, I’ve started asking myself how other content could be multicasted over an IP network. Take the [ABC News](https://www.abc.net.au/news/newschannel/) television stream from Australia as an example. Is it possible to re-stream this to a multicast group? The answer is yes and VLC is the tool to use. ## Find the stream link The first thing to do is to find the streaming link. There are two ways to go about doing this; the easy way and the slightly more difficult way where you may have to get creative. However, the latter method is the one that will always yield a result. First, open the source code of the page (In Chrome, CMD + OPTION U on a Mac, or CTRL + U on Windows and Linux). Search for “m3u8”. If something comes up then great! The ABC News stream happens to have this hidden in the source code. However, not all streaming sites will do this. ![ABC Stream URL]({{ site.url }}{{ site.baseurl }}/assets/images/posts/2019/abc-stream-url.png) My preference is to use this second method as the m3u8 file will often point to the specific stream quality. Rather than opening the source code, load the page and where possible, do not play the stream yet. Open the Developer Tools and click on the Network tab (In Chrome, CMD + OPTION + I on Mac, or CTRL + SHIFT + I on Windows and Linux). Here’s where you need to get a little creative and know what to look for. What I tend to do is press the clear button, quickly start and pause the stream and look for “index.m3u8” or “master.m3u8” files. In the case of the ABC News Channel, the index.m3u8 file is actually loaded into the page before the video is played. If you mess around with changing the quality, you will find that the index_1.m3u8 file is the one that references the 576p quality stream. Right click on this, select copy and copy link address. ![Stream Developer Tools]({{ site.url }}{{ site.baseurl }}/assets/images/posts/2019/stream-developer-tools.png) Now that we have the stream URL you should test that this is in fact the network stream by using VLC. Go to Media, Open Network Stream, paste the URL and click Play. If your video starts, then you are good to go onto the next steps. Otherwise you will need to keep looking for the stream link. ## Streaming to multicast with VLC This can be done in two ways - through the GUI or using the command line. ### GUI I start the stream with the GUI so that I know the parameters to issue to the command line - Media > Stream - Click on the Network Tab (as you can see from the other tabs, VLC can also stream a file, disc, or capture device such as a TV tuner) - Paste the URL and click Stream - Click Next - Select RTP/MPEG Transport Stream from the dropdown and click Add - Enter your multicast address and port (e.g 239.255.0.1, 10000) and click Next - Select your Transcoding Profile. I uncheck this as I don’t want to transcode into another format - Make sure Stream all elementary streams is unchecked and click stream. Here you will notice that a generated stream output string is shown. This is very useful when writing out the command line version of this ![VLC Output String]({{ site.url }}{{ site.baseurl }}/assets/images/posts/2019/vlc-stream-output-string.png) Your video will now be streaming to the multicast group you specified. You can open it in VLC on another computer through Media > Open Network Stream. Enter your multicast address (e.g. rtp://239.255.0.1:10000) and click play. ### Command Line On a Linux machine, you can run VLC through the command line. This is useful if you want to run the stream from a central server that you will not be viewing the video from. You can install vlc-nox which is basically VLC without the GUI. With a slight modification to the stream output string in the image above, we can run the same stream created through the GUI in the command line instead. {% highlight bash %} # Install VLC without a GUI ~]$ sudo apt install vlc-nox # Send stream to multicast group ~]$ vlc <stream_url> '#rtp{dst=10.24.5.240,port=10000,mux=ts}' --no-sout-all --sout-keep {% endhighlight %} The video will now begin multicasting to your group. You can open it through Media > Open Network Stream. Enter your multicast address (e.g. rtp://239.255.0.1:10000) and click play. ## References [VLC - Streaming HowTo/Advanced Streaming Using the Command Line](https://wiki.videolan.org/Documentation:Streaming_HowTo/Advanced_Streaming_Using_the_Command_Line/#rtp)
Python
UTF-8
1,358
2.8125
3
[]
no_license
#read the data into dict from one source #read the other source while comparing similarity #1- check if we have the same #if yes do nothing, join the records #if no: #check the similarity (word by word similarity should be good) #if high -> match and join #if low -> create another record import Levenshtein import csv import fuzzy_matcher as fuzz filepaths=["Elsevier_all/elsevier0_sheet1.csv", "CoreAuto/Core0_sheetLatest2.csv", "Scimagojr_all/scimagojr2016_sheet0.csv"] dict={} def check_and_add(dictionary, data): #d is dict if (data in dictionary): dictionary[data]+=1 elif check_similarity(dictionary, data): print "Similar pair found: "+data else: dict[data]=1 def check_similarity(dictionary, data): for record in dictionary: if Levenshtein.ratio(record, data)>0.7: return fuzz.is_ci_token_stopword_match(record, data) for filename in filepaths: with open (filename, 'r') as csvinput: reader=csv.reader(csvinput, delimiter="\t") for row in reader: if len(row)>1: check_and_add(dict, row[1])
JavaScript
UTF-8
369
2.734375
3
[]
no_license
/** * created by wangyingchang 2019/11/10 * @param {*} date */ function date2String(date) { const year = date.getFullYear(); const month = date.getMonth() + 1; const day = date.getDate(); const hour = date.getHours(); const seconds = date.getSeconds(); return year + '-' + month + '-' + day + ' ' + hour + ':' + seconds } export default date2String;
Java
UHC
4,188
3.796875
4
[]
no_license
package hamilton; //2015112232 public class hamilton { public static void combination(int[][] matrix, int row, String[] array) { // ϱ int count = 1; // return String s = array[row];// ó ڸ for (int i = 0; i < matrix.length; i++) { if (matrix[row][i] != 0) { // Ǵ ڸ subcombination(matrix, i, array, s, count + 1); } } } public static void subcombination(int[][] matrix, int row, String[] array, String s, int count) { // ϴ Լ if (count == matrix.length) { // row s = s + array[row].substring(array[0].length() - 1); if (Iscorrect(array, s)) { // ߺ ִ üũ System.out.println(s); // ϰ } } else { s = s + array[row].substring(array[0].length() - 1); // ڸ ش. for (int i = 0; i < matrix.length; i++) { if ((matrix[row][i] != 0)) { // Ǵ ߰ subcombination(matrix, i, array, s, count + 1); } } } } public static boolean Iscorrect(String[] array, String s) { // ڿ ߺڰ Ȯ int n = array.length; String[] s_array = new String[n]; boolean[] check = new boolean[n]; for (int i = 0; i < n; i++) { // ߺüũ ʱȭ check[i] = false; } for (int i = 0; i < n; i++) { s_array[i] = s.substring(i, i + array[0].length()); // s ڿ spectrumó ڸ. } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (array[i].equals(s_array[j]) && (check[i] == false)) { // üũ ȵǾְ ִ° ȮεǸ check[i] = true; // Ǿٰ üũ } } } for (int i = 0; i < n; i++) { if (check[i] == false) { // ϳ ȵȰ ȮεǸ return false; // ڿ Ʋ } } return true; // s array ڿ } public static void spectrum(String[] s) { // ع path ذϱ int n = s.length; int[][] matrix = new int[n][n]; int l = s[0].length(); // ع path // ڱ ڽ ƴ϶ Ͽ 1~l ڰ 0~l-1ڿ ٸ ε Է for (int row = 0; row < n; row++) { for (int column = 0; column < n; column++) { if (s[row].substring(1).equals(s[column].substring(0, l - 1)) && (row != column)) { matrix[row][column] = 1; } else { matrix[row][column] = 0; } } } // for (int i = 0; i < n; i++) { // matrix // for (int j = 0; j < n; j++) { // System.out.print(String.format("%3d", matrix[i][j])); // } // System.out.println(""); // } for (int i = 0; i < n; i++) { // غ combination(matrix, i, s); } } public static void main(String[] args) { String[] array1 = { "AGT", "AAA", "ACT", "AAC", "CTT", "GTA", "TTT", "TAA" }; String[] array2 = { "ATG", "AGG", "TGC", "TCC", "GTC", "GGT", "GCA", "CAG" }; String[] array3 = { "ATG", "TGG", "TGC", "GTG", "GGC", "GCA", "GCG", "CGT" }; String[] array4 = { "ATGC", "TGCG", "GCGG", "CGGC", "GGCT", "GCTG", "CTGT", "TGTA", "GTAT", "TATG", "ATGG", "TGGT", "GGTG" }; String[] array5 = { "ABA", "BAB", "ABC", "BCB", "CBA" }; // spectrum String[] array6 = { "TAT", "ATG", "TGG", "GGT", "GTG", "TGC" }; // ppt spectrum String[] array7 = { "ATG", "GGT", "GTG", "TAT", "TGC", "TGG" }; System.out.println("array1 ü ִ :"); spectrum(array1); System.out.println("array2 ü ִ :"); spectrum(array2); System.out.println("array3 ü ִ :"); spectrum(array3); System.out.println("array4 ü ִ :"); spectrum(array4); System.out.println("array5 ü ִ :"); spectrum(array5); System.out.println("array6 ü ִ :"); spectrum(array6); System.out.println("array7 ü ִ :"); spectrum(array7); } }
Go
UTF-8
1,091
3.359375
3
[]
no_license
package models import ( "sort" "strings" "github.com/taciomcosta/cookify/pkg/recipepuppy" ) // Recipe represts a recipe in the domain model. type Recipe struct { Title string `json:"title"` Ingredients Ingredients `json:"ingredients"` Link string `json:"link"` Gif string `json:"gif"` } // ParseManyRecipes parses recipes from RecipePuppy into our format. func ParseManyRecipes(puppyRecipes []recipepuppy.Recipe) []Recipe { recipes := make([]Recipe, 0) for _, puppyRecipe := range puppyRecipes { recipe := parseOneRecipe(puppyRecipe) recipes = append(recipes, recipe) } return recipes } func parseOneRecipe(puppyRecipe recipepuppy.Recipe) Recipe { return Recipe{ Title: puppyRecipe.Title, Ingredients: parsePuppyIngredients(puppyRecipe.Ingredients), Link: puppyRecipe.Href, Gif: "", } } func parsePuppyIngredients(ingredients string) Ingredients { parsed := strings.Split(ingredients, ",") for i := range parsed { parsed[i] = strings.TrimSpace(parsed[i]) } sort.Strings(parsed) return parsed }
Java
UTF-8
281
1.9375
2
[]
no_license
package com.kuki.common.eventbus; /** * author :yeton * date : 2021/8/20 17:51 * package:com.kuki.common.eventbus * description : */ public class LoginEvent { public String userName; public LoginEvent(String userName) { this.userName = userName; } }
Java
UTF-8
4,980
2.078125
2
[ "Apache-2.0" ]
permissive
/* * Project Scelight * * Copyright (c) 2013 Andras Belicza <iczaaa@gmail.com> * * This software is the property of Andras Belicza. * Copying, modifying, distributing, refactoring without the author's permission * is prohibited and protected by Law. */ package hu.sllauncher.service.registration; import hu.sllauncher.bean.reginfo.RegInfoBean; import hu.sllauncher.service.env.LEnv; import hu.sllauncher.util.LUtils; import hu.sllauncher.util.secure.DecryptUtil; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Calendar; import java.util.Date; import java.util.zip.InflaterInputStream; import javax.xml.bind.JAXB; /** * Registration manager. * * @author Andras Belicza */ public class RegManager { /** Magic word of the registration files (<code>"SLREG"</code>). */ private static final byte[] REG_FILE_MAGIC = new byte[] { 'S', 'L', 'R', 'E', 'G' }; /** Handled registration file version. */ private static final byte[] REG_FILE_VERSION = new byte[] { 0, 1 }; /** Bytes of accepted / valid key selector. */ private static final byte[] KEY_SELECTOR = new byte[] { (byte) ( DecryptUtil.CURRENT_KEY_SELECTOR >> 8 ), (byte) DecryptUtil.CURRENT_KEY_SELECTOR }; /** Registration file path. */ public static final Path PATH_REGISTRATION_FILE = LEnv.PATH_WORKSPACE.resolve( "reginfo.slreg" ); /** Expiration time of the registration file in months (calculated from the reg file encryption date). */ public static final int REG_FILE_EXPIRATION_MONTHS = 6; /** Registration status. */ public final RegStatus regStatus; /** Loaded registration info. */ private final RegInfoBean regInfo; /** * Creates a new {@link RegManager}. */ public RegManager() { // Check registration file if ( !Files.exists( PATH_REGISTRATION_FILE ) ) { regStatus = RegStatus.NOT_FOUND; LEnv.LOGGER.debug( "No registration file found." ); regInfo = null; return; } // Load registration info RegInfoBean regInfo_; try { final byte[] regInfoEncData = Files.readAllBytes( PATH_REGISTRATION_FILE ); // "reginfo.xml.deflated.enc" int offset = 0; // Check magic for ( int i = 0; i < REG_FILE_MAGIC.length; i++, offset++ ) if ( REG_FILE_MAGIC[ i ] != regInfoEncData[ offset ] ) throw new RuntimeException( "Invalid magic word!" ); // Check version for ( int i = 0; i < REG_FILE_VERSION.length; i++, offset++ ) if ( REG_FILE_VERSION[ i ] != regInfoEncData[ offset ] ) throw new RuntimeException( "Invalid or unsupported version!" ); // Check key selector for ( int i = 0; i < KEY_SELECTOR.length; i++, offset++ ) if ( KEY_SELECTOR[ i ] != regInfoEncData[ offset ] ) throw new RuntimeException( "Invalid or unsupported key selector!" ); // We're cool, decrypt... final byte[] regInfodeflatedXmlData = DecryptUtil.decrypt( regInfoEncData, offset, regInfoEncData.length - offset ); // "reginfo.xml.deflated" if ( regInfodeflatedXmlData == null ) throw new Exception( "Failed to decrypt registration file!" ); // ...and inflate try ( final InputStream in = new InflaterInputStream( new ByteArrayInputStream( regInfodeflatedXmlData ) ) ) { regInfo_ = JAXB.unmarshal( in, RegInfoBean.class ); // "reginfo.xml" } if ( LEnv.LOGGER.testDebug() ) LEnv.LOGGER.debug( "Registration info loaded (registered to: " + regInfo_.getPerson().getPersonName() + ")." ); if ( LEnv.LOGGER.testTrace() ) LEnv.LOGGER.trace( "Registration info: " + regInfo_.toString() ); } catch ( final Exception e ) { regStatus = RegStatus.INVALID; LEnv.LOGGER.error( "Invalid or corrupt registration file: " + PATH_REGISTRATION_FILE, e ); regInfo = null; return; } regInfo = regInfo_; // Check expiration final Calendar expCal = Calendar.getInstance(); expCal.setTime( regInfo.getEncryptionDate() ); expCal.add( Calendar.MONTH, REG_FILE_EXPIRATION_MONTHS ); if ( new Date().after( expCal.getTime() ) ) { regStatus = RegStatus.EXPIRED; LEnv.LOGGER.warning( "Registration file has expired!" ); return; } // Quick check if registered system info matches current system info if ( !LUtils.getSysInfo().matches( regInfo.getSysInfo() ) ) { regStatus = RegStatus.SYSINFO_MISMATCH; LEnv.LOGGER.warning( "Registration info mismatch: your system info does not match the registered system info!" ); return; } regStatus = RegStatus.MATCH; } /** * @return the loaded registration info */ public RegInfoBean getRegInfo() { return regInfo; } /** * Returns if registration is OK. * * @return if registration is OK. */ public boolean isOk() { return regStatus == RegStatus.MATCH; } }
C
UTF-8
752
2.5625
3
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include "t_hashtable.h" #include "t_assert.h" #include "../str.h" #include "../hashtable.h" #include "../error.h" #include "../bin.h" #include "../alloc.h" static unsigned long num_allocs = 0; static void *count_malloc(unsigned long n) { ++num_allocs; return malloc(n); } void except1(struct hashtable *h) { /* try to trigger overflow condition */ h->slots[1].used = -1; add(h, ch1str[0], ch1str[0], -1); test_assert(errno == error_overflow); ht_free(h); test_assert(ht_init(h)); test_assert(h->slots[1].used == 0); } int main(void) { struct hashtable ht; alloc_set_alloc(count_malloc); test_assert(ht_init(&ht)); except1(&ht); ht_free(&ht); return 0; }
Java
UTF-8
715
2.203125
2
[]
no_license
package com.yaochen.tester.cases; //public class RecaseV4 { // @Test(dataProvider = "datas") // public void test1(String search,String condition) { // String url = "http://132.232.44.158:8080/morning/searchGoods"; // Map<String, String> data = new HashMap<String, String>(); // data.put("search", search); // data.put("condition", condition); // String AA = Httputil.doPost(url, data); // System.out.println(AA); // } // @DataProvider // public Object [] []datas(){ // int [] rows={2,3,4,5,6,7}; // int [] calls={6,7}; // Object[][]datas= ExcelUtil.datas("src/main/resources/casesV1.xlsx",rows,calls); // return datas; // } //}
JavaScript
UTF-8
351
3.671875
4
[]
no_license
// JavaScript Document // James McGorty var strFirstName = "James"; var strLastName = "McGorty" var strMiddle = "Britten"; // var strFullName = "James Britten McGorty"; var strFullName = strFirstName + " " + strMiddle + " " + strLastName; var input = parseInt(prompt("Value", 3)); // parseFloat() var iNum = 1 + 2 + input; console.log(iNum); console.log(strFullName);
Java
UTF-8
2,657
2.515625
3
[]
no_license
package com.fh.plugin.websocketVideo; import java.io.IOException; import java.net.InetSocketAddress; import java.net.UnknownHostException; import org.java_websocket.WebSocket; import org.java_websocket.WebSocketImpl; import org.java_websocket.framing.Framedata; import org.java_websocket.handshake.ClientHandshake; import org.java_websocket.server.WebSocketServer; /** * 说明:视频弹幕服务端 * 作者:FH Admin Q313 59 6790 * 官网:www. fhadmin. org */ public class VideoServer extends WebSocketServer{ public VideoServer(int port) throws UnknownHostException { super(new InetSocketAddress(port)); } public VideoServer(InetSocketAddress address) { super(address); } /** * 触发连接事件 */ @Override public void onOpen( WebSocket conn, ClientHandshake handshake ) { //this.sendToAll( "new connection: " + handshake.getResourceDescriptor() ); //System.out.println("===" + conn.getRemoteSocketAddress().getAddress().getHostAddress()); } /** * 触发关闭事件 */ @Override public void onClose( WebSocket conn, int code, String reason, boolean remote ) { userLeave(conn); } /** * 客户端发送消息到服务器时触发事件 */ @Override public void onMessage(WebSocket conn, String message){ message = message.toString(); if(null != message && message.startsWith("[video313596790]")){ this.userjoin(message.replaceFirst("\\[video313596790\\]", ""),conn); }else{ VideoServerPool.sendMessage(message.toString());//向所有在线用户发送消息 } } public void onFragment( WebSocket conn, Framedata fragment ) { } /** * 触发异常事件 */ @Override public void onError( WebSocket conn, Exception ex ) { ex.printStackTrace(); if( conn != null ) { //some errors like port binding failed may not be assignable to a specific websocket } } /** * 用户加入处理 * @param user */ public void userjoin(String user, WebSocket conn){ VideoServerPool.addUser(user,conn); //向连接池添加当前的连接对象 } /** * 用户下线处理 * @param user */ public void userLeave(WebSocket conn){ VideoServerPool.removeUser(conn); //在连接池中移除连接 } public static void main( String[] args ) throws InterruptedException , IOException { WebSocketImpl.DEBUG = false; int port = 8886; //端口 VideoServer s = new VideoServer(port); s.start(); //System.out.println( "服务器的端口" + s.getPort() ); } @Override public void onStart() { // TODO Auto-generated method stub } }
Markdown
UTF-8
1,747
3.53125
4
[]
no_license
# Byte Pair Encoding ## Introduction Byte-pair encoding (BPE) is currently a popular technique to deal with this issue. The idea is to encode text using a set of automatically constructed types, instead of conventional word types. A type can be a character or a subword unit; and the types are built through a iterative process, which we now walk you through. ## Description This assignment requires to implement BPE algorithm. The following steps are followed when encoding a corpus: Suppose we have the following tiny training data: *it unit unites* 1. Append a special *<s>* symbol marking the ned of the words * This now becomes: *i t <s> u n i t <s> u n i t e s <s>* 2. In each iteration we do the following: 1. Find the most frequent type of bigram 2. Merge this into a new symbol 3. Added it to the type vocabulary From the examples we would have the following: 1. Bigram to merge: i t * Training data: it <s> u n it <s> u n it e s <s> 2. Bigram to merge: it <s> * Training data: it<s> u n it<s> u n it e s <s> 3. Bigram to merge: u n * Training data: it<s> un it<s> un it e s <s> In this example, we end up with the type vocabulary: {i, t, u, n, e, s, <s>, it, it<s>, un} ## Usage / Running the code The source code assumes the following directory structure and files to be present: ``` ├── encoder.py # The source code file containing the BPE encoder └── A5-data.txt # The corpus ``` The simple command will run the code: ``` python3 encoder.py ``` The file produces multiple files, however 2 are important: 1. frequency_one_bpe_scatterplot.png * A plot of the vocab size vs the length of the types vocab 2. frequency_one.out * Information about the model
Python
UTF-8
4,694
2.515625
3
[]
no_license
#import math as M import multiprocessing as mp import threading import time import math ''' Primes=[2,3,5,7,11,13] EndPoint=Primes[-1] iMainPrime=len(Primes)-2 NextMPrimeSqrd=Primes[iMainPrime+1]**2 print('1.5') while True: for dummy in range(700): StartPoint=EndPoint+2 EndPoint+=Primes[iMainPrime]-1 if EndPoint >= NextMPrimeSqrd: EndPoint=NextMPrimeSqrd iMainPrime+=1 NextMPrimeSqrd=Primes[iMainPrime+1]**2 CurrentList=list(range(StartPoint,EndPoint+1,2)) lcl=len(CurrentList) for prime in Primes[1:iMainPrime+1]: c=-(-StartPoint//prime)*prime for i in range(((c if c%2 else c+prime)-StartPoint)//2,lcl,prime): CurrentList[i]=0 Primes+=[x for x in CurrentList if x] print('The '+str(len(Primes))+"'th prime is "+str(Primes[-1])) ''' def doPrimes(START,END,PRIMES): #print(START,END,PRIMES) l=list(range(START,END+1,2)) #print(l) ln=len(l) #print(ln) for prime in PRIMES: s=-(-START//prime)*prime for i in range(((s if s%2 else s+prime)-START)//2,ln,prime): l[i]=0 #print(l) return l def ppl(l): r=l.pop(0) ln=len(l) while ln>0 and l[0]==0: ln-=1 l.pop(0) return r def doWork(Jobs,Rq): n,i,c,s,e,p=Jobs.get() Rq.put([n,i,c,doPrimes(s,e,p)]) def doWork(Jobs,Rq): try: n,i,c,s,e,p=Jobs.get(True,0) Rq.put([n,i,c,doPrimes(s,e,p)]) except: pass def threadWork(Jobs,Rq): try: t = threading.Thread(target = tryWork, args=[Jobs,Rq]) t.start() except: pass def worker(Jobs,Rq,Rlenq,Rpq,Pq,CORES,NUM): if NUM==0: Primes=[3,5,7] iCP=0#index Current Prime Li=iCP#Lowes used index Rlens={}#return lengths update=time.time() while True: doW=True if time.time()-update>1: print("the " + str(len(Primes)+1) + "'th prime is " + str(Primes[-1])) update+=1 if not Pq.empty(): print("P") doW=False Primes+=Pq.get() if Jobs.empty() and iCP<len(Primes)-1: print("A") doW=False START=Primes[iCP]**2+2 END=Primes[iCP+1]**2-2 numj=int((END-START+1)**.5)#number of jobs s=START for i in range(numj): e=((END-s)//(numj-i))+s e=e if e%2 else e+1 Jobs.put([numj,i,iCP,s,e,Primes[:iCP+1]]) s=e+2 iCP+=1 if doW: #threadWork(Jobs,Rq) pass elif NUM==1: while True: if not Rpq.empty(): print("B") primes=Rpq.get() p=[] while primes: p+=[ppl(primes)] print("1",p) Pq.put(p) else: #threadWork(Jobs,Rq) pass elif NUM==2: Li=0 Curc=0 Rl={}#Return list Rl[0]=[] while True: if not Rq.empty(): print("C") n,i,c,x=Rq.get() if x[0]==0: ppl(x) if x: if c not in Rl: Rl[c]=[] Rl[c]+=[[i,n,c]+x] Rl[c].sort() while c==Curc and i==Li: Rpq.put(Rl[c].pop(0)[3:]) Li+=1 #print("asdf") if i==n-1: del Rl[c] Curc+=1 Li=0 try: i,n,c=Rl[c][0][:3] except: break else: #threadWork(Jobs,Rq) pass else: while True: doWork(Jobs,Rq) if __name__ == "__main__": import sys print(sys.argv[0]) Jobs=mp.Queue() CORES = max(3, mp.cpu_count()) Rq= mp.Queue()#Return Queue p={} Rlenq=mp.Queue()#Return lenght Queue Rpq=Pq=mp.Queue()#Return Primes Queue Pq=mp.Queue()#Primes Queue for i in range(CORES): p[i] = mp.Process(target = worker, args=[Jobs,Rq,Rlenq,Rpq,Pq,CORES,i]) p[i].start() for i in range(CORES): p[i].join()
TypeScript
UTF-8
786
2.796875
3
[ "MIT" ]
permissive
import isString from '@/isString' import camelize from '@/camelize' export const getCSS: { /** * 读取所有的css属性 * @param elt 元素 * @param pseudoElt 伪元素 'before' | 'after' */ (elt: HTMLElement, pseudoElt?: 'before' | 'after' | null): CSSStyleDeclaration /** * 读取css属性 * @param elt 元素 * @param prop 属性名称 * @param pseudoElt 伪元素 'before' | 'after' */ (elt: HTMLElement, prop: string, pseudoElt?: 'before' | 'after' | null): any } = (elt: HTMLElement, prop?: string, pseudoElt?: 'before' | 'after' | null) => { if (!isString(prop)) { return document.defaultView.getComputedStyle(elt, pseudoElt) } return document.defaultView.getComputedStyle(elt, pseudoElt)[camelize(prop)] } export default getCSS
C++
UTF-8
33,462
2.625
3
[]
no_license
#ifndef _SPITER_HPP #define _SPITER_HPP //============================================================================ // File: spiter.h // // Author: Bob Steagall // // History: Version 0.98 // // Notes: // // Copyright (c) 1998 R.C. Elston // All Rights Reserved //============================================================================ // #include "mped/mpbase.h" namespace SAGE { namespace MPED { /** \ingroup DerivedIterators * \brief Iterates across a set of family s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Iterates across a set of family s */ template <class GI, class FI, class SI, class PI, class MI> class family_iterator : public family_base_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef family<GI,FI,SI,PI,MI>* pointer; typedef family<GI,FI,SI,PI,MI>& reference; typedef family_iterator<GI,FI,SI,PI,MI> this_type; typedef family_base_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ family_iterator(); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; bool operator <(const this_type& c) const; pointer operator ->() const; reference operator *() const; reference operator [](difference_type n) const; this_type& operator +=(difference_type n); this_type& operator -=(difference_type n); this_type& operator ++(); this_type& operator --(); this_type operator ++(int); this_type operator --(int); //@} private: family_iterator(const base_type& i); }; /** \ingroup DerivedConstIterators * \brief Const-iterates across a set of family s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Const-iterates across a set of family s */ template <class GI, class FI, class SI, class PI, class MI> class family_const_iterator : public family_base_const_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef const family<GI,FI,SI,PI,MI>* pointer; typedef const family<GI,FI,SI,PI,MI>& reference; typedef family_const_iterator<GI,FI,SI,PI,MI> this_type; typedef family_base_const_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ family_const_iterator(); family_const_iterator(const family_iterator<GI,FI,SI,PI,MI>& i); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; bool operator <(const this_type& c) const; pointer operator ->() const; reference operator *() const; reference operator [](difference_type n) const; this_type& operator +=(difference_type n); this_type& operator -=(difference_type n); this_type& operator ++(); this_type& operator --(); this_type operator ++(int); this_type operator --(int); //@} private: family_const_iterator(const base_type& i); }; /** \ingroup DerivedIterators * \brief Iterates across a set of mate s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Iterates across a set of mate s */ template <class GI, class FI, class SI, class PI, class MI> class mate_iterator : public mate_base_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef mate_info<GI,FI,SI,PI,MI>* pointer; typedef mate_info<GI,FI,SI,PI,MI>& reference; typedef mate_iterator<GI,FI,SI,PI,MI> this_type; typedef mate_base_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ mate_iterator(); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; pointer operator ->() const; reference operator *() const; this_type& operator ++(); this_type operator ++(int); //@} private: mate_iterator(const base_type& i); }; /** \ingroup DerivedConstIterators * \brief Const-iterates across a set a mate s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Const-iterates across a set a mate s */ template <class GI, class FI, class SI, class PI, class MI> class mate_const_iterator : public mate_base_const_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef const mate_info<GI,FI,SI,PI,MI>* pointer; typedef const mate_info<GI,FI,SI,PI,MI>& reference; typedef mate_const_iterator<GI,FI,SI,PI,MI> this_type; typedef mate_base_const_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ mate_const_iterator(); mate_const_iterator(const mate_iterator<GI,FI,SI,PI,MI>& i); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; pointer operator ->() const; reference operator *() const; this_type& operator ++(); this_type operator ++(int); //@} private: mate_const_iterator(const base_type& i); }; /** \ingroup DerivedIterators * \brief Iterates across a set of member s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Iterates across a set of member s */ template <class GI, class FI, class SI, class PI, class MI> class member_iterator : public member_base_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; friend class member_const_iterator<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef member<GI,FI,SI,PI,MI>* pointer; typedef member<GI,FI,SI,PI,MI>& reference; typedef member_iterator<GI,FI,SI,PI,MI> this_type; typedef member_base_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ member_iterator(); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; bool operator <(const this_type& c) const; pointer operator ->() const; reference operator *() const; reference operator [](difference_type n) const; this_type& operator +=(difference_type n); this_type& operator -=(difference_type n); this_type& operator ++(); this_type& operator --(); this_type operator ++(int); this_type operator --(int); //@} private: member_iterator(const base_type& i); }; /** \ingroup DerivedConstIterators * \brief Const-iterates across a set of member s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Const-iterates across a set of member s */ template <class GI, class FI, class SI, class PI, class MI> class member_const_iterator : public member_base_const_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef const member<GI,FI,SI,PI,MI>* pointer; typedef const member<GI,FI,SI,PI,MI>& reference; typedef member_const_iterator<GI,FI,SI,PI,MI> this_type; typedef member_base_const_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ member_const_iterator(); member_const_iterator(const member_iterator<GI,FI,SI,PI,MI>& i); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; bool operator <(const this_type& c) const; pointer operator ->() const; reference operator *() const; reference operator [](difference_type n) const; this_type& operator +=(difference_type n); this_type& operator -=(difference_type n); this_type& operator ++(); this_type& operator --(); this_type operator ++(int); this_type operator --(int); //@} private: member_const_iterator(const base_type& i); }; /** \ingroup DerivedIterators * \brief Iterates across a set of offspring s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Iterates across a set of offspring s */ template <class GI, class FI, class SI, class PI, class MI> class offspring_iterator : public offspring_base_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef member<GI,FI,SI,PI,MI>* pointer; typedef member<GI,FI,SI,PI,MI>& reference; typedef offspring_iterator<GI,FI,SI,PI,MI> this_type; typedef offspring_base_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ offspring_iterator(); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; pointer operator ->() const; reference operator *() const; this_type& operator ++(); this_type operator ++(int); //@} private: offspring_iterator(const base_type& i); }; /** \ingroup DerivedConstIterators * \brief Const-iterates across a set of offspring s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Const-iterates across a set of offspring s */ template <class GI, class FI, class SI, class PI, class MI> class offspring_const_iterator : public offspring_base_const_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef const member<GI,FI,SI,PI,MI>* pointer; typedef const member<GI,FI,SI,PI,MI>& reference; typedef offspring_const_iterator<GI,FI,SI,PI,MI> this_type; typedef offspring_base_const_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ offspring_const_iterator(); offspring_const_iterator(const offspring_iterator<GI,FI,SI,PI,MI>& i); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; pointer operator ->() const; reference operator *() const; this_type& operator ++(); this_type operator ++(int); //@} private: offspring_const_iterator(const base_type& i); }; /** \ingroup DerivedIterators * \brief Iterates across a set of parent s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Iterates across a set of parent s */ template <class GI, class FI, class SI, class PI, class MI> class parent_iterator : public parent_base_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef member<GI,FI,SI,PI,MI>* pointer; typedef member<GI,FI,SI,PI,MI>& reference; typedef parent_iterator<GI,FI,SI,PI,MI> this_type; typedef parent_base_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ parent_iterator(); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; pointer operator ->() const; reference operator *() const; this_type& operator ++(); this_type operator ++(int); //@} private: parent_iterator(const base_type& i); }; /** \ingroup DerivedConstIterators * \brief Const-iterates across a set of parent s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Const-iterates across a set of parent s */ template <class GI, class FI, class SI, class PI, class MI> class parent_const_iterator : public parent_base_const_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef const member<GI,FI,SI,PI,MI>* pointer; typedef const member<GI,FI,SI,PI,MI>& reference; typedef parent_const_iterator<GI,FI,SI,PI,MI> this_type; typedef parent_base_const_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ parent_const_iterator(); parent_const_iterator(const parent_iterator<GI,FI,SI,PI,MI>& i); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; pointer operator ->() const; reference operator *() const; this_type& operator ++(); this_type operator ++(int); //@} private: parent_const_iterator(const base_type& i); }; /** \ingroup DerivedIterators * \brief Iterates across a set of pedigree s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Iterates across a set of pedigree s */ template <class GI, class FI, class SI, class PI, class MI> class pedigree_iterator : public pedigree_base_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; friend class multipedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef pedigree<GI,FI,SI,PI,MI>* pointer; typedef pedigree<GI,FI,SI,PI,MI>& reference; typedef pedigree_iterator<GI,FI,SI,PI,MI> this_type; typedef pedigree_base_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ pedigree_iterator(); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; bool operator <(const this_type& c) const; pointer operator ->() const; reference operator *() const; reference operator [](difference_type n) const; this_type& operator +=(difference_type n); this_type& operator -=(difference_type n); this_type& operator ++(); this_type& operator --(); this_type operator ++(int); this_type operator --(int); //@} private: pedigree_iterator(const base_type& i); }; /** \ingroup DerivedConstIterators * \brief Const-iterates across a set of pedigree s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Const-iterates across a set of pedigree s */ template <class GI, class FI, class SI, class PI, class MI> class pedigree_const_iterator : public pedigree_base_const_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; friend class multipedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef const pedigree<GI,FI,SI,PI,MI>* pointer; typedef const pedigree<GI,FI,SI,PI,MI>& reference; typedef pedigree_const_iterator<GI,FI,SI,PI,MI> this_type; typedef pedigree_base_const_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ pedigree_const_iterator(); pedigree_const_iterator(const pedigree_iterator<GI,FI,SI,PI,MI>& i); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; bool operator <(const this_type& c) const; pointer operator ->() const; reference operator *() const; reference operator [](difference_type n) const; this_type& operator +=(difference_type n); this_type& operator -=(difference_type n); this_type& operator ++(); this_type& operator --(); this_type operator ++(int); this_type operator --(int); //@} private: pedigree_const_iterator(const base_type& i); }; /** \ingroup DerivedIterators * \brief Iterates across a set of progeny s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Iterates across a set of progeny s */ template <class GI, class FI, class SI, class PI, class MI> class progeny_iterator : public progeny_base_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef member<GI,FI,SI,PI,MI>* pointer; typedef member<GI,FI,SI,PI,MI>& reference; typedef progeny_iterator<GI,FI,SI,PI,MI> this_type; typedef progeny_base_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ progeny_iterator(); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; pointer operator ->() const; reference operator *() const; this_type& operator ++(); this_type operator ++(int); //@} private: progeny_iterator(const base_type& i); }; /** \ingroup DerivedConstIterators * \brief Const-iterates across a set of progeny s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Const-iterates across a set of progeny s */ template <class GI, class FI, class SI, class PI, class MI> class progeny_const_iterator : public progeny_base_const_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef const member<GI,FI,SI,PI,MI>* pointer; typedef const member<GI,FI,SI,PI,MI>& reference; typedef progeny_const_iterator<GI,FI,SI,PI,MI> this_type; typedef progeny_base_const_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ progeny_const_iterator(); progeny_const_iterator(const progeny_iterator<GI,FI,SI,PI,MI>& i); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; pointer operator ->() const; reference operator *() const; this_type& operator ++(); this_type operator ++(int); //@} private: progeny_const_iterator(const base_type& i); }; /** \ingroup DerivedIterators * \brief Iterates across a set of sibling s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Iterates across a set of sibling s */ template <class GI, class FI, class SI, class PI, class MI> class sibling_iterator : public sibling_base_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef member<GI,FI,SI,PI,MI>* pointer; typedef member<GI,FI,SI,PI,MI>& reference; typedef sibling_iterator<GI,FI,SI,PI,MI> this_type; typedef sibling_base_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ sibling_iterator(); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; pointer operator ->() const; reference operator *() const; this_type& operator ++(); this_type operator ++(int); //@} private: sibling_iterator(const base_type& i); }; /** \ingroup DerivedConstIterators * \brief Const-iterates across a set of sibling s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Const-iterates across a set of sibling s */ template <class GI, class FI, class SI, class PI, class MI> class sibling_const_iterator : public sibling_base_const_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef const member<GI,FI,SI,PI,MI>* pointer; typedef const member<GI,FI,SI,PI,MI>& reference; typedef sibling_const_iterator<GI,FI,SI,PI,MI> this_type; typedef sibling_base_const_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ sibling_const_iterator(); sibling_const_iterator(const sibling_iterator<GI,FI,SI,PI,MI>& i); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; pointer operator ->() const; reference operator *() const; this_type& operator ++(); this_type operator ++(int); //@} private: sibling_const_iterator(const base_type& i); }; /** \ingroup DerivedIterators * \brief Iterates across a set of subpedigree s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Iterates across a set of subpedigree s */ template <class GI, class FI, class SI, class PI, class MI> class subpedigree_iterator : public subpedigree_base_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef subpedigree<GI,FI,SI,PI,MI>* pointer; typedef subpedigree<GI,FI,SI,PI,MI>& reference; typedef subpedigree_iterator<GI,FI,SI,PI,MI> this_type; typedef subpedigree_base_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ subpedigree_iterator(); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; bool operator <(const this_type& c) const; pointer operator ->() const; reference operator *() const; reference operator [](difference_type n) const; this_type& operator +=(difference_type n); this_type& operator -=(difference_type n); this_type& operator ++(); this_type& operator --(); this_type operator ++(int); this_type operator --(int); //@} private: subpedigree_iterator(const base_type& i); }; /** \ingroup DerivedConstIterators * \brief Const-iterates across a set of subpedigree s * * \par Template parameters * * \c GI Info object associated with individuals (SAGE::MPED::member) * \c FI Info object associated with families (SAGE::MPED::family) * \c SI Info object associated with subpedigrees (SAGE::MPED::subpedigree) * \c PI Info object associated with pedigrees (SAGE::MPED::pedigree) * \c MI Info object associated with multipedigrees (SAGE::MPED::multipedigree) * * Const-iterates across a set of subpedigree s */ template <class GI, class FI, class SI, class PI, class MI> class subpedigree_const_iterator : public subpedigree_base_const_iterator { public: friend class member<GI,FI,SI,PI,MI>; friend class family<GI,FI,SI,PI,MI>; friend class subpedigree<GI,FI,SI,PI,MI>; friend class pedigree<GI,FI,SI,PI,MI>; /** \name Typedefs * Typedef-ed local to this class */ //@{ typedef const subpedigree<GI,FI,SI,PI,MI>* pointer; typedef const subpedigree<GI,FI,SI,PI,MI>& reference; typedef subpedigree_const_iterator<GI,FI,SI,PI,MI> this_type; typedef subpedigree_base_const_iterator base_type; //@} public: /** \name Standard iterator interface * Standard iterator interface */ //@{ subpedigree_const_iterator(); subpedigree_const_iterator(const subpedigree_iterator<GI,FI,SI,PI,MI>& i); bool operator ==(const this_type& c) const; bool operator !=(const this_type& c) const; bool operator <(const this_type& c) const; pointer operator ->() const; reference operator *() const; reference operator [](difference_type n) const; this_type& operator +=(difference_type n); this_type& operator -=(difference_type n); this_type& operator ++(); this_type& operator --(); this_type operator ++(int); this_type operator --(int); //@} private: subpedigree_const_iterator(const base_type& i); }; } // End namespace MPED } // End namespace SAGE #include "mped/spiter.ipp" #endif //- _SPITER_HPP
C#
UTF-8
559
2.59375
3
[]
no_license
using System; using System.Runtime.InteropServices; namespace Maze_Algorithm { class Util { [DllImport("kernel32.dll", ExactSpelling = true)] private static extern IntPtr GetConsoleWindow(); private static IntPtr ThisConsole = GetConsoleWindow(); [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); public static void MaximizeConsoleWindow() { ShowWindow(ThisConsole, 3); } } }
Java
UTF-8
614
3.875
4
[]
no_license
import java.util.Arrays; public class ArraySort { public static void main(String[] args) { Integer[] integers = {4, 3, 6, 2, 5, 1}; Double[] doubles = {4.0, 3.0, 2.0, 5.0, 1.0}; sortArray(integers); sortArray(doubles); } public static <T extends Number> void sortArray(T[] list) { Arrays.sort(list); for (int i = 0; i < list.length / 2; i++) { T temp = list[i]; list[i] = list[list.length - (i + 1)]; list[list.length - (i + 1)] = temp; } for (int i = 0; i < list.length; i++) { System.out.print(list[i] + " "); } System.out.println(); } }
Java
UTF-8
3,384
2.46875
2
[]
no_license
package Collectors; import GlobalConstants.Enums; import Interfaces.ICollectorIssuesContainer; import Utils.GeneralFunctions; import Utils.Logit; import lycus.Host; import GlobalConstants.Constants; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import java.util.HashMap; import java.util.HashSet; /** * Created by roi on 12/11/16. */ public class CollectorIssuesContainer implements ICollectorIssuesContainer { private static CollectorIssuesContainer instance; private JSONArray issuesArray; private int count; private Object lockIssues = new Object(); private Object lockLiveIssues = new Object(); private HashMap<String, HashSet<Enums.CollectorType>> liveIssues;// HashMap<HostId,HashSet<CollectorType>> public synchronized static CollectorIssuesContainer getInstance() { if (instance == null) { instance = new CollectorIssuesContainer(); } return instance; } public boolean isIssue(String hostId, Enums.CollectorType collectorType) { if (this.liveIssues.get(hostId) == null) return false; return this.liveIssues.get(hostId).contains(collectorType); } private CollectorIssuesContainer() { issuesArray = new JSONArray(); liveIssues = new HashMap<String, HashSet<Enums.CollectorType>>(); int count = 0; } @Override public synchronized void addIssue(Host host, Enums.CollectorType type, String issue, int issueState) { String hostId = ""; String userId = ""; try { if (host.getHostIp().contains("62.90.132.124")) Logit.LogDebug("BP"); hostId = host.getHostId().toString(); if (issueState == 1) { if (this.liveIssues.containsKey(hostId)) { if (this.liveIssues.get(hostId).contains(type)) return; else this.liveIssues.get(hostId).add(type); } else { HashSet<Enums.CollectorType> newIssueTable = new HashSet<Enums.CollectorType>(); newIssueTable.add(type); this.liveIssues.put(hostId, newIssueTable); } } else { if (!this.liveIssues.containsKey(hostId) || !this.liveIssues.get(hostId).contains(type)) return; else { this.liveIssues.get(hostId).remove(type); if (this.liveIssues.get(hostId).size() == 0) this.liveIssues.remove(hostId); } } JSONObject issueObject = new JSONObject(); try { userId = host.getUserId(); if (userId != null) issueObject.put("user_id", userId); } catch (Exception e) { Logit.LogWarn("Error getting userId from host: " + hostId + " userId: " + userId); e.printStackTrace(); } issueObject.put("host_id", hostId); issueObject.put("host_name", host.getName()); issueObject.put("type", type.toString()); issueObject.put("issue_info", issue); issueObject.put("issue_status", issueState); issueObject.put("time", System.currentTimeMillis()); count++; issuesArray.add(issueObject); } catch (Exception e) { Logit.LogError("CollectorIssuesContainer - addIssue()", "Error adding issue. Host:" + hostId + ", UserId: " + userId, e); e.printStackTrace(); } } public void clearAll() { issuesArray.clear(); count = 0; } public int length() { return count; } @Override public synchronized JSONObject getAllIssues() { JSONObject issuesObject = new JSONObject(); issuesObject.put(Constants.issues, GeneralFunctions.Base64Encode(issuesArray.toJSONString())); clearAll(); return issuesObject; } }
Python
UTF-8
200
2.9375
3
[]
no_license
fp=open("unique_names.csv",'r') fp1=open("sur.csv",'w') while True: line=fp.readline() if not line: break k=line.split() fp1.write(str(k[len(k)-1])+"\n") fp.close() fp1.close()
Python
UTF-8
222
3.078125
3
[ "Unlicense" ]
permissive
from sys import stdin from collections import Counter c = Counter() for line in stdin: words = line.split() cand, votes = words[0], int(words[1]) c[cand] += votes for key, val in c.items(): print(key, val)
Python
UTF-8
371
3.3125
3
[]
no_license
from double_link_list import DoubleLinkList class Stack(): def __init__(self): self.__list = DoubleLinkList() def push_item(self, value): return self.__list.add(value) def pop_item(self): return self.__list.r def __str__(self): return self.__list.__str__() obj = Stack() obj.push_item(300) obj.push_item(400) print(obj)
JavaScript
UTF-8
1,602
3.46875
3
[]
no_license
describe('Spaceship', function(){ describe('A space ship is created', function() { it('ship should exist', function () { var shipDiv = document.getElementById('ship'); expect(shipDiv.constructor.name).to.be('HTMLImageElement', 'You should be using an image tag for this exericse.'); }); it('should be an image of a ship', function() { var shipDiv = document.getElementById('ship'); expect(shipDiv.getAttribute('src')).to.equal('./pictures/ship.gif', 'You need to link a source to your image tag'); }); }); describe('Ths spaceship has a move property', function(){ it('should have a move method', function(){ var move = Ship.prototype.move.constructor; expect(move).to.be(Function, 'the move function must be on the constructor prototype.'); }); }); }); describe('Asteroid', function() { it('an asteroid should exist', function () { var asteroid = document.getElementsByClassName('asteroid'); expect(asteroid[0].constructor.name).to.be('HTMLImageElement', 'You should be using an image tag for this exercise'); }); it('should be an image of an asteroid', function() { var asteroid = document.getElementsByClassName('asteroid'); expect(asteroid[0].getAttribute('src')).to.equal('./pictures/asteroid.png', 'You need your source to link to your asteroid image'); }); describe('Ths asteroid has a move property', function(){ it('should have a move method', function(){ var move = AddAsteroid.prototype.move.constructor; expect(move).to.be(Function, 'the move function must be on the constructor prototype to conserve memory'); }); }); });
PHP
UTF-8
422
3
3
[]
no_license
<?php namespace JK\Console; use JK\Console\IO\InputInterface; use JK\Console\IO\OutputInterface; /** * Class Console [Excecute command] * * @package JK\Console\ConsoleInterface */ interface ConsoleInterface { /** * Run and execute commands * * @param InputInterface $input * @param OutputInterface $output * * @return mixed */ public function run( InputInterface $input, OutputInterface $output ); }
Rust
UTF-8
3,053
3.421875
3
[]
no_license
use std::net::UdpSocket; use std::io; mod text; pub struct Flaschen { socket: UdpSocket, host: String, width: usize, height: usize, } #[derive(Debug, Copy, Clone)] pub struct Pixel { pub r: u8, pub g: u8, pub b: u8, } impl Flaschen{ pub fn new(hostname: String, width: usize, height: usize) -> io::Result<Flaschen> { println!("connecting to {}: ({}, {})", hostname, width, height); let local_socket = "0.0.0.0:0"; let port_string = ":1337"; match UdpSocket::bind(&*local_socket) { Result::Ok(s) => Ok(Flaschen{socket: s, height: height, width: width, host: hostname + port_string}), Result::Err(e) => Err(e), } } pub fn fill(&self, image: &[Vec<Pixel>]) -> io::Result<usize> { let height = image.len(); if height == 0 { return Ok(0); } let width = image[0].len(); // this is dumb - should make a packet and then send it rather than sending a million packets // (for small fill images, packets get lost in a buffer somewhere) let rows: usize = self.height / height + 1; let cols: usize = self.width / width + 1; for row in 0..rows { for col in 0..cols { try!(self.put(row * height, col * width, 0, image)); } } let parts = self.height * self.width; Ok(parts) } pub fn putchar(&self, x: usize, y: usize, z: usize, c: char, color: Pixel, background: Pixel) -> io::Result<usize> { let index = ((c as u32) - ('a' as u32)) as usize; let mut display = text::LOWERCASE[index]; let mut image: Vec<Vec<Pixel>> = vec![]; for row in 0..6 { image.push(vec![]); for pt in 0..3 { if ((display >> (17 - (row * 3 + pt))) & 1) == 1 { image.last_mut().unwrap().push(color); } else { image.last_mut().unwrap().push(background); } } } self.put(x, y, z, &image) } pub fn put(&self, x: usize, y: usize, z: usize, image: &[Vec<Pixel>]) -> io::Result<usize> { let height = image.len(); if height == 0 { return Ok(0); } let width = image[0].len(); let header = format!("P6\n{} {}\n255\n", width.to_string(), height.to_string()); let mut packet = header.into_bytes(); for row in image { for pixel in row { packet.extend_from_slice(&[pixel.r, pixel.g, pixel.b]); } } let footer = format!("\n{}\n{}\n{}", x, y, z); packet.extend_from_slice(&footer.into_bytes()); self.socket.send_to(&packet, &*(self.host)) } } #[cfg(test)] mod tests { #[test] fn it_works() { let host = "localhost"; let f = ::Flaschen::new(host.to_string(), 45, 35).unwrap(); let p = ::Pixel {r: 0, g: 255, b: 20}; let image = vec![vec![p, p, p]]; f.fill(&image); } }
Java
UTF-8
2,432
2.125
2
[]
no_license
package com.example.pikot.sugophapp.Both; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import com.example.pikot.sugophapp.R; import com.example.pikot.sugophapp.RandomClasses.SessionHandler; import com.example.pikot.sugophapp.RandomClasses.SharedPrefManager; import com.example.pikot.sugophapp.RandomClasses.Validation; import java.util.ArrayList; public class RegAddress extends AppCompatActivity { private EditText txtCity, txtStreet, txtBrgy; private Button btnNext; Validation validation= new Validation(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_reg_address); if(SharedPrefManager.getInstance(this).isLoggedIn()) { startActivity(new Intent(this, MainActivity.class)); } txtStreet= findViewById(R.id.txtStreet); txtBrgy= findViewById(R.id.txtBrgy); txtCity= findViewById(R.id.txtCity); btnNext= findViewById(R.id.btnNext); btnNext.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Boolean testStreet = validation.validateNormalInput(txtStreet); Boolean testCity = validation.validateNormalInput(txtCity); Boolean testBrgy = validation.validateNormalInput(txtBrgy); if (testStreet && testBrgy && testCity) { Intent intent1 = getIntent(); ArrayList<String> data = intent1.getStringArrayListExtra("data"); data.add(txtStreet.getText().toString().trim()); data.add(txtCity.getText().toString().trim()); data.add(txtBrgy.getText().toString().trim()); Intent intent = new Intent(getApplicationContext(), RegContact.class); intent.putStringArrayListExtra("data", data); startActivity(intent); } } }); } @Override protected void onResume() { if(SharedPrefManager.getInstance(this).isLoggedIn()) { startActivity(new Intent(this, MainActivity.class)); } super.onResume(); } }
Shell
UTF-8
336
3.328125
3
[]
no_license
#!/bin/bash if [ -z "$1" ] ; then echo "usage : $0 : <hosts files>" exit 1 fi files="$*" remote_dir="hadoop-dns" for host in $(cat $* | grep -v '#') do echo echo "==== $host ==== " rsync -avz --delete -e ssh a.jar run.sh $files "${host}:${remote_dir}" ssh $host "cd ${remote_dir} ; sh run.sh $files" done
Markdown
UTF-8
881
2.671875
3
[]
no_license
# Glozzom_bootstrap_website To see live this wesite here is the link -- https://sazidhabib.github.io/Glozzom_bootstrap_website/ This Bootstrap website design look like this images and it is completely Responsive website for every device. It have five page. Which is HOME, ABOUT US, SERVICES, BLOG, CONTACT. All are in this below.... ![1](https://user-images.githubusercontent.com/68610034/137854266-2e89a41d-dbc2-4065-bc7c-17d290ef9658.png) ![2](https://user-images.githubusercontent.com/68610034/137854290-2ac84fe8-2fd3-4ed3-9748-3c2f0e5dc0e6.png) ![3](https://user-images.githubusercontent.com/68610034/137854297-cb4fb43e-6f70-46bc-bc04-e9480defb96e.png) ![4](https://user-images.githubusercontent.com/68610034/137854300-c676e5c7-9832-4a42-a39b-5b3f99f01e43.png) ![5](https://user-images.githubusercontent.com/68610034/137854306-3835e93d-5cea-4f2c-aa9a-8b0898b12c65.png)
JavaScript
UTF-8
2,642
2.53125
3
[]
no_license
'use strict'; const AWS = require('aws-sdk') const db = new AWS.DynamoDB.DocumentClient({ apiVersion: '2012-08-10'}) const uuid = require('uuid').v4 const userTable = process.env.USER_TABLE function response(statusCode, message) { return { headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': true, }, statusCode: statusCode, body: JSON.stringify(message) } } //Create user module.exports.createUser = (event, context, callback) => { const reqBody = JSON.parse(event.body) const emptyTweets = [{}] const user = { id: uuid(), username: reqBody.username, password: reqBody.password, email: reqBody.email, tweets: emptyTweets, } return db.put({ TableName: userTable, Item: user }).promise().then(() => { callback(null, response(201, user)) }) .catch(err => response(null, response(err.statusCode, err))) } // Get all module.exports.getAllUsers = (event, context, callback) => { return db.scan({ TableName: userTable }).promise().then(res => { callback(null, response(200, res.Items)) }) .catch(err => callback(null, response(err.statusCode, err))) } // Get one module.exports.getUser = (event, context, callback) => { const id = event.pathParameters.id const params = { Key: {id: id}, TableName: userTable } return db.get(params).promise() .then(res => { if(res.Item) callback(null, response(200, res.Item)) else callback(null, response(404, {error: 'User not found'})) }) .catch(err => callback(null, response(err.statusCode, err))) } //Update // module.exports.updateUser = (event, context, callback) => { // const id = event.pathParameters.id // const body = JSON.parse(event.body) // const paramName = body.paramName // const paramValue = body.paramValue // const params = { // Key: {id: id}, // TableName: userTable, // ConditionExpression: 'attribute_exists(id)', // UpdateExpression: 'set ' + paramName + ' = :v', // ExpressionAttributeValues: { // ':v': paramValue // }, // ReturnValue: 'ALL_NEW' // } // return db.update(params) // .promise() // .then(res => { // callback(null, response(200, res)) // }) // .catch(err => callback(null, response(err.statusCode, err))) // } //Delete module.exports.deleteUser = (event, context, callback) => { const id = event.pathParameters.id const params = { Key: {id: id}, TableName: userTable } return db.delete(params) .promise() .then(() => callback(null, response(200, {message: 'User deleted'}))) .catch(err => callback(null, response(err.statusCode, err))) }
Go
UTF-8
3,795
3.078125
3
[ "Apache-2.0" ]
permissive
package values import ( "reflect" "testing" "github.com/cortezaproject/corteza-server/compose/types" ) func Test_sanitizer_Run(t *testing.T) { tests := []struct { name string kind string options map[string]interface{} input string output string outref uint64 }{ { name: "numbers should be trimmed", kind: "Number", input: " 42 ", output: "42", }, { name: "object reference should be processed", kind: "Record", input: " 133569629112020995 ", output: "133569629112020995", outref: 133569629112020995, }, { name: "object reference should be numeric", kind: "Record", input: " foo ", output: "", }, { name: "user reference should be processed", kind: "User", input: " 133569629112020995 ", output: "133569629112020995", outref: 133569629112020995, }, { name: "user reference should be numeric", kind: "User", input: " foo ", output: "", }, { name: "strings should be kept intact", kind: "String", input: " The answer ", output: " The answer ", }, { name: "booleans should be converted (t)", kind: "Bool", input: "t", output: "1", }, { name: "booleans should be converted (false)", kind: "Bool", input: "false", output: "0", }, { name: "booleans should be converted (garbage)", kind: "Bool", input: "%%#)%)')$)'", output: "0", }, { name: "dates should be converted to ISO", kind: "DateTime", input: "Mon Jan 2 15:04:05 2006", output: "2006-01-02T15:04:05Z", }, { name: "dates should be converted to UTC", kind: "DateTime", input: "2020-03-02T20:20:20+05:00", output: "2020-03-02T15:20:20Z", }, { name: "micro/mili seconds should be cut off", kind: "DateTime", input: "2020-03-11T11:20:08.471Z", output: "2020-03-11T11:20:08Z", }, { name: "number space trim", kind: "Number", input: " 42 ", output: "42", }, { name: "number negative", kind: "Number", input: "-42", output: "-42", }, { name: "number positive", kind: "Number", input: "+42", output: "42", }, { name: "number precision", kind: "Number", options: map[string]interface{}{"precision": 3}, input: "42.44455", output: "42.445", }, { name: "number precision; bigger precision then provided fracture", kind: "Number", options: map[string]interface{}{"precision": 3}, input: "42.4", output: "42.4", }, { name: "number precision; default to 0", kind: "Number", options: map[string]interface{}{}, input: "42.4", output: "42", }, { name: "number precision; clamped between [0, 6]", kind: "Number", options: map[string]interface{}{"precision": 10}, input: "42.5555555555", output: "42.555556", }, { name: "number precision; clamped between [0, 6]", kind: "Number", options: map[string]interface{}{"precision": -1}, input: "42.4", output: "42", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { s := sanitizer{} m := &types.Module{Fields: types.ModuleFieldSet{&types.ModuleField{Name: "testField", Kind: tt.kind, Options: tt.options}}} v := types.RecordValueSet{&types.RecordValue{Name: "testField", Value: tt.input}} o := types.RecordValueSet{&types.RecordValue{Name: "testField", Value: tt.output, Ref: tt.outref}} // Need to mark values as updated to trigger sanitization. v.SetUpdatedFlag(true) o.SetUpdatedFlag(true) if sanitized := s.Run(m, v); !reflect.DeepEqual(sanitized, o) { t.Errorf("\ninput value:\n%v\n\nresult of sanitization:\n%v\n\nexpected:\n%v\n", tt.input, sanitized, o) } }) } }
C#
UTF-8
2,045
2.546875
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace Tsumugi.Localize { public class LocalizationTexts { public static readonly string CannotFindJumpTarget = "Cannot find label {0} to jump to."; public static readonly string NotDefined = "{0} is not defined."; public static readonly string AlreadyUsedLabelName = "{0} has already been used as the label name."; public static readonly string CannotFindAttributeRequiredTag = "Cannot find attribute {0} which is required for tag {1}. "; public static readonly string ThisTokenMustBe = "In this token, it must be {0}, not {1}."; public static readonly string CannotConvertNumber = "Cannot convert {0} to an {1}."; public static readonly string NoAssociatedWith = "There is no {1} associated with {0}."; public static readonly string UnknownOperatorPrefix = "Unknown operator : {0}{1}"; public static readonly string UnknownOperatorInfix = "Unknown operator : {0} {1} {2}"; public static readonly string TypeMismatch = "Type mismatch : {0} {1} {2}"; public static readonly string UndefinedIdentifier = "Undefined identifier {0}."; public static readonly string NotFunction = "{0} is not a function."; public static readonly string NumberOfArgumentsDoesNotMatch = "Number of arguments to the function {0} does not match."; public static readonly string DoesNotSupportArgumentsOfType = "{0} does not support arguments of type {1}."; public static readonly string AssigningValuesNotAllowed = "Assigning values to other than identifiers is not allowed."; public static readonly string NoValueFoundForAttribute = "No value found for attribute {1} in {0} tag."; public static readonly string SyntaxError = "Syntax error."; public static readonly string ErrorInStructureIfTag = "Error in the structure of the if tag."; public static readonly string LexingPosition = "Lines: {0} Columns: {1} Position: {2}"; } }
PHP
UTF-8
7,642
2.515625
3
[]
no_license
<?php function PermissionPage() { require 'config.php'; mysql_connect($host, $name, $password); mysql_select_db($db); // Usage Permissions echo '<table width="70%" class="tborder">'; echo '<thead><tr><td class="thead"><strong>Usage Permissions:</strong></td></tr></thead>'; echo '<tbody><tr><td class="tcat">'; echo '<form action="admin.php?action=permission" method="post">'; echo '<strong>Username: <input type="hidden" name="permission_type" value="store_permission"><input type="text" name="permission_user" size="50"/><div style="float: right"><input type="submit" value="Add" name="permission_action" /><input type="submit" value="Remove" name="permission_action" /></div></strong></form></td></tr>'; echo '<tr><td class="trow1">'; $permitted = mysql_query("SELECT * FROM store_permission INNER JOIN mybb_users ON user_id = uid INNER JOIN mybb_userfields ON uid = ufid WHERE isBanned = '0' AND isAdmin = '0' AND isOfficial = '0' ORDER BY username ASC"); $numpermitted = mysql_num_rows($permitted); echo '<table border="0" width="100%">'; $i=0; while ($i < $numpermitted) { if ($i % 4 == 0) { echo '<tr>'; } echo '<td width="25%">'; $currusr = mysql_result($permitted,$i,"username"); $curradm = mysql_result($permitted,$i,"isAdmin"); $currcountry = mysql_result($permitted, $i, "fid5"); if ($currcountry != "") { echo '[<img width="15" height="10" src="../forum/images/flags/'.$currcountry.'.gif" alt="'.$currcountry.'" />] '; } echo ''.$currusr; if ($curradm == true) { echo '*'; } echo '</td>'; $i++; if ($i % 4 == 0) { echo '</tr>'; } } $remaining = $numpermitted % 4; while($remaining > 0) { echo '<td></td>'; $remaining--; } if ($numpermitted < 4) { echo '</tr>'; } echo '</table>'; echo '</td></tr>'; echo '</table>'; echo '<br/>'; // Store Permissions echo '<table width="70%" class="tborder">'; echo '<thead><tr><td class="thead"><strong>Store Permissions:</strong></td></tr></thead>'; echo '<tbody><tr><td class="tcat">'; echo '<form action="admin.php?action=permission" method="post">'; echo '<strong>Username: <input type="hidden" name="permission_type" value="store_permission"><input type="text" name="permission_user" size="50"/><input type="checkbox" name="permission_admin" />Administrator<input type="checkbox" name="permission_official" />Official Storer<div style="float: right"><input type="submit" value="Add" name="permission_action" /><input type="submit" value="Remove" name="permission_action" /></div></strong></form></td></tr>'; echo '<tr><td class="trow1">'; $permitted = mysql_query("SELECT * FROM store_permission INNER JOIN mybb_users ON user_id = uid INNER JOIN mybb_userfields ON uid = ufid WHERE isBanned = '0' AND isAdmin = '1' OR isOfficial = '1' ORDER BY username ASC"); $numpermitted = mysql_num_rows($permitted); echo '<table border="0" width="100%">'; $i=0; while ($i < $numpermitted) { if ($i % 4 == 0) { echo '<tr>'; } echo '<td width="25%">'; $currusr = mysql_result($permitted,$i,"username"); $curradm = mysql_result($permitted,$i,"isAdmin"); $currcountry = mysql_result($permitted, $i, "fid5"); if ($currcountry != "") { echo '[<img width="15" height="10" src="../forum/images/flags/'.$currcountry.'.gif" alt="'.$currcountry.'" />] '; } echo ''.$currusr; if ($curradm == true) { echo '*'; } echo '</td>'; $i++; if ($i % 4 == 0) { echo '</tr>'; } } $remaining = $numpermitted % 4; while($remaining > 0) { echo '<td></td>'; $remaining--; } if ($numpermitted < 4) { echo '</tr>'; } echo '</table>'; echo '</td></tr>'; echo '</table>'; echo '<br/>'; // Banned Users echo '<table width="70%" class="tborder">'; echo '<thead><tr><td class="thead"><strong>Banned Users:</strong></td></tr></thead>'; echo '<tbody><tr><td class="tcat">'; echo '<form action="admin.php?action=permission" method="post">'; echo '<strong>Username: <input type="hidden" name="permission_type" value="store_banned"><input type="text" name="permission_user" size="50"/><div style="float: right"><input type="submit" value="Add" name="permission_action" /><input type="submit" value="Remove" name="permission_action" /></div></strong></form></td></tr>'; echo '<tr><td class="trow1">'; $permitted = mysql_query("SELECT * FROM store_permission INNER JOIN mybb_users ON user_id = uid INNER JOIN mybb_userfields ON uid = ufid WHERE isBanned = TRUE ORDER BY username ASC"); $numpermitted = mysql_num_rows($permitted); echo '<table border="0" width="100%">'; $i=0; while ($i < $numpermitted) { if ($i % 4 == 0) { echo '<tr>'; } echo '<td width="25%">'; $currusr = mysql_result($permitted,$i,"username"); $currcountry = mysql_result($permitted, $i, "fid5"); if ($currcountry != "") { echo '[<img width="15" height="10" src="../forum/images/flags/'.$currcountry.'.gif" alt="'.$currcountry.'" />] '; } echo ''.$currusr; echo '</td>'; $i++; if ($i % 4 == 0) { echo '</tr>'; } } $remaining = $numpermitted % 4; while($remaining > 0) { echo '<td></td>'; $remaining--; } if ($numpermitted < 4) { echo '</tr>'; } if ($numpermitted == 0) { echo '<tr><td><i><smalltext>No user banned</smalltext></i></td></tr>'; } echo '</table>'; echo '</td></tr>'; echo '</table>'; mysql_close(); } function AddStorePermission($username, $isAdmin, $isBanned, $isStorer) { require 'config.php'; mysql_connect($host, $name, $password); mysql_select_db($db); $userResult = mysql_query("SELECT * FROM store_permission INNER JOIN mybb_users ON user_id = uid WHERE username = '".$username."'"); if (mysql_num_rows($userResult) > 0) { // Modify User $uid = mysql_result($userResult, 0, "uid"); $query = "UPDATE store_permission SET isAdmin = '".$isAdmin."', isBanned = '".$isBanned."', isOfficial = '".$isStorer."' WHERE user_id = '".$uid."'"; mysql_query($query); } else { // Insert User $userResult = mysql_query("SELECT * FROM mybb_users INNER JOIN mybb_userfields WHERE username = '".$username."'"); if (mysql_num_rows($userResult) > 0) { // Only if user really exists $uid = mysql_result($userResult, 0, "uid"); $query = "INSERT INTO store_permission (`user_id`, `isAdmin`, `isBanned`, `isOfficial`) VALUES ('".$uid."', '".$isAdmin."', '".$isBanned."', '".$isStorer."');"; mysql_query($query); } } mysql_close(); } function RemoveStorePermission($username, $banFlag) { require 'config.php'; mysql_connect($host, $name, $password); mysql_select_db($db); $userResult = mysql_query("SELECT * FROM store_permission INNER JOIN mybb_users ON user_id = uid WHERE username = '".$username."'"); if (mysql_num_rows($userResult) > 0) { $uid = mysql_result($userResult, 0, "uid"); if ($banFlag) { // Only Remove Ban Flag $query = "UPDATE store_permission SET isBanned = '0' WHERE user_id = '".$uid."'"; mysql_query($query); } else { // Remove the entire Entry mysql_query("DELETE FROM store_permission WHERE user_id = '".$uid."'"); } } mysql_close(); } ?>
Markdown
UTF-8
1,632
3.28125
3
[]
no_license
[frontMatter] title = "Simple Problem Redux" tags = ["reduce"] created = "2019-02-20 19:49:10" description = "" published = true [meta] swift_version = "5.0" --- We can now go back to our initial count & average problem and try to solve it with `reduce`. # InfoFromState, take two ``` Swift func infoFromState(state: String, persons: [[String: Any]]) -> (count: Int, age: Float) { // The type alias in the function will keep the code cleaner typealias Acc = (count: Int, age: Float) // reduce into a temporary variable let u = persons.reduce((count: 0, age: 0.0)) { (ac: Acc, p) -> Acc in // Retrive the state and the age guard let personState = (p["city"] as? String)?.componentsSeparatedByString(", ").last, personAge = p["age"] as? Int // make sure the person is from the correct state where personState == state // if age or state are missing, or personState!=state, leave else { return ac } // Finally, accumulate the acount and the age return (count: ac.count + 1, age: ac.age + Float(personAge)) } // our result is the count and the age divided by count return (age: u.age / Float(u.count), count: u.count) } print(infoFromState(state: "CA", persons: persons)) // prints: (count: 3, age: 34.3333) ``` As in earlier examples above, we\'re once again using a `tuple` to share state in the accumulator. Apart from that, the code is easy to understand. We also defined a `typealias` **Acc** within the `func` in order to simplify the type annotations a bit.
Java
UTF-8
3,153
2.3125
2
[]
no_license
package generalutils; import java.util.HashMap; import java.util.List; //import com.jayway.restassured.*; //import com.jayway.restassured.response.Response; import io.restassured.RestAssured; import io.restassured.response.Response; public class DataReset { public static boolean call(String apiKey, List<String> paramValues) { HashMap<String, String> dataResetURI = new HashMap<String, String>(); HashMap<String, String> apiCallMethod = new HashMap<String, String>(); // dataResetURI Map contains all the API's available for data reset dataResetURI.put("meterreadURI", "https://i-api.eon.de/sales/csc/test/v1/meterread?serialNo={0}&anlage={1}"); dataResetURI.put("getPasswordResetUrl", "https://i-api.eon.de/rex/resetpassword/v1?email={0}"); dataResetURI.put("resetCommunicationPopup", "https://i-api.eon.de/sales/csc/test/v1/popups/COMMUNICATION_PREFERENCES?xid={0}&action={1}"); dataResetURI.put("resetAdvertisingPopup", "https://i-api.eon.de/sales/csc/test/v1/advertismentPopup?xid={0}"); dataResetURI.put("resetDoubledPricePeriods", "https://i-api.eon.de/sales/csc/test/v1/doubledpriceperiods"); dataResetURI.put("resetAccountdata", "https://i-api.eon.de/sales/csc/test/v1/accountdata"); dataResetURI.put("resetBillingplan", "https://i-api.eon.de/sales/csc/test/v1/billingplan?crsId={0}"); dataResetURI.put("homemove", "https://i-api.eon.de/sales/csc/test/v1/homemove?crsId={0}"); dataResetURI.put("balance", "https://i-api.eon.de/sales/csc/test/v1/balance?crsId={0}&amount={1}"); dataResetURI.put("autoreg", "https://i-api.eon.de/sales/csc/test/v1/autoregaccount?identCode={0}"); // Different Method types of API calls apiCallMethod.put("meterreadURI", "GET"); apiCallMethod.put("getPasswordResetUrl", "GET"); apiCallMethod.put("resetCommunicationPopup", "PUT"); apiCallMethod.put("resetAdvertisingPopup", "PUT"); apiCallMethod.put("resetDoubledPricePeriods", "GET"); apiCallMethod.put("resetAccountdata", "GET"); apiCallMethod.put("resetBillingplan", "GET"); apiCallMethod.put("homemove", "GET"); apiCallMethod.put("balance", "POST"); apiCallMethod.put("autoreg", "PUT"); String apiTobePrepared = dataResetURI.get(apiKey); // Below loop is for replacing the place holders like {0),{1} in the URI for (int i = 0; i < paramValues.size(); i++) apiTobePrepared = apiTobePrepared.replace("{" + i + "}", paramValues.get(i)); System.out.println("CALLING API: " + apiTobePrepared); Response getResponse = null; if (apiCallMethod.get(apiKey).equalsIgnoreCase("GET")) { getResponse = RestAssured.given().auth().oauth2("Bearer a97899b8f1197a4b254ffbfe3f60c3") .get(apiTobePrepared); } if (apiCallMethod.get(apiKey).equalsIgnoreCase("PUT")) { getResponse = RestAssured.given().auth().oauth2("Bearer a97899b8f1197a4b254ffbfe3f60c3") .put(apiTobePrepared); } if (apiCallMethod.get(apiKey).equalsIgnoreCase("POST")) { getResponse = RestAssured.given().auth().oauth2("Bearer a97899b8f1197a4b254ffbfe3f60c3") .post(apiTobePrepared); } if (getResponse.getStatusCode() == 200) { return true; } else { return false; } } }
PHP
UTF-8
376
2.546875
3
[]
no_license
<?php /** * @author OnTheGo Systems */ /** * @author OnTheGo Systems */ interface OTGS_Log { /** * @param string $entry * @param int $level * @param array $extra_data * * @return */ public function add( $entry, $level, array $extra_data = array() ); /** * Get all entries * * @throws \OTGS_MissingAdaptersException */ public function get(); }
Markdown
UTF-8
735
2.609375
3
[ "MIT" ]
permissive
I have a work project which, for a variety of reasons, has a custom nginx build. We were already using the nginx compile-time option `--with-openssl-opt=enabled-weak-ciphers` (because currently, we need to support `3DES`) but we also wanted to enable TLS1.3 so we needed to add another compile-time option `--with-openssl-opt=enable-tls1_3`. We found that adding these two discretetely seemingly resulted in only the last `--with-openssl-opt=` taking effect. After a bit of tinkering/googling, we found that combining the two `--with-openssl-opt' statements into one worked, like this: ``` --with-openssl-opt='enable-weak-ssl-ciphers enable-tls1_3' ``` There is very little information on this on the web so I wanted to document it.
Markdown
UTF-8
3,027
2.84375
3
[]
no_license
--- tags: Bible, JST, NT, New_Translation, Old_Testament --- [[nt/Ezekiel/Ezekiel 3|<< Ezekiel 3]] | [[nt/Ezekiel|Ezekiel]] | [[nt/Ezekiel/Ezekiel 5|Ezekiel 5 >>]] ### Ezekiel 4 1 Thou also, son of man, take thee a tile, and lay it before thee, and portray upon it the city, even Jerusalem; ^1 2 And lay siege against it, and build a fort against it, and cast a mount against it; set the camp also against it, and set battering rams against it round about. ^2 3 Moreover, take thou unto thee an iron pan, and set it for a wall of iron between thee and the city; and set thy face against it; and it shall be besieged, and thou shalt lay siege against it. This shall be a sign to the house of Israel. ^3 4 Lie thou also upon thy left side and lay the iniquity of the house of Israel upon it; according to the number of the days that thou shalt lie upon it, thou shalt bear their iniquity. ^4 5 For I have laid upon thee the years of their iniquity, according to the number of the days, three hundred and ninety days; so shalt thou bear the iniquity of the house of Israel. ^5 6 And when thou hast accomplished them, lie again on thy right side; and thou shalt bear the iniquity of the house of Judah forty days; I have appointed thee each day for a year. ^6 7 Therefore, thou shalt set thy face toward the siege of Jerusalem, and thine arm shall be uncovered, and thou shalt prophesy against it. ^7 8 And behold, I will lay bands upon thee, and thou shalt not turn thee from one side to another till thou hast ended the days of thy siege. ^8 9 Take thou also unto thee wheat, and barley, and beans, and lentils, and millet, and fitches; and put them in one vessel, and make thee bread thereof, according to the number of the days that thou shalt lie upon thy side; three hundred and ninety days shalt thou eat thereof. ^9 10 And thy meat which thou shalt eat shall be by weight, twenty shekels a day; from time to time shalt thou eat it. ^10 11 Thou shalt drink also water by measure, the sixth part of a hin; from time to time shalt thou drink. ^11 12 And thou shalt eat it as barley cakes; and thou shalt bake it, with dung that cometh out of man, in their sight. ^12 13 And the Lord said, Even thus shall the children of Israel eat their defiled bread among the Gentiles, whither I will drive them. ^13 14 Then said I, Ah, Lord God! Behold, my soul hath not been polluted; for from my youth up even till now have I not eaten of that which dieth of itself or is torn in pieces; neither came there abominable flesh into my mouth. ^14 15 Then he said unto me, Lo, I have given thee cow\'s dung for man\'s dung, and thou shalt prepare thy bread therewith. ^15 16 Moreover, he said unto me, Son of man, behold, I will break the staff of bread in Jerusalem; and they shall eat bread by weight, and with care; and they shall drink water by measure, and with astonishment\-- ^16 17 That they may want bread and water, and be astonished one with another, and consume away for their iniquity. ^17
Ruby
UTF-8
1,120
2.640625
3
[]
no_license
class Adult < ActiveRecord::Base belongs_to :family_group, :dependent => :destroy belongs_to :editor, :class_name => "User", :foreign_key => "updated_by" before_validation :set_income, :format_rut after_validation :titleize_name validates_presence_of :fathers_name, :mothers_name, :names, :sex validates_inclusion_of :sex, :in => %w{M F} validates_numericality_of :income def fullname fathers_name+" "+mothers_name+", "+names end def self.find_by_name(criteria) terms = criteria.split.collect do |word| "%#{word.downcase}%" end find(:all, :conditions => [ ( ["(concat(names, ' ', fathers_name, ' ', mothers_name) LIKE ?)"] * terms.size ).join(" AND "), * terms.flatten ]) end def is_guardian? is_guardian end def is_guardian self == self.family_group.guardian end def set_income self.income ||= 0 end def format_rut self.run.gsub!(/[.]/,'') end def titleize_name self.names = self.names.titleize self.fathers_name = self.fathers_name.titleize self.mothers_name = self.mothers_name.titleize end end
PHP
UTF-8
6,620
3.09375
3
[]
no_license
<?php class User { public $Username; public $Password; public $Fname; public $Lname; public $Library_Card; public $Phone; public $Email; public $is_Admin; public function __construct(String $Username, STring $Password, String $Fname, String $Lname, String $Library_Card, String $Phone, String $Email, int $is_Admin) { $this->Username = $Username; $this->Password = $Password; $this->Fname = $Fname; $this->Lname = $Lname; $this->Library_Card = $Library_Card; $this->Phone = $Phone; $this->Email = $Email; $this->is_Admin = $is_Admin; } public static function parseUser($row) { $Username = $row['Username']; $Password = $row['User_Password']; $FName = $row['User_Fname']; $LName = $row['User_Lname']; $Library_Card = $row['Library_Card']; $Phone = $row['Phone']; $Email = $row['Email']; $is_Admin = $row['is_Admin']; return new User($Username, $Password, $FName, $LName, $Library_Card, $Phone, $Email, $is_Admin); } public static function getUser($Username) { global $conn; $sql = "SELECT * FROM Users WHERE Username = ?"; $params = array( &$Username); $results = sqlsrv_query($conn, $sql, $params); $row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC); if ($row) { return User::parseUser($row); } return null; } } class Author { public $authorID; public $authorFName; public $authorLName; public function __construct(int $authorID, String $authorFName, String $authorLName) { $this->authorID = $authorID; $this->authorFName = $authorFName; $this->authorLName = $authorLName; } public static function parseAuthor($row) { $authorID = $row['Author_ID']; $FName = $row['Auth_Fname']; $LName = $row['Auth_Lname']; return new Author($authorID, $FName, $LName); } public static function getAuthor($authorID) { global $conn; $sql = "SELECT * FROM Author WHERE Author_ID = ?"; $params = array( &$authorID); $results = sqlsrv_query($conn, $sql, $params); $row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC); if ($row) { return Author::parseAuthor($row); } return null; } public function __toString() { return strval($this->authorID) . ":" . $this->authorFName . ":" . $this->authorLName; } } class Book { public $ISBN; public $Book_Title; public $authorID; public $genre; public $pYear; public $country; public $pageCount; public function __construct(int $ISBN, String $Book_Title, int $authorID, String $genre, int $pYear, String $country, int $pageCount) { $this->ISBN = $ISBN; $this->Book_Title = $Book_Title; $this->authorID = $authorID; $this->genre = $genre; $this->pYear = $pYear; $this->country = $country; $this->pageCount = $pageCount; } public static function parseBook($row) { $ISBN = $row['ISBN']; $Book_Title = $row['Book_Title']; $authorID = $row['Author_ID']; $genre = $row['Genre']; $pYear = $row['Publication_Year']; $country = $row['Country']; $pageCount = $row['Page_Count']; return new Book($ISBN, $Book_Title, $authorID, $genre, $pYear, $country, $pageCount); } public static function getBook($ISBN) { global $conn; $sql = "SELECT * FROM Book WHERE ISBN = ?"; $params = array( &$ISBN); $results = sqlsrv_query($conn, $sql, $params); if (!$results) { return null; } if ($row = sqlsrv_fetch_array( $results, SQLSRV_FETCH_ASSOC)) { return Book::parseBook($row); } return null; } public function Author() { return Author::getAuthor($this->authorID); } public function __toString() { return strval($this->ISBN) . ":" . $this->Book_Title . ":" . strval($this->authorID) . ":" . $this->genre . ":" . strval($this->pYear) . ":" . $this->country . ":" . strval($this->pageCount); } } class BookStock { public $BookID; public $ISBN; public $inStock; public function __construct(int $BookID, int $ISBN, int $inStock) { $this->BookID = $BookID; $this->ISBN = $ISBN; $this->inStock = $inStock; } public static function parseBookStock($row) { $BookID = $row['Book_ID']; $ISBN = $row['ISBN']; $inStock = $row['In_Stock']; return new BookStock($BookID, $ISBN, $inStock); } public function checkoutBook() { return checkoutBookID($this->BookID); } public function Book() { return Book::getBook($this->ISBN); } public function __toString() { return strval($this->BookID) . ":" . strval($this->ISBN) . ":" . strval($this->inStock); } } class Checkout { public $Checkout_ID; public $Username; public $Book_ID; public $Checkout_Date; public $Return_Date; public $Actual_Return_Date; // This can be null public function __construct(int $Checkout_ID, String $Username, int $Book_ID, $Checkout_Date, $Return_Date, $Actual_Return_Date) { $this->Checkout_ID = $Checkout_ID; $this->Username = $Username; $this->Book_ID = $Book_ID; $this->Checkout_Date = $Checkout_Date; $this->Return_Date = $Return_Date; $this->Actual_Return_Date = $Actual_Return_Date; } public static function parseCheckout($row) { $Checkout_ID = $row['Checkout_ID']; $Username = $row['Username']; $Book_ID = $row['Book_ID']; $Checkout_Date = $row['Checkout_ID']; $Return_Date = $row['Return_Date']; $Actual_Return_Date = $row['Actual_Return_Date']; return new Checkout($Checkout_ID, $Username, $Book_ID, $Checkout_Date, $Return_Date, $Actual_Return_Date); } public function User() { return User::getUser($Username); } public function __toString() { return strval($this->Checkout_ID) . ":" . $this->Username . ":" . strval($this->Book_ID) . ":" . $this->Checkout_Date . ":" . $this->Return_Date . ":" . $this->Actual_Return_Date; } } class Transaction { public $Checkout_ID; public $Amount_Paid; public function __construct(int $Checkout_ID, float $Amount_Paid) { $this->Checkout_ID = $Checkout_ID; $this->Amount_Paid = $Amount_Paid; } public static function parseTransaction($row) { $Checkout_ID = $row['Checkout_ID']; $Amount_Paid = $row['Amount_Paid']; return new Transaction($Checkout_ID, $Amount_Paid); } public function __toString() { return strval($this->Checkout_ID) . ":" . strval($this->Amount_Paid); } } ?>
Python
UTF-8
4,131
2.71875
3
[]
no_license
""" verinfo = グラフ表示 ver1.1 2018.11.18 check for ITC27 ver1.0 2018.11.** Developing codes by H.Tsuchiya (NIFS) """ import numpy as np from matplotlib import pyplot as plt from mpl_toolkits.mplot3d.axes3d import Axes3D #公開する関数を指定する __all__ = ['SAVE_FIGURE_1',\ 'SAVE_FIGURE_2',\ 'SAVE_FIGURE_4',\ 'SAVE_FIGURE_4_ITC',\ 'CHECK_3D_PROFILE',\ 'SAVE_2D_FIGURE' ]; def SAVE_FIGURE_1(data,text,text1): x = np.arange(data[0].shape[0]) fig = plt.figure() for g in data: plt.plot(x,g) plt.suptitle(text+"_"+text1) plt.savefig(text+".png") plt.close(fig) #plt.show() def SAVE_FIGURE_2(dat1,dat2,text,text1): xa = np.arange(dat1[0].shape[0]) xb = np.arange(dat2[0].shape[0]) fig = plt.figure() ax1 = fig.add_subplot(2,1,1) for y in dat1: ax1.plot(xa,y) ax2 = plt.subplot(2,1,2) for y in dat2: ax2.plot(xb,y) fig.suptitle(text+"_"+text1) fig.savefig(text+".png") plt.close(fig) #plt.show() def SAVE_FIGURE_4(dat1,dat2,dat3,dat4,text,text1): x1 = np.arange(dat1[0].shape[0]) x2 = np.arange(dat2[0].shape[0]) x3 = np.arange(dat3[0].shape[0]) x4 = np.arange(dat4[0].shape[0]) fig = plt.figure() ax1 = fig.add_subplot(2,2,1) for y in dat1: ax1.plot(x1,y) ax2 = plt.subplot(2,2,2) for y in dat2: ax2.plot(x2,y) ax3 = plt.subplot(2,2,3) for y in dat3: ax3.plot(x3,y) ax4 = plt.subplot(2,2,4) for y in dat4: ax4.plot(x4,y) fig.suptitle(text+"_"+text1) fig.savefig(text+".png") plt.close(fig) #plt.show() def SAVE_FIGURE_4_ITC(dat1,dat2,dat3,dat4,text,text1): x1 = np.arange(dat1[0].shape[0]) x2 = np.arange(dat2[0].shape[0]) x3 = np.arange(dat3[0].shape[0]) x4 = np.arange(dat4[0].shape[0]) fig = plt.figure() ax1 = fig.add_subplot(2,2,1) ax1.plot(x1,dat1[0],linewidth=3.0,label="reconstructed f",color="c") ax1.plot(x1,dat1[1],linewidth=1.5,label="assumed f",linestyle="--",color="r") ax1.legend(loc='uppper right', bbox_to_anchor=(-1.0, 0.5, 0.5, .100), ) ax2 = plt.subplot(2,2,2) ax2.plot(x2,dat2[0],linewidth=3.0,label="reconstructed f",color="c") ax2.plot(x2,dat2[1],linewidth=1.5,label="assumed f",linestyle="--",color="r") ax2.set_ylim([-0.15,0.15]) ax3 = plt.subplot(2,2,3) ax3.plot(x3,dat3[0],marker="o",linewidth=3.0,label="reconstructed g",color="c") ax3.plot(x3,dat3[1],label="assumed g",linestyle="--",color="r") ax4 = plt.subplot(2,2,4) ax4.plot(x4,dat4[0],marker="o",linewidth=3.0,label="reconstructed g",color="c") ax4.plot(x4,dat4[1],label="assumed g",linestyle="--",color="r") fig.suptitle(text+"_"+text1) fig.savefig(text+".png") plt.close(fig) #plt.show() def CHECK_3D_PROFILE(xyz,f,text,text1): fig = plt.figure() ax = Axes3D(fig) x = xyz[:,0] y = xyz[:,1] z = xyz[:,2] p = ax.scatter(x,y,z,c=f,cmap='Blues') fig.colorbar(p) fig.savefig(text+".png") plt.close(fig) def SAVE_2D_FIGURE(dat,text,text1): fig = plt.figure() plt.imshow(dat,cmap="GnBu_r") #plt.xlabel(L1) #plt.ylabel(L0) plt.colorbar() plt.savefig(text+".png") plt.close(fig) if __name__ == "__main__": x = np.arange(-1.0,1.0,0.1) y0 = np.sin(np.pi * x) y1 = np.cos(np.pi * x) y2 = y0*y0 y3 = y1*y1 SAVE_FIGURE_1([y0,y1],"fig1","comment1") SAVE_FIGURE_2([y0,y1],[y2,y3],"fig2","comment2") SAVE_FIGURE_4([y0,y1],[y2,y3],[y0,y2],[y1,y3],"fig4","comment4") z = np.reshape(y0,(4,5)) SAVE_2D_FIGURE(z,"fig_2d","comment_2d") xyz = np.array( [(i,j,k) for i in range(10) for j in range(10) for k in range(10) ]) f = np.empty((xyz.shape[0])) for i in range(xyz.shape[0]): f[i]= np.exp(-np.linalg.norm(xyz[i])/10) CHECK_3D_PROFILE(xyz,f,"fig_3d","comment_3d")
Java
UTF-8
632
3.65625
4
[]
no_license
package lesson2; public class LambdaMain { public static void main(String[] args) { int a = 5; int b = 10; MyFunction f = new MyFunctionImpl(); MyFunction f2 = new MyFunction() { @Override public int apply(int a, int b) { return a + b; } }; MyFunction f3 = (a1, b1) -> { return a1 + b1; }; MyFunction f4 = Integer::sum; System.out.println(f.apply(a, b)); } } class MyFunctionImpl implements MyFunction { @Override public int apply(int a, int b) { return a + b; } }
Java
UTF-8
269
2.6875
3
[]
no_license
package com.zjn.designpattern.creative.factorymethod; /** * ProductB 借用简单工厂包中Product * * @author zjn * @date 2019/8/28 **/ public class ProductB implements Product { public ProductB(){ System.out.println("生产产品B"); } }
Markdown
UTF-8
4,841
2.859375
3
[]
no_license
``` 业精于勤而荒于戏,行成于思而毁于随。 ``` #### TOF(Time of Flight)基本原理 ToF是Time of Flight的缩写,直译为飞行时间,通过给目标发送光,然后用传感器**接收从物体返回的光**,通过探测这些发射和接收光脉冲的**飞行(往返)时间**来得到**目标物距离**。 #### TOF相机的一般组成 ToF相机与普通相机成像过程类似,主要由**光源、感光芯片、镜头、传感器、驱动控制电路以及处理电路**等几部分关键单元组成。 ToF相机包括两部分核心模块,`发射照明模块`和`感光接收模块`,根据这两大核心模块之间的相互关联来生成深度信息。ToF相机的感光芯片根据像素单元的数量也分为`单点`和`面阵式`感光芯片,为了测量整个三维物体表面位置深度信息,可以利用单点ToF相机通过逐点扫描方式获取被探测物体三维几何结构,也可以通过面阵式ToF相机,拍摄一张场景图片即可实时获取整个场景的表面几何结构信息,面阵式ToF相机更易受到消费类电子系统搭建的青睐 TOF的照射单元都是对光进行高频调制之后再进行发射,一般采用LED或激光(包含激光二极管和VCSEL)来发射高性能脉冲光 #### 飞行时间的两种常见方案 ##### 脉冲式激光测距 ``` L = c Δt/2 ``` *L*为测量距离, *c*为光在空气中传播的速度, Δ*t*为光波信号在测距仪与目标往返的时间 可见此方式对时钟要求很高。 脉冲激光的发射角小,能量在空间相对集中,瞬时功率大,利用这些特性可制成各种中远距离激光测距仪、激光雷达等。目前,脉冲式激光测距广泛应用在地形地貌测量、地质勘探、工程施工测量、飞行器高度测量、人造地球卫星相关测距、天体之间距离测量等遥测技术方面 ##### 相位式激光测距(连续式) ``` 2L=ϕ⋅c⋅T/2π ``` 式中*L*为测量距离,*c*为光在空气中传播的速度,*T*为调制信号的周期时间, *ϕ*为发射与接收波形的相位差。 特点是只能测试出一个周期内的距离,为解决这个问题可以使用多个频率 发射一束照明光,利用发射光波信号与反射光波信号的**相位变化**来进行距离测量。其中,照明模组的波长一般是红外波段,且需要进行高频率调制。ToF感光模组与普通手机摄像模组类似,由芯片,镜头,线路板等部件构成,ToF感光芯片每一个像元对发射光波的往返相机与物体之间的`具体相位`分别进行录,通过数据处理单元提取出`相位差`,由公式计算出深度信息。该芯片传感器结构与普通手机摄像模组所采用的CMOS图像传感器类似,但更复杂一些,它包含`调制控制单元`,`A/D转换单元`,`数据处理单元`等,因此ToF芯片像素比一般图像传感器像素尺寸要大得多,一般20um左右。也需要一个搜集光线的镜头,不过与普通光学镜头不同的是这里需要加一个`红外带通滤光片`来保证`只有与照明光源波长相同`的光才能进入。由于光学成像系统不同距离的场景为各个`不同直径的同心球面`,而非平行平面,所以在实际使用时,需要后续数据处理单元对这个误差进行校正。ToF相机的`校正`是生产制程中必不可少的最重要的工序,没有校正工序,ToF相机就无法正常工作。 #### 连续式正弦波调制测距原理推导 波形示意图 ![](img/2.png) - 发射波s(t),接收波r(t) ``` s(t) = a * (1+sin(2πft)) ``` ``` r(t) = A *(1+sin(2πf(t-Δt))) + B ``` ![](img/3.png) 优点: 1. 相位偏移(公式5)中的(r2-r0)和(r1-r3)相对于脉冲调试法消除了由于测量器件或者环境光引起的固定偏差。 2. 可以根据接收信号的振幅A和强度偏移B来间接的估算深度测量结果的精确程度(方差)。 3. 不要求光源必须是短时高强度脉冲,可以采用不同类型的光源,运用不同的调制方法 缺点: 1. 需要多次采样积分,测量时间较长,限制了相机的帧率 2. 需要多次采样积分,测量运动物体时可能会产生运动模糊。 #### TOF优点 - 体积小,误差小 TOF相机要求接收端与发射端尽可能的接近,越接近,由于发射、接收路径不同而带来的误差就越小,从体积紧凑角度来讲有着天然的优势; - 直接输出深度信息 TOF可以直接输出深度信息,不需要类似双目立体视觉或者结构光等需要通过算法计算来获得深度信息。 - 抗干扰强 TOF不受表面灰度和特征影响,太阳光由于没有经过调制,所以TOF抗强光能力也较好
Markdown
UTF-8
6,017
3.125
3
[]
no_license
+++ date = "2015-08-29T18:15:08-05:00" title = "Grails Example Project" categories = ["techtalk","code","grails"] tags = ["josdem","techtalks","programming","technology","grails"] description = "Simple project in Grails" +++ Simple project in Grails ## Project user story As application owner I want to deliver my application installer so the client can download it. ## Acceptance Criteria * I need to know how many downloads I have by installer * Installers are Linux, Ubuntu, Mac and Windows * I need to know what is the client IP address As first step, I’m going to create a project as follow: ```bash grails create-app operating-system-downloader-stat ``` Next, I’m going to create a Domain as follow: ```bash grails create-domain-class com.tim.Downloader ``` This domain Downloader will store download stats by operating system, it looks like this: ```groovy package com.tim class Downloader { Date dateCreated String address InstallerType type static constraints = { address blank:false,size:5..255 } } ``` ## About Domain * Grails will create an "downloader" table * If you define an property "dateCreated" it will set current date at creating new instances * Grails will validate "address" is not empty and a size between 5 and 255 * InstallerType is an enum and I need to define it in src/groovy/ folder ## Creating enum Create path src/groovy/com/tim Create InstallerType enum as follow: ```groovy package com.tim enum InstallerType { LINUX, MAC, UBUNTU, WINDOWS } ``` ## Creating controller In order to create a controller we need to start grails application, type this: ```bash grails ``` And then: ```bash create-controller com.tim.DownloaderController ``` ## Creating service Services are transactional by default in Grails and is intended contains business logic, in order to create a service type: ```bash grails ``` And then: ```bash create-service com.tim.DownloaderService ``` ## Unit testing Now we are ready to write unit test and let the test guide us to the solution, we are going to start with DownloaderControllerSpec.groovy which is located in test/unit/com/tim ```groovy package com.tim import grails.test.mixin.TestFor import spock.lang.Specification @TestFor(DownloaderController) class DownloaderControllerSpec extends Specification { DownloaderService downloaderService = Mock(DownloaderService) String address = "127.0.0.1" def setup(){ controller.downloaderService = downloaderService } void "should count ubuntu download"() { when: controller.downloadUbuntuVersion() then: 1 * downloaderService.createUbuntuStat(address) } } ``` ## DownloaderControllerSpec facts * DownloaderService is a mock, needs to be that way since we are trying to test DownloaderController * The purpose "def setup()" method is execute code before any test is called * We assigned downloaderService to the controller in line 11 * When we call controller.downloadUbuntuVersion() we expect to call downloaderService.createUbuntuStat() once You can run unit tests by typing in your command line: ```bash grails test-app :unit ``` Now is time to set business logic which is create a record any time someone download an ubuntu version, so let’s our DownloaderServiceSpec lead us to the light ```groovy package com.tim import grails.test.mixin.TestFor import spock.lang.Specification @TestFor(DownloaderService) class DownloaderControllerSpec extends Specification { void "should create a ubuntu download stat"() { when: def downloader = service.createUbuntuStat("127.0.0.1") then: downloader.address == "127.0.0.1" downloader.type == InstallerType.UBUNTU } } ``` ## DownloaderServiceSpec facts * When we call service.createUbuntuStat("127.0.0.1") we are expecting that service returns an downloader object * Then we verify that object contains "127.0.0.1" as address and UBUNTU as InstallerType That’s it, the first part of the story is complete, we know what is the client IP address and when an Ubuntu package is downloaded. Next step is to deliver my Ubuntu package as downloader file, let’s return to our DownloaderControllerSpec ```groovy package com.tim import grails.test.mixin.TestFor import spock.lang.Specification @TestFor(DownloaderController) class DownloaderControllerSpec extends Specification { DownloaderService downloaderService = Mock(DownloaderService) String address = "127.0.0.1" def setup(){ controller.downloaderService = downloaderService } void "should count ubuntu download"() { when: controller.downloadUbuntuVersion() then: 1 * downloaderService.createUbuntuStat(address) response.contentType == "application/octet-stream" response.getHeader("Content-disposition") =="attachment;filename=JMetadata.deb" } } ``` ## DownloaderServiceSpec modifications * Now we are expecting that ContentType is application/octet-stream * The intended purpose is to be saved to disk as "arbitrary binary data" * We are expecting that Content-disposition is an attachment named JMetadata.deb Now is time to see the DownloadController and DownloadService implementations ## DownloaderController ```groovy package com.tim class DownloaderController { def DownloaderService downloaderService def downloadUbuntuVersion(){ downloaderService.createUbuntuStat(request.getRemoteAddr()) def file = new File("/home/josdem/.jmetadata/JMetadata.deb") response.setContentType("application/octet-stream") response.setHeader("Content-disposition","attachment;filename=${file.getName()}") response.outputStream << file.newInputStream() } } ``` ## DownloaderService ```groovy package com.tim import grails.transaction.Transactional @Transactional class DownloaderService { def Downloader createUbuntuStat(String address){ def downloader = new Downloader() downloader.address = address downloader.type = InstallerType.UBUNTU downloader.save() } } ``` [Return to the main article](/techtalk/grails)
Markdown
UTF-8
6,454
3.15625
3
[]
no_license
# cdeps Clojure + deps.edn, a basic guide. After a rather long break from programming and Clojure I decided give them another go. When it comes to managing Clojure projects, [Leiningen](https://leiningen.org/) is de-facto standard tool. Recently, [Clojure CLI tools](https://clojure.org/guides/deps_and_cli) are becoming more and more popular, though. Switching to yet-another-build-tool doesn't have any pragmatic value, but it's perfect for learning purposes. From a build tool I expect it to perform certain tasks: 1. Creating a project. 1. Managing source and tests paths. 1. Managing dependencies. 1. Running tests. 1. Building a self-contained JAR, a.k.a. uberjar. 1. Managing outdated dependencies. Let's see how it's performed using Clojure CLI tools, a.k.a. deps.edn. ## Creating a project Leiningen allows to generate a project structure simply by invoking: ```bash $ lein new [template] [project-name] ``` We get a lot for free, but is it really needed? How is it done with Clojure CLI tools? Imagine a simple project. It allows add and divide numbers, it also prints some example calculations when invoked. We can start by simply creating a new directory: ```bash $ mkdir cdeps && cd cdeps ``` Now, let's add an empty `deps.edn` file: ```clojure ;; /deps.edn {} ``` And now we can start adding some actual code to the project. ## Managing source and tests paths To demonstrate the feature of managing source paths we will put our code at `src/main/clojure`. ```bash $ mkdir -p src/main/clojure ``` `deps.edn` is no magic so we can just set the path in the file: ```clojure ;; deps.edn {:paths ["src/main/clojure"]} ``` Now, we can write the calculator code: ```clojure ;; src/main/clojure/com/tomekw/cdeps/calculator.clj (ns com.tomekw.cdeps.calculator) (defn plus [a b] (+ a b)) (defn divide [a b] (/ a b)) ``` ## Managing dependencies In such a simple project there is no real need to add external dependencies. We can always specify the Clojure version we would like to use, though: ```clojure ;; deps.edn {:paths ["src/main/clojure"] :deps {org.clojure/clojure {:mvn/version "1.10.1"}}} ``` Clojure CLI tools allow to specify local and git dependencies too, see [documentation and more examples](https://clojure.org/guides/deps_and_cli#_using_local_libraries). ## Running tests The calculator we wrote is super simple but we can still write some tests: ```clojure ;; test/main/clojure/com/tomekw/cdeps/calculator_test.clj (ns com.tomekw.cdeps.calculator-test (:require [clojure.test :refer :all] [com.tomekw.cdeps.calculator :refer :all])) (deftest adding-numbers (is (= 4 (plus 2 2)))) (deftest dividing-numbers (is (= 2 (divide 4 2)))) (deftest dividing-numbers-by-zero (is (thrown? ArithmeticException (divide 1 0)))) ``` Now we need to run them to make sure they pass. We have to add an alias (a command we will run), and a test runner, as an extra dependency. I picked [kaocha](https://github.com/lambdaisland/kaocha). Also, we need to tell the runner where the tests are located: ```clojure ;; deps.edn {:paths ["src/main/clojure"] :deps {org.clojure/clojure {:mvn/version "1.10.1"}} :aliases {:test {:extra-paths ["test/main/clojure"] :extra-deps {lambdaisland/kaocha {:mvn/version "0.0-529"}} :main-opts ["-m" "kaocha.runner"]}}} ``` Here is the test report: ```bash $ clj -Atest [(...)] 3 tests, 3 assertions, 0 failures. ``` ## Building a self-contained JAT, a.k.a. uberjar Presume, we would like to print example calculations to the console. Let's add the code to do that: ```clojure ;; src/main/clojure/com/tomekw/cdeps/core.clj (ns com.tomekw.cdeps.core (:gen-class) (:require [com.tomekw.cdeps.calculator :refer :all])) (defn -main [& args] (do (println (format "2 + 2 is %s" (plus 2 2))) (println (format "4 / 2 is %s" (divide 4 2))))) ``` To run the main function we can invoke the following command: ```bash $ clj -m com.tomekw.cdeps.core 2 + 2 is 4 4 / 2 is 2 ``` It could be burdensome for the users of our calculator to install Clojure. To avoid this, we can package our project as a standalone Java JAR. There is number of tools to do that, like [cambada](https://github.com/luchiniatwork/cambada), but I've decided to try out [uberdeps](https://github.com/tonsky/uberdeps). Let's add a proper configuration first: ```clojure ;; deps.edn {:paths ["src/main/clojure"] :deps {org.clojure/clojure {:mvn/version "1.10.1"}} :aliases {:test {:extra-paths ["test/main/clojure"] :extra-deps {lambdaisland/kaocha {:mvn/version "0.0-529"}} :main-opts ["-m" "kaocha.runner"]} :uberjar {:extra-deps {uberdeps {:mvn/version "0.1.4"}} :main-opts ["-m" "uberdeps.uberjar" "--target" "target/cdeps-0.1.0.jar"]}}} ``` To package the project we simply run: ```bash $ clj -Auberjar [uberdeps] Packaging target/cdeps-0.1.0.jar... + src/main/clojure/** + org.clojure/clojure 1.10.1 . org.clojure/core.specs.alpha 0.2.44 . org.clojure/spec.alpha 0.2.176 [uberdeps] Packaged target/cdeps-0.1.0.jar in 567 ms ``` And now we can run the project with Java: ```bash $ java -cp target/cdeps-0.1.0.jar clojure.main -m com.tomekw.cdeps.core 2 + 2 is 4 4 / 2 is 2 ``` ## Managing outdated dependencies It's often needed to manage the versions of all dependencies we put into our `deps.edn` file. There is a tool named [depot](https://github.com/Olical/depot): ```clojure ;; deps.edn {:paths ["src/main/clojure"] :deps {org.clojure/clojure {:mvn/version "1.10.1"}} :aliases {:test {:extra-paths ["test/main/clojure"] :extra-deps {lambdaisland/kaocha {:mvn/version "0.0-529"}} :main-opts ["-m" "kaocha.runner"]} :outdated {:extra-deps {olical/depot {:mvn/version "1.8.4"}} :main-opts ["-m" "depot.outdated.main" "-a" "outdated"]} :uberjar {:extra-deps {uberdeps {:mvn/version "0.1.4"}} :main-opts ["-m" "uberdeps.uberjar" "--target" "target/cdeps-0.1.0.jar"]}}} ``` Everything should be up to date: ```bash $ clj -Aoutdated All up to date! ``` ## Summary This guide covers basic use-cases in the daily workflow with Clojure. Of course there is alwats more than I presented here, like deploying the project to [Clojars](https://clojars.org). The process is still not fully automated and I will try to cover it with the next post.
C++
UTF-8
806
3.109375
3
[]
no_license
class Solution { public: vector<string> ans; void dfs(vector<vector<char>>& space, int depth, string& s) { if (depth == space.size()) { ans.push_back(s); return; } for (auto j : space[depth]) { s.push_back(j); dfs(space, depth + 1, s); s.pop_back(); } } vector<string> letterCombinations(string digits) { if (digits.empty()) return {}; vector<vector<char>> v = { {},{},{'a','b','c'},{'d','e','f'},{'g','h','i'}, {'j','k','l' },{'m','n','o' },{'p','q','r','s'},{'t','u','v'},{'w','x','y','z'} }; vector<vector<char>> space; for (auto i : digits) space.push_back(v[(int)(i-'0')]); string s; dfs(space, 0, s); return ans; } };
Markdown
UTF-8
1,690
2.828125
3
[]
no_license
# OAuth_Assignment_SSD This repository created for SSD Assignment 2. This assignment mainly tested the knowledge of the OAuth 2.0. Authorization is a security way to access the levels or user privileges related to the system resources such as services, programs, data information and files. OAuth 2.0 is the authorization industry standard protocol. It mainly focusing on the client developers. It provides more specific authorization flows for applications like mobile applications, desktop applications, web applications. It is an authorization framework that used to applications obtain limited access to user accounts on a HTTP service, such as Facebook and GitHub. I created the web application which is called as OWA that enables to upload the certain files into the google drive. # Set Up the Client ID,Client Secret ID using Google develop Console # Clone the Project 1.Setting up the Google Developer Console. 2.Clone this repository. 3.Add the project in the WAMPP SERVER -> www-> add your folder. # Open the Visual Studio Code 1. Go to the www-> your project 2. Select your Project 3. By using .code Command open the vs code from that location. 4. run the Source code file(first.html) Using "http://localhost/SSDOAuthAssignment/first.html" # Run the App 1. Click the " Signin by using Google Account" 2. Accept the necessary permissions. 3. After Successfully suthorize it will navigate to the File upload page # File Upload Page 1.Click the "Choose Files" Button. 2. After select the file Clicks the "upload" Button. 3. File is successfully uploaded by prompt up the sucess ful message with progress bar. For more details refer the report. # Thankyou
Ruby
UTF-8
1,404
2.609375
3
[]
no_license
class Rental < ApplicationRecord belongs_to :customer belongs_to :movie validates :customer_id, presence: { message: "Customer ID is required." }, numericality: {only_integer: true, message: "Customer ID must be an integer."} validates :movie_id, presence: { message: "Movie ID is required."}, numericality: {only_integer: true, message: "Movie ID must be an integer."} validates :due_date, presence: { message: "Due date is required." } validates :checkout_date, presence: { message: "Checkout date is required." } def self.available?(movie_id) inventory = Movie.find_by(id: movie_id.to_i).inventory currently_rented = Rental.currently_rented(movie_id.to_i) return true if currently_rented.length < inventory return false end def self.currently_rented(movie_id) return Rental.where(movie_id: movie_id.to_i, checkin_date: nil) end def self.overdue overdue_rentals = Rental.where(checkin_date: nil).where('due_date < ?', Date.today) overdue = overdue_rentals.map { |rental| { "title" => rental.movie.title, "customer_id" => rental.customer_id, "name" => rental.customer.name, "postal_code" => rental.customer.postal_code, "checkout_date" => rental.checkout_date, "due_date" => rental.due_date } } return overdue end end
PHP
UTF-8
1,568
3
3
[]
no_license
<?php namespace Application\Form; use Application\Form\Base\FormAdapter; use Application\OCISchema\Util\Cipher; use Application\Util\Validator; /** * Description of LogIn * * @author Roman */ class LogIn extends FormAdapter { //Properties of LogIn public $userId; public $password; /** * Constructor * * @param Array $data */ public function __construct($data = null) { if ($data !== null) { foreach ($data as $key => $value) { if (\property_exists(__CLASS__, $key)) { $this->$key = $value; } } } } /** * Validates the model * * @return boolean|Array */ public function isValid() { $validator = Validator::getInstance(); $resultValidation = $validator->validateArray( $this->getData(), array( array("name" => "userId", "rules" => array("required")), array("name" => "password", "rules" => array("required")) ) ); if ($resultValidation === false) { return true; } else { return $resultValidation; } } /** * Gets teh password encrypted * * @return String */ public function getPasswordEncrypted() { $password = ""; if ($this->password !== "") { $password = Cipher::encrypt($this->password); } return $password; } }
Java
UTF-8
157
1.945313
2
[]
no_license
package com.lavamancer.car.util; import com.badlogic.gdx.graphics.g2d.SpriteBatch; public interface Drawable { void draw(SpriteBatch spriteBatch); }
C#
UTF-8
2,767
2.515625
3
[ "MIT" ]
permissive
using System; using System.Windows.Media; using System.Windows.Media.Imaging; using PixiEditor.Exceptions; using PixiEditor.Models.IO; using Xunit; namespace PixiEditorTests.ModelsTests.IO { public class ImporterTests { private readonly string testImagePath; private readonly string testCorruptedPixiImagePath; // I am not testing ImportDocument, because it's just a wrapper for BinarySerialization which is tested. public ImporterTests() { testImagePath = $"{Environment.CurrentDirectory}\\..\\..\\..\\ModelsTests\\IO\\TestImage.png"; testCorruptedPixiImagePath = $"{Environment.CurrentDirectory}\\..\\..\\..\\ModelsTests\\IO\\CorruptedPixiFile.pixi"; } [Theory] [InlineData("wubba.png")] [InlineData("lubba.pixi")] [InlineData("dub.jpeg")] [InlineData("-.JPEG")] [InlineData("dub.jpg")] public void TestThatIsSupportedFile(string file) { Assert.True(Importer.IsSupportedFile(file)); } [Fact] public void TestThatImportImageImportsImage() { Color color = Color.FromArgb(255, 255, 0, 0); WriteableBitmap image = Importer.ImportImage(testImagePath); Assert.NotNull(image); Assert.Equal(5, image.PixelWidth); Assert.Equal(5, image.PixelHeight); Assert.Equal(color, image.GetPixel(0, 0)); // Top left Assert.Equal(color, image.GetPixel(4, 4)); // Bottom right Assert.Equal(color, image.GetPixel(0, 4)); // Bottom left Assert.Equal(color, image.GetPixel(4, 0)); // Top right Assert.Equal(color, image.GetPixel(2, 2)); // Middle center } [Fact] public void TestThatImporterThrowsCorruptedFileExceptionOnWrongPixiFileWithSupportedExtension() { Assert.Throws<CorruptedFileException>(() => { Importer.ImportDocument(testCorruptedPixiImagePath); }); } [Theory] [InlineData("CorruptedPNG.png")] [InlineData("CorruptedPNG2.png")] [InlineData("CorruptedJpg.jpg")] public void TestThatImporterThrowsCorruptedFileExceptionOnWrongImageFileWithSupportedExtension(string fileName) { string imagePath = $"{Environment.CurrentDirectory}\\..\\..\\..\\ModelsTests\\IO\\{fileName}"; Assert.Throws<CorruptedFileException>(() => { Importer.ImportImage(imagePath); }); } [Fact] public void TestThatImportImageResizes() { WriteableBitmap image = Importer.ImportImage(testImagePath, 10, 10); Assert.Equal(10, image.PixelWidth); Assert.Equal(10, image.PixelHeight); } } }
Java
UTF-8
944
3.671875
4
[]
no_license
package com.srm.lab02.java; import java.util.Scanner; public class ConvertUpToLow { public static void main(String[] args) { System.out.println("CONVERTING UPPERCASE TO LOWER WITHOUT BUILT-IN METHOD."); System.out.println("------------------------------------------------------"); Scanner sc=new Scanner(System.in); String str1,str2=" "; char ch = ' '; System.out.println("Enter your string(Upper case):"); str1=sc.nextLine(); str1+='\0'; int i=0; while(str1.charAt(i)!='\0') { if(str1.charAt(i)>64 && str1.charAt(i)<91 ) //or if(str1[i]>='A' && str1[i]<='Z') ch=(char)(str1.charAt(i)+32); else ch=(char)(str1.charAt(i)); str2+=ch; i++; } System.out.println(""); System.out.println("Original string:"+str1); System.out.println("Lower case tring: "+str2); sc.close(); } }
Python
UTF-8
234
2.546875
3
[]
no_license
readline = open(0).readline N, M = map(int, readline().split()) A = [list(map(int, readline().split())) for i in range(N)] B = [int(readline()) for i in range(M)] print(*map((lambda Ai: sum(a*b for a, b in zip(Ai, B))), A), sep='\n')
C++
UTF-8
847
3
3
[]
no_license
/* * Beispiel für ein Lauflicht * * TODO: Mache doch mal die Wartezeit kürzer und schaue was passiert. */ #define WAITTIME 100 //Die LED Pin in von Oben nach Unten const uint8_t LEDPins[] = {5, 6, 7, 8, 9, 10, 11, 12, 13, A5, A4, A3, A2, A1, A0, 4 }; // setup: Wird aufgerufen, wenn das Programm startet (nach RESET) void setup() { //Alle LED Pins als AUSGANG setzen for (uint8_t i = 0; i < 16; i++) { pinMode(LEDPins[i], OUTPUT); } } // wird immer wieder aufgerufen.. void loop() { for (uint8_t i = 0; i < 16; i++) { digitalWrite(LEDPins[i], HIGH); //den i. Pin auf Versorgungsspannung (3.3V) setzen delay(WAITTIME); //Warten digitalWrite(LEDPins[i], LOW); //wieder auf 0V setzen } //Hier ist Ende und die loop-Funktion wird verlassen //um dann gleich wieder neu aufgerufen zu werden. }
Markdown
UTF-8
3,048
3.359375
3
[]
no_license
# Exercices types and boolean Ces exercices devront tous être pushés sur un repository accessible depuis github. Ce repository devra se nommer `exo-numbers-strings` Vous devrez fournir ce lien dans le formulaire de rendus d'exercices suivant: https://docs.google.com/forms/d/e/1FAIpQLSc6C1su3FLwG1ESO4PfhWLjnOUe8dngO7Ddvx3Md9s2X55M5w/viewform Essayez d'aller le plus loin possible. Les exercices qui nécessitent une réflexion approfondie sont sous la section: **Challenge** # Exercice 1 Vérifier les conditions de vos exercices précédents: https://github.com/AbsoluteVirtueXI/blockchain-courses/blob/master/exercices/programming/exercices-types-and-boolean.md Testez bien chaque conditions en changeant vos variables et vérifier que vous obtenez bien le résultat attendu. # decimal.js Ecrivez un programme qui affiche sur la console, les nombres suivants en base 10 (c'est à dire en décimal) ```js 0x123 0123 0b10011001 0xdeadbeef 0xea7beef 0b1111111111111111 0777 ``` # convert.js Ecrivez un programme qui convertira les nombres suivants en binaire, octal et hexadécimal (utiliser `.toString()` pour cela): ```txt 10 15 16 5005 52390903 ``` ## nbChar.js Ecrivez un programme qui affiche le nombre de caractères que possède le texte suivant: ```txt Je suis le ténébreux, - le veuf, - l'inconsolé, Le prince d'Aquitaine à la tour abolie : Ma seule étoile est morte, - et mon luth constellé Porte le soleil noir de la Mélancolie. Dans la nuit du tombeau, toi qui m'as consolé, Rends-moi le Pausilippe et la mer d'Italie, La fleur qui plaisait tant à mon cœur désolé, Et la treille où le pampre à la rose s'allie. Suis-je Amour ou Phébus ? ... Lusignan ou Biron ? Mon front est rouge encor du baiser de la reine ; J'ai rêvé dans la grotte où nage la sirène... Et j'ai deux fois vainqueur traversé l'Achéron ; Modulant tour à tour sur la lyre d'Orphée Les soupirs de la sainte et les cris de la fée. ``` # showChar.js Ecrivez un programme qui affiche ligne par ligne, l'index et le caractère situé à cet index de la phrase suivante: ```txt C'était à Mégara, faubourg de Carthage, dans les jardins d'Hamilcar. ``` Le format du message attendu pour chaque caractère sera par exemple: `Le caractère C est à l'index 0` `Le caractère ' est à l'index 1` ## showChar.js Améliorez l'exercice précédent pour écrire un message introductif avant l'exécution du programme. Ce message devra afficher l'auteur et le livre dont est extrait cette phrase, ainsi que le nombre de caractères que contient cette phrase. # Challenge ## countE.js Ecrivez un programme qui compte le nombre de `e` dans le texte de l'exercice `nbChar.js` ## countFullE.js Le programme précédent ne compte pas les `E` majuscules. Pouvez vous trouver un moyen pour que l'on compte le nombre de `e` total peu importe la casse. Vous devrez utiliser la méthode `.toUpperCase()` ou `.toLowerCase()` pour cela. ## countVowel.js Même exercice que précédemment mais vous compterez toutes les voyelles.
Java
UTF-8
2,184
2.125
2
[]
no_license
package pe.edu.upc.dew.veterinaria.controller; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import pe.edu.upc.dew.veterinaria.model.Producto; import pe.edu.upc.dew.veterinaria.model.Usuario; import pe.edu.upc.dew.veterinaria.service.UsuarioService; import pe.edu.upc.dew.veterinaria.service.UsuarioServiceImpl; import pe.edu.upc.dew.veterinaria.service.ReservaService; import pe.edu.upc.dew.veterinaria.service.ReservaServiceImpl; public class ReservaServlet extends HttpServlet { // private String email; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ReservaServiceImpl oReservaService = new ReservaServiceImpl(); System.out.println("ReservaServlet.doPost"); String codigo = request.getParameter("txtCodigo"); String nombre = request.getParameter("txtNombre"); System.out.println(codigo); System.out.println(nombre); String precio = request.getParameter("txtPrecio"); double igv=0.19; Double pre = Double.parseDouble(precio); igv = igv*pre; //precio; Producto oProducto = new Producto(); //oProducto.setCodigo(codigo); oProducto.setNombre(nombre); oProducto.setPrecio(Double.parseDouble(precio)); //Categoriaa oCategoria = new Categoria(); //Stringa catcodigo = request.getParameter("catcodigo"); //String catnombre = request.getParameter("catnombre"); //oCategoria.setCodigo(catcodigo); //oCategoria.setNombre(catnombre); //oProducto.setCategoria(oCategoria); List<Producto> lstReserva = new ArrayList<Producto>(); lstReserva.add(oProducto); request.setAttribute("lstReserva",lstReserva); request.getRequestDispatcher("miscompras.jsp").forward(request, response); } }
Markdown
UTF-8
4,652
2.78125
3
[ "CC-BY-4.0", "OFL-1.1", "MIT" ]
permissive
_model: page --- _template: page-with-toc.html --- title: Pull Request Guidelines --- description: We ask that contributors to CC projects submit a pull request with your changes. If you're not familiar with pull requests, please read [this GitHub documentation](https://help.github.com/en/articles/about-pull-requests). Here are our expectations for pull requests; following them will expedite the process of merging your code in. --- body: Read and follow the contributing guidelines and code of conduct for the project. Here are screenshots of where to find them for [first time contributors](first-time-contributor-resources.png) and [previous contributors](previous-contributor-resources.png). We aim to review pull requests within five business days.<a href="#footnote-1"><strong>*</strong></a>. If it has been over five business days and you have not received any feedback, feel free to follow up with us. * **Make A Branch** * Please create a separate branch for each issue that you're working on. Do not make changes to the default branch (e.g. `master`, `develop`) of your fork. * **Push Your Code ASAP** * Push your code as soon as you can. Follow the "[early and often](https://www.worklytics.co/blog/commit-early-push-often/)" rule. * Make a pull request as soon as you can and **mark the title with a "[WIP]"**. You can create a [draft pull request](https://help.github.com/en/articles/about-pull-requests#draft-pull-requests). <br/> [Screenshot: How to create draft PR?](draft_pr.gif) * **Describe Your Pull Request** * Use the format specified in pull request template for the repository. **Populate the stencil completely** for maximum verbosity. * Tag the actual issue number by replacing `#[issue_number]` e.g. `#42`. This closes the issue when your PR is merged. * Tag the actual issue author by replacing `@[author]` e.g. `@issue_author`. This brings the reporter of the issue into the conversation. * Mark the tasks off your checklist by adding an `x` in the `[ ]` e.g. `[x]`. This checks off the boxes in your to-do list. The more boxes you check, the better. * Describe your change in detail. Too much detail is better than too little. * Describe how you tested your change. * Check the Preview tab to make sure the Markdown is correctly rendered and that all tags and references are linked. If not, go back and edit the Markdown. <br/> [Screenshot: Populated pull request](populated_pr.png) * **Request Review** * Once your PR is ready, **remove the "[WIP]" from the title** and/or change it from a draft PR to a regular PR. * If a specific reviewer is not assigned automatically, please [request a review](https://help.github.com/en/articles/requesting-a-pull-request-review) from the project maintainer and any other interested parties manually. * **Incorporating feedback** * If your PR gets a 'Changes requested' review, you will need to address the feedback and update your PR by pushing to the same branch. You don't need to close the PR and open a new one. * Be sure to **re-request review** once you have made changes after a code review. <br/> [Screenshot: How to request re-review?](rereview.png) * Asking for a re-review makes it clear that you addressed the changes that were requested and that it's waiting on the maintainers instead of the other way round. <br/> [Screenshot: Difference between 'Changes requested' and 'Review required'](difference.png) ## Code guidelines * Write comprehensive and robust tests that cover the changes you've made in your work. * Follow the appropriate code style standards for the language and framework you're using (e.g. PEP 8 for Python). * Write readable code – keep functions small and modular and name variables descriptively. * Document your code thoroughly. * Make sure all the existing tests pass. * User-facing code should support the following browsers: * Chrome (Webkit-Blink / 22+) * Firefox (Gecko / 28+) * Edge (Chromium based / 12+) * Opera (Chromium-Blink / 12.1+) * Safari (Apple’s Webkit / 7+) * IE 11 (Trident) <p class="caption"><a name="footnote-1" class="has-color-dark-slate-gray"><strong>*</strong></a> CC staff work Monday through Friday and are not available on weekends and national holidays (the specific holidays observed vary based on the person's location). CC is closed between Christmas Eve and New Years' Day every year and for a few days following the CC Global Summit. Also, our availability during events such as the CC Global Summit and our biannual staff meetups is limited.</p>
PHP
UTF-8
1,138
2.921875
3
[]
no_license
<?php require_once 'Product.php'; require_once 'Category.php'; require_once 'CategoryModel.php'; class ProductModel { private $pdo; public function __construct() { try { $this->pdo = new PDO('mysql:host=localhost;dbname=wowfood', 'samdeb', 'admin'); $this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch(Exception $e) { die($e->getMessage()); } } public function Listar() { try { $result = array(); $stm = $this->pdo->prepare("SELECT * FROM product"); $stm->execute(); foreach($stm->fetchAll(PDO::FETCH_OBJ) as $r) { $categoryModel = new CategoryModel(); $category = $categoryModel->Obtener($r->category); $product = new Product($r->id, $r->name, $category, $r->price, $r->description, $r->img); $result[] = $product; } return $result; } catch(Exception $e) { die($e->getMessage()); } } }
Java
UTF-8
2,236
2.46875
2
[]
no_license
/* * Copyright (c) 2006-2013 LabKey Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.labkey.demo.model; import org.apache.commons.lang3.StringUtils; import org.labkey.api.data.Entity; import java.util.Objects; /** * User: brittp * Date: Jan 23, 2006 * Time: 1:18:25 PM */ public class Person extends Entity { private String _firstName; private String _lastName; private Integer _age; private Integer _rowId; public Person() { } public Person(String firstName, String lastName, Integer age) { _firstName = StringUtils.trimToEmpty(firstName); _lastName = StringUtils.trimToEmpty(lastName); _age = age; } public Integer getAge() { return _age; } public void setAge(Integer age) { _age = age; } public String getFirstName() { return _firstName; } public void setFirstName(String firstName) { _firstName = firstName; } public String getLastName() { return _lastName; } public void setLastName(String lastName) { _lastName = lastName; } public Integer getRowId() { return _rowId; } public void setRowId(Integer rowId) { _rowId = rowId; } public boolean equals(Object obj) { if (!(obj instanceof Person)) return false; Person p = (Person)obj; return Objects.equals(_firstName, p.getFirstName()) && Objects.equals(_lastName, p.getLastName()) && Objects.equals(_age, p.getAge()); } }
Markdown
UTF-8
16,830
3.875
4
[]
no_license
--- title: javascript菜鸟教程复习(二) date: 2017-06-23 08:40:40 categories: 前端 tags: [javascript] --- <Excerpt in index | 首页摘要> <!-- more --> <The rest of contents | 余下全文> ----- 网址:http://www.runoob.com/js/js-tutorial.html #### 1.typeof ```html typeof "John" // 返回 string typeof 3.14 // 返回 number typeof false // 返回 boolean typeof [1,2,3,4] // 返回 object typeof {name:'John', age:34} // 返回 object typeof null //返回object typeof NaN //返回number typeof myCar //undefined,因为没有定义 typeof new Date() //返回object ``` 如果对象是 JavaScript Array 或 JavaScript Date ,我们就无法通过 typeof 来判断他们的类型,因为都是 返回 Object。 1. 可以设置null来清空对象 ``` var persion=null;//值为null(空),但是类型为对象 ``` 2. 设置undefined来清空对象 ```javascript var person = undefined; // 值为 undefined, 类型为 undefined ``` 3. null与undefined的区别 ```javascript typeof undefined // undefined typeof null // object null === undefined // false null == undefined // true ``` 4. construction属性:返回所有的javascript变量的构造函数 ```html "John".constructor // 返回函数 String() { [native code] } (3.14).constructor // 返回函数 Number() { [native code] } false.constructor // 返回函数 Boolean() { [native code] } [1,2,3,4].constructor // 返回函数 Array() { [native code] } {name:'John', age:34}.constructor // 返回函数 Object() { [native code] } new Date().constructor // 返回函数 Date() { [native code] } function () {}.constructor // 返回函数 Function(){ [native code] } ``` eg:可以使用instruction可以查看对象是否为数组(是否包含字符串array) ```javascript function isArray(myArray){ return myArray.constructor.toString().indexOf("Array")>-1; }; ``` 5. 类型转换 ```javascript String(x) // 报错未定义 String(123) // 将数字 123 转换为字符串并返回"123" String(100 + 23) // 将数字表达式转换为字符串并返回"123" ``` 上面的代码相当于使用 `(123).toString()` 转换布尔值 ```javascript String(false) // 返回 "false" String(true) // 返回 "true" ``` 转换日期 ```javascript String(Date()) // 返回 Thu Jul 17 2014 15:38:19 GMT+0200 (W. Europe Daylight Time) ``` 6. +号,强制类型转换 ```javascript var y = "5"; // y 是一个字符串 var x = + y; // x 是一个数字 typeof x "number" ``` 如果变量不能转换,它仍然会是一个数字,但值为 NaN (不是一个数字): ```javascript var y = "John"; // y 是一个字符串 var x = + y; // x 是一个数字 (NaN) ``` 7. 布尔值转换为数字 ```javascript Number(false) //0 Number(true) //1 ``` 8. 日期转为数字 ```javascript var d=new Date //Fri Jun 23 2017 10:24:22 GMT+0800 (中国标准时间) Number(d) //1498184662219 //和Date的getTime()方法效果是一样的 d.getTime() //1498184662219 ``` 9. 自动类型转换 ```javascript 5 + null // 返回 5 null 转换为 0 "5" + null // 返回"5null" null 转换为 "null" "5" + 1 // 返回 "51" 1 转换为 "1" "5" - 1 // 返回 4 "5" 转换为 5 ``` #### 2.正则表达式 1. 使用字符串的方法 search():用于检索字符串中指定的子字符串,或检索与正则表达式相匹配的子字符串,并返回子串的起始位置,没有就返回-1 ```javascript var x="hello zhu"; x.search("zhu") //6,注意有空格,这是使用的字符串作为子串的 var x="AAAABBBJJOIDDKKOHF" x.search(/o/i); //9,这里的参数i是说不区分大小写 ``` replace():用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式相匹配的子串 ```javascript var x="AAAABBBJJOIDDKKOHF" x.replace("A","Z");//这样写只替换了第一个匹配到的字符 //"ZAAABBBJJOIDDKKOHF" x.replace(/A/g,"Z"); //"ZZZZBBBJJOIDDKKOHF" ``` 2. 正则表达式修饰符 - i:执行对大小写敏感的匹配 - g:执行全局匹配(查找所有匹配,而不是在找到第一个匹配以后停止) - m:执行多行匹配 3. 使用test()函数 用于检测一个字符串是否匹配某个模式,如果字符串中含有匹配文本,则返回true,否则返回false ```javascript var x="AAAABBBJJOIDDKKOHF" var y=/F/; y.test(x) true ``` 4. 使用exec() 是正则表达式的一个方法,检测一个字符串是否匹配某个模式,该函数返回一个数组,其中存放匹配的结果,如果没有找到,则返回null ```javascript var x="AAAABBBJJOIDDKKOHF" var y=/A/g y.exec(x); ["A", index: 0, input: "AAAABBBJJOIDDKKOHF"]0: "A"index: 0input: "AAAABBBJJOIDDKKOHF"length: 1__proto__: Array(0) ``` #### 3.javascript 错误 - try:语句测试代码块的错误 - catch:语句处理错误 - throw:语句创建自定义错误 语法: ```javascript try { //在这里运行代码 } catch(err) { //在这里处理错误 } ``` eg ```javascript <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <p>请输入5-10之间的数字</p> <input type="text" id="demo"> <button type="button" onclick="test()">测试输入</button> <p id="message"></p> </body> <script> function test(){ var message,x; //错误信息显示的地方 message=document.getElementById("message"); //每次点击按钮清空错误信息 message.innerHTML=""; //获取用户输入 x=document.getElementById("demo").value try{ if(x==""){ throw "值为空" } if(isNaN(x)){ throw "不是数字" } x=Number(x); if(x<5){ throw "太小" } if(x>10){ throw "太大" } }catch(error){ message.innerHTML="错误:" +error } }; </script> </html> ``` #### 4.严格模式 ```javascript "use strict"; myFunction(); function myFunction() { y = 3.14; // 报错 (y 未定义) } ``` #### 5. javascript使用误区 ##### 5.1 赋值运算符应用错误在 :JavaScript 程序中如果你在 if 条件语句中使用赋值运算符的等号 (=) 将会产生一个错误结果, 正确的方法是使用比较运算符的两个等号 (==)。 - 正常写法,if条件返回false,因为0不等于10 ```javascript var x=0; if(x==10) ``` - 错误写法,这时候的if后面返回的是true,因为x被重新赋值为10了,会被强制转换为true,这和我们本意是不一样的 ```javascript var x=0 if(x=10){} ``` - 错误写法,这时候我们的本意是当x=0的时候执行后面的语句,结果if后面的x=0直接给赋值了,0会被强制转为false,导致后面的语句不执行 ```javascript var x=0; if(x=0){} ``` ##### 5.2 比较运算符常见错误: - 比较运算中,数据类型会被忽略.下面的if返回true ```javascript var x=10; var y="10"; if(x==y){} ``` - ===值和类型都相同,下面的if返回false ```javascript var x=10; var y="10"; if(x===y){} ``` - switch里面的case使用的恒等计算(====) 下面这个会执行后面的alert ```javascript var x = 10; switch(x) { case 10: alert("Hello"); } ``` 下面这个不会执行,因为switch执行的是恒等 ```javascript var x = 10; switch(x) { case "10": alert("Hello"); } ``` ##### 5.3 加号还是连接符号? +两边只要有一个是字符串,那他就是连接符号 ##### 5.4 浮点型数据使用注意事项 所有的编程语言,包括 JavaScript,对浮点型数据的精确度都很难确定: ```javascript var x = 0.1; var y = 0.2; var z = x + y // z 的结果为 0.3 if (z == 0.3) // 返回 false ``` 为解决上面的问题,可以这么写 ```javascript var z = (x * 10 + y * 10) / 10; // z 的结果为 0.3 ``` ##### 5.5字符串分行 正确 ``` var x = "Hello World!"; ``` 错误 ``` var x ="Hello World!"; ``` 需要使用反斜杠\来解决 ``` var x = "Hello \ World!"; ``` ##### 5.6错误使用分号 由于分号使用错误,if 语句中的代码块将无法执行: ``` if (x == 19); { // code block } ``` ##### 5.7 return使用错误 js默认在最后一行自动结束,一下两个实验结果是一样的(有无分号) ``` function myFunction(a) { var power = 10 return a * power } ``` ``` function myFunction(a) { var power = 10; return a * power; } ``` JavaScript 也可以使用多行来结束一个语句。 以下实例返回相同的结果: ``` function myFunction(a) { var power = 10; return a * power; } ``` 但是,以下实例结果会返回 undefined: ``` function myFunction(a) { var power = 10; return a * power; } ``` 上面的代码相当于下面的实例 ``` function myFunction(a) { var power = 10; return; // 分号结束,返回 undefined a * power; } ``` 由于 return 是一个完整的语句,所以 JavaScript 将关闭 return 语句。 ##### 5.8数组中使用名字来索引 使用名字来作为索引的数组称为关联数组(或哈希) javascript不支持使用名字来索引,仅允许数字索引 ``` var person = []; person[0] = "John"; person[1] = "Doe"; person[2] = 46; var x = person.length; // person.length 返回 3 var y = person[0]; // person[0] 返回 "John" ``` js中,对象可以使用名字来作为索引,但是如果你使用名字作为索引,当访问数组时,JavaScript 会把数组重新定义为标准对象。 执行这样操作后,数组的方法及属性将不能再使用,否则会产生错误 ``` var person = []; person["firstName"] = "John"; person["lastName"] = "Doe"; person["age"] = 46; var x = person.length; // person.length 返回 0 var y = person[0]; // person[0] 返回 undefined ``` ##### 5.9 定义数组元素和定义对象元素,最后都不能留逗号 以下两个都是错误的 ``` points = [40, 100, 1, 5, 25, 10,]; websites = {site:"菜鸟教程", url:"www.runoob.com", like:460,} ``` ##### 5.9 undefined不是null 在javascript中,null用于对象,undefined用于变量、属性和方法。对象只有被定义才会有可能为null,否则就是undefined。如果我们测试对象是否存在,在对象还没有定义的时候会抛出错误 错误使用 ``` if(myObjcet !==null && myObject !=="undefined") ``` 正确使用 ``` if(myObject !=="undefined" && myObject !==null) ``` 根本还是&&机制 ##### 5.10代码块的作用域是全局 在每个代码块中 JavaScript 不会创建一个新的作用域,一般各个代码块的作用域都是全局的。 以下代码的的变量 i 返回 10,而不是 undefined: ``` for (var i = 0; i < 10; i++) { // some code } return i; ``` #### 6. javascript 表单 当用户提交的时候进行验证 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <script> function validate(){ var userName=document.forms[0]["userName"].value; if(userName==null || userName==""){ alert("请输入姓名"); return false; } }; </script> </head> <body> <form action="test.php" method="post" id="myform" name="myform" onsubmit="return validate()"> <label for="userName">名字:</label><input type="text" id="userName" name="userName"> <input type="submit" value"提交"> </form> </body> </html> ``` 判断用户输入的数字 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <p>请输入10-20之间的数字</p> <form action="test.php" name="myform" id="myform"> <label for="typeNum">请输入数字:<input type="text" name="typeNum" id="typeNum"></label> <input type="button" value="提交" id="btn"> </form> <p id="aa"></p> </body> <script> var aa=document.getElementById("aa"), btn=document.getElementById("btn"); btn.addEventListener("click",check); function check(){ var typeNum=document.forms["myform"]["typeNum"].value; aa.innerHTML=""; if(isNaN(typeNum)){ text="请输入数字"; } else if(typeNum==""){ text="你没有输入任何值" } else if(typeNum <10){ text="输入的值小于10"; } else if(typeNum > 20){ text="输入的值过大"; }else{ text=typeNum; } aa.innerHTML=text; }; </script> </html> ``` html表单自动校验 ``` <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form action="1.php" id="myform"> <label for="userName">请输入姓名: <input type="text" name="userName" id="userName" required="required"> </label> <label for="pword">请输入密码: <input type="password" name="pword" id="pword" required pattern="[A-Z]{3}" title="只能输入三个大写字母"> </label> <label for="age">请输入年龄: <input type="number." name="age" id="age" required pattern="[0-9]" min="10" max="100" title="只能输入数字"> </label> <input type="submit" value="提交"> </form> </body> </html> ``` min和max只可以给type=date和type=number用,pattern里面放的是正则,title是提示 ##### 验证约束的dom方法 - checkValidity():如果input里面数据是合法的则返回true,否则返回false - setCustomValidity():设置input元素的validationMessage属性,用于自定义错误信息提示的方法。使用setCustomValidity()设置了自定义提示以后,validity.customError就会变成true,则checkValidity总是会返回false。如果重新判断,需要取消自定义提示,方式如下: ```html setCustomValidity(""); setCustomValidity(null); setCustomValidity(undefined); ``` ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p>输入数字并点击验证按钮:</p> <input id="id1" type="number" min="100" max="300" required> <button onclick="myFunction()">验证</button> <p>如果输入的数字小于 100 或大于300,会提示错误信息。</p> <p id="demo"></p> <script> function myFunction() { var inpObj = document.getElementById("id1"); if (inpObj.checkValidity() == false) { document.getElementById("demo").innerHTML = inpObj.validationMessage; } else { document.getElementById("demo").innerHTML = "输入正确"; } } </script> </body> </html> ``` ##### 约束验证dom属性 - validity:布尔属性值,返回input输入值是否合法 - validationMessage:浏览器错误提示信息 - willValidate:指定input是否需要验证 ##### validity属性 input元素的validity属性包含一系列validity数据属性 - customError:设置为true,如果设置了自定义的validity信息 - patternMismatch:设置为true,如果元素的值不匹配他的模式属性 - rangeOverflow:设置为true,如果元素的值大于设置的最大值 - rangeUnderflow:设置为true,如果元素的值小于设置的最小值 - stepMismatch:设置为true,如果元素的值不按照规定的step属性设置 - tooLong:设置为true,如果元素的值超过了maxLength属性设置的长度 - typeMismatch:设置为true,如果元素的值不是预期相匹配的类型 - valueMissing:设置为true,如果元素(require)没有值 - valid:设置为true,如果元素的值是合法的 ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p>输入数字并点击验证按钮:</p> <input id="id1" type="number" max="100"> <button onclick="myFunction()">验证</button> <p>如果输入的数字大于 100 ( input 的 max 属性), 会显示错误信息。</p> <p id="demo"></p> <script> function myFunction() { var txt = ""; if (document.getElementById("id1").validity.rangeOverflow) { txt = "输入的值太大了"; } else { txt = "输入正确"; } document.getElementById("demo").innerHTML = txt; } </script> </body> </html> ``` ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <p>输入数字并点击验证按钮:</p> <input id="id1" type="number" min="100" required> <button onclick="myFunction()">验证</button> <p>如果输入的数字小于 100 ( input 的 min 属性), 会显示错误信息。</p> <p id="demo"></p> <script> function myFunction() { var txt = ""; var inpObj = document.getElementById("id1"); if(!isNumeric(inpObj.value)) { txt = "你输入的不是数字"; } else if (inpObj.validity.rangeUnderflow) { txt = "输入的值太小了"; } else { txt = "输入正确"; } document.getElementById("demo").innerHTML = txt; } // 判断输入是否为数字 function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } </script> </body> </html> ```
JavaScript
UTF-8
472
2.5625
3
[]
no_license
// EXPORTANDO OS ARQUIVOS.. const moduloA = require('./aula2_sistemaDeModulos') const moduloB = require('./aula2b_exportacao') console.log(moduloA,moduloB) console.log(moduloA.ola) console.log(moduloB.boaNoite()) // Organização no Back end. // Por PADRÃO tudo fica dentro do modulo e quando vc exporta aquilo fica disponivel para que for usar. // se o modulo estiver detro do seu projeto o modulo de acesso é o relativo // se estiver fora o modulo de requerer é
Python
UTF-8
2,242
3.65625
4
[]
no_license
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: """ Runtime: 92 ms, faster than 27.57% of Python3 online submissions for Add Two Numbers. Memory Usage: 13.4 MB, less than 12.52% of Python3 online submissions for Add Two Numbers. Test cases: [2,4,3] [5,6,4] [0] [0] [5] [5] [9, 9, 9] [1] """ @staticmethod def add(a, b, curry): q = a + b + curry if q >= 10: q = q % 10 r = 1 else: r = 0 return q, r def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode: cur1 = l1 cur2 = l2 q, curry = self.add(cur1.val, cur2.val, 0) result = ListNode(q) cur1 = cur1.next cur2 = cur2.next head = result while cur1 is not None and cur2 is not None: value1 = cur1.val value2 = cur2.val q, curry = self.add(value1, value2, curry) result.next = ListNode(q) result = result.next cur1 = cur1.next cur2 = cur2.next if cur1 is None and cur2 is None: if curry == 1: result.next = ListNode(curry) if cur1 is not None: q, curry = self.add(cur1.val, curry, 0) result.next = ListNode(q) result = result.next cur1 = cur1.next while cur1 is not None: q, curry = self.add(cur1.val, curry, 0) result.next = ListNode(q) result = result.next cur1 = cur1.next if curry == 1: result.next = ListNode(curry) if cur2 is not None: q, curry = self.add(cur2.val, curry, 0) result.next = ListNode(q) result = result.next cur2 = cur2.next while cur2 is not None: q, curry = self.add(cur2.val, curry, 0) result.next = ListNode(q) result = result.next cur2 = cur2.next if curry == 1: result.next = ListNode(curry) return head
Java
UTF-8
1,105
2.1875
2
[]
no_license
package lk.autostreet.services.core; import lk.autostreet.services.core.exception.UserNotCreatedException; import lk.autostreet.services.core.model.User; import lk.autostreet.services.core.model.UserType; import lk.autostreet.services.core.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import javax.annotation.security.RolesAllowed; @RestController public class UserController { @Autowired private UserService userService; @PostMapping("/users") public User create() throws UserNotCreatedException { User user = new User(); user.setUsername("chathuranga"); user.setPassword("123456"); user.setSeller(1L); user.setUserType(UserType.ADMIN); return userService.create(user); } @RolesAllowed({"ROLE_SYSTEM_ADMIN"}) @GetMapping("/test") public String test() { return "Admin user"; } }
C++
UTF-8
5,181
3.890625
4
[]
no_license
#include <iostream> #include <vector> using namespace std; /* *冒泡排序 *时间复杂度 平均O(n^2) 最坏O(n^2) 最好O(n) *比如12345,优化过的冒泡排序第一趟就发现,没有任何交换,则全部有序,相当于遍历一次 * 稳定 */ void BubbleSort(vector<int> &v) { int n = v.size(); bool isExchange = true; for (int i = 0; i < n-1 && isExchange; i++) { isExchange = false; for (int j = 0; j < n-1-i; j++) { if (v[j] > v[j+1]) { int tmp = v[j]; v[j] = v[j+1]; v[j+1] = tmp; isExchange = true; } } } } /** *插入排序 *时间复杂度 平均O(n^2) 最坏O(n^2) 最好O(n) *如12345,从小到大排序,则相当于只从头到尾遍历一次,没有作任何交换 *稳定 */ void InsertSort(vector<int> &v) { int n = v.size(); for (int i = 1; i < n; i++) { for (int j = i; j > 0; j--) { if (v[j]< v[j-1]) { int tmp = v[j-1]; v[j-1] = v[j]; v[j] = tmp; } } } } /** *选择排序 *时间复杂度 平均O(n^2) 最坏O(n^2) 最好O(n^2) *不稳定 * */ void SelectSort(vector<int> &v) { int n = v.size(); for (int i = 0; i < n - 1; i++) { for (int j = i+1; j < n; j++) { if (v[i] > v[j]) { int tmp = v[i]; v[i] = v[j]; v[j] = tmp; } } } } /** *希尔排序 *时间复杂度 平均O(n^1.3) 最坏O(n^2) 最好O(n) *不稳定 **/ void ShellSort(vector<int> &v) { } /** *快速排序 **/ int Partition(vector<int> &v, int start, int end) { int i = start, j = end; int tmp = v[i]; while (i < j) { while (i < j && tmp <= v[j]) { j--; } if (i < j) { v[i++] = v[j]; } while (i < j && tmp >= v[i]) { i++; } if (i < j) { v[j--] = v[i]; } } v[i] = tmp; return i; } void QuickSort(vector<int> &v, int start, int end) { if (start < end) { int n = Partition(v, start, end); QuickSort(v, start, n-1); QuickSort(v, n+1, end); } } /** *快速排序 *时间复杂度 平均O(nlgn) 最坏O(n^2) 最好O(nlgn) *不稳定 **/ void QuickSort(vector<int> &v) { int n = v.size(); QuickSort(v, 0, n-1); } /** *堆排序 *时间复杂度 平均O(nlgn) 最坏O(nlgn) 最好O(nlgn) *不稳定 **/ //从小到大排序要建大根堆,每次把堆顶(最大)放到最后,然后前面的再建大根堆 void HeapAdjust(vector<int> &v, int start, int end) { int parent = start; int child = 2 * parent + 1; while (child <= end) { if (child + 1 <= end && v[child + 1] > v[child]) { child++; } if (v[parent] >= v[child]) { break; } else { int tmp = v[parent]; v[parent] = v[child]; v[child] = tmp; parent = child; child = 2 * parent + 1; } } } void HeapSort(vector<int> &v) { int n = v.size(); //从最后一个父节点开始建堆 for (int i = n/2 - 1; i >= 0; i--) { HeapAdjust(v, i, n-1); } for (int i = n-1; i > 0; i--) { int tmp = v[0]; v[0] = v[i]; v[i] = tmp; HeapAdjust(v, 0, i-1); } } /** *归并排序 *时间复杂度 平均O(nlgn) 最坏O(nlgn) 最好O(nlgn) *稳定 **/ void MergeSort(vector<int> &v) { } /** *计数排序 O(n+k) O(n+k) O(n+k) 空间复杂度 O(n+k) * * 找出待排序的数组中最大和最小的元素; * 统计数组中每个值为i的元素出现的次数,存入数组C的第i项; * 对所有的计数累加(从C中的第一个元素开始,每一项和前一项相加); *反向填充目标数组:将每个元素i放在新数组的第C(i)项,每放一个元素就将C(i)减去1。 * * * 桶排序 O(n+k) O(n^2) O(n) 空间复杂度 O(n+k) * * 桶排序是计数排序的升级版。它利用了函数的映射关系,高效与否的关键就在于这个映射函数的确定。桶排序 (Bucket sort)的工作的原理:假设输入数据服从均匀分布,将数据分到有限数量的桶里,每个桶再分别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排)。 * * * 基数排序 O(n*k) O(n*k) O(n*k) 空间复杂度 O(n+k) * * 基数排序是按照低位先排序,然后收集;再按照高位排序,然后再收集;依次类推,直到最高位。有时候有些属性是有优先级顺序的,先按低优先级排序,再按高优先级排序。最后的次序就是高优先级高的在前,高优先级相同的低优先级高的在前。 **/ void Show(vector<int> v) { for (auto item : v) { cout << item << ","; } cout << endl; } int main() { vector<int> v = {1,4,3,2,5,6,8,7}; // BubbleSort(v); // InsertSort(v); // SelectSort(v); // QuickSort(v); HeapSort(v); Show(v); }
C
UTF-8
1,625
3.140625
3
[]
no_license
// C Primier Plus Exercise8.11 Q5 #include<stdio.h> int main(void) { int guest=50; char user,tips; char clear; const int MAX=100; const int MIN=0; int max=MAX,min=MIN; printf("I guess the magic number is %d,is it?\n",guest); printf("If I correct then you key in y,otherwise you key in n\n"); scanf("%c",&user); while( (clear=getchar())!='\n') continue; determine_user : switch(user) { case'y': { printf("I win!"); break; } case'n': { printf("If it is bigger then you key in B otherwise key in S\n"); tips=getchar(); while( (clear=getchar())!='\n') continue; determine_tips : switch(tips) { case'S': { min=guest; guest=(max+min)/2; break; } case'B': { max=guest; guest=(max+min)/2; break; } default: { printf("I can't understand,please insert an effective char B or S\n"); scanf("%c",&tips); while( (clear=getchar())!='\n') continue; goto determine_tips; } } printf("I guess the magic number is %d,is it?\n",guest); printf("If I correct then you key in y,otherwise you key in n\n"); scanf("%c",&user); while( (clear=getchar())!='\n') continue; goto determine_user; } default: { printf("I can't understand,please insert an effective char y or n:"); scanf("%c",&user); printf("\n"); while( (clear=getchar())!='\n') continue; goto determine_user; } } return 0; }
Python
UTF-8
1,343
2.5625
3
[]
no_license
from typing import Optional # 選択肢とアイテムの種類は別な気がするが、二重に定義するのもなあ # 選択肢がEnumじゃなくて、特定のリストを返すProtocolなら良いのかな・・・ # 選択肢の結果ともとれるか?うーん from ..response.choices import AddContainerTypeChoice, AddItemTypeChoice class Item: item_type: AddItemTypeChoice item_count: int zone_number: Optional[int] = None container_type: Optional[AddContainerTypeChoice] = None container_number: Optional[int] = None author_name: str = "nobody" # class Builder: # item_type: Optional[AddItemTypeChoice] # item_count: Optional[int] # zone_number: Optional[int] # container_type: Optional[AddContainerTypeChoice] # container_number: Optional[int] # def build(self) -> "Item": # return Item(self) # def __init__(self, builder: Builder): # if not builder.item_type: # raise Exception() # if not builder.item_count: # raise Exception() # self.item_type = builder.item_type # self.item_count = builder.item_count # self.zone_number = builder.zone_number # self.container_type = builder.container_type # self.container_number = builder.container_number
PHP
UTF-8
1,800
2.71875
3
[]
no_license
<?php // this method call should be placed at the start (top) of every php file that uses session variables session_start(); require_once ("../siteCommon2Pro.php"); // call the displayPageHeader method in siteCommon2.php displayPageHeader("Home Page"); // the session array element "userInfo" will be set (see d10loginform.php) if the user has been authenticated $logFName = (isset($_SESSION['userInfo']))? $_SESSION['userInfo']['firstname'] : ""; ?> <section> <?php // if the user is authenticated, customize greeting" if (!empty($logFName)) { // print_r($_SESSION['userInfo']); echo "<p>Welcome back to Rams Insurance, <strong>$logFName</strong>!</p>"; } else { echo "<p>Hello, and welcome to Rams Insurance!</p> <p>Please Login As an <strong>Administrator</strong> Or <strong>Customer</strong> to Use This Application</p> "; } ?> <?php if(isset($_SESSION['userInfo'])&&($_SESSION['userInfo']['userrole']=='Admin')){ echo "<p>You Have Logged in as an <strong>Administrator</strong></p> <p>You have the privilege to add new Insurance Policies Which will be purchased by our customers</p> <p>You can also make changes to existing policies in the system and also delete unwanted policies</p>"; } else if(isset($_SESSION['userInfo'])&&($_SESSION['userInfo']['userrole']=='Customer')){ echo "<p>You Have Logged in as a <strong>Customer</strong></p> <p>You have the privilege to buy Insurance Policies which will be added to your account</p> <p>You can also search which policy is suitable for you from the wide variety of policies we offer</p> <p>Also you can cancel any policy that you do not require</p>"; } ?> </section> <?php // call the displayPageFooter method in siteCommon2.php displayPageFooter(); ?>
Python
UTF-8
161
3.609375
4
[]
no_license
if name == 'Alice': print('Hi, Alice.') elif age < 12: print('You arenot Alice, kiddo.') else: print('You are neither Alice nor a lottle kid')
Swift
UTF-8
870
3.046875
3
[]
no_license
// // AuthUser.swift // On The Map // // Created by Justin Kumpe on 7/19/20. // Copyright © 2020 Justin Kumpe. All rights reserved. // import Foundation //Struct holds Authenticated User's Info struct AuthUser { static var sessionId = "" static var userId = "" static var userFirstName = "" static var userLastName = "" init(userInfo: Bool, dictionary: [String:AnyObject]) { if userInfo{ AuthUser.userFirstName = dictionary["first_name"] as! String AuthUser.userLastName = dictionary["last_name"] as! String }else{ AuthUser.sessionId = dictionary["session"]!["id"] as! String AuthUser.userId = dictionary["account"]!["key"] as! String } } static func logout(){ sessionId = "" userId = "" userFirstName = "" userLastName = "" } }
C++
UTF-8
4,499
2.78125
3
[]
no_license
#include "catch.hpp" #include "server_lib.hpp" #include "client_lib.hpp" #include <nlohmann/json.hpp> #include <boost/asio.hpp> #include <boost/asio/spawn.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/buffer.hpp> #include <boost/asio/io_context.hpp> #include <sstream> #include <string> using boost::asio::ip::tcp; using json = nlohmann::json; TEST_CASE("RUN ALL TESTS TOGETHER") { REQUIRE(true == true); } TEST_CASE("1. create first user") { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 1234)); tcp::socket socket(io_context); acceptor.async_accept(socket, [&](boost::system::error_code ec) { REQUIRE(!ec); std::make_shared<session>(io_context, std::move(socket))->go(); }); std::thread th{[&] { std::string username = "alice"; REQUIRE(signup(username) == true); }}; io_context.run(); th.join(); } TEST_CASE("2. create second user") { REQUIRE(signup("mark 123") == false); boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 1234)); tcp::socket socket(io_context); acceptor.async_accept(socket, [&](boost::system::error_code ec) { REQUIRE(!ec); std::make_shared<session>(io_context, std::move(socket))->go(); }); std::thread th{[&] { std::string username = "bob"; REQUIRE(signup(username) == true); }}; io_context.run(); th.join(); } TEST_CASE("3. login first user") { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 1234)); tcp::socket socket(io_context); acceptor.async_accept(socket, [&](boost::system::error_code ec) { REQUIRE(!ec); std::make_shared<session>(io_context, std::move(socket))->go(); }); std::thread th{[&] { std::string username = "alice"; REQUIRE(login(username) == true); }}; io_context.run(); th.join(); } TEST_CASE("4. login second user") { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 1234)); tcp::socket socket(io_context); acceptor.async_accept(socket, [&](boost::system::error_code ec) { REQUIRE(!ec); std::make_shared<session>(io_context, std::move(socket))->go(); }); std::thread th{[&] { std::string username = "bob"; REQUIRE(login(username) == true); }}; io_context.run(); th.join(); } TEST_CASE("5. alice sends to bob") { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 1234)); tcp::socket socket(io_context); acceptor.async_accept(socket, [&](boost::system::error_code ec) { REQUIRE(!ec); std::make_shared<session>(io_context, std::move(socket))->go(); }); std::thread th{[&] { std::string sender = "alice"; std::string receiver = "bob"; std::string text = "hello bob!"; REQUIRE(send_reply(sender, receiver, text) == true); }}; io_context.run(); th.join(); } TEST_CASE("6. bob sends to alice") { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 1234)); tcp::socket socket(io_context); acceptor.async_accept(socket, [&](boost::system::error_code ec) { REQUIRE(!ec); std::make_shared<session>(io_context, std::move(socket))->go(); }); std::thread th{[&] { std::string sender = "bob"; std::string receiver = "alice"; std::string text = "hello alice!"; REQUIRE(send_reply(sender, receiver, text) == true); }}; io_context.run(); th.join(); } TEST_CASE("7. alice gets messages") { boost::asio::io_context io_context; tcp::acceptor acceptor(io_context, tcp::endpoint(tcp::v4(), 1234)); tcp::socket socket(io_context); acceptor.async_accept(socket, [&](boost::system::error_code ec) { REQUIRE(!ec); std::make_shared<session>(io_context, std::move(socket))->go(); }); std::thread th{[&] { User u; u.username = "alice"; REQUIRE(get_messages(u) == json::parse(R"({"bob":{"0":{"receiver":"bob","sender":"alice","text":"hello bob!"},"1":{"receiver":"alice","sender":"bob","text":"hello alice!"}}})")); }}; io_context.run(); th.join(); }
C++
UTF-8
2,009
2.609375
3
[]
no_license
#ifndef TC_NETWORK_READER_H #define TC_NETWORK_READER_H #include "alias.h" #include "../general/timer.hpp" namespace tobilib{ namespace network{ struct ReaderOptions { double read_timeout = 0; double inactive_warning = 0; }; namespace detail{ // SocketType: // boost::asio::ip::tcp::socket // boost::asio::ssl::stream template<class SocketType> class SocketReader { public: SocketReader(ReaderOptions&,SocketType*); void tick(); void start_reading(); bool is_reading() const; void reset(SocketType*); bool warning = false; bool inactive = false; bool received = false; boost::system::error_code error; std::string data; const static std::size_t BUFFER_SIZE = 256; private: ReaderOptions& options; SocketType* socket; Timer timer_A; // used for no activity warning Timer timer_B; // used for no activity deadline std::string buffer = std::string(BUFFER_SIZE,0); bool asio_reading = false; void on_receive(const boost::system::error_code&,size_t); }; template <class SocketType> class WebsocketReader { public: using WebsocketType = boost::beast::websocket::stream<SocketType>; WebsocketReader(ReaderOptions&,WebsocketType*); void tick(); void start_reading(); bool is_reading() const; void reset(WebsocketType*); bool warning = false; bool inactive = false; bool received = false; boost::system::error_code error; std::string data; private: ReaderOptions& options; WebsocketType* socket; Timer timer_A; Timer timer_B; boost::asio::streambuf buffer; bool asio_reading = false; void on_receive(const boost::system::error_code&, size_t); }; } // namespace detail } // namespace network } // namespace tobilib #endif
JavaScript
UTF-8
480
3.1875
3
[]
no_license
function isVisible(element){ if (element.offsetWidth > 0 && element.offsetHeight > 0) return true; } var show = function(link, block, textShow, textHide){ var infoblock = document.querySelectorAll(block); for (var j = 0; j < infoblock.length; j++) { if (isVisible(infoblock[j])){ infoblock[j].style.display = 'none'; if(textHide) link.innerHTML = textHide; } else{ infoblock[j].style.display = 'block'; if(textShow) link.innerHTML = textShow; } } }
Java
UTF-8
1,511
2.09375
2
[]
no_license
package com.btw.helpservice; import com.btw.helpservice.utils.ResultJsonUtil; import com.btw.helpservice.utils.TokenVerifier; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import javax.servlet.http.HttpServletRequest; /** * @description: 权限验证 * @author: elvis.yue@i9i8.com * @create: 2021-04-02 09:32 */ @Aspect @Slf4j @Component public class ControllerAspect { @Pointcut("execution(* com.btw.helpservice.controller.*.*(..)) ") public void pointCut(){ } @Around("pointCut()") public Object permissionsValidation(ProceedingJoinPoint joinPoint) throws Throwable { MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); log.info("正在调用:"+methodSignature.getName()+"()"); HttpServletRequest request=(HttpServletRequest) joinPoint.getArgs()[0]; String user_id=request.getHeader("user_id"); String token=request.getHeader("token"); if (TokenVerifier.verifyToken(user_id,token)) return joinPoint.proceed(); else return ResultJsonUtil.getInstance() .addParam(ResultJsonUtil.RESULT_STR,ResultJsonUtil.RESULT_FAIL) .addParam(ResultJsonUtil.INFO_STR,"没有权限") .getResult(); } }
JavaScript
UTF-8
3,284
3.015625
3
[]
no_license
let employeesModel = []; //Function: initializeEmployeesModel() function initializeEmployeesModel() { $.get("https://stormy-cliffs-97970.herokuapp.com/employees") .done(function (data) { employeesModel = data; refreshEmployeeRows(employeesModel); }) .fail(function (err) { showGenericModal('Error, Unable to get EmployeesS'); }) } //Function: showGenericModal(title,message) function showGenericModal(title, message) { console.log("modal is maybe working i don't know yet") $(".modal-title").html(title); $(".modal-body").html(message); $("#genericModal").modal({}); } //Function: refreshEmployeeRows(employees) function refreshEmployeeRows(employees) { $("#employees-table").empty(); let template = _.template('<% _.forEach(employees, function(employee){%>' + '<div class="row body-row" data-id="<%- employee._id %>">' + '<div class="col-xs-4 body-column"><%- _.escape(employee.FirstName) %></div>' + '<div class="col-xs-4 body-column"><%- _.escape(employee.LastName) %></div>' + '<div class="col-xs-4 body-column"><%- _.escape(employee.Position.PositionName) %></div>' + '</div>' + '<% }); %>'); $("#employees-table").append(template({ 'employees': employees })); }; //Function: getFilteredEmployeesModel(filterString) function getFilteredEmployeesModel(filterString) { let filteredEmployeesModel = _.filter(employeesModel, function (e) { if (e.FirstName.toLowerCase().includes(filterString.toLowerCase()) || e.LastName.toLowerCase().includes(filterString.toLowerCase()) || e.Position.PositionName.toLowerCase().includes(filterString.toLowerCase())) return true; else return false; }); return filteredEmployeesModel; }; //Function: getEmployeeModelById(id) function getEmployeeModelById(id) { let retValue = null; for (let i = 0; i < employeesModel.length; i++) { if (employeesModel[i]._id = id) { retValue = _.cloneDeep(employeesModel[i]); } } return retValue; } ////////// $(document).ready(function () { console.log("jQuery Working"); initializeEmployeesModel(); $("#employee-search").on("keyup", function (event) { let filtered = getFilteredEmployeesModel(this.value); refreshEmployeeRows(filtered); }); $(document.body).on('click', '.body-row', function () { let employee = getEmployeeModelById($(this).attr("data-id")); if (employee != null) { employee.HireDate = moment(employee.HireDate).format('LL'); let modalContentTemplate = _.template( '<strong>Address:</strong> <%- employee.AddressStreet %> <%- employee.AddressCity %>, <%- employee.AddressState %>. <%- employee.AddressZip %></br>' + '<strong>Phone Number:</strong> <%- employee.PhoneNum %> ext: <%- employee.Extension %></br>' + '<strong>Hire Date:</strong> <%- employee.HireDate %>' ); let modalContent = modalContentTemplate({ 'employee': employee }); showGenericModal(employee.FirstName + ' ' + employee.LastName, modalContent); } }); });
Java
UTF-8
508
2.828125
3
[]
no_license
package JUnitTest; import model.Task; import org.junit.jupiter.api.Test; import java.time.LocalDate; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Unit test for Task class */ class TaskTest { String content = "testString"; LocalDate date = LocalDate.now(); Task task = new Task(content, date); @Test void getContent() { assertEquals(content, task.getContent()); } @Test void getDate() { assertEquals(LocalDate.now(), date); } }
Python
UTF-8
433
4.28125
4
[]
no_license
""" Problem: Leia um valor de volume em metros cúbicos e apresente-o em litros A formula de conversão é: L = 1000 * M Sendo L o volume em litros e M o volume em metros cúbicos Author: João Lucas Pycamp """ print('======= Metros cúbicos em Litros =======') m = float(input('Valor do metro cúbico \n')) litros = round(1000 * m, 2) print('{0} metros cúbicos e igual a {1} litros'.format(m, litros))
Markdown
UTF-8
5,943
2.53125
3
[]
no_license
# Algorithm-Design Laboratory solutions for the Algorithm Design course @ Faculty of Automatic Control and Computer Science, Politehnica University of Bucharest. * **Lab 1**: * Divide et Impera [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator1) * Count Occurrences [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator1/java/task-1) * SQRT [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator1/java/task-2) * ZParsing [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator1/java/task-3) * Logarithmic Exponentiation [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator1/java/task-4) * Inversions [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator1/java/bonus-lab1pa) * **Lab 2**: * Greedy [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator2) * Fractional Knapsack Problem [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator2/java/task-1) * Distances [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator2/java/task-2) * Homeworks [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator2/java/task-3) * Dishonest Sellers [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator2/java/bonus-lab2-pa) * **Lab 3**: * Dynamic Programming I [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator3) * The minimum number of coins with which the sum S can be formed [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator3/java/task-1) * The longest common subsequence [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator3/java/task-2) * Cages [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator3/java/bonus-lab3-pa) * **Lab 4**: * Dynamic Programming II [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator4) * Number of subsequences with even sum [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator4/java/task-1) * Boolean Parenthesization Problem [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator4/java/task-2) * Rabbits (Matrix Exponentiation) [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator4/java/bonus-lab4-pa-iepuri) * **Lab 5**: * Backtracking [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator5) * Arrangements [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator5/java/task-1) * Subsets [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator5/java/task-2) * N Queen Problem [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator5/java/task-3) * Generate Strings [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator5/java/task-4) * **Lab 6**: * Minimax [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator6) * Nim [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator6/java/Nim) * Reversi [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator6/java/Reversi) * **Lab 7**: * Graph Traversals. Topological Sort [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator7) * BFS [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator7/java/task-1) * Topological Sort [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator7/java/task-2) * Lee Algorithm [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator7/java/Bonus-lab7-PA) * **Lab 8**: * DFS Applications [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator8) * Strongly Connected Components (Kosaraju Algorithm + Tarjan Algorithm) [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator8/java/task-1) * Cut Vertices (Articulation Points) [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator8/java/task-2) * Critical Edges [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator8/java/task-3) * Biconnected Components [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator8/java/ComponenteBiconexe) * **Lab 9**: * Shortest Path Problem [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator9) * Dijkstra Algorithm (Array&Heap Implementations) [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator9/java/task-1) * Bellman-Ford Algorithm [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator9/java/task-2) * Floyd-Warshall Algorithm [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator9/java/task-3) * Shortest Path Reconstruction (with Dijkstra) [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator9/java/Bonus-lab9-pa) * **Lab 10**: * Minimum Spanning Tree [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator10) * Kruskal Algorithm [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator10/java/task-1) * Prim Algorithm [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator10/java/task-2) * **Lab 11**: * Maximum Flow Problem [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator11) * Edmonds-Karp Algorithm [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator11/java/task-1) * **Lab 12**: * Heuristic Search Algorithms. A* [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator12) * PACMAN [source](https://github.com/danserboi/Algorithm-Design/tree/master/laborator12/java/task-1) ### Author * Florea-Dan Șerboi
Java
UTF-8
1,982
2.140625
2
[]
no_license
package tn.esprit.spring.control; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import tn.esprit.spring.entity.Rating; import tn.esprit.spring.service.RatingService; @RestController public class RatingRestControlImpl { @Autowired RatingService ratingService; // http://localhost:8081/SpringMVC/servlet/retrieve-all-ratings @GetMapping("/retrieve-all-ratings") @ResponseBody public List<Rating> getRatings() { List<Rating> list = ratingService.retrieveAllRatings(); return list; } //http://localhost:8081/SpringMVC/servlet/retrieve-rating/{rating-id} @GetMapping("/retrieve-rating/{rating-id}") @ResponseBody public Rating retrieveRating(@PathVariable("rating-id") String ratingId) { return ratingService.retrieveRating(ratingId); } // Ajouter Comment : http://localhost:8081/SpringMVC/servlet/add-rating @PostMapping("/add-rating") @ResponseBody public Rating addRating(@RequestBody Rating r) { Rating rating = ratingService.addRatings(r); return rating ; } //http://localhost:8081/SpringMVC/servlet/remove-rating/{rating-id} @DeleteMapping("/remove-rating/{rating-id}") @ResponseBody public void removeRating(@PathVariable("rating-id") String ratingId) { ratingService.deleteRatings(ratingId); } // http://localhost:8081/SpringMVC/servlet/modify-rating @PutMapping("/modify-rating") @ResponseBody public Rating modifyRating(@RequestBody Rating rating) { return ratingService.updateRatings(rating); } }
Go
UTF-8
2,223
2.765625
3
[]
no_license
package service import ( "fmt" "github.com/myrachanto/power/httperors" "github.com/myrachanto/power/model" r "github.com/myrachanto/power/repository" "github.com/myrachanto/power/support" ) var ( UserService userService = userService{} ) type redirectUser interface{ Create(customer *model.User) (*model.User, *httperors.HttpError) Login(auser *model.LoginUser) (*model.Auth, *httperors.HttpError) Logout(token string) (*httperors.HttpError) GetOne(id int) (*model.User, *httperors.HttpError) GetAll(users []model.User, search *support.Search) ([]model.User, *httperors.HttpError) Update(id int, user *model.User) (*model.User, *httperors.HttpError) Delete(id int) (*httperors.HttpSuccess, *httperors.HttpError) } type userService struct { } func (service userService) Create(user *model.User) (string, *httperors.HttpError) { if err := user.Validate(); err != nil { return "", err } s, err1 := r.Userrepo.Create(user) if err1 != nil { return "", err1 } return s, nil } func (service userService) Login(auser *model.LoginUser) (*model.Auth, *httperors.HttpError) { user, err1 := r.Userrepo.Login(auser) if err1 != nil { return nil, err1 } return user, nil } func (service userService) Logout(token string) (*httperors.HttpError) { err1 := r.Userrepo.Logout(token) if err1 != nil { return err1 } return nil } // func (service userService) GetOne(id int) (*model.User, *httperors.HttpError) { // user, err1 := r.Userrepo.GetOne(id) // if err1 != nil { // return nil, err1 // } // return user, nil // } // func (service userService) GetAll(users []model.User, search *support.Search) ([]model.User, *httperors.HttpError) { // users, err := r.Userrepo.GetAll(users, search) // if err != nil { // return nil, err // } // return users, nil // } func (service userService) Update(id int, user *model.User) (*model.User, *httperors.HttpError) { fmt.Println("update1-controller") fmt.Println(id) user, err1 := r.Userrepo.Update(id, user) if err1 != nil { return nil, err1 } return user, nil } func (service userService) Delete(id int) (*httperors.HttpSuccess, *httperors.HttpError) { success, failure := r.Userrepo.Delete(id) return success, failure }
JavaScript
UTF-8
5,833
2.828125
3
[]
no_license
var express = require('express'); var bodyParser = require('body-parser'); // Instanciamos a Express y definimos el puerto con el que trabajaremos. var app = express(); var port = process.env.PORT || 3525; // Convierte una petición recibida (POST-GET...) a objeto JSON. app.use(bodyParser.urlencoded({extended:false})); app.use(bodyParser.json()); // Imprimos en el navegador, que el servicio ha sido lanzado. app.get('/', function(req, res){ // Módulo de envío de estatus del servicio levantado. res.status(200).send({ message: 'GET Home route working fine!' }); // Módulo de errores, en el caso de que no se pueda acceder al puerto establecido. res.render('error', { message: err.message, error: err }); }); // Aquí imprimimos en consola los datos de la Aplicación como su puerto y cálculos. app.listen(port, function(){ // Dibujamos panel de bienvenida e informativo. console.log("|---------------------------------------------------------------|"); console.log("|---------------------------------------------------------------|"); console.log("|-------- BIENVENIDOS AL CALCULADOR SALARIO POR PROYECTO -------|"); console.log("|---------------------------------------------------------------|"); console.log("|-----------------------PARCIAL I-------------------------------|"); console.log("|--------------- MATERIA: DISEÑO WEB ADAPTABLE -----------------|"); console.log("|--------------- ESTUDIANTE: ROCÍO ORTIZ -----------------------|"); console.log("|---------------------------------------------------------------|"); console.log("|---------------------------------------------------------------| \n"); console.log(`INFORMACIÓN - PROYECTO CORRIENDO EN LA RUTA://localhost:${port}/`); console.log("\n"); // Mostramos los datos de los integrantes del proyecto. console.log("INTEGRANTES DEL PROYECTO - (EXPO-DESING): "); console.log(" 1- John Doe Martínez, Diseñador Web."); console.log(" 2- Ceci Ohm Griffinn, Tester UX/UI."); console.log(" 3- Karla Ohmspring's, Desarrolladora Web."); console.log(" 4- Simon Smith Dogmi, Administrador de BD. \n"); // Instanciamos la función que se encarga de cálcular y mostrar los datos del equipo. salaryJob(); }); function salaryJob() { // Declaramos variables para alamacenar el salario devengado por persona y por el equipo. var salarioTeam = 0.0, salarioPerson1 = 0.0, salarioPerson2=0.0, salarioPerson3 = 0.0, salarioPerson4 = 0.0; // Declaramos variables para asignar las horas trabajadas por c/u además del total del equipo. var totalHorasTeam = 0.0, horas1 = 55, horas2 = 45, horas3 = 65, horas4 = 50; // Declaramos variables para asignar el total de horas trabajadas por c/u del equipo. var pagoPerson1 = 22.30, pagoPerson2 = 18.50, pagoPerson3 = 14.50, pagoPerson4 = 19.80; // Valor de la holgura y total extra. var hlg = 0.08, totalHlg = 0.0, totalMateriales = 785.00, totalProject = 0.0, totalProjectHlg = 0.0; console.log("|---------------------------------------------------------------|"); console.log("|-------------- SALARIO DEVENGADO C/U POR PROYECTO -------------|"); console.log("|---------------------------------------------------------------| \n"); // Proceso de cálculo de salario, para trabajador 1: salarioPerson1 = horas1 * pagoPerson1; console.log(" 1- John Doe Martínez, Diseñador Web."); console.log(" Horas trabajadas: ", horas1); console.log(" Pago por hora: $", pagoPerson1); console.log(" Pago total proyecto: $", salarioPerson1, "\n"); // Proceso de cálculo de salario, para trabajador 2: salarioPerson2 = horas2 * pagoPerson2; console.log(" 2- Ceci Ohm Griffinn, Tester UX/UI."); console.log(" Horas trabajadas: ", horas2); console.log(" Pago por hora: $", pagoPerson2); console.log(" Pago total proyecto: $", salarioPerson2, "\n"); // Proceso de cálculo de salario, para trabajador 3: salarioPerson3 = horas3 * pagoPerson3; console.log(" 3- Karla Ohmspring's, Desarrolladora Web."); console.log(" Horas trabajadas: ", horas3); console.log(" Pago por hora: $", pagoPerson3); console.log(" Pago total proyecto: $", salarioPerson3, "\n"); // Proceso de cálculo de salario, para trabajador 4: salarioPerson4 = horas4 * pagoPerson4; console.log(" 4- Simon Smith Dogmi, Administrador de BD."); console.log(" Horas trabajadas: ", horas4); console.log(" Pago por hora: $", pagoPerson4); console.log(" Pago total proyecto: $", salarioPerson4, "\n"); console.log("|---------------------------------------------------------------|"); console.log("|--------------- DATOS GENERALES DEL PROYECTO ------------------|"); console.log("|---------------------------------------------------------------| \n"); // Proceso de cálculo de datos generales del proyecto. salarioTeam = salarioPerson1 + salarioPerson2 + salarioPerson3 + salarioPerson4; totalHorasTeam = horas1 + horas2 + horas3 + horas4; totalProject = salarioTeam + totalMateriales; totalHlg = totalProject * hlg; totalProjectHlg = totalProject + totalHlg; // Creamos una función que almacena en un array los datos cálculados anteriormente. function devolverArrayDatos() { // Insertamos en el Array los datos cálculados. var miArray = [salarioTeam, totalMateriales,totalHorasTeam, totalProject, totalHlg, totalProjectHlg]; // Retornamos los valores return miArray; }; // Volcamos los datos en variables para su impresión. var [a, b, c, d, e,f] = devolverArrayDatos(); console.log("Total de salario devengado por el equipo: $", a); console.log("Total de costo materiales: $", b); console.log("Total de horas trabajadas por el equipo: $", c); console.log("Total de desarrollo por el proyecto (materiales + salario del equipo): $", d); console.log("Total de holgura: $", e); console.log("Total del proyecto con holgura: $", f); } module.exports = { salaryJob : salaryJob }
Java
UTF-8
368
2.359375
2
[]
no_license
package com.cucci.service; import com.cucci.annations.AutoWired; import com.cucci.annations.Bean; /** * C服务 * * @author shenyunwen **/ @Bean public class ServiceC { @AutoWired private ServiceA serviceA; public void say() { serviceA.say(); System.out.println("3333333333"); System.out.println("i'm in ServiceC"); } }
PHP
UTF-8
484
2.734375
3
[ "BSD-4-Clause-UC", "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "TCL", "ISC", "Zlib", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "blessing", "MIT" ]
permissive
--TEST-- Bug #72957: Null coalescing operator doesn't behave as expected with SimpleXMLElement --SKIPIF-- <?php if (!extension_loaded("simplexml")) print "skip simplexml extension is not loaded"; ?> --FILE-- <?php $xml = new SimpleXMLElement('<root><elem>Text</elem></root>'); echo 'elem2 is: ' . ($xml->elem2 ?? 'backup string') . "\n"; echo 'elem2 is: ' . (isset($xml->elem2) ? $xml->elem2 : 'backup string') . "\n"; ?> --EXPECT-- elem2 is: backup string elem2 is: backup string
Java
UTF-8
2,341
2.390625
2
[]
no_license
package main.com.java.entity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name="orderitem") public class OrderItem { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="orderItemID") private long orderItemID; @Column(name="amount") private long amount; @Column(name="accountNumberSender") private String accountNumberSender; @Column(name="accountNumberReceiver") private String accountNumberReceiver; // @ManyToOne // @JoinColumn(name="accountNumberSender", insertable = false, updatable = false) // private Account senderAccount; // // @ManyToOne // @JoinColumn(name="accountNumberReceiver", insertable = false, updatable = false) // private Account receiverAccount; public OrderItem() {} public OrderItem(long amount, String accountNumberSender, String accountNumberReceiver) { this.amount = amount; this.accountNumberSender = accountNumberSender; this.accountNumberReceiver = accountNumberReceiver; } // // public Account getSenderAccount() { // return senderAccount; // } // // public Account getReceiverAccount() { // return receiverAccount; // } // // public void setSenderAccount(Account senderAccount) { // this.senderAccount = senderAccount; // } // // public void setReceiverAccount(Account receiverAccount) { // this.receiverAccount = receiverAccount; // } public long getOrderItemID() { return orderItemID; } public void setOrderItemID(long orderItemID) { this.orderItemID = orderItemID; } public long getAmount() { return amount; } public void setAmount(long amount) { this.amount = amount; } public String getAccountNumberSender() { return accountNumberSender; } public void setAccountNumberSender(String accountNumberSender) { this.accountNumberSender = accountNumberSender; } public String getAccountNumberReceiver() { return accountNumberReceiver; } public void setAccountNumberReceiver(String accountNumberReceiver) { this.accountNumberReceiver = accountNumberReceiver; } }
Java
UTF-8
2,014
2.1875
2
[]
no_license
package com.project.interfacebuilder.http.actions; import java.util.Map; import com.project.datasource.DataSource; import com.project.inspection.FilterItem; import com.project.interfacebuilder.Action; import com.project.interfacebuilder.InterfaceException; import com.project.interfacebuilder.http.HTTPController; import com.project.interfacebuilder.http.forms.HTTPDataRangeForm; import com.project.interfacebuilder.http.forms.HTTPFilterForm; public class HTTPApplyFilterAction extends HTTPApplyActionSupport<FilterItem> { public HTTPApplyFilterAction() { super("ApplyFilter"); } @Override public void perform() throws InterfaceException { checkState(); // check if parameters are valid DataSource dataSource=(DataSource) controller.getAttribute(HTTPController.DATA_SOURCE_ATTRIBUTE); if(dataSource==null) throw new InterfaceException(HTTPController.DATA_SOURCE_ATTRIBUTE+" must be set before applying HTTPApplyFilterAction"); @SuppressWarnings("unchecked") java.util.List<Action> actions=(java.util.List<Action>)controller.getAttribute(HTTPController.ACTIONS_ATTRIBUTE); if(actions==null) throw new InterfaceException(HTTPController.ACTIONS_ATTRIBUTE+" must be set after HTTPBrowseForm submission"); Map<String,String[]> requestParametersMap=controller.getParameters(); if(!(getSourceForm() instanceof HTTPFilterForm)) throw new InterfaceException("source form must be an instance of HTTPFilterForm"); if(!(getTargetForm() instanceof HTTPDataRangeForm)) throw new InterfaceException("target form must be an instance of HTTPDataRangeForm"); HTTPDataRangeForm dataRangeForm=(HTTPDataRangeForm)getTargetForm(); dataRangeForm.setDataSource(dataSource); synchronizeValuesAndParameters( dataSource, dataSource.getFilter(), requestParametersMap,actions); dataRangeForm.setStart(HTTPDataRangeForm.RANGE_UNDEFINED); dataRangeForm.setFinish(HTTPDataRangeForm.RANGE_UNDEFINED); super.perform(); } }
C#
UTF-8
943
3.296875
3
[]
no_license
using P03._Database_Before.Contracts; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace P03._Database_Before { class MemoryCourseData : ICourseData { private List<Course> courses; public MemoryCourseData() { courses = new List<Course>() { new Course(){Id=5, Name="C# OOP"}, new Course(){Id=12, Name="Python OOP"}, new Course(){Id=16, Name="Java OOP"}, new Course(){Id=5, Name="JavaScript"} }; } public IEnumerable<int> CourseIds() { return courses.Select(c => c.Id); } public IEnumerable<string> CourseNames() { return courses.Select(c => c.Name); } public string GetCourseById(int id) { return courses.First(c => c.Id == id).Name; } } }
JavaScript
UTF-8
1,585
3.96875
4
[]
no_license
/* SOLUTION Similar to findPermutation, but instead of returning true when the first match is found, continue to iterate over the entire string looking for all the matches and returning an array of the starting indices of the matches. Time: O(n) where n is the length of the input string Space: O(m) where m is the length of the pattern */ const find_string_anagrams = function(str, pattern) { let resultIndexes = []; const charFreq = {}; let left = 0; let matched = 0; let windowSize = 0; // add pattern to hashmap for(let ch of pattern){ if(charFreq[ch]) charFreq[ch]++; else charFreq[ch] = 1; } for(let right=0; right<str.length; right++){ let curr = str[right]; windowSize = right - left + 1; if(curr in charFreq){ if(--charFreq[curr] === 0) matched++; } if(windowSize > pattern.length){ let prev = str[left++]; if(prev in charFreq){ if(++charFreq[prev] > 0) matched--; } } console.log('currChar', curr, 'matched', matched, 'charFreq', charFreq); if(matched === Object.keys(charFreq).length){ resultIndexes = [...resultIndexes, left]; } } return resultIndexes; }; const inputSet = [ { str: 'ppqp', pattern: 'qp', expected: [1,2], }, { str: 'abbcabc', pattern: 'abc', expected: [2,3,4], }, ]; for(input of inputSet){ console.log(input, `actual: [${find_string_anagrams(input.str, input.pattern)}]`); }
Java
UTF-8
1,477
2.125
2
[]
no_license
package com.sukinsan.pixelgame.activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import com.sukinsan.pixelgame.R; import com.sukinsan.pixelgame.utils.SystemUtils; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); SystemUtils.initFullScreen(this); getWindow().getDecorView().getRootView(); findViewById(R.id.btn_create).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, ServerActivity.class)); } }); findViewById(R.id.btn_join).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(MainActivity.this, GamePadActivity.class)); } }); findViewById(R.id.btn_exit).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); } @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); SystemUtils.restoreFullScreen(this, hasFocus); } }
Java
UTF-8
208
1.851563
2
[]
no_license
package Lista_05_03_2018Exer2; import java.util.List; public class Localidade { private String nome; private String facilidadeDeTransporte; private List<Localidade> localdiadeVizinhas; }
C++
UTF-8
1,080
2.515625
3
[]
no_license
#ifndef A_WINDOW_H # define A_WINDOW_H # include "IMonitorModule.hpp" # include <ncurses.h> # include <string> class AWindow { public: AWindow(void); AWindow(int, int, int, int); virtual ~AWindow(void); AWindow(AWindow const &src); AWindow& operator=(AWindow const &rhs); virtual void init(void); WINDOW *getWin(void) const; // const std::string &getTitle(void) const; // int getH(void) const; // int getW(void) const; // int getX(void) const; // int getY(void) const; virtual void serialize(std::ostream &stream) const; virtual std::string readUser(void) const; virtual void notifyUser(const std::string&) const; virtual void setTitle(const std::string&); virtual void printText(const std::string &str) const; virtual void showGraph(IMonitorModule::sData &d) const; protected: WINDOW *_wwin; WINDOW *_wuser; int _wh; int _ww; int _wy; int _wx; std::string _wtitle; void setDefaultSize(void); private: }; std::ostream& operator<<(std::ostream& stream, AWindow const &s); #endif
Java
UTF-8
3,830
2.5
2
[]
no_license
package onion.bookapp.DB.Impl; import onion.bookapp.DB.DAO.GoodsDAO; import onion.bookapp.mybean.data.Goods; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class GoodsDAOImpl implements GoodsDAO { private Connection conn=null; private PreparedStatement pstmt=null; public GoodsDAOImpl(Connection conn){this.conn=conn;} public boolean insert(Goods goods) throws Exception { boolean flag=false; String sql="Insert into goods(goodsid,publisherid,images,publishTime,price,title,detail,sort)Values(?,?,?,?,?,?,?,?)"; try { this.pstmt=this.conn.prepareStatement(sql); this.pstmt.setString(1,goods.getGoodsid()); this.pstmt.setString(2,goods.getPublisherid()); this.pstmt.setString(3,goods.getImages()); this.pstmt.setString(4,goods.getPublishTime()); this.pstmt.setString(5,goods.getPrice()); this.pstmt.setString(6,goods.getTitle()); this.pstmt.setString(7,goods.getDetail()); this.pstmt.setString(8,goods.getSort()); if (this.pstmt.executeUpdate()>0){ flag=true; } this.pstmt.close(); }catch (SQLException e){ e.printStackTrace(); throw new Exception(); } return flag; } public ResultSet search(String keyword) { try{ String sql = "select goodsid,images,title,price from goods where title like ? or detail like ?"; pstmt=conn.prepareStatement(sql); pstmt.setString(1,"%"+keyword+"%"); pstmt.setString(2,"%"+keyword+"%"); return pstmt.executeQuery(); }catch (SQLException e){ e.printStackTrace(); } return null; } @Override public ResultSet screenSearch(String words, String city, String university, int num, int index, String sort) throws Exception { boolean tag=false; String sql="select goodsid,images,title,price,city,university from goods"; if(words!=""){ sql+=" where title like ?"; tag=true; } if (city!=""){ if (tag==true) sql+=" and"; else{ tag=true; sql+=" where"; } sql+=" city=?"; } if (university!=""){ if (tag==true) sql+=" and"; else{ tag=true; sql+=" where"; } sql+=" university=?"; } if (sort!=""){ if (tag==true) sql+=" and"; else{ tag=true; sql+=" where"; } sql+=" sort=?"; } sql+=" limit ?,?"; System.out.println(sql); System.out.println(city); try{ pstmt=conn.prepareStatement(sql); int i=1; if(words!="")pstmt.setString(i++,"%"+words+"%"); if(city!="")pstmt.setString(i++,city); if (university!="")pstmt.setString(i++,university); if (sort!="")pstmt.setString(i++,sort); pstmt.setInt(i++,index); pstmt.setInt(i++,num); System.out.println(pstmt.toString()); return pstmt.executeQuery(); } catch (Exception e){ throw e; } } @Override public ResultSet getdeatil(String goodsid) throws Exception { String sql="select * from goods where goodsid=?"; try{ pstmt=conn.prepareStatement(sql); pstmt.setString(1,goodsid); return pstmt.executeQuery(); }catch(Exception e){ throw e; } } }
C
UTF-8
458
3.59375
4
[]
no_license
#include <stdio.h> int main(void) { int i, n, niz[25], suma = 0; // Promenljive u vezi zadatka printf("Unesite velicinu niza: "); scanf("%d", &n); for(i = 0; i < n; i++) { printf("Unesite niz[%d] = ", i); scanf("%d", &niz[i]); suma = suma + niz[i]; // Racunanje sume elemenata u nizu } printf("Suma elemenata niza je: %d\n", suma); printf("Broj elemenata niza je: %d", n); return 0; }
Python
UTF-8
805
3.09375
3
[]
no_license
import numpy as np def vipp(x, y, t, w): """ From original MATLAB code See https://code.google.com/p/carspls/ #+++ vip=vipp(x,y,t,w); #+++ t: scores, which can be obtained by pls_nipals.m #+++ w: weight, which can be obtained by pls_nipals.m #+++ to calculate the vip for each variable to the response; #+++ vip=sqrt(p*q/s); """ #initializing [p, h] = w.shape co = np.matrix(np.zeros([1, h])) # Calculate s for ii in range(h): corr = np.corrcoef(y, t[:, ii], rowvar=0) co[0, ii] = corr[0, 1]**2 s = np.sum(co) # Calculate q # This has been linearized to replace the original nested for loop w_power = np.power(w, 2) d = np.multiply(w_power, co) q = np.sum(d, 1) vip = np.sqrt(p*q/s) return vip