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
Python
UTF-8
254
2.9375
3
[]
no_license
def solution(array, commands): answer = [] for a in range(len(commands)): i, j, k = commands[a][0], commands[a][1], commands[a][2] arr = array[i-1:j] arr.sort() answer.append(arr[k-1]) return answer
Markdown
UTF-8
1,328
2.828125
3
[ "Apache-2.0" ]
permissive
# Examples This directory contains examples for how to use the Planet SDK for Python. # Navigation Each example script is named according to the convention `<Planet API>_<use_case>.py`. ## Usage To use these examples, just run the scripts with `python <script_name>`. These examples hit the Planet services, so be aware that usage and fees may apply. ## Contributing New examples are great! They just need to meet two requirements. First off, the name of the new example needs to follow the examples naming convention. Second, the new example needs to be tested. All examples in this directory are tested as a part of an automated test suite. The testing is conducted by `test_examples.py`. All scripts should default to downloading into the directory pointed to by the `TEST_DOWNLOAD_DIR` environment variable, with logic for when that variable is missing. For example, `DOWNLOAD_DIR = os.getenv('TEST_DOWNLOAD_DIR', '.')`. Running all example script tests is a long process and also, since each script communicates with the Planet servers, could affect your usage and incur fees. To minimize the pain, filter the scripts tested to e.g. the script under development with: ```console > nox -s examples -- <script_name>.py ```` For a new script named `new_script.py`, this would be `nox -s examples -- new_script.py`
Python
UTF-8
2,687
3.125
3
[ "Apache-2.0" ]
permissive
import re import sys ## class count_instances(dict): '''Instance counter implemented as a Dict subclass. Elements are stored as dictionary keys and their counts are stored as dictionary values. NOTE: An alternative to this can be using the Counter object in Collections, which may provide a more wider range of functionality than this fuction ''' def __init__(*args, **kwds): '''Initial an empty object for counting instances. ''' self, *args = args super(count_instances, self).__init__() self.update(*args, **kwds) def __missing__(self, key): '''This ensures that a missing key does not raise KeyError ''' return 0 def sort_by_val(self, n=None): '''Function to sort through the counted instances using the values first and then in case of ties, alphabetically ''' if n is None: n=len(self.items()) return sorted(self.items(), key=lambda item: (-item[1], item[0]), reverse = False)[:n] ## def clean(line): '''This function is used to process through a line from the file if parsing does not work properly ''' # We first search for and ignore any special characters which may effect REGEX line = re.sub(r'(?i)[^a-z0-9;" +-]','',line) # Find portions of string within " ", look for ';' and replace them matches = re.findall('\".+?\"',line) for match in matches: line = re.sub(''.join(match),''.join(match).replace(';',''),line) return [s.strip() for s in line.split(";")] ## def get_indices(header): '''This function is used to get valid indices from the header of each file Files prior to 2014 have the first format while the laters ones have the second one. ''' try: idx1 = header.index('LCA_CASE_SOC_NAME') idx2 = header.index('LCA_CASE_WORKLOC1_STATE') idx3 = header.index('STATUS') except: idx1 = header.index('SOC_NAME') idx2 = header.index('WORKSITE_STATE') idx3 = header.index('CASE_STATUS') return idx1,idx2,idx3 ## def write_output(sorted_list,total,nfile): '''This function is used to generate the top10**.txt files as requested''' if nfile.find('state') != -1: op_header = ('TOP_STATES','NUMBER_CERTIFIED_APPLICATIONS','PERCENTAGE') elif nfile.find('occupation') != -1: op_header = ('TOP_OCCUPATIONS','NUMBER_CERTIFIED_APPLICATIONS','PERCENTAGE') with open(nfile,'w') as op_file: print('%s;%s;%s' %op_header,file=op_file) for item in sorted_list: print('%s;%i;%0.1f%%' %(item[0],item[1],item[1]*100/total),file=op_file) op_file.close()
C++
UTF-8
623
2.734375
3
[]
no_license
class Solution { public: //bucket sort vector<int> topKFrequent(vector<int>& a, int k) { unordered_map<int,int> mp; for(auto x:a) mp[x]++; int n=a.size(); vector<int> buck[n+1]; for(auto &x:mp) buck[x.second].push_back(x.first); vector<int> res; for(int i=n;i>=0 and res.size()<k;i--) { for(auto &x:buck[i]) { res.push_back(x); if(res.size()==k) break; } } return res; } };
Rust
UTF-8
933
3.15625
3
[]
no_license
#[cfg(test)] mod tests { use super::*; #[test] fn it_works() { assert_eq!(Solution::num_decodings("12".to_string()), 2); assert_eq!(Solution::num_decodings("226".to_string()), 3); assert_eq!(Solution::num_decodings("06".to_string()), 0); } } struct Solution {} impl Solution { pub fn num_decodings(s: String) -> i32 { if s.len() == 0 { return 0; } let mut dp = vec![0; s.len()+1]; dp[0] = 1; let bytes = s.as_bytes(); if bytes[0] == b'0' { dp[1] = 0; } else { dp[1] = 1; } for i in 2..dp.len() { if bytes[i-1] != b'0' { dp[i] += dp[i-1]; } let sum = (bytes[i-2] - b'0') * 10 + bytes[i-1] - b'0'; if sum >= 10 && sum <= 26 { dp[i] += dp[i-2]; } } dp[s.len()] } }
C#
UTF-8
6,680
2.609375
3
[]
no_license
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using GHIElectronics.TinyCLR.UI.Input; namespace GHIElectronics.TinyCLR.UI.Controls { public class ListBox : ContentControl { public ListBox() { this._panel = new StackPanel(); this._scrollViewer = new ScrollViewer { Child = this._panel }; this.LogicalChildren.Add(this._scrollViewer); } public ListBoxItemCollection Items { get { VerifyAccess(); if (this._items == null) { this._items = new ListBoxItemCollection(this, this._panel.Children); } return this._items; } } public event SelectionChangedEventHandler SelectionChanged { add { VerifyAccess(); this._selectionChanged += value; } remove { VerifyAccess(); this._selectionChanged -= value; } } public int SelectedIndex { get => this._selectedIndex; set { VerifyAccess(); if (this._selectedIndex != value) { if (value < -1) { throw new ArgumentOutOfRangeException("SelectedIndex"); } var item = (this._items != null && value >= 0 && value < this._items.Count) ? this._items[value] : null; if (item != null && !item.IsSelectable) { throw new InvalidOperationException("Item is not selectable"); } var previousItem = this.SelectedItem; if (previousItem != null) { previousItem.OnIsSelectedChanged(false); } var args = new SelectionChangedEventArgs(this._selectedIndex, value); this._selectedIndex = value; if (item != null) { item.OnIsSelectedChanged(true); } this._selectionChanged?.Invoke(this, args); } } } public ListBoxItem SelectedItem { get { if (this._items != null && this._selectedIndex >= 0 && this._selectedIndex < this._items.Count) { return this._items[this._selectedIndex]; } return null; } set { VerifyAccess(); var index = this.Items.IndexOf(value); if (index != -1) { this.SelectedIndex = index; } } } public void ScrollIntoView(ListBoxItem item) { VerifyAccess(); if (!this.Items.Contains(item)) return; this._panel.GetLayoutOffset(out var panelX, out var panelY); item.GetLayoutOffset(out var x, out var y); var top = y + panelY; var bottom = top + item._renderHeight; // Make sure bottom of item is in view // if (bottom > this._scrollViewer._renderHeight) { this._scrollViewer.VerticalOffset -= (this._scrollViewer._renderHeight - bottom); } // Make sure top of item is in view // if (top < 0) { this._scrollViewer.VerticalOffset += top; } } protected override void OnButtonDown(GHIElectronics.TinyCLR.UI.Input.ButtonEventArgs e) { if (e.Button == HardwareButton.Down && this._selectedIndex < this.Items.Count - 1) { var newIndex = this._selectedIndex + 1; while (newIndex < this.Items.Count && !this.Items[newIndex].IsSelectable) newIndex++; if (newIndex < this.Items.Count) { this.SelectedIndex = newIndex; ScrollIntoView(this.SelectedItem); e.Handled = true; } } else if (e.Button == HardwareButton.Up && this._selectedIndex > 0) { var newIndex = this._selectedIndex - 1; while (newIndex >= 0 && !this.Items[newIndex].IsSelectable) newIndex--; if (newIndex >= 0) { this.SelectedIndex = newIndex; ScrollIntoView(this.SelectedItem); e.Handled = true; } } } // // Scrolling events re-exposed from the ScrollViewer // /// <summary> /// Event handler if the scroll changes. /// </summary> public event ScrollChangedEventHandler ScrollChanged { add { this._scrollViewer.ScrollChanged += value; } remove { this._scrollViewer.ScrollChanged -= value; } } /// <summary> /// Horizontal offset of the scroll. /// </summary> public int HorizontalOffset { get => this._scrollViewer.HorizontalOffset; set => this._scrollViewer.HorizontalOffset = value; } /// <summary> /// Vertical offset of the scroll. /// </summary> public int VerticalOffset { get => this._scrollViewer.VerticalOffset; set => this._scrollViewer.VerticalOffset = value; } /// <summary> /// Extent height of the scroll area. /// </summary> public int ExtentHeight => this._scrollViewer.ExtentHeight; /// <summary> /// Extent width of the scroll area. /// </summary> public int ExtentWidth => this._scrollViewer.ExtentWidth; /// <summary> /// The scrolling style. /// </summary> public ScrollingStyle ScrollingStyle { get => this._scrollViewer.ScrollingStyle; set => this._scrollViewer.ScrollingStyle = value; } internal ScrollViewer _scrollViewer; internal StackPanel _panel; private int _selectedIndex = -1; private SelectionChangedEventHandler _selectionChanged; private ListBoxItemCollection _items; } }
C#
UTF-8
1,921
2.59375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Mysterious_Insiders.Services; using Mysterious_Insiders.Models; namespace Mysterious_Insiders.Controllers { [Route("api/[controller]")] [ApiController] public class SheetsController : ControllerBase { private readonly SheetService sheetService; public SheetsController(SheetService service) { sheetService = service; } [HttpGet] public ActionResult<List<ModularSheet>> Get() { return sheetService.Get(); } [HttpGet("{id:length(24)}", Name = "GetSheet")] public ActionResult<ModularSheet> Get(string id) { var sheet = sheetService.Get(id); if(sheet == null) { return NotFound(); } return sheet; } [HttpPost] public ActionResult<ModularSheet> Create(ModularSheet sheet) { sheetService.Create(sheet); return CreatedAtRoute("GetSheet", new { id = sheet.DatabaseId.ToString() }, sheet); } [HttpPut("{id:length(24)}")] public IActionResult Update(string id, ModularSheet sheetIn) { var sheet = sheetService.Get(id); if (sheet == null) { return NotFound(); } sheetService.Update(id, sheetIn); return NoContent(); } [HttpDelete("{id:length(24)}")] public IActionResult Delete(string id) { var sheet = sheetService.Get(id); if (sheet == null) { return NotFound(); } sheetService.Remove(sheet.DatabaseId); return NoContent(); } } }
Python
UTF-8
656
4.09375
4
[]
no_license
import turtle def drawSnake(rad, angle, len, neckrad): for i in range(len): turtle.pencolor("red") turtle.circle(rad, angle) turtle.pencolor("black") turtle.circle(-rad, angle) turtle.pencolor("green") turtle.circle(rad, angle/2) turtle.pencolor("yellow") turtle.fd(rad) turtle.pencolor("purple") turtle.circle(neckrad+1, 180) turtle.pencolor("cyan") turtle.fd(rad*2/3) def main(): turtle.setup(1300, 700, 0, 0) pythonsize = 30 turtle.pensize(pythonsize) turtle.pencolor("red") turtle.seth(-40) drawSnake(30, 80, 5, pythonsize/2) main()
Python
UTF-8
474
3.296875
3
[]
no_license
class Letter: """ Class qui definie une variable dans une regle Dans: A + B => C A, B et C sont des Letter Elle contient une valeur "True" ou "False" qui servira a la resolution de l'expert system """ def __init__(self, letter): self.letter = letter self.value = False def setTrue(self): """Apeller au moment du parser, potentiellement au moment ou on push dans factsBase""" self.value = True
Java
UTF-8
674
1.851563
2
[]
no_license
package com.github.springwebflux.reposity; import com.github.springwebflux.entity.DockerEvent; import org.springframework.data.mongodb.repository.ReactiveMongoRepository; import org.springframework.data.mongodb.repository.Tailable; import reactor.core.publisher.Flux; /** * @author: <a href="mailto:lingxiao@2dfire.com">凌霄</a> * @time: Created in 下午11:40 2018/9/17 * @desc */ public interface DockerEventMongoRepository extends ReactiveMongoRepository<DockerEvent, String> { @Tailable Flux<DockerEvent> findByStatus(String status); @Tailable Flux<DockerEvent> findByTypeAndFrom(String type, String from); @Tailable Flux<DockerEvent> findBy(); }
Java
UTF-8
1,742
3.0625
3
[]
no_license
package com.putoet.day10; import org.junit.Test; import java.util.Arrays; import java.util.Map; import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertTrue; public class AstroidMapTest { final AstroidMap astroidMap = AstroidMap.of(new String[] { ".#..#", ".....", "#####", "....#", "...##"}); private Astroid[] astroids = new Astroid[]{ new Astroid(new Point(1, 0)), new Astroid(new Point(4, 0)), new Astroid(new Point(1, 2)), new Astroid(new Point(0, 2)), new Astroid(new Point(2, 2)), new Astroid(new Point(3, 2)), new Astroid(new Point(4, 2)), new Astroid(new Point(4, 3)), new Astroid(new Point(3, 4)), new Astroid(new Point(4, 4)) }; @Test public void testAstroidMapOf() { assertTrue(astroidMap.astroids().containsAll(Arrays.asList(astroids))); // // final Map<Astroid, LineOfSightMap> lineOfSightMaps = astroidMap.linesOfSightMaps(); // lineOfSightMaps.forEach((k, v) -> System.out.println(v)); } @Test public void testLeastVisible() { final Map<Astroid, LineOfSightMap> lineOfSightMaps = astroidMap.linesOfSightMaps(); assertEquals(5, lineOfSightMaps.entrySet().stream().mapToInt(entry -> entry.getValue().inLineOfSightCount()).min().getAsInt()); } @Test public void testMaxVisible() { final Map<Astroid, LineOfSightMap> lineOfSightMaps = astroidMap.linesOfSightMaps(); assertEquals(8, lineOfSightMaps.entrySet().stream().mapToInt(entry -> entry.getValue().inLineOfSightCount()).max().getAsInt()); } }
SQL
UTF-8
292
2.890625
3
[]
no_license
SELECT * FROM study.cz88_ip WHERE inet_aton('192.247.24.30') BETWEEN inet_aton (minIp) AND inet_aton(maxIp); SELECT * FROM study.cz88_ip; SELECT location FROM study.cz88_ip WHERE inet_aton("192.168.1.1") BETWEEN inet_aton (minIp) AND inet_aton(maxIp); SHOW FULL COLUMNS FROM study.cz88_ip
Java
UTF-8
688
2.328125
2
[]
no_license
package com.semm.core.servicios; import java.io.Serializable; import java.util.Set; public class Lista implements Serializable{ private long id; private String nombre; private Set<Cliente> clientes; private Usuario owner; public Set<Cliente> getClientes() { return clientes; } public void setClientes(Set<Cliente> clientes) { this.clientes = clientes; } public Usuario getOwner() { return owner; } public void setOwner(Usuario owner) { this.owner = owner; } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } }
Java
UTF-8
1,977
3.59375
4
[]
no_license
/* * @lc app=leetcode id=1073 lang=java * * [1073] Adding Two Negabinary Numbers * * https://leetcode.com/problems/adding-two-negabinary-numbers/description/ * * algorithms * Medium (31.27%) * Total Accepted: 2.7K * Total Submissions: 8.8K * Testcase Example: '[1,1,1,1,1]\n[1,0,1]' * * Given two numbers arr1 and arr2 in base -2, return the result of adding them * together. * * Each number is given in array format:  as an array of 0s and 1s, from most * significant bit to least significant bit.  For example, arr = [1,1,0,1] * represents the number (-2)^3 + (-2)^2 + (-2)^0 = -3.  A number arr in array * format is also guaranteed to have no leading zeros: either arr == [0] or * arr[0] == 1. * * Return the result of adding arr1 and arr2 in the same format: as an array of * 0s and 1s with no leading zeros. * * * * Example 1: * * * Input: arr1 = [1,1,1,1,1], arr2 = [1,0,1] * Output: [1,0,0,0,0] * Explanation: arr1 represents 11, arr2 represents 5, the output represents * 16. * * * * * Note: * * * 1 <= arr1.length <= 1000 * 1 <= arr2.length <= 1000 * arr1 and arr2 have no leading zeros * arr1[i] is 0 or 1 * arr2[i] is 0 or 1 * */ class Solution { public int[] addNegabinary(int[] arr1, int[] arr2) { LinkedList<Integer> res = new LinkedList<>(); int n1 = arr1.length; int n2 = arr2.length; int c = 0; int i = 0; while (n1 - i - 1 >= 0 || n2 - i - 1 >= 0 || c != 0) { int num1 = n1 - i - 1 >= 0 ? arr1[n1 - i - 1] : 0; int num2 = n2 - i - 1 >= 0 ? arr2[n2 - i - 1] : 0; int sum = num1 + num2 + c; res.addFirst(sum & 1); c = -1 * (sum >> 1); i++; } int cur = 0; while (cur < res.size() - 1 && res.get(cur) == 0) { cur++; } int[] resArr = new int[res.size() - cur]; for (int j = 0; j < resArr.length; j++) { resArr[j] = res.get(cur + j); } return resArr; } }
Java
GB18030
6,873
2.78125
3
[]
no_license
package com.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.OutputStream; import java.io.SequenceInputStream; import java.util.Arrays; import java.util.List; import java.util.Vector; import com.univocity.parsers.common.processor.BeanListProcessor; import com.univocity.parsers.common.processor.BeanWriterProcessor; import com.univocity.parsers.csv.CsvParser; import com.univocity.parsers.csv.CsvParserSettings; import com.univocity.parsers.csv.CsvWriter; import com.univocity.parsers.csv.CsvWriterSettings; public class CSVUtils { /** * csvļĿ¼ * @param filename ļ * @param headers ͷ * @param data * @param encoding ַ */ public static <T> void exportCsvFileToLocal(String filename, String[] headers, List<T> data, String encoding) { File outputFile = new File("D:/" + filename); CsvWriterSettings csvWriterSettings = new CsvWriterSettings(); // ļ(ѡݣԶд) csvWriterSettings.setHeaders(headers); // Ϊֶʹ com.univocity.parsers.annotations жע, ͨ BeanWriterProcessorֱֶӳ䵽RowWriterProcessorһ, "֪"νӳ䵽ֵ csvWriterSettings.setRowWriterProcessor(new BeanWriterProcessor<T>((Class<T>) data.get(0).getClass())); // Ϊôһwriter CsvWriter localWriter = new CsvWriter(outputFile, encoding, csvWriterSettings); //localWriter.writeRow(headers); // Ϊдָı localWriter.writeHeaders(); localWriter.processRecords(data); localWriter.close(); System.out.println("ļ" + filename + "ɹ"); } /** * csvļFTP * @param filename ļ * @param headers ͷ * @param data * @param dir · * @param encoding ַ */ public static <T> void exportCsvFileToFTP(String filename, String[] headers, List<T> data, String dir, String encoding) { CsvWriterSettings csvWriterSettings = new CsvWriterSettings(); // ļ(ѡݣԶд) csvWriterSettings.setHeaders(headers); // Ϊֶʹ com.univocity.parsers.annotations жע, ͨ BeanWriterProcessorֱֶӳ䵽RowWriterProcessorһ, "֪"νӳ䵽ֵ csvWriterSettings.setRowWriterProcessor(new BeanWriterProcessor<T>((Class<T>) data.get(0).getClass())); // FTP FTPUtils ftpUtils = new FTPUtils(); OutputStream outputStream = ftpUtils.getFTPOutputStream(FTPProperties.HOST, FTPProperties.PORT, FTPProperties.USER, FTPProperties.PASSWORD, filename, dir); CsvWriter ftpWriter = new CsvWriter(outputStream, encoding, csvWriterSettings); ftpWriter.writeHeaders(); ftpWriter.processRecords(data); ftpWriter.close(); System.out.println("ļдɹ"); ftpUtils.releaseSource(); } /** * FTPcsvļ * @param filename ļ * @param bean JavaBean * @param encoding ַ * @return Bean */ public static <T> List<T> importCsvFileFromFTP(String filename, T bean, String encoding) { CsvParserSettings csvParserSettings = new CsvParserSettings(); BeanListProcessor<T> beanListProcessor = new BeanListProcessor<T>((Class<T>) bean.getClass()); csvParserSettings.setProcessor(beanListProcessor); csvParserSettings.setHeaderExtractionEnabled(true); CsvParser parser = new CsvParser(csvParserSettings); FTPUtils ftpUtils = new FTPUtils(); InputStream inputStream = ftpUtils.getFTPInputStream(FTPProperties.HOST, FTPProperties.PORT, FTPProperties.USER, FTPProperties.PASSWORD, filename, FTPProperties.IMPORTDIR); if(inputStream == null) { return null; } parser.parse(inputStream, encoding); List<T> returnList = beanListProcessor.getBeans(); System.out.println("ļȡɹ"); ftpUtils.releaseSource(); return returnList; } /** * ӱصcsvļ * @param filename ļ * @param bean JavaBean * @param encoding ַ * @return Bean */ public static <T> List<T> importCsvFileFromLocal(String filename, T bean, String encoding) { CsvParserSettings csvParserSettings = new CsvParserSettings(); BeanListProcessor<T> beanListProcessor = new BeanListProcessor<T>((Class<T>) bean.getClass()); csvParserSettings.setProcessor(beanListProcessor); csvParserSettings.setHeaderExtractionEnabled(true); CsvParser parser = new CsvParser(csvParserSettings); File importFile = new File("D:/" + filename); if(!importFile.exists()) { System.out.println("Ҳļ: " + filename); return null; } parser.parse(importFile, encoding); List<T> returnList = beanListProcessor.getBeans(); System.out.println("ļȡɹ, " + importFile.getAbsolutePath()); return returnList; } /** * ӱĿ¼csvļ * @param direction ļ· * @param bean JavaBean * @param encoding ַ * @return Bean */ public static <T> List<T> importCsvFileFromLocalFolder(String direction, T bean, String encoding) { CsvParserSettings csvParserSettings = new CsvParserSettings(); BeanListProcessor<T> beanListProcessor = new BeanListProcessor<T>((Class<T>) bean.getClass()); csvParserSettings.setProcessor(beanListProcessor); csvParserSettings.setHeaderExtractionEnabled(true); CsvParser parser = new CsvParser(csvParserSettings); File folder = new File(direction); if(!folder.isDirectory()) { System.out.println(direction + " ·"); return null; } else { System.out.println("· " + direction + "ļȡʼ"); File[] files = folder.listFiles(); Vector<InputStream> vectorStreams = new Vector<InputStream>(); for (File file : files) { if(file.isFile()) { InputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } vectorStreams.add(inputStream); } } SequenceInputStream sequenceInputStream = new SequenceInputStream(vectorStreams.elements()); parser.parse(sequenceInputStream, encoding); List<T> returnList = beanListProcessor.getBeans(); System.out.println("ļȡɹ" + Arrays.toString(folder.list())); System.out.println("ܼ¼: " + returnList.size()); return returnList; } } }
C++
UTF-8
8,254
2.703125
3
[ "MIT" ]
permissive
#include "doctest.h" #include "FootSoldier.hpp" #include "FootCommander.hpp" #include"Paramedic.hpp" #include"ParamedicCommander.hpp" #include"Sniper.hpp" #include"SniperCommander.hpp" #include "Board.hpp" #include <iostream> using namespace std; namespace WarGame{ TEST_CASE("Test-1-soldiers") { Board board(8,8); CHECK(board.has_soldiers(1)==false); board[{0,0}] = new FootSoldier(1); board[{0,1}] = new FootSoldier(1); board[{0,2}] = new SniperCommander(1); board[{0,3}] = new FootCommander(1); board[{0,4}] = new FootSoldier(1); board[{0,5}] = new Sniper(1); board[{0,6}] = new ParamedicCommander(1); board[{0,7}] = new Paramedic(1); CHECK(board.has_soldiers(1)==true); CHECK(board.has_soldiers(2)==false); board[{7,0}] = new FootSoldier(2); board[{7,1}] = new FootSoldier(2); board[{7,2}] = new SniperCommander(2); board[{7,3}] = new FootCommander(2); board[{7,4}] = new FootSoldier(2); board[{7,5}] = new Sniper(2); board[{7,6}] = new ParamedicCommander(2); board[{7,7}] = new Paramedic(2); CHECK(board.has_soldiers(2)==true); CHECK(board[{0,0}]->_numOfplayer == 1); CHECK(board[{0,1}]->_numOfplayer == 1); CHECK(board[{0,2}]->_numOfplayer == 1); CHECK(board[{0,3}]->_numOfplayer == 1); CHECK(board[{0,4}]->_numOfplayer == 1); CHECK(board[{0,5}]->_numOfplayer == 1); CHECK(board[{0,6}]->_numOfplayer == 1); CHECK(board[{0,7}]->_numOfplayer == 1); CHECK(board[{7,0}]->_numOfplayer == 2); CHECK(board[{7,1}]->_numOfplayer == 2); CHECK(board[{7,2}]->_numOfplayer == 2); CHECK(board[{7,3}]->_numOfplayer == 2); CHECK(board[{7,4}]->_numOfplayer == 2); CHECK(board[{7,5}]->_numOfplayer == 2); CHECK(board[{7,6}]->_numOfplayer == 2); CHECK(board[{7,7}]->_numOfplayer == 2); CHECK(board[{0,2}]->_life == 120);//SniperCommander CHECK(board[{0,3}]->_life == 150);//FootCommander CHECK(board[{0,4}]->_life == 100);//FootSoldier CHECK(board[{0,5}]->_life == 100);//Sniper CHECK(board[{0,6}]->_life == 200);//ParamedicCommander CHECK(board[{0,7}]->_life == 100);//Paramedic CHECK(board[{0,2}]->_attack == 100);//SniperCommander CHECK(board[{0,3}]->_attack == 20);//FootCommander CHECK(board[{0,4}]->_attack == 10);//FootSoldier CHECK(board[{0,5}]->_attack == 50);//Sniper CHECK(board[{0,6}]->_attack == 0);//ParamedicCommander CHECK(board[{0,7}]->_attack == 0);//Paramedic CHECK(board[{7,2}]->_life == 120);//SniperCommander CHECK(board[{7,3}]->_life == 150);//FootCommander CHECK(board[{7,4}]->_life == 100);//FootSoldier CHECK(board[{7,5}]->_life == 100);//Sniper CHECK(board[{7,6}]->_life == 200);//ParamedicCommander CHECK(board[{7,7}]->_life == 100);//Paramedic CHECK(board[{7,2}]->_attack == 100);//SniperCommander CHECK(board[{7,3}]->_attack == 20);//FootCommander CHECK(board[{7,4}]->_attack == 10);//FootSoldier CHECK(board[{7,5}]->_attack == 50);//Sniper CHECK(board[{7,6}]->_attack == 0);//ParamedicCommander CHECK(board[{7,7}]->_attack == 0);//Pa board.move(1, {0,1}, Board::MoveDIR::Up); CHECK(board[{7,1}]->_life == 90); board.move(2, {7,1}, Board::MoveDIR::Down); CHECK(board[{0,1}]->_life == 90); board.move(1, {0,3}, Board::MoveDIR::Up); CHECK(board[{0,1}]->_life == 90); board.move(2, {7,3}, Board::MoveDIR::Left); CHECK(board[{0,1}]->_life == 90); board.move(1, {0,1}, Board::MoveDIR::Up); CHECK(board[{7,1}]->_life == 90); board.move(2, {7,1}, Board::MoveDIR::Down); CHECK(board[{0,1}]->_life == 90); board.move(1, {0,3}, Board::MoveDIR::Up); CHECK(board[{0,1}]->_life == 90); board.move(2, {7,3}, Board::MoveDIR::Left); CHECK(board[{0,1}]->_life == 90); board.move(1, {0,1}, Board::MoveDIR::Up); CHECK(board[{7,1}]->_life == 90); board.move(2, {7,1}, Board::MoveDIR::Down); CHECK(board[{0,1}]->_life == 90); board.move(1, {0,3}, Board::MoveDIR::Up); CHECK(board[{0,1}]->_life == 90); board.move(2, {7,3}, Board::MoveDIR::Left); CHECK(board[{0,1}]->_life == 90); board.move(1, {0,1}, Board::MoveDIR::Up); CHECK(board[{7,1}]->_life == 90); board.move(2, {7,1}, Board::MoveDIR::Down); CHECK(board[{0,1}]->_life == 90); board.move(1, {0,3}, Board::MoveDIR::Up); CHECK(board[{0,1}]->_life == 90); board.move(2, {7,3}, Board::MoveDIR::Left); CHECK(board[{0,1}]->_life == 90); //59 } TEST_CASE("Test -2-soldiers") { Board board(10,10); CHECK(board.has_soldiers(1)==false); board[{0,0}] = new FootSoldier(1); board[{0,1}] = new FootSoldier(1); board[{0,2}] = new SniperCommander(1); board[{0,3}] = new FootCommander(1); board[{0,4}] = new FootSoldier(1); board[{0,5}] = new Sniper(1); board[{0,6}] = new ParamedicCommander(1); board[{0,7}] = new Paramedic(1); board[{0,8}] = new Paramedic(1); board[{0,9}] = new Sniper(1); board[{5,0}] = new FootSoldier(1); board[{1,0}] = new FootSoldier(1); CHECK(board.has_soldiers(1)==true); CHECK(board.has_soldiers(2)==false); board[{7,0}] = new FootSoldier(2); board[{7,1}] = new FootSoldier(2); board[{7,2}] = new SniperCommander(2); board[{7,3}] = new FootCommander(2); board[{1,3}] = new FootCommander(2); board[{4,3}] = new FootCommander(2); board[{7,4}] = new FootSoldier(2); board[{7,5}] = new Sniper(2); board[{7,6}] = new ParamedicCommander(2); board[{7,7}] = new Paramedic(2); board[{5,6}] = new ParamedicCommander(2); board[{6,7}] = new Paramedic(2); board[{6,6}] = new ParamedicCommander(2); CHECK(board.has_soldiers(2)==true); CHECK(board[{0,0}]->_numOfplayer == 1); CHECK(board[{0,1}]->_numOfplayer == 1); CHECK(board[{0,2}]->_numOfplayer == 1); CHECK(board[{0,3}]->_numOfplayer == 1); CHECK(board[{0,4}]->_numOfplayer == 1); CHECK(board[{0,5}]->_numOfplayer == 1); CHECK(board[{0,6}]->_numOfplayer == 1); CHECK(board[{0,7}]->_numOfplayer == 1); CHECK(board[{5,0}]->_numOfplayer == 1); CHECK(board[{1,0}]->_numOfplayer == 1); // CHECK(board[{6,5}]->_numOfplayer == 2); CHECK(board[{6,6}]->_numOfplayer == 2); CHECK(board[{6,7}]->_numOfplayer == 2); CHECK(board[{7,0}]->_numOfplayer == 2); CHECK(board[{7,1}]->_numOfplayer == 2); CHECK(board[{7,2}]->_numOfplayer == 2); CHECK(board[{7,3}]->_numOfplayer == 2); CHECK(board[{7,4}]->_numOfplayer == 2); CHECK(board[{7,5}]->_numOfplayer == 2); CHECK(board[{7,6}]->_numOfplayer == 2); CHECK(board[{7,7}]->_numOfplayer == 2); CHECK(board[{5,0}]->_life == 100);//FootSoldier CHECK(board[{1,0}]->_life == 100);//FootSoldier CHECK(board[{0,2}]->_life == 120);//SniperCommander CHECK(board[{0,3}]->_life == 150);//FootCommander CHECK(board[{0,4}]->_life == 100);//FootSoldier CHECK(board[{0,5}]->_life == 100);//Sniper CHECK(board[{0,6}]->_life == 200);//ParamedicCommander CHECK(board[{0,7}]->_life == 100);//Paramedic CHECK(board[{5,0}]->_attack == 10);//FootSoldier CHECK(board[{1,0}]->_attack == 10);//FootSoldier CHECK(board[{0,2}]->_attack == 100);//SniperCommander CHECK(board[{0,3}]->_attack == 20);//FootCommander CHECK(board[{0,4}]->_attack == 10);//FootSoldier CHECK(board[{0,5}]->_attack == 50);//Sniper CHECK(board[{0,6}]->_attack == 0);//ParamedicCommander CHECK(board[{0,7}]->_attack == 0);//Paramedic CHECK(board[{7,2}]->_life == 120);//SniperCommander CHECK(board[{7,3}]->_life == 150);//FootCommander CHECK(board[{7,4}]->_life == 100);//FootSoldier CHECK(board[{7,5}]->_life == 100);//Sniper CHECK(board[{7,6}]->_life == 200);//ParamedicCommander CHECK(board[{7,7}]->_life == 100);//Paramedic CHECK(board[{7,2}]->_attack == 100);//SniperCommander CHECK(board[{7,3}]->_attack == 20);//FootCommander CHECK(board[{7,4}]->_attack == 10);//FootSoldier CHECK(board[{7,5}]->_attack == 50);//Sniper CHECK(board[{7,6}]->_attack == 0);//ParamedicCommander CHECK(board[{7,7}]->_attack == 0);//Pa } };
Java
UTF-8
4,668
2
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
/* * Copyright 2022 Google LLC * * 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. */ import static junit.framework.TestCase.assertNotNull; import static org.hamcrest.MatcherAssert.assertThat; import com.google.api.gax.longrunning.OperationFuture; import com.google.cloud.dataproc.v1.Cluster; import com.google.cloud.dataproc.v1.ClusterConfig; import com.google.cloud.dataproc.v1.ClusterControllerClient; import com.google.cloud.dataproc.v1.ClusterControllerSettings; import com.google.cloud.dataproc.v1.ClusterOperationMetadata; import com.google.cloud.dataproc.v1.InstanceGroupConfig; import com.google.protobuf.Empty; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.PrintStream; import java.util.UUID; import java.util.concurrent.ExecutionException; import org.hamcrest.CoreMatchers; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; @RunWith(JUnit4.class) public class SubmitHadoopFsJobTest { private static final String CLUSTER_NAME = String.format("java-fs-test--%s", UUID.randomUUID().toString()); private static final String REGION = "us-central1"; private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT"); private static final String ENDPOINT = String.format("%s-dataproc.googleapis.com:443", REGION); private static final String HADOOP_FS_QUERY = "-ls /"; private ByteArrayOutputStream bout; private static void requireEnv(String varName) { assertNotNull( String.format("Environment variable '%s' is required to perform these tests.", varName), System.getenv(varName)); } @BeforeClass public static void checkRequirements() { requireEnv("GOOGLE_APPLICATION_CREDENTIALS"); requireEnv("GOOGLE_CLOUD_PROJECT"); } @Before public void setUp() throws IOException, ExecutionException, InterruptedException { bout = new ByteArrayOutputStream(); System.setOut(new PrintStream(bout)); ClusterControllerSettings clusterControllerSettings = ClusterControllerSettings.newBuilder().setEndpoint(ENDPOINT).build(); try (ClusterControllerClient clusterControllerClient = ClusterControllerClient.create(clusterControllerSettings)) { // Configure the settings for our cluster. InstanceGroupConfig masterConfig = InstanceGroupConfig.newBuilder() .setMachineTypeUri("n1-standard-2") .setNumInstances(1) .build(); InstanceGroupConfig workerConfig = InstanceGroupConfig.newBuilder() .setMachineTypeUri("n1-standard-2") .setNumInstances(2) .build(); ClusterConfig clusterConfig = ClusterConfig.newBuilder() .setMasterConfig(masterConfig) .setWorkerConfig(workerConfig) .build(); // Create the Dataproc cluster. Cluster cluster = Cluster.newBuilder().setClusterName(CLUSTER_NAME).setConfig(clusterConfig).build(); OperationFuture<Cluster, ClusterOperationMetadata> createClusterAsyncRequest = clusterControllerClient.createClusterAsync(PROJECT_ID, REGION, cluster); createClusterAsyncRequest.get(); } } @Test public void submitHadoopFsJobTest() throws IOException, InterruptedException { SubmitHadoopFsJob.submitHadoopFsJob(PROJECT_ID, REGION, CLUSTER_NAME, HADOOP_FS_QUERY); String output = bout.toString(); assertThat(output, CoreMatchers.containsString("/tmp")); } @After public void tearDown() throws IOException, InterruptedException, ExecutionException { ClusterControllerSettings clusterControllerSettings = ClusterControllerSettings.newBuilder().setEndpoint(ENDPOINT).build(); try (ClusterControllerClient clusterControllerClient = ClusterControllerClient.create(clusterControllerSettings)) { OperationFuture<Empty, ClusterOperationMetadata> deleteClusterAsyncRequest = clusterControllerClient.deleteClusterAsync(PROJECT_ID, REGION, CLUSTER_NAME); deleteClusterAsyncRequest.get(); } } }
C++
UTF-8
1,727
3.171875
3
[]
no_license
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { int size1 = nums1.size(); int size2 = nums2.size(); if (size1 == 0) { int mid = size2/2; if ((size2 % 2) == 0) { return ( nums2[mid] + nums2[mid-1])/2.0; } else { return nums2[mid]; } } if (size2 == 0) { int mid = size1/2; if ((size1 % 2) == 0) { return ( nums1[mid] + nums1[mid-1])/2.0; } else { return nums1[mid]; } } if (size1 > size2) { return findMedianSortedArrays(nums2, nums1); } int low = 0; int high = size1; double med = 0.0; int x, leftx, lefty, rightx, righty; int y; while (low <= high) { x = (low+high)/2; y = ((size1+size2+1)/2) -x; leftx = ((x == 0) ? INT_MIN: nums1[x-1]); rightx = ((x == size1) ? INT_MAX: nums1[x]); lefty = ((y == 0) ? INT_MIN: nums2[y-1]); righty = ((y == size2) ? INT_MAX: nums2[y]); if (leftx > righty) { high = x - 1; } else if (lefty > rightx) { low= x + 1; } else { if (((size1+size2) % 2) == 0){ med = (max (leftx, lefty) + min(rightx, righty))/2.0; } else { med = max(leftx, lefty); } break; } } return med; } };
Java
UTF-8
945
2.359375
2
[ "Apache-2.0" ]
permissive
package source.transactional; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.math.BigDecimal; /** * @author xin.huang * @version v1.0 * @date 2019/9/24 17:28 */ @Service("accountService") public class AccountServiceImpl implements AccountService { @Resource private AccountDao accountDao; @Override @Transactional(rollbackFor = Exception.class) public void transfer(String sourceAccount, String targetAccount, BigDecimal money) { Account source = accountDao.findByName(sourceAccount); Account target = accountDao.findByName(targetAccount); BigDecimal sourceBalance = source.getBalance().subtract(money); source.setBalance(sourceBalance); BigDecimal targetBalance = target.getBalance().add(money); target.setBalance(targetBalance); accountDao.update(source); accountDao.update(target); int i = 1/0; } }
Java
UTF-8
2,154
1.8125
2
[]
no_license
package com.sammbo.imdemo.sdk; import com.geely.imsdk.client.bean.custom.SIMCustomTip; import com.geely.imsdk.client.bean.friend.tip.SIMSNSChangeInfo; import com.geely.imsdk.client.bean.message.SIMMessage; import com.geely.imsdk.client.bean.offline.SIMRecentMsgPage; import com.geely.imsdk.client.bean.session.SIMSessionTip; import com.geely.imsdk.client.bean.system.SIMLoginTip; import com.geely.imsdk.client.bean.system.SIMOffLineTip; import com.geely.imsdk.client.listener.SIMListener; import com.sammbo.imdemo.entity.MessageEntity; import com.sammbo.imdemo.entity.busevent.EventConnectState; import com.sammbo.imdemo.entity.busevent.EventMessage; import me.goldze.mvvmhabit.bus.RxBus; public class ChatListener implements SIMListener { @Override public void onReceivedMessage(SIMMessage msg) { RxBus.getDefault().post(MessageEntity.get(msg)); } @Override public void onReadSYNMessage(SIMMessage elem) { } @Override public void onReadTipMessage(SIMMessage elem) { } @Override public void onRevokeMessage(SIMMessage elem) { } @Override public void onDeleteMessage(SIMMessage elem) { } @Override public void onSignMessage(SIMMessage elem) { } @Override public void onReplyMessage(SIMMessage elem) { } @Override public void onReceiveSessionTips(SIMSessionTip tip) { } @Override public void onReceiveGroupTips(SIMMessage tips) { } @Override public void onReceiveSystemTips(SIMMessage tips) { } @Override public void onReceiveSNSMessage(SIMSNSChangeInfo changeInfo) { } @Override public void onReceiveCustomTip(SIMCustomTip customTip) { } @Override public void onReceiveRecentMessages(SIMRecentMsgPage page) { } @Override public void onReceiveLoginTips(SIMLoginTip tip) { } @Override public void onReceiveKickOff(SIMOffLineTip tip) { EventMessage logOut = new EventMessage(); logOut.setCode(1); RxBus.getDefault().post(logOut); } @Override public void onReceiveRedpacket(SIMMessage simMessage) { } }
Markdown
UTF-8
386
2.53125
3
[ "MIT" ]
permissive
# [High Quality Code - Part 2 Course](https://github.com/TelerikAcademy/High-Quality-Code-Part-2) Homework, exam practice tasks and exam ### Topics covered 1. [Defensive Programming and Exceptions](01-Defensive-Programming-and-Exceptions) 1. [Code Tuning and Optimization](02-Code-Tuning-and-Optimization) 1. [Refactoring](03-Refactoring) 1. [Development Tools](04-Development-Tools)
Markdown
UTF-8
1,604
3.109375
3
[]
no_license
### 缘起 > 最开始萌生要维护这个repo是在看了之前同事同样命名的一个repo,[link](https://github.com/hningoba/KnowledgeSummary)。他这个repo里面很多都是列了知识点,但是绝大部分都没有具体的知识总结或者有的总结写的不是特别详细,于是就萌生了自己重新整理一份的想法。 ### 现状 > 现在这个KnowledgeSummary借鉴了不少他的整理记录,我计划选择性地找出一些知识点或者是面试问题来进行总结,一个是希望能够自己能够不断巩固Android的知识点,总结也是对于自己知识体系的一种构建,另一个则是让自己对于原理性的知识有个更深层次的理解,知其然,知其所以然。 ### 为什么 因为自己是Android开发,写了快三年的Android了,现在工作中大部分内容都是写业务代码,更多的是画UI,写业务逻辑,但是对于一些原理性的知识了解的不够深。现在Android开发的要求越来越高,如果只是写业务,那无异于原地踏步,甚至说是在倒退,我会一直持续更新这个repo。 ### 完成部分 现在已经完成的大部分是自己平时工作中一些问题的记录和总结的一些读书笔记,包括Java一些常用集合的源码分析以及多线程相关的原理分析,JVM部分则是主要是看《深入理解Java虚拟机》这本书的知识提炼。 ### 后续计划 后面会对JVM以及Android面试中常问的知识点做个总结,开源库的分析也在计划中,目前在README中看到的都是一些比较简单的记录。
Java
UTF-8
1,124
2.4375
2
[]
no_license
package com.prueba.mascotas.pojo; /** * Created by Intel on 23/12/2016. */ public class Mascota { private int id; private String nombre; private int foto; private int fotolike; private int megusta; public Mascota(int megusta, String nombre, int foto, int fotlike) { this.megusta = megusta; this.nombre = nombre; this.foto = foto; this.fotolike = fotolike; } public Mascota(){ } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getFotolike() { return fotolike; } public void setFotolike(int fotolike) { this.fotolike = fotolike; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public int getFoto() { return foto; } public void setFoto(int foto) { this.foto = foto; } public int getMegusta() { return megusta; } public void setMegusta(int megusta) { this.megusta = megusta; } }
PHP
UTF-8
3,765
3.609375
4
[]
no_license
<?php namespace model; use \JsonSerializable; /** * */ class Book implements JsonSerializable { // La classe book ha come variabili d'istanza i parametri di un libro, ne possiamo aggiungere altri successivamente private $id; private $title; private $author; private $price; private $img; private $link; private $recent; private $source; // Constructor public function __construct( string $title, string $author, float $price, string $image, string $link, string $source, bool $recent = false ) { $this->id = 0; $this->title = $title; $this->author = $author; $this->price = $price; $this->img = $image; $this->link = $link; $this->recent = $recent; $this->source = $source; } // getters public function getId(): int { return $this->id; } public function getTitle(): string { return $this->title; } public function getAuthor(): string { return $this->author; } public function getPrice(): float { return $this->price; } public function getImg(): string { return $this->img; } public function getLink(): string { return $this->link; } public function isRecent(): bool { return $this->recent; } public function getSource(): string { return $this->source; } // setters public function setId(int $id) { $this->id = $id; } public function setTitle(string $title) { $this->title = $title; } public function setAuthor(string $author) { $this->author = $author; } public function setPrice(float $price) { $this->price = $price; } public function setImg(string $img) { $this->img = $img; } public function setLink(string $link) { $this->link = $link; } public function setRecent(bool $recent) { $this->recent = $recent; } public function setSource(string $source) { $this->source = $source; } // object methods public function __toString(): string { $desc = "ID: $this->id"; $desc .= "<br />Title: $this->title"; $desc .= "<br />Author: $this->author"; $desc .= "<br />Price: $this->price"; $desc .= "<br />Imagine: $this->img"; $desc .= "<br />Link: $this->link"; $desc .= "<br />From: $this->source"; $this->recent? $desc .= "<br /><strong>New!</strong>": null; $desc .= "<hr />"; return $desc; } public function __clone() { $this->id = 0; } public function jsonSerialize() { $vars = get_object_vars($this); return $vars; } public function equals(Book $b): bool { return ($this->title === $b->getTitle() && $this->author === $b->getAuthor() && $this->price == $b->getPrice() && $this->img === $b->getImg() && $this->source === $b->getSource()); } }
C++
UTF-8
3,009
3
3
[]
no_license
/* * File: main.cpp * Author: anthony * * Created on November 22, 2010, 7:02 PM */ #include <GL/freeglut.h> #include <iostream> #include <cstdlib> using namespace std; static GLfloat spin_z = 0.0; static GLfloat spin_x = 0.0; static GLfloat spin_y = 0.0; void init(void); void display(void); void reshape(int, int); void keyboard(unsigned char, int, int); void mouse(int, int, int, int); /* * */ int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA); glutInitWindowPosition(100, 100); glutInitWindowSize(640,480); glutCreateWindow("OpenGL.20101122.SpinningSquare"); init(); glutDisplayFunc(display); glutReshapeFunc(reshape); glutKeyboardFunc(keyboard); glutMouseFunc(mouse); // call our main loop glutMainLoop(); return 0; } void init(void) { // set the clear color glClearColor(0.0, 0.0, 0.0, 0.0); } void reshape(int w, int h) { glViewport(0, 0, (GLsizei)w, (GLsizei) h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-50.0, 50.0, -50.0, 50.0, -50.0, 50.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } void display(void) { glClear(GL_COLOR_BUFFER_BIT); glColor3f(1.0, 0.0, 0.0); glPushMatrix(); glRotatef(spin_z, 0.0, 0.0, 1.0); glRotatef(spin_y, 0.0, 1.0, 0.0); glRotatef(spin_x, 1.0, 0.0, 0.0); glBegin(GL_POLYGON); glVertex2f(0.0, 0.0); glVertex2f(20.0, 0.0); glVertex2f(20.0, 20.0); glVertex2f(0.0, 20.0); glEnd(); glPopMatrix(); glutSwapBuffers(); } void keyboard(unsigned char key, int x, int y) { switch(key) { case 27: exit(0); break; case 32: spin_z += 1.0; if(spin_z > 360.0) spin_z = spin_z - 360.0; cout << "spin_z: " << spin_z << endl; glutPostRedisplay(); break; case 97: spin_y -= 1.0; if(spin_y < 0.0) spin_y = spin_y + 360.0; cout << "spin_y: " << spin_y << endl; glutPostRedisplay(); break; case 100: spin_y += 1.0; if(spin_y > 360.0) spin_y = spin_y - 360.0; cout << "spin_y: " << spin_y << endl; glutPostRedisplay(); break; case 115: spin_x -= 1.0; if(spin_y < 0.0) spin_x = spin_x + 360.0; cout << "spin_x: " << spin_x << endl; glutPostRedisplay(); break; case 119: spin_x += 1.0; if(spin_x > 360.0) spin_x = spin_x - 360.0; cout << "spin_y: " << spin_x << endl; glutPostRedisplay(); break; case 113: spin_x = spin_y = spin_z = 0; glutPostRedisplay(); break; default: break; } } void mouse(int button, int state, int x, int y) { }
Java
UTF-8
1,346
2.46875
2
[]
no_license
package myMarkdown; import java.awt.Color; import java.awt.Dialog; import java.awt.Font; import java.awt.Frame; import java.awt.GraphicsConfiguration; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JLabel; import javax.swing.JTextArea; public class MessegeDialog extends JDialog { public MessegeDialog(Frame owner, String msg) { super(owner, "Information"); setSize(380, 150); setVisible(true); setLayout(null); setLocationRelativeTo(null); this.getContentPane().setBackground(Color.white); JTextArea info = new JTextArea(msg); info.setEditable(false); info.setColumns(8); info.setLineWrap(true); info.setWrapStyleWord(true); info.setFont(new Font("SansSerif", Font.BOLD, 13)); info.setBounds(40,0,300,60); getContentPane().add(info); JButton yes=new JButton("OK"); yes.setBounds(140,70,60,25); yes.setFont(new Font("SansSerif", Font.PLAIN, 12)); yes.addActionListener(new ActionListener(){ @Override public void actionPerformed(ActionEvent e) { // TODO Auto-generated method stub MessegeDialog.this.dispose(); } }); // TODO Auto-generated constructor stub getContentPane().add(yes); } }
C++
UTF-8
2,000
3.71875
4
[ "Unlicense" ]
permissive
#include <iostream> #include <list> #include <string> #include <algorithm> namespace USA { struct President { std::string FirstName; std::string MiddleInitial; std::string LastName; uint32_t Presidency; }; } int main() { // Create a list container (a double (bi-directional) linked list) for the US Presidents std::list<USA::President> Presidents; // Create an iterator which we can use to find a President in the list std::list<USA::President>::iterator PresidentIterator; // Add some US Presidents to the list Presidents.push_back(USA::President{"George", "", "Washington", 1}); Presidents.push_back(USA::President{"Abraham", "", "Lincoln", 16}); Presidents.push_back(USA::President{"Ulysses", "S.", "Grant", 18}); Presidents.push_back(USA::President{"Theodore", "", "Roosevelt", 26}); Presidents.push_back(USA::President{"Franklin", "D.", "Roosevelt", 32}); // Find a President in the list and use a Lamda. PresidentIterator = std::find_if(Presidents.begin(), Presidents.end(), [](const USA::President& ListItem) { return (ListItem.FirstName == "Franklin") & (ListItem.LastName == "Roosevelt"); }); // Insert a President in the list if (PresidentIterator != Presidents.end()) { Presidents.insert(PresidentIterator, USA::President{"Woodrow", "", "Wilson", 28}); } Presidents.erase(PresidentIterator); // Print the list of Presidents for(auto PresidentIterator2 : Presidents) { std::cout << "United States President #" << PresidentIterator2.Presidency << ": - " << PresidentIterator2.FirstName << " " << PresidentIterator2.MiddleInitial << (PresidentIterator2.MiddleInitial == "" ? "" : " ") << PresidentIterator2.LastName << "\n"; } }
Java
UTF-8
2,475
2.078125
2
[]
no_license
package me.leefeng.beida.bean; import cn.bmob.v3.BmobObject; /** * Created by FengTing on 2017/4/25. */ public class User extends BmobObject { String username; String password; String phone; Long account; boolean isBeida; String realName; String headPic; String subject; String bdAccount; String bdPassword; String app="beida"; public User(){ } public User(User user) { setObjectId(user.getObjectId()); this.username=user.getUsername(); this.password=user.getPassword(); this.phone=user.getPhone(); this.account=user.getAccount(); this.isBeida=user.isBeida(); this.realName=user.getRealName(); this.bdAccount=user.getBdAccount(); this.bdPassword=user.getBdPassword(); this.subject=user.getSubject(); } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getBdAccount() { return bdAccount; } public void setBdAccount(String bdAccount) { this.bdAccount = bdAccount; } public String getBdPassword() { return bdPassword; } public void setBdPassword(String bdPassword) { this.bdPassword = bdPassword; } public boolean isBeida() { return isBeida; } public void setBeida(boolean beida) { isBeida = beida; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Long getAccount() { return account; } public void setAccount(Long account) { this.account = account; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getRealName() { return realName; } public void setRealName(String realName) { this.realName = realName; } public String getHeadPic() { return headPic; } public void setHeadPic(String headPic) { this.headPic = headPic; } public String getApp() { return app; } public void setApp(String app) { this.app = app; } }
Java
UTF-8
355
1.671875
2
[]
no_license
package com.techredefined.saathi; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; public class PhoneNumberSetup extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_phone_number_setup); } }
C#
UTF-8
1,120
2.546875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { [SerializeField] private int xp = 0; [SerializeField] private int requiredXp = 100; [SerializeField] private int levelBase = 100; // [SerializeField] private List<GameObject> droids = new List<GameObject>(); private int lvl = 1; public int Xp { get { return xp; } } public int RequiredXp { get { return requiredXp; } } public int LevelBase { get { return levelBase; } } public int Lvl { get { return lvl; } } /* public List<GameObject> Droids { get { return droids; } }*/ // Start is called before the first frame update void Start() { InitLevelData(); } public void AddXp(int xp) { this.xp += Mathf.Max(0, xp); } /* public void AddDroid(GameObject droid) { droids.Add(droid); }*/ private void InitLevelData() { lvl = (xp / levelBase) + 1; requiredXp = levelBase * lvl; } }
Markdown
UTF-8
16,152
2.96875
3
[]
no_license
--- layout: post title: <font color="ff0000">前景提取调研(未完成)</font> date: 2018-10-15 description: "Foreground Detection" tag: Research --- ### 目录 * [简介](#abstract) * [Image or $\alpha$ matting现状](#introduction) * [图像语义分割方法](#similar) * [CRF](#technical) * [待复习](#will-review) * [参考文献](#reference) ### <a name="abstract"></a>简介 经过初步调研, 对于前景提取问题, 主要有两类方法可以解决:1)基于回归的传统方法(image matting);2)基于分类的图像语义分割方法. #### 关键字 >* A Bayesian Approach to Digital Matting >* Semantic Segmentation ### <a name="introduction"></a>Image or $\alpha$ matting现状 问题: 求解$\alpha$通道图像的过程, 边缘的透明程度直接反应了最终切割图像细节的丰富程度. Summary: | 类别 | 关键点 | 假设 | 求解 | 运算时间 | | ------------ | ------------------------------ | ---- | ---- | --- | | _Bayesian_ | _Local color analysis_ | _Color separation, camera quality_ | _Iterative_ | _~30 secs_ | | __Poisson__ | __Image gradients__ | __Locally smooth foreground and background__ | __Iterative__ | __~5 secs__ | | _Closed Form_ | _Image windows_ | _Locally linear foreground and background_ | _Direct_ | _~60 secs_ | #### ___Bayesian Matting Method___ 总结: 需要trimap数据的监督方法, 是一个逐步精细化trimap的过程, 精细化指的是边界$\alpha$. 换句话说: 在极大似然的框架下从trimap出发逐步精细化$\alpha$通道图像的过程. 注意点: >* 统计方法 >* 极大似然 >* 迭代求解 主要问题: >* 需要trimap标记数据 #### ___Poisson Matting Method___ 总结: 仍然是从trimap出发, 然后根据图像的梯度逐步精细化trimap, 因此这里有个假设: matting图像的梯度和图像梯度类似. 注意点: >* 迭代求解 主要问题: >* 需要trimap标记数据 #### ___Closed Form Matting Method___ 总结: 与Posisson Matting理论类似, 关键在于将求解部分通过closed-form的方式将迭代求解转换成直接求解. ### <a name="similar"></a>图像语义分割方法 #### ___问题描述:___ 图像的语义分割是计算机视觉中重要的基本问题之一,其目标是对图像的每个像素点进行分类,将图像分割为若干个视觉上有意义的或感兴趣的区域, 以利于后续的图像分析和视觉理解. 有一点要注意: 语义分割包含了传统的分割和目标识别, 最终的输出是一副具有___逐像素语义___标注的图像. 从抠图应用的角度看待图像语义分割方法, 这类方法与前面提到的方法的最大不同是: 语义分割方法将问题 转换为一个分类问题, 而前文的方法则是将问题当作回归来处理. 问题的难点体现在: + __1.__ 光照、视角、距离对算法的干扰 + __2.__ 类内物体的相异性、类间物体的相似性 + __3.__ 复杂背景的干扰 #### ___输入数据:___ + __1.__ 灰度图像与多通道图像 + __2.__ 单图像语义分割、多图像语义分割 #### ___评价指标:___ + __1.__ 被正确分类的像素与总像素的比例 + __2.__ 平均正确率(mean accuracy)、平均交叉率(mean intersection over union)、频率加权交叠率(frequency weighted intersection over union) + __3.__ 算法对同场景图像的鲁棒性 #### ___方法分类:___ 传统方法: | 方法 | 概述 | 存在的问题 | | ------------ | ------------------------------ | --- | | _阈值法_ | _根据像素强度的不同设定阈值进行分类_ | _像素接近时、出错概率高_ | | __边缘检测__ | __边缘检测、连线(Sobel, Canny常用的边缘检测算子)__ | __适合梯度明显、噪声小的简单图像; 往往需要在抗噪性与检测精度之间做trade-off__ | | _主动轮廓模型(ACM)_ | _跟人脸对齐的原理一样_ | _需要模式一样的标注数据_ | | __MRF、CRF__ | __计算像素的概率以进行分类__ | __-__ | ps: 传统方法中CRF通常被选做神经网络模型(做特征工程、提取图像的高阶特征)的后端来做inference工作. 操作模式纬度: | 方法 | 概述、存在的问题 | 操作模式 | | ------------ | ------------------------------ | --- | | _正则化切_ | _基于距离的二义分类方法; 容易将一个物体分成多类_ | _被动式_ | | __GrabCut__ | __加了人工干预的二义分类方法; 需要若干个人工干预才可以得到精确的结果__ | __交互式__ | | _FCN+CRF_ | _FCN做特征工程然后喂给CRF做inference_ | _交互式_ | ps: 二义分类指的是一次只能分两类. ### <a name="technical"></a>CRF 最后一种FCN+CRF是目前主流的方法, 其中FCN的特征工程部分和CRF的推理部分可以并行进行. 后续安排: + __1.__ 基于CRF推理模型的传统方法: 理解算法、实现、看效果 + __2.__ 根据step 1的demo结果决定是否实施FCN特征工程 + __3.__ 基于回归的方法调研 #### 条件随机场(CRF) + 图像符合马尔可夫分布 + 马尔可夫在计算上的复杂性 + Gibbs模型 + MRF中变量的联合概率形式又叫做Gibbs distribution + Markov Random Field与Gibbs Random Field的等价性 + CRF本质上是给定了observations的马尔可夫随机场, linear CRF、high-level CRF都是某种特定结构的CRF #### 随机场 ___cheat sheet:___ | 概念 | 描述 | 补充 | | ------------ | ------------------------------ | --- | | _随机场(Random Field)_ | _随机变量的集合_ | _随机变量对应同一样本空间、随机变量具有依赖关系_ | | __Markov Random Field(MRF)__ | __MRF对应一个无向图, 其中随机变量对应节点、边意味着两随机变量间具有概率依赖关系__ | __图结构反映了先验知识(变量之间的关系); MRF具有临域性质__ | | _clique-potential_ | _clique对应的函数_ | _具体的问题对clique的定义不同; 用户定义; 用来帮助描述随机变量分布的_ | | __energy function__ | __MRF上所有clique-potential之和__ | __none__ | | _CRF_ | _在MRF基础上, 每个随机变量还有观察值_ | _条件分布(后验概率)、形式类似于MRF的分布_ | ___训练:___ + clique-potential由用户自定义的特征函数组成, 其强弱、方向由函数中的参数控制, 而这些参数是通过训练确定的. + 图的结构由特征函数的定义确定. 只有一维特征函数, 对应的图没有边. + 通过最大log似然准则进行训练: 取log后, 指数没了, 目标函数是凸的, 且梯度具有解析解, 这样可以通过LBFGS(拟牛顿法)进行求解. 该框架下的训练, 每次迭代都要做inference. + 为了提高训练速度, 可以采用伪似然来训练, 从而免得在训练过程中做inference, 但这种方法的训练效果比较差. ___推理:___ + 分类的时候要找出概率最大的一组解. + 推断的本质是图模型上的概率推断问题, 对于最简单的线性框架结构可以使用Viterbi. + 如果图是树状的, 可采用belief propogation用sum-product得到概率. #### CRF2 + 概率图模型:用图论的方法表现数个独立随机变量之间关系的一种建模方法, 两种常见模型为: 有向图模型、无向图模型. + 给定观察集合$X=(x_1, x_2, ..., x_n)$后输出集合$Y$实质上是一个MRF, 因此参数化这个条件概率的方法和MRF模型的参数化方法是一样的. + Hammersley-Clifford 定理指出:马尔科夫随机场和Gibbs分布是一致的, 这就意味着概率无向图模型的联合概率分布可用Gibbs Distribution来表示. ___viterbi inference:___ + 跟dijkstra差不多 + 动态规划算法 #### Linear chain CRF ### <a name="will-review"></a>待复习 + Graphical Models and Sampling Methods. + 最大熵准则下的GIS和IIS求解与最大似然下的LBFGS求解, 取log后本质上应该区别不大. + 贝叶斯网络和马尔可夫网络 #### Introduction to crf + 由于输出变量间具有依赖关系, 因此, 用Graphical model来表示这种关系就比较自然. + 生成模型通常是求联合分布, 而判别模型是求条件分布 + CRF结合了判别模型和图模型的优势 ___Graphical Modeling:___ + 图模型主要利用local dependency, 这样在求多变量分布的时候可以将其拆分成多个local function的乘积, 其中每个local function依赖一个小的变量子集. + Graphical modeling framework的几个关键要素是: factorization、conditional independence、graph structure, 其中, conditional independence 用于独立建模、factorization用于设计inference算法, 另外, 从数学的角度讲factorization可以使分布的表达更高效(变量子集可能比整个变量集小的多). + 之所以提到Graphical Model, 是指联合概率分布可以用一个图来表示. + 无向图模型: local fucntion没有概率解释. + 有向图模型: 将联合概率分布分解成条件概率乘积的形式. + 有向图模型与无向图模型的本质区别在于local function的含义差异. ___生成模型与判别模型:___ + 生成模型: how a label vector __y__ can probabilistically "generate" a feature vector __x__. + 判别模型: how a feature vector __x__ can probabilistically "discriminate" a label vector __y__. + 理论上, 通过贝叶斯准则, 可以将一个生成模型转换成一个判别模型, 反之亦然. #### feature engineering + Label-observation features: 指定的标签$\tilde{y}_c$才有值, 而特征值完全由输入观测决定(这里的特征值计算可能是文本、图像处理, 也称之为观测函数). + Unsupported features: 训练集中出现的错误的特征, 这些特征可能有用, 因为可以给他们一个负权重以阻止错误的标签被赋予高概率.eg, ad hoc技术. + Edge-Observation and Node-Observation Features: + Boundary labels: 边界处理. + Feature Induction: Unsupported feature是穷人版feature induction, eg: L1 regularization. + Categorical Features: 对特征进行数值化处理, 如: 二值化、正规化. + Features as Backoff: 数据集小的时候采用的一种策略. + Features as Model Combination: 将先验知识改成观测函数 #### Efficient Inference in Fully Connected CRFs with Gaussian Edge Potentials + 通过mean field approximation来对CRF distribution进行近似: 利用iterative message passing 算法实现近似推理. + 关键观察: message passing 可以通过特征空间的高斯滤波近似实现, 这样可以降低message passing的计算复杂度. ### <a name="reference"></a>参考文献 ___Traditional method(image or $\alpha$ matting):___ - [1. (2017)-Three-layer graph framework with the sumD feature for alpha matting](https://www.sciencedirect.com/science/article/pii/S1077314217301236) - [2. (2011-Xiaoou Tang&Jian Sun)-A Global Sampling Method for Alpha Matting](http://mmlab.ie.cuhk.edu.hk/archive/2011/cvpr11matting.pdf) - [3. (2010)-Shared Sampling for Real-Time Alpha Matting](https://pdfs.semanticscholar.org/074e/39a1c533993dcc829d9996c6518608d01e49.pdf) - [4. (2006-Closed Form)-A Closed Form Solution to Matting](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.478.6701&rep=rep1&type=pdf) - [6. (2004-Posisson)-Poisson Matting](http://www.wisdom.weizmann.ac.il/~vision/courses/2006_2/papers/matting/Sun%20poisson%20matting.pdf) - [7. (2003)-Digital Matting and Compositing](http://grail.cs.washington.edu/projects/digital-matting/) - [8. (2002-siggraph-Bayesian)Video Matting of Complex Scenes](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.164.911&rep=rep1&type=pdf) - [9. (2001-cvpr-Bayesian)-A Bayesian Approach to Digital Matting](https://grail.cs.washington.edu/projects/digital-matting/image-matting/) ___Deep learning(image or $\alpha$ matting):___ - [1. (2018)-Deep Energy: Using Energy Functions for Unsupervised Training of DNNs](https://arxiv.org/pdf/1805.12355.pdf) - [2. (2018-US Patent)-Utilizing deep learning for automatic digital image segmentation and stylization](https://patentimages.storage.googleapis.com/d4/00/65/0f72d794c37845/US9978003.pdf) ___Image segmentation:___ - [1. (2000-classical method)-Normalized Cuts and Image Segmentation](https://repository.upenn.edu/cgi/viewcontent.cgi?article=1101&context=cis_papers) - [2. (2004)-GrabCut](http://pages.cs.wisc.edu/~dyer/cs534-fall11/papers/grabcut-rother.pdf) - [3. (2011-1059cited-nips-CRF)-Efficient Inference in Fully Connected CRFs with Gaussian Edge Potentials](http://www.philkr.net/papers/2011-12-01-nips/2011-12-01-nips.pdf) ___Domain Knowledge:___ - [1. An Introduction to Conditional Random Fields for Relational Learning](https://people.cs.umass.edu/~mccallum/papers/crf-tutorial.pdf) - [2. An Introduction to Conditional Random Fields](http://homepages.inf.ed.ac.uk/csutton/publications/crftut-fnt.pdf) - [3. Conditional Random Fields: Probabilistic Models for Segmenting and Labeling Sequence Data](https://www.seas.upenn.edu/~strctlrn/bib/PDF/crf.pdf) - [4. Training Conditional Random Field](https://www.lewuathe.com/machine%20learning/crf/conditional-random-field.html) ___中文博客:___ - [1. FCN和CRF博客](https://zhuanlan.zhihu.com/p/22308032) - [2. 十分钟看懂图像语义分割技术](https://mp.weixin.qq.com/s?__biz=MzA4ODgxMDY4MA==&mid=2655430607&idx=1&sn=fac0142ff44fac2d466350b922a707b1) - [3. 基于随机场的图像语义分割](https://blog.csdn.net/step_forward_ML/article/details/80519698) - [4. 图像语义分割综述](http://ojmhfvae7.bkt.clouddn.com/%E5%9B%BE%E5%83%8F%E8%AF%AD%E4%B9%89%E5%88%86%E5%89%B2%E7%BB%BC%E8%BF%B0.pdf) - [5. 抠图算法(交互式)以及证件照的自动抠图](https://blog.csdn.net/zlj6786579/article/details/79941170) - [6. 图像抠图算法学习 - Shared Sampling for Real-Time Alpha Matting](https://www.cnblogs.com/Imageshop/p/3550185.html) - [7. 条件随机场(CRF)](https://hit-computer.github.io/2017/06/10/CRF/) ___资源:___ - [1. image matting](http://www.alphamatting.com) - [2. 2006-presentation of Digital Matting](http://www.cs.tau.ac.il/~dcor/Graphics/adv-slides/DigitalMatting2.pdf) - [3. PyDenseCRF](https://github.com/lucasb-eyer/pydensecrf) - [4. MSRC-21](http://rodrigob.github.io/are_we_there_yet/build/semantic_labeling_datasets_results.html#4d5352432d3231) - [5. 无痛的机器学习第一季目录](https://zhuanlan.zhihu.com/p/22464594) <br> 转载请注明:[Mengranlin](https://lmrshare.github.io) » [点击阅读原文](https://lmrshare.github.io/2015/09/iOS9_Note/)
Java
UTF-8
2,922
3.71875
4
[]
no_license
package day07; import com.sun.tools.doclets.formats.html.SourceToHTMLConverter; /** * Created by reyren on 2016/11/3. */ /*构造函数: 构造函数的作用: 给对应的对象进行初始化. 构造函数注意细节: 1.没有返回值类型 2.函数名必须要与类名一致 3.构造函数并不是由我们手动调用的,而是在创建对象时,JVM就会主动的调用到对应的构造函数 4.以前创建对象时,jvm会调用构造方法,java编译器在编译的时候给加上去的 jdk提供了一个开发工具给我们进行反编译javap.exe,就将.class反编译出来了 5.如果一个类没有显式的写上构造方法时,那么java编译器会为该类添加一个无参的构造函数的 6.如果一个类已经显式的写上一个构造方法值,那么java编译器则不会再为该类添加一个无参的构造方法,所以自己写上之后,这个类中就没有无参的构造函数 想要一个无参的构造函数必须自己再写一个 7.java编译器添加的无参的构造方法的权限与类的权限一致 8.构造函数可以在一个类中以函数重载的形式存在的 构造函数与普通函数的区别: 1.构造函数没有返回值类型,void一写就不再是构造函数了普通函数即使没有返回值类型也要写上void 2.函数名不同 3.调用方式不同 * */ /*构造代码块: 给对象进行统一的初始化(就像底下的cry方法的重复书写) * * * * 构造代码块要注意的事项: * 1.java编译器编译一个java源文件的时候,会把成员变量的申明语句提至一个类的最前端 * 2.成员变量中的赋值都是在构造函数中进行的,构造代码块的执行是在构造函数内代码块的前面执行的 * 3.成员变量的显初始化(Int a = 1000;)与构造代码块的代码是按照当前代码的顺序执行的 * */ public class demo1 { public static void main(String[] args) { Baby b = new Baby(110, "狗娃");//婴儿诞生,白户的话是一旦new就有名字了 System.out.println("编号:" + b.id + " 姓名:" + b.name); //黑户 Baby b2 = new Baby(); b.id = 111; b.name = "狗剩"; b.cry(); } } class Baby{ int id;//身份证 String name; //构造代码块,一new就执行 { cry(); } //构造函数 public Baby(int i, String n){ id = i; name = n; // cry(); System.out.println("baby的属性初始化完毕"); } //无参的构造函数 public Baby(){ //cry(); System.out.println("无参的构造函数被调用了"); } public void cry(){ System.out.println(name + "哇哇哇的哭....");//null是因为cry()放在构造代码块中执行,但是是在name = n之前执行的 } }
Python
UTF-8
4,178
2.671875
3
[]
no_license
import sys import pjsua as pj import threading import time # Method to print Log of callback class def log_cb(level, str, len): print((str), end=' ') # Account Callback class to get notifications of Account registration class MyAccountCallback(pj.AccountCallback): def __init__(self, acc): pj.AccountCallback.__init__(self, acc) # Call Callback to receive events from Call class SRCallCallback(pj.CallCallback): def __init__(self, call=None): pj.CallCallback.__init__(self, call) def on_state(self): print(("Call is :", self.call.info().state_text), end=' ') print(("last code :", self.call.info().last_code), end=' ') print(("(" + self.call.info().last_reason + ")")) # This is the notification when call's media state is changed def on_media_state(self): global lib if self.call.info().media_state == pj.MediaState.ACTIVE: # Connect the call to sound device call_slot = self.call.info().conf_slot lib.conf_connect(call_slot, 0) lib.conf_connect(0, call_slot) print("Hey !!!!! Hope you are doing GOOD !!!!!!!!!!") print (lib) # Lets start our main loop here try: # Start of the Main Class # Create library instance of Lib class lib = pj.Lib() # Instantiate library with default config lib.init(log_cfg = pj.LogConfig(level=3, callback=log_cb)) # Configuring one Transport Object and setting it to listen at 5060 port and UDP protocol trans_conf = pj.TransportConfig() print("-------------------------LETS START THE REGISTRATION PROCESS----------------------") print("\n\n") trans_conf.port = 5060 # 5060 is default port for SIP # a=input("Please Enter the IP address of the Client: ") a="192.168.0.50" # Local VM IP print("Using the default port number for SIP: 5060") trans_conf.bound_addr = a transport = lib.create_transport(pj.TransportType.UDP,trans_conf) # Starting the instance of Lib class lib.start() lib.set_null_snd_dev() # Configuring Account class to register with Registrar server # Giving information to create header of REGISTER SIP message # ab4=input("Enter IP address of the Server: ") ab4="philly.sip.us1.twilio.com" # Asteriek server IP # ab=input("Enter Username: ") ab = "gowtham" # ab1=input("Enter Password: ") ab1 = "Gowtham_password123" # ab2=input("Do you want to use the display name same as the username Y/N ??") ab2 = "Y" if ab2=="y" or ab2=="Y": ab3=ab else: ab3=input("Enter Display Name: ") acc_conf = pj.AccountConfig(ab4, ab, ab1) # registrar = 'sip:'+ab4+':5060', proxy = 'sip:'+ab4+':5060') # acc_conf.id ="sip:"+ab # acc_conf.reg_uri ='sip:'+ab4+':5060' acc_callback = MyAccountCallback(acc_conf) acc = lib.create_account(acc_conf) # creating instance of AccountCallback class acc.set_callback(acc_callback) time.sleep(20) print('\n') print("Registration Complete-----------") print(('Status= ',acc.info().reg_status, \ '(' + acc.info().reg_reason + ')')) ab5=input("Do you want to make a call right now ?? Y/N\n") print("\n") if ab5=="y" or ab5=="Y": # Starting Calling process. b=input("Enter the destination URI: ") # c="sip:"+ b + "@192.168.0.34:5060" call = acc.make_call(b, SRCallCallback()) # Waiting Client side for ENTER command to exit print('Press <ENTER> to exit and destroy library') input = sys.stdin.readline().rstrip('\r\n') # We're done, shutdown the library lib.destroy() lib = None else: print(" Unregistering ---------------------------") time.sleep(2) print("Destroying Libraries --------------") time.sleep(2) lib.destroy() lib = None sys.exit(1) except pj.Error as e: print(("Exception: " + str(e))) lib.destroy() lib = None sys.exit(1)
Java
UTF-8
184
1.84375
2
[]
no_license
package cl.acgp.commons.mvc.web; public enum WebCallType { /** insert */ SAVE, /** update */ UPDATE, /** delete */ DELETE, /** saveOrUpdate */ SVUPDATE }
Python
UTF-8
741
2.578125
3
[]
no_license
from typing import List from repository.database import Database from repository.category_repository import CategoryRepository from model.category_model import Category from model.category_model import Category from core import handling_error as error class CategoryResource(): def __init__(self) -> None: self.repository = CategoryRepository(Database()) def get_category_by_id(self, id: int) -> Category: category = self.repository.get_category_by_id(id) if category is None: raise error.http_404_object_not_found("Category not found!", "category_not_found") return category def get_all_categories(self) -> List[Category]: return self.repository.get_all_categories()
Markdown
UTF-8
714
2.6875
3
[]
no_license
# Event Hub Proxy Test This will send 10 test messages to a specified Event Hub instance through a proxy. After sending each message it will wait for user input on the keyboard. This sample uses [proxy support for Azure Event Hubs](https://github.com/Azure/azure-event-hubs-java/commit/a85a662d233408e683cbc641dd9100bbacbaf04d) ## Running the sample In order to run this, set 3 environment variables: * **EVENT_HUB_CONNECTION_STRING** should be in the format of `Endpoint=----NAMESPACE_ENDPOINT------;EntityPath=----EVENTHUB_NAME----;SharedAccessKeyName=----KEY_NAME----;SharedAccessKey=----KEY_VALUE----`. * **PROXY_HOSTNAME** and **PROXY_PORT** should be the address and port of the proxy you are using.
Markdown
UTF-8
385
2.53125
3
[]
no_license
# xPlayer.addWeapon ```lua xPlayer.addWeapon(weaponName, ammo) ``` This function adds a weapon. ## Arguments | Argument | Data Type | Optional | Default Value | Explanation | |------------|-----------|----------|---------------|-------------| | weaponName | string | No | - | Weapon name | | ammo | number | No | - | Ammo count |
JavaScript
UTF-8
1,794
2.75
3
[ "MIT" ]
permissive
var callbackArguments = []; var argument1 = function (cb) { callbackArguments.push(arguments) cb(); }; var argument2 = null; var argument3 = function (subFold) { callbackArguments.push(arguments) fold.restoreRange(subFold); this.addFold(subFold); }; var argument4 = false; var argument5 = false; var argument6 = function (triple) { callbackArguments.push(arguments) n3 = n3 + triple.toString(); }; var argument7 = false; var argument8 = false; var argument9 = function (side) { callbackArguments.push(arguments) var value = 0, sideValue = this[side]; null != sideValue && (value = 'number' == typeof sideValue ? sideValue : sideValue.resolve('left' === side || 'right' === side ? width : height)); sides[side] = value; }; var argument10 = false; var base_0 = [969] var r_0= undefined try { r_0 = base_0.forEach(argument1,argument2) } catch(e) { r_0= "Error" } var base_1 = [969] var r_1= undefined try { r_1 = base_1.forEach(argument3,argument4,argument5) } catch(e) { r_1= "Error" } var base_2 = [969] var r_2= undefined try { r_2 = base_2.forEach(argument6,argument7,argument8) } catch(e) { r_2= "Error" } var base_3 = [969] var r_3= undefined try { r_3 = base_3.forEach(argument9,argument10) } catch(e) { r_3= "Error" } function serialize(array){ return array.map(function(a){ if (a === null || a == undefined) return a; var name = a.constructor.name; if (name==='Object' || name=='Boolean'|| name=='Array'||name=='Number'||name=='String') return JSON.stringify(a); return name; }); } setTimeout(function(){ require("fs").writeFileSync("./experiments/forEach/forEachMined/test405.json",JSON.stringify({"baseObjects":serialize([base_0,base_1,base_2,base_3]),"returnObjects":serialize([r_0,r_1,r_2,r_3]),"callbackArgs":callbackArguments})) },300)
Java
UTF-8
130
1.921875
2
[]
no_license
package reteta; public class CasaAsigurari { public static boolean esteAsigurat(int nrCard) { return nrCard % 2 == 1; } }
Java
UTF-8
1,420
2.546875
3
[]
no_license
package edu.ub.pis15.madmodes.madmodes_pis.dades; import java.sql.Array; import java.util.ArrayList; import java.util.concurrent.TimeUnit; import edu.ub.pis15.madmodes.madmodes_pis.boss.BossMain; /** * Created by earaujgi7.alumnes on 02/05/17. */ public class Model { //private static Nivell bossActual; private static ArrayList<Nivell> Nivells= new ArrayList<Nivell>(); Jugador player; int nivell; public Model(Jugador player){ this.player = player; this.nivell=1; //comença a nivell 1 per defecte Nivells.add(new Nivell(500,25,1)); //vida, mal, nºnivell Nivells.add(new Nivell(1000,50,2)); } public Boss getBoss(int n) {//torna el boss del nivell n return Nivells.get(n-1).getBoss(); } public Jugador getPlayer() { return player; } public int getLevel(){ return nivell;} public void nextLevel(int n){ this.nivell=n;} //public void setBossActual(Nivell nivellActual) { //this.bossActual = nivellActual; //} public void setPlayer(Jugador player) { this.player = player; } public int actualizardatos(long f, int dmgBoss){ //this.player.menysVida(this.getBoss(nivell).getPuntsmal()); if (player.getVida()>0){ this.player.updateJugador(f,dmgBoss); return 0; } return 1; //significa que el player ha mort } }
Shell
UTF-8
204
2.734375
3
[]
no_license
#!/usr/bin/env bash # # Executes setup.rb using the Ruby bundled with Vagrant. # if [ ! -d "wordpress" ]; then wget https://wordpress.org/latest.tar.gz tar -zxvf latest.tar.gz rm -rf latest.tar.gz fi
Python
UTF-8
465
2.59375
3
[ "MIT" ]
permissive
# -*- coding: UTF-8 -*- #@Time : 2020/3/23 @Author : SUNLIN from src import detect_faces, show_bboxes from PIL import Image def face_detect(filename,save_file_name): img = Image.open(filename) print(img) bounding_boxes, landmarks = detect_faces(img) img_copy=show_bboxes(img, bounding_boxes, landmarks) img_copy.save(save_file_name) return img_copy if __name__=='__main__': face_detect('images/office1.jpg','images/office1_copy.jpg')
Java
UTF-8
2,030
1.890625
2
[]
no_license
package com.easy.tvbox.bean; public class AlbumList { // uid: "0f7ebeeddb904f3d8a7c8e343635e896", // created: "2019-07-07 22:58:01", // updated: "2019-07-07 22:58:01", // shopNo: "S0001", // name: "我的歌单2", //歌单名称 // image: "http://azitai.oss-cn-shanghai.aliyuncs.com/1562511478072_1.jpg?x-oss-process=style/photo_handle_320", //歌单图片 // status: "1" private String uid; private String created; private String updated; private String shopNo; private String image; private String name; private String status; private String total; private int width; private int height; public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getTotal() { return total; } public void setTotal(String total) { this.total = total; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getCreated() { return created; } public void setCreated(String created) { this.created = created; } public String getUpdated() { return updated; } public void setUpdated(String updated) { this.updated = updated; } public String getShopNo() { return shopNo; } public void setShopNo(String shopNo) { this.shopNo = shopNo; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
PHP
UTF-8
553
2.875
3
[]
no_license
<?php namespace Hobocta\Patterns\Creational\AbstractFactory; /** * Class VirtualProductsFactory * @package Hobocta\Patterns\Creational\AbstractFactory */ class VirtualProductsFactory extends AbstractFactory { /** * @return ProductInterface */ function createBook(): ProductInterface { return new VirtualProductBook('Virtual book', 300); } /** * @return ProductInterface */ function createMagazine(): ProductInterface { return new VirtualProductBook('Virtual magazine', 400); } }
Markdown
UTF-8
2,525
2.578125
3
[]
no_license
--- Title: Kmom04 Description: Redovisning av kmom04. Template: kmom # hidden: true --- <section> <h2>Kmom04</h2> <h3>Kommentera kort om skrivuppgiften, något som är värt att nämna från arbetet med den?</h3> <p> Skrivuppgiften var lärorik tycker jag. Det är ju väldigt fördelaktigt att öva på att skriva på en akademisk nivå, att ta reda på fakta, utföra litteraturstudier och ett mindre projekt för att öva inför examensarbete. Jag tycker att det var en lagom stor uppgift. Det var även bra att vi fick en färdig mall att utgå ifrån. </p> <h3>Vilket färgschema valde du till ditt tema och hur valde du att använda färgerna (mer eller mindre eller lika mycket av alla färger)?</h3> <p> För mitt ljusare tema valde jag att använda mig av lite färger för att "liva" upp sidan också, det blev ett monokromatiskt tema. Jag använde mig då av lila nyanser, ljusare och mörkare. Vid de mörka temat byttes dessa ut till en mörkare nyans av blå. Jag ville inte att mitt dark-theme skulle vara helt svart, utan istället ha blå nyans som fortfarande är lite lättare för ögat. </p> <h3>Valde du att jobba med accentfärg och isåfall hur?</h3> <p> Nej, inte accent men vid färg-temat använde jag olika nyanser av samma färg istället. Vid det mörka temat fick en ljusare färg hjälpa vissa element att "poppa" lite. Tex vid report sidan så får varje "kmom-kort" sticka ut lite med hjälp av den ljusare färgen. </p> <h3>Hur valde du att lösa ditt dark theme? Gjorde du en kopia på ditt vanliga tema? Eller löste du det med imports?</h3> <p> Jag testade lite olika lösningar. Svårt att säga om min slutliga lösning var så optimal. Det blev i alla fall en exakt kopia av mitt ljusa tema bara att färgerna fick annan färg genom variabler. I mitt ljusa tema kan man ladda in mitt mörka tema som endast innehåller dessa variabler för att skriva över de ljusa färgerna. </p> <h3>Vilken är din TIL för detta kmom?</h3> <p> Variabler i scss är nytt för mig. Jag har använt lite variabler i css, då med hjälp av att till exempel skriva i rooten --main-bg-color. Det har funkat bra men jag vet att vid vissa valideringar så varnar den, eventuellt för att detta inte kan läsas av alla webbläsare. Men Scss variabler var suveränt smidigt, riktigt bra att få testa på detta i ett kmom! Övrig så tycker jag att detta kmom var superkul! </p> </section>
PHP
UTF-8
8,380
2.53125
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Auth; use Session; use App\Category; use App\Product; use App\ProductsAttribute; use Illuminate\Support\Facades\Input; use Image; class ProductsController extends Controller { // public function addProduct(Request $request){ if($request->isMethod('post')){ $data = $request->all(); //echo "<pre>"; print_r($data); die; $product = new Product; if(empty($data['category_id'])){ return redirect()->back()->with('flash_message_error','Under Category is missing!'); } $product->category_id = $data['category_id']; $product->product_name = $data['product_name']; $product->product_code = $data['product_code']; $product->product_color = $data['product_color']; if(!empty($data['description'])){ $product->description = $data['description']; }else{ $product->description = ''; } $product->price = $data['price']; //Upload Image if($request->hasFile('image')){ $image_imp = Input::file('image'); if($image_imp->isValid()){ $extension = $image_imp->getClientOriginalExtension(); $filename = rand(111,99999).'.'.$extension; $large_image_path = 'images/backend_images/products/large/'.$filename; $medium_image_path = 'images/backend_images/products/medium/'.$filename; $small_image_path = 'images/backend_images/products/small/'.$filename; //Resize Images Image::make($image_imp)->save($large_image_path); Image::make($image_imp)->resize(600,600)->save($medium_image_path); Image::make($image_imp)->resize(300,300)->save($small_image_path); //Store image name in products table $product->image = $filename; } } $product->save(); //return redirect()->back()->with('flash_message_success','Product has been added successfully!'); return redirect('/admin/view-products')->with('flash_message_success','Category Added Successfully!'); } //categories_dropdown $categories = Category::where(['parent_id'=>0])->get(); $categories_dropdown = "<option value='' selected disabled>Select</option>"; foreach($categories as $cat){ $categories_dropdown.="<option value='".$cat->id."'>".$cat->name."</option>"; $sub_categories = Category::where(['parent_id'=>$cat->id])->get(); foreach($sub_categories as $sub_cat){ $categories_dropdown.="<option value='".$sub_cat->id."'>---".$sub_cat->name."</option>"; } } return view('admin.products.add_product')->with(compact('categories_dropdown')); } public function viewProducts(){ $products = Product::get(); //$products = json_decode(json_encode($products)); foreach($products as $key => $val){ $category_name = Category::where(['id'=>$val->category_id])->first(); $products[$key]->category_name = $category_name->name; } //echo "<pre>"; print_r($products); die; return view('admin.products.view_products')->with(compact('products')); } public function editProduct(Request $request, $id=null){ //Update Product if($request->isMethod('post')){ $data = $request->all(); //echo "<pre>"; print_r($data); die; //Upload Image if($request->hasFile('image')){ $image_imp = Input::file('image'); if($image_imp->isValid()){ $extension = $image_imp->getClientOriginalExtension(); $filename = rand(111,99999).'.'.$extension; $large_image_path = 'images/backend_images/products/large/'.$filename; $medium_image_path = 'images/backend_images/products/medium/'.$filename; $small_image_path = 'images/backend_images/products/small/'.$filename; //Resize Images Image::make($image_imp)->save($large_image_path); Image::make($image_imp)->resize(600,600)->save($medium_image_path); Image::make($image_imp)->resize(300,300)->save($small_image_path); } }else{ $filename=$data['current_image']; } if(empty($data['description'])){ $data['description']=''; } Product::where(['id'=>$id])->update(['category_id'=>$data['category_id'],'product_name'=>$data['product_name'], 'product_code'=>$data['product_code'],'product_color'=>$data['product_color'],'description'=>$data['description'], 'price'=>$data['price'],'image'=>$filename]); //return redirect('/admin/view-products')->with('flash_message_success','Product Updated Successfully!'); return redirect()->back()->with('flash_message_success','Product updated successfully!'); } //Get product Detail $productsDetails = Product::where(['id'=>$id])->first(); //Categories Dropdown $categories = Category::where(['parent_id'=>0])->get(); $categories_dropdown = "<option value='' selected disabled>Select</option>"; foreach($categories as $cat){ if($cat->id==$productsDetails->category_id){ $selected = 'selected'; }else{ $selected = ''; } $categories_dropdown.="<option value='".$cat->id."'".$selected.">".$cat->name."</option>"; $sub_categories = Category::where(['parent_id'=>$cat->id])->get(); foreach($sub_categories as $sub_cat){ if($sub_cat->id==$productsDetails->category_id){ $selected = 'selected'; }else{ $selected = ''; } $categories_dropdown.="<option value='".$sub_cat->id."'".$selected.">---".$sub_cat->name."</option>"; } } return view('admin.products.edit_product')->with(compact('productsDetails','categories_dropdown')); } public function deleteProductImage($id=null){ if(!empty($id)){ Product::where(['id'=>$id])->update(['image'=>'']); return redirect()->back()->with('flash_message_success','Product image delete successfully!'); } } public function deleteProduct($id=null){ if(!empty($id)){ Product::where(['id'=>$id])->delete(); return redirect()->back()->with('flash_message_success','Product Delete Successfully!'); } } public function addAttributes(Request $request, $id=null){ $productDetails = Product::with('attributes')->where(['id'=>$id])->first(); //$productDetails = json_decode(json_encode($productDetails)); //echo "<pre>"; print_r($productDetails); die; if($request->isMethod('post')){ $data = $request->all(); //echo "<pre>"; print_r($data); die; foreach($data['sku'] as $key => $val){ if(!empty($val)){ $attribute = new ProductsAttribute; $attribute->product_id = $id; $attribute->sku = $val; $attribute->size = $data['size'][$key]; $attribute->price = $data['price'][$key]; $attribute->stock = $data['stock'][$key]; $attribute->save(); } } return redirect('/admin/add-attributes/'.$id)->with('flash_message_success','Product Attribute nas been added Successfully!'); } return view('admin.products.add_attributes')->with(compact('productDetails')); } public function deleteAttribute($id=null){ //if(!empty($id)){ ProductsAttribute::where(['id'=>$id])->delete(); return redirect()->back()->with('flash_message_success','Product Attribute Delete Successfully!'); //} } }
Java
UTF-8
2,693
2.609375
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package si.hop; import java.time.Year; import java.util.ArrayList; import nf.DPI.DM.Acte; import nf.DPI.DM.Code; import nf.DPI.DM.Prescription; import nf.DPI.DM.TypeActe; import nf.DPI.DM.TypePrescription; /** * * @author Loïc */ public class SIHop { /** * @param args the command line arguments */ public static void main(String[] args) { int maxIPP = 1612345; int annee = maxIPP; while (annee > 100) { System.out.println(annee % 10); annee = annee / 10; } System.out.println(annee); int year = Year.now().getValue(); System.out.println(year); annee += 2000; if(year == annee){ maxIPP += 1; System.out.println("valeur finale : " + maxIPP); } else { year = year - 2000; maxIPP = year*100000+1; System.out.println("valeur finale : " + maxIPP); } Acte acte = new Acte(1,Code.AIS,1,"23",TypeActe.THERAPEUTIQUE); System.out.println(acte.toString()); Prescription prescription = new Prescription(1, "Rhûme","ras",TypePrescription.CONSULTATION); System.out.println(prescription.getPrescription() + "\n" +prescription.getTypePrescription()); ArrayList<String> listeRes = new ArrayList<>(); listeRes.add("mal"); listeRes.add("bien"); listeRes.add("contagieux"); System.out.println(listeRes); //Resultat resultat = new Resultat (listeRes); //System.out.println(resultat); ArrayList<String> listeActes = new ArrayList<>(); listeActes.add("CS"); listeActes.add("KS"); System.out.println(listeActes); ArrayList<String> listePrescriptions = new ArrayList<>(); listePrescriptions.add("EXAMEN_SANGUIN"); listePrescriptions.add("EXAMEN_RADIOLOGIQUE"); listePrescriptions.add("CONSULTATION"); listePrescriptions.add("MEDICAMENT"); System.out.println(listePrescriptions); // Personnel createur = new Personnel ("GERES", "DENIZ","479283743", Sexe.FEMME, "24 rue de la jonquière 38000 GRENOBLE"); // System.out.println(createur.getNom()+ "\n" + createur.getPrenom()+ "\n" + createur.getIdPersonel() + "\n" + createur.getSexe() + "\n" + createur.getAdresse()); //FicheDeSoins fds = new FicheDeSoins(listeActes,listePrescriptions, listeRes); } }
Python
UTF-8
2,005
3.171875
3
[ "MIT" ]
permissive
#!/usr/bin/python3 import pandas as pd import matplotlib.pyplot as plt import numpy as np from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn import preprocessing from sklearn import metrics import seaborn as sns data=np.genfromtxt('./data/adult.data', delimiter=', ', unpack=True, dtype="S") print(data[:,0]) le = preprocessing.LabelEncoder() data_frame=pd.DataFrame({ 'age':data[0,:].astype(int), 'workclass':le.fit_transform(data[1,:]), 'fnlwgt':data[2,:].astype(int), 'education':le.fit_transform(data[3,:]), 'education-num':data[4,:].astype(int), 'marital-status':le.fit_transform(data[5,:]), 'occupation':le.fit_transform(data[6,:]), 'relationship':le.fit_transform(data[7,:]), 'race':le.fit_transform(data[8,:]), 'sex':le.fit_transform(data[9,:]), 'capital-gain':data[10,:].astype(float), 'capital-loss':data[11,:].astype(float), 'hours-per-week':data[12,:].astype(float), 'native-country':le.fit_transform(data[13,:]), 'income': le.fit_transform(data[14,:]) }) feature_names = ['age', 'workclass', 'fnlwgt', 'education', 'education-num', 'marital-status', 'occupation', 'relationship', 'race', 'capital-gain', 'capital-loss', 'hours-per-week', 'native-country'] x=data_frame[feature_names] y=data_frame['income'] X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.3) # 70% training and 30% test #Create a Gaussian Classifier clf=RandomForestClassifier(n_estimators=100) #Train the model using the training sets y_pred=clf.predict(X_test) clf.fit(X_train,y_train) y_pred=clf.predict(X_test) print("Accuracy:",metrics.accuracy_score(y_test, y_pred)) feature_imp = pd.Series(clf.feature_importances_,index=feature_names).sort_values(ascending=False) print(feature_imp) sns.barplot(x=feature_imp, y=feature_imp.index) plt.xlabel('Feature Importance Score') plt.ylabel('Features') plt.title("Visualizing Important Features") plt.legend() plt.show()
Python
UTF-8
1,221
3.03125
3
[]
no_license
# coding=utf-8 __author__ = 'carl' import os import sys import xlrd class PicInfo: def __init__(self, category, name, path): self.category = category self.name = name self.path = path def __str__(self): return self.category + " " + self.name + " " + self.path def __dict__(self): return {'category': self.category, 'name': self.name, 'path': self.path} class PicParser: def __init__(self, file_path): self.filePath = file_path self.picList = [] def parse(self): if not os.path.isfile(self.filePath): print 'File not found! :', self.filePath return reload(sys) sys.setdefaultencoding('utf-8') xlsx_file = xlrd.open_workbook(self.filePath) # 读取第一sheet info_sheet = xlsx_file.sheet_by_name(u"所有图片") row = 1 while row < len(info_sheet._cell_values): row_data = info_sheet.row_values(row) pic_url = row_data[2] end = pic_url.index('?') picInfo = PicInfo(row_data[0], row_data[1], pic_url[0:end]) self.picList.append(picInfo) # print picInfo row = row + 1
Python
UTF-8
2,003
2.875
3
[]
no_license
import requests import json import pandas as pd import numpy as np hero_status_dict = { 'lv50FiveStarFullyAwakened': 50, 'lv60SixStarFullyAwakened': 60 } def api_get_status(get_data): if get_data.status_code != 200: print("Error", get_data.status_code) return def get_e7_hero_data(hero_name): hero_call = requests.get('https://api.epicsevendb.com/hero/'+str(hero_name)) return hero_call.json()['results'][0] response_hero_list = requests.get('https://api.epicsevendb.com/hero/') api_get_status(response_hero_list) hero_stat_list = [] for i in range(0,len(response_hero_list.json()['results'])): try: hero_name = response_hero_list.json()['results'][i]['_id'] hero_data = get_e7_hero_data(hero_name) for status in hero_status_dict.keys(): new_dict = hero_data['calculatedStatus'][status] new_dict['hero_id'] = hero_name new_dict['name'] = response_hero_list.json()['results'][i]['name'] new_dict['level'] = hero_status_dict[status] new_dict['attribute'] = response_hero_list.json()['results'][i]['attribute'] new_dict['role'] = response_hero_list.json()['results'][i]['role'] new_dict['zodiac'] = response_hero_list.json()['results'][i]['zodiac'] new_dict['sc'] = 1 if len(hero_data['specialty_change']) > 0 else 0 new_dict['ee'] = 1 if len(hero_data['ex_equip']) > 0 else 0 new_dict['ee_stat'] = hero_data['ex_equip'][0]['stat']['type'] if len(hero_data['ex_equip']) > 0 else '' hero_stat_list.append(new_dict) except: pass #end for loop df = pd.DataFrame(hero_stat_list) df['role'] = df['role'].replace(['manauser','assassin'],['soul-weaver','thief']) df['hp_flat'] = np.where(df['hp'] < 4100, 1, 0) df['atk_flat'] = np.where(df['atk'] < 790, 1, 0) df['def_flat'] = np.where(df['def'] < 475, 1, 0) print("There were", len(df['name'].unique()), "heroes pulled") df.to_csv('../inp/character_data.csv')
C#
UTF-8
1,129
3.71875
4
[ "MIT" ]
permissive
using System; using System.Collections.Generic; // https://www.spoj.com/problems/TRICOUNT/ #math #proof // Counts triangles (of all sizes) for different levels of the given construction. public static class TRICOUNT { private const int _maxLevel = 1000000; private static readonly IReadOnlyList<long> _triangleCounts; // See image for details: http://i.imgur.com/Sa2yh7R.jpg. static TRICOUNT() { long[] triangleCounts = new long[_maxLevel + 1]; triangleCounts[0] = 0; for (long n = 1; n <= _maxLevel; ++n) { triangleCounts[n] = triangleCounts[n - 1] + (n + 1) * n / 2 + (long)Math.Ceiling(0.25 * (n * n - 1)); } _triangleCounts = triangleCounts; } public static long Solve(int level) => _triangleCounts[level]; } public static class Program { private static void Main() { int remainingTestCases = int.Parse(Console.ReadLine()); while (remainingTestCases-- > 0) { Console.WriteLine( TRICOUNT.Solve(int.Parse(Console.ReadLine()))); } } }
Java
UTF-8
3,141
2.203125
2
[]
no_license
package com.yanwu.www.controller; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.fasterxml.jackson.databind.ObjectMapper; import com.yanwu.www.domain.Student; import com.yanwu.www.service.StudentService; import com.yanwu.www.util.GenerateCode; @Controller public class StudentController { private String mainPage; @Autowired StudentService studentService; @RequestMapping("/login") public String login(HttpServletRequest request,HttpServletResponse response,Student student,String inputCode, Model model){ Map<String, String> map=new HashMap<String, String>(); Student s=studentService.login(student); if(s!=null && "00000".equals(s.getId())){ s.setFlag("1"); } request.getSession().setAttribute("student", s); if(s!=null){ request.getSession().removeAttribute("code"); response.addHeader("msg", "success");//为了ajax能取到数据 }else{ response.addHeader("msg", "fail"); } model.addAttribute("map", map); mainPage="/WEB-INF/views/loginSuccess.jsp"; request.setAttribute("mainPage", mainPage); return "main"; } @RequestMapping("/logout") public String logout(HttpServletRequest request){ request.getSession().setAttribute("student", null); mainPage="/WEB-INF/views/loginSuccess.jsp"; request.setAttribute("mainPage", mainPage); return "main"; } @RequestMapping("/updatePassword") public String updatePassword(HttpServletRequest request,String newPassword,Model model){ if(newPassword!=null){ Student student=(Student) request.getSession().getAttribute("student"); student.setPassword(newPassword); try { studentService.update(student); } catch (Exception e) { // TODO Auto-generated catch block //e.printStackTrace(); model.addAttribute("error_msg", e.getMessage()); } } mainPage="/WEB-INF/views/student/updatePassword.jsp"; request.setAttribute("mainPage",mainPage); return "main"; } @RequestMapping("/getCode") @ResponseBody public String geCode(HttpServletRequest request,HttpServletResponse response,Student student ,Model model) throws IOException{ Map map=new HashMap<String,String>(); GenerateCode generateCode=new GenerateCode(); String code=generateCode.getCode(); ObjectMapper mapper = new ObjectMapper(); System.out.println("----------req------------"); String reqData=mapper.writeValueAsString(student); System.out.println(reqData); System.out.println("----------res------------"); map.put("code", code); String resData=mapper.writeValueAsString(map); System.out.println(resData); request.getSession().setAttribute("code", code); System.out.println(request.getSession().getAttribute("code")); return resData; } }
JavaScript
UTF-8
776
2.71875
3
[]
no_license
var message = require('face-message') // 默认延迟3秒关闭 message.info('信息') message.success('成功') message.error('错误') message.warn('警告') message.loading('加载') message.info('延迟2秒', 2) var info = message.info('手动关闭', false) setTimeout(function() { info.hide() }, parseFloat(Math.random()*1000)) var dom = document.createElement('em') setTimeout(function callee () { dom.innerHTML = 'dom' + Math.random() setTimeout(callee, 500) }, 500) message.info(dom) document.getElementById('show').onclick = function () { message.loadingBar.show(2) } document.getElementById('hide').onclick = function () { message.loadingBar.hide() } document.getElementById('fail').onclick = function () { message.loadingBar.fail() }
Java
UTF-8
276
2.140625
2
[]
no_license
package com.examle.model; public class Company { private String cNmae; public String getcNmae() { return cNmae; } public void setcNmae(String cNmae) { this.cNmae = cNmae; } @Override public String toString() { return "Company [cNmae=" + cNmae + "]"; } }
Go
UTF-8
761
3.609375
4
[]
no_license
package day15 type Generator struct { Factor int64 PreviousValue int64 Multiple int64 } func (g *Generator) Next() int64 { if g.Multiple > 0 { for { g.PreviousValue = (g.PreviousValue * g.Factor) % 2147483647 if g.PreviousValue%g.Multiple == 0 { return g.PreviousValue } } } else { g.PreviousValue = (g.PreviousValue * g.Factor) % 2147483647 return g.PreviousValue } } func NewGenerator(factor int64, startingValue int64) *Generator { g := new(Generator) g.Factor = factor g.PreviousValue = startingValue return g } func NewGeneratorMultiple(factor int64, startingValue int64, multiple int64) *Generator { g := new(Generator) g.Factor = factor g.PreviousValue = startingValue g.Multiple = multiple return g }
Markdown
UTF-8
5,856
2.734375
3
[]
no_license
# 零行代码为App添加异常加载占位图 - 努力,可能成功!放弃,注定失败! - CSDN博客 置顶2016年12月07日 17:05:34[上天眷顾我](https://me.csdn.net/qq_30513483)阅读数:612 ###### 前文提要 近期准备重构项目,需要重写一些通用模块,正巧需要设置App异常加载占位图的问题,心血来潮设想是否可以零行代码解决此问题,特在此分享实现思路。 ###### 思路分享 对于App占位图,通常需要考虑的控件有tableView、collectionView和webView,异常加载情况区分为无数据和网络异常等。 既然要实现零代码形式,因此就不能继承原始类重写或添加方法等方式,而是通过对对应控件添加类别(分类)来实现。 简单来说,以tableView为例实现思路为每当tableView调用reloadData进行刷新时,检测此时tableView行数,若行数不为零,正常显示数据。若行数为零,说明无数据显示占位图。 添加占位图的方式有很多种,例如借助tableView的backgroundView或直接以addSubView的方式添加,这里采用的为addSubView方式,尽量避免原生属性的占用。 对于检测tableView数据是否为空,借助tableView的代理dataSource即可。核心代码如下,依次获取tableView所具有的组数与行数,通过isEmpty这个flag标示最后确定是否添加占位图。 ``` - (void)checkEmpty { BOOL isEmpty = YES;//flag标示 id <UITableViewDataSource> dataSource = self.dataSource; NSInteger sections = 1;//默认一组 if ([dataSource respondsToSelector:@selector(numberOfSectionsInTableView:)]) { sections = [dataSource numberOfSectionsInTableView:self] - 1;//获取当前TableView组数 } for (NSInteger i = 0; i <= sections; i++) { NSInteger rows = [dataSource tableView:self numberOfRowsInSection:sections];//获取当前TableView各组行数 if (rows) { isEmpty = NO;//若行数存在,不为空 } } if (isEmpty) {//若为空,加载占位图 if (!self.placeholderView) {//若未自定义,展示默认占位图 [self makeDefaultPlaceholderView]; } self.placeholderView.hidden = NO; [self addSubview:self.placeholderView]; } else {//不为空,隐藏占位图 self.placeholderView.hidden = YES; } } ``` 相应的对于CollectionView亦可通过`numberOfSectionsInCollectionView:`和`collectionView:numberOfItemsInSection`获取其组数和行数,这里就不一一赘述。 需要注意的为webView占位图是否显示的判断,一种情况为webView调用其`webView: didFailLoadWithError:`方法,第二种为webView完成加载显示为空的情况。但存在的一个问题是,webView没有必选的协议方法,或可能根本没有设置代理。因此无法很好的判断webView是否响应其协议方法。因此该demo暂时没有添加webView的占位图,如果有好的想法可以评论指出。 ###### 接下来说最重要的一步,如何实现零行代码添加占位图呢? 其实实现思路非常简单,如果可以让tableView在执行reloadData时自动检测其行数就可以了。也就是我们需要在reloadData原有方法的基础上添加checkEmpty此方法。 这里又能体现到Runtime Method Swizzling的作用了,我们可以通过Method Swizzling替换reloadData方法,给予它新的实现。核心代码如下: ``` + (void)load { static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ //方法交换,将reloadData实现交换为sure_reloadData [self methodSwizzlingWithOriginalSelector:@selector(reloadData) bySwizzledSelector:@selector(sure_reloadData)]; }); } - (void)sure_reloadData { [self checkEmpty]; [self sure_reloadData]; } ``` 这样就可以实现reloadData的同时检测行数从而判断是否显示占位图的功能。 这里采用了上篇文章[《Runtime Method Swizzling开发实例汇总》](http://www.jianshu.com/p/f6dad8e1b848)的代码用例类`NSObject+Swizzling.h`,因此该篇文章也算上篇文章的延续,为Runtime Method Swizzling的另一种用例。感兴趣的朋友可以前往阅读更多的实用用例。 为实现零代码的效果,代码中已添加了placeholder视图的默认样式,如图所示: ![](http://upload-images.jianshu.io/upload_images/1767950-359ca5b4d9ce8452.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 占位图样式 若要实现效果图中点击图标重新刷新效果,需要让tableView调用reloadBlock,因为数据的刷新大多是不同的,所以具体刷新执行代码还是需要自己手动设置的。若不需要,则无需添加此操作。 ``` [_tableView setReloadBlock:^{ //刷新操作 }]; ``` 如果需要自定制占位视图样式也非常简单,因占位图样式比较统一,所以可直接修改`SurePlaceholderView`占位图类以达到自己想要的效果,再而在`UITableView+Sure_Placeholder.h`、`UICollectionView+Sure_Placeholder.h`、`UIWebView+Sure_Placeholder.h`类别中均外漏了placeholderView属性,将其赋值为新的视图亦可。 以tableView为例,可以通过如下方式进行修改 `_tableView.placeholderView =[[CustomPlaceholderView alloc]initWithFrame:_tableView.bounds];` 同样的对于无数据与无网络的效果切换,也可以通过网络是否可用的标示来进行展示不同的占位图。例如 ``` if (is_Net_Available) { _tableView.placeholderView = [[CustomPlaceholderView alloc]initWithFrame:_tableView.bounds]; } else { _tableView.placeholderView = [[NetNoAvailableView alloc]initWithFrame:_tableView.bounds]; } ``` 为方便大家阅读和修改,demo已上传github。 下载链接如下: [零行代码为App添加无数据占位图](https://github.com/LSure/AppPlaceholder)
Markdown
UTF-8
6,737
3.21875
3
[]
no_license
## What this module is about? This module introduces students to the fundamental techniques, concepts and contemporary discussions across the broad field of data science. With data and data related artefacts becoming ubiquitous in all aspects of social life, data science gains access to new sources of data, is taken up across an expanding range of research fields and disciplines, and increasingly engages with societal challenges. The module provides an advanced introduction to the theoretical and scientific frameworks of data science, and to the fundamental techniques for working with data using appropriate procedures, algorithms and visualisation. Students learn how to critically approach data and data-driven artefacts, and engage with and critically reflect on contemporary discussions around the practice of data science, its compatibility with different analytics frameworks and disciplinary, and its relation to on-going digital transformations of society. As well as lectures discussing the theoretical, scientific and ethical frameworks of data science, the module features coding labs and workshops that expose students to the practice of working effectively with data, algorithms, and analytical techniques, as well as providing a platform for reflective and critical discussions on data science practices, resulting data artefacts and how they can be interpreted, actioned and influence society. ## What does this module aim to achieve? In this module, students gain both formal knowledge and practical experience of the theoretical, scientific and ethical frameworks underpinning data science and critically reflect on the scope and impact of these frameworks. Lectures will provide a grounded understanding of the theoretical and scientific frameworks underpinning data science. In workshops, students gain experience of the fundamentals of the practice of data science, and through seminars they will be exposed to academic debates in data studies and related fields about the changing role of data science in society as seen in, for instance, the increasing use of data artefacts in policy and decision making in governmental bodies and businesses, how scientific discoveries are made and communicated, or how (in)equalities and power (im)balances are surfacing in uses of data. The module aims to build the required skills to apply data science techniques and algorithms within and across analytics frameworks developed in different disciplines. The module aims to cultivate a holistic data science practice which reviews the whole data science process critically and inquisitively, and handles problems through a user-centred thinking. This practice also embraces critical reflection about the data, algorithms, and data artefacts, as well as the ethical, societal, and cultural implications of data science broadly conceived. ## Learning outcomes - Demonstrate an in-depth understanding of the theoretical underpinnings, scientific and ethical frameworks of data science as applied across disciplines - Demonstrate a critical understanding of the role that data and data intensive practices play in research, industry and the wider society - Demonstrate an understanding of the workings and the practicalities of the data science process - Apply and evaluate data science techniques and tools for particular scenarios and argue their suitability - Demonstrate an ability to critique any resulting data artefacts, such as data-informed decisions to data-driven models, including from a user-centred perspective - Develop and demonstrate an understanding of the societal, ethical, and cultural implications of advances in and applications of data science ## Assessment The assessments will be individual based and will involve two components: a critical review and a data-driven essay. The critical review will involve students approaching a selected Data Science project through a critical lens covered during the lectures. The short report will expect students to engage with the related literature and reflect on the decisions made by the researchers of the project. Within the second component, the data-driven essay, students will report on a data science project that they carried on a chosen question and appropriate data set. The essay will be reporting on the data science process from initiation to evaluation to reflection while engaging with the relevant literature in the domain. These essays vary in length, depending on the number of CATS a student wishes to complete. | | **15-CATS** | **20 CATS** | **30 CATS** | | ------------------- | ------------------- | ------------------- | ------------------- | | **Critical Review** | (1000 words) -- 40% | (1250 words) -- 40% | (1500 words) -- 40% | | **Final Essay** | (1500 words) -- 60% | (2000 words) -- 60% | (3000 words) -- 60% | ## Illustrative Bibliography - Data science as a scientific practice : Dhar, Vasant. "Data science and prediction." Communications of the ACM, 56.12 (2013): 64-73. - Iliadis, A. and Russo, F., 2016. Critical data studies: An introduction. Big Data & Society, 3(2), p.2053951716674238. - Ginsberg, Jeremy, et al. "Detecting influenza epidemics using search engine query data." Nature (2008) - Kandel, Sean, et al. "Enterprise data analysis and visualization: An interview study." Visualization and Computer Graphics, IEEE Transactions on 18.12 (2012): 2917-2926. - Osborne, Jason. "Notes on the use of data transformations." Practical Assessment, Research & Evaluation 8.6 (2002): 1-8. - Osborne, Jason W., and Amy Overbay. "The power of outliers (and why researchers should always check for them)." Practical assessment, research & evaluation 9.6 (2004): 1- 12. - Guyon, Isabelle, and André Elisseeff. "An introduction to variable and feature selection." The Journal of Machine Learning Research 3 (2003): 1157-1182. - Ringnér, Markus (2008). "What is principal component analysis?". Nature biotechnology (1087-0156), 26 (3), p. 303. - Jaworska, Natalia, and Angelina Chupetlovska-Anastasova. "A review of multidimensional scaling (MDS) and its utility in various psychological domains." Tutorials in Quantitative Methods for Psychology 5.1 (2009): 1-10. - Kohavi, A Study of Cross-Validation and Bootstrap for Accuracy Estimation and Model Selection, Intl. Jnt. Conf. AI - White, Douglas R., and Stephen P. Borgatti. "Betweenness centrality measures for directed graphs." Social Networks 16.4 (1994): 335-346. - Heer, Jeffrey, and Ben Shneiderman. "Interactive dynamics for visual analysis." Queue 10.2 (2012): 30. - Ruckenstein, M. and Schüll, N.D., 2017. The datafication of health. Annual Review of Anthropology, 46, pp.261-278. - Pink, S., Ruckenstein, M., Willim, R. and Duque, M., 2018. Broken data: Conceptualising data in an emerging world. Big Data & Society, 5(1), p.2053951717753228.
Ruby
UTF-8
3,130
2.875
3
[ "MIT" ]
permissive
#!/usr/bin/env ruby # # Validate a content security policy for syntax violations. # Internal: Helper for formatting the output. # # message - The message to display to the end user. # type - Severity of the message. Values can be 'error', 'success' or 'info'. # # Returns a formatted string of the message. def output(message, type) puts "\e[31m[ ✘ ]\e[0m #{message}" if type == 'error' puts "\e[32m[ ✔︎ ]\e[0m #{message}" if type == 'success' puts "\e[33m[ ✻ ]\e[0m #{message}" if type == 'info' end require 'optparse' require 'net/http' options = {} # Setup and allow options to be passed into the script. OptionParser.new do |opts| opts.banner = "Usage:\n" \ "\n URL ./validate-csp http://example.com" \ "\n Inline ./validate-csp \"default-src *; script-src; etc\"" \ "\n\n" \ 'Options:' opts.on('-r', '--report-only', 'Check using "Content-Security-Policy-Report-Only" header.') do options[:report_only] = true end end.parse! # Determine whether we are working a URL or a string. if ARGV[0].match(/^http/) response = Net::HTTP.get_response(URI(ARGV[0])) header = (options[:report_only]) ? response['Content-Security-Policy-Report-Only'] : response['Content-Security-Policy'] abort 'Sorry, no content security policy data found.' if header.nil? csp_data = header else csp_data = ARGV[0] end # Everyone needs a good default. if csp_data.include? 'default-src' output "'default-src' is present.", 'success' else missing_defaul_src = "The 'default-src' directive should be defined to " \ 'actas a default for any missing directives - ' \ 'See http://bit.ly/1uTJfGM.' output missing_defaul_src, 'info' end # Ensure we have all the recommended rules for a default policy. required_directives = [ 'script-src', 'object-src', 'img-src', 'media-src', 'frame-src', 'font-src', 'frame-ancestors', 'connect-src', 'style-src' ] required_directives.each do |directive| if csp_data.include? directive output "'#{directive}' was found.", 'success' else output "'#{directive}' is not present.", 'error' end end # Evaluate each directive and check for any malformed domains. rulesets = csp_data.split(';') rulesets.each do |ruleset| ruleset_data = "#{ruleset}".strip ruleset_items = ruleset_data.split(' ') ruleset_items.each do |uri| output "Invalid URI entry detected (#{uri})", 'error' if uri =~ /\.\*$/ end end if csp_data.include? 'frame-src' frame_src_deprecation = "'frame-src' is being deprecated in favour of " \ "'child-src' - See http://bit.ly/1uTJ3Ye." output frame_src_deprecation, 'info' end # While not required, it is a good idea to ensure you have somewhere to report # any violations should they occur. if csp_data.include? 'report-uri' output 'Violation reporting endpoint found.', 'success' else violation_text = 'You should consider including a reporting endpoint ' \ '(using report-uri) so you capture any violations - ' \ 'See http://bit.ly/1C4caYK' output violation_text, 'info' end
C
GB18030
2,865
2.546875
3
[]
no_license
#include "timer.h" #include "led.h" #include "usart.h" void DIR_Init(void) //DIRPB3ʼ { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_SetBits(GPIOB,GPIO_Pin_5); //ʼλ } void TIM4_PWM_Init(u32 arr,u32 psc) { NVIC_InitTypeDef NVIC_InitStructure; GPIO_InitTypeDef GPIO_InitStructure; TIM_OCInitTypeDef TIM_OCInitStructure; TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE); //ʱʹ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB , ENABLE); //ʹGPIOAFIOùģʱ //øΪ,TIM4 CH1PWM岨 GPIOB.6 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOB, &GPIO_InitStructure);//ʼGPIO //ʼTIM4 TIM4->CR1 |= TIM_CR1_URS; //һʼʱʱԶһжϵ⡣ TIM_TimeBaseStructure.TIM_Period = arr; //һ¼װԶװؼĴڵֵ TIM_TimeBaseStructure.TIM_Prescaler =psc; //ΪTIMxʱƵʳԤƵֵ TIM_TimeBaseStructure.TIM_ClockDivision = 0; //ʱӷָ:TDTS = Tck_tim TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; //TIMϼģʽ TIM_TimeBaseInit(TIM4, &TIM_TimeBaseStructure); //TIM_TimeBaseInitStructָIJʼTIMxʱλ TIM_ITConfig(TIM4,TIM_IT_Update,ENABLE ); //ʹָTIM4ж,ж NVIC_InitStructure.NVIC_IRQChannel = TIM4_IRQn; //TIM4ж NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; //ռȼ0 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //ȼ3 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQͨʹ NVIC_Init(&NVIC_InitStructure); //NVIC_InitStructָIJʼNVICĴ //ʼTIM4_CH1 PWMģʽ TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM2; //ѡʱģʽ:TIMȵģʽ2 TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; //Ƚʹ TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; //:TIMȽϼԸ TIM_OC1Init(TIM4, &TIM_OCInitStructure); //TָIJʼTIM4_CH1 TIM_OC1PreloadConfig(TIM4, TIM_OCPreload_Enable); //ʹTIM4CCR2ϵԤװؼĴ //TIM_Cmd(TIM4, ENABLE); }
C++
UTF-8
6,981
2.515625
3
[]
no_license
// ********************************************************************* // ** // ** Informática Gráfica, curso 2019-20 // ** Implementación de la clase 'MallaRevol' // ** // ********************************************************************* #include "ig-aux.h" #include "tuplasg.h" #include "lector-ply.h" #include "matrices-tr.h" #include "malla-revol.h" using namespace std ; // ***************************************************************************** // Método que crea las tablas de vértices, triángulos, normales y cc.de.tt. // a partir de un perfil y el número de copias que queremos de dicho perfil. void MallaRevol::inicializar ( const std::vector<Tupla3f> & perfil, // tabla de vértices del perfil original const unsigned num_copias // número de copias del perfil ) { // COMPLETAR: Práctica 2: completar: creación de la malla.... /* //Barrido int num_verts=perfil.size(); vertices.clear(); triangulos.clear(); for(int i=0;i<num_copias;i++){ for(int j=0;j<num_verts;j++){ Tupla3f q=MAT_Traslacion(0,0,(float)i/(num_copias-1))*perfil[j]; vertices.push_back(q); } } for(int i=0;i<num_copias-1;i++){ for(int j=0;j<num_verts-1;j++){ int k=i*num_verts+j; triangulos.push_back({k,k+num_verts,k+num_verts+1}); triangulos.push_back({k,k+num_verts+1,k+1}); } } */ //Cálculo de las normales vector<Tupla3f> nor_aristas; Tupla3f m; for (int i=0;i<perfil.size()-1;i++){ m=perfil[i+1]-perfil[i]; nor_aristas.push_back({m(1),-m(0),0.0}); //¿? if(nor_aristas[i](0)!=0 || nor_aristas[i](1)!=0 || nor_aristas[i](2)!=0) nor_aristas[i]=nor_aristas[i].normalized(); } vector<Tupla3f> nor_ver_aux; nor_ver_aux.push_back(nor_aristas[0]); for (int i=1;i<perfil.size()-1;i++){ nor_ver_aux.push_back(nor_aristas[i-1]+nor_aristas[i]); if(nor_ver_aux[i](0)!=0 || nor_ver_aux[i](1)!=0 || nor_ver_aux[i](2)!=0) nor_ver_aux[i]=nor_ver_aux[i].normalized(); } nor_ver_aux.push_back(nor_aristas[nor_aristas.size()-1]); //Cálculo de coordenadas de textura vector<float> d; for(int i=0;i<perfil.size()-1;i++){ d.push_back(sqrt(pow(perfil[i+1](X)-perfil[i](X),2.0)+pow(perfil[i+1](Y)-perfil[i](Y),2.0))); } float tam=0.0; for (int i=0;i<d.size();i++){ tam+=d[i]; } vector<float> t (perfil.size(),0.0); for (int i=0;i<t.size()-1;i++){ for (int j=0;j<i;j++){ t[i]+=d[j]; } t[i]=t[i]/tam; } t.back()=1.0; //¿? //Tabla de vértices int num_verts=perfil.size(); vertices.clear(); triangulos.clear(); Tupla3f q,n; for(int i=0;i<num_copias;i++){ for(int j=0;j<num_verts;j++){ q=MAT_Rotacion((2*180*i)/(num_copias-1),{0,1,0})*perfil[j]; vertices.push_back(q); n=MAT_Rotacion((2*180*i)/(num_copias-1),{0,1,0})*nor_ver_aux[j]; //¿? nor_ver.push_back(n); cc_tt_ver.push_back({1.0-(float)i/(num_copias-1),1-t[j]}); } } //Tabla de triángulos for(int i=0;i<num_copias-1;i++){ for(int j=0;j<num_verts-1;j++){ int k=i*num_verts+j; triangulos.push_back({k,k+num_verts,k+num_verts+1}); triangulos.push_back({k,k+num_verts+1,k+1}); } } } // ----------------------------------------------------------------------------- // constructor, a partir de un archivo PLY MallaRevolPLY::MallaRevolPLY ( const std::string & nombre_arch, const unsigned nperfiles ) { ponerNombre( std::string("malla por revolución del perfil en '"+ nombre_arch + "'" )); vector<Tupla3f> perfil; LeerVerticesPLY(nombre_arch,perfil); inicializar(perfil,nperfiles); } //x=1 Cilindro::Cilindro(const int num_verts_per, const unsigned nperfiles){ ponerNombre( std::string("malla por revolución: cilindro" )); vector<Tupla3f> perfil; perfil.push_back({0,0,0}); perfil.push_back({1,0,0}); float y; for(float i=0 ;i < num_verts_per; i++){ y=i/(num_verts_per-1); perfil.push_back({1,y,0}); } perfil.push_back({1,1,0}); perfil.push_back({0,1,0}); inicializar(perfil,nperfiles); } //y=-x+1 (Recta que pasa por (1,1)) Cono::Cono(const int num_verts_per, const unsigned nperfiles){ ponerNombre( std::string("malla por revolución: cono" )); vector<Tupla3f> perfil; perfil.push_back({0,0,0}); perfil.push_back({1,0,0}); for(float i= 0;i < num_verts_per;i++){ float x=(num_verts_per-1-i)/(num_verts_per-1); perfil.push_back({x,-x+1,0}); } /* for(int i = 0; i < num_verts_per; i++) perfil.push_back({1-(float)i/(num_verts_per-1),(float)i/(num_verts_per-1),0}); */ inicializar(perfil,nperfiles); } Esfera::Esfera(const int num_verts_per, const unsigned nperfiles){ ponerNombre( std::string("malla por revolución: esfera" )); vector<Tupla3f> perfil; for(float i = 0; i < num_verts_per; i++){ float x=i/(num_verts_per-1); float ang = M_PI*(x-(float)1/2); perfil.push_back({cos(ang),sin(ang),0}); } //y=sqrt(1-x^2) /*vector<Tupla3f> perfil; for(float i= 0;i < num_verts_per ;i++){ float x=i/num_verts_per; perfil.push_back({x,sqrt(1-x*x),0}); } for(float i= 0;i < num_verts_per ;i++){ float x=(num_verts_per-i)/num_verts_per; perfil.push_back({x,-sqrt(1-x*x),0}); }*/ inicializar(perfil,nperfiles); } //Fijo unos valores en el constructor vacío con los que la esfera se ve bien //Para usarlo más cómodamente en la práctica 3 Esfera::Esfera() : Esfera(20,30){} /*Prueba1::Prueba1( const int num_verts_per,const unsigned nperfiles){ vector<Tupla3f> perfil={ {0,-1,0}, {1,-1,0} }; for(float i = 0; i < num_verts_per; i++){ float x=i/(num_verts_per-1); float ang = M_PI*(x-(float)1/2); perfil.push_back({1+(-cos(ang)*0.75),sin(ang)*0.75,0}); } perfil.push_back({1,1,0}); perfil.push_back({0,1,0}); /*perfil.push_back({0,-1.5,0}); perfil.push_back({1.5,-1.5,0}); for(int i = 0; i < num_verts_curva; i++){ float alpha = M_PI*(float)i/(num_verts_curva-1); perfil.push_back({1.5-sin(alpha),-cos(alpha),0}); } perfil.push_back({1.5,1.5,0}); perfil.push_back({0,1.5,0}); */ /* inicializar(perfil,nperfiles); }*/ /*Puente::Puente( const int num_verts_per,const unsigned nperfiles){ vector<Tupla3f> perfil={ {0.5,0,0}, {1,0,0}, {1,1,0}, {-1,1,0}, {-1,0,0}, {-0.5,0,0} }; /*perfil.push_back({0.5,0,0}); perfil.push_back({1,0,0}); perfil.push_back({1,1,0}); perfil.push_back({-1,1,0}); perfil.push_back({-1,0,0}); perfil.push_back({-0.5,0,0});*/ /*for(float i = 0; i < num_verts_per; i++){ float x=i/(num_verts_per-1); float ang = M_PI*(1-x); perfil.push_back({(float)(cos(ang))/2,(float)(sin(ang))/2,0}); } inicializar(perfil,nperfiles); }*/
Python
UTF-8
738
2.984375
3
[]
no_license
import sqlite3 DATABASE = 'data/b.db' #setuping up database def setup_db(): db = sqlite3.connect(DATABASE) cur = db.cursor() #creating a table for database cur.execute("CREATE TABLE IF NOT EXISTS mytable( title TEXT, define TEXT)") db.commit() #Inserting data into tables database cur.execute("SELECT COUNT(*) FROM mytable") if cur.fetchall()[0][0] == 0: #inserting definition cur.execute('INSERT INTO mytable(title, define) VALUES("Deadlock", "When two or more programs, become deadlocked, when each of them is doing nothing while waiting for a resource, occupied by another program, in the same set. ")') db.commit() if __name__ == "__main__": setup_db()
PHP
UTF-8
1,598
2.875
3
[]
no_license
<?php function getAllDeparts(): array { global $connexion; $query = "SELECT depart.*, pays.nom AS pays, sejour.nom AS sejour FROM depart INNER JOIN sejour ON sejour.id = depart.sejour_id INNER JOIN pays ON pays.id = sejour.pays_id;"; $stmt = $connexion->prepare($query); $stmt->execute(); return $stmt->fetchAll(); } function insertDepart(string $date_depart, string $nb_place, string $prix, string $sejour_id): int { /* @var $connexion PDO */ global $connexion; $query = "INSERT INTO depart (date_depart, nb_place, prix, sejour_id) VALUES (:date_depart, :nb_place, :prix, :sejour_id)"; $stmt = $connexion->prepare($query); $stmt->bindParam(":date_depart", $date_depart); $stmt->bindParam(":nb_place", $nb_place); $stmt->bindParam(":prix", $prix); $stmt->bindParam(":sejour_id", $sejour_id); $stmt->execute(); return $connexion->lastInsertId(); } function updateDepart(int $id, string $date_depart, string $nb_place, string $prix, string $sejour_id) { /* @var $connexion PDO */ global $connexion; $query = "UPDATE depart SET date_depart = :date_depart, nb_place = :nb_place, prix = :prix, sejour_id = :sejour_id WHERE id = :id"; $stmt = $connexion->prepare($query); $stmt->bindParam(":id", $id); $stmt->bindParam(":date_depart", $date_depart); $stmt->bindParam(":nb_place", $nb_place); $stmt->bindParam(":prix", $prix); $stmt->bindParam(":sejour_id", $sejour_id); $stmt->execute(); }
Java
UTF-8
699
2.84375
3
[]
no_license
import static org.junit.Assert.*; import org.junit.Test; /** [*] --> Vide Vide --> Courant : push() Vide --> Vide : pull() Courant --> Plein : push() [size() = MAX-1] Courant --> Courant : push() [size() < MAX-1] Plein --> Courant : pull() Plein --> Plein : push() Courant --> Courant : pull() [size() > 1] Courant --> Vide : pull() [size() = 1] @enduml */ public class TestPile { //[*] --> Vide @Test public void test_nouvelle_pile_vide_au_depart() { Pile p = new Pile(); assertEquals(true, p.est_vide()); } @Test public void test_pile_vide_plus_vide_apres_push() { Pile p = new Pile(); assertEquals(true, p.est_vide()); p.push(1); assertEquals(false,p.est_vide()); } }
Java
UTF-8
2,353
2.203125
2
[]
no_license
package fi.tkk.media.xide.client.parsing.elements.form; import java.util.ArrayList; import java.util.Iterator; import com.google.gwt.user.client.ui.CheckBox; import com.google.gwt.user.client.ui.HasVerticalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.ListBox; import com.google.gwt.user.client.ui.RadioButton; import com.google.gwt.user.client.ui.TextBox; import com.google.gwt.user.client.ui.Widget; import fi.tkk.media.xide.client.parsing.ParseElement; public class Select1Element extends ParseElement { public Select1Element(){ super("select1"); } public ParseElement getInstance(){ return (new Select1Element()); } public Widget draw() { //return super.Create(); HorizontalPanel hp = new HorizontalPanel(); hp.setWidth("100%"); // TODO: add css // hp.addStyleName(style); hp.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE); hp.setWidth("100%"); // Draw label ParseElement label = getChildByName("label"); if (label != null) { hp.add ( label.draw() ); } String type = parameters.get("appearance"); if (type.equals(FULL)) { // Radiobuttons for (Iterator<ParseElement> iterator = children.iterator(); iterator.hasNext();) { ParseElement o = iterator.next(); if (o.getName().equals("item")) { RadioButton rb_1 = new RadioButton(""); rb_1.setEnabled(false); hp.add(rb_1); ParseElement buttonLabel = o.getChildByName("label"); if (buttonLabel != null) { hp.add ( buttonLabel.draw() ); } } } } else if (type.equals(COMPACT) || type.equals(MIN)) { // Dropdown list final ListBox listBox = new ListBox(); for (Iterator<ParseElement> iterator = children.iterator(); iterator.hasNext();) { ParseElement o = iterator.next(); if (o.getName().equals("item")) { String textLabel; ParseElement buttonLabel = o.getChildByName("label"); if (buttonLabel != null) { textLabel = o.getChildByName("label").getValue(); listBox.addItem(textLabel); } } } listBox.setMultipleSelect(false); if (type.equals(COMPACT)) { listBox.setVisibleItemCount(listBox.getItemCount()); } hp.add(listBox ); } return hp; } }
C++
UTF-8
1,109
2.6875
3
[]
no_license
#include <iostream> #include <stdlib.h> #include <stdio.h> #include "Graph.h" #include "Distribution.h" #include "ImagesComparison.h" ImagesComparison::ImagesComparison() { } ImagesComparison::~ImagesComparison() { } void ImagesComparison::buildGraph(std::vector<Image*> &images, Graph *graph) { std::vector<Distribution*> images_dists; for(unsigned int i = 0; i < images.size(); ++i) { Distribution *image_dist = new Distribution(); images[i]->getDistribution(image_dist); images_dists.push_back(image_dist); } for(unsigned int i = 0; i < images.size(); ++i) { for(unsigned int j = i+1; j < images.size(); ++j) { if(i == j) break; bool similar = images_dists[i]->compare(images_dists[j]); graph->setAdjacency(i,j,similar); } } for(unsigned int i = 0; i < images_dists.size(); ++i) { delete images_dists[i]; } images_dists.clear(); } void ImagesComparison::getSimilarImages(std::vector<Image*> &images, std::vector<std::vector<int> > &similar_images) { Graph graph(images.size()); buildGraph(images, &graph); graph.getCliques(similar_images); }
C#
UTF-8
892
2.59375
3
[]
no_license
using System; using MyProjectCsharp.OneArgument; using NUnit.Framework; namespace MyProjectCsharp.tests.OneArgument { [TestFixture] public class OneArgumentFactoryTests { [TestCase("Sinus", typeof(Sinus))] [TestCase("Cosinus", typeof(Cosinus))] [TestCase("Tangens", typeof(TangentTest))] [TestCase("Catangens", typeof(Cotangent))] [TestCase("ArcSinus", typeof(Arcsin))] [TestCase("ArcCosinus", typeof(Arccos))] [TestCase("ArcTangens", typeof(Arctan))] [TestCase("Power", typeof(Power))] [TestCase("Logarifm", typeof(Logarithm))] [TestCase("LogarifmOfTwo", typeof(LogarithmOfTwoTests))] public void CalculateTest(string name, Type type) { var calculator = OneArgumentFactory.CreateCalculator(name); Assert.IsInstanceOf(type, calculator); } } }
Java
UTF-8
2,261
2.21875
2
[]
no_license
package com.example.astronomer; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import java.util.ArrayList; import java.util.Objects; public class EventsActivity extends AppCompatActivity { protected static ArrayList<String> events = new ArrayList<String>(); private void initModel(){ events.clear(); events.add("Lunar Eclipses"); events.add("Solar Eclipses"); events.add("Solar Transits"); events.add("Comets"); events.add("Moon Phases"); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_events); Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); initModel(); EventArrayAdapter<String> dayAdapter = new EventArrayAdapter<>(this, android.R.layout.simple_list_item_1, android.R.id.text1, events); final ListView eventLV = findViewById(R.id.eventLV); eventLV.setAdapter(dayAdapter); eventLV.setOnItemClickListener(new ListView.OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { swapToSettings(view, position); } }); } public void swapToSettings(View v, int position){ Intent swap = new Intent(this, SettingsActivity.class); swap.putExtra("eventName", events.get(position)); startActivityForResult(swap,1 ); } public void onActivityResult(int resultcode, int errorcode, Intent ini){ } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { //Handling for back button inside ActionBar Intent ini = getIntent(); setResult(0, ini); finish(); return true; } else return super.onOptionsItemSelected(item); } }
Java
UTF-8
737
2.40625
2
[]
no_license
package net.loveruby.cflat.ast; import net.loveruby.cflat.type.Type; import net.loveruby.cflat.type.TypeRef; import net.loveruby.cflat.type.UnionType; import java.util.List; /** * @author 刘科 2018/5/28 */ public class UnionNode extends CompositeTypeDefinition { public UnionNode(Location location, TypeRef typeRef, String name, List<Slot> members) { super(location, typeRef, name, members); } public String kind() { return "union"; } public boolean isUnion(){ return true; } public Type definingType() { return new UnionType(name(), members(), location()); } public <T> T accept(DeclarationVisitor<T> visitor) { return visitor.visit(this); } }
Java
UTF-8
3,386
2.5625
3
[ "LicenseRef-scancode-unknown-license-reference", "CC-BY-4.0" ]
permissive
package fossilsarcheology.client.gui; import fossilsarcheology.server.entity.mob.EntityQuagga; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; public class ContainerQuagga extends Container { private IInventory inventory; private EntityQuagga entity; public ContainerQuagga(IInventory playerInventory, IInventory inventory, EntityQuagga entity) { this.inventory = inventory; this.entity = entity; byte b0 = 3; inventory.openInventory(); int i = (b0 - 4) * 18; this.addSlotToContainer(new Slot(inventory, 0, 8, 18)); // Sideslot this.addSlotToContainer(new Slot(inventory, 1, 8, 36)); // armor int j; int k; if (entity.isChested()) { for (j = 0; j < b0; ++j) { for (k = 0; k < 5; ++k) { this.addSlotToContainer(new Slot(inventory, 2 + k + j * 5, 80 + k * 18, 18 + j * 18)); } } } for (j = 0; j < 3; ++j) { for (k = 0; k < 9; ++k) { this.addSlotToContainer(new Slot(playerInventory, k + j * 9 + 9, 8 + k * 18, 102 + j * 18 + i)); } } for (j = 0; j < 9; ++j) { this.addSlotToContainer(new Slot(playerInventory, j, 8 + j * 18, 160 + i)); } } @Override public boolean canInteractWith(EntityPlayer player) { return this.inventory.isUseableByPlayer(player) && this.entity.isEntityAlive() && this.entity.getDistanceToEntity(player) < 8.0F; } /** * Called when a player shift-clicks on a slot. You must override this or * you will crash when someone does that. */ @Override public ItemStack transferStackInSlot(EntityPlayer player, int slotIndex) { ItemStack transferred = null; Slot slot = (Slot) this.inventorySlots.get(slotIndex); if (slot != null && slot.getHasStack()) { ItemStack stack = slot.getStack(); transferred = stack.copy(); if (slotIndex < this.inventory.getSizeInventory()) { if (!this.mergeItemStack(stack, this.inventory.getSizeInventory(), this.inventorySlots.size(), true)) { return null; } } else if (this.getSlot(1).isItemValid(stack) && !this.getSlot(1).getHasStack()) { if (!this.mergeItemStack(stack, 1, 2, false)) { return null; } } else if (this.getSlot(0).isItemValid(stack)) { if (!this.mergeItemStack(stack, 0, 1, false)) { return null; } } else if (this.inventory.getSizeInventory() <= 2 || !this.mergeItemStack(stack, 2, this.inventory.getSizeInventory(), false)) { return null; } if (stack.stackSize == 0) { slot.putStack(null); } else { slot.onSlotChanged(); } } return transferred; } /** * Called when the container is closed. */ @Override public void onContainerClosed(EntityPlayer player) { super.onContainerClosed(player); this.inventory.closeInventory(); } }
Java
UTF-8
1,334
1.671875
2
[]
no_license
package com.zend.ide.g; import com.zend.ide.util.dr; import com.zend.ide.util.u; import javax.swing.Action; import javax.swing.ActionMap; public class f extends u { final m i; public f(m paramm) { super(paramm); } public void b() { super.b(); ActionMap localActionMap = this.i.getActionMap(); Object localObject = new dr(this, new k(this.i), this.g); localActionMap.put(m.k, (Action)localObject); a("keys.showInBrowser", (Action)localObject, "outputComponent", true); a("keys.showInBrowser", (Action)localObject, "debug_output", true); localObject = localActionMap.get("closeAction"); a("keys.closeDocument", (Action)localObject, "debug_output", true); a("keys.closeDocument", (Action)localObject, "outputComponent", true); localObject = localActionMap.get("closeAllAction"); a("keys.closeAll", (Action)localObject, "debug_output", true); a("keys.closeAll", (Action)localObject, "outputComponent", false); localObject = localActionMap.get("closeOthersAction"); a("keys.closeOthers", (Action)localObject, "debug_output", true); a("keys.closeOthers", (Action)localObject, "outputComponent", false); } } /* Location: C:\Program Files\Zend\ZendStudio-5.5.1\bin\ZendIDE.jar * Qualified Name: com.zend.ide.g.f * JD-Core Version: 0.6.0 */
JavaScript
UTF-8
735
2.625
3
[ "MIT" ]
permissive
const fs = require('fs'); /* eslint-disable no-console, no-undef*/ const location = './src/constants/environment-configs.json'; fs.readFile(location, 'utf8', (err, data) => { if (err) { console.log('ERROR!', err); return; } const cliArgs = process.argv.reduce((acc, val, index) => { acc[index] = val; return acc; }, {}); const setToTrue = !cliArgs[2] || (cliArgs[2] === 'true'); const config = JSON.parse(data); config.WEB_PAGE_MODE = setToTrue; fs.writeFile(location, JSON.stringify(config, null, 2), (error) => { if (error) { console.log('WRITE ERROR', error); return; } console.log(`SET TO ${setToTrue ? 'TRUE' : 'FALSE'}`); }); }); /* eslint-enable no-console, no-undef*/
Shell
UTF-8
2,466
3.46875
3
[]
no_license
#!/bin/bash ORATAB=/etc/oratab function help() { echo "$(basename $0) -a [start/stop] -s [sid]" exit } while getopts :a:s: OPT do case $OPT in a) OPERATION="$OPTARG" ;; s) DBNAME="$OPTARG" ;; *) help ;; esac done test -z $OPERATION && help test -z $DBNAME && help LINE=$(grep -E "^$DBNAME:.*:.*" "$ORATAB") if [ $? != 0 ]; then echo "Could not locate $DBNAME in $ORATAB" exit fi source /usr/local/bin/nnip_oraenv ${DBNAME} mkdir -p /mnt/oracle/admin/${ORACLE_SID}/log VERSION=$(sqlplus -V | grep -o -E '12|11|19') case "${VERSION}" in 11) SQLCONN="/@${ORACLE_SID}_SYSDBA as sysdba" ;; 12) SQLCONN="/@${ORACLE_SID}_SYSDBA as SYSDBA" ;; 19) SQLCONN="/@${ORACLE_SID}_SYSDBA as SYSDBA" ;; esac case "$OPERATION" in start) echo "Starting $ORACLE_SID instance." sqlplus ${SQLCONN} 1> /mnt/oracle/admin/${ORACLE_SID}/log/db_start.log 2>&1 << EOF startup mount; declare v_bum_active number := 0; v_role varchar2(50); begin select count(1) into v_bum_active from v\$backup where STATUS = 'ACTIVE'; select DATABASE_ROLE into v_role from v\$database; if (v_bum_active > 0) then execute immediate 'alter database end backup'; end if; if (v_role = 'PRIMARY') then execute immediate 'alter database open'; end if; end; / select open_mode from v\$database; EOF ;; stop) echo "Stopping $ORACLE_SID instance." sqlplus ${SQLCONN} 1>/mnt/oracle/admin/${ORACLE_SID}/log/db_stop.log 2>&1 << EOF declare v_mode varchar2(50); v_bum_active number := 0; begin select count(1) into v_bum_active from v\$backup where STATUS = 'ACTIVE'; if (v_bum_active > 0) then execute immediate 'alter database end backup'; end if; end; / shutdown immediate; EOF exit $? ;; esac
Java
UTF-8
1,915
1.71875
2
[ "MIT" ]
permissive
/******************************************************************************* * Copyright (c) 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.core.refactoring.participants; /** * Interface to define the processor IDs provided by JDT refactorings. * * <p> * This interface declares static final fields only; it is not intended to be * implemented. * </p> * * @since 1.4 * * @noimplement This interface is not intended to be implemented by clients. * @noextend This interface is not intended to be extended by clients. */ public interface IRefactoringProcessorIds { /** * Processor ID of the Change Method Signature processor * (value <code>"org.eclipse.jdt.ui.changeMethodSignatureRefactoring"</code>). * * The Change Method Signature processor loads {@link ChangeMethodSignatureParticipant}s registered for the * <code>IMethod</code> whose signature is changed. */ //$NON-NLS-1$ public static String CHANGE_METHOD_SIGNATURE_PROCESSOR = "org.eclipse.jdt.ui.changeMethodSignatureRefactoring"; /** * Processor ID of the Introduce Parameter Object processor * (value <code>"org.eclipse.jdt.ui.introduceParameterObjectRefactoring"</code>). * * The Introduce Parameter Object processor loads {@link ChangeMethodSignatureParticipant}s registered for the * <code>IMethod</code> whose signature is changed. */ //$NON-NLS-1$ public static String INTRODUCE_PARAMETER_OBJECT_PROCESSOR = "org.eclipse.jdt.ui.introduceParameterObjectRefactoring"; }
Python
UTF-8
337
3.6875
4
[]
no_license
import sys import random def fibonacci(): # 生成器函数 - 斐波那契 for i in range(5): L1 = random.randint(1, 10) yield L1 f = fibonacci() # f 是一个迭代器,由生成器返回生成 while True: try: print(next(f),end = ' ') except StopIteration: sys.exit()
Markdown
UTF-8
1,316
2.609375
3
[ "CC-BY-4.0", "MIT", "CC-BY-3.0" ]
permissive
此條件會評估每個新的 Salesforce 潛在客戶的電子郵件地址] 的欄位。 如果電子郵件地址包含*amazon.com*,條件則結果為*True*。 1. 選取 [ **+ 新的步驟**。 ![Salesforce 條件圖像 1](./media/connectors-create-api-salesforce/condition-1.png) - 選取 [**新增條件**。 ![Salesforce 條件圖像 2](./media/connectors-create-api-salesforce/condition-2.png) - 選取 [**選擇一個值**。 ![Salesforce 條件圖像 3](./media/connectors-create-api-salesforce/condition-3.png) - 從潛在客戶的觸發程序中選取的*電子郵件*的 token。 ![Salesforce 條件圖像 4](./media/connectors-create-api-salesforce/condition-4.png) - 選取 [*包含*]。 ![Salesforce 條件圖像 5](./media/connectors-create-api-salesforce/condition-5.png) - 選取 [**選擇一個值**,底部的控制項。 ![Salesforce 條件圖像 6](./media/connectors-create-api-salesforce/condition-6.png) - 輸入*amazon.com*做為您想要評估的新的潛在客戶的電子郵件地址的值。 如果電子郵件地址包含*amazon.com*,則條件會評估為*True* ,邏輯應用程式中的其他步驟進行。 ![Salesforce 條件圖像 7](./media/connectors-create-api-salesforce/condition-7.png) - 儲存您的邏輯應用程式。
Java
UTF-8
2,292
2.125
2
[]
no_license
package com.coders.crud.kppay; import android.graphics.Bitmap; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.google.zxing.WriterException; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; public class AddItemActivity extends AppCompatActivity { public enum BarcodeFormat { /** Aztec 2D barcode format. */ AZTEC, /** CODABAR 1D format. */ CODABAR, /** Code 39 1D format. */ CODE_39, /** Code 93 1D format. */ CODE_93, /** Code 128 1D format. */ CODE_128, /** Data Matrix 2D barcode format. */ DATA_MATRIX, /** EAN-8 1D format. */ EAN_8, /** EAN-13 1D format. */ EAN_13, /** ITF (Interleaved Two of Five) 1D format. */ ITF, /** MaxiCode 2D barcode format. */ MAXICODE, /** PDF417 format. */ PDF_417, /** QR Code 2D barcode format. */ QR_CODE, /** RSS 14 */ RSS_14, /** RSS EXPANDED */ RSS_EXPANDED, /** UPC-A 1D format. */ UPC_A, /** UPC-E 1D format. */ UPC_E, /** UPC/EAN extension format. Not a stand-alone format. */ UPC_EAN_EXTENSION } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_item); } public void generateRQCode(String contents) { QRCodeWriter qrCodeWriter = new QRCodeWriter(); /* try { Bitmap bitmap = toBitmap(qrCodeWriter.encode(contents, BarcodeFormat.QR_CODE, 100, 100)); } catch (WriterException e) { e.printStackTrace(); } */ } public static Bitmap toBitmap(BitMatrix matrix) { int height = matrix.getHeight(); int width = matrix.getWidth(); Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { bmp.setPixel(x, y, matrix.get(x, y) ? Color.BLACK : Color.WHITE); } } return bmp; } }
Rust
UTF-8
7,930
2.796875
3
[ "MIT" ]
permissive
use std::io::Read; use rayon::prelude::*; pub const KEY_LENGTH_IN_BYTES: usize = 10; type RoundKeys = [u64; super::NUM_ROUNDS + 1]; #[derive(Clone, Copy)] pub struct Key { bytes: [u8; KEY_LENGTH_IN_BYTES], } #[derive(Clone, Copy)] struct KeyRegister { a: u64, b: u64, } impl Key { pub fn new(bytes: &[u8]) -> Key { let mut b = [0u8; KEY_LENGTH_IN_BYTES]; bytes.take(KEY_LENGTH_IN_BYTES as u64).read(&mut b).unwrap(); Key { bytes: b } } } impl KeyRegister { fn rotate(&mut self) { let w = self.a & 0b1111111111111111111111111111111111111111111110000000000000000000; let x = self.a & 0b0000000000000000000000000000000000000000000001111111111111111000; let y = self.a & 0b0000000000000000000000000000000000000000000000000000000000000111; let z = self.b & 0b1111111111111111000000000000000000000000000000000000000000000000; let a = (y << 61) + (z >> 3) + (w >> 19); let b = x << 45; self.a = a; self.b = b; } fn update2(&mut self) { let w = (self.a >> 60) & 0xf; let x = super::S[w as usize]; let y = (x as u64) << 60; let z = self.a & 0x0fffffffffffffff; let a = y + z; let b = self.b; self.a = a; self.b = b; } fn update3(&mut self, round_counter: u64) { let w = (self.a & 0xf) << 1; let x = (self.b >> 63) & 1; let y = w + x; let z = y ^ round_counter; let p = (z & 0b11110) >> 1; let q = (z & 0b00001) << 63; let r = self.a & 0xfffffffffffffff0; let s = self.b & 0x7fffffffffffffff; let a = p + r; let b = q + s; self.a = a; self.b = b; } fn update(&mut self, round_counter: usize) { self.rotate(); self.update2(); self.update3(round_counter as u64); } } fn generate_round_keys(key: Key) -> [u64; super::NUM_ROUNDS + 1] { let mut round_keys = [0u64; super::NUM_ROUNDS + 1]; let mut key_register = KeyRegister::from(key); for i in 0..super::NUM_ROUNDS { round_keys[i] = key_register.a; key_register.update(i + 1); } round_keys[super::NUM_ROUNDS] = key_register.a; round_keys } impl From<Key> for KeyRegister { fn from(key: Key) -> Self { let (mut a, mut b) = (0u64, 0u64); for (i, x) in key.bytes.iter().enumerate() { let byte = *x as u64; if i < 8 { let shift = 56 - i * 8; a |= byte << shift; } else { let shift = 120 - i * 8; b |= byte << shift; } } KeyRegister { a, b } } } fn decrypt(state: u64, round_keys: &RoundKeys) -> u64 { let mut state = state; state = super::add_round_key(state, round_keys[super::NUM_ROUNDS]); for i in (0..super::NUM_ROUNDS).rev() { state = super::inv_p_layer(state); state = super::inv_s_box_layer(state); state = super::add_round_key(state, round_keys[i]); } state } fn encrypt(state: u64, round_keys: &RoundKeys) -> u64 { let mut state = state; for i in 0..super::NUM_ROUNDS { state = super::add_round_key(state, round_keys[i]); state = super::s_box_layer(state); state = super::p_layer(state); } state = super::add_round_key(state, round_keys[super::NUM_ROUNDS]); state } pub fn ecb_encrypt(data: &[u8], key: Key) -> Vec<u8> { let round_keys = generate_round_keys(key); let blocks: Vec<[u8; 8]> = data.chunks(super::BLOCK_SIZE_IN_BYTES) .map(|bytes| super::bytes_to_state(bytes)) .map(|state| encrypt(state, &round_keys)) .map(|state| super::state_to_bytes(state)) .collect(); let num_blocks = blocks.len() * super::BLOCK_SIZE_IN_BYTES; let mut encrypted: Vec<u8> = Vec::with_capacity(num_blocks); for block in blocks.iter() { encrypted.extend(block.iter()); } encrypted } pub fn ecb_decrypt(data: &[u8], key: Key) -> Vec<u8> { let round_keys = generate_round_keys(key); let blocks: Vec<[u8; 8]> = data.chunks(super::BLOCK_SIZE_IN_BYTES) .map(|bytes| super::bytes_to_state(bytes)) .map(|state| decrypt(state, &round_keys)) .map(|state| super::state_to_bytes(state)) .collect(); let num_blocks = blocks.len() * super::BLOCK_SIZE_IN_BYTES; let mut decrypted: Vec<u8> = Vec::with_capacity(num_blocks); for block in blocks.iter() { decrypted.extend(block.iter()); } decrypted } pub fn par_ecb_encrypt(data: &[u8], key: Key) -> Vec<u8> { let round_keys = generate_round_keys(key); let blocks: Vec<[u8; 8]> = data.par_chunks(super::BLOCK_SIZE_IN_BYTES) .map(|bytes| super::bytes_to_state(bytes)) .map(|state| encrypt(state, &round_keys)) .map(|state| super::state_to_bytes(state)) .collect(); let num_blocks = blocks.len() * super::BLOCK_SIZE_IN_BYTES; let mut encrypted: Vec<u8> = Vec::with_capacity(num_blocks); for block in blocks.iter() { encrypted.extend(block.iter()); } encrypted } pub fn par_ecb_decrypt(data: &[u8], key: Key) -> Vec<u8> { let round_keys = generate_round_keys(key); let blocks: Vec<[u8; 8]> = data.par_chunks(super::BLOCK_SIZE_IN_BYTES) .map(|bytes| super::bytes_to_state(bytes)) .map(|state| decrypt(state, &round_keys)) .map(|state| super::state_to_bytes(state)) .collect(); let num_blocks = blocks.len() * super::BLOCK_SIZE_IN_BYTES; let mut encrypted: Vec<u8> = Vec::with_capacity(num_blocks); for block in blocks.iter() { encrypted.extend(block.iter()); } encrypted } pub fn encrypt_block(data: &[u8], key: Key) -> [u8; super::BLOCK_SIZE_IN_BYTES] { let state = super::bytes_to_state(data); let round_keys = generate_round_keys(key); let encrypted = encrypt(state, &round_keys); super::state_to_bytes(encrypted) } pub fn decrypt_block(data: &[u8], key: Key) -> [u8; super::BLOCK_SIZE_IN_BYTES] { let state = super::bytes_to_state(data); let round_keys = generate_round_keys(key); let decrypted = decrypt(state, &round_keys); super::state_to_bytes(decrypted) } #[cfg(test)] mod tests { use super::*; #[test] fn test_key_register_from_key1() { let key = Key::new(&[0, 0, 0, 0, 0, 1]); let key_register = KeyRegister::from(key); assert_eq!(key_register.a, 1u64 << 16); assert_eq!(key_register.b, 0u64); } #[test] fn test_key_register_from_key2() { let key = Key::new(&[0, 0, 0, 0, 0, 0, 0, 1, 0, 0]); let key_register = KeyRegister::from(key); assert_eq!(key_register.a, 1u64); assert_eq!(key_register.b, 0u64); } #[test] fn test_key_register_from_key3() { let key = Key::new(&[0, 0, 0, 0, 0, 0, 0, 1, 0, 1]); let key_register = KeyRegister::from(key); assert_eq!(key_register.a, 1u64); assert_eq!(key_register.b, 1u64 << 48); } #[test] fn test_key_register_from_key4() { let key = Key::new(&[0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1]); let key_register = KeyRegister::from(key); assert_eq!(key_register.a, 1u64); assert_eq!(key_register.b, 1u64 << 48); } #[test] fn test_key_register_rotate() { let mut key_register = KeyRegister { a: 0b1100, b: 0 }; key_register.rotate(); let a: u64 = 1 << 63; let b: u64 = 1 << 48; assert_eq!(a, key_register.a); assert_eq!(b, key_register.b); } #[test] fn test_key_register_update1() { let mut key_register = KeyRegister { a: 0, b: 0 }; key_register.update(1); let a: u64 = 0b11 << 62; let b: u64 = 1 << 63; assert_eq!(a, key_register.a); assert_eq!(b, key_register.b); } }
C#
UTF-8
2,847
2.5625
3
[]
no_license
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace RestAPIDemo.Controllers { public class ChangeTableController : ApiController { // GET: api/ChangeTable public string Get(string token, int fromTableID, int toTableID) { return ChangeTable(token, fromTableID, toTableID); } // POST: api/ChangeTable public string Post([FromBody]string token, [FromBody]int fromTableID, [FromBody]int toTableID) { return ChangeTable(token, fromTableID, toTableID); } private static string ChangeTable(string token, int fromTableID, int toTableID) { SecurityFunction sf = new SecurityFunction(); if (sf.checkToken(token)) //login success { //check if destination table is not in use SQL sql = new SQL(); SqlCommand cmd = new SqlCommand("select * from dbo.TableTbl where id=@tableID"); cmd.Parameters.AddWithValue("@tableID", toTableID); DataTable dt = sql.executeSQLQuery(cmd); if (dt.Rows.Count == 0) //no data { return "Destination table does not exists"; } DataRow dr = dt.Rows[0]; if (bool.Parse(dr["flag"].ToString())) //true, has client inside { return "Destination table in use"; } //update current table to empty cmd = new SqlCommand("update dbo.TableTbl set flag=0 where id=@tableID"); cmd.Parameters.AddWithValue("@tableID", fromTableID); sql.executeSQL(cmd); //update destination table to in use cmd = new SqlCommand("update dbo.TableTbl set flag=1 where id=@tableID"); cmd.Parameters.AddWithValue("@tableID", toTableID); sql.executeSQL(cmd); //get Orderid from fromTableID cmd = new SqlCommand("SELECT id FROM dbo.OrderTbl where tableID=@tableID order by id desc"); cmd.Parameters.AddWithValue("@tableID", fromTableID); dt = sql.executeSQLQuery(cmd); int orderid = int.Parse(dt.Rows[0][0].ToString()); //update tableid in orderTbl cmd = new SqlCommand("update dbo.OrderTbl set tableID=@tableID where id=@id"); cmd.Parameters.AddWithValue("@tableID", toTableID); cmd.Parameters.AddWithValue("@id", orderid); sql.executeSQL(cmd); return "true"; } return "Login Session Expired."; } } }
C
UTF-8
719
3.328125
3
[]
no_license
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <string.h> void reverse(char* str, int k) { int i = 0; char tmp; for (i = 0; i < k / 2; i++) { tmp = *(str + i); *(str + i) = *(str + k - 1 - i); *(str + k - 1 - i) = tmp; } } void left_move(char *str, int k) { reverse(str, k); reverse(str + k, strlen(str) - k); reverse(str, strlen(str)); } int is_left_move(char *arr, const char *p) { int ret; ret = strlen(arr); while (ret) { left_move(arr, 1); ret--; if (strcmp(arr, p) == 0) return 1; } return 0; } int main() { char* p = "AABCD"; char arr[20] = "BCDA"; int ret; ret = is_left_move(arr, p); printf("%d\n", ret); system("pause"); return 0; }
Java
UTF-8
967
2.3125
2
[]
no_license
package com.gcox.fansmeet.customview; import android.app.Activity; import android.content.Context; import android.util.AttributeSet; import android.view.KeyEvent; import android.widget.EditText; /** * Created by User on 4/4/2016. */ public class EditTextBackPress extends EditText { Context context; private static Activity mActivity; public static void sethActivity(Activity searchActivity) { mActivity = searchActivity; } public EditTextBackPress(Context context, AttributeSet attrs) { super(context, attrs); this.context = context; } @Override public boolean onKeyPreIme(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { // User has pressed Back key. So hide the keyboard if (mActivity != null && !mActivity.isFinishing()) { mActivity.onBackPressed(); } } return super.dispatchKeyEvent(event); } }
Java
UTF-8
3,307
2.203125
2
[]
no_license
package pageObjects.hw6; import com.codeborne.selenide.ElementsCollection; import com.codeborne.selenide.SelenideElement; import enums.ServiceMenu; import enums.UserTable; import org.openqa.selenium.support.FindBy; import java.util.List; import static com.codeborne.selenide.Condition.*; import static com.codeborne.selenide.Selenide.page; import static com.codeborne.selenide.Selenide.title; import static enums.UserTable.getUserByName; import static org.testng.Assert.assertEquals; public class Hw6UserTablePage { public Hw6UserTablePage() { page(this); } @FindBy(css = "select") private ElementsCollection dropdowns; @FindBy(css = "td [href]") private ElementsCollection names; @FindBy(css = "td img") private ElementsCollection images; @FindBy(css = ".user-descr") private ElementsCollection descriptions; @FindBy(css = "th") private ElementsCollection tableColumns; @FindBy(css = "[type='checkbox']") private ElementsCollection checkboxes; @FindBy(css = "tr>td:nth-of-type(4n-3)") private ElementsCollection numbers; @FindBy(css = ".logs li") private ElementsCollection logs; @FindBy(css = "tr:nth-of-type(2) option") private ElementsCollection dropdownOptions; public void checkTitle(ServiceMenu userTablePageTitle) { assertEquals(title(), userTablePageTitle.toString()); } public void checkDropdowns() { for (SelenideElement dropdown : dropdowns) { dropdown.shouldBe(visible); } } public void checkNames() { for (UserTable user : UserTable.values()) { names.find(text(user.getName())).shouldBe(visible); } } public void checkImages() { for (SelenideElement image : images) { image.shouldBe(visible); } } public void checkDescriptionsTexts() { for (SelenideElement description : descriptions) { description.shouldBe(visible); } } public void checkCheckboxes() { for (SelenideElement checkbox : checkboxes) { checkbox.shouldBe(visible); } } public void checkUserTable(List<String> values) { for (int i = 0; i < 3; i++) { tableColumns.find(text(values.get(i))).should(visible); } for (int i = 3; i < values.size(); i++) { if (i % 3 == 0) numbers.find(text(values.get(i))).shouldBe(visible); if (i % 3 == 1) names.find(text(values.get(i))).shouldBe(visible); if (i % 3 == 2) descriptions.find(text(values.get(i))).shouldBe(visible); } } public void clickVIPCheckboxByName(String... names) { for (String name : names) { checkboxes.find(id(getUserByName(name).getCheckboxId())).click(); } } public void checkVIPCheckboxStatus(String status) { logs.find(text(status)).shouldBe(visible); } public void clickDropdownByName(String... names) { for (String name : names) { checkboxes.get(getUserByName(name).getNumber() - 1).click(); } } public void checkDropdownOptions(List<String> userTypes) { for (String userType : userTypes) { dropdownOptions.find(text(userType)).should(exist); } } }
Python
UTF-8
1,913
2.703125
3
[]
no_license
import cv2 from tensorflow.keras.models import load_model from tensorflow.keras.applications.mobilenet_v2 import preprocess_input from tensorflow.keras.preprocessing.image import img_to_array import numpy as np # Load the cascade face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') # Load the mask detection model mask_model = load_model('mask_detector_model') # To capture video from webcam. #cap = cv2.VideoCapture(0) # To use a video file as input cap = cv2.VideoCapture('film.mov') while True: # Read the frame _, img = cap.read() # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detect the faces faces = face_cascade.detectMultiScale(gray, 1.1, 4) # Draw the rectangle around each face for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) # Classify if the face contains a mask or not mask_im = img.copy() #mask_im = img_to_array(mask_im) #mask_im = cv2.cvtColor(mask_im, cv2.COLOR_BGR2RGB) mask_im = cv2.resize(mask_im, (224, 224)) mask_im = preprocess_input(mask_im) mask_im = np.expand_dims(mask_im, axis=0) (mask, no_mask) = mask_model.predict(mask_im)[0] # determine the class label and color we'll use to draw # the bounding box and text label = "Mask" if mask > no_mask else "No Mask" color = (0, 255, 0) if label == "Mask" else (0, 0, 255) # include the probability in the label label = "{}: {:.2f}%".format(label, max(mask, no_mask) * 100) img = cv2.putText(img=img, text=label, org=(x, y), color=color, fontFace=0, fontScale=1, thickness=2) # Display cv2.imshow('img', img) # Stop if escape key is pressed k = cv2.waitKey(30) & 0xff if k == 27: break # Release the VideoCapture object cap.release()
Go
UTF-8
2,849
3
3
[]
no_license
package main import ( "context" "errors" "fmt" "net/http" "os" "os/signal" "syscall" "time" "golang.org/x/sync/errgroup" ) // LISTENS service const LISTENS string = "0.0.0.0:8080" // LISTENM manage const LISTENM string = "0.0.0.0:8081" // IndexHandler index type IndexHandler struct { name string } func (h *IndexHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(200) _, _ = w.Write([]byte(h.name)) } // CloseHandler close chan type CloseHandler struct { CloseChan chan error } func (h *CloseHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { w.Header().Set("Content-Type", "text/plain; charset=utf-8") w.WriteHeader(200) _, _ = w.Write([]byte("closing")) select { default: h.CloseChan <- errors.New("api shutdown") case <-h.CloseChan: } } func startServer(stopCh chan<- struct{}) { mux1 := http.NewServeMux() mux1.Handle("/", &IndexHandler{name: "hello golang, service is running.\n"}) closeHandler1 := &CloseHandler{} mux1.Handle("/close", closeHandler1) s1Ch := make(chan error, 1) mux2 := http.NewServeMux() mux2.Handle("/", &IndexHandler{name: "hello golang, manage is running.\n"}) closeHandler2 := &CloseHandler{} mux2.Handle("/close", closeHandler1) s2Ch := make(chan error, 1) ch := make(chan os.Signal, 10) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP) ctx := context.Background() group, _ := errgroup.WithContext(ctx) server1 := &http.Server{Addr: LISTENS, Handler: mux1} closeHandler1.CloseChan = s1Ch server2 := &http.Server{Addr: LISTENM, Handler: mux2} closeHandler2.CloseChan = s2Ch group.Go(func() error { select { case <-ch: fmt.Println("receive close signal!") case err := <-s1Ch: fmt.Printf("receive service close! %+v\n", err) case err := <-s2Ch: fmt.Printf("receive manage close! %+v\n", err) } signal.Stop(ch) close(s1Ch) close(s2Ch) ctx, cancel := context.WithTimeout(context.Background(), time.Second*5) defer cancel() err1 := server1.Shutdown(ctx) fmt.Printf("service close %+v \n", err1) ctx, cancel = context.WithTimeout(context.Background(), time.Second*5) defer cancel() err2 := server2.Shutdown(ctx) fmt.Printf("manage close %+v \n", err2) return nil }) group.Go(func() error { err := server1.ListenAndServe() select { default: s1Ch <- err case <-s1Ch: } fmt.Printf("service closed %+v \n", err) return nil }) group.Go(func() error { err := server2.ListenAndServe() select { default: s1Ch <- err case <-s1Ch: } fmt.Printf("manage closed %+v \n", err) return nil }) err := group.Wait() stopCh <- struct{}{} fmt.Printf("group err %+v \n", err) } func main() { stopCh := make(chan struct{}, 1) go startServer(stopCh) <-stopCh close(stopCh) }
Java
UHC
2,852
1.757813
2
[]
no_license
/*************************************************************************************************** * ϸ : * : * ۼ : * ۼ : ***************************************************************************************************/ /*************************************************************************************************** * : * : * : * : ***************************************************************************************************/ package chosun.ciis.mt.etccar.wb; import java.rmi.RemoteException; import java.util.StringTokenizer; import javax.ejb.CreateException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import chosun.ciis.co.base.wb.BaseWB; import somo.framework.db.BaseDataSet; import somo.framework.expt.AppException; import somo.framework.expt.SysException; import somo.framework.lib.JNDIManager; import somo.framework.db.DBManager; import somo.framework.log.LogManager; import somo.framework.util.Util; import chosun.ciis.mt.etccar.dm.*; import chosun.ciis.mt.etccar.ds.*; /** * */ public class MT_ETCCAR_7000WB extends BaseWB { /** * Ƽڵó row */ public final String ROW_SEPARATOR = "|"; /** * Ƽڵó column */ public final String COL_SEPARATOR = "#"; // ܰ ȸ public void mt_etccar_7001_l(HttpServletRequest req, HttpServletResponse res) throws AppException { MT_ETCCAR_7001_LDataSet ds = null; MT_ETCCAR_7001_LDM dm = new MT_ETCCAR_7001_LDM(); dm.cmpy_cd = Util.getSessionParameterValue(req,"cmpycd",true); dm.print(); DBManager manager = new DBManager("MISMAT"); ds = (MT_ETCCAR_7001_LDataSet)manager.executeCall(dm); if(!ds.getErrcode().equals("")) { throw new AppException(ds.getErrcode(), ds.getErrmsg()); } req.setAttribute("ds", ds); } public void mt_etccar_7002_a(HttpServletRequest req, HttpServletResponse res) throws AppException { MT_ETCCAR_7002_ADataSet ds = null; MT_ETCCAR_7002_ADM dm = new MT_ETCCAR_7002_ADM(); dm.mode = Util.checkString(req.getParameter("mode")); dm.cmpy_cd = Util.getSessionParameterValue(req, "cmpycd", true); dm.close_yymm = Util.checkString(req.getParameter("close_yymm")); dm.incmg_pers_ipadd = req.getRemoteAddr(); dm.incmg_pers = Util.getSessionParameterValue(req, "emp_no", true); DBManager manager = new DBManager("MISMAT"); ds = (MT_ETCCAR_7002_ADataSet)manager.executeCall(dm); if(!ds.getErrcode().equals("")) { throw new AppException(ds.getErrcode(), ds.getErrmsg()); } req.setAttribute("ds", ds); } }
Go
UTF-8
136
2.96875
3
[]
no_license
package main import ( "fmt" t "time" ) // Main function func main() { fmt.Println("Hello world") fmt.Println("Time: ", t.Now()) }
Swift
UTF-8
863
3.296875
3
[]
no_license
// // MovieViewModel.swift // MovieStore // // Created by Anton Filipović on 15/05/2018. // Copyright © 2018 Anton Filipović. All rights reserved. // import Foundation class SingleMovieViewModel { private let movie: Movie init (movie: Movie){ self.movie = movie } var title: String{ return movie.title! } var year: String{ return movie.year! } var genre: String{ return movie.genre! } var directorName: String{ return movie.directorName! } var directorSurname: String{ return movie.directorSurname! } var photoURL: URL?{ return URL(string: movie.photoURL!) } var summary: String{ get { return movie.summary! } set(text) { movie.summary = text } } }
Java
UTF-8
3,275
2.078125
2
[ "BSD-3-Clause", "EPL-1.0", "OFL-1.1", "MIT", "Apache-2.0", "BSD-2-Clause" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.apache.zeppelin.notebook.repo; import static org.junit.jupiter.api.Assertions.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.stream.Stream; class ToPathArrayTest { private MongoNotebookRepo repo = new MongoNotebookRepo(); private static Stream<Arguments> data() { return Stream.of( Arguments.of(null, true, null), Arguments.of(null, false, null), Arguments.of("", true, null), Arguments.of("", false, null), Arguments.of("/", true, new String[0]), Arguments.of("/", false, new String[0]), Arguments.of("/abc", true, new String[] { "abc" }), Arguments.of("/abc/", true, new String[] { "abc" }), Arguments.of("/a/b/c", true, new String[] { "a", "b", "c" }), Arguments.of("/a/b//c/", true, new String[] { "a", "b", "c" }), Arguments.of("/abc", false, new String[] {}), Arguments.of("/abc/", false, new String[] {}), Arguments.of("/a/b/c", false, new String[] { "a", "b" }), Arguments.of("/a/b//c/", false, new String[] { "a", "b" }), Arguments.of("abc", true, new String[] { "abc" }), Arguments.of("abc/", true, new String[] { "abc" }), Arguments.of("a/b/c", true, new String[] { "a", "b", "c" }), Arguments.of("a/b//c/", true, new String[] { "a", "b", "c" }), Arguments.of("abc", false, new String[] {}), Arguments.of("abc/", false, new String[] {}), Arguments.of("a/b/c", false, new String[] { "a", "b" }), Arguments.of("a/b//c/", false, new String[] { "a", "b" })); } @ParameterizedTest @MethodSource("data") void runTest(String pathStr, boolean includeLast, String[] expactPathArray) { if (expactPathArray == null) { runForThrow(pathStr, includeLast, expactPathArray); } else { runNormally(pathStr, includeLast, expactPathArray); } } private void runForThrow(String pathStr, boolean includeLast, String[] expactPathArray) { assertThrows(NullPointerException.class, () -> { runNormally(pathStr, includeLast, expactPathArray); }); } private void runNormally(String pathStr, boolean includeLast, String[] expactPathArray) { String[] pathArray = repo.toPathArray(pathStr, includeLast); assertArrayEquals(expactPathArray, pathArray); } }
Java
UTF-8
1,807
2.28125
2
[]
no_license
package com.buecoin01.controller; import com.buecoin01.Repositories.BlockRepository; import com.buecoin01.model.Block; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Optional; @RestController @CrossOrigin(origins = {"http://localhost:8100", "http://localhost:8080"}) public class BlockController { @Autowired private BlockRepository blockRepository; @RequestMapping(value = "/block/{id}", method = RequestMethod.GET) public ResponseEntity get(@PathVariable Long id) { Optional<Block> block = blockRepository.findById( id ); return new ResponseEntity <>( block, HttpStatus.OK ); } @RequestMapping(value = "/blocks", method = RequestMethod.GET) public ResponseEntity <Iterable <Block>> getAllUsers() { Iterable <Block> allBlocks = blockRepository.findAll(); return new ResponseEntity <>( allBlocks, HttpStatus.OK ); } @RequestMapping(path = "/addBlock", method = RequestMethod.POST) public ResponseEntity <?> create(@RequestBody Block block) { blockRepository.save(block); return new ResponseEntity <>( block, HttpStatus.CREATED ); } @RequestMapping(path = "/deleteBlock", method = RequestMethod.DELETE) public ResponseEntity <Block> deleteBlock(@RequestBody Block block) { blockRepository.delete(block ); return new ResponseEntity <>( HttpStatus.OK ); } @RequestMapping(path = "/updateBlock", method = RequestMethod.PUT) public ResponseEntity <Block> updateBlock(@RequestBody Block block) { blockRepository.save(block); return new ResponseEntity <>( HttpStatus.OK ); } }
Java
UTF-8
2,183
2.5
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015 CIRDLES. * * 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.cirdles.topsoil.app.browse; import java.awt.Desktop; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import javax.annotation.Nullable; import javax.inject.Inject; import org.cirdles.topsoil.app.util.Alerter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author Emily */ public class DesktopWebBrowser implements WebBrowser { private static final Logger LOGGER = LoggerFactory.getLogger(DesktopWebBrowser.class); private final Desktop desktop; private final Alerter alerter; @Inject public DesktopWebBrowser(@Nullable Desktop desktop, Alerter alerter) { this.desktop = desktop; this.alerter = alerter; } @Override public void browse(String uriString) { try { URI uri = new URI(uriString); checkDesktopAndBrowse(uri); } catch (URISyntaxException ex) { LOGGER.error(null, ex); throw new RuntimeException(ex); } } void checkDesktopAndBrowse(URI uri) { if (desktop != null) { if (desktop.isSupported(Desktop.Action.BROWSE)) { browse(uri); } else { alerter.alert("Browsing not supported"); } } else { alerter.alert("Desktop not supported"); } } void browse(URI uri) { try { desktop.browse(uri); } catch (IOException ex) { LOGGER.error(null, ex); alerter.alert("Browser could not be opened."); } } }
Java
UTF-8
31,677
2.25
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package btl_giang; import java.sql.ResultSet; import java.sql.Statement; import java.util.Vector; import javax.swing.table.DefaultTableModel; import java.sql.PreparedStatement; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * * @author TruongGiang */ public class QuanLyGiaoVienForm extends javax.swing.JFrame { public static ResultSet rs =null; public Statement st=null; Connect cn =new Connect(); /** * Creates new form QuanLyGiaoVienForm */ public QuanLyGiaoVienForm() { initComponents(); cn.getConnect(); xoaTrang(); textCanhBao.setEnabled(false); loadData(); } private void xoaTrang(){ txtDC.setText(""); txtHoTen.setText(""); txtMK.setText(""); txtMaBHYT.setText(""); txtMaGV.setText(""); txtSDT.setText(""); txtSoCMND.setText(""); txtQuocTich.setText(""); } private void loadData(){ cn.getConnect(); jTable1.removeAll(); String []noiDung={"Mã Giáo Viên","Họ Tên","Quốc Tịch","Xã","Quận","Tỉnh","Số CMND","Số Điện Thoại","Mã BHYT","Mật Khẩu"}; DefaultTableModel table =new DefaultTableModel(noiDung,0); try{ st=cn.con.createStatement(); rs=st.executeQuery("select MaGiaoVien,HoTen,QuocTich,Xa,Quan,Tinh,SoCMND,SoDienThoai,MaBHYT,MatKhau from GVIEN "); while(rs.next()){ String []noiDung1={rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4) ,rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8) ,rs.getString(9),rs.getString(10)}; table.addRow(noiDung1); } rs.close(); }catch(Exception e){ System.out.println("Lỗi là : "+e.getMessage()); } jTable1.setModel(table); } private void them(){ cn.getConnect(); int d=0; try{ st=cn.con.createStatement(); rs=st.executeQuery("select MaGiaoVien from GVIEN "); while(rs.next()){ if(txtMaGV.getText().equals(rs.getString("MaGiaoVien"))) d++; } }catch(Exception e){} if(d!=0){ JOptionPane.showMessageDialog(this, "Mã Giáo Viên bị trùng"); }else{ if(!txtMaGV.getText().trim().equals("")&&!txtMK.getText().trim().equals("")){ String []diaChi = txtDC.getText().split(","); int dem=0; for(int i=0;i<txtDC.getText().length();i++) if(txtDC.getText().charAt(i)==',') dem++; String sql = "insert into GVIEN (MaGiaoVien,Hoten,QuocTich,Xa,Quan,Tinh,SoCMND,SoDienThoai,MaBHYT,MatKhau)" + " values (?,?,?,?,?,?,?,?,?,?)"; try{ PreparedStatement pre = cn.con.prepareStatement(sql); pre.setString(1, txtMaGV.getText()); pre.setString(2, txtHoTen.getText()); pre.setString(3, txtQuocTich.getText()); if(dem>=2){ pre.setString(4, diaChi[0]); pre.setString(5, diaChi[1]); pre.setString(6, diaChi[2]); }else{ if(dem==1){ pre.setString(4, diaChi[0]); pre.setString(5, diaChi[1]); pre.setString(6, ""); }else { pre.setString(4, txtDC.getText()); pre.setString(5, ""); pre.setString(6, ""); } } pre.setString(7, txtSoCMND.getText()); pre.setString(8, txtSDT.getText()); pre.setString(9, txtMaBHYT.getText()); pre.setString(10, txtMK.getText()); pre.execute(); JOptionPane.showMessageDialog(this, "Bạn đã thêm thành công giáo viên chủ nhiệm mới ( "+txtMaGV.getText()+")"); }catch(Exception e){ System.out.println("Lỗi là : "+e.getMessage()); } }else{ JOptionPane.showMessageDialog(this, "Cần đủ mã giáo viên và mật khẩu", "CẢNH BÁO", JOptionPane.ERROR_MESSAGE); } } loadData(); } private void xoa(){ cn.getConnect(); if(txtMaGV.getText().trim().equals("")){ JOptionPane.showMessageDialog(this, "Không có Mã Giáo Viên để xóa", "Cảnh Báo", JOptionPane.ERROR_MESSAGE); return; } int d=0; try{ st=cn.con.createStatement(); rs=st.executeQuery("select MaGiaoVien from GVIEN "); while(rs.next()){ if(txtMaGV.getText().equals(rs.getString("MaGiaoVien"))) d++; } }catch(Exception e){} if(d==0){ JOptionPane.showMessageDialog(this, "Không tồn tại Mã Giáo Viên này"); }else{ int select=JOptionPane.showConfirmDialog(this, "Bạn chắc muốn xóa chứ !!!", "Thông Báo", JOptionPane.YES_NO_OPTION); if(select==JOptionPane.YES_OPTION){ String sql ="delete from GVIEN where MaGiaoVien=?"; try{ PreparedStatement pre = cn.con.prepareStatement(sql); pre.setString(1, txtMaGV.getText()); pre.execute(); JOptionPane.showMessageDialog(this, "xóa thành công"); }catch(Exception e){ System.out.println("Lỗi là : "+e.getMessage()); } } } loadData(); } private void sua(){ cn.getConnect(); if(txtMaGV.getText().trim().equals("")){ JOptionPane.showMessageDialog(this, "Mã Giáo Viên Trống", "CẢNH BÁO", JOptionPane.ERROR_MESSAGE); return; } int d=0; try{ st=cn.con.createStatement(); rs=st.executeQuery("select MaGiaoVien from GVIEN "); while(rs.next()){ if(txtMaGV.getText().equals(rs.getString("MaGiaoVien"))) d++; } }catch(Exception e){} if(d==0){ JOptionPane.showMessageDialog(this, "Không tồn tại Mã Giáo Viên này"); }else{ String []diaChi = txtDC.getText().split(","); int dem=0; for(int i=0;i<txtDC.getText().length();i++) if(txtDC.getText().charAt(i)==',') dem++; String sql = "update GVIEN set HoTen=?,QuocTich=?,Xa=?,Quan=?,Tinh=?,SoCMND=?,SoDienThoai=?,MaBHYT=?,MatKhau=? where MaGiaoVien=?"; try{ PreparedStatement pre = cn.con.prepareStatement(sql); pre.setString(1, txtHoTen.getText()); pre.setString(2, txtQuocTich.getText()); if(dem>=2){ pre.setString(3, diaChi[0]); pre.setString(4, diaChi[1]); pre.setString(5, diaChi[2]); }else{ if(dem==1){ pre.setString(3, diaChi[0]); pre.setString(4, diaChi[1]); pre.setString(5, ""); }else { pre.setString(3, txtDC.getText()); pre.setString(4, ""); pre.setString(5, ""); } } pre.setString(6, txtSoCMND.getText()); pre.setString(7, txtSDT.getText()); pre.setString(8, txtMaBHYT.getText()); pre.setString(9, txtMK.getText()); pre.setString(10, txtMaGV.getText()); pre.executeUpdate(); JOptionPane.showMessageDialog(this, "Bạn đã Sửa thành công giáo viên chủ nhiệm mới ( "+txtMaGV.getText()+")"); }catch(Exception e){ System.out.println("Lỗi là : "+e.getMessage()); } } loadData(); } private void timKiem(){ cn.getConnect(); if(txtMaGV.getText().trim().equals("")){ JOptionPane.showMessageDialog(this, "Không có Mã Giáo viên để tìm kiếm"); return; }else{ int d=0; try{ st=cn.con.createStatement(); rs=st.executeQuery("select MaGiaoVien from GVIEN "); while(rs.next()){ if(txtMaGV.getText().equals(rs.getString("MaGiaoVien"))) d++; } }catch(Exception e){} if(d==0){ JOptionPane.showMessageDialog(this, "Không tồn tại mã giáo viên này"); return; }else{ jTable1.removeAll(); String []noiDung={"Mã Giáo Viên","Họ Tên","Quốc Tịch","Xã","Quận","Tỉnh","Số CMND","Số Điện Thoại","Mã BHYT","Mật Khẩu"}; DefaultTableModel table =new DefaultTableModel(noiDung,0); try { st=cn.con.createStatement(); rs=st.executeQuery("select MaGiaoVien,HoTen,QuocTich,Xa,Quan,Tinh,SoCMND,SoDienThoai,MaBHYT,MatKhau from GVIEN" + " where MaGiaoVien='"+txtMaGV.getText()+"'"); while(rs.next()){ String []noiDung1={rs.getString(1),rs.getString(2),rs.getString(3),rs.getString(4) ,rs.getString(5),rs.getString(6),rs.getString(7),rs.getString(8) ,rs.getString(9),rs.getString(10)}; table.addRow(noiDung1); } } catch (Exception e) { System.out.println("Lỗi là : "+e.getMessage()); } jTable1.setModel(table); } } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jLabel1 = new javax.swing.JLabel(); jButtonThem = new javax.swing.JButton(); jButtonSua = new javax.swing.JButton(); jButtonXoa = new javax.swing.JButton(); jButtonXoaTrang = new javax.swing.JButton(); jButtonThoat = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); txtMaGV = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); txtHoTen = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); txtDC = new javax.swing.JTextField(); jLabel5 = new javax.swing.JLabel(); txtSoCMND = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); txtMaBHYT = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); txtMK = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); txtSDT = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); txtQuocTich = new javax.swing.JTextField(); textCanhBao = new javax.swing.JLabel(); jButtonTimKiem = new javax.swing.JButton(); jButtonLoad = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null}, {null, null, null, null, null, null, null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4", "Title 5", "Title 6", "Title 7", "Title 8", "Title 9", "Title 10" } )); jTable1.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { jTable1MouseClicked(evt); } }); jScrollPane1.setViewportView(jTable1); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jLabel1.setText("QUẢN LÝ GIÁO VIÊN CHỦ NGHIỆM"); jButtonThem.setText("Thêm"); jButtonThem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonThemActionPerformed(evt); } }); jButtonSua.setText("Sửa"); jButtonSua.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonSuaActionPerformed(evt); } }); jButtonXoa.setText("Xóa"); jButtonXoa.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonXoaActionPerformed(evt); } }); jButtonXoaTrang.setText("Xóa trắng"); jButtonXoaTrang.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonXoaTrangActionPerformed(evt); } }); jButtonThoat.setText("Thoát"); jButtonThoat.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonThoatActionPerformed(evt); } }); jLabel2.setText("Mã Giáo Viên"); jLabel3.setText("Họ Tên"); jLabel4.setText("Địa Chỉ"); txtDC.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { txtDCMouseClicked(evt); } }); jLabel5.setText("Số CMND"); jLabel6.setText("Mã HBYT"); jLabel7.setText("Mật Khẩu"); jLabel8.setText("Số Điện Thoại"); txtSDT.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtSDTActionPerformed(evt); } }); jLabel9.setText("Quốc Tịch"); textCanhBao.setText("Nhập dạng xa,quan,tinh"); jButtonTimKiem.setText("Tìm Kiếm"); jButtonTimKiem.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonTimKiemActionPerformed(evt); } }); jButtonLoad.setText("Load"); jButtonLoad.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonLoadActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap(27, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel8) .addComponent(jLabel6)) .addGap(72, 72, 72) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtSDT, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE) .addComponent(txtMaBHYT)) .addGap(145, 145, 145)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(layout.createSequentialGroup() .addComponent(jLabel5) .addGap(93, 93, 93) .addComponent(txtSoCMND)) .addGroup(layout.createSequentialGroup() .addComponent(jLabel2) .addGap(78, 78, 78) .addComponent(txtMaGV, javax.swing.GroupLayout.PREFERRED_SIZE, 280, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(jLabel9)) .addGap(93, 93, 93) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtMK) .addComponent(txtQuocTich))) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel4)) .addGap(104, 104, 104) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(txtHoTen, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE) .addComponent(txtDC) .addComponent(textCanhBao, javax.swing.GroupLayout.PREFERRED_SIZE, 137, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButtonSua, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonThem, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonXoa, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jButtonThoat, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonXoaTrang, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButtonTimKiem, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jButtonLoad, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 73, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(73, 73, 73)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jLabel1) .addGap(158, 158, 158)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 770, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(23, 23, 23)))) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1) .addGap(15, 15, 15) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonThem) .addComponent(jLabel2) .addComponent(txtMaGV, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(txtHoTen, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(27, 27, 27) .addComponent(jButtonSua))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtDC, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addGap(3, 3, 3) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButtonXoa) .addComponent(textCanhBao)) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(3, 3, 3) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5) .addComponent(txtSoCMND, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(txtSDT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel8)) .addGap(19, 19, 19) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(txtMaBHYT, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(layout.createSequentialGroup() .addGap(30, 30, 30) .addComponent(jButtonXoaTrang) .addGap(28, 28, 28) .addComponent(jButtonTimKiem))) .addGap(16, 16, 16) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel7) .addComponent(txtMK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonLoad)) .addGap(32, 32, 32) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel9) .addComponent(txtQuocTich, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButtonThoat)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 30, Short.MAX_VALUE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void txtSDTActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSDTActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtSDTActionPerformed private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked // TODO add your handling code here: int select=jTable1.getSelectedRow(); txtMaGV.setText(jTable1.getValueAt(select, 0)+""); txtHoTen.setText(jTable1.getValueAt(select, 1)+""); txtQuocTich.setText(jTable1.getValueAt(select, 2)+""); txtDC.setText(jTable1.getValueAt(select, 3)+", "+jTable1.getValueAt(select, 4)+", "+jTable1.getValueAt(select, 5)); txtSoCMND.setText(jTable1.getValueAt(select, 6)+""); txtSDT.setText(jTable1.getValueAt(select, 7)+""); txtMaBHYT.setText(jTable1.getValueAt(select, 8)+""); txtMK.setText(jTable1.getValueAt(select, 9)+""); }//GEN-LAST:event_jTable1MouseClicked private void jButtonXoaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonXoaActionPerformed // TODO add your handling code here: xoa(); xoaTrang(); }//GEN-LAST:event_jButtonXoaActionPerformed private void jButtonSuaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSuaActionPerformed // TODO add your handling code here: sua(); }//GEN-LAST:event_jButtonSuaActionPerformed private void jButtonThemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonThemActionPerformed // TODO add your handling code here: them(); }//GEN-LAST:event_jButtonThemActionPerformed private void jButtonXoaTrangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonXoaTrangActionPerformed // TODO add your handling code here: xoaTrang(); }//GEN-LAST:event_jButtonXoaTrangActionPerformed private void jButtonThoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonThoatActionPerformed // TODO add your handling code here: new MenuAdsForm().setVisible(true); this.setVisible(false); }//GEN-LAST:event_jButtonThoatActionPerformed private void txtDCMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_txtDCMouseClicked // TODO add your handling code here: textCanhBao.setEnabled(true); }//GEN-LAST:event_txtDCMouseClicked private void jButtonLoadActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonLoadActionPerformed // TODO add your handling code here: loadData(); xoaTrang(); }//GEN-LAST:event_jButtonLoadActionPerformed private void jButtonTimKiemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonTimKiemActionPerformed // TODO add your handling code here: timKiem(); }//GEN-LAST:event_jButtonTimKiemActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(QuanLyGiaoVienForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(QuanLyGiaoVienForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(QuanLyGiaoVienForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(QuanLyGiaoVienForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new QuanLyGiaoVienForm().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButtonLoad; private javax.swing.JButton jButtonSua; private javax.swing.JButton jButtonThem; private javax.swing.JButton jButtonThoat; private javax.swing.JButton jButtonTimKiem; private javax.swing.JButton jButtonXoa; private javax.swing.JButton jButtonXoaTrang; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable jTable1; private javax.swing.JLabel textCanhBao; private javax.swing.JTextField txtDC; private javax.swing.JTextField txtHoTen; private javax.swing.JTextField txtMK; private javax.swing.JTextField txtMaBHYT; private javax.swing.JTextField txtMaGV; private javax.swing.JTextField txtQuocTich; private javax.swing.JTextField txtSDT; private javax.swing.JTextField txtSoCMND; // End of variables declaration//GEN-END:variables }
Java
UTF-8
632
2.203125
2
[]
no_license
package co.com.ceiba.domain.service.command.person; import co.com.ceiba.domain.dto.person.PersonDTO; import co.com.ceiba.domain.exception.TLException; import co.com.ceiba.domain.port.person.PersonDAO; import co.com.ceiba.domain.port.person.PersonRepository; public class UpdatePersonService { PersonRepository personRepository; PersonDAO personDao; public UpdatePersonService(PersonRepository personRepository,PersonDAO personDao) { this.personRepository = personRepository; this.personDao = personDao; } public PersonDTO execute(PersonDTO person) throws TLException { return personRepository.update(person); } }
Java
GB18030
417
3.171875
3
[]
no_license
package com.wjy.code; /** * ȡ쳲 * @author Administrator * */ public class Fibonacci { public static long fbnq(long n){ return _fbnq(n); } private static long _fbnq(long n){ if(n==1) return 1; if(n==0) return 1; else return _fbnq(n-1)+_fbnq(n-2); } public static void main(String[] args) { for (long i = 0; i < 15; i++) { System.out.println(fbnq(i)); } } }
C++
UTF-8
17,644
3.34375
3
[]
no_license
#include "driver_state.h" #include "common.h" #include <cstring> driver_state::driver_state() { } driver_state::~driver_state() { delete [] image_color; delete [] image_depth; } // This function should allocate and initialize the arrays that store color and // depth. This is not done during the constructor since the width and height // are not known when this class is constructed. void initialize_render(driver_state& state, int width, int height) { state.image_width = width; state.image_height = height; state.image_color = new pixel[width * height]; state.image_depth = new float[width * height]; for(size_t i = 0; i < width * height; i++) { state.image_color[i] = make_pixel(0,0,0); state.image_depth[i] = 1; } } // This function will be called to render the data that has been stored in this class. // Valid values of type are: // render_type::triangle - Each group of three vertices corresponds to a triangle. // render_type::indexed - Each group of three indices in index_data corresponds // to a triangle. These numbers are indices into vertex_data. // render_type::fan - The vertices are to be interpreted as a triangle fan. // render_type::strip - The vertices are to be interpreted as a triangle strip. void render(driver_state& state, render_type type) { switch(type) { case render_type::triangle: { const data_geometry* triangle_geometry[3]; data_geometry geometry_d[3]; data_vertex vertex_d[3]; //If the render is a triangle, the number of triangles should be //The number of verticies divided by 3. state.num_triangles = state.num_vertices / 3; int index = 0; //std::cout << state.num_triangles << std::endl; //For each triangle, copy each vertex by setting data_geometry data pointer //to the first entry of the vertex data, allowing the x,y coordinates to be //found for each vertex by looking at next location in memory. for(size_t triangle = 0; triangle < state.num_triangles; triangle++) { for(size_t i = 0; i < 3; i++) { //std::cout << *(state.vertex_data + index) << std::endl; vertex_d[i].data = state.vertex_data + index; geometry_d[i].data = vertex_d[i].data; //std::cout << *triangle_geometry[i].data << std::endl; //Fill gl_Position for the triangle geometry allowing it to be accessed while clipping state.vertex_shader(vertex_d[i], geometry_d[i], state.uniform_data); triangle_geometry[i] = &geometry_d[i]; //std::cout << triangle_geometry[i].gl_Position << std::endl; index += state.floats_per_vertex; } //rasterize_triangle(state, (const data_geometry**)&triangle_geometry); clip_triangle(state, triangle_geometry, 0); } break; } case render_type::indexed: { const data_geometry* triangle_geometry[3]; data_geometry geometry_d[3]; data_vertex vertex_d[3]; for(size_t index = 0; index < state.num_triangles * 3; index += 3) { for(size_t i = 0; i < 3; i++) { vertex_d[i].data = &state.vertex_data[state.index_data[index + i] * state.floats_per_vertex]; geometry_d[i].data = vertex_d[i].data; state.vertex_shader(vertex_d[i], geometry_d[i], state.uniform_data); triangle_geometry[i] = &geometry_d[i]; } clip_triangle(state, triangle_geometry, 0); } break; } case render_type::fan: { const data_geometry* triangle_geometry[3]; data_geometry geometry_d[3]; data_vertex vertex_d[3]; int temp = 0; for(size_t fan = 0; fan < state.num_vertices; fan++) { for(size_t i = 0; i < 3; i++) { if(i == 0) { temp = 0; } else { temp = fan + i; } vertex_d[i].data = &state.vertex_data[temp * state.floats_per_vertex]; geometry_d[i].data = vertex_d[i].data; state.vertex_shader(vertex_d[i], geometry_d[i], state.uniform_data); triangle_geometry[i] = &geometry_d[i]; } clip_triangle(state, triangle_geometry, 0); } break; } case render_type::strip: { const data_geometry* triangle_geometry[3]; data_geometry geometry_d[3]; data_vertex vertex_d[3]; for(size_t strip = 0; strip < state.num_vertices - 2; strip++) { for(size_t i = 0; i < 3; i++) { vertex_d[i].data = &state.vertex_data[(strip + i) * state.floats_per_vertex]; geometry_d[i].data = vertex_d[i].data; state.vertex_shader(vertex_d[i], geometry_d[i], state.uniform_data); triangle_geometry[i] = &geometry_d[i]; } clip_triangle(state, triangle_geometry, 0); } break; } default: { std::cout << "Invalid Type" << std::endl; } } } void interpolate_clipping(driver_state& state, const data_geometry* in[3], data_geometry(&geometry_d) [3], float& lerp, int& interp_case) { enum {x, y, z, w}; enum {a, b, c}; switch(interp_case) { case 0: for(size_t i = 0; i < state.floats_per_vertex; i++) { //Update A<->C based on interpolation type switch(state.interp_rules[i]) { case interp_type::flat: geometry_d[a].data[i] = in[a]->data[i]; break; case interp_type::noperspective:{ float temp = lerp * in[c]->gl_Position[w] / (lerp * in[c]->gl_Position[w] + (1 - lerp) * in[a]->gl_Position[w]); //std::cout << temp << std::endl; geometry_d[a].data[i] = temp * in[c]->data[i] + (1 - temp) * in[a]->data[i]; //std::cout << geometry_d1[a].data[i] << std::endl; break; } case interp_type::smooth: geometry_d[a].data[i] = lerp * in[c]->data[i] + (1 - lerp) * in[a]->data[i]; //std::cout << geometry_d1[a].data[i] << std::endl; default: break; } } break; case 1: for(size_t i = 0; i < state.floats_per_vertex; i++) { //Update A<->B based on interpolation type switch(state.interp_rules[i]) { case interp_type::flat: geometry_d[a].data[i] = in[a]->data[i]; break; case interp_type::noperspective:{ float temp = lerp * in[a]->gl_Position[w] / (lerp * in[a]->gl_Position[w] + (1 - lerp) * in[b]->gl_Position[w]); geometry_d[a].data[i] = temp * in[a]->data[i] + (1 - temp) * in[b]->data[i]; break; } case interp_type::smooth: geometry_d[a].data[i] = lerp * in[a]->data[i] + (1 - lerp) * in[b]->data[i]; default: break; } } break; default: break; } } // This function clips a triangle (defined by the three vertices in the "in" array). // It will be called recursively, once for each clipping face (face=0, 1, ..., 5) to // clip against each of the clipping faces in turn. When face=6, clip_triangle should // simply pass the call on to rasterize_triangle. void clip_triangle(driver_state& state, const data_geometry* in[3], int face) { if(face == 6) { rasterize_triangle(state, in); return; } enum {x, y, z, w}; enum {a, b, c}; const data_geometry* triangle_geometry[3] = {in[a], in[b], in[c]}; vec4 A = in[a]->gl_Position; vec4 B = in[b]->gl_Position; vec4 C = in[c]->gl_Position; int interp_case = 0; float lerp_1, lerp_2; vec4 P1, P2; data_geometry geometry_d1[3], geometry_d2[3]; geometry_d1[a].data = new float[state.floats_per_vertex]; geometry_d1[b] = *in[b]; geometry_d1[c] = *in[c]; geometry_d2[a].data = new float[state.floats_per_vertex]; geometry_d2[b] = *in[b]; geometry_d2[c] = *in[c]; //Check if clipping is needed if(A[z] < -A[w] && B[z] < -B[w] && C[z] < -C[w]) { //All points outside so no need to clip return; } else if(A[z] < -A[w] && B[z] >= -B[w] && C[z] >= -C[w]) { //Clip triangle and update interpolation //A is outside //Find lerp factors lerp_1 = (-A[z] - A[w]) / (C[z] + C[w] - A[z] - A[w]); lerp_2 = (-B[z] - B[w]) / (A[z] + A[w] - B[z] - B[w]); //std::cout << lerp_1 << " " << lerp_2 << std::endl; P1 = lerp_1 * C + (1 - lerp_1) * A; P2 = lerp_2 * A + (1 - lerp_2) * B; //std::cout << P1 << " " << P2 << std::endl; //Interpolate geometry data interpolate_clipping(state, in, geometry_d1, lerp_1, interp_case); geometry_d1[a].gl_Position = P1; triangle_geometry[a] = &geometry_d1[a]; triangle_geometry[b] = &geometry_d1[b]; triangle_geometry[c] = &geometry_d1[c]; clip_triangle(state, triangle_geometry, face + 1); interp_case = 1; //Interpolate geometry data interpolate_clipping(state, in, geometry_d2, lerp_2, interp_case); geometry_d2[a].gl_Position = P2; triangle_geometry[a] = &geometry_d2[a]; triangle_geometry[b] = &geometry_d1[b]; triangle_geometry[c] = &geometry_d1[a]; } clip_triangle(state, triangle_geometry, face + 1); } void interpolate_pixels(driver_state& state, const data_geometry* in[3], data_output& output_d, data_fragment& fragment_d, float& alpha, float& beta, float& gamma, float(&w) [3]) { enum {a, b, c}; const float ALPHA = alpha; const float BETA = beta; const float GAMMA = gamma; //Interpolation for (int k = 0; k < state.floats_per_vertex; k++) { float temp; switch (state.interp_rules[k]) { case interp_type::flat: //Flat fragment shader fragment_d.data[k] = in[a]->data[k]; break; case interp_type::noperspective: //interpolate using image-space barycentric coordinates fragment_d.data[k] = ( alpha * in[a]->data[k] + beta * in[b]->data[k] + gamma * in[c]->data[k] ); break; case interp_type::smooth: //Perspective interpolation temp = (ALPHA / w[0]) + (BETA / w[1]) + (GAMMA / w[2]); alpha = ALPHA / temp / w[0]; beta = BETA / temp / w[1]; gamma = GAMMA / temp / w[2]; fragment_d.data[k] = ( alpha * in[a]->data[k] + beta * in[b]->data[k] + gamma * in[c]->data[k] ); break; default: break; } } } // Rasterize the triangle defined by the three vertices in the "in" array. This // function is responsible for rasterization, interpolation of data to // fragments, calling the fragment shader, and z-buffering. void rasterize_triangle(driver_state& state, const data_geometry* in[3]) { enum {a, b, c}; //How to access vertex data: //Find pointer to data from: (*in)[vertex].data + (0 for x axis, 1 for y axis) //Or use in[vertex]->data[axis] //Or in[vertex]->gl_Position[axis] //Must dereference address to get values //std::cout << *(*in)[1].data << std::endl; //std::cout << in[1]->data << std::endl; //std::cout << in[1]->gl_Position[0]; //Get the w values for each vertex from geometry_d float w0 = in[0]->gl_Position[3]; float w1 = in[1]->gl_Position[3]; float w2 = in[2]->gl_Position[3]; float w[] = {w0, w1, w2}; //std::cout << w0 << w1 << w2 << std::endl; //Get each vertex coordinates divided by respective w float x0 = in[0]->gl_Position[0] / w0; float x1 = in[1]->gl_Position[0] / w1; float x2 = in[2]->gl_Position[0] / w2; float x[] = {x0, x1, x2}; float y0 = in[0]->gl_Position[1] / w0; float y1 = in[1]->gl_Position[1] / w1; float y2 = in[2]->gl_Position[1] / w2; float y[] = {y0, y1, y2}; float z0 = in[0]->gl_Position[2] / w0; float z1 = in[1]->gl_Position[2] / w1; float z2 = in[2]->gl_Position[2] / w2; //std::cout << "X:" << x0 << " " << x1 << " " << x2 << std::endl; //std::cout << "Y:" << y0 << " " << y1 << " " << y2 << std::endl; //std::cout << "Z:" << z0 << " " << z1 << " " << z2 << std::endl; int width = state.image_width; int height = state.image_height; float pixel_x[3], pixel_y[3]; float i, j; float middle_w = width / 2.0; float middle_h = height / 2.0; for(size_t iter = 0; iter < 3; iter++) { i = middle_w * x[iter] + middle_w - .5; j = middle_h * y[iter] + middle_h - .5; pixel_x[iter] = i; pixel_y[iter] = j; //state.image_color[i + j * w] = make_pixel(255, 255, 255); } //Find the mins and maxes of triangle to check if it's in bounds and to reduce //pixels to check when rendering triangle. float minimum_x = std::min(pixel_x[0], std::min(pixel_x[1], pixel_x[2])); float maximum_x = std::max(pixel_x[0], std::max(pixel_x[1], pixel_x[2])); float minimum_y = std::min(pixel_y[0], std::min(pixel_y[1], pixel_y[2])); float maximum_y = std::max(pixel_y[0], std::max(pixel_y[1], pixel_y[2])); //Check to make sure that triangle is in bounds using max and min verticies //If the minimum vertex is less than zero or the maximum vertex is larger than //it's coresponding dimention then it is out of bounds and we need to set it to //zero or the corresponding maximum image width/height. if(minimum_x < 0){ minimum_x = 0; } if(maximum_x > width){ maximum_x = width; } if(minimum_y < 0){ minimum_y = 0; } if(maximum_y > height){ maximum_y = height; } //Calculate area of triangle to use barycentric coordinates //Area(abc) = .5 * ((BxCy - CxBy)-(AxCy - CxAy)-(AxBy - BxAy)) //Broke up into parts and used enum for readability. //(Parts also useful in barycentric coordinate calculations) float part1 = (pixel_x[b] * pixel_y[c]) - (pixel_x[c] * pixel_y[b]); float part2 = (pixel_x[a] * pixel_y[c]) - (pixel_x[c] * pixel_y[a]); float part3 = (pixel_x[a] * pixel_y[b]) - (pixel_x[b] * pixel_y[a]); float triangle_area = .5 * (part1 - part2 + part3); //std::cout << triangle_area << std::endl; // for(unsigned i = 0; i < 3; i++) { // std::cout << pixel_x[i] << std::endl; // std::cout << pixel_y[i] << std::endl; // } float alpha, beta, gamma; //std::cout << "X:" << minimum_x << maximum_x << std::endl; //std::cout << "Y:" << minimum_y << maximum_y << std::endl; //Find the barycentric coords for each pixel in the area of the triangle. If the coordinate is inside //the triangle then we update the color, otherwise leave it black. //We only need to check from the minimum x,y pixels to maximum x,y pixels since we know the triangle is in this area. //Interpolate points within the triangle based on interp_rules. for(int i = minimum_x; i < maximum_x; i++) { for(int j = minimum_y; j < maximum_y; j++) { alpha = (.5 * (part1 + (pixel_y[b] - pixel_y[c]) * i + (pixel_x[c] - pixel_x[b]) * j) / triangle_area); beta = (.5 * (((pixel_x[c] * pixel_y[a]) - (pixel_x[a] * pixel_y[c])) + (pixel_y[c] - pixel_y[a]) * i + (pixel_x[a] - pixel_x[c]) * j) / triangle_area); gamma = (.5 * (part3 + (pixel_y[a] - pixel_y[b]) * i + (pixel_x[b] - pixel_x[a]) * j) / triangle_area); //Find depth for Z-Buffering float depth = alpha * z0 + beta * z1 + gamma * z2; //Only render pixel when the point is inside of the triangle and if(alpha >= 0 && beta >= 0 && gamma >= 0 && state.image_depth[i + j * width] > depth) { data_output output_d; data_fragment fragment_d; fragment_d.data = new float[state.floats_per_vertex]; //Interpolation interpolate_pixels(state, in, output_d, fragment_d, alpha, beta, gamma, w); state.fragment_shader(fragment_d, output_d, state.uniform_data); //std::cout << output_d.output_color << std::endl; state.image_depth[i + j * width] = depth; state.image_color[i + j * width] = make_pixel(output_d.output_color[0] * 255, output_d.output_color[1] * 255, output_d.output_color[2] * 255); } } } }
JavaScript
UTF-8
895
3.125
3
[]
no_license
/* * @lc app=leetcode.cn id=152 lang=javascript * * [152] 乘积最大子数组 */ // @lc code=start /** * @param {number[]} nums * @return {number} */ var maxProduct = function(nums) { const maxPre = nums[0]<0?[0]:[nums[0]] const maxMinusPre = nums[0]>0?[0]:[nums[0]] let max = nums[0]; for (let i = 1; i < nums.length; i++) { const cur = nums[i]; if(cur == 0){ maxMinusPre.push(0); maxPre.push(0); }else if(cur>0){ maxPre.push(Math.max(cur*maxPre[i-1],cur)); const maxMinus =cur*maxMinusPre[i-1] maxMinusPre.push(maxMinus) }else{ const maxMinus = Math.min(cur*maxPre[i-1],cur) maxMinusPre.push(maxMinus) maxPre.push(Math.max(cur*maxMinusPre[i-1],0)); } max = Math.max(max,maxPre[i]) } return max; }; // @lc code=end
JavaScript
UTF-8
3,220
2.546875
3
[]
no_license
import React from 'react'; import {Row} from "reactstrap"; import Mqtt from 'mqtt'; import {SubscribeForm} from "./components/SubscribeForm"; import {MessageItem} from "./components/MessageItem"; import {SubscribeList} from "./components/SubscribeList"; let client; export default class App extends React.Component { state = { newTopic: '', topics: [], messages: [] }; componentDidMount() { const SERVER_URL = process.env.REACT_APP_MQTT_SERVER_URL; const USERNAME = process.env.REACT_APP_USERNAME; const PASSWORD = process.env.REACT_APP_PASSWORD; console.log("using server '%s'", SERVER_URL); client = Mqtt.connect('mqtt://' + SERVER_URL, { username: USERNAME, password: PASSWORD, clientId: 'mqttclient_' + Math.random() }); client.on('connect', function () { console.log('connected with mqtt server ' + SERVER_URL); }); client.on('message', this.messageHandler); } render() { return ( <div> <h1>WELCOME TO SUBSCRIBER CLIENT</h1> <Row> <SubscribeForm subscribeHandler={this.subscribeToTopic} topicHandler={e => this.topicHandler(e)} /> <SubscribeList allTopics={this.state.topics} unsubscribeHandler={e => this.unsubscribeHandler(e)} /> </Row> <Row> {this.state.messages.map((messageItem, i) => <MessageItem key={i} messageItem={messageItem} /> )} </Row> </div> ) } messageHandler = (topic, message) => { console.log("message received over topic '%s'", topic); let response = JSON.parse(message); response.time = new Date().toLocaleTimeString(); this.setState(state => ({ messages: [...state.messages, response] })); }; topicHandler = (topic) => { this.setState({ newTopic: topic }) }; subscribeToTopic = () => { if (!this.state.topics.includes(this.state.newTopic) && this.state.newTopic.length > 0) { const topic = this.state.newTopic; this.setState(state => ({ topics: [...state.topics, topic], newTopic: "" })); client.subscribe(topic); console.log("subscribed to topic: " + topic) } else { console.log("already to topic subscribed: " + this.state.newTopic); } }; unsubscribeHandler = (topic) => { console.log("unsubscribed from topic: " + topic); const index = this.state.topics.indexOf(topic); let currentTopics = [...this.state.topics]; currentTopics.splice(index, 1); this.setState({ topics: currentTopics }); client.unsubscribe(topic) }; componentWillUnmount() { client.end(true); } }
C++
UTF-8
2,183
2.703125
3
[]
no_license
// ExpColum.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。 // #include <iostream> #include <tchar.h> #include <assert.h> typedef unsigned char UINT8; static int get_bit_at_position(UINT8* buf, UINT8& bytepotion, UINT8& bitPosition) { UINT8 mask = 0, val = 0; mask = 1 << (7 - bitPosition); val = ((buf[bytepotion] & mask) != 0); if (++bitPosition > 7) { bytepotion++; bitPosition = 0; } return val; } static int get_uev_code_num(UINT8* buf, UINT8& bytePosition, UINT8& bitPosition) { assert(bitPosition < 8); UINT8 val = 0, prefixZeroCount = 0; int prefix = 0, surfaix = 0; while (true) { val = get_bit_at_position(buf, bytePosition, bitPosition); if (val == 0) { prefixZeroCount++; } else { break; } } prefix = (1 << prefixZeroCount) - 1; for (size_t i = 0; i < prefixZeroCount; i++) { val = get_bit_at_position(buf, bytePosition, bitPosition); surfaix += val * (1 << (prefixZeroCount - i - 1)); } return val; } int _tmain(int argc, _TCHAR* argv[]) { UINT8 strArray[6] = { 0xA6, 0x42, 0x98, 0xE2, 0x04, 0x8A }; UINT8 bytePosition = 0, bitPosition = 0; UINT8 dataLengthInBits = sizeof(strArray) / sizeof(UINT8) * 8; int codeNum = 0; while ((bytePosition * 8 + bitPosition) < dataLengthInBits) { codeNum = get_uev_code_num(strArray, bytePosition, bitPosition); printf("ExpoColumb codeNum= %d \n", codeNum); } return 0; } // 运行程序: Ctrl + F5 或调试 >“开始执行(不调试)”菜单 // 调试程序: F5 或调试 >“开始调试”菜单 // 入门使用技巧: // 1. 使用解决方案资源管理器窗口添加/管理文件 // 2. 使用团队资源管理器窗口连接到源代码管理 // 3. 使用输出窗口查看生成输出和其他消息 // 4. 使用错误列表窗口查看错误 // 5. 转到“项目”>“添加新项”以创建新的代码文件,或转到“项目”>“添加现有项”以将现有代码文件添加到项目 // 6. 将来,若要再次打开此项目,请转到“文件”>“打开”>“项目”并选择 .sln 文件
C
ISO-8859-15
473
3.546875
4
[]
no_license
#include <stdlib.h> char *strpbrk(char *s1 , char *s2) { char *p1, *p2; for (p1 = s1; *p1; p1++) { for (p2 = s2; *p2;) if (*p1 == *p2++) return p1; } return NULL; } // Testprogram, ingick inte i uppgiften #include <stdio.h> int main() { char a[30],b[30]; printf("Skriv tv ord\n"); scanf("%s%s", a, b); char *r = strpbrk(a, b); if (r != NULL) { int i = r-a; printf("Finns p plats %d\n", i); } else printf("Finns inte\n"); }
Java
UTF-8
2,281
3.953125
4
[]
no_license
package com.java; import java.util.Scanner; import com.java.BadChangeException; /** * @author Anthony Zenin - ID: 991508379 * @author Kirtan Parekh - ID: 991551563 * Title: ICE 3 - Change Maker - SYST 38634 ICE03 * Date: February 5th, 2021 * * Description: A program that counts the change (in coins) for a given number of cents. */ public class ChangeCounter { private static final int QUARTER = 25; private static final int DIME = 10; private static final int NICKEL = 5; public static void main(String[] args) throws BadChangeException { int input = getInput(); int[] change = makeChange(input); String quarterStr = ""; String dimeStr = ""; String nickelStr = ""; if (change[0] != 0) { quarterStr = change[0] + " quarter(s) "; } if (change[1] != 0) { dimeStr = change[1] + " dime(s) "; } if (change[2] != 0) { nickelStr = change[2] + " nickel(s) "; } System.out.println(input + " cents requires " + quarterStr + dimeStr + nickelStr); } private static int getInput() { Scanner sc = new Scanner(System.in); System.out.print("Please enter amount in cents between 0 and 100: "); int input = sc.nextInt(); return input; } public static int[] makeChange(int input) throws BadChangeException { // Checking if the input is within range if (input < 0 || input > 100) { throw new BadChangeException("Change out of bounds."); } int numberOfQuarters = 0; int numberOfDimes = 0; int numberOfNickels = 0; int[] change = {0, 0, 0}; // Performing actions to determine amount of change numberOfQuarters = input / QUARTER; input = input % QUARTER; numberOfDimes = input / DIME; input = input % DIME; numberOfNickels = input / NICKEL; input = input % NICKEL; // Checking input and if non zero, then round either up or down if (input == 0) { change[0] = numberOfQuarters; change[1] = numberOfDimes; change[2] = numberOfNickels; return change; } else { // Rounding done here if (input >= 3) { input = (int) Math.ceil(input / 100); numberOfNickels += 1; } else { input = (int) Math.floor(input / 100); } // Returning data change[0] = numberOfQuarters; change[1] = numberOfDimes; change[2] = numberOfNickels; return change; } } }
PHP
UTF-8
513
3.3125
3
[ "MIT" ]
permissive
<!-- Aplicar 10% de desconto ao preço de um produto --> <!Doctype html> <html lang = "pt-br"> <head> <meta charset = "utf-8"> </head> <body> <?php $preco = $_GET["preco"]; echo "O preço do produto é R$ $preco </br>"; $aumento = $preco + ($preco * 10 / 100); echo "O preço com 10 % de aumento é R$".number_format($aumento,2,",",".")." </br>"; $desc = $preco - ($preco * 10 /100); echo "O preço com 10 % de desconto é ".number_format($desc,2,",","."); ?> </body> </html>
Java
UTF-8
555
4.03125
4
[]
no_license
package Session2; public class PrimeNumbers { /** * PS: Generate prime number between 1 to 100 using for loop. */ public static void main(String[] args) { for(int i=1; i<100; i++){ int count=0, remainder=0; //variables initialized to zero. for (int j=1; j<i+1; j++){ remainder = i%j; // finding the remainder if(remainder==0) // if the remainder is equal to zero increment the count count++; } if(count==2) // if the loop count is equal to two then print the number as prime. System.out.print(i+" "); } } }