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
Go
UTF-8
891
3.546875
4
[]
no_license
package main import ( "fmt" "time" ) func main() { defer timeTrack(time.Now()) endYear := 2000 result := 0 dayOfWeek := 1 year := 1901 month := 0 day := 0 for year <= endYear { for month < 12 { for day < getDaysMonth(month, year) { if dayOfWeek == 6 && day == 0 { result ++ } dayOfWeek++ dayOfWeek = dayOfWeek % 7 day++ } day = 0 month++ } month = 0 year++ } fmt.Printf("Result: %[1]d\n", result) } func getDaysMonth(currentMonth int, currentYear int) int { if currentMonth == 1 { if currentYear % 400 == 0 { return 29 } if currentYear % 100 == 0 { return 28 } if currentYear % 4 == 0 { return 29 } } months := [12]int{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31} return months[currentMonth] } func timeTrack(start time.Time) { elapsed := time.Since(start) fmt.Printf("Runtime: %s\n", elapsed) }
Java
UTF-8
1,258
2.515625
3
[]
no_license
package com.java.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; @WebFilter("/account/*") public class ServletFilter implements Filter{ Logger logger = Logger.getLogger(ServletFilter.class); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpSession session = req.getSession(); boolean isLoggedIn = (session != null && session.getAttribute("user") != null); if(isLoggedIn) { logger.info("Session is valid."); chain.doFilter(request, response); } else { logger.info("User has not loggend in properly. Redirected to log in page."); RequestDispatcher reqDispatch = request.getRequestDispatcher("../login.html"); reqDispatch.forward(request, response); } } }
JavaScript
UTF-8
860
3.71875
4
[ "MIT" ]
permissive
/** * @param preferences - an array of integers. Indices of people, whom they love * @returns number of love triangles */ module.exports = function getLoveTrianglesCount(preferences = []) { // your implementation if(preferences === null || !Array.isArray(preferences) || preferences.length < 3){ return 0; } let prefDistinct = [0].concat(preferences); // make index of person equal it's number --> code more clear let triangleCount = 0; prefDistinct.forEach(function(lovedPerson, personNumber, array) { let lovedOfLovedPerson = array[lovedPerson]; if(lovedOfLovedPerson === personNumber){ return; } let lovedOfLovedOfLoved = array[lovedOfLovedPerson]; if(lovedOfLovedOfLoved === personNumber){ triangleCount++; } }); return triangleCount/3; };
Java
UTF-8
2,883
2.421875
2
[]
no_license
package com.predictivemovement.route.optimization; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.json.JSONObject; /** * Try out manually some performance measures. */ public class TryPerformanceMeasure { private JSONObject response; public static void main(final String args[]) throws Exception { // increase vehicles // String requestFile = "src/test/resources/metrics/vehicles/req_v68_b1.json"; // String requestFile = "src/test/resources/metrics/vehicles/req_v137_b1.json"; // String requestFile = "src/test/resources/metrics/vehicles/req_v205_b1.json"; // String requestFile = "src/test/resources/metrics/vehicles/req_v274_b1.json"; // increase bookings // String requestFile = "src/test/resources/metrics/bookings/req_v1_b34.json"; // String requestFile = "src/test/resources/metrics/bookings/req_v1_b68.json"; // String requestFile = "src/test/resources/metrics/bookings/req_v1_b102.json"; // String requestFile = "src/test/resources/metrics/bookings/req_v1_b137.json"; // mixed String requestFile = "src/test/resources/metrics/req_v1_b1.json"; // String requestFile = "src/test/resources/metrics/req_v34_b120.json"; // String requestFile = "src/test/resources/metrics/req_v68_b103.json"; // String requestFile = "src/test/resources/metrics/req_v136_b69.json"; // String requestFile = "src/test/resources/metrics/req_v205_b103.json"; TryPerformanceMeasure tryOut = new TryPerformanceMeasure(); try { tryOut.jsprit(requestFile); } catch (RouteOptimizationException exception) { String errorResponse = new ErrorResponse(exception).create(); System.out.println(errorResponse); throw exception; } } public void jsprit(String requestFile) throws Exception { // given Path fileName = Path.of(requestFile); String msg = Files.readString(fileName); JSONObject routeRequest = new JSONObject(msg); // when RouteProcessing routeProcessing = new RouteProcessingWithMetrics(); routeProcessing.calculate(routeRequest); StatusResponse statusResponse = routeProcessing.getStatusResponse(); response = statusResponse.status; // then JSONObject metrics = response.getJSONObject("data").getJSONObject("metrics"); System.out.println(metrics); String metricFilename = fileName.toString().replace(".json", "_metric.json"); writeJsonFile(metrics, metricFilename); } private void writeJsonFile(JSONObject request, String filename) throws IOException { Path filepath = Paths.get(filename); Files.write(filepath, request.toString().getBytes()); } }
Java
UTF-8
1,976
2.015625
2
[ "EPL-1.0", "Classpath-exception-2.0", "LicenseRef-scancode-unicode", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-protobuf", "CDDL-1.1", "W3C", "APSL-1.0", "GPL-2.0-only", "Apache-2.0", "LicenseRef-scancode-public-domain", "SAX-PD", "MPL-2.0", "MPL-1.1", "CC-PDDC", "BSD-2-Clause", "Plexus", "EPL-2.0", "CDDL-1.0", "LicenseRef-scancode-proprietary-license", "MIT", "CC0-1.0", "APSL-2.0", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-only", "LGPL-2.1-or-later", "UPL-1.0" ]
permissive
/* * Copyright (c) 2000, 2022, Oracle and/or its affiliates. * * Licensed under the Universal Permissive License v 1.0 as shown at * https://oss.oracle.com/licenses/upl. */ package com.tangosol.coherence.rest; import com.oracle.coherence.common.base.Logger; import com.tangosol.coherence.rest.config.DirectQuery; import com.tangosol.coherence.rest.config.QueryConfig; import com.tangosol.coherence.rest.config.ResourceConfig; import com.tangosol.coherence.rest.util.StaticContent; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; /** * An alternate {@link ResourceConfig} implementation that supports pass-through * access to all the caches defined by the cache configuration. * * @author as 2015.09.07 * @since 12.2.1 */ @Path("/") public class PassThroughRootResource extends DefaultRootResource { /** * Returns a resource representing a single named cache. * * @param sName resource name * * @return resource representing a single named cache */ @Override @Path("{name}") public CacheResource getCacheResource(@PathParam("name") String sName) { ResourceConfig configResource = m_config.getResources().get(sName); if (configResource == null) { // register pass-through resource for the specified cache name configResource = new ResourceConfig(); configResource.setCacheName(sName); configResource.setKeyClass(String.class); configResource.setValueClass(StaticContent.class); configResource.setQueryConfig(new QueryConfig().setDirectQuery(new DirectQuery(Integer.MAX_VALUE))); configResource.setMaxResults(Integer.MAX_VALUE); m_config.getResources().put(sName, configResource); Logger.info("Configured pass-through resource for cache: " + sName); } return instantiateCacheResourceInternal(configResource); } }
C#
UTF-8
1,111
2.78125
3
[]
no_license
using eNotification.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Web.Mvc; namespace NotificationService.Models { public static class CustomExtensions { public static IEnumerable<SelectListItem> ToSelectListItems( this IEnumerable<Doctor> doctors) { return doctors.OrderBy(doctor => doctor.SecondName) .Select(doctor => new SelectListItem { Text = doctor.SecondName, Value = doctor.Id.ToString() }); } public static string RemoveSpecialCharacters(this string input) { if (string.IsNullOrEmpty(input)) return input; Regex regex = new Regex("(?:[^a-z0-9 ]|(?<=['\"])s)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); return regex.Replace(input, String.Empty); } } }
Java
UTF-8
1,458
3.5
4
[]
no_license
package Graphs; import java.util.Iterator; import java.util.LinkedList; import java.util.Queue; public class BFSAdjacencyList { private int V; private LinkedList<Integer>[] adjacencyList; public BFSAdjacencyList(int v){ V = v; adjacencyList = new LinkedList[v]; for(int i=0; i<v;i++){ adjacencyList[i] = new LinkedList<Integer>(); } } public void addEdge(int v, int n){ adjacencyList[v].add(n); } public boolean bfsUtil(int target, int start, boolean[] visited){ Queue<Integer> q = new LinkedList<Integer>(); q.add(start); while(q.isEmpty() == false){ int node = q.remove(); if(visited[node] == false){ System.out.print(node + " "); if(node == target){ return true; } visited[node] = true; Iterator<Integer> iterator = adjacencyList[node].listIterator(); while(iterator.hasNext()){ q.add(iterator.next()); } } } return false; } public boolean BFS(int target, int start){ boolean[]visited = new boolean[V]; return bfsUtil(target, start, visited); } public static void main(String[] args){ BFSAdjacencyList graph = new BFSAdjacencyList(7); graph.addEdge(1,3); graph.addEdge(0,2); graph.addEdge(2,0); graph.addEdge(2,6); graph.addEdge(6,2); graph.addEdge(4,5); graph.addEdge(5,4); graph.addEdge(1,0); graph.addEdge(0,1); graph.addEdge(2,4); graph.addEdge(4,2); boolean b = graph.BFS(1, 3); System.out.println(b); } }
TypeScript
UTF-8
1,308
3.046875
3
[ "MIT" ]
permissive
import { ApiProperty } from '@nestjs/swagger'; import { IsEmail, Matches, MaxLength, MinLength } from 'class-validator'; export class RegisterDto { @ApiProperty() @IsEmail( {}, { message: 'Please enter a valid email address, for example your-email@domain.com', }, ) readonly email: string; @ApiProperty() @Matches(/^[a-zA-Z0-9]+$/, { message: 'Password contains only digit and word', }) @MinLength(8, { message: 'Password Min length is 8 characters', }) readonly password: string; @ApiProperty() @MinLength(3, { message: 'First name Minimum length is 3 characters', }) @MaxLength(50, { message: 'First name Maximum length is 50 characters', }) @Matches(/^[a-z ]+$/i, { message: 'First name contains only text', }) readonly firstName: string; @ApiProperty() @MinLength(3, { message: 'Last name Minimum length is 3 characters', }) @MaxLength(50, { message: 'Last name Maximum length is 50 characters', }) @Matches(/^[a-z ]+$/i, { message: 'Last name contains only text', }) readonly lastName: string; @ApiProperty() @MinLength(6, { message: 'Phone Minimum length is 6 characters', }) @MaxLength(50, { message: 'Phone Maximum length is 20 characters', }) @Matches(/^[0-9 +]+$/i, { message: 'Phone contains only number', }) readonly phoneNumber: string; }
Markdown
UTF-8
1,051
2.515625
3
[]
no_license
CacheInvalidationTester ======================= Tool to Test Cache Invalidation scenarios To run the tests: ```bash python server.py [portnumber] ``` portnumber defaults to 8000, if you don't specify it. Open a browser to http://localhost:8000 #Test 0 This test checks to make sure that two back to back GET requests are correctly cached. 1. GET data.json 2. GET data.json This means the first GET comes from the server (or cache depending on what else has happend) and the second one must come from the browser cache. #Test 1 This test is meant to check to make sure that a POST invalidates the local cache so it does: 1. GET data.json 2. POST data.json 3. GET data.json * Step one's GET should come from the server (or cache depending on what else has happend) * Step two's POST should always go to the server * Step three's GET should always come from the server #Currently Status: ##Test 0 Results: ###Passing Chrome Firefox Safari ##Test 1 Results: ###Passing Firefox ###Failing Chrome Safari
Java
UTF-8
3,371
2.390625
2
[]
no_license
package com.admin.core.net; import com.admin.core.app.ConfigType; import com.admin.core.app.Latte; import com.admin.core.net.rx.RxRestService; import java.util.ArrayList; import java.util.WeakHashMap; import java.util.concurrent.TimeUnit; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.scalars.ScalarsConverterFactory; /** * Copyright (C) * * @file: RestCreator * @author: 345 * @Time: 2019/4/17 19:19 * @description: Creator:创造者 */ public class RestCreator { /** * 参数容器 */ private static final class ParamsHolder{ static final WeakHashMap<String ,Object> PARAMS = new WeakHashMap<>(); } public static WeakHashMap<String,Object> getParams(){ return ParamsHolder.PARAMS; } /** * 构建 全局Retrofit 客户端 */ private static final class RetrofitHolder{ /** * 加载已经初始化的网络地址 */ private static final String BASE_URL = (String) Latte.getConfigurations().get(ConfigType.API_HOST.name()); /** * 创建 Retrofit 的实例 * 创建 Retrofit 的实例是需要通过 Retrofit.Builder创建,并调用baseUrl 设置 url */ private static final Retrofit RETROFIT_CLIENT = new Retrofit.Builder() //设置网络请求的 url地址 .baseUrl(BASE_URL) // .client(OkHttpHolder.OK_HTTP_CLIENT) //依赖中引入的转换器 .addConverterFactory(ScalarsConverterFactory.create()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .build(); } /** * 构建 Okhttp */ private static final class OkHttpHolder{ private static final int TIME_OUT = 60; public static final OkHttpClient.Builder BUILDER = new OkHttpClient.Builder(); private static final ArrayList<Interceptor> INTERCEPTORS = Latte.getConfiguration(ConfigType.INTERCEPTOR); private static OkHttpClient.Builder addInterceptor(){ if (INTERCEPTORS != null && !INTERCEPTORS.isEmpty()){ for (Interceptor interceptor : INTERCEPTORS){ BUILDER.addInterceptor(interceptor); } } return BUILDER; } private static final OkHttpClient OK_HTTP_CLIENT = addInterceptor() .connectTimeout(TIME_OUT, TimeUnit.SECONDS) .build(); } /** * Service 接口 */ private static final class RestServiceHolder{ private static final RestService REST_SERVICE = RetrofitHolder.RETROFIT_CLIENT.create(RestService.class); } /** * @return 返回网络接口请求的实例 */ public static RestService getRestService(){ return RestServiceHolder.REST_SERVICE; } /** * RxService 接口 */ private static final class RxRestServiceHolder{ //创建 网络请求接口 的实例 private static final RxRestService REST_SERVICE = RetrofitHolder.RETROFIT_CLIENT.create(RxRestService.class); } public static RxRestService getRxRestService(){ return RxRestServiceHolder.REST_SERVICE; } }
JavaScript
UTF-8
6,343
2.734375
3
[]
no_license
//----KONFIGURACIJA----// //----React/React Native----// import React, { useState, useEffect } from 'react'; import { Button, StyleSheet, Text, TextInput, View } from 'react-native'; //---Expo paketi----// import * as Permissions from 'expo-permissions'; import * as Location from 'expo-location'; //----Komponente----// import GlavniNaslov from '../components/GlavniNaslov'; import PrikazKarte from '../components/PrikazKarte'; import OdabirRadijusa from '../components/OdabirRadijusa'; import PreporuceneOsobe from '../components/PreporuceneOsobe'; //----Servisi----// import lokacijaServis from '../services/locRecommendation'; const PreporukaUpit = () => { // Stanja za komponentu const [upit, postaviUpit] = useState(""); // Korisnički upit const [lokacija, postaviLokaciju] = useState([]); // Korisnička lokacija const [radijus, postaviRadijus] = useState(25.0); // Radijus pretrage const [rezultati, postaviRezultate] = useState(null); // Konačni rezultati const [regija, postaviRegiju] = useState(null); // Širina karte // Kontrolirani unos - upit const promjenaUpit = (unos) => { postaviUpit(unos); } // Dozvola pristupa lokaciji (Android) const dozvoliPristup = async () => { const odobrenje = await Permissions.askAsync(Permissions.LOCATION); if (odobrenje.status !== "granted") { Alert.alert( "Nedozvoljen pristup", "Morate odobriti aplikaciji pristup lokaciji kako bi mogli koristiti sve funkcionalnosti", [{ text: "OK" }] ); return false; } return true; }; // Dohvat lokacije korisničkog uređaja (Android) const dohvatiLokaciju = async () => { // ako ne dobije pristup piši kući propalo const pristup = await dozvoliPristup(); if (!pristup) { return; } try { // inače dohvati trenutni položaj korisnika (kroz 5 sekundi) const polozaj = await Location.getCurrentPositionAsync({ timeout: 5000, }); // postavi dobivene podatke postaviLokaciju({ latitude: polozaj.coords.latitude, longitude: polozaj.coords.longitude, }); postaviRegiju({ latitude: polozaj.coords.latitude, longitude: polozaj.coords.longitude, latitudeDelta: 0.1, longitudeDelta: 0.1 }) } catch (err) { console.log(err); Alert.alert("Nije moguće dohvatiti lokaciju", "Pokušajte ponovno", [ { text: "OK" }, ]); } }; // Slanje korisničkog upita i dohvat potencijalnih kandidata const saljiUpit = () => { // prvo lociraj korisnike u zadanom radijusu lokacijaServis.locirajPotencijalneKandidate(lokacija, radijus) .then((response) => { // nakon toga zatraži računanje podobnosti kandidata na temelju recenzija console.log(response.data); lokacijaServis.dobijPreporuceneKandidate(response.data, upit) .then((response) => { // na kraju dohvati i postavi rezultate za prikaz postaviRezultate(response.data); }); }); } // Dodaj korisnički zahtjev recenzijama najpodobnijeg kandidata (sustav postaje "pametniji") // Operira pod pretpostavkom da će korisnik najčešće uzeti kandidata koji ima i najbolji rezultat za njegov upit // premda to ne mora značiti ako je korisnik zapeo na blizinu samog kandidata (drugim riječima stvarni korisnik može // odabrati i kandidata koji mu je na karti najbliže, a da nema nužno najbolji rezultat za njegov zahtjev) const odabirKandidata = () => { // ako je korisnik uopće dobio rezultate za svoju lokaciju // onda ažuriraj prvog kandidata if (rezultati.length > 0) { let id = rezultati[0].id; lokacijaServis.azurirajNajboljegKandidata(id, upit) .then((response) => { console.log(response.data); }); postaviRezultate(null); postaviUpit(""); postaviRadijus(25.0); } // inače samo očisti stanja else { postaviRezultate(null); postaviUpit(""); postaviRadijus(25.0); } } // Dohvat lokacije na početku useEffect(() => { dohvatiLokaciju(); }, []); return ( <View style={styles.container}> <GlavniNaslov naslov="ASK FOR A RECOMMENDATION" /> <View style={styles.sadrzaj}> <TextInput style={styles.unos} placeholder="What do you want to visit?" value={upit} onChangeText={promjenaUpit} /> <Text>Where are you located?</Text> <PrikazKarte postaviLokaciju={postaviLokaciju} regija={regija} lokacija={lokacija} rezultati={rezultati} /> { rezultati ? <View> <Button title="Return" onPress={odabirKandidata} /> <PreporuceneOsobe rezultati={rezultati} /> </View> : <View style={styles.sadrzaj}> <OdabirRadijusa postaviRadijus={postaviRadijus} /> <Button title="Get recommendation" onPress={saljiUpit} /> </View> } </View> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', }, sadrzaj: { paddingTop: 10, justifyContent: 'space-between', alignItems: 'center', height: "15%", width: "100%", }, unos: { backgroundColor: "#f3f3f3", padding: 5, width: "90%", marginBottom: "5%" } }); export default PreporukaUpit;
Markdown
UTF-8
6,463
3.953125
4
[]
no_license
# PHP-Function PHP 函数 ### 1. 用户自定义函数 1. 函数名以字母或下划线开头,后面跟字母、数字或下划线 2. 函数无需在调用之前被定义,除非以下两种情况 - 当一个函数是有条件被定义时,必须在调用函数之前定义 示例: ``` $makefoo = true; // foo(); // 报错 致命错误,函数未定义 if ($makefoo) { // 函数是否定义是有条件的 function foo() { echo "Hello world"; } } foo(); // 现在可以安全调用 ``` - 函数中的函数 示例: ``` function foo() { function bar() { echo "Hello World"; } } // bar(); // 报错 致命错误,因为此时它未定义 foo(); // 执行foo()函数,定义bar()函数 bar(); // 现在可以执行bar()函数 ``` 3. PHP中的所有函数和类都具有全局作用域,可以定义在一个函数之内而在之外调用,反之亦然 4. PHP不支持函数重载,也不可能取消定义或者重定义已经声明的函数 示例: ``` function abc(){ echo 'Hello World'; } function abc(){ echo '123456'; } // 报错 致命错误,不能重复声明 abc(); ``` 5. PHP函数名是大小写无关的,不过在调用函数的时候,应使用其在定义时相同的形式 示例: ``` function aBc(){ echo 'Hello World'; } AbC(); // 打印 Hello World ``` 6. PHP中可以调用递归函数 示例: ``` function recursion($a) { if ($a <= 10) { echo "$a "; recursion($a + 1); } } recursion(5); // 打印 5678910 ``` ### 2. 函数参数 1. 普通形式,值传递 *默认情况下,函数参数使用值传递(即使在函数内部改变参数的值,也不会改变函数外部的值)* 示例: ``` function print_arg($arg) { print $arg; } ``` 2. 引用传递参数 *在参数前面加上符号(&),允许函数修改它的参数值* 示例: ``` // 这种情况下,在函数中做的修改并不会影响外面的值 $str = 'Hello World'; function print_arg($arg) { $arg = $arg . '123456'; print $arg; } print_arg($str); // 打印 Hello World123456 print $str; // 打印 Hello World // 在函数参数前加上符号(&) $str = 'Hello World'; function print_arg(&$arg) { $arg = $arg . '123456'; print $arg; } print_arg($str); // 打印 Hello World123456 print $str; // 打印 Hello World123456 ``` 3. 默认参数的值 默认值必须是常量表达式 *函数有参数时,若使用时没有传递参数又没有设置默认参数时,报致命错误* *使用默认参数时,任何默认参数必须放在任何非默认参数的右侧,否则报错 WARNING* *PHP 5+,传引用的参数也可以有默认值* 示例: ``` // 使用标量类型作为默认参数 function makecoffee($type = "cappuccino") { return "Making a cup of $type.\n"; } echo makecoffee(); // 不传,使用默认值 "cappuccino" 代替 $type echo makecoffee(null); // 传NULL, 使用 "" 代替 $type echo makecoffee("espresso"); // 使用 "espresso" 代替 $type // 使用非标量类型作为默认参数 function makecoffee($types = array("cappuccino"), $coffeeMaker = NULL) { $device = is_null($coffeeMaker) ? "hands" : $coffeeMaker; return "Making a cup of ".join(", ", $types)." with $device.\n"; } echo makecoffee(); echo makecoffee(array("cappuccino", "lavazza"), "teapot"); // 默认参数在非默认参数的右侧 function print_arg($arg0,$arg1 = '123456') { print $arg0.$arg1; } print_arg('Hello World'); // 打印 Hello World123456 ``` 4. 参数类型声明 常见的类型声明:class、interface、self、array、callable、bool(PHP 7+)、float(PHP 7+)、int(PHP 7+)、string(PHP 7+) PHP 7+,若调用时,指定的参数类型不对,将抛出 TypeError 异常(PHP 5 可恢复的致命错误) *默认情况下,PHP会先强迫错误类型的值转为函数期望的标量类型;严格模式下,只有与类型声明完全相符才会被接受* 示例: ``` // 正常情况 function arg(int $e){ var_dump($e); // 打印 int(123) } arg(123); // 发生了转换 function arg(int $e){ var_dump($e); // 打印 int(123) } arg('123'); // 发生了转换 function arg(int $e){ var_dump($e); // 报错 TypeError 异常 } arg([123]); ``` 5. 可变数量的参数列表 PHP 5.6+,使用 ... 语法 - ...$e 访问参数 示例: ``` function sum(...$e) { $res = 0; foreach ($e as $x) { $res += $x; } return $res; } echo sum(3,2,1); // 打印 6 ``` - ...[x,y,z] 提供参数 示例: ``` function add($a, $b) { return $a + $b; } print add(...[1, 2]); // 打印 3 $a = [1, 2]; print add(...$a); // 打印 3 ``` - *可以在 ... 之前指定正常位置参数。在这种情况下,只有与位置参数不匹配的尾随参数会被添加到由 ... 生成的数组中* 示例: ``` function sum($e0,...$e) { $res = 0; foreach ($e as $x) { $res += $x; } print $e0; return $res; } echo sum(3,2,1); // 打印 33 ``` - *可以在 ... 之前添加类型声明,如果有进行声明,那么 ... 数组中的元素都必须符合此类型* 示例: ``` function sum(int ...$e) { $res = 0; foreach ($e as $x) { $res += $x; } return $res; } echo sum([0, 1],0,1); // 报错 TypeError异常 echo sum(0,1); // 打印 3 ``` --- STARTED 2018/11/19 ChenJian MODIFIED 2018/11/19 ChenJian
Markdown
UTF-8
8,038
2.578125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "ICU" ]
permissive
--- layout: post title: "Richard Stallman on Free Software and your Freedom (lecture)" author: Amir Chaudhry tags: [cambridge, lecture, notes] description: shorturl: http://bit.ly/IineFM --- {% include JB/setup %} Lecture at Cambridge Computer Lab on 1 March 2011 - Sponsored by Software East (@markdalgarno) \[pls excuse the typos & poor grammar. I'm typing this on the fly and unlikely to edit it before posting. Caveat emptor\] \[edit: It was a long talk and I missed some chunks. Overall, he spoke for just over 90mins. Longer than I was expecting\] Bio: Richard Stallman launched the development of the GNU operating system (see [www.gnu.org](http://www.gnu.org)) in 1984. GNU is free software: everyone has the freedom to copy it and redistribute it, as well as to make changes either large or small. The GNU/Linux system, basically the GNU operating system with Linux added, is used on tens of millions of computers today. Stallman has received the ACM Grace Hopper Award, a MacArthur Foundation fellowship, the Electrical Frontier Foundation's Pioneer Award, and the Takeda Award for Social/Economic Betterment, as well as several honorary doctorates. <br /> \[taken from: [http://www.theiet.org/local/emea/europe/switzerland/stallman-2010.cfm](http://www.theiet.org/local/emea/europe/switzerland/stallman-2010.cfm) see his website at stallman.org\] Stallman enters room and hush descends immediately. Cue joke about slides and "definitely not PowerPoint". What is free software? It sw that respects your freedom. Think of free speech not free beer. A non free sw is digital colonization. It acts to divide and conquer people A program is free if you have 4 freedoms <br /> 0 - To run it as you wish <br /> 1 - Have source to edit to run as you wish <br /> 2 - To share & distribute & help others, as you wish <br /> 3 - To distribute modified, copies if you wish If sw does not obey these then it's unethical. Notice that these are not about the technical issues. The difference is an ethical, social and political distinction. The use of propriety sw is a social problem and we should aim to eliminate the problem. ie eliminate propriety sw. Goal of free sw is to make all sw free so that users are free. If you use a program without freedom 2 then you end up in a moral dilemma. If someone says "Hey, great sw. Can I get a copy?". In this case you should choose lesser of two evils, which is to violate the license and give your friend a copy. Being the lesser evil doesn't mean it's good though. When you've fully studied this dilemma what should you do? Option 1: don't have any friends! That what the proprietary debs would have you do. Option 2: don't have that sw in the first place so you don't end up in the dilemma in the first place. Note on Piracy: They attack ships. With arms. Freedom 0 - Essential so you can control your computing. No one else should have that control. Only you. There are proprietary programs that have licenses that restrict your freedom of speech (ie website software that means you cannot publish stuff disparaging to sw vendor) Freedom 1 - Being a victim of malicious sw is something that ppl are subject to all the time. For example back-doors, DRM, spyware, handcuffs. The sw is not there to serve you but is actually a prison guard. Eg in MSFT sw can install stuff on pc w/out user consent or knowledge. Once windows has installed then it's no longer your machine. Apple is no better. They've even stolen the ability to install apps. They don't even agree w free sw. Also a back-door by which Apple can delete sw installed on users machine. Even apps exist that detect Jailbreak and refuse to operate. All these are Malware. Products include: Apple iMoan, Apple iBad, Amazon Swindle - "Kindle was conceived to burn books." (riffs on Amazon taking books off devices etc) Even if devs of proprietary sw are good, they're human and make errors. ie bugs. Without freedom 1 you are a prisoner. Freedom 1 isn't enough. There too much sw and plenty of non-devs cannot edit it. That's why we need Freedom 3. To contribute to your community and spread benefits. Without this freedom what a waste it would be for people to write changes over and over. Every user can take part in Freedom 0 and 2 since it doesn't require any programming knowledge. Freedom 1 and 3 allow those who can to make improvements. With free software. Support is a free-market since everyone can study the code and master it. Hence people can get better support. Since support for proprietary sw is a monopoly, the support sucks. The four freedoms together give us democracy. These are sufficient for people to have control over the sw. Without these the sw controls the ppl. Launched free software foundation in 1983. All operating systems were proprietary hence ppl immediately lost freedom when they had to install an OS. This was an injustice. As an OS developer, he could write the OS and then legally make it free. At the time, the free sw movement had no enemies at the time. Mostly because ppl thought the job was so big that it couldn't get done. Following the basic design of UNIX made sense. Then I gave it a name which was a joke. \[digs in bag\]. GNU = Gnu Not Unix. (riffs on the name and pronunciation). History of Linux. Aside: What is a free sw license? Why do we need them? <br /> Copyright law automatically limits anything that's written so you have to explicitly grant the four freedoms. Even then there are distinctions. Eg copy-left licenses and non copy-left licenses. Specifically, user has to pass on the freedoms that have been passed on to him (copy-left). Torvalds made the Linux Kernel free under the GNU license. The name matters. Linux does not have the same views on 'free' as GNU. Yet people using Linux think that most of the ideas came from Torvalds rather than GNU. Debate on Human Rights has continued for centuries. Yet the debate on free/proprietary sw has only gone on for about 20yrs. Therefore the debate on what human rights are applicable to sw have only involved the devs, who obviously have said "none". Another problem. Now ppl have another term: Open-Source. The ideas that surround this didn't include the ethical aspects of 'free'. Easy to lose freedom if you don't fight for it. There are now distros that contain proprietary sw and are no longer free. Free distros can be found at gnu.org/distros. Why did all this happen? <br /> Because the idea of freedom wasn't important to people. They didn't appreciate it. We have to teach ppl to value freedom and demand it. Our greatest scarcity in FSF is not ppl to write sw but ppl to fight for the idea of freedoms. Freedom is now different since JavaScript in browsers means that things get installed in browser without your knowledge. 'Like' buttons even track ppl that don't use Facebook. Ppl need to be educated. Even SaaS is becoming pervasive and is worse than proprietary since the data goes elsewhere. There's no remedy for this, other than not to use it. Only a minority of things like this but need to be aware (eg GoogleDocs). Free software and Education <br /> Schools must only teach free software. It's cheaper (but should be considered secondary benefit). Free stuff from proprietary vendors is simply a drug to get them hooked. Only free sw gives ppl the opportunity to learn from code of large Programs. Even deeper reason though. For goodwill and the moral imperative of sharing knowledge. Every school from nursery to university must practice this. The issue should always be an ethical one. Biggest obstacle to free sw is social inertia. Websites for more info: <br /> Gnu.org <br /> FSF.org <br /> Defectivebydesign.org (against digital handcuffs) \[dresses up\] St Ignuseus of emacs \[riffs on emacs and free sw\]. Applause <br /> \[ends\] Sent via mobile <p class="footnote">Comment on original post: Nov 21, 2011 - <a href="http://mrhpages.blogspot.com/">human</a> said... thank u so much, This is the same lecture of richard in benghazi-libya at november 2010 :) i hope to get this lecture in a audio file </p>
Java
UTF-8
3,748
2.296875
2
[]
no_license
package com.jyw.classinfo.controller; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.jyw.classinfo.service.SyllabusInfoService; import com.jyw.model.SyllabusInfo; import com.jyw.model.SyllabusInfoCriteria; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.annotation.Resource; import java.util.List; /** * Created by XXXX on 2016-11-10. */ @Controller @RequestMapping("/syllabusinfo") public class SyllabusInfoController { @Resource private SyllabusInfoService syllabusInfoService; SyllabusInfoCriteria syllabusInfoCriteria = null; /** * 加载所有课程信息 * * @param model * @return */ @RequestMapping("/list.do") public String list(Model model,String syllabusName,@RequestParam(required = false, defaultValue = "1")int pageNum) { syllabusInfoCriteria=new SyllabusInfoCriteria(); if(syllabusName!=null){ syllabusInfoCriteria.or() .andIsUesdEqualTo("1") .andSyllabusNameLike("%" + syllabusName + "%") ; }else{ syllabusInfoCriteria.or().andIsUesdEqualTo("1"); } PageHelper.startPage(pageNum, 10); List<SyllabusInfo> syllabusInfos = syllabusInfoService.selectByExample(syllabusInfoCriteria); PageInfo page = new PageInfo(syllabusInfos); model.addAttribute("page", page); return "classinfo/syllabusinfo/syllabusinfo_list"; } /** * 根据id删除课程信息 * * @param id * @return */ @RequestMapping("/delete/{id}") public String delete(@PathVariable Integer id, Model model) { SyllabusInfo syllabusInfo=syllabusInfoService.selectByPrimaryKey(id); syllabusInfo.setIsUesd("0"); int count = syllabusInfoService.updateByPrimaryKeySelective(syllabusInfo); if (count > 0) { model.addAttribute("info", "删除成功"); } else { model.addAttribute("info", "删除失败"); } return "forward:/syllabusInfo/list"; } /** * 根据id查询课程信息 * * @param id * @param model * @return */ @RequestMapping("/selectById/{id}") public String selectById(@PathVariable Integer id, Model model) { SyllabusInfo syllabusInfo = syllabusInfoService.selectByPrimaryKey(id); model.addAttribute("syllabusInfo", syllabusInfo); return "classinfo/syllabusinfo/syllabusinfo_update"; } /** * 修改课程信息 * * @param syllabusInfo * @return */ @RequestMapping("/update") public String update(SyllabusInfo syllabusInfo, Model model) { syllabusInfo.setIsUesd("1"); int count = syllabusInfoService.updateByPrimaryKey(syllabusInfo); if (count > 0) { model.addAttribute("info", "修改成功"); } else { model.addAttribute("info", "修改失败"); } return list(model,null,1); } /** * 添加课程信息 * * @param syllabusInfo * @return */ @RequestMapping("/add") public String add(SyllabusInfo syllabusInfo, Model model) { syllabusInfo.setIsUesd("1"); int count = syllabusInfoService.insert(syllabusInfo); if (count > 0) { model.addAttribute("info", "添加成功"); } else { model.addAttribute("info", "添加失败"); } return list(model,null,1); } }
SQL
WINDOWS-1251
1,761
3.34375
3
[]
no_license
PROMPT ===================================================================================== PROMPT *** Run *** ========== Scripts /Sql/BARS/function/f_acc_branch.sql =========*** Run * PROMPT ===================================================================================== CREATE OR REPLACE FUNCTION BARS.F_ACC_BRANCH (p_acc accounts.acc%type) return varchar2 as l_branch accounts.branch%type; begin /* , . " " select l.* from bars.sparam_list l where l.semantic=' i' and l.tabname='ACCOUNTSW' and l.nsiname='V_TARIF_SCHEME_ACCBRANCH'; */ if p_acc = 0 then l_branch := sys_context('bars_context','user_branch'); else begin select branch into l_branch from accounts where acc=to_number(p_acc) and nbs is not null; exception when no_data_found then l_branch := sys_context('bars_context','user_branch'); end; end if; return l_branch; end; / show err; PROMPT *** Create grants F_ACC_BRANCH *** grant EXECUTE on F_ACC_BRANCH to BARS_ACCESS_DEFROLE; PROMPT ===================================================================================== PROMPT *** End *** ========== Scripts /Sql/BARS/function/f_acc_branch.sql =========*** End * PROMPT =====================================================================================
PHP
UTF-8
21,694
3.078125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Laura 4 * Date: 12/7/2015 * Time: 2:16 PM */ /** * @param $connection object the mysql connection object from db-functions.php * @param $email * @return mixed */ function getUserInfo($connection, $studentID) { $firstname = ""; $lastname = ""; $country = ""; $sql = "SELECT firstname,lastname,country,currentYear FROM studentTable WHERE studentID = ?"; $preparedStatement = $connection->prepare($sql) or die("error: ".$connection->error); $preparedStatement->bind_param("s",$studentID); $preparedStatement->execute(); $preparedStatement->bind_result($firstname,$lastname,$country,$currentYear); $list = array(); while($preparedStatement->fetch()) { array_push($list,$firstname,$lastname,$country,$currentYear); } return $list; } /** * @param $connection object the mysql connection object from db-functions.php * @param $list * @return mixed */ function setUserInfo($connection, $list) { //$list is a key-value array containing the columns to be updated for each user $sql = ""; $preparedStatement = $connection->prepare($sql) or die("error: ".$connection->error); //can I have multiple bind_param statements? return $preparedStatement->execute(); } /* * @param object $connection a mysqli connection object * @param int $id a student id * @return true or false depending on whether the user has done the first run procedure */ function isFirstRunComplete($connection, $id) { $firstRunComplete = NULL; $sql = "SELECT firstRunCompelete FROM studentTable WHERE studentID = ?"; $preparedStatement = $connection->prepare($sql) or die("error: ".$connection->error); $preparedStatement->bind_param("i",$id); $preparedStatement->execute(); $preparedStatement->bind_result($firstRunComplete); while($preparedStatement->fetch()) { if ($firstRunComplete == 1) { return true; } } return false; } /* * @param object $connection a mysqli connection object * @param int $value the new value for firstRunComplete. Must be 0 or 1. * @return false if an invalid value is passed in, else true */ function setFirstRunValue($connection,$value,$id) { if(($value!=1) && ($value!=0)) { return false; } $sql = "UPDATE studentTable SET firstRunComplete = ? WHERE studentID = ?"; $preparedStatement = $connection->prepare($sql) or die("error: ".$connection->error); $preparedStatement->bind_param("ii",$value,$id); $preparedStatement->execute(); return true; } function getPathInfo($connection) { $sql = "SELECT pathName,currentLevel,maxLevel,progress FROM pathTable WHERE studentID = ?"; $preparedStatement = $connection->prepare($sql); $preparedStatement->bind_param("i", $_SESSION['studentID']); $preparedStatement->execute(); $preparedStatement->bind_result($pathName, $currentLevel, $maxLevel,$progress); $pathOutput = array(); while ($preparedStatement->fetch()) { $row = array(); array_push($row, $pathName); array_push($row, $currentLevel); array_push($row, $maxLevel); $progress = str_split($progress); array_push($row, $progress); array_push($pathOutput, $row); } return $pathOutput; } /* function getGCSEs($connection,$country="",$id=0) { $gcseID = NULL; $gcseName = NULL; $gcseCode = NULL; if($country != "") { $sql = "SELECT g.gcseID, g.gcseName,g.gcseCode FROM studentGCSETable AS s, gcseTable AS g WHERE gcseCountryList LIKE '%" . substr($country,0,1) . "%'"; $preparedStatement = $connection->prepare($sql) or die($connection->error); } else { $sql = "SELECT g.gcseID, g.gcseName, g.gcseCode FROM studentGCSETable s, gcseTable g WHERE s.studentID = ? AND s.gcseID = g.gcseID"; $preparedStatement = $connection->prepare($sql) or die($connection->error); $preparedStatement->bind_param("i",$id); } $preparedStatement->execute(); $preparedStatement->bind_result($gcseID, $gcseName, $gcseCode); $list = array(); while($preparedStatement->fetch()) { $row = array(); array_push($row,$gcseID); array_push($row,$gcseName); array_push($row,$gcseCode); // $row = $gcseID . "|" . $gcseName . "|" . $gcseCode; array_push($list,$row); } return $list; }*/ function getAllGCSEs($connection, $country) { $gcseID = NULL; $gcseName = NULL; $initial = substr($country,0,1); $sql = "SELECT gcseID, gcseName FROM gcseTable WHERE gcseCountryList LIKE '%" . $initial . "%'"; $preparedStatement = $connection->prepare($sql) or die("error: ".$connection->error); $preparedStatement->execute(); $preparedStatement->bind_result($gcseID, $gcseName); $list = array(); while($preparedStatement->fetch()) { $row = $gcseID . "|" . $gcseName; array_push($list,$row); } return $list; } /** * @param $connection * @param $id * @return array */ function getMyGCSEs($connection, $id) { $name = NULL; $sql = "SELECT DISTINCT g.gcseID, g.gcseName FROM studentGCSETable AS s, gcseTable AS g WHERE s.studentID = ? AND s.gcseID = g.gcseID"; $preparedStatement = $connection->prepare($sql) or die($connection->error); $preparedStatement->bind_param("i",$id); $preparedStatement->execute(); $preparedStatement->bind_result($id,$name); $list = array(); while($preparedStatement->fetch()) { $subArray = array(); array_push($subArray,$id); array_push($subArray,$name); array_push($list,$subArray); } return $list; } function getOtherGCSEs($connection, $id) { $gcseID = null; $sql = "SELECT gcseID FROM gcseTable WHERE gcseID NOT IN (SELECT gcseID FROM studentGCSETable WHERE studentID = ?)"; $preparedStatement = $connection->prepare($sql) or die("error2: ".$connection->error); $preparedStatement->bind_param("i",$id); $preparedStatement->execute(); $preparedStatement->bind_result($gcseID); $list = array(); while($preparedStatement->fetch()) { array_push($list,$gcseID); } return $list; } /* function addGCSEs($connection, $list) { $sql = "INSERT INTO pathTable (JACSCode,pathName,gcseProgress) VALUES (?,?,0) ON DUPLICATE KEY UPDATE gcseProgress=0"; $preparedStatement = $connection->prepare($sql) or die($connection->error); for($i=0;$i<count($list);$i++) { $listVal = explode("|",$list[$i]); $preparedStatement->bind_param("ss",$listVal[0],$listVal[1]); $preparedStatement->execute() or die($connection->error); } } function updateGCSE($connection,$code,$newValue) { $sql = "UPDATE pathTable SET gcseProgress=? WHERE JACSCode=?"; $preparedStatement = $connection->prepare($sql); $preparedStatement->bind_param("is",$newValue,$code); $preparedStatement->execute(); }*/ /* * part of updateGCSE() now function removeGCSEs($connection, $list) { $sql = "DELETE FROM studentGCSETable WHERE studentID = ? AND gcseID = ?"; $preparedStatement = $connection->prepare($sql) or die($connection->error); for($i=0;$i<count($list);$i++) { $preparedStatement->bind_param("ii",$_SESSION['studentID'],$list[$i]); $preparedStatement->execute(); } }*/ function getAllALevels($connection,$country) { $aLevelID = NULL; $aLevelName = NULL; $initial = substr($country,0,1); $sql = "SELECT alevelID, alevelName FROM aLevelTable WHERE alevelCountryList LIKE '%" . $initial . "%'"; $preparedStatement = $connection->prepare($sql) or die("error: ".$connection->error); $preparedStatement->execute(); $preparedStatement->bind_result($aLevelID, $aLevelName); $list = array(); while($preparedStatement->fetch()) { $row = $aLevelID . "|" . $aLevelName; array_push($list,$row); } return $list; } function getMyALevels($connection, $id) { $name = NULL; $sql = "SELECT DISTINCT a.aLevelID, a.aLevelName FROM studentALevelTable AS s, aLevelTable AS a WHERE s.studentID = ? AND s.aLevelID = a.aLevelID"; $preparedStatement = $connection->prepare($sql) or die($connection->error); $preparedStatement->bind_param("i",$id); $preparedStatement->execute(); $preparedStatement->bind_result($id, $name); $list = array(); while($preparedStatement->fetch()) { $subArray = array(); array_push($subArray,$id); array_push($subArray,$name); array_push($list,$subArray); } return $list; } function getOtherALevels($connection, $id) { $aLevelID = null; $sql = "SELECT aLevelID FROM aLevelTable WHERE aLevelID NOT IN (SELECT aLevelID FROM studentALevelTable WHERE studentID = ?)"; $preparedStatement = $connection->prepare($sql) or die("error2: ".$connection->error); $preparedStatement->bind_param("i",$id); $preparedStatement->execute(); $preparedStatement->bind_result($aLevelID); $list = array(); while($preparedStatement->fetch()) { array_push($list,$aLevelID); } return $list; } function addALevels($connection,$list) { $sql = "INSERT INTO studentALevelTable (studentID,aLevelID) VALUES(?,?)"; $preparedStatement = $connection->prepare($sql) or die($connection->error); for($i=0;$i<count($list);$i++) { $listVal = $list[$i]; $preparedStatement->bind_param("ii",$_SESSION['studentID'],$listVal) or die("error1"); $preparedStatement->execute() or die($connection->error); } } function removeALevels($connection,$list) { echo "userfunctions:179 removeALevels()"; $sql = "DELETE FROM studentALevelTable WHERE studentID = ? AND aLevelID = ?"; $preparedStatement = $connection->prepare($sql) or die($connection->error); for($i=0;$i<count($list);$i++) { $preparedStatement->bind_param("ii",$_SESSION['studentID'],$list[$i]); $preparedStatement->execute(); } } //do all interests appear in myInterests or OtherInterests? function getOtherInterests($connection, $id) //gets all interests not associated with the current student { $interestID = NULL; $sql = "SELECT interestID FROM interestTable WHERE interestID NOT IN " . "(SELECT interestID FROM studentInterestsTable WHERE studentID = " . $id . ")"; $preparedStatement = $connection->prepare($sql) or die("error: ".$connection->error); $preparedStatement->execute(); $preparedStatement->bind_result($interestID); $list = array(); while($preparedStatement->fetch()) { array_push($list,$interestID); } return $list; } class career { private $id; private $name; private $interestList; private $description; function getID() { return $this->id; } function getName() { return $this->name; } function getInterestList() { return $this->interestList; } function getDescription() { return $this->description; } function setID($id) { $this->id = $id; } function setName($name) { $this->name = $name; } function setInterestList($interestList) { $this->interestList; } function setDescription($description) { $this->description; } } /* * gets all information about all careers or about all careers associated with a student id * * @param object $connection a mysql connection object * @param int $studentID optional. the student's id * @return array a 2d array of strings */ function getCareerInfo($connection,$studentID=-1) { $id = NULL; $careerName = NULL; $interestList = NULL; $careerDescription = NULL; if($studentID==-1) { $sql = "SELECT * FROM careersTable"; $preparedStatement = $connection->prepare($sql) or die($connection->error); } else { $sql = "SELECT * FROM careersTable WHERE id = (SELECT careerID FROM studentTable WHERE studentID = ?)"; $preparedStatement = $connection->prepare($sql) or die($connection->error); $preparedStatement->bind_param("i",$studentID); } $preparedStatement->execute(); $preparedStatement->bind_result($id,$careerName,$interestList, $careerDescription); $careerArray = Array(); while($preparedStatement->fetch()) { $row = Array(); array_push($row,$id); array_push($row,$careerName); array_push($row,$careerDescription); array_push($row,$interestList); array_push($careerArray,$row); } return $careerArray; } function getMyCareerInfo($connection,$studentID) { $careerName = NULL; $sql = "SELECT careerName FROM careersTable WHERE id = (SELECT careerID FROM studentTable WHERE id = ?)"; $preparedStatement = $connection->prepare($sql) or die($connection->error); $preparedStatement->bind_param("i",$studentID); $preparedStatement->execute(); $preparedStatement->bind_result($careerName); while($preparedStatement->fetch()) { $_SESSION['careerName'] = $careerName; } } function getCareerNameByID($connection,$id) { $careerName = NULL; $sql = "SELECT careerName FROM careersTable WHERE id = ?"; $preparedStatement = $connection->prepare($sql) or die($connection->error); $preparedStatement->bind_param("i",$id); $preparedStatement->execute(); $preparedStatement->bind_result($careerName); while($preparedStatement->fetch()) { return $careerName; } } /** * @param $connection * @param int $studentID * @return array */ function getCareerInterests($connection, $studentID = -1) //returns a 2d array of interests for each career { if($studentID == -1) { //split this into two sections so the proper info will be passed to $careerInterestList on firsturn.php:33 $sql = "SELECT careerName, interestList, careerDescription FROM careersTable"; $preparedStatement = $connection->prepare($sql) or die($connection->error); $preparedStatement->execute(); $preparedStatement->bind_result($careerName,$interestList, $careerDescription); $careerInterestList = array(); while ($preparedStatement->fetch()) { $row = array(); array_push($row,$careerName); array_push($row,$interestList); array_push($row,$careerDescription); array_push($careerInterestList,$row); } return $careerInterestList; } else { //split this into two sections so the proper info will be passed to $careerInterestList on firsturn.php:33 $sql = "SELECT interestList FROM careersTable WHERE studentID = ?"; $preparedStatement = $connection->prepare($sql) or die($connection->error); $preparedStatement->bind_param("i",$studentID); $preparedStatement->execute(); $preparedStatement->bind_result($interests); while ($preparedStatement->fetch()) { array_push($careerInterestList, explode(",", $interests)); } return $careerInterestList; } } /* function getCareerInfo($connection) { $sql = "SELECT * FROM careersTable"; $preparedStatement = $connection->prepare($sql); $preparedStatement->execute(); $preparedStatement->bind_result($id, $careerName, $interestList, $careerDescription); $careerArray = Array(); while($preparedStatement->fetch()) { $career = new career(); $career->setID($id); $career->setName($careerName); $career->setInterestList($interestList); $career->setDescription($careerDescription); array_push($careerArray,$career); } $_SESSION['careerArray'] = $careerArray; }*/ function getCareerDescriptions($connection) { $description = NULL; $sql = "SELECT careerDescription FROM careersTable"; $preparedStatement = $connection->prepare($sql) or die($connection->error); $preparedStatement->execute(); $preparedStatement->bind_result($description); $careerDescriptionList = array(); while($preparedStatement->fetch()) { array_push($careerDescriptionList,$description); } return $careerDescriptionList; } /** * @param $connection * @return array */ function getCareerIDs($connection) { $id = NULL; $sql = "SELECT id FROM careersTable"; $preparedStatement = $connection->prepare($sql) or die($connection->error); $preparedStatement->execute(); $preparedStatement->bind_result($id); $careerIDList = array(); while($preparedStatement->fetch()) { array_push($careerIDList,$id); } return $careerIDList; } function getCareerNames($connection) { $name = NULL; $sql = "SELECT careerName FROM careersTable"; $preparedStatement = $connection->prepare($sql) or die($connection->error); $preparedStatement->execute(); $preparedStatement->bind_result($name); $careerNameList = array(); $careerInterestList = array(); while($preparedStatement->fetch()) { array_push($careerNameList,$name); } return $careerNameList; } function setCareer($connection, $careerID, $studentID) { $sql = "UPDATE studentTable SET careerID = ? WHERE studentID = ?"; $preparedStatement = $connection->prepare($sql); $preparedStatement->bind_param("ii",$careerID,$studentID); $preparedStatement->execute(); } function intCheck($array1,$array2) { $arrayIntersection = array_intersect($array1,$array2); return (count($arrayIntersection)/count($array1))*100; } //interests function getInterests($connection,$id=-1) { $interestID = NULL; $interestName = NULL; $interestCategory = NULL; if($id==-1) { $sql = "SELECT interestID, interestName, interestCategory FROM interestTable ORDER BY interestCategory"; $preparedStatement = $connection->prepare($sql) or die("error: " . $connection->error); $preparedStatement->execute() or die("execution error"); $preparedStatement->bind_result($interestID, $interestName, $interestCategory) or die($connection->error); $list = array(); while ($preparedStatement->fetch()) { $row = array(); array_push($row,$interestID); array_push($row,$interestName); array_push($row,$interestCategory); array_push($list,$row); } } else { $sql = "SELECT interestID, interestName, interestCategory FROM interestTable WHERE interestID IN (SELECT interestID FROM studentInterestsTable WHERE studentID = ?)"; $preparedStatement = $connection->prepare($sql) or die("getInterests() default error ".$connection->error); $preparedStatement->bind_param("i",$_SESSION['studentID']); $preparedStatement->execute() or die("execution error"); $preparedStatement->bind_result($interestID,$interestName,$interestCategory) or die("e".$connection->error); $list = array(); while ($preparedStatement->fetch()) { $row = array(); array_push($row,$interestID); array_push($row,$interestName); array_push($row,$interestCategory); array_push($list,$row); } } return $list; } /* function getAllInterests($connection) { //gets IDs and names from the INterestTable $sql = "SELECT interestID, interestName, interestCategory FROM interestTable ORDER BY interestCategory"; $preparedStatement = $connection->prepare($sql) or die("error: " . $connection->error); $preparedStatement->execute() or die("execution error"); $preparedStatement->bind_result($interestID, $interestName, $interestCategory) or die("result error"); $list = array(); while ($preparedStatement->fetch()) { $row = $interestID . "|" . $interestName . "|" . $interestCategory; array_push($list,$row); } return $list; } function getMyInterests($connection, $id) { //$sql = "SELECT interestList FROM studentTable WHERE studentID = $id"; $sql = "SELECT interestID, interestName FROM interestTable WHERE interestID IN (SELECT * FROM studentInterestTable WHERE studentID = ?)"; $preparedStatement = $connection->prepare($sql) or die($connection->error); $preparedStatement->bind_param("i",$_SESSION['studentID']); $preparedStatement->execute(); $preparedStatement->bind_result($interestID, $interestName); $studentInterestList = array(); while ($preparedStatement->fetch()) { $row = array(); array_push($row,$interestID); array_push($row,$interestName); array_push($studentInterestList,$row); } return $studentInterestList; } */ /** * @param $connection * @param $list * @param $id */ function addInterests($connection, $list, $id) { $sql = "INSERT INTO studentInterestsTable (studentID,interestID) VALUES(?,?)"; $preparedStatement = $connection->prepare($sql) or die($connection->error); for($i=0;$i<count($list);$i++) { $preparedStatement->bind_param("ii", $id, $list[$i]); $preparedStatement->execute(); //will silently fail if studentID/interestID combo already in db } } function removeInterests($connection,$list) { $sql = "DELETE FROM studentInterestsTable WHERE studentID = ? AND interestID = ?"; $preparedStatement = $connection->prepare($sql) or die($connection->error); for($i=0;$i<count($list);$i++) { $preparedStatement->bind_param("ii",$_SESSION['studentID'],$list[$i]); $preparedStatement->execute(); } }
C
UTF-8
332
3.375
3
[]
no_license
#include "headers.h" void stenv(char** arg, int noa) { if(noa==2) setenv(arg[1]," ",2); else if(noa==3) setenv(arg[1],arg[2],2); else printf("Number of arguments must be 2 or 3\n"); } void unstenv(char** arg, int noa) { if(noa==1) printf("No arguments given"); else for(int i=0;i<noa-1;i++) unsetenv(arg[i+1]); }
Java
UTF-8
35,559
2.1875
2
[ "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "LGPL-2.1-or-later", "CC0-1.0", "BSD-3-Clause", "UPL-1.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-generic-cla" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. package com.azure.resourcemanager.resources.fluentcore.dag; import com.azure.core.util.logging.ClientLogger; import com.azure.resourcemanager.resources.fluentcore.model.Indexable; import com.azure.resourcemanager.resources.fluentcore.utils.ResourceManagerUtils; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; /** * Type representing a group of task entries with dependencies between them. Initially a task * group will have only one task entry known as root task entry, then more entries can be * added by taking dependency on other task groups or adding "post-run" task group dependents. * <p> * The method {@link TaskGroup#invokeAsync(InvocationContext)} ()} kick-off invocation of tasks * in the group, task are invoked in topological sorted order. * <p> * {@link TaskGroup#addDependencyTaskGroup(TaskGroup)}: A task group "A" can take dependency on * another task group "B" through this method e.g. `A.addDependencyTaskGroup(B)` indicates that * completion of tasks in the dependency task group "B" is required before the invocation of root * task in group "A". A.invokeAsync(cxt) will ensure this order. * <p> * {@link TaskGroup#addPostRunDependentTaskGroup(TaskGroup)}: there are scenarios where a subset * of dependent task groups say "H", "I" may required to run after the invocation of a task group * "K" when K.invokeAsync(cxt) is called. Such special dependents can be added via * K.addPostRunDependentTaskGroup(H) and K.addPostRunDependentTaskGroup(I). * <p> * The result produced by the tasks in the group are of type {@link Indexable}. */ public class TaskGroup extends DAGraph<TaskItem, TaskGroupEntry<TaskItem>> implements Indexable { /** * The root task in this task group. */ private final TaskGroupEntry<TaskItem> rootTaskEntry; /** * Task group termination strategy to be used once any task in the group error-ed. */ private TaskGroupTerminateOnErrorStrategy taskGroupTerminateOnErrorStrategy; /** * Flag indicating whether this group is marked as cancelled or not. This flag will be used only * when group's terminate on error strategy is set as * {@link TaskGroupTerminateOnErrorStrategy#TERMINATE_ON_IN_PROGRESS_TASKS_COMPLETION}. * Effect of setting this flag can be think as broadcasting a cancellation signal to tasks those * are yet to invoke. */ private final AtomicBoolean isGroupCancelled; /** * The shared exception object used to indicate that a task is not invoked since the group * is marked as cancelled i.e. {@link this#isGroupCancelled} is set. */ private final TaskCancelledException taskCancelledException = new TaskCancelledException(); /** * The helper to operate on proxy TaskGroup of this TaskGroup for supporting dependents marked * for post run. */ protected ProxyTaskGroupWrapper proxyTaskGroupWrapper; private final ClientLogger logger = new ClientLogger(this.getClass()); /** * Creates TaskGroup. * * @param rootTaskEntry the entry holding root task */ private TaskGroup(TaskGroupEntry<TaskItem> rootTaskEntry) { super(rootTaskEntry); this.isGroupCancelled = new AtomicBoolean(false); this.rootTaskEntry = rootTaskEntry; this.proxyTaskGroupWrapper = new ProxyTaskGroupWrapper(this); } /** * Creates TaskGroup. * * @param rootTaskItemId the id of the root task in the group * @param rootTaskItem the root task */ public TaskGroup(String rootTaskItemId, TaskItem rootTaskItem) { this(new TaskGroupEntry<TaskItem>(rootTaskItemId, rootTaskItem)); } /** * Creates TaskGroup. * * @param rootTaskItem the root task */ public TaskGroup(IndexableTaskItem rootTaskItem) { this(new TaskGroupEntry<TaskItem>(rootTaskItem.key(), rootTaskItem)); } /** * @return the key of this task group, which is same as key of the root entry in the group */ @Override public String key() { return this.rootTaskEntry.key(); } /** * Retrieve the result produced by a task with the given id in the group. * <p> * This method can be used to retrieve the result of invocation of both dependency * and "post-run" dependent tasks. If task with the given id does not exists then * IllegalArgumentException exception will be thrown. * * @param taskId the task item id * @return the task result, null will be returned if task has not yet been invoked */ public Indexable taskResult(String taskId) { TaskGroupEntry<TaskItem> taskGroupEntry = super.getNode(taskId); if (taskGroupEntry != null) { return taskGroupEntry.taskResult(); } if (!this.proxyTaskGroupWrapper.isActive()) { throw logger.logExceptionAsError( new IllegalArgumentException("A dependency task with id '" + taskId + "' is not found")); } taskGroupEntry = this.proxyTaskGroupWrapper.proxyTaskGroup.getNode(taskId); if (taskGroupEntry != null) { return taskGroupEntry.taskResult(); } throw logger.logExceptionAsError(new IllegalArgumentException( "A dependency task or 'post-run' dependent task with with id '" + taskId + "' not found")); } /** * Checks this TaskGroup depends on the given TaskGroup. * * @param taskGroup the TaskGroup to check * @return true if TaskGroup is depends on the given TaskGroup */ public boolean dependsOn(TaskGroup taskGroup) { return this.nodeTable.containsKey(taskGroup.root().key()); } /** * @return the root task entry in the group. */ protected TaskGroupEntry<TaskItem> root() { return this.rootTaskEntry; } /** * Mark root of this task task group depends on the given TaskItem. * This ensure this task group's root get picked for execution only after the completion * of invocation of provided TaskItem. * * @param dependencyTaskItem the task item that this task group depends on * @return the key of the dependency */ public String addDependency(FunctionalTaskItem dependencyTaskItem) { IndexableTaskItem dependency = IndexableTaskItem.create(dependencyTaskItem); this.addDependency(dependency); return dependency.key(); } /** * Mark root of this task task group depends on the given item's taskGroup. * This ensure this task group's root get picked for execution only after the completion * of invocation of provided TaskItem. * * @param hasTaskGroup an item with taskGroup that this task group depends on */ public void addDependency(TaskGroup.HasTaskGroup hasTaskGroup) { this.addDependencyTaskGroup(hasTaskGroup.taskGroup()); } /** * Mark root of this task task group depends on the given task group's root. * This ensure this task group's root get picked for execution only after the completion * of all tasks in the given group. * * @param dependencyTaskGroup the task group that this task group depends on */ public void addDependencyTaskGroup(TaskGroup dependencyTaskGroup) { if (dependencyTaskGroup.proxyTaskGroupWrapper.isActive()) { dependencyTaskGroup.proxyTaskGroupWrapper.addDependentTaskGroup(this); } else { DAGraph<TaskItem, TaskGroupEntry<TaskItem>> dependencyGraph = dependencyTaskGroup; super.addDependencyGraph(dependencyGraph); } } /** * Mark the given TaskItem depends on this taskGroup. * * @param dependentTaskItem the task item that depends on this task group * @return key to be used as parameter to taskResult(string) method to retrieve result of * invocation of given task item. */ public String addPostRunDependent(FunctionalTaskItem dependentTaskItem) { IndexableTaskItem taskItem = IndexableTaskItem.create(dependentTaskItem); this.addPostRunDependent(taskItem); return taskItem.key(); } /** * Mark the given TaskItem depends on this taskGroup. * * @param dependentTaskItem the task item that depends on this task group * @param internalContext the internal runtime context * @return key to be used as parameter to taskResult(string) method to retrieve result of * invocation of given task item. */ public String addPostRunDependent( FunctionalTaskItem dependentTaskItem, ResourceManagerUtils.InternalRuntimeContext internalContext) { IndexableTaskItem taskItem = IndexableTaskItem.create(dependentTaskItem, internalContext); this.addPostRunDependent(taskItem); return taskItem.key(); } /** * Mark the given item with taskGroup depends on this taskGroup. * * @param hasTaskGroup an item with as task group that depends on this task group */ public void addPostRunDependent(TaskGroup.HasTaskGroup hasTaskGroup) { this.addPostRunDependentTaskGroup(hasTaskGroup.taskGroup()); } /** * Mark root of the given task group depends on this task group's root. * This ensure given task group's root get picked for invocation only after the completion * of all tasks in this group. Calling invokeAsync(cxt) will run the tasks in the given * dependent task group as well. * * @param dependentTaskGroup the task group depends on this task group */ public void addPostRunDependentTaskGroup(TaskGroup dependentTaskGroup) { this.proxyTaskGroupWrapper.addPostRunTaskGroupForActualTaskGroup(dependentTaskGroup); } /** * Invokes tasks in the group. * It is not guaranteed to return indexable in topological order. * * @param context group level shared context that need be passed to invokeAsync(cxt) * method of each task item in the group when it is selected for invocation. * @return an observable that emits the result of tasks in the order they finishes. */ public Flux<Indexable> invokeAsync(final InvocationContext context) { return Flux.defer(() -> { if (proxyTaskGroupWrapper.isActive()) { return proxyTaskGroupWrapper.taskGroup().invokeInternAsync(context, true, null); } else { Set<String> processedKeys = runBeforeGroupInvoke(null); if (proxyTaskGroupWrapper.isActive()) { // If proxy got activated after 'runBeforeGroupInvoke()' stage due to the addition of direct // 'postRunDependent's then delegate group invocation to proxy group. // return proxyTaskGroupWrapper.taskGroup().invokeInternAsync(context, true, processedKeys); } else { return invokeInternAsync(context, false, null); } } }); } /** * Invokes tasks in the group. * * @return the root result of task group. */ public Mono<Indexable> invokeAsync() { return invokeAsync(this.newInvocationContext()) .then(Mono.defer(() -> { if (proxyTaskGroupWrapper.isActive()) { return Mono.just(proxyTaskGroupWrapper.taskGroup().root().taskResult()); } return Mono.just(root().taskResult()); })); } /** * Invokes dependency tasks in the group, but not. * * @param context group level shared context that need be passed to invokeAsync(cxt) * method of each task item in the group when it is selected for invocation. * @return an observable that emits the result of tasks in the order they finishes. */ public Flux<Indexable> invokeDependencyAsync(final InvocationContext context) { context.put(TaskGroup.InvocationContext.KEY_SKIP_TASKS, Collections.singleton(this.key())); return Flux.defer(() -> { if (proxyTaskGroupWrapper.isActive()) { return Flux.error(new IllegalStateException("postRunDependent is not supported")); } else { Set<String> processedKeys = runBeforeGroupInvoke(null); if (proxyTaskGroupWrapper.isActive()) { return Flux.error(new IllegalStateException("postRunDependent is not supported")); } else { return invokeInternAsync(context, false, null); } } }); } /** * Invokes tasks in the group. * * @param context group level shared context that need be passed to invokeAsync(cxt) * method of each task item in the group when it is selected for invocation. * @param shouldRunBeforeGroupInvoke indicate whether to run the 'beforeGroupInvoke' method * of each tasks before invoking them * @param skipBeforeGroupInvoke the tasks keys for which 'beforeGroupInvoke' should not be called * before invoking them * @return an observable that emits the result of tasks in the order they finishes. */ private Flux<Indexable> invokeInternAsync(final InvocationContext context, final boolean shouldRunBeforeGroupInvoke, final Set<String> skipBeforeGroupInvoke) { if (!isPreparer()) { return Flux.error(new IllegalStateException( "invokeInternAsync(cxt) can be called only from root TaskGroup")); } this.taskGroupTerminateOnErrorStrategy = context.terminateOnErrorStrategy(); if (shouldRunBeforeGroupInvoke) { // Prepare tasks and queue the ready tasks (terminal tasks with no dependencies) // this.runBeforeGroupInvoke(skipBeforeGroupInvoke); } // Runs the ready tasks concurrently // return this.invokeReadyTasksAsync(context); } /** * Run 'beforeGroupInvoke' method of the tasks in this group. The tasks can use beforeGroupInvoke() * method to add additional dependencies or dependents. * * @param skip the keys of the tasks that are previously processed hence they must be skipped * @return the keys of all the tasks those are processed (including previously processed items in skip param) */ private Set<String> runBeforeGroupInvoke(final Set<String> skip) { HashSet<String> processedEntryKeys = new HashSet<>(); if (skip != null) { processedEntryKeys.addAll(skip); } List<TaskGroupEntry<TaskItem>> entries = this.entriesSnapshot(); boolean hasMoreToProcess; // Invokes 'beforeGroupInvoke' on a subset of non-processed tasks in the group. // Initially processing is pending on all task items. do { hasMoreToProcess = false; for (TaskGroupEntry<TaskItem> entry : entries) { if (!processedEntryKeys.contains(entry.key())) { entry.data().beforeGroupInvoke(); processedEntryKeys.add(entry.key()); } } int prevSize = entries.size(); entries = this.entriesSnapshot(); if (entries.size() > prevSize) { // If new task dependencies/dependents added in 'beforeGroupInvoke' then // set the flag which indicates another pass is required to 'prepare' new // task items hasMoreToProcess = true; } } while (hasMoreToProcess); // Run another pass if new dependencies/dependents were added in this pass super.prepareForEnumeration(); return processedEntryKeys; } /** * @return list with current task entries in this task group */ private List<TaskGroupEntry<TaskItem>> entriesSnapshot() { List<TaskGroupEntry<TaskItem>> entries = new ArrayList<>(); super.prepareForEnumeration(); for (TaskGroupEntry<TaskItem> current = super.getNext(); current != null; current = super.getNext()) { entries.add(current); super.reportCompletion(current); } return entries; } /** * Invokes the ready tasks. * * @param context group level shared context that need be passed to * {@link TaskGroupEntry#invokeTaskAsync(boolean, InvocationContext)} * method of each entry in the group when it is selected for execution * @return a {@link Flux} that emits the result of tasks in the order they finishes. */ // Due to it takes approximate 3ms in flux for returning, it cannot be guaranteed to return in topological order. // One simply fix for guaranteeing the last element could be https://github.com/Azure/azure-sdk-for-java/pull/15074 @SuppressWarnings({"unchecked", "rawtypes"}) private Flux<Indexable> invokeReadyTasksAsync(final InvocationContext context) { TaskGroupEntry<TaskItem> readyTaskEntry = super.getNext(); final List<Flux<Indexable>> observables = new ArrayList<>(); // Enumerate the ready tasks (those with dependencies resolved) and kickoff them concurrently // while (readyTaskEntry != null) { final TaskGroupEntry<TaskItem> currentEntry = readyTaskEntry; final TaskItem currentTaskItem = currentEntry.data(); if (currentTaskItem instanceof ProxyTaskItem) { observables.add(invokeAfterPostRunAsync(currentEntry, context)); } else { observables.add(invokeTaskAsync(currentEntry, context)); } readyTaskEntry = super.getNext(); } return Flux.mergeDelayError(32, observables.toArray(new Flux[0])); } /** * Invokes the task stored in the given entry. * <p> * if the task cannot be invoked because the group marked as cancelled then an observable * that emit {@link TaskCancelledException} will be returned. * * @param entry the entry holding task * @param context a group level shared context that is passed to {@link TaskItem#invokeAsync(InvocationContext)} * method of the task item this entry wraps. * @return an observable that emits result of task in the given entry and result of subset of tasks which gets * scheduled after this task. */ private Flux<Indexable> invokeTaskAsync(final TaskGroupEntry<TaskItem> entry, final InvocationContext context) { return Flux.defer(() -> { if (isGroupCancelled.get()) { // One or more tasks are in faulted state, though this task MAYBE invoked if it does not // have faulted tasks as transitive dependencies, we won't do it since group is cancelled // due to termination strategy TERMINATE_ON_IN_PROGRESS_TASKS_COMPLETION. // return processFaultedTaskAsync(entry, taskCancelledException, context); } else { // Any cached result will be ignored for root resource // boolean ignoreCachedResult = isRootEntry(entry) || (entry.proxy() != null && isRootEntry(entry.proxy())); Mono<Indexable> taskObservable; Object skipTasks = context.get(InvocationContext.KEY_SKIP_TASKS); if (skipTasks instanceof Set && ((Set) skipTasks).contains(entry.key())) { taskObservable = Mono.just(new VoidIndexable(entry.key())); } else { taskObservable = entry.invokeTaskAsync(ignoreCachedResult, context); } return taskObservable.flatMapMany((indexable) -> Flux.just(indexable), (throwable) -> processFaultedTaskAsync(entry, throwable, context), () -> processCompletedTaskAsync(entry, context)); } }); } /** * Invokes the {@link TaskItem#invokeAfterPostRunAsync(boolean)} method of an actual TaskItem * if the given entry holds a ProxyTaskItem. * * @param entry the entry holding a ProxyTaskItem * @param context a group level shared context * @return An Observable that represents asynchronous work started by * {@link TaskItem#invokeAfterPostRunAsync(boolean)} method of actual TaskItem and result of subset * of tasks which gets scheduled after proxy task. If group was not in faulted state and * {@link TaskItem#invokeAfterPostRunAsync(boolean)} emits no error then stream also includes * result produced by actual TaskItem. */ private Flux<Indexable> invokeAfterPostRunAsync(final TaskGroupEntry<TaskItem> entry, final InvocationContext context) { return Flux.defer(() -> { final ProxyTaskItem proxyTaskItem = (ProxyTaskItem) entry.data(); if (proxyTaskItem == null) { return Flux.empty(); } final boolean isFaulted = entry.hasFaultedDescentDependencyTasks() || isGroupCancelled.get(); return proxyTaskItem.invokeAfterPostRunAsync(isFaulted) .flatMapMany(indexable -> Flux.error( new IllegalStateException("This onNext should never be called")), (error) -> processFaultedTaskAsync(entry, error, context), () -> { if (isFaulted) { if (entry.hasFaultedDescentDependencyTasks()) { return processFaultedTaskAsync(entry, new ErroredDependencyTaskException(), context); } else { return processFaultedTaskAsync(entry, taskCancelledException, context); } } else { return Flux.concat(Flux.just(proxyTaskItem.result()), processCompletedTaskAsync(entry, context)); } }); }); } /** * Handles successful completion of a task. * <p> * If the task is not root (terminal) task then this kickoff execution of next set of ready tasks * * @param completedEntry the entry holding completed task * @param context the context object shared across all the task entries in this group during execution * @return an observable represents asynchronous operation in the next stage */ private Flux<Indexable> processCompletedTaskAsync(final TaskGroupEntry<TaskItem> completedEntry, final InvocationContext context) { reportCompletion(completedEntry); if (isRootEntry(completedEntry)) { return Flux.empty(); } else { return invokeReadyTasksAsync(context); } } /** * Handles a faulted task. * * @param faultedEntry the entry holding faulted task * @param throwable the reason for fault * @param context the context object shared across all the task entries in this group during execution * @return an observable represents asynchronous operation in the next stage */ private Flux<Indexable> processFaultedTaskAsync(final TaskGroupEntry<TaskItem> faultedEntry, final Throwable throwable, final InvocationContext context) { markGroupAsCancelledIfTerminationStrategyIsIPTC(); reportError(faultedEntry, throwable); if (isRootEntry(faultedEntry)) { if (shouldPropagateException(throwable)) { return toErrorObservable(throwable); } return Flux.empty(); } else if (shouldPropagateException(throwable)) { return Flux.concatDelayError(invokeReadyTasksAsync(context), toErrorObservable(throwable)); } else { return invokeReadyTasksAsync(context); } } /** * Mark this TaskGroup as cancelled if the termination strategy associated with the group * is {@link TaskGroupTerminateOnErrorStrategy#TERMINATE_ON_IN_PROGRESS_TASKS_COMPLETION}. */ private void markGroupAsCancelledIfTerminationStrategyIsIPTC() { this.isGroupCancelled.set(this.taskGroupTerminateOnErrorStrategy == TaskGroupTerminateOnErrorStrategy.TERMINATE_ON_IN_PROGRESS_TASKS_COMPLETION); } /** * Check that given entry is the root entry in this group. * * @param taskGroupEntry the entry * @return true if the entry is root entry in the group, false otherwise. */ private boolean isRootEntry(TaskGroupEntry<TaskItem> taskGroupEntry) { return isRootNode(taskGroupEntry); } /** * Checks the given throwable needs to be propagated to final stream returned by * {@link this#invokeAsync(InvocationContext)} ()} method. * * @param throwable the exception to check * @return true if the throwable needs to be included in the {@link RuntimeException} * emitted by the final stream. */ private static boolean shouldPropagateException(Throwable throwable) { return (!(throwable instanceof ErroredDependencyTaskException) && !(throwable instanceof TaskCancelledException)); } /** * Gets the given throwable as observable. * * @param throwable the throwable to wrap * @return observable with throwable wrapped */ private Flux<Indexable> toErrorObservable(Throwable throwable) { return Flux.error(throwable); } /** * @return a new clean context instance. */ public InvocationContext newInvocationContext() { return new InvocationContext(this); } /** * An interface representing a type composes a TaskGroup. */ public interface HasTaskGroup { /** * @return Gets the task group. */ TaskGroup taskGroup(); } /** * A mutable type that can be used to pass data around task items during the invocation * of the TaskGroup. */ public static final class InvocationContext { /** Key of the {@link Set} of tasks to skip. */ public static final String KEY_SKIP_TASKS = "SKIP_TASKS"; private final Map<String, Object> properties; private final TaskGroup taskGroup; private TaskGroupTerminateOnErrorStrategy terminateOnErrorStrategy; private final ClientLogger logger = new ClientLogger(this.getClass()); /** * Creates InvocationContext instance. * * @param taskGroup the task group that uses this context instance. */ private InvocationContext(final TaskGroup taskGroup) { this.properties = new ConcurrentHashMap<>(); this.taskGroup = taskGroup; } /** * @return the TaskGroup this invocation context associated with. */ public TaskGroup taskGroup() { return this.taskGroup; } /** * Sets the group termination strategy to use on error. * * @param strategy the strategy * @return the context */ public InvocationContext withTerminateOnErrorStrategy(TaskGroupTerminateOnErrorStrategy strategy) { if (this.terminateOnErrorStrategy != null) { throw logger.logExceptionAsError(new IllegalStateException( "Termination strategy is already set, it is immutable for a specific context")); } this.terminateOnErrorStrategy = strategy; return this; } /** * @return the termination strategy to use upon error during the current invocation of the TaskGroup. */ public TaskGroupTerminateOnErrorStrategy terminateOnErrorStrategy() { if (this.terminateOnErrorStrategy == null) { return TaskGroupTerminateOnErrorStrategy.TERMINATE_ON_HITTING_LCA_TASK; } return this.terminateOnErrorStrategy; } /** * Put a key-value in the context. * * @param key the key * @param value the value */ public void put(String key, Object value) { this.properties.put(key, value); } /** * Get a value in the context with the given key. * * @param key the key * @return value with the given key if exists, null otherwise. */ public Object get(String key) { return this.properties.get(key); } /** * Check existence of a key in the context. * * @param key the key * @return true if the key exists, false otherwise. */ public boolean hasKey(String key) { return this.get(key) != null; } } /** * Wrapper type to simplify operations on proxy TaskGroup. * <p> * A proxy TaskGroup will be activated for a TaskGroup as soon as a "post-run" dependent * added to the actual TaskGroup via {@link TaskGroup#addPostRunDependentTaskGroup(TaskGroup)}. * "post run" dependents are those TaskGroup which need to be invoked as part of invocation * of actual TaskGroup. */ protected static final class ProxyTaskGroupWrapper { // The "proxy TaskGroup" private TaskGroup proxyTaskGroup; // The "actual TaskGroup" for which above TaskGroup act as proxy private final TaskGroup actualTaskGroup; private final ClientLogger logger = new ClientLogger(this.getClass()); /** * Creates ProxyTaskGroupWrapper. * * @param actualTaskGroup the actual TaskGroup for which proxy TaskGroup will be enabled */ ProxyTaskGroupWrapper(TaskGroup actualTaskGroup) { this.actualTaskGroup = actualTaskGroup; } /** * @return true if the proxy TaskGroup is enabled for original TaskGroup. */ boolean isActive() { return this.proxyTaskGroup != null; } /** * @return the wrapped proxy task group. */ TaskGroup taskGroup() { return this.proxyTaskGroup; } /** * Add "post-run TaskGroup" for the "actual TaskGroup". * * @param postRunTaskGroup the dependency TaskGroup. */ void addPostRunTaskGroupForActualTaskGroup(TaskGroup postRunTaskGroup) { if (this.proxyTaskGroup == null) { this.initProxyTaskGroup(); } postRunTaskGroup.addDependencyGraph(this.actualTaskGroup); if (postRunTaskGroup.proxyTaskGroupWrapper.isActive()) { this.proxyTaskGroup.addDependencyGraph(postRunTaskGroup.proxyTaskGroupWrapper.proxyTaskGroup); } else { this.proxyTaskGroup.addDependencyGraph(postRunTaskGroup); } } /** * Add a dependent for the proxy TaskGroup. * * @param dependentTaskGroup the dependent TaskGroup */ void addDependentTaskGroup(TaskGroup dependentTaskGroup) { if (this.proxyTaskGroup == null) { throw logger.logExceptionAsError(new IllegalStateException( "addDependentTaskGroup() cannot be called in a non-active ProxyTaskGroup")); } dependentTaskGroup.addDependencyGraph(this.proxyTaskGroup); } /** * Initialize the proxy TaskGroup if not initialized yet. */ private void initProxyTaskGroup() { if (this.proxyTaskGroup == null) { // Creates proxy TaskGroup with an instance of ProxyTaskItem as root TaskItem which delegates actions on // it to "actual TaskGroup"'s root. // ProxyTaskItem proxyTaskItem = new ProxyTaskItem(this.actualTaskGroup.root().data()); this.proxyTaskGroup = new TaskGroup("proxy-" + this.actualTaskGroup.root().key(), proxyTaskItem); if (this.actualTaskGroup.hasParents()) { // Once "proxy TaskGroup" is enabled, all existing TaskGroups depends on "actual TaskGroup" should // take dependency on "proxy TaskGroup". // String atgRootKey = this.actualTaskGroup.root().key(); for (DAGraph<TaskItem, TaskGroupEntry<TaskItem>> parentDAG : this.actualTaskGroup.parentDAGs) { parentDAG.root().removeDependency(atgRootKey); parentDAG.addDependencyGraph(this.proxyTaskGroup); } // re-assigned actual's parents as proxy's parents, so clear actual's parent collection. // this.actualTaskGroup.parentDAGs.clear(); } // "Proxy TaskGroup" takes dependency on "actual TaskGroup" // this.proxyTaskGroup.addDependencyGraph(this.actualTaskGroup); // Add a back reference to "proxy" in actual // this.actualTaskGroup.rootTaskEntry.setProxy(this.proxyTaskGroup.rootTaskEntry); } } } /** * A {@link TaskItem} type that act as proxy for another {@link TaskItem}. */ private static final class ProxyTaskItem implements TaskItem { private final TaskItem actualTaskItem; private ProxyTaskItem(final TaskItem actualTaskItem) { this.actualTaskItem = actualTaskItem; } @Override public Indexable result() { return actualTaskItem.result(); } @Override public void beforeGroupInvoke() { // NOP } @Override public boolean isHot() { return actualTaskItem.isHot(); } @Override public Mono<Indexable> invokeAsync(InvocationContext context) { return Mono.just(actualTaskItem.result()); } @Override public Mono<Void> invokeAfterPostRunAsync(final boolean isGroupFaulted) { if (actualTaskItem.isHot()) { return Mono.defer(() -> actualTaskItem.invokeAfterPostRunAsync(isGroupFaulted).subscribeOn(Schedulers.immediate())); } else { return this.actualTaskItem.invokeAfterPostRunAsync(isGroupFaulted) .subscribeOn(Schedulers.immediate()); } } } }
Java
UTF-8
324
1.664063
2
[]
no_license
package life.hrx.weibo.dto; import lombok.Data; /** * 点赞对象 */ @Data public class LikeCountDTO { private Long userId; private Boolean isLike;//是否已经点过赞 private Long likeCount; //点赞数量 private Long likeId;//被点赞对象的id private String likeType;//点赞的类型 }
Python
UTF-8
439
3.59375
4
[]
no_license
#!/usr/bin/python3 sandwich_orders = ['sub', 'pb&j', 'knuckle', 'pastrami'] finished_sandwiches = [] while sandwich_orders: temp = sandwich_orders.pop() if temp == 'pastrami': print("We're out of pastrami. Skipping...") else: print("Making a " + temp + ".") finished_sandwiches.append(temp) print("\nDone!\n") print("The following sandwiches were made:") for i in finished_sandwiches: print(i)
Java
UTF-8
635
2.40625
2
[]
no_license
/** * */ package com.jason.stock.http.core; /** * @author lenovo * */ public class DataAccessException extends RuntimeException { /** * */ private static final long serialVersionUID = 452684673511911522L; /** * Constructor for DataAccessException. * @param msg the detail message */ public DataAccessException(String msg) { super(msg); } /** * Constructor for DataAccessException. * @param msg the detail message * @param cause the root cause (usually from using a underlying * data access API such as JDBC) */ public DataAccessException(String msg, Throwable cause) { super(msg, cause); } }
JavaScript
UTF-8
832
2.515625
3
[]
no_license
const expectations = (function() { const asciiStart = "test123"; const asciiExpect = [ 116, 101, 115, 116, "1", "2", "3" ]; const asciiSingleStart = asciiExpect; const asciiSingleExpect = [1,1,6,1,0,1,1,1,5,1,1,6,1,2,3]; const spliceAndFillStart = asciiSingleExpect; const spliceAndFillExpect = [ [ 1, 1, 6, 1, 0, 1, 1, 1, 5, 1 ], [ 1, 6, 1, 2, 3, 0, 1, 2, 3, 4 ] ]; const mergeArraysStart = spliceAndFillExpect; const mergeArraysExpect = [ 2, 7, 7, 3, 3, 1, 2, 3, 8, 5 ]; return { asciiStart, asciiExpect, asciiSingleStart, asciiSingleExpect, spliceAndFillStart, spliceAndFillExpect, mergeArraysStart, mergeArraysExpect } }()); module.exports = expectations;
C
UTF-8
236
2.765625
3
[]
no_license
#include <stdio.h> int main(int argc, const char** argv, const char** envp) { // loops from 100 to 999 for (int i = 100; i < 999; i++) { // i know it goes from 100 to 999 // but i cannot figure out exactly what it is doing } }
Markdown
UTF-8
596
2.78125
3
[]
no_license
# Bot, Don King Bot, Don King is an automatic Reddit promoter that posts to the specified sub-reddits at the sub-reddits' optimal time. ```python urls_subreddits = { 'http://www.yourblog.com/your-article': { # URL 'title': 'Check out this article', # title of the article 'subreddits': ['python', 'rstats'], #subreddit you want to post to }, 'http://www.yourblog.com/your-other-article': { 'title': 'this is still a test', 'subreddits': ['pystats', 'datascience', 'statistics'], } } dk = DonKing(urls_subreddits) dk.queue_articles() dk.promote() ```
Go
UTF-8
871
3.0625
3
[]
no_license
package main import ( "fmt" "html/template" "net/http" ) var tpl *template.Template func init() { tpl = template.Must(template.ParseFiles("index.gohtml")) } func main() { http.HandleFunc("/", foo) http.HandleFunc("/bar", bar) http.HandleFunc("/barform", barform) http.Handle("/favicon.ico", http.NotFoundHandler()) http.ListenAndServe(":8080", nil) } func foo(w http.ResponseWriter, r *http.Request) { fmt.Println("You requested foo with", r.Method) } func bar(w http.ResponseWriter, r *http.Request) { fmt.Println("You called bar with", r.Method) // handle form post // redirect with explicit headers w.Header().Set("Location", "/") w.WriteHeader(http.StatusSeeOther) // use http.Redirect // http.Redirect(w, r, "/", http.StatusSeeOther) } func barform(w http.ResponseWriter, r *http.Request) { tpl.ExecuteTemplate(w, "index.gohtml", nil) }
Python
UTF-8
44,610
2.96875
3
[]
no_license
from Game import Game import constants import skfuzzy as fuzz from skfuzzy import control as ctrl import numpy as np import math as m #To Calculate the angle between 2 points #myradians = math.atan2(targetY-gunY, targetX-gunX) class FuzzyRulesController: def __init__(self, max_moves=2000): self.max_moves = max_moves self.current_move_number = 0 self.game = Game() self.mf_pm_right() self.mf_pm_left() self.mf_pm_up() self.mf_pm_down() self.old_snake_pos_y = 0 self.old_snake_pos_x = 0 def mf_pm_right(self): '''if the previous move is RIGHT, the only direciton you can move is UP, RIGHT, DOWN''' self.next_move_pm_right = ctrl.Consequent(np.arange(0, 101, 1), 'Next Direction') self.next_move_pm_right['up'] = fuzz.trapmf(self.next_move_pm_right.universe,[0,0,25, 40]) self.next_move_pm_right['right'] = fuzz.trimf(self.next_move_pm_right.universe,[25,50,75]) self.next_move_pm_right['down'] = fuzz.trapmf(self.next_move_pm_right.universe,[60,75,100,100]) self.food_loc = ctrl.Antecedent(np.arange(-181, 181, 1), 'food_loc') '''Based on a clock with respect the the snake head''' self.food_loc['up'] = fuzz.trimf(self.food_loc.universe,[-50,0, 50]) self.food_loc['right'] = fuzz.trimf(self.food_loc.universe,[45,135,181]) self.food_loc['left'] = fuzz.trimf(self.food_loc.universe, [-181,-135,-45]) self.rule1 = ctrl.Rule(self.food_loc['up'], self.next_move_pm_right['right']) self.rule2 = ctrl.Rule(self.food_loc['left'], self.next_move_pm_right['up']) self.rule3 = ctrl.Rule(self.food_loc['right'], self.next_move_pm_right['down']) # self.collison_ang = ctrl.Antecedent(np.arange(-181, 181, 1), 'collison_ang') # '''Based on a clock with respect the the snake head''' # self.collison_ang['0'] = fuzz.trapmf(self.collison_ang.universe,[-90,-45,45,90]) # self.collison_ang['90'] = fuzz.trimf(self.collison_ang.universe,[45,90,135]) # self.collison_ang['-90'] = fuzz.trimf(self.collison_ang.universe, [-135,-90,-45]) # # self.rule4 = ctrl.Rule(self.collison_ang['0'], self.next_move_pm_right['up']) # self.rule5 = ctrl.Rule(self.collison_ang['90'], self.next_move_pm_right['up']) # self.rule6 = ctrl.Rule(self.collison_ang['-90'], self.next_move_pm_right['down']) self.collison_ang_2 = ctrl.Antecedent(np.arange(-181, 181, 1), 'collison_ang_2') '''Based on a clock with respect the the snake head''' self.collison_ang_2['0'] = fuzz.trapmf(self.collison_ang_2.universe,[-90,-45,45,90]) self.collison_ang_2['90'] = fuzz.trimf(self.collison_ang_2.universe,[45,90,135]) self.collison_ang_2['-90'] = fuzz.trimf(self.collison_ang_2.universe, [-135,-90,-45]) self.rule7 = ctrl.Rule(self.collison_ang_2['0'], self.next_move_pm_right['right']) self.rule8 = ctrl.Rule(self.collison_ang_2['90'], self.next_move_pm_right['up']) self.rule9 = ctrl.Rule(self.collison_ang_2['-90'], self.next_move_pm_right['down']) self.weight_snake = ctrl.Antecedent(np.arange(-10,10,1),'weight_snake') self.weight_snake['left'] = fuzz.trapmf(self.weight_snake.universe,[-10,-10,-5,0]) self.weight_snake['right'] = fuzz.trapmf(self.weight_snake.universe,[0,5,10,10]) self.rule10 = ctrl.Rule(self.weight_snake['left'], self.next_move_pm_right['down']) self.rule11= ctrl.Rule(self.weight_snake['right'], self.next_move_pm_right['up']) self.spiral_snake = ctrl.Antecedent(np.arange(-91,91,1),'spiral_snake') self.spiral_snake['-90'] = fuzz.trimf(self.spiral_snake.universe,[-91,-90,-89]) self.spiral_snake['90'] = fuzz.trimf(self.spiral_snake.universe,[89,90,91]) self.spiral_snake['0'] = fuzz.trimf(self.spiral_snake.universe,[-1,0,1]) self.rule12 = ctrl.Rule(self.spiral_snake['-90'], self.next_move_pm_right['down']) self.rule13= ctrl.Rule(self.spiral_snake['90'], self.next_move_pm_right['up']) self.rule14= ctrl.Rule(self.spiral_snake['0'], self.next_move_pm_right['right']) ############################################################################################### def mf_pm_left(self): '''if the previous move is LEFT, the only direciton you can move is UP, LEFT, DOWN''' self.next_move_pm_left = ctrl.Consequent(np.arange(0, 101, 1), 'Next Direction') self.next_move_pm_left['up'] = fuzz.trapmf(self.next_move_pm_left.universe,[0,0,25, 40]) self.next_move_pm_left['left'] = fuzz.trimf(self.next_move_pm_left.universe,[25,50,75]) self.next_move_pm_left['down'] = fuzz.trapmf(self.next_move_pm_left.universe,[60,75,100,100]) self.food_loc = ctrl.Antecedent(np.arange(-181, 181, 1), 'food_loc') '''Based on a clock with respect the the snake head''' self.food_loc['up'] = fuzz.trimf(self.food_loc.universe,[-50,0, 50]) self.food_loc['right'] = fuzz.trimf(self.food_loc.universe,[45,135,181]) self.food_loc['left'] = fuzz.trimf(self.food_loc.universe, [-181,-135,-45]) self.rule1 = ctrl.Rule(self.food_loc['up'], self.next_move_pm_left['left']) self.rule2 = ctrl.Rule(self.food_loc['left'], self.next_move_pm_left['down']) self.rule3 = ctrl.Rule(self.food_loc['right'], self.next_move_pm_left['up']) # self.collison_ang = ctrl.Antecedent(np.arange(-181, 181, 1), 'collison_ang') # '''Based on a clock with respect the the snake head''' # self.collison_ang['0'] = fuzz.trapmf(self.collison_ang.universe,[-90,-45,45,90]) # self.collison_ang['90'] = fuzz.trimf(self.collison_ang.universe,[45,90,135]) # self.collison_ang['-90'] = fuzz.trimf(self.collison_ang.universe, [-135,-90,-45]) # # self.rule4 = ctrl.Rule(self.collison_ang['0'], self.next_move_pm_left['up']) # self.rule5 = ctrl.Rule(self.collison_ang['90'], self.next_move_pm_left['down']) # self.rule6 = ctrl.Rule(self.collison_ang['-90'], self.next_move_pm_left['up']) self.collison_ang_2 = ctrl.Antecedent(np.arange(-181, 181, 1), 'collison_ang_2') '''Based on a clock with respect the the snake head''' self.collison_ang_2['0'] = fuzz.trapmf(self.collison_ang_2.universe,[-90,-45,45,90]) self.collison_ang_2['90'] = fuzz.trimf(self.collison_ang_2.universe,[45,90,135]) self.collison_ang_2['-90'] = fuzz.trimf(self.collison_ang_2.universe, [-135,-90,-45]) self.rule7 = ctrl.Rule(self.collison_ang_2['0'], self.next_move_pm_left['left']) self.rule8 = ctrl.Rule(self.collison_ang_2['90'], self.next_move_pm_left['down']) self.rule9 = ctrl.Rule(self.collison_ang_2['-90'], self.next_move_pm_left['up']) self.weight_snake = ctrl.Antecedent(np.arange(-10,10,1),'weight_snake') self.weight_snake['left'] = fuzz.trapmf(self.weight_snake.universe,[-10,-10,-5,0]) self.weight_snake['right'] = fuzz.trapmf(self.weight_snake.universe,[0,5,10,10]) self.rule10 = ctrl.Rule(self.weight_snake['left'], self.next_move_pm_left['up']) self.rule11= ctrl.Rule(self.weight_snake['right'], self.next_move_pm_left['down']) self.spiral_snake = ctrl.Antecedent(np.arange(-91,91,1),'spiral_snake') self.spiral_snake['-90'] = fuzz.trimf(self.spiral_snake.universe,[-91,-90,-89]) self.spiral_snake['90'] = fuzz.trimf(self.spiral_snake.universe,[89,90,91]) self.spiral_snake['0'] = fuzz.trimf(self.spiral_snake.universe,[-1,0,1]) self.rule12 = ctrl.Rule(self.spiral_snake['-90'], self.next_move_pm_left['up']) self.rule13= ctrl.Rule(self.spiral_snake['90'], self.next_move_pm_left['down']) self.rule14= ctrl.Rule(self.spiral_snake['0'], self.next_move_pm_left['left']) ############################################################################################### def mf_pm_up(self): '''if the previous move is UP, the only direciton you can move is UP, LEFT, RIGHT''' self.next_move_pm_up = ctrl.Consequent(np.arange(0, 101, 1), 'Next Direction') self.next_move_pm_up['left'] = fuzz.trapmf(self.next_move_pm_up.universe,[0,0,25, 40]) self.next_move_pm_up['up'] = fuzz.trimf(self.next_move_pm_up.universe,[25,50,75]) self.next_move_pm_up['right'] = fuzz.trapmf(self.next_move_pm_up.universe, [60,75,100,100]) self.food_loc = ctrl.Antecedent(np.arange(-181, 181, 1), 'food_loc') '''Based on a clock with respect the the snake head''' self.food_loc['up'] = fuzz.trimf(self.food_loc.universe,[-50,0, 50]) self.food_loc['right'] = fuzz.trimf(self.food_loc.universe,[45,135,181]) self.food_loc['left'] = fuzz.trimf(self.food_loc.universe, [-181,-135,-45]) self.rule1 = ctrl.Rule(self.food_loc['up'], self.next_move_pm_up['up']) self.rule2 = ctrl.Rule(self.food_loc['left'], self.next_move_pm_up['left']) self.rule3 = ctrl.Rule(self.food_loc['right'], self.next_move_pm_up['right']) # self.collison_ang = ctrl.Antecedent(np.arange(-181, 181, 1), 'collison_ang') # '''Based on a clock with respect the the snake head''' # self.collison_ang['0'] = fuzz.trapmf(self.collison_ang.universe,[-90,-45,45,90]) # self.collison_ang['90'] = fuzz.trimf(self.collison_ang.universe,[45,90,135]) # self.collison_ang['-90'] = fuzz.trimf(self.collison_ang.universe, [-135,-90,-45]) # # self.rule4 = ctrl.Rule(self.collison_ang['0'], self.next_move_pm_up['left']) # self.rule5 = ctrl.Rule(self.collison_ang['90'], self.next_move_pm_up['left']) # self.rule6 = ctrl.Rule(self.collison_ang['-90'], self.next_move_pm_up['right']) self.collison_ang_2 = ctrl.Antecedent(np.arange(-181, 181, 1), 'collison_ang_2') '''Based on a clock with respect the the snake head''' self.collison_ang_2['0'] = fuzz.trapmf(self.collison_ang_2.universe,[-90,-45,45,90]) self.collison_ang_2['90'] = fuzz.trimf(self.collison_ang_2.universe,[45,90,135]) self.collison_ang_2['-90'] = fuzz.trimf(self.collison_ang_2.universe, [-135,-90,-45]) self.rule7 = ctrl.Rule(self.collison_ang_2['0'], self.next_move_pm_up['up']) self.rule8 = ctrl.Rule(self.collison_ang_2['90'], self.next_move_pm_up['left']) self.rule9 = ctrl.Rule(self.collison_ang_2['-90'], self.next_move_pm_up['right']) self.weight_snake = ctrl.Antecedent(np.arange(-10,10,1),'weight_snake') self.weight_snake['left'] = fuzz.trapmf(self.weight_snake.universe,[-10,-10,-5,0]) self.weight_snake['right'] = fuzz.trapmf(self.weight_snake.universe,[0,5,10,10]) self.rule10 = ctrl.Rule(self.weight_snake['left'], self.next_move_pm_up['right']) self.rule11= ctrl.Rule(self.weight_snake['right'], self.next_move_pm_up['left']) self.spiral_snake = ctrl.Antecedent(np.arange(-91,91,1),'spiral_snake') self.spiral_snake['-90'] = fuzz.trimf(self.spiral_snake.universe,[-91,-90,-89]) self.spiral_snake['90'] = fuzz.trimf(self.spiral_snake.universe,[89,90,91]) self.spiral_snake['0'] = fuzz.trimf(self.spiral_snake.universe,[-1,0,1]) self.rule12 = ctrl.Rule(self.spiral_snake['-90'], self.next_move_pm_up['right']) self.rule13= ctrl.Rule(self.spiral_snake['90'], self.next_move_pm_up['left']) self.rule14= ctrl.Rule(self.spiral_snake['0'], self.next_move_pm_up['up']) ############################################################################################### def mf_pm_down(self): '''if the previous move is DOWN, the only direciton you can move is DOWN, LEFT, RIGHT''' self.next_move_pm_down = ctrl.Consequent(np.arange(0, 101, 1), 'Next Direction') self.next_move_pm_down['left'] = fuzz.trapmf(self.next_move_pm_down.universe,[0,0,25, 40]) self.next_move_pm_down['down'] = fuzz.trimf(self.next_move_pm_down.universe,[25,50,75]) self.next_move_pm_down['right'] = fuzz.trapmf(self.next_move_pm_down.universe,[60,75,100,100]) self.food_loc = ctrl.Antecedent(np.arange(-181, 181, 1), 'food_loc') '''Based on a clock with respect the the snake head''' self.food_loc['up'] = fuzz.trimf(self.food_loc.universe,[-50,0, 50]) self.food_loc['right'] = fuzz.trimf(self.food_loc.universe,[45,135,181]) self.food_loc['left'] = fuzz.trimf(self.food_loc.universe, [-181,-135,-45]) self.rule1 = ctrl.Rule(self.food_loc['up'], self.next_move_pm_down['down']) self.rule2 = ctrl.Rule(self.food_loc['left'], self.next_move_pm_down['right']) self.rule3 = ctrl.Rule(self.food_loc['right'], self.next_move_pm_down['left']) # self.collison_ang = ctrl.Antecedent(np.arange(-181, 181, 1), 'collison_ang') # '''Based on a clock with respect the the snake head''' # self.collison_ang['0'] = fuzz.trapmf(self.collison_ang.universe,[-90,-45,45,90]) # self.collison_ang['90'] = fuzz.trimf(self.collison_ang.universe,[45,90,135]) # self.collison_ang['-90'] = fuzz.trimf(self.collison_ang.universe, [-135,-90,-45]) # # self.rule4 = ctrl.Rule(self.collison_ang['0'], self.next_move_pm_down['left']) # self.rule5 = ctrl.Rule(self.collison_ang['90'], self.next_move_pm_down['right']) # self.rule6 = ctrl.Rule(self.collison_ang['-90'], self.next_move_pm_down['left']) self.collison_ang_2 = ctrl.Antecedent(np.arange(-181, 181, 1), 'collison_ang_2') '''Based on a clock with respect the the snake head''' self.collison_ang_2['0'] = fuzz.trapmf(self.collison_ang_2.universe,[-90,-45,45,90]) self.collison_ang_2['90'] = fuzz.trimf(self.collison_ang_2.universe,[45,90,135]) self.collison_ang_2['-90'] = fuzz.trimf(self.collison_ang_2.universe, [-135,-90,-45]) self.rule7 = ctrl.Rule(self.collison_ang_2['0'], self.next_move_pm_down['down']) self.rule8 = ctrl.Rule(self.collison_ang_2['90'], self.next_move_pm_down['right']) self.rule9 = ctrl.Rule(self.collison_ang_2['-90'], self.next_move_pm_down['left']) #From the viewpoint of the snake self.weight_snake = ctrl.Antecedent(np.arange(-10,10,1),'weight_snake') self.weight_snake['left'] = fuzz.trapmf(self.weight_snake.universe,[-10,-10,-5,0]) self.weight_snake['right'] = fuzz.trapmf(self.weight_snake.universe,[0,5,10,10]) self.rule10 = ctrl.Rule(self.weight_snake['left'], self.next_move_pm_down['left']) self.rule11= ctrl.Rule(self.weight_snake['right'], self.next_move_pm_down['right']) self.spiral_snake = ctrl.Antecedent(np.arange(-91,91,1),'spiral_snake') self.spiral_snake['-90'] = fuzz.trimf(self.spiral_snake.universe,[-91,-90,-89]) self.spiral_snake['90'] = fuzz.trimf(self.spiral_snake.universe,[89,90,91]) self.spiral_snake['0'] = fuzz.trimf(self.spiral_snake.universe,[-1,0,1]) self.rule12 = ctrl.Rule(self.spiral_snake['-90'], self.next_move_pm_down['left']) self.rule13= ctrl.Rule(self.spiral_snake['90'], self.next_move_pm_down['right']) self.rule14= ctrl.Rule(self.spiral_snake['0'], self.next_move_pm_down['down']) ############################################################################################### def get_angle_pm_right(self,food_y, food_x, snake_y,snake_x): '''Angle is based on the 4 quadrant We require to convert it back where 0 is the y-axis''' #print(str(food_y) + " " + str(food_x) + " " + str(snake_y) +" " + str(snake_x)) angle = m.degrees(m.atan2((food_y-snake_y),(food_x - snake_x))) if angle <= 90 and angle >= 0: final_angle = angle if angle >= 90 and angle <= 180: final_angle = angle if -90 <=angle <= 0: final_angle = angle if angle >= -180 and angle <= -90: final_angle = angle return int(final_angle) def get_angle_pm_left(self,food_y, food_x, snake_y,snake_x): '''Angle is based on the 4 quadrant We require to convert it back where 0 is the y-axis''' #print(str(food_y) + " " + str(food_x) + " " + str(snake_y) +" " + str(snake_x)) angle = m.degrees(m.atan2((food_y-snake_y),(food_x - snake_x))) if angle <= 90 and angle >= 0: final_angle = -(180-angle) if angle >= 90 and angle <= 180: final_angle = -(180-angle) if -90 <=angle <= 0: final_angle = 180 + angle if angle >= -180 and angle <= -90: final_angle = 180 + angle return int(final_angle) def get_angle_pm_up(self,food_y, food_x, snake_y,snake_x): '''Angle is based on the 4 quadrant We require to convert it back where 0 is the y-axis''' #print(str(food_y) + " " + str(food_x) + " " + str(snake_y) +" " + str(snake_x)) angle = m.degrees(m.atan2((food_y-snake_y),(food_x - snake_x))) if angle <= 90 and angle >= 0: final_angle = 90 + angle if angle >= 90 and angle <= 180: final_angle = (angle - 90)-180 if -90 <=angle <= 0: final_angle = 90 + angle if angle >= -180 and angle <= -90: final_angle = angle + 90 return int(final_angle) def get_angle_pm_down(self,food_y, food_x, snake_y,snake_x): '''Angle is based on the 4 quadrant We require to convert it back where 0 is the y-axis''' #print(str(food_y) + " " + str(food_x) + " " + str(snake_y) +" " + str(snake_x)) angle = m.degrees(m.atan2((food_y-snake_y),(food_x - snake_x))) if angle <= 90 and angle >= 0: final_angle = -(90 - angle) if angle >= 90 and angle <= 180: final_angle = angle - 90 if -90 <=angle <= 0: final_angle = angle-90 if angle >= -180 and angle <= -90: final_angle = 270+angle return int(final_angle) #Calculate Mahatten Distance #Put in a list of x and y values def manhatten_distance(self, snake_x , snake_y): overall_man_dist = [] for i in range(0,len(snake_x)): x_head = snake_x[0] y_head = snake_y[0] manhatten_distance = int((abs(x_head - snake_x[i]) + abs(y_head - snake_y[i]))/44) overall_man_dist.append(manhatten_distance) return overall_man_dist def check_snake(self,snake_x , snake_y): length_of_snake = len(snake_x) if snake_x[-1] == -100: snake_x.pop() snake_y.pop() else: pass print(snake_x) print(snake_y) return snake_x,snake_y def weight_snake_pm_up(self,snake_x , snake_y): snake_pos = [] left = 0 right = 0 center = 0 for i in range(0,len(snake_x)): x_head = snake_x[0] y_head = snake_y[0] left_right = int((x_head - snake_x[i])/44) snake_pos.append(left_right) print(snake_pos) for x in snake_pos: # print(x) if x > 0: left = left + 1 if x < 0: right = right + 1 if x ==0: center = center + 1 print(left) print(right) print(center) overall = ((right-left)/(right + left)) * 10 print(overall) return overall def weight_snake_pm_down(self,snake_x , snake_y): snake_pos = [] left = 0 right = 0 center = 0 for i in range(0,len(snake_x)): x_head = snake_x[0] y_head = snake_y[0] left_right = int((x_head - snake_x[i])/44) snake_pos.append(left_right) print(snake_pos) for x in snake_pos: # print(x) if x < 0: left = left + 1 if x >0: right = right + 1 if x ==0: center = center + 1 print(left) print(right) print(center) overall = ((right-left)/(right + left)) * 10 print(overall) return overall def weight_snake_pm_left(self,snake_x , snake_y): snake_pos = [] left = 0 right = 0 center = 0 for i in range(0,len(snake_x)): x_head = snake_x[0] y_head = snake_y[0] left_right = int((y_head - snake_y[i])/44) snake_pos.append(left_right) print(snake_pos) for y in snake_pos: if y < 0: left = left + 1 if y > 0: right = right + 1 if y ==0: center = center + 1 print(left) print(right) print(center) overall = ((right-left)/(right + left)) * 10 print(overall) return overall def weight_snake_pm_right(self,snake_x , snake_y): snake_pos = [] left = 0 right = 0 center = 0 for i in range(0,len(snake_x)): x_head = snake_x[0] y_head = snake_y[0] left_right = int((y_head - snake_y[i])/44) snake_pos.append(left_right) print(snake_pos) for y in snake_pos: if y > 0: left = left + 1 if y < 0: right = right + 1 if y ==0: center = center + 1 print(left) print(right) print(center) overall = ((right-left)/(right + left)) * 10 print(overall) return overall def spiral_pm_right(self,snake_x , snake_y): angle_of_snake_body = [] x_head = snake_x[0] y_head = snake_y[0] man_distance = self.manhatten_distance(snake_x , snake_y) for i in range(2, len(man_distance)): angle = self.get_angle_pm_right(snake_y[i], snake_x[i], y_head,x_head) angle_of_snake_body.append(angle) print(angle_of_snake_body) for angle in angle_of_snake_body: if angle == 90: print('Spiral Angle is' + str(angle)) return angle elif angle == -90: print('Spiral Angle is' + str(angle)) return angle elif angle ==0: print('Spiral Angle is' + str(angle)) return angle def spiral_pm_left(self,snake_x , snake_y): angle_of_snake_body = [] x_head = snake_x[0] y_head = snake_y[0] man_distance = self.manhatten_distance(snake_x , snake_y) for i in range(2, len(man_distance)): angle = self.get_angle_pm_left(snake_y[i], snake_x[i], y_head,x_head) angle_of_snake_body.append(angle) print(angle_of_snake_body) for angle in angle_of_snake_body: if angle == 90: print('Spiral Angle is' + str(angle)) return angle elif angle == -90: print('Spiral Angle is' + str(angle)) return angle elif angle ==0: print('Spiral Angle is' + str(angle)) return angle def spiral_pm_up(self,snake_x , snake_y): angle_of_snake_body = [] x_head = snake_x[0] y_head = snake_y[0] man_distance = self.manhatten_distance(snake_x , snake_y) for i in range(2, len(man_distance)): angle = self.get_angle_pm_up(snake_y[i], snake_x[i], y_head,x_head) angle_of_snake_body.append(angle) print(angle_of_snake_body) for angle in angle_of_snake_body: if angle == 90: return angle print('Spiral Angle is' + str(angle)) elif angle == -90: print('Spiral Angle is' + str(angle)) return angle elif angle ==0: print('Spiral Angle is' + str(angle)) return angle def spiral_pm_down(self,snake_x , snake_y): angle_of_snake_body = [] x_head = snake_x[0] y_head = snake_y[0] man_distance = self.manhatten_distance(snake_x , snake_y) for i in range(2, len(man_distance)): angle = self.get_angle_pm_down(snake_y[i], snake_x[i], y_head,x_head) angle_of_snake_body.append(angle) print(angle_of_snake_body) for angle in angle_of_snake_body: if angle == 90: print('Spiral Angle is' + str(angle)) return angle elif angle == -90: print('Spiral Angle is' + str(angle)) return angle elif angle ==0: print('Spiral Angle is' + str(angle)) return angle def perform_next_move(self, snake, food, bricks): overall_rules = [] indicator = 0 #counter for offending angle if self.current_move_number < self.max_moves: if self.old_snake_pos_y == snake.y[0] and self.old_snake_pos_x == snake.x[0] and self.current_move_number != 0: if snake.direction == constants.LEFT: snake.moveLeft() if snake.direction == constants.RIGHT: snake.moveRight() if snake.direction == constants.UP: snake.moveUp() if snake.direction == constants.DOWN: snake.moveDown() self.current_move_number += 1 else: if snake.direction == constants.RIGHT: self.mf_pm_right() # overall_rules = [self.rule1, self.rule2, self.rule3] overall_rules = [] angle = self.get_angle_pm_right(food.y, food.x, snake.y[0], snake.x[0]) print("Angle :" +str(angle)) snake_x,snake_y = self.check_snake(snake.x[0:snake.length],snake.y[0:snake.length]) overall_man_dist = self.manhatten_distance(snake_x,snake_y) print(overall_man_dist) if snake.length > 4: for i in range(3, len(overall_man_dist)): if overall_man_dist[i] == 1: indicator = indicator + 1 if indicator ==1: print('Offending part is:' + " " +str(snake.y[0]) + " " +str(snake.x[0]) + " " + str(snake.y[i]) + " " +str(snake.x[i])) collison_angle = self.get_angle_pm_right(snake.y[i], snake.x[i],snake.y[0], snake.x[0]) print('Collison angle is :' + str(collison_angle)) elif indicator == 2: print('2nd Offending part is:' + " " +str(snake.y[0]) + " " +str(snake.x[0]) + " " + str(snake.y[i]) + " " +str(snake.x[i])) collison_angle_2 = self.get_angle_pm_right(snake.y[i], snake.x[i],snake.y[0], snake.x[0]) print('2nd Collison angle is :' + str(collison_angle_2)) else: pass if indicator == 1: print('yeah') overall_weight = self.weight_snake_pm_right(snake_x,snake_y) print("Overall Weight is " + str(overall_weight)) spiral_angle = self.spiral_pm_right(snake_x,snake_y) overall_rules.extend((self.rule1, self.rule2, self.rule3,self.rule10,self.rule11,self.rule12,self.rule13,self.rule14)) next_move_crtl = ctrl.ControlSystem(overall_rules) next_move_crtl_fuzzy = ctrl.ControlSystemSimulation(next_move_crtl) next_move_crtl_fuzzy.input['food_loc'] = angle # next_move_crtl_fuzzy.input['collison_ang'] = collison_angle next_move_crtl_fuzzy.input['weight_snake'] = overall_weight next_move_crtl_fuzzy.input['spiral_snake'] = spiral_angle elif indicator >= 2: print('bah') overall_weight = self.weight_snake_pm_right(snake_x,snake_y) spiral_angle = self.spiral_pm_right(snake_x,snake_y) overall_rules.extend((self.rule7, self.rule8, self.rule9,self.rule12,self.rule13,self.rule14)) next_move_crtl = ctrl.ControlSystem(overall_rules) next_move_crtl_fuzzy = ctrl.ControlSystemSimulation(next_move_crtl) # next_move_crtl_fuzzy.input['food_loc'] = angle next_move_crtl_fuzzy.input['collison_ang_2'] = collison_angle_2 + collison_angle # next_move_crtl_fuzzy.input['collison_ang'] = collison_angle # next_move_crtl_fuzzy.input['weight_snake'] = overall_weight next_move_crtl_fuzzy.input['spiral_snake'] = spiral_angle else: next_move_crtl = ctrl.ControlSystem([self.rule1, self.rule2, self.rule3]) next_move_crtl_fuzzy = ctrl.ControlSystemSimulation(next_move_crtl) next_move_crtl_fuzzy.input['food_loc'] = angle result = next_move_crtl_fuzzy.compute() result = int(next_move_crtl_fuzzy.output['Next Direction']) print(str(result)+" is the output score." ) if result >= 0 and result < 35: snake.moveUp() print("Move up1") print("################") if result >=35 and result <=65: snake.moveRight() print("Move right2") print("################") if result >65 and result <= 100: snake.moveDown() print("Move down3") print("################") elif snake.direction == constants.LEFT: self.mf_pm_left() # overall_rules = [self.rule1, self.rule2, self.rule3] overall_rules = [] angle = self.get_angle_pm_left(food.y, food.x, snake.y[0], snake.x[0]) print("Angle :" +str(angle)) snake_x,snake_y = self.check_snake(snake.x[0:snake.length],snake.y[0:snake.length]) overall_man_dist = self.manhatten_distance(snake_x,snake_y) print(overall_man_dist) if snake.length > 4: for i in range(3, len(overall_man_dist)): if overall_man_dist[i] == 1: indicator = indicator + 1 if indicator ==1: print('Offending part is:' + " " +str(snake.y[0]) + " " +str(snake.x[0]) + " " + str(snake.y[i]) + " " +str(snake.x[i])) collison_angle = self.get_angle_pm_left(snake.y[i], snake.x[i],snake.y[0], snake.x[0]) print('Collison angle is :' + str(collison_angle)) elif indicator == 2: print('2nd Offending part is:' + " " +str(snake.y[0]) + " " +str(snake.x[0]) + " " + str(snake.y[i]) + " " +str(snake.x[i])) collison_angle_2 = self.get_angle_pm_left(snake.y[i], snake.x[i],snake.y[0], snake.x[0]) print('2nd Collison angle is :' + str(collison_angle_2)) else: pass if indicator == 1: print('yeah') overall_weight = self.weight_snake_pm_left(snake_x,snake_y) spiral_angle = self.spiral_pm_left(snake_x,snake_y) overall_rules.extend((self.rule1, self.rule2, self.rule3,self.rule10,self.rule11,self.rule12,self.rule13,self.rule14)) next_move_crtl = ctrl.ControlSystem(overall_rules) next_move_crtl_fuzzy = ctrl.ControlSystemSimulation(next_move_crtl) next_move_crtl_fuzzy.input['food_loc'] = angle # next_move_crtl_fuzzy.input['collison_ang'] = collison_angle next_move_crtl_fuzzy.input['weight_snake'] = overall_weight next_move_crtl_fuzzy.input['spiral_snake'] = spiral_angle elif indicator >= 2: print('bah') overall_weight = self.weight_snake_pm_left(snake_x,snake_y) spiral_angle = self.spiral_pm_left(snake_x,snake_y) overall_rules.extend((self.rule7, self.rule8, self.rule9,self.rule12,self.rule13,self.rule14)) next_move_crtl = ctrl.ControlSystem(overall_rules) next_move_crtl_fuzzy = ctrl.ControlSystemSimulation(next_move_crtl) # next_move_crtl_fuzzy.input['food_loc'] = angle next_move_crtl_fuzzy.input['collison_ang_2'] = (collison_angle_2 + collison_angle) # next_move_crtl_fuzzy.input['collison_ang'] = collison_angle # next_move_crtl_fuzzy.input['weight_snake'] = overall_weight next_move_crtl_fuzzy.input['spiral_snake'] = spiral_angle else: next_move_crtl = ctrl.ControlSystem([self.rule1, self.rule2, self.rule3]) next_move_crtl_fuzzy = ctrl.ControlSystemSimulation(next_move_crtl) next_move_crtl_fuzzy.input['food_loc'] = angle result = next_move_crtl_fuzzy.compute() result = int(next_move_crtl_fuzzy.output['Next Direction']) print(str(result)+" is the output score." ) if result >= 0 and result < 35: snake.moveUp() print("Move up4") print("################") if result >=35 and result <=65: snake.moveLeft() print("Move Left5") print("################") if result >65 and result <= 100: snake.moveDown() print("Move Down6") print("################") elif snake.direction == constants.UP: self.mf_pm_up() # overall_rules = [self.rule1, self.rule2, self.rule3] overall_rules = [] angle = self.get_angle_pm_up(food.y, food.x, snake.y[0], snake.x[0]) print("Angle :" +str(angle)) snake_x,snake_y = self.check_snake(snake.x[0:snake.length],snake.y[0:snake.length]) overall_man_dist = self.manhatten_distance(snake_x,snake_y) print(overall_man_dist) if snake.length > 4: for i in range(3, len(overall_man_dist)): if overall_man_dist[i] == 1: indicator = indicator + 1 if indicator ==1: print('Offending part is:' + " " +str(snake.y[0]) + " " +str(snake.x[0]) + " " + str(snake.y[i]) + " " +str(snake.x[i])) collison_angle = self.get_angle_pm_up(snake.y[i], snake.x[i],snake.y[0], snake.x[0]) print('Collison angle is :' + str(collison_angle)) elif indicator == 2: print('2nd Offending part is:' + " " +str(snake.y[0]) + " " +str(snake.x[0]) + " " + str(snake.y[i]) + " " +str(snake.x[i])) collison_angle_2 = self.get_angle_pm_up(snake.y[i], snake.x[i],snake.y[0], snake.x[0]) print('2nd Collison angle is :' + str(collison_angle_2)) else: pass if indicator == 1: print('yeah') overall_weight = self.weight_snake_pm_up(snake_x,snake_y) spiral_angle = self.spiral_pm_up(snake_x,snake_y) overall_rules.extend((self.rule1, self.rule2, self.rule3,self.rule10,self.rule11,self.rule12,self.rule13,self.rule14)) next_move_crtl = ctrl.ControlSystem(overall_rules) next_move_crtl_fuzzy = ctrl.ControlSystemSimulation(next_move_crtl) next_move_crtl_fuzzy.input['food_loc'] = angle # next_move_crtl_fuzzy.input['collison_ang'] = collison_angle next_move_crtl_fuzzy.input['weight_snake'] = overall_weight next_move_crtl_fuzzy.input['spiral_snake'] = spiral_angle elif indicator >= 2: print('bah') overall_weight = self.weight_snake_pm_up(snake_x,snake_y) spiral_angle = self.spiral_pm_up(snake_x,snake_y) overall_rules.extend((self.rule7, self.rule8, self.rule9,self.rule12,self.rule13,self.rule14)) next_move_crtl = ctrl.ControlSystem(overall_rules) next_move_crtl_fuzzy = ctrl.ControlSystemSimulation(next_move_crtl) # next_move_crtl_fuzzy.input['food_loc'] = angle next_move_crtl_fuzzy.input['collison_ang_2'] = (collison_angle_2 + collison_angle) # next_move_crtl_fuzzy.input['collison_ang'] = collison_angle # next_move_crtl_fuzzy.input['weight_snake'] = overall_weight next_move_crtl_fuzzy.input['spiral_snake'] = spiral_angle else: next_move_crtl = ctrl.ControlSystem([self.rule1, self.rule2, self.rule3]) next_move_crtl_fuzzy = ctrl.ControlSystemSimulation(next_move_crtl) next_move_crtl_fuzzy.input['food_loc'] = angle result = next_move_crtl_fuzzy.compute() result = int(next_move_crtl_fuzzy.output['Next Direction']) print(str(result)+" is the output score." ) if result >= 0 and result < 35: snake.moveLeft() print("Move Left7") print("################") if result >=35 and result <=65: snake.moveUp() print("Move up8") print("################") if result >65 and result <= 100: snake.moveRight() print("Move Right9") print("################") elif snake.direction == constants.DOWN: self.mf_pm_down() # overall_rules = [self.rule1, self.rule2, self.rule3] overall_rules = [] angle = self.get_angle_pm_down(food.y, food.x, snake.y[0], snake.x[0]) print("Angle :" +str(angle)) snake_x,snake_y = self.check_snake(snake.x[0:snake.length],snake.y[0:snake.length]) overall_man_dist = self.manhatten_distance(snake_x,snake_y) print(overall_man_dist) if snake.length > 4: for i in range(3, len(overall_man_dist)): if overall_man_dist[i] == 1: indicator = indicator + 1 if indicator ==1: print('Offending part is:' + " " +str(snake.y[0]) + " " +str(snake.x[0]) + " " + str(snake.y[i]) + " " +str(snake.x[i])) collison_angle = self.get_angle_pm_down(snake.y[i], snake.x[i],snake.y[0], snake.x[0]) print('Collison angle is :' + str(collison_angle)) elif indicator == 2: print('2nd Offending part is:' + " " +str(snake.y[0]) + " " +str(snake.x[0]) + " " + str(snake.y[i]) + " " +str(snake.x[i])) collison_angle_2 = self.get_angle_pm_down(snake.y[i], snake.x[i],snake.y[0], snake.x[0]) print('2nd Collison angle is :' + str(collison_angle_2)) else: pass if indicator == 1: print('yeah') overall_weight = self.weight_snake_pm_down(snake_x,snake_y) spiral_angle = self.spiral_pm_down(snake_x,snake_y) overall_rules.extend((self.rule1, self.rule2, self.rule3,self.rule10,self.rule11,self.rule12,self.rule13,self.rule14)) next_move_crtl = ctrl.ControlSystem(overall_rules) next_move_crtl_fuzzy = ctrl.ControlSystemSimulation(next_move_crtl) next_move_crtl_fuzzy.input['food_loc'] = angle # next_move_crtl_fuzzy.input['collison_ang'] = collison_angle next_move_crtl_fuzzy.input['weight_snake'] = overall_weight next_move_crtl_fuzzy.input['spiral_snake'] = spiral_angle elif indicator >= 2: print('bah') overall_weight = self.weight_snake_pm_down(snake_x,snake_y) spiral_angle = self.spiral_pm_down(snake_x,snake_y) overall_rules.extend((self.rule7, self.rule8, self.rule9,self.rule12,self.rule13,self.rule14)) next_move_crtl = ctrl.ControlSystem(overall_rules) next_move_crtl_fuzzy = ctrl.ControlSystemSimulation(next_move_crtl) # next_move_crtl_fuzzy.input['food_loc'] = angle next_move_crtl_fuzzy.input['collison_ang_2'] = (collison_angle_2 + collison_angle) # next_move_crtl_fuzzy.input['collison_ang'] = collison_angle # next_move_crtl_fuzzy.input['weight_snake'] = overall_weight next_move_crtl_fuzzy.input['spiral_snake'] = spiral_angle else: next_move_crtl = ctrl.ControlSystem([self.rule1, self.rule2, self.rule3]) next_move_crtl_fuzzy = ctrl.ControlSystemSimulation(next_move_crtl) next_move_crtl_fuzzy.input['food_loc'] = angle result = next_move_crtl_fuzzy.compute() result = int(next_move_crtl_fuzzy.output['Next Direction']) print(str(result)+" is the output score." ) if result >= 0 and result < 35: snake.moveLeft() print("Move Left10") print("################") if result >=35 and result <=65: snake.moveDown() print("Move Down11") print("################") if result >65 and result <= 100: snake.moveRight() print("Move Right12") print("################") self.old_snake_pos_y = snake.y[0] self.old_snake_pos_x = snake.x[0] self.current_move_number += 1 return snake, True return snake, False
Shell
UTF-8
2,032
3.171875
3
[ "Apache-2.0" ]
permissive
#!/bin/bash # -*- coding: utf-8 -*- # # Copyright 2015 eNovance SAS <licensing@enovance.com> # # 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. # # This script is an example of a post-xfer hook for rsyncd.conf. For example: # [demo-incoming] # comment = incoming # read only = false # timeout = 300 # uid = demo # gid = demo # path = /home/demo/incoming # post-xfer exec = su - demo -c /usr/local/bin/prepare_build_dir.sh export LOG_DIR="/srv/html/logs/${USER}/" [ -d ${LOG_DIR} ] || mkdir ${LOG_DIR} find ${LOG_DIR} -mindepth 1 -exec rm -rf {} \; [ -z $HOME ] && exit 1 [ -f ~/.ssh/id_rsa ] || ssh-keygen -t rsa -N "" -f ~/.ssh/id_rsa date -R > $LOG_DIR/build.txt [ -f $HOME/build.pid ] && pkill -P $(cat $HOME/build.pid) [ -d $HOME/building ] && rm -rf $HOME/building cp -R $HOME/incoming $HOME/building cd $HOME [ -d config-tools ] || git init config-tools cd config-tools if [ ! -d .git/refs/remotes/goneri/ ]; then git remote add goneri git://github.com/goneri/config-tools.git fi git fetch --all git checkout master git branch -D goneri-wip || true git reset --hard git clean -ffdx git checkout -b goneri-wip goneri/goneri-wip cd $HOME [ -d venv ] || virtualenv --system-site-packages venv # site-package: libvirt-python source venv/bin/activate pip install -rconfig-tools/virtualization/requirements.txt pip install python-swiftclient pip install python-keystoneclient cd $HOME/building $HOME/config-tools/virtualize.sh localhost &>> ${LOG_DIR}/build.txt & echo $! > $HOME/build.pid
Python
UTF-8
1,192
3.296875
3
[]
no_license
#!/usr/bin/env python3 #-*- coding:utf-8 -*- __author__ = "tongzi" from sqlalchemy import Column, String, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base #创建对象的基类 Base = declarative_base() class Student(Base): __tablename__ = 'student' #表名 #表的结构 id = Column(String(20),primary_key=True) name = Column(String(30)) age = Column(String(3)) def __str__(self): return "id: " + self.id + ", name: " + self.name + ", age: " + self.age #初始化数据库连接 engine = create_engine('mysql+mysqlconnector://root:2015201315@localhost:3306/test') #创建DBSession类型 DBSession = sessionmaker(bind=engine) #创建session对象 session = DBSession() #创建Student对象 s = Student(id='2015201315',name='Alice',age='18') session.add(s) #添加到sess session.commit() #提交即保存到数据库 session.close() #关闭session session = DBSession() # 创建Query查询,filter是where条件,最后调用one()返回唯一行,如果调用all()则返回所有行: std = session.query(Student).filter(Student.id=='2015201315').one() print('type:',type(std)) print(std)
Java
UTF-8
1,687
2.375
2
[ "MIT" ]
permissive
package org.se.lab.data; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.List; public class UserContactDAOTest extends AbstractDAOTest { private User u = new User("Fantom", "***"); private UserContact uc = new UserContact(u,2); private UserContact uc2 = new UserContact(u, 3); private UserContactDAOImpl ucdao = new UserContactDAOImpl(); @Before @Override public void setup() { tx.begin(); ucdao.setEntityManager(em); } @Test @Override public void testCreate() { em.persist(u); ucdao.insert(uc); } @Test @Override public void testModify() { em.persist(u); UserContact persisted = ucdao.insert(uc); persisted.setContactId(3); ucdao.update(persisted); Assert.assertEquals(3, uc.getContactId()); } @Test @Override public void testRemove() { em.persist(u); ucdao.insert(uc); ucdao.delete(uc); UserContact uc3 = ucdao.findById(uc.getId()); Assert.assertNull(uc3); } @Test public void testfindAll() { em.persist(u); ucdao.insert(uc); ucdao.insert(uc2); List<UserContact> ups = ucdao.findAll(); Assert.assertEquals(2, ups.size()); } @Test public void testfindById() { em.persist(u); ucdao.insert(uc); UserContact uc3 = ucdao.findById(uc.getId()); Assert.assertEquals(uc, uc3); } @Test public void testdoesContactExist() { em.persist(u); ucdao.insert(uc); Assert.assertTrue(ucdao.doesContactExist(uc.getId())); } }
Java
UTF-8
183
2.4375
2
[]
no_license
package DesignPattern; public class Parent { Parent(){ System.out.println("Parent()"); } public void test(){ System.out.println("Parent test()"); } }
Java
UTF-8
3,661
2.421875
2
[]
no_license
package com.oscgc.securevideo.server.multitenancy.impl; import java.util.concurrent.ConcurrentHashMap; import com.oscgc.securevideo.server.multitenancy.*; import org.springframework.util.StringUtils; public class DefaultTenancyContext implements TenancyContext, TenancyNamingAware { private final ConcurrentHashMap<String, Object> tenancyNamespaceCache = new ConcurrentHashMap<String, Object>(); private final ThreadLocal<String> tenancyNamespaceHolder = new ThreadLocal<String>(); private TenancyNaming tenancyNaming = new DefaultTenancyNaming(); private final TenantProvider tenantProvider; public DefaultTenancyContext(TenantProvider tenantProvider) { this.tenantProvider = tenantProvider; } @Override public TenancyNaming getTenancyNaming() { return tenancyNaming; } @Override public void setTenancyNaming(TenancyNaming tenancyNaming) { this.tenancyNaming = tenancyNaming; } @Override public String getSubNameForTenant(String tenantNamespace) { return tenancyNaming.getSubNameForTenant(tenantNamespace); } @Override public String getTenantForSubName(String subName) { return tenancyNaming.getTenantForSubName(subName); } @Override public void setCurrentTenancyNamespace(String value) { tenancyNamespaceHolder.set(value); } @Override public String currentTenancyNamespace() { return tenancyNamespaceHolder.get(); } @Override public String currentTenancyNamespaceOrDefault() { String namespace = currentTenancyNamespace(); if (StringUtils.isEmpty(namespace)) { namespace = Tenant.DEFAULT_NAMESPACE; } return namespace; } @Override public void clearTenancyNamespace() { tenancyNamespaceHolder.remove(); } @Override public boolean isTenancyNamespaceValid(String value) { if (tenancyNamespaceCache.get(value) != null) { return true; } Tenant object = tenantProvider.findByNamespace(value); if (object != null) { tenancyNamespaceCache.put(value, object); } return (tenancyNamespaceCache.get(value) != null); } @Override public Tenant currentTenancy() { if (tenancyNamespaceHolder.get() == null) { return null; } return tenantProvider.findByNamespace(currentTenancyNamespace()); } @Override public Tenant currentTenancyOrDefault() { Tenant tenant = currentTenancy(); if (tenant == null) { tenant = tenantProvider.findByNamespace(Tenant.DEFAULT_NAMESPACE); } return tenant; } @Override public boolean isDefaultTenancy() { return Tenant.DEFAULT_NAMESPACE.equals(currentTenancyNamespace()); } @Override public String getFullNameForCurrentTenant() { return tenancyNaming.getFullNameForTenant( currentTenancyNamespaceOrDefault()); } @Override public String getFullNameForTenant(String tenantNamespace) { return tenancyNaming.getFullNameForTenant( currentTenancyNamespaceOrDefault()); } @Override public String getSubNameForCurrentTenant() { return tenancyNaming.getSubNameForTenant(currentTenancyNamespaceOrDefault()); } @Override public String getRootUrl() { return tenancyNaming.getRootUrl(); } }
Java
UTF-8
2,764
2.5625
3
[ "Apache-2.0" ]
permissive
package de.fau.cs.mad.fly.HttpClient; import com.badlogic.gdx.scenes.scene2d.ui.Button; import de.fau.cs.mad.fly.profile.PlayerProfileManager; import de.fau.cs.mad.fly.profile.ScoreManager; import de.fau.cs.mad.fly.ui.DialogWithOneButton; import de.fau.cs.mad.fly.ui.screens.LevelGroupHighscoreScreen.UploadScoreClickListener; /** * Service to upload a highscore to the server; * * @author Fan, Lukas Hahmann <lukas.hahmann@gmail.com> * */ public class PostScoreHttpRespListener implements FlyHttpResponseListener { /** {@link Button} to deactivate when upload was successful */ private Button uploadButton; private PostHighscoreService.RequestData requestData; private UploadScoreClickListener uploadListener; /** * Creates a new {@link PostScoreHttpRespListener}, that listens to response * of the upload of a score ({@link #requestData}) to the server. * <p> * If the data is successfully uploaded, the {@link #uploadButton} is * disabled, to prevent uploading a score twice. Furthermore a * {@link DialogWithOneButton} is shown that displays weather the uploading * was successful or not. Therefore the {@link #stageToShowMessage} is * necessary. * * @param requestData * @param uploadButton * @param stageToShowMessage */ public PostScoreHttpRespListener(PostHighscoreService.RequestData requestData, Button uploadButton, UploadScoreClickListener uploadListener) { this.requestData = requestData; this.uploadButton = uploadButton; this.uploadListener = uploadListener; } @Override public synchronized void successful(Object obj) { uploadButton.setDisabled(true); requestData.Score.setIsUploaded(true); int playerProfileId = PlayerProfileManager.getInstance().getCurrentPlayerProfile().getId(); ScoreManager.getInstance().updateIsUploaded(requestData.Score, playerProfileId, requestData.LevelGroupID, requestData.LevelID); if (requestData.Score.getServerScoreId() <= 0) { PostHighscoreService.ResponseData response = (PostHighscoreService.ResponseData) obj; if (response != null) { requestData.Score.setServerScoreId(response.scoreID); } ScoreManager.getInstance().updateServerScoreId(requestData.Score, playerProfileId, requestData.LevelGroupID, requestData.LevelID); } uploadListener.uploadSuccessfull(); } @Override public synchronized void failed(String msg) { uploadButton.setDisabled(false); uploadListener.uploadFailed(); } @Override public void cancelled() { // currently it is not possible to cancel the upload process } };
Markdown
UTF-8
7,864
2.765625
3
[]
no_license
--- title: Overview of Share extension points --- An extension point is an interface that a developer can use to customize the Share web application in a supported way. There are a number of extension points that can be used to do things like adding custom pages, hiding content on existing pages, display custom metadata, modify the menu, and so on. To fully understand the extension points it is a good idea to first read through the [Share Architecture]({% link content-services/community/develop/software-architecture.md %}#sharearchitecture) section. Also, you should get familiar with the [Alfresco SDK]({% link content-services/community/develop/sdk.md %}) as it is the recommended way of developing Share extensions. The Share extension points can be grouped into three different categories: * **Declarative** - XML configuration that requires no coding * **Programmatic** - Code that adds new functionality * **Override** - Code that overrides default behavior of Share The following table lists all the extension points that are available to you when customization the Share web application: |Extension Point Name|Description|Category|Support Status| |--------------------|-----------|--------|--------------| |[Share Configuration]({% link content-services/community/develop/share-ext-points/share-config.md %})|A lot of customizations to the Share UI can be done via configuration, get familiar with what can be achieved with configuration before attempting any programming customizations.|Declarative|Full Support| |[Form Controls]({% link content-services/community/develop/share-ext-points/form-controls.md %})|When defining a form the form controls for each field controls how the field is displayed and handled.|Programmatic|Full Support| |[Form Processors]({% link content-services/community/develop/share-ext-points/form-processors.md %})|Form processors control the persistence of form data and the generation of the form template for a specific item such as a node, task, type, or action. Custom Form Processors can be implemented to support a new kind of item.|Programmatic|Full Support| |[Form Processor Filters]({% link content-services/community/develop/share-ext-points/form-processor-filters.md %})|Form filters can be used to intercept a form processor's persist form data call and generate form template call. "Before" and "After" method hooks are available in the filter to control form data persistence and form template generation.|Programmatic|Full Support| |[Form Field Validation Handlers]({% link content-services/community/develop/share-ext-points/form-field-validation-handlers.md %})|A validation handler is a small JavaScript function that gets called by the forms runtime when a field value needs to be validated.|Programmatic|Full Support| |[Evaluators]({% link content-services/community/develop/share-ext-points/evaluators.md %})|Component visibility in the Share user interface can be controlled by Evaluators.|Declarative and Programmatic|Full Support| |[Site Presets]({% link content-services/community/develop/share-ext-points/site-presets.md %})|A site preset contains the initial configuration for a Share site, such as the site Dashboard layout.|Declarative|Full Support| |[Share Themes]({% link content-services/community/develop/share-ext-points/share-themes.md %})|The Share web application comes with a number of themes that can be used to set the look and feel of the application. It is also possible to create your own custom UI themes.|Declarative|Full Support| |[Document Library]({% link content-services/community/develop/share-ext-points/doclib.md %})|The Document Library page has several extension points that can be used to customize its behavior, such as actions.|Declarative and Programmatic|Full Support| |[Surf Extension Modules]({% link content-services/community/develop/share-ext-points/surf-extension-modules.md %})|Surf Extension Modules are the main tool to use when adding, updating, or hiding content in the Share User Interface (UI). They can be deployed and un-deployed during runtime. A module is defined in XML and stored in the `site-data/extensions` directory.|Declarative and Programmatic|Full Support| |[Surf Web Scripts]({% link content-services/community/develop/share-ext-points/web-scripts.md %})|When you look under the covers of the Share web application you will notice that most of the functionality is implemented as Surf Web Scripts. This is true for both Pages and Dashlets.|Declarative and Programmatic|Full Support| |[Surf Web Script JavaScript Root Objects]({% link content-services/community/develop/share-ext-points/javascript-root-objects.md %})|A number of JavaScript root objects are available when you are implementing a controller for a Surf Web Script, such as `page` and `remote`. Sometimes you might have custom Java code that you want to call from JavaScript controllers, this is possible by adding custom JavaScript root objects.|Programmatic|Full Support| |[Surf Pages]({% link content-services/community/develop/share-ext-points/surf-pages.md %})|The Alfresco Share web application is built up of a main menu from which you can navigate to a number of pages.|Declarative and Programmatic|Limited Support (Use Aikau Pages instead)| |[Surf Dashlets]({% link content-services/community/develop/share-ext-points/surf-dashlets.md %})|The Share web application has a special page called Dashboard, which contains windows (think Portlets) of content called dashlets.|Declarative and Programmatic|Limited Support (Use Aikau Dashlets instead)| |[Surf Widgets]({% link content-services/community/develop/share-ext-points/surf-widgets.md %})|The Share web application is built up of a main menu, pages, and dashlets. The pages and dashlets are mainly processed on the server side as web scripts. When client side processing is needed in the form of browser JavaScript and CSS then this is contained in Widgets.|Programmatic|Full Support| |[Aikau Menus]({% link content-services/community/develop/share-ext-points/aikau-menus.md %})|The main menu of Share is implemented with the new Aikau UI development framework.|Programmatic|Full Support| |[Aikau Pages]({% link content-services/community/develop/share-ext-points/aikau-pages.md %})|The Share web application is built up of a main menu from which you can navigate to a number of pages. These pages are implemented mostly in the Surf development framework. However, a number of pages, such as search, have been converted and implemented with the new Aikau development framework, see architecture section.|Declarative and Programmatic|Full Support| |[Aikau Dashlets]({% link content-services/community/develop/share-ext-points/aikau-dashlets.md %})|The Share web application has a special page called Dashboard, which contains windows of content called dashlets. Currently most of these dashlets are Spring Surf dashlets, but they will eventually be converted to Aikau dashlets.|Declarative and Programmatic|Full Support| |[Aikau Widgets]({% link content-services/community/develop/share-ext-points/aikau-widgets.md %})|Aikau pages are built up of widgets. There are two types of widgets, presentation widgets and service widgets. These JavaScript widgets are Dojo classes. A widget can have its own CSS, HTML, and Properties.|Programmatic|Full Support| |[Modifying OOTB Code]({% link content-services/community/develop/share-ext-points/modify-ootb-code.md %})|Most of the Share UI functionality can be traced back to a web script in one place or another. Sometimes it is useful to be able to override the controller or template of one of these out-of-the-box web scripts. Same things goes for other out-of-the-box code for things like pages and dashlets.|Override|Full Support via [Surf Extension Modules]({% link content-services/community/develop/share-ext-points/surf-extension-modules.md %})|
PHP
UTF-8
8,033
2.515625
3
[]
no_license
<?php namespace App\Model; use Doctrine\ORM\Mapping as ORM; /** * Model\Certificado * * @ORM\Entity() * @ORM\Table(name="certificado") */ class Certificado { /** * Tipos */ const PART_PALESTRA = 0; const PART_MINICURSO = 1; const PART_MARATONA = 2; const APRE_MINICURSO = 3; const APRE_PALESTRA = 4; const PUBL_ARTIGO = 5; const ORG_PALESTRA = 6; const ORG_EVENTO = 7; const APRE_EVENTO = 8; const GRP_ESTUDO = 9; const ESTAGIO = 10; const GET = 11; const REPRESENTACAO = 12; const LING_ENTRANGEIRA = 13; const CERT_CURSO = 14; const EMP_JUNIOR = 15; const VIVENCIA = 16; const PART_EVENTO = 17; const MONITORIA = 18; const TP = 19; const IC = 20; const TA = 21; /** * @ORM\Id * @ORM\Column(type="integer") * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @ORM\ManyToOne(targetEntity="Usuario", inversedBy="certificados") * @ORM\JoinColumn(name="usuario", referencedColumnName="id", nullable=false) */ protected $usuario; /** * @ORM\Column(type="string", length=255, nullable=false) */ protected $nome; /** * @ORM\Column(type="string", length=255, nullable=false) */ protected $nome_impresso; /** * @ORM\Column(type="string", length=255, nullable=false) */ protected $extensao; /** * @ORM\Column(type="smallint", nullable=false) */ protected $tipo; /** * @ORM\Column(type="boolean", nullable=true) */ protected $valido; /** * @ORM\Column(type="integer", nullable=false) */ protected $num_horas; /** * @ORM\Column(type="date", nullable=true) */ protected $data_inicio; /** * @ORM\Column(type="date", nullable=true) */ protected $data_fim; /** * @ORM\Column(type="date", nullable=true) */ protected $data_inicio1; /** * @ORM\Column(type="date", nullable=true) */ protected $data_fim1; /** * @ORM\Column(type="date", nullable=true) */ protected $data_inicio2; /** * @ORM\Column(type="date", nullable=true) */ protected $data_fim2; public function __construct() { } /** * @return mixed */ public function getId() { return $this->id; } /** * @param mixed $id * @return Certificado */ public function setId($id) { $this->id = $id; return $this; } /** * @return mixed */ public function getUsuario() { return $this->usuario; } /** * @param mixed $usuario * @return Certificado */ public function setUsuario($usuario) { $this->usuario = $usuario; return $this; } /** * @return mixed */ public function getNome() { return $this->nome; } /** * @param mixed $nome * @return Certificado */ public function setNome($nome) { $this->nome = $nome; return $this; } /** * @return mixed */ public function getNomeImpresso() { return $this->nome_impresso; } /** * @param mixed $nome_impresso */ public function setNomeImpresso($nome_impresso): void { $this->nome_impresso = $nome_impresso; } /** * @return mixed */ public function getExtensao() { return $this->extensao; } /** * @param mixed $extensao * @return Certificado */ public function setExtensao($extensao) { $this->extensao = $extensao; return $this; } /** * @return mixed */ public function getTipo() { return $this->tipo; } /** * @param mixed $tipo * @return Certificado */ public function setTipo($tipo) { $this->tipo = $tipo; return $this; } /** * @return mixed */ public function getValido() { return $this->valido; } /** * @param mixed $valido * @return Certificado */ public function setValido($valido) { $this->valido = $valido; return $this; } static public function getAllTipos() { return [ Certificado::PART_PALESTRA => 'Participação em Palestra', Certificado::PART_MINICURSO => 'Participação em Minicurso', Certificado::PART_MARATONA => 'Maratona de Programação', Certificado::APRE_MINICURSO => 'Apresentação de Minicurso', Certificado::APRE_PALESTRA => 'Apresentação de Palestra', Certificado::PUBL_ARTIGO => 'Publicação de Artigo', Certificado::ORG_EVENTO => 'Organização de Evento', Certificado::APRE_EVENTO => 'Organizacao de Palestra', Certificado::GRP_ESTUDO => 'Grupo de Estudo', Certificado::ESTAGIO => 'Estágio', Certificado::GET => 'Grupo de Educação Tutorial (GET)', Certificado::REPRESENTACAO => 'Representação Estudantil', Certificado::LING_ENTRANGEIRA => 'Certificação em Língua Estrangeira', Certificado::CERT_CURSO => 'Certificação na área do curso (linguagem de programação, metodologias, outros)', Certificado::EMP_JUNIOR => 'Participação na administração de empresa júnior', Certificado::VIVENCIA => 'Vivência profissional complementar na área de formação do curso', Certificado::PART_EVENTO => 'Participação em eventos (congresso, seminários...)', Certificado::MONITORIA => 'Bolsa de Monitoria', Certificado::TP => 'Treinamento Profissional', Certificado::IC => 'Iniciação Científica', Certificado::TA => 'Treinamento Administrativo', ]; } public function getNomeTipo() { return Certificado::getAllTipos()[$this->getTipo()]; } public function isInReview() { return is_null($this->getValido()); } /** * @return mixed */ public function getNumHoras() { return $this->num_horas; } /** * @param mixed $num_horas */ public function setNumHoras($num_horas): void { $this->num_horas = $num_horas; } /** * @return mixed */ public function getDataFim() { return $this->data_fim; } /** * @return mixed */ public function getDataInicio() { return $this->data_inicio; } /** * @param mixed $data_fim */ public function setDataFim($data_fim): void { $this->data_fim = $data_fim; } /** * @param mixed $data_inicio */ public function setDataInicio($data_inicio): void { $this->data_inicio = $data_inicio; } /** * @return mixed */ public function getDataFim1() { return $this->data_fim1; } /** * @return mixed */ public function getDataFim2() { return $this->data_fim2; } /** * @return mixed */ public function getDataInicio1() { return $this->data_inicio1; } /** * @return mixed */ public function getDataInicio2() { return $this->data_inicio2; } /** * @param mixed $data_fim1 */ public function setDataFim1($data_fim1): void { $this->data_fim1 = $data_fim1; } /** * @param mixed $data_fim2 */ public function setDataFim2($data_fim2): void { $this->data_fim2 = $data_fim2; } /** * @param mixed $data_inicio1 */ public function setDataInicio1($data_inicio1): void { $this->data_inicio1 = $data_inicio1; } /** * @param mixed $data_inicio2 */ public function setDataInicio2($data_inicio2): void { $this->data_inicio2 = $data_inicio2; } }
Java
UTF-8
8,781
2.3125
2
[ "MIT", "BSD-3-Clause", "EPL-2.0", "CDDL-1.0", "JSON", "EPL-1.0", "Apache-2.0" ]
permissive
package com.exasol.adapter.dialects; import static org.junit.Assert.assertTrue; import java.io.File; import java.lang.reflect.InvocationTargetException; import java.nio.file.Files; import java.sql.Connection; import java.util.*; import java.util.stream.Stream; import javax.json.JsonObject; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; import com.exasol.adapter.AdapterException; import com.exasol.adapter.AdapterProperties; import com.exasol.adapter.request.AdapterRequest; import com.exasol.adapter.request.PushDownRequest; import com.exasol.adapter.request.parser.RequestParser; import com.exasol.utils.JsonHelper; /** * This is an integration test for Virtual Schemas. The idea is that the <code>jdbc-adapter</code> and the Exasol * database have a common set of test data to use. By doing this we avoid to write and keep tests in multiple locations. * <p> * This class executes the given (in JSON file) test scenarios and asserts the results. * <p> * Writing a new test means writing new test data files. The test files are in JSON format and have to have the * extension <code>.json</code>. The following attributes have to be present: * <dl> * <dt><code>testSchema</code></dt> * <dd>This is the schema definition. This test does not use the schema definition, since the test case parses the * pushdown request directly.</dd> * <dt><code>testCases</code></dt> * <dd>A list of test cases to be performed on the schema. * <dd> * </dl> * <p> * The list of test cases contains: * </p> * <dl> * <dt><code>testQuery</code></dt> * <dd>A single string containing the test query. This test does not use the test query, since the test case parses the * pushdown request directly.</dd> * <dt><code>expectedPushdownRequest</code></dt> * <dd>A list of pushdownRequests as they are generated by the database. This is a list because a single query can * generate multiple push-downs (e.g. <code>JOIN</code>).</dd> * <dt><code>expectedPushdownResponse</code></dt> * <dd>For each dialect that should be tested a list of strings with the returned push-down SQLs.</dd></dd> * </dl> */ class FileBasedIntegrationTest { private static final String INTEGRATION_TESTFILES_DIR = "target/test-classes/integration"; private static final String TEST_FILE_KEY_TESTCASES = "testCases"; private static final String TEST_FILE_KEY_EXP_PD_REQUEST = "expectedPushdownRequest"; private static final String TEST_FILE_KEY_EXP_PD_RESPONSE = "expectedPushdownResponse"; static Stream<File> listTestFiles() { final File testDir = new File(INTEGRATION_TESTFILES_DIR); return Arrays.stream(testDir.listFiles((dir, name) -> name.endsWith(".json"))); } @MethodSource("listTestFiles") @ParameterizedTest void testPushdownFromTestFile(final File testFile) throws Exception { final String jsonTest = new String(Files.readAllBytes(testFile.toPath())); final int numberOfTests = getNumberOfTestsFrom(jsonTest); for (int testNr = 0; testNr < numberOfTests; testNr++) { final List<PushDownRequest> PushDownRequests = getPushDownRequestsFrom(jsonTest, testNr); final Map<String, List<String>> expectedPushdownQueries = getExpectedPushdownQueriesFrom(jsonTest, testNr); for (final String dialect : expectedPushdownQueries.keySet()) { for (final PushDownRequest PushDownRequest : PushDownRequests) { final String pushdownQuery = generatePushdownQuery(dialect, PushDownRequest, testFile.getName(), testNr); assertExpectedPushdowns(expectedPushdownQueries.get(dialect), pushdownQuery, testFile.getName(), testNr, dialect); } } } } private void assertExpectedPushdowns(final List<String> expectedPushdownQueries, final String pushdownQuery, final String testFile, final int testNr, final String dialect) { final boolean foundInExpected = expectedPushdownQueries.stream().anyMatch(pushdownQuery::contains); final StringBuilder errorMessage = new StringBuilder(); if (!foundInExpected) { errorMessage.append("Generated Pushdown: "); errorMessage.append(pushdownQuery); errorMessage.append(" not found in expected pushdowns ("); errorMessage.append(expectedPushdownQueries); errorMessage.append("). Testfile: "); errorMessage.append(testFile); errorMessage.append(" ,Test#: "); errorMessage.append(testNr); errorMessage.append(" ,Dialect: "); errorMessage.append(dialect); } assertTrue(errorMessage.toString(), foundInExpected); } private int getNumberOfTestsFrom(final String jsonTest) throws Exception { final JsonObject root = JsonHelper.getJsonObject(jsonTest); return root.getJsonArray(TEST_FILE_KEY_TESTCASES).size(); } private List<PushDownRequest> getPushDownRequestsFrom(final String jsonTest, final int testNr) throws Exception { final JsonObject root = JsonHelper.getJsonObject(jsonTest); final JsonObject test = root.getJsonArray(TEST_FILE_KEY_TESTCASES).getValuesAs(JsonObject.class).get(testNr); final int numberOfPushDownRequests = test.getJsonArray(TEST_FILE_KEY_EXP_PD_REQUEST).size(); final List<PushDownRequest> PushDownRequests = new ArrayList<>(numberOfPushDownRequests); for (int requestNr = 0; requestNr < numberOfPushDownRequests; requestNr++) { final String request = test.getJsonArray(TEST_FILE_KEY_EXP_PD_REQUEST).get(requestNr).toString(); final RequestParser parser = new RequestParser(); final AdapterRequest parsedRequest = parser.parse(request); PushDownRequests.add((PushDownRequest) parsedRequest); } return PushDownRequests; } private String generatePushdownQuery(final String dialect, final PushDownRequest PushDownRequest, final String testFile, final int testNr) throws AdapterException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { final String schemaName = "LS"; final SqlGenerationContext context = new SqlGenerationContext("", schemaName, false); final Class<?> dialectClass = getDialectClass(dialect); final SqlDialect sqlDialect = (SqlDialect) dialectClass .getConstructor(Connection.class, AdapterProperties.class) .newInstance(null, AdapterProperties.emptyProperties()); final SqlGenerationVisitor sqlGeneratorVisitor = sqlDialect.getSqlGenerationVisitor(context); try { return PushDownRequest.getSelect().accept(sqlGeneratorVisitor); } catch (final Exception e) { System.err.println("Exception in: " + testFile + " Test#: " + testNr + " dialect: " + dialect); throw e; } } protected Class<?> getDialectClass(final String dialect) throws ClassNotFoundException { final String fullyQualifiedDialectName = "com.exasol.adapter.dialects." + dialect.toLowerCase() + "." + dialect + "SqlDialect"; final Class<?> dialectClass = Class.forName(fullyQualifiedDialectName); return dialectClass; } private Map<String, List<String>> getExpectedPushdownQueriesFrom(final String jsonTest, final int testNr) throws Exception { final JsonObject root = JsonHelper.getJsonObject(jsonTest); final JsonObject test = root.getJsonArray(TEST_FILE_KEY_TESTCASES).getValuesAs(JsonObject.class).get(testNr); final JsonObject expectedResponses = test.getJsonObject(TEST_FILE_KEY_EXP_PD_RESPONSE); final Map<String, List<String>> expectedQueriesForDialects = new HashMap<>(); for (final String dialect : expectedResponses.keySet()) { final int numberOfPushdownResponses = test.getJsonObject(TEST_FILE_KEY_EXP_PD_RESPONSE) .getJsonArray(dialect).size(); final List<String> pushdownResponses = new ArrayList<>(numberOfPushdownResponses); for (int pushdownNr = 0; pushdownNr < numberOfPushdownResponses; pushdownNr++) { pushdownResponses .add(test.getJsonObject(TEST_FILE_KEY_EXP_PD_RESPONSE).getJsonArray(dialect).get(pushdownNr) .toString().replaceAll("\\\\\"", "\"").replaceAll("^\"+", "").replaceAll("\"$", "")); } expectedQueriesForDialects.put(dialect, pushdownResponses); } return expectedQueriesForDialects; } }
Java
UTF-8
7,439
2.34375
2
[]
no_license
import com.cedarsoftware.util.io.JsonWriter; import com.sun.net.httpserver.*; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.net.URI; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Arrays; import java.util.Set; import java.util.List; import java.lang.Math; import java.util.Base64; public class TPSIServer { public static void main(String[] args) throws Exception { int port = 8000; HttpContext context; HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext("/", new RootHandler()); server.createContext("/echo", new EchoHandler()); server.createContext("/redirect/", new StatusHandler()); server.createContext("/cookies", new CookiesHandler()); server.createContext("/auth", new AuthHandler()); context = server.createContext("/auth2", new Auth2Handler()); context.setAuthenticator(new BasicAuthenticator("get") { @Override public boolean checkCredentials(String username, String password) { return username.equals("admin") && password.equals("admin"); } }); System.out.println("Starting server on port: " + port); server.start(); } static class RootHandler implements HttpHandler { public void handle(HttpExchange exchange) throws IOException { displayHeader(exchange.getRequestHeaders(), "root req"); byte[] fileContent = Files.readAllBytes(Paths.get("src/main/java/index.html")); exchange.getResponseHeaders().set("Content-Type", "text/html"); exchange.sendResponseHeaders(200, fileContent.length); OutputStream os = exchange.getResponseBody(); os.write(fileContent); os.close(); displayHeader(exchange.getResponseHeaders(),"root res"); } } static class EchoHandler implements HttpHandler { public void handle(HttpExchange exchange) throws IOException { displayHeader(exchange.getRequestHeaders(), "echo req"); Headers reqHeader = exchange.getRequestHeaders(); String json = JsonWriter.objectToJson(reqHeader); String json2 = JsonWriter.formatJson(json); exchange.getResponseHeaders().set("Content-Type", "application/json"); exchange.sendResponseHeaders(200, json2.length()); OutputStream os = exchange.getResponseBody(); os.write(json2.getBytes()); os.close(); displayHeader(exchange.getResponseHeaders(),"echo res"); } } static class StatusHandler implements HttpHandler { public void handle(HttpExchange exchange) throws IOException { displayHeader(exchange.getRequestHeaders(),"redirect req"); URI uri = exchange.getRequestURI(); String path = uri.getPath(); String code = path.substring(path.lastIndexOf('/') + 1); int redirect_code = Integer.parseInt(code); System.out.println("Code is: " + redirect_code); exchange.getResponseHeaders().set("Location", "/"); exchange.sendResponseHeaders(redirect_code, -1); exchange.close(); displayHeader(exchange.getResponseHeaders(),"redirect res"); } } static class CookiesHandler implements HttpHandler { public void handle(HttpExchange exchange) throws IOException { displayHeader(exchange.getRequestHeaders(),"cookies req"); double random_base = Math.random() * 1000; int id = (int)random_base; String cookie1= "echo"+id+"="+id+"; Path=/echo; domain=localhost; HttpOnly"; String cookie2= "root"+id+"="+(id+1)+"; Path=/; domain=wp.pl; HttpOnly"; List<String> cookies = Arrays.asList(cookie1, cookie2); exchange.getResponseHeaders().put("Set-Cookie", cookies); exchange.sendResponseHeaders(200, -1); exchange.close(); displayHeader(exchange.getResponseHeaders(),"cookies res"); } } static class AuthHandler implements HttpHandler { public void handle(HttpExchange exchange) throws IOException { Headers reqHead = exchange.getRequestHeaders(); if ( reqHead.containsKey("Authorization") && reqHead.get("Authorization").get(0).indexOf("Basic ") != -1) { String auth_val = reqHead.get("Authorization").get(0); String base64Cred = auth_val.split(" ", 2)[1]; byte[] decodedCred = Base64.getDecoder().decode(base64Cred); String credentials = new String(decodedCred, StandardCharsets.UTF_8); String[] values = credentials.split(":",2); if (values[0].equals("admin") && values[1].equals("admin")) { System.out.println("Authorized");// to remove byte[] fileContent = Files.readAllBytes(Paths.get("src/main/java/auth.html")); exchange.getResponseHeaders().set("Content-Type", "text/html"); exchange.sendResponseHeaders(200, fileContent.length); OutputStream os = exchange.getResponseBody(); os.write(fileContent); os.close(); } else { String msg = "An incorrect password or login"; exchange.getResponseHeaders().set("Content-Type", "text/plain"); exchange.getResponseHeaders().set("WWW-Authenticate", "Basic real=\"get\""); exchange.sendResponseHeaders(401, msg.length()); OutputStream os = exchange.getResponseBody(); os.write(msg.getBytes()); os.close(); } }else { exchange.getResponseHeaders().set("WWW-Authenticate", "Basic real=\"get\""); exchange.sendResponseHeaders(401, -1); exchange.close(); } } } static class Auth2Handler implements HttpHandler { public void handle(HttpExchange exchange) throws IOException { byte[] fileContent = Files.readAllBytes(Paths.get("src/main/java/auth.html")); exchange.getResponseHeaders().set("Content-Type", "text/html"); exchange.sendResponseHeaders(200, fileContent.length); OutputStream os = exchange.getResponseBody(); os.write(fileContent); os.close(); } } static void displayHeader(Headers header, String title) { System.out.println("##############START - " + title + " ###################"); Set <String> keys = header.keySet(); for (String key : keys) { System.out.print(key + ": "); List<String> values = header.get(key); for (String value : values) { System.out.print(value + ","); } System.out.println(); } System.out.println("##############END###################"); } }
C++
UTF-8
810
3.390625
3
[]
no_license
// func-operator.cpp by Bill Weinman <http://bw.org/> // updated for C++EssT 2014-10-24 #include <cstdio> using namespace std; class A { int a; public: A ( const int &a ) : a(a) {} const int & value() const { return a; } }; // operator here indicates operator overload function // // lhs, rhs is a typical representation of lhs operator rhs,ie lhs+rhs // in this case // // use recerences for classes, constant refrences,when your passing // them to fns. classes are big and you don't want them on the stack, // for obvious problems(ie stack overflow). // // int operator + (const A & lhs, const A & rhs ) { puts("operator + for class A"); return lhs.value() + rhs.value(); } int main( int argc, char ** argv ) { A a(7); A b(42); printf("add em up! %d\n", a + b); return 0; }
TypeScript
UTF-8
416
2.515625
3
[ "MIT" ]
permissive
import * as React from 'react'; declare type mapper<TInner, TOutter> = (input: TInner) => TOutter; export interface StateAndUpdater<TState> { state: TState; setState: (newState: TState) => TState; } declare type StateProviderType = <TState, TExtOuter = {}>(initialState: TState | mapper<TExtOuter, TState>) => React.ComponentType<TExtOuter>; export declare const StateProvider: StateProviderType; export {};
Markdown
UTF-8
31,724
3.1875
3
[]
no_license
# How to Eat a Peach *by Diana Henry* Source: [https://www.blinkist.com/books/how-to-eat-a-peach-en](https://www.blinkist.com/books/how-to-eat-a-peach-en) ![How to Eat a Peach](https://images.blinkist.com/images/books/5ec44ee26cee070006b2fc80/1_1/470.jpg) (2018) is part cookbook, part autobiography and part travelogue. Full of ideas for delicious menus and making a mean cocktail, these blinks tell you everything you need to know about hosting a memorable dinner party. They also give you a glimpse into the mind of a chef who has mastered the art of telling stories through food, and take you on a culinary tour of the places that have inspired her the most.  # What's in it for me? Travel around the world, one meal at a time. Have you ever become restless, and wished you could expand your culinary horizons? And do you wish you could host elaborate dinner parties for friends, but feel like you don't have the skills?  If so, the blinks to **How to Eat a Peach** are required reading for you. You'll learn about how adventurous chef Diana Henry creates delicious menus for every occasion, from a sleepy lunch at home to a festive summer banquet. But even more, you'll learn about how she sees the world through food. Henry has been travelling since she was a teenager, and her cooking is formed by the places she's visited and lived in. Her menus capture the exhilaration of being in Mexico City at night, the pleasures of being on holiday on the Normandy coast, and the sensual shock of arriving in the bustle of Madrid. The idea of having a dinner party can be intimidating because it sounds so formal, conjuring up images of starched white cloths and polite conversation. In these blinks, you'll learn that the best dinner parties actually happen in messy kitchens with plenty of cocktails. Good food doesn't have to be complicated or fancy; it's just about choosing quality ingredients and preparing them with care. In these blinks, you will learn - how to make a delicious roast chicken from just two ingredients; - why a peach dessert shaped Henry's entire cooking philosophy; and - how spicy food can help to ease a broken heart. # Travel shaped Henry’s DNA as a chef. Most 16-year-olds devote their time to scrawling angsty love notes in their diaries. Not Diana Henry. If an inquisitive friend had peeked into her notebooks at the time, they would have found recipe after recipe. Henry was keenly attuned to food from a young age. She carefully observed all the meals her mother prepared, and spent hours poring over **Cordon Bleu** cooking magazines.  For Henry, food was a way of getting to know the world even before she was able to travel. She grew up in Northern Ireland, which was isolated from the rest of Europe; travel was cumbersome and expensive. By poring over exotic dishes from the rest of the world, Henry wasn't only learning about food. She was learning about other ways of life. **The key message here is: Travel shaped Henry’s DNA as a chef.** When she was fifteen, she had the chance to travel to France as an exchange student. Finally, she could immerse herself in the country she'd dreamed so much about. French people's devotion to food was a revelation. She watched as families with meager incomes devoted large parts of their paychecks to buying the perfect cheese, or spent a whole afternoon baking their own bread. Henry’s devotion to preparing food with the very best ingredients can be traced right back to that formative trip.  But her travels didn't end in France. Henry is as much an explorer as she is a chef, and the way she explores is through food.  Her recipes are experiences transmuted into meals. The soft exuberance of an Italian summer night is reconfigured into a fizzy raspberry champagne cocktail with a melon and goat cheese salad. The sensual shock of Madrid plays itself out in her recipe for jet black pulpo rice with blood-red romesco sauce. The euphoria of a trip to Mexico City while nursing a broken heart can be tasted in every zingy mouthful of sea bass ceviche and ginger-lime mango slice.  Food is sensual, and emotional. But it's also all about stories. And there’s no better way to tell a story than through a set menu: a succession of dishes designed to be eaten together. In her teenage notebook, Henry didn’t only collect recipes. She also spent ages planning special meals that she would prepare for her bemused friends, who couldn't understand why they were eating in candlelight, or what pineapple water ices **were** exactly.  Today, Henry is still most renowned for her carefully designed set menus, and her diners are now a lot more appreciative than those teenage friends were.  # Dinner parties should be all about having fun. When you think of serving an elaborate three-course menu, you might imagine a group of people solemnly gathered around a white table cloth,  sniffing their wine before they drink it and eating dainty morsels off china plates. But that's not what Henry envisions when she's planning a meal. She grew up in an Irish family that loved food, but never hosted what they called dinner parties. Rather, they had parties that included lots of food, as well as loud chatter and good whiskey and dancing around the living room to Frank Sinatra. **The key message here is: Dinner parties should be all about having fun.** Henry's belief that eating should be a festive occasion explains why each of her menus begin – and often end – with a festive alcoholic drink. Accompanying her meals with a homemade cocktail is one of her trademarks. And her belief that food is meant to be enjoyed in a social setting also informs how she cooks. For example, she has a golden rule that no more than two courses of any meal are prepared last minute. There's nothing worse than being stuck in the kitchen frantically stirring sauces while your guests wait for you at the table.  She also tries to ensure that her food facilitates conversation, instead of interrupting it. Funnily enough, that means not making food that is too complicated or obviously spectacular. Being showered with compliments as a chef is nice, but it means that people are fixated on the dishes, and aren't just enjoying being together. Her southern Italian supper menu is an excellent example of this low-fuss, high-deliciousness  type of meal. It contains only one dish that should be prepared last minute: the spaghetti with mussels, shrimps and tomato sauce is cooked in little paper parcels in the oven and needs to be served piping hot. But all the other courses can be made in advance. The fennel** taralli** - knotted bread rolls - can be made up to a week before. The starter of creamy burrata cheese with roast pepper and anchovies can be prepared in advance and assembled last minute. And the creamy homemade ice cream of candied lemon peel, ricotta and pistachio only needs to be taken out the freezer.  By carefully preparing most ingredients in advance, Henry is able to serve a decadent meal and still be the life of the party.  # Menus should balance rich, creamy dishes with light, fresh flavors. One of the first menus that Henry made as a budding young cook consisted of buckwheat blinis swimming in butter, cream and smoked salmon; guinea fowl breasts with a creamy red wine sauce, and a soufflé to end. It was a rich creamy meal from start to finish without a fresh vegetable in sight! Today, her tastes tend towards the lighter end of the scale. Most of her meals include only one course containing cream, and she makes sure to keep her food fresh with sharp flavors, citrus fruits, and fresh herbs. And almost every meal will feature a fresh green salad. **The key message here is: Menus should balance rich, creamy dishes with light, fresh flavors.** When she was living in France, Henry learned to value the bowl of simple greens served after the main course. While it looks like there's nothing to it, a green salad needs to be made with care. You should always buy whole heads of lettuce as they’re fresher, and make sure to wash and dry your salad leaves thoroughly – if wet, the vinaigrette won't cling to the lettuce. The best dressing is a simple mix of oil and vinegar, but here again – it takes care to get the right balance of acidity. Keep tasting as you make it! Some of her salads are more complex, combining fruit and different vegetables. In an Italian-inspired menu Henry begins the meal with a fennel, celery and apple salad with pomegranates and toasted hazelnuts and a lemony vinaigrette. The clean, sharp flavors are a perfect combination with the decadent and creamy wild mushroom **vincisgrassi – **a kind of lasagne – to follow. In a midsummer menu, Henry combines crispy matchsticks of beetroot and carrots with cool garlicky yoghurt.  Although she's been known to go for a rich chocolatey end to a meal, most of the time Henry chooses light, fruity desserts. For example, she completes a late summer menu with a compote of raspberries, blackberries and figs served in a syrupy late-harvest riesling. The citrusy flavor of her pink grapefruit and basil ice cream adds a sweet tartness to a dinner of spinach gnocchi and roast lamb. Coming up with a good menu is all about balance – which Henry knows. Creamy indulgence tastes even better alongside tangy, fresh flavors. # Eating seasonally is not only more ethical, it also makes for better meals.  The benefits of seasonal eating are now widely accepted. Not only is locally sourced food more ethical in terms of environmental impact, it also tastes better.  Henry has believed in these principles long before they were fashionable, but she also has another reason for eating seasonally. For her, meals are not only about food; they're events. Seasonal factors like the weather and even the fragrances wafting in from the garden will influence these events because they affect what people feel like eating. **The key message here is: Eating seasonally is not only more ethical, it also makes for better meals.  ** In order to celebrate the start of the season, Henry chooses some of her favorite produce that's only available at that specific time of year. For example, for a spring meal she concocted a starter of green asparagus with a homemade pistachio pesto, fresh radish and green peas. Eating that, you can practically feel the freshness of spring unfurling. And no summer meal would be complete without the tangy sweetness of apricots. To celebrate the start of the warm months, Henry created a meal around the glory of an apricot and almond tart. The meal begins with two starters: moreish zucchini, ricotta, and pecorino fritters and a delicate salad made with sea bass **crudo** with radishes and nasturtium flowers.  As a main course, Henry roasts a whole chicken with lemons. After bashing the lemons with a rolling pin to soften them, and then pricking them all over, they’re inserted whole inside the chicken. Add some salt and pepper and **voilà,** it’s good to go. As it bakes, the lemon creates delicious juices which mingle with the natural fat of the chicken to create a tasty sauce.  And then, of course, there's the apricot and almond tart to finish. Apricots contain an acidity that balances sugary flavors, and cooking brings out the best of them. Even the most uninspiring apricots get a rich honey sweetness when baked. The dessert is a perfect end to a mid-summer meal. The season doesn’t only dictate what products are available; it informs how we feel and what we want to eat. Meals planned around fresh local products can help to fulfill these seasonal cravings. # The best dishes are daringly simple. On her first trip to Italy, Henry was eating dinner outside on a summer evening when she noticed a waiter carrying a bowl of peaches over to the diners at a neighboring table. Everybody took a peach and then cut it up, dropping the slices into a glass of chilled Moscato wine. They left the slices to muddle in the wine for a while, then ate them and drank the peach-infused wine. Henry was enthralled; the dessert had been savored as if it were the most complicated piece of** patisserie**, but it hadn't required any cooking, or even chopping. At the same time, it had been served with the utmost care and attention to detail. Everything was perfect,  from the quality of the peaches to the glasses they were served in.  **The key message here is: The best dishes are daringly simple.** This experience came to symbolize Henry's philosophy that good meals are created with simple ingredients served with attention to detail. It was a philosophy Henry kept coming back to when she found herself being momentarily swayed by food fads like **nouvelle cuisine **which involved chefs creating finickity gels and assembling plates of microscopic food with tweezers.  As an ode to the peach dessert, Henry has created a special menu. It's a perfect summer dinner that sums up her approach to preparing meals using the best ingredients with minimum fuss.  To set the tone, she serves a Summer Sandal – a fizzy, fruity cocktail prepared with strained raspberries. To follow, she serves toasted sourdough bread topped with a paste of green fava beans, garlic, lemon, and mint.  As a starter, she serves a juicy wedge of cantaloupe melon with creamy goat cheese and a lavender – red wine dressing. The main course consists of a whole fish roasted in the oven with fennel and served with garlicky anise aioli and roasted tomatoes.  And then, finally, comes the famous dessert which inspired the meal: white peaches served whole alongside a bottle of delicious chilled dessert wine like Moscato.  This isn’t a pretentious meal, but it is a careful one. Every ingredient belongs on the plate, and every dish is perfectly prepared. To try out this menu for yourself, check out our bonus blink at the end for a more detailed description of the menu. # **“Menus, no matter how simple, are made better by small things: flowers, candles, a pitcher of water.”** # Henry’s menus reveal how varied French cuisine can be.   When we think of French food we may think of some classics, like snails in garlic or **boeuf bourguignon**. But there's so much more to it than that. Each region of France has its own delectable specialties, drawing on local produce and cooking traditions. Henry has travelled all over France, intent on discovering the tastes of every region. Her menus are steeped in these specific experiences and have an exacting regional specificity. For example, a menu inspired by carefree holidays at the seaside in Brittany pays tribute to her memories of eating oysters with sourdough bread from a roadside stall in the wild wind, with the tang of the sea in the air.  **The key message here is: Henry’s menus reveal how varied French cuisine can be.  ** She starts the meal with an artfully simple starter: leeks steamed until just perfectly tender and then dressed with a breton vinagrette of white wine vinegar, olive oil, capers and herbs. The leeks are followed by rich homemade pork rillettes and a large dish of mussels with cream, garlic, parsley and white wine. To finish, she serves a paper-thin crepe, with caramelized apple and thick cream. The pleasures of a seaside holiday are captured in this one meal. To encapsulate her experience of visiting the Lot Valley and Dordogne in south-west France, Henry creates a more intense, autumnal menu that pays tribute to the complex, layered cooking she tasted there. The meal starts with an **aperitif agenais** – rich, rum-soaked prunes covered in chilled champagne. As a starter, she makes crisp puff pastry squares covered in spinach, crumbled blue cheese, and caramelized onions. To follow is a roasted quail, marinated in herbs and brandy and served with **aillade – **a creamy walnut sauce famous in the region. To go with the quail, Henry recommends making sautéed wild mushrooms with potatoes and the simplest green salad tossed with a hazelnut vinaigrette.  Her moist fig and honey cake made with port and rosemary becomes a perfectly comforting end to the meal. By first poaching the figs in a syrup of port, lemon juice, rosemary and honey, Henry coaxes out the richest flavors from the fruit before allowing them to caramelize as they bake on top of the cake.  Although not all of us can indulge in holidays in the French countryside, these meals can take us there. # Henry’s Spanish menu is intense and rich – just like the country itself.  Henry's first visit to Spain was a sensory overload; smells of leather and garlic, loud conversations, and crowded bars. She'd read the bittersweet descriptions of the country written by Lorca and seen the dark, somber portraits by El Greco, and being there felt just as moodily high-pitched as their art suggests.  Spain has fascinated and intrigued her ever since. The fraught political history under Franco reminds her of the Troubles she grew up in in Northern Ireland. She marvels at the capacity that people seem to have for embracing darkness and melancholy but also for living life so fully. There’s an electric aliveness in Spain that keeps people up dancing and drinking and talking and singing all night! **The key message here is: Henry’s Spanish menu is intense and rich – just like the country itself.**** ** How do you express such a sensual intensity in just one meal? Henry decided to create a menu that centred around the most intense dish she'd ever tasted: **arroz negro**. Arroz negro is a rich risotto made in Catalonia that is colored jet black with squid or cuttlefish ink. It tastes of what Henry describes as “darkness and the sea.” To go with it, she created a romesco sauce made of tomatoes, red peppers, and garlic blistered on the grill and then mixed in a food processor with ground almonds and hazelnuts. The sauce is sharp and vibrant, given depth by the nuts and the rich charred flavor of the peppers. The plate of food is also visually arresting: a gash of red sauce in a sea of black.  To accompany the rice,  Henry serves a salad of fennel basted in a sauce of orange zest and sherry. As it cooks, the fennel becomes gold and caramelized. It’s served with goat cheese, hazelnuts, and olive oil.  And for dessert, she makes the richest possible ice cream out of the dark chocolate and Pedro Ximenez sherry. It's so decadent that it can only be eaten slowly, spoon by spoon. The very best way to end a meal designed to capture the intense pleasures of Spain.  # Spicy food and lots of mezcal can be good for heartbreak.  When her plane touched down in Mexico in the middle of the night, Henry felt exhilarated. The trip had been planned as a distraction from a broken heart; she'd just been dumped by her boyfriend. When she walked into her hotel at one in the morning to find a band playing La Bamba in a raucous bar serving shots of mezcal, she knew it would do the trick. Mexico entranced her with its bright colors, and its vivid flavors. Mexican food turned out to be about so much more than the guacamole with tacos served in Europe. It was delicate, rich, and complex. Today, when she wants a jolt of the exuberant heat that helped to heal her heart, Henry prepares a menu of the dishes she loved so much while she was there. **The key message here is: Spicy food and lots of mezcal can be good for heartbreak. ** She starts with a ceviche which is made with the freshest white fish – like sea bass or mackerel – sliced thinly and pickled on the plate in lime juice. The fish is layered with avocado slices, pomegranate seeds, chillis and cilantro as a delicate starter. To follow, she prepares a **tinga poblana** – a rich, slow-cooked stew made with pork – which is made with chillies and scorched tomatoes which add a caramelized note. It's served with ripe avocados, sour cream, and crumbled goat cheese. On the side, she serves **arroz verde - **or green rice – and a roast pumpkin and cauliflower dish with black beans and yet more chilis.  She brings together the zesty flavors of the meal with a simple dessert of “mango cheeks” – the plump round sides of a mango. The mangos are served in a bowl, adorned with the fiery lime-ginger syrup. When Henry is searching for even more heat to lift the spirits, she turns to Asian cuisine. Southeast Asian food expertly combines hot, sour, salty and sweet flavors together. To celebrate this addictive combination, Henry created a pan-Asian smorgasbord of dishes. To start, she makes the Thai snack food “galloping horses” – sweet and salty chicken-shrimp paste served on pineapple slices. It’s followed by a spicy stir-fry of shrimps with basil and lime accompanied by a Korean pickled cucumber salad and braised pork cooked over three hours with a sticky glaze of the Indonesian sauce **kecap manis** with ginger, chillies and star anise. To finish, she serves a fragrant sago pudding cooked with coconut milk and pandan leaves. These meals are guaranteed to make you feel alive, no matter how gloomy the weather or the state of your heart.  # **“There is poetry in menus. They can transport you to the Breton coast, or a Saturday night in Manhattan; they are short stories.” ** # Food can provide comfort, and remind us of home.  Food is about adventure, but it's also about comfort. And there's nothing more comforting than home. For Henry, the most nostalgic food will always be the kind of fare she ate when she was growing up in Northern Ireland. Things like Guinness bread, made with molasses and buttermilk, or seafood–like smoked eel, cockles, or mussels. The food makes her think of her father, and childhood holidays, and the exuberance of the place where she was born.  **The key message here is: Food can provide comfort, and remind us of home. ** The strong sensual associations we have with food explain why immigrants to new countries are so set on bringing their culinary traditions with them; it’s a way of tasting home. To go out to eat in a city like New York is to sample the “edible history” of its inhabitants from China, Italy, Germany, West India and Eastern Europe–  the food made by immigrants and refugees who tried to create a new home by making the meals they loved best.  Sometimes, a craving for the comfort of home is much more literal: we just want to stay inside and hibernate. Or just have a few loved ones over to share a cosy meal. Of course, that urge becomes much more intense as the winter months roll around bringing cold, rainy days. While many of Henry's menus are designed to evoke the festive and exotic, she also knows how to cater to comfort. For example, her menu “I Can Never Resist Pumpkins” is a collection of all the most delicious, warming foods.  To start off with, she suggests serving vegetables like roasted Jerusalem artichokes and broccolini alongside a hazelnut and roast pepper relish. To follow, there's a warming pumpkin soup, made with a rich chicken stock and served with sage butter and freshly-baked Tuscan grape bread. Fresh bread not only tastes delicious, the warmth of the oven and smell of it baking creates a cosy cocoon on gray days when the rain is pounding down outside.  Then, to finish off the meal, Henry makes a decadent Turinese hot chocolate, prepared with dark chocolate, espresso, milk, and full cream. And she recommends adding some grappa or brandy for even more of a kick.  After a meal like that there's nothing for it but to curl up in front of the fire with a good book, or indulge in a sleepy afternoon siesta.   # You can plan your own menu inspired by Henry’s approach. By now you've probably become very inspired by Henry's festive menus. But what about if you want to plan your own meal from scratch? Planning the perfect menu is easy, if you just follow some of Henry’s key principles. The first question you can ask yourself is, what are you trying to say with the meal? Henry has said that her meals are like stories – they express something, be it a festive occasion, a memory of a place, or an ode to a particular season. What is it that you would like your guests to experience through your food? **The key message here is: You can plan your own menu inspired by Henry’s approach.** Then, think about the season and setting for the meal. Are you serving lunch next to the fire, or a summer dinner amidst the trees? The seasonal setting won't only influence the kind of produce available, it will also affect what kind of food you feel like.  Once you've got those factors clearly in mind, you can start thinking about the ingredients you'd like to work with. Do you have a love of beetroots, and feel like building a meal around their sweet, earthy flavors? Are mussels in season? Once you've decided on some key ingredients, or even a favorite dish, it will be easy to build the meal around that. As we’ve seen, Henry often begins with a favorite starter or even dessert, and works forwards (or backwards) from there. When composing your menu, keep Henry’s principles of balance and harmony in mind. Think about how to combine colors, textures, and the temperatures, making sure to mix up soft bakes with crunchy salads and hot mains with cooler sides. Variety makes meals feel more balanced, and the individual elements become more distinct.  Of course, if you're serving several courses, you should also think about how filling your dishes are. It would be a big pity if your guests are stuffed after their first course, and can't enjoy the dishes to follow. And, last, but definitely not least, make sure that whatever you serve is of the best possible quality. A good piece of bread can make a meal – a mediocre one can break it. # Try out Henry’s iconic menu. Want to try out the menu that inspired the title of Henry’s book -- and her entire cooking philosophy? We’ve included some instructions here so you can make your own version of “How to Eat a Peach”. This menu was especially designed for those balmy summer nights when you’re sitting in the garden  with a group of friends, enjoying a long leisurely meal.  To set the tone, Henry serves a fruity cocktail called a Summer Sandal. To make it, you need to combine half a cup of sugar with a pound of raspberries and the juice of one lemon. Place these ingredients in a blender and combine. Then strain the mixture through a mesh strainer to remove the seeds. Add three quarters of a cup freshly squeezed orange juice. Divide the mixture between six glasses, and then add one tablespoon of Cointreau and another of vodka to each glass. Top up with very cold sparkling wine just before you serve! To follow, she serves  two starters. The first is toasted sourdough bread topped with a fava bean, mint and lemon mash.  To make it, cook 2 and a half cups of fava beans in boiling water until tender. Rinse in cold water, and then slip off the skins. The beans are then blended with a garlic clove, lemon juice, white balsamic vinegar, mint and olive oil. Season to taste salt and pepper.  Then toast six slices of sourdough bread in the oven until golden brown. Rub garlic and olive oil over each slice, and top with a generous scoop of the fava bean mix. You can add a few chunks of ‘nduja - a spicy spreadable chorizo.   The second starter is a simple salad made with a juicy wedge of cantaloupe melon with creamy goat cheese and a lavender – red wine dressing.  To make the dressing, heat a cup of red wine with three tablespoons of honey and a tablespoon of white or red wine vinegar. Once the honey has melted, pour the mixture into a heatproof jug with 2 lavender sprigs. Season with salt flakes and black pepper. Arrange slices of the melon on plates with chunks of the goat cheese, and then spoon the dressing over. As a main course, Henry serves a whole baked sea bass with fennel and aioli. To start, she slices two large fennel bulbs into wedges, and tosses them with lemon juice, toasted fennel seeds, orange zest and olive oil. After seasoning, she roasts the wedges in the oven for twenty minutes in a foil-covered dish. She then stuffs the fish with fresh dill, and lays it atop the roasted fennel, sprinkling with toasted fennel seeds and olive oil. After the dish has been in the oven for around half an hour, she sprinkles a third of a cup of fresh orange juice and some more fresh dill over the fennel. Bake for a further five minutes and then take out of the oven.  While the fish is in the oven, you can make the fresh aioli by crushing two garlic cloves with salt. Combine the garlic with two egg yolks and a teaspoon of Dijon mustard. Then add a cup of olive oil drop by drop while mixing continuously with a wooden spoon or electric mixture. When all the oil has been incorporated, add some finely chopped fennel, fennel fronds, toasted fennel seeds and half a teaspoon of Pernod. Season with salt, pepper and lemon juice and serve alongside the fish.  As a side, Henry serves **tomates provençales aux anchois. **To make it, cut eight plum tomatoes in the oven and put them in a single layer in a baking dish. Cover each tomato half with some slices of anchovy and garlic, and drizzle oil from the anchovies over the tomatoes. Then combine a cup of stale bread crumbs with a spoon of lemon zest and 4 sprigs of thyme. Spoon the crumbs on top of the tomatoes and then bake in the oven for around half an hour until the top is crispy.  To bring the summer meal to a sweet end is the famous dessert which inspired the meal: white peaches served whole alongside a bottle of delicious chilled dessert wine like Moscato.  Bon appetit!  # Final summary The key message in these blinks: **A good meal is about so much more than just sustenance. It can transport us to different places, provide a sensual link to special people or memories, and provide comfort in dark times. The best dinner parties are meticulously prepared with attention to details. At the same time, they  aren’t pretentious or fussy. The main aim of a meal should always be to have fun and enjoy each other’s company. ** Actionable advice: **Practice the art of restraint. ** When planning a menu it can be very tempting to cram in just one more interesting dish. But not only can that throw off your planning by keeping you too busy in the kitchen, it can actually take away from the deliciousness of the meal. The best menus are careful compositions of select dishes. Squeezing in an extra flavor can throw off the whole balance of the meal.  **Got feedback?** We’d love to hear what you think about our content! Just drop an email to remember@blinkist.com with the title of this book as the subject line and share your thoughts! **What to read next: ******The Alice B. Toklas Cookbook ******by Alice B. Toklas.** If you’ve been enthralled by Diana Henry’s stories of travelling around the world foraging for good food, then we highly recommend you read our blinks to the Alice B. Toklas cookbook.  Like Henry, Toklas was an inveterate explorer with a nose for a good meal. Living in Paris between the wars, she kept company with other interesting expats like Picasso, Hemingway, and Fitzgerald. While they wrote and painted, she cooked her way through the French classics and pioneered the art of creating the autobiographical cookbook that contemporary food writers like Henry do so well. In these blinks, you can read about Toklas’s fascinating exploits in Paris, and get some tips for making some delicious dishes while you’re at it. If you’re ready to delve into the mind of another fascinating food writer, then the blinks to **The Alice B. Toklas Cookbook** are for you.  
C#
UTF-8
9,260
2.65625
3
[ "MIT" ]
permissive
namespace BotBits { public static class Morph { public enum Id { } public static BotBits.Team ToTeam(this Id morph) { return (BotBits.Team) morph; } public static class Portal { public const Id Down = 0, Left = (Id) 1, Up = (Id) 2, Right = (Id) 3; } public static class OneWay { public const Id Left = 0, Up = (Id) 1, Right = (Id) 2, Down = (Id) 3; } public static class FairyOneWay { public const Id Left = 0, Down = (Id)1, Right = (Id)2, Up = (Id)3; } public static class Flowers { public const Id Pink = 0, Blue = (Id)1, Orange = (Id)2; } public static class HalfBlock { public const Id Left = 0, Down = (Id) 1, Right = (Id) 2, Up = (Id) 3; } public static class Spike { public const Id Left = 0, Up = (Id) 1, Right = (Id) 2, Down = (Id) 3; } public static class Dojo { public const Id Red = 0, Blue = (Id) 1, Green = (Id) 2; } public static class Medieval { public const Id Red = 0, Blue = (Id) 1, Green = (Id) 2, Yellow = (Id) 3; } public static class SciFiSlope { public const Id TopLeft = 0, BottomLeft = (Id) 1, BottomRight = (Id) 2, TopRight = (Id) 3; } public static class SciFiStraight { public const Id Vertical = 0, Horizontal = (Id) 1; } public static class Sword { public const Id TopLeft = 0, BottomLeft = (Id) 1, BottomRight = (Id) 2, TopRight = (Id) 3; } public static class Axe { public const Id TopRight = 0, TopLeft = (Id) 1, BottomLeft = (Id) 2, BottomRight = (Id) 3; } public static class Timber { public const Id VSupport = 0, None = (Id) 1, TSupport = (Id) 2, HorizontalSupport = (Id) 3, LeftDiagonalSupport = (Id) 4, RightDiagonalSupport = (Id) 5; } public static class Piano { public const Id A0 = (Id) (-24), ASharp0 = (Id) (-23), B0 = (Id) (-22), C1 = (Id) (-24), CSharp1 = (Id) (-23), D1 = (Id) (-22), DSharp1 = (Id) (-21), E1 = (Id) (-20), F1 = (Id) (-19), FSharp1 = (Id) (-18), G1 = (Id) (-17), GSharp1 = (Id) (-16), A1 = (Id) (-15), ASharp1 = (Id) (-14), B1 = (Id) (-13), C2 = (Id) (-12), CSharp2 = (Id) (-11), D2 = (Id) (-10), DSharp2 = (Id) (-9), E2 = (Id) (-8), F2 = (Id) (-7), FSharp2 = (Id) (-6), G2 = (Id) (-5), GSharp2 = (Id) (-4), A2 = (Id) (-3), ASharp2 = (Id) (-2), B2 = (Id) (-1), C3 = (Id) 0, CSharp3 = (Id) 1, D3 = (Id) 2, DSharp3 = (Id) 3, E3 = (Id) 4, F3 = (Id) 5, FSharp3 = (Id) 6, G3 = (Id) 7, GSharp3 = (Id) 8, A3 = (Id) 9, ASharp3 = (Id) 10, B3 = (Id) 11, C4 = (Id) 12, CSharp4 = (Id) 13, D4 = (Id) 14, DSharp4 = (Id) 15, E4 = (Id) 16, F4 = (Id) 17, FSharp4 = (Id) 18, G4 = (Id) 19, GSharp4 = (Id) 20, A4 = (Id) 21, ASharp4 = (Id) 22, B4 = (Id) 23, C5 = (Id) 24, CSharp5 = (Id) 25, D5 = (Id) 26, DSharp5 = (Id) 27, E5 = (Id) 28, F5 = (Id) 29, FSharp5 = (Id) 30, G5 = (Id) 31, GSharp5 = (Id) 32, A5 = (Id) 33, ASharp5 = (Id) 34, B5 = (Id) 35, C6 = (Id) 36, CSharp6 = (Id) 37, D6 = (Id) 38, DSharp6 = (Id) 39, E6 = (Id) 40, F6 = (Id) 41, FSharp6 = (Id) 42, G6 = (Id) 43, GSharp6 = (Id) 44, A6 = (Id) 45, ASharp6 = (Id) 46, B6 = (Id) 47, C7 = (Id) 48, CSharp7 = (Id) 49, D7 = (Id) 50, DSharp7 = (Id) 51, E7 = (Id) 52, F7 = (Id) 53, FSharp7 = (Id) 54, G7 = (Id) 55, GSharp7 = (Id) 56, A7 = (Id) 57, ASharp7 = (Id) 58, B7 = (Id) 59, C8 = (Id) 60; } public static class Percussion { public const Id Base1 = 0, Base2 = (Id) 1, Snare1 = (Id) 2, Snare2 = (Id) 3, Cymbal1 = (Id) 4, Cymbal2 = (Id) 5, Cymbal3 = (Id) 6, Clap = (Id) 7, Cymbal4 = (Id) 8, Maraca = (Id) 9; } public static class Team { public const Id None = (Id) BotBits.Team.None, Red = (Id) BotBits.Team.Red, Blue = (Id) BotBits.Team.Blue, Green = (Id) BotBits.Team.Green, Cyan = (Id) BotBits.Team.Cyan, Magenta = (Id) BotBits.Team.Magenta, Yellow = (Id) BotBits.Team.Yellow; } public static class LightBulb { public const Id StandingOff = 0, HangingOn = (Id) 1, HangingOff = (Id) 2, SandingOn = (Id) 3; } public static class Pipe { public const Id TopLeft = 0, BottomLeft = (Id) 1, BottomRight = (Id) 2, TopRight = (Id) 3; } public static class Painting { public const Id Cabin = 0, River = (Id) 1, Mountain = (Id) 2, Sunset = (Id) 3; } public static class Vase { public const Id Blue = 0, Yellow = (Id) 1, Orange = (Id) 2, Red = (Id) 3; } public static class Television { public const Id Yellow = 0, Black = (Id) 1, Gray = (Id) 2, Blue = (Id) 3; } public static class Window { public const Id Yellow = 0, Gray = (Id) 1, Blue = (Id) 2, Orange = (Id) 3; } public static class Light { public const Id On = 0, Off = (Id) 1; } public static class Jump { public const Id Disabled = 0, Single = (Id)1, Double = (Id)2; } public static class NewYear2015 { public const Id Green = 0, Orange = (Id)1, Red = (Id)2, Purple = (Id)3; } public static class Sign { public const Id Wood = 0, Iron = (Id)1, Bronze = (Id)2, Gold = (Id)3; } public static class Daisy { public const Id Violet = 0, White = (Id)1, Blue = (Id)2; } public static class Tulip { public const Id Pink = 0, Red = (Id)1, Yellow = (Id)2; } public static class Daffodil { public const Id Orange = 0, Yellow = (Id)1, White = (Id)2; } } }
Python
UTF-8
2,511
3.203125
3
[]
no_license
#!/usr/bin/python3 import time import subprocess import os import multiprocessing import sys import argparse def main(): # Argparser description desc = 'Ping sweeping script designed to perform slow pings to the network to capture the active hosts' parser = argparse.ArgumentParser(description = desc) parser.add_argument("net_range", help="Base network address of target network", type=str) parser.add_argument("sleep_time", help="Quantity of time to sleep before pinging the next host", type=int) # Variable of the args parser args = parser.parse_args() print("Base network address is {}".format(args.net_range) + '0') print("Selected sleep time: {}".format(args.sleep_time)) # Scans a class C range by default for last_octect_digit in range(1, 254): address = args.net_range + str(last_octect_digit) ip_check = validate_ip(address) # If the IP validation function comes out as incorrect then quit if ip_check != True: print("Error: The IP address is not correct") sys.exit(-1) # Using fping to print out the active IP addresses from a /24 subnet mask result = subprocess.call(['fping', '-q', address]) sleep = time.sleep(args.sleep_time) if result == 0: sleep print("{} is active".format(address)) else: print("{} not alive".format(address)) def timer(value): for remaining in range(value, 0 -1): sys.stdout.write("\r") sys.stdout.write("{:2d} seconds remaining.".format(remaining)) sys.stdout.flush() time.sleep(1) sys.stdout.write("\rIP address scanned! \n") # TO VALIDATE A GIVEN IP ADDRESS TO ENSURE THE ADDRESS REMAINS WITHIN IP FORMATTING def validate_ip(ip_address): split_address = ip_address.split('.') # If there are not 4 octects in the given address then the boolean logic is false if len(split_address) != 4: return False # For the values within the split address, validate for any non-integer values for num in split_address: if not num.isdigit(): return False # Values in the actual split addressing assigned to integer values for checks value = int(num) # If the IP address contains a value which is not in range of 0 to 255 then it's invalid if value < 0 or value > 255: return False # Return the function as true if all checks pass return True main()
Markdown
UTF-8
3,246
3.59375
4
[]
no_license
# Stock-Management-Software Offline software used to keep track of the current stock in the factories or stores. It also provides a feature to generate and print bills right through the desktop app while selling the product. # Features The features include: 1. Registration of new Product ( Master ) 2. Purchase 3. Sell 4. Check Current Availability 5. Update Existing Product Details 6. Generate Existing Bill with Bill Number 7. Search the history of Customer's Purchase # 1. Registration of new Product ( Master ) This section registers a new product whenever a new product appears in the stock.\ For eg:\ Salt 500 g and Salt 100 g are 2 different products. So, the user will have to enter the details twice.\ For 1 type of product ( say salt 500 g ) there is no need to do the entry more than once. # 2. Purchase Whenever a retailer or a wholesaler purchases a new item, he/she will have to enter the quantity, Cost Price and MRP of the product. This will automatically add the quantity with the previous value. Thus, the user is free of all his tensions to find and update the previous quantity of the product.\ For eg:\ Salt 500 g has already been registered in master branch.\ Now, he/ she can purchase Salt 500 g with a given Quantity, Cost Price and MRP which will get added in the database. # 3. Sell Whenever a retailer or a wholesaler sells item, he/she will have to enter the quantity, selling price and MRP of the product. This will automatically subtract the quantity with the previous value. Thus, the user is free of all his tensions to find and update the previous quantity of the product.\ After this the user will be directed to the **Bill Section** where the bill will be generated after entering the address and required details of customer. The Name of the company and details can be edited. Just drop me a mail if u want ( address in the description ). # 4. Check Current Availability This feature displays the current available stock with all the required details in a table format. # 5. Update Existing Product Details If the user has made any kind of mistakes or want to make changes to the entered product, this section provides the facility to do that. # 6. Generate Existing Bill with Bill Number Sometimes during Audit or verification, the retailer or wholesaler needs to generate a bill which was originally given to the customer days back. It becomes to too hectic to find out and produce the bill. This section helps them to enter the bill number ( which they will get from the Search section ) and print it instantly. # 7. Search the history of Customer's Purchase Sometimes it becomes very important to search the history of the customer's purchase along with the date, time and bill number. It becomes too difficult to search if the data is mentained in excel or in any other database. This section allows them to easily find out the details of when and what of the customer's purchase. # Security This desktop app is secured using username and password. Not only that, no one can enter the details of the product which is not registered in Master Branch. No one can sell items if the quantity becomes negative or not there in the stock. There are other securities as well which are not listed here.
C++
UTF-8
639
2.609375
3
[]
no_license
// // Peon.cpp for in /home/baptiste/rendu/piscine_cpp_d10/ex00 // // Made by Bertrand-Rapello Baptiste // Login <bertra_l@epitech.net> // // Started on Fri Jan 16 12:01:48 2015 Bertrand-Rapello Baptiste // Last update Fri Jan 16 12:14:34 2015 Bertrand-Rapello Baptiste // #include "Peon.hh" Peon::Peon(std::string name) : Victim(name) { std::cout << "Zog zog." << std::endl; } Peon::~Peon() { std::cout << "Bleuark..." << std::endl; } void Peon::getPolymorphed() const { std::cout << _name << " has been turned into a pink pony !" << std::endl; } /* std::ostream &operator<<(std::ostream &os, Victim const &pe) { os << "I'm " << pe.getName() << " and i like otters !"; return os; } */
C#
UTF-8
1,485
4.09375
4
[]
no_license
using System; namespace LeetCode { public class RomanToIntSolution { public int RomanToInt(string s) { var result = 0; for (int i = 0, j = 1; i < s.Length;) { var intI = GetIntValue(s[i]); j = i + 1; if (j < s.Length) { var intJ = GetIntValue(s[j]); if (intI >= intJ) { result += intI; i++; } else { result += (intJ - intI); i += 2; } } else { result += intI; i++; } } return result; } private int GetIntValue(char c) { switch (c) { case 'I': return 1; case 'V': return 5; case 'X': return 10; case 'L': return 50; case 'C': return 100; case 'D': return 500; case 'M': return 1000; default: throw new ArgumentException("ArgumentException"); } } } }
Markdown
UTF-8
11,960
3.03125
3
[]
no_license
# Laravel Advanced Nova Media Library Manage images of [spatie's media library package](https://github.com/spatie/laravel-medialibrary). Upload multiple images and order them by drag and drop. ##### Table of Contents * [Examples](#examples) * [Install](#install) * [Model media configuration](#model-media-configuration) * [Generic file management](#generic-file-management) * [Single image upload](#single-image-upload) * [Multiple image upload](#multiple-image-upload) * [Selecting existing media](#selecting-existing-media) * [Names of uploaded images](#names-of-uploaded-images) * [Image cropping](#image-cropping) * [Custom properties](#custom-properties) * [Custom headers](#custom-headers) * [Media Field (Video)](#media-field-video) * [Change log](#change-log) ## Examples ![Cropping](https://raw.githubusercontent.com/ebess/advanced-nova-media-library/master/docs/cropping.gif) ![Single image upload](https://raw.githubusercontent.com/ebess/advanced-nova-media-library/master/docs/single-image.png) ![Multiple image upload](https://raw.githubusercontent.com/ebess/advanced-nova-media-library/master/docs/multiple-images.png) ![Custom properties](https://raw.githubusercontent.com/ebess/advanced-nova-media-library/master/docs/custom-properties.gif) ![Generic file management](https://raw.githubusercontent.com/ebess/advanced-nova-media-library/master/docs/file-management.png) ## Install ```bash composer require ebess/advanced-nova-media-library ``` ```bash php artisan vendor:publish --tag=nova-media-library ``` ## Model media configuration Let's assume you configured your model to use the media library like following: ```php use Spatie\MediaLibrary\MediaCollections\Models\Media; public function registerMediaConversions(Media $media = null): void { $this->addMediaConversion('thumb') ->width(130) ->height(130); } public function registerMediaCollections(): void { $this->addMediaCollection('main')->singleFile(); $this->addMediaCollection('my_multi_collection'); } ``` ## Generic file management ![Generic file management](https://raw.githubusercontent.com/ebess/advanced-nova-media-library/master/docs/file-management.png) In order to be able to upload and handle generic files just go ahead and use the `Files` field. ```php use Ebess\AdvancedNovaMediaLibrary\Fields\Files; Files::make('Single file', 'one_file'), Files::make('Multiple files', 'multiple_files'), ``` ## Single image upload ![Single image upload](https://raw.githubusercontent.com/ebess/advanced-nova-media-library/master/docs/single-image.png) ```php use Ebess\AdvancedNovaMediaLibrary\Fields\Images; public function fields(Request $request) { return [ Images::make('Main image', 'main') // second parameter is the media collection name ->conversionOnIndexView('thumb') // conversion used to display the image ->rules('required'), // validation rules ]; } ``` ## Multiple image upload If you enable the multiple upload ability, you can **order the images via drag & drop**. ![Multiple image upload](https://raw.githubusercontent.com/ebess/advanced-nova-media-library/master/docs/multiple-images.png) ```php use Ebess\AdvancedNovaMediaLibrary\Fields\Images; public function fields(Request $request) { return [ Images::make('Images', 'my_multi_collection') // second parameter is the media collection name ->conversionOnPreview('medium-size') // conversion used to display the "original" image ->conversionOnDetailView('thumb') // conversion used on the model's view ->conversionOnIndexView('thumb') // conversion used to display the image on the model's index page ->conversionOnForm('thumb') // conversion used to display the image on the model's form ->fullSize() // full size column ->rules('required', 'size:3') // validation rules for the collection of images // validation rules for the collection of images ->singleImageRules('dimensions:min_width=100'), ]; } ``` ## Selecting existing media ![Selecting existing media](https://raw.githubusercontent.com/ebess/advanced-nova-media-library/master/docs/existing-media.png) ![Selecting existing media 2](https://raw.githubusercontent.com/ebess/advanced-nova-media-library/master/docs/existing-media-2.png) If you upload the same media files to multiple models and you do not want to select it from the file system all over again, use this feature. Selecting an already existing media will **copy it**. **Attention**: This feature will expose an endpoint to every user of your application to search existing media. If your media upload / custom properties on the media models are confidential, **do not enable this feature!** * Publish the config files if you did not yet ```bash artisan vendor:publish --tag=nova-media-library ``` * Enable this feature in config file *config/nova-media-library* ```php return [ 'enable-existing-media' => true, ]; ``` * Enable the selection of existing media field ```php Images::make('Image')->enableExistingMedia(), ``` **Note**: This feature does not support temporary URLs. ## Names of uploaded images The default filename of the new uploaded file is the original filename. You can change this with the help of the function `setFileName`, which takes a callback function as the only param. This callback function has three params: `$originalFilename` (the original filename like `Fotolia 4711.jpg`), `$extension` (file extension like `jpg`), `$model` (the current model). Here are just 2 examples of what you can do: ```php // Set the filename to the MD5 Hash of original filename Images::make('Image 1', 'img1') ->setFileName(function($originalFilename, $extension, $model){ return md5($originalFilename) . '.' . $extension; }); // Set the filename to the model name Images::make('Image 2', 'img2') ->setFileName(function($originalFilename, $extension, $model){ return str_slug($model->name) . '.' . $extension; }); ``` By default, the "name" field on the Media object is set to the original filename without the extension. To change this, you can use the `setName` function. Like `setFileName` above, it takes a callback function as the only param. This callback function has two params: `$originalFilename` and `$model`. ```php Images::make('Image 1', 'img1') ->setName(function($originalFilename, $model){ return md5($originalFilename); }); ``` ## Responsive images If you want to use responsive image functionality from the [Spatie MediaLibrary](https://docs.spatie.be/laravel-medialibrary/v7/responsive-images/getting-started-with-responsive-images), you can use the `withResponsiveImages()` function on the model. ```php Images::make('Image 1', 'img1') ->withResponsiveImages(); ``` ## Image cropping ![Cropping](https://raw.githubusercontent.com/ebess/advanced-nova-media-library/master/docs/cropping.gif) By default you are able to crop / rotate images by clicking the scissors in the left bottom corner on the edit view. The [vue-js-clipper](https://github.com/timtnleeProject/vuejs-clipper) is used for this purpose. The cropping feature is limited to mime type of `image/jpg`, `image/jpeg` and `image/png`. **Important:** By cropping an existing image the original media model is deleted and replaced by the cropped image. All custom properties are copied form the old to the new model. To disable this feature use the `croppable` method: ```php Images::make('Gallery')->croppable(false); ``` You can set all configurations like ratio e.g. as following: ```php Images::make('Gallery')->croppingConfigs(['aspectRatio' => 4/3]); ``` Available cropping configuration, see https://github.com/timtnleeProject/vuejs-clipper#clipper-basic. It is possible to enforce cropping on upload, for example to ensure the image has the set aspect ratio: ```php Images::make('Gallery')->mustCrop(); ``` ### Disabling cropping by default By default, the cropping feature is enabled. To disable it by default for all images set `default-croppable` in `config/nova-media-library.php` to `false`: ```php return [ 'default-croppable' => false, ]; ``` ## Custom properties ![Custom properties](https://raw.githubusercontent.com/ebess/advanced-nova-media-library/master/docs/custom-properties.gif) ```php Images::make('Gallery') ->customPropertiesFields([ Boolean::make('Active'), Markdown::make('Description'), ]); Files::make('Multiple files', 'multiple_files') ->customPropertiesFields([ Boolean::make('Active'), Markdown::make('Description'), ]); // custom properties without user input Files::make('Multiple files', 'multiple_files') ->customProperties([ 'foo' => auth()->user()->foo, 'bar' => $api->getNeededData(), ]); ``` ## Show image statistics *(size, dimensions, type)* ![Image statistics](https://raw.githubusercontent.com/ebess/advanced-nova-media-library/master/docs/show-statistics.png) ```php Images::make('Gallery') ->showStatistics(); ``` ## Custom headers ```php Images::make('Gallery') ->customHeaders([ 'header-name' => 'header-value', ]); ``` ## Media Field (Video) In order to handle videos with thumbnails you need to use the `Media` field instead of `Images`. This way you are able to upload videos as well. ```php use Ebess\AdvancedNovaMediaLibrary\Fields\Media; class Category extends Resource { public function fields(Request $request) { Media::make('Gallery') // media handles videos ->conversionOnIndexView('thumb') ->singleMediaRules('max:5000'); // max 5000kb } } // .. class YourModel extends Model implements HasMedia { public function registerMediaConversions(Media $media = null): void { $this->addMediaConversion('thumb') ->width(368) ->height(232) ->extractVideoFrameAtSecond(1); } } ``` ## Temporary Urls If you are using Amazon S3 to store your media, you will need to use the `temporary` function on your field to generate a temporary signed URL. This function expects a valid Carbon instance that will specify when the URL should expire. ``` Images::make('Image 1', 'img1') ->temporary(now()->addMinutes(5)) Files::make('Multiple files', 'multiple_files') ->temporary(now()->addMinutes(10), ``` **Note**: This feature does not work with the existing media feature. # Credits * [nova media library](https://github.com/jameslkingsley/nova-media-library) # Alternatives * [dmitrybubyakin/nova-medialibrary-field](https://github.com/dmitrybubyakin/nova-medialibrary-field) # Change log ## v4.0.2 - 2022-04-26 - Fix ratio for cropping in Nova 4. Config from `Images::( ... )->croppingConfigs()` are now passed along to the `stencil-props` property of the cropper. See [cropper docs](https://norserium.github.io/vue-advanced-cropper/components/rectangle-stencil.html#props) for more details on available props. ## v4.0.1 - 2022-04-20 - Fix details component - Fix layout inconsistencies ## v4.0.0 - 2022-04-18 - Upgrade to support Laravel Nova 4 - Breaks compatibility with Laravel Nova 1,2 and 3. For those nova versions use `v3.*` - Replaced [vuejs-clipper](https://www.npmjs.com/package/vuejs-clipper) with [vue-advanced-cropper](https://www.npmjs.com/package/vue-advanced-cropper) for vue3 support Full change log in [PR #317](https://github.com/ebess/advanced-nova-media-library/pull/317) # How to contribute - You need to have Nova installed of course in your Laravel app - Work directly in the package in the `vendor` directory (webpack needs Nova to be installed) - Then from the `vendor/xxx/advanced-nova-media-library` folder: - Use a least `nvm use 14` - `yarn install` - `yarn run watch` - Work hard 🤘 - `yarn npm production` when job is finished - Make a PR
Java
UTF-8
449
2
2
[]
no_license
package com.wedo.OMS.repository; import com.wedo.OMS.entity.Resource; import com.wedo.OMS.entity.Task; import com.wedo.OMS.entity.TaskResource; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface TaskResourceRepository extends JpaRepository<TaskResource, Long> { List<TaskResource> findTaskResourcesByResource(Resource resource); List<TaskResource> findTaskResourcesByTask(Task task); }
Java
UTF-8
1,060
3.28125
3
[]
no_license
package e2; import java.util.HashSet; import java.util.Set; public class BasicBackpackApplication { public static void main (String[] args) { Set<String>backpack= new HashSet<>(); System.out.println("Backpack: " + backpack); String item1 = "toothpaste"; String item2 = "towel"; String item3 = "underwear"; backpack.add(item1); backpack.add(item2); backpack.add(item3); System.out.println("backpack: " + backpack ); if(backpack.contains("underwear"));{ System.out.println(" The backpack contains underwear "); } backpack.remove("underwear"); System.out.println("backpack: " + backpack); if(!backpack.contains("underwear"));{ System.out.println(" The backpack no longer contains underwear "); } System.out.println("backpack: " + backpack); System.out.println("backpack: " + backpack); Integer size = backpack.size(); System.out.println("backpack size: "+ size); } }
Java
UTF-8
275
1.726563
2
[ "Apache-2.0" ]
permissive
package keisuke.count.xmldefine; /** * 言語ルール定義でScriptletブロック定義を保持するクラス */ public class ScriptBlockDefine extends AbstractBlockDefine { /** * デフォルトコンストラクター */ protected ScriptBlockDefine() { } }
Python
UTF-8
416
3.015625
3
[ "MIT" ]
permissive
from coordinates_named import geohash, Coordinate, display def test_geohash_max_precision() -> None: sao_paulo = -23.5505, -46.6339 result = geohash(Coordinate(*sao_paulo)) assert '6gyf4bf0r' == result def test_display() -> None: sao_paulo = -23.5505, -46.6339 assert display(sao_paulo) == '23.6°S, 46.6°W' shanghai = 31.2304, 121.4737 assert display(shanghai) == '31.2°N, 121.5°E'
C++
UTF-8
1,188
3.34375
3
[]
no_license
#include<cstdio> #include<algorithm> #include<string> using namespace std; bool cmp(int a, int b){ return a > b; } int main(){ int x = 1, y = 2; //max() min() printf("%d %d\n", max(x, y), min(x, y)); //swap() swap(x,y); printf("x=%d y=%d\n", x, y); int a[10]={10, 12, 13, 14, 15}; string str = "abcdefghijk"; //reverse() reverse(a,a+3); reverse(str.begin()+2, str.begin()+6); for(int i=0;i<5;i++){ printf("%d ", a[i]); } printf("\n"); for(int i=0;i<str.length();i++){ printf("%c",str[i]); } //next_permutation() printf("\n"); int b[10]={1, 2, 3}; do{ printf("%d%d%d\n", b[0], b[1], b[2]); }while(next_permutation(b, b+3)); //fill() fill(b,b+3, 6); for(int i=0;i<3;i++){ printf("%d", b[i]); } printf("\n"); //sort() int c[10]={5,3,6,7,2}; sort(c, c+5, cmp); for(int i=0;i<5;i++){ printf("%d ", c[i]); } printf("\n"); //lower_bound() upper_bound() int d[10]={1, 2, 2, 3, 3, 3, 5, 5, 5, 5}; int X = 2; printf("%d, %d", lower_bound(d, d + 10, X) - d, upper_bound(d, d + 10, X) - d); return 0; }
Go
UTF-8
6,701
2.84375
3
[ "MIT" ]
permissive
package gorpc import ( "fmt" "os" "reflect" "sync" ) // ServerCodec ... type ServerCodec interface { ReadHeader(Header) error ReadRequestBody(header Header, args interface{}) error WriteResponse(header Header, reply interface{}) error } type ServerContextHandler interface { GetServerContext(Header) interface{} } type ServerContextHandlerFunc func(Header) reflect.Value func (p ServerContextHandlerFunc) GetServerContext(h Header) interface{} { return p(h).Interface() } type ServerContextFunc func(Header) interface{} func (p ServerContextFunc) GetServerContext(h Header) interface{} { return p(h) } func NewServerContextHandler(ctx interface{}) ServerContextHandler { if ctx == nil { return nil } return &serverContextHandler{ ctx: reflect.ValueOf(ctx), } } type serverContextHandler struct { ctx interface{} } func (p *serverContextHandler) GetServerContext(Header) interface{} { return p.ctx } // Server ... type Server interface { Serve() ServeRequest() error ReadFunction() (ServerFunction, error) SetContextHandler(ServerContextHandler) } type ResponseWriter interface { Header Free() Reply(interface{}) error } type ServerFunction interface { Call() Free() } // serverFunction ... type serverFunction struct { server *server svc Service rsp *header } // Call ... func (p *serverFunction) Call() { p.server.call(p.rsp, p.svc) } func (p *serverFunction) Free() { p.server.freeFunction(p) } // NewServerWithCodec ... func NewServerWithCodec(handlerManager ServiceManager, codec ServerCodec) Server { return newServerWithCodec(handlerManager, codec) } // Precompute the reflect type for error. Can't use error directly // because Typeof takes an empty interface value. This is annoying. var typeOfError = reflect.TypeOf((*error)(nil)).Elem() type server struct { handlers ServiceManager codec ServerCodec contextHandler ServerContextHandler responsePool *sync.Pool request header responseWriterPool *sync.Pool funcPool *sync.Pool *client } func newServerWithCodec(handlers ServiceManager, codec ServerCodec) *server { s := &server{ handlers: handlers, codec: codec, responsePool: &sync.Pool{ New: func() interface{} { return &header{} }, }, responseWriterPool: &sync.Pool{ New: func() interface{} { return &Response{} }, }, funcPool: &sync.Pool{ New: func() interface{} { return &serverFunction{} }, }, } return s } func (p *server) SetContextHandler(h ServerContextHandler) { p.contextHandler = h } func (p *server) Serve() { var err error for err == nil { err = p.ServeRequest() } } func (p *server) ServeRequest() (err error) { head := p.getRequest() for err == nil { head.Reset() err = p.codec.ReadHeader(head) if err != nil { continue } if p.client != nil && !head.IsRequest() { err = p.client.dealResp(head) continue } err = p.dealRequestBody(head, false) if err != nil { continue } return } if p.client != nil { p.client.dealClose(err) } return } func (p *server) ReadFunction() (sf ServerFunction, err error) { head := p.getRequest() for err == nil { head.Reset() err = p.codec.ReadHeader(head) if err != nil { break } if p.client != nil && !head.IsRequest() { err = p.client.dealResp(head) continue } sf, err = p.dealFunction(head) return } if p.client != nil { p.client.dealClose(err) } return } func (p *server) getResponse() *header { rsp := p.responsePool.Get().(*header) if rsp.Seq() == nil { return rsp } rsp.Reset() return rsp } func (p *server) freeResponse(rsp *header) { p.responsePool.Put(rsp) } func (p *server) getResponseWriter(rsp *header) ResponseWriter { w := p.responseWriterPool.Get().(*Response) w.header = rsp w.server = p return w } func (p *server) sendResponse(rsp *header, reply interface{}, withFree bool) error { e := p.codec.WriteResponse(rsp, reply) if withFree { p.freeResponse(rsp) } return e } func (p *server) getRequest() *header { return &p.request } func (p *server) getFunction() *serverFunction { return p.funcPool.Get().(*serverFunction) } func (p *server) freeFunction(f *serverFunction) { p.funcPool.Put(f) } func (p *server) getService(req, rsp *header) (s Service, ok bool, err error) { s, ok = p.handlers.Get(req.Method()) if ok { s = s.Clone() return } err = fmt.Errorf("there is no handler for the method: %s, [%w]", req.Method(), os.ErrInvalid) rsp.SetErr(err) req.SetErr(err) err = p.codec.ReadRequestBody(req, nil) if err != nil { p.freeResponse(rsp) return } err = p.sendResponse(rsp, nil, true) if err != nil && debugLog { fmt.Println("sendResponse failed: ", err.Error()) } return } func (p *server) dealFunction(req *header) (sf *serverFunction, err error) { rsp := p.getResponse() rsp.SetSeq(req.Seq()) rsp.SetMethod(req.Method()) rsp.SetContext(req.Context()) s, ok, err := p.getService(req, rsp) if !ok || err != nil { return } sf = p.getFunction() sf.server = p sf.svc = s sf.rsp = rsp err = p.getHeaderBody(req, s.GetArg()) if err != nil { p.freeResponse(rsp) return } return } func (p *server) dealRequestBody(req *header, block bool) (err error) { rsp := p.getResponse() rsp.SetSeq(req.Seq()) rsp.SetMethod(req.Method()) rsp.SetContext(req.Context()) s, ok, err := p.getService(req, rsp) if !ok || err != nil { return } e := p.getHeaderBody(req, s.GetArg()) if e != nil { p.freeResponse(rsp) err = e return } if block { p.call(rsp, s) return } go p.call(rsp, s) return } func (p *server) getHeaderBody(req *header, arg interface{}) (err error) { // Decode the argument value. // argv guaranteed to be a pointer now. return p.codec.ReadRequestBody(req, arg) } func (p *server) call(rsp *header, svc Service) { sc, ok := svc.(ServiceWithContext) if ok && p.contextHandler != nil { sc.WithContext(p.contextHandler.GetServerContext(rsp)) } sh, ok := svc.(ServiceWithHeader) if ok { sh.WithHeader(rsp) } ss, ok := svc.(SyncService) if ok { reply, err := ss.Do() if err != nil { rsp.SetErr(err) } err = p.sendResponse(rsp, reply, true) if err != nil && debugLog { fmt.Println("sendResponse failed: ", err.Error()) } return } as, ok := svc.(AsyncService) if ok { as.Do(p.getResponseWriter(rsp)) return } } // Response ... type Response struct { *header server *server } // Free ... func (p *Response) Free() { p.server.freeResponse(p.header) } // Reply ... func (p *Response) Reply(reply interface{}) error { return p.server.sendResponse(p.header, reply, false) } var responseWriterType = reflect.TypeOf(&Response{})
Go
UTF-8
2,450
3.375
3
[ "MIT" ]
permissive
package snippet import ( "bytes" "errors" "testing" "github.com/stretchr/testify/assert" ) const ( snippetText = ` snippet foo alias f abbr foo ... foobar # comment snippet multiline alias m abbr multiline ... bar fuzzbuzz ` ) func TestTestShouldStringOK(t *testing.T) { const given = ` snippet foo alias f abbr foo ... foobar snippet multiline alias m abbr multiline ... bar fuzzbuzz ` underTest, err := parse(bytes.NewBufferString(given)) assert.NoError(t, err) assert.Equal(t, "foobar\n", underTest[0].String()) assert.Equal(t, "bar\n fuzzbuzz", underTest[1].String()) } func TestShouldParse(t *testing.T) { var tests = []struct { name string given string expected list }{ {"empty", "", []*snippet{}}, { "two_with_multiline", snippetText, []*snippet{ { name: "foo", alias: "f", abbr: "foo ...", body: []string{ " foobar", "", }, bodyMinIndent: 4, }, { name: "multiline", alias: "m", abbr: "multiline ...", body: []string{ " bar", "", "\tfuzzbuzz", "", "", }, }, }, }, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { actualList, err := parse(bytes.NewBufferString(tt.given)) assert.NoError(t, err) assert.Len(t, actualList, len(tt.expected)) for i, actual := range actualList { assert.Equal(t, tt.expected[i], actual) } }) } } func TestShouldParseFail(t *testing.T) { expected := errors.New("boom") r := &errReader{expected} res, err := parse(r) assert.Nil(t, res) assert.Equal(t, expected, err) } func TestShouldFindSnippet(t *testing.T) { underTest := list([]*snippet{ {name: "foo"}, {name: "bar", abbr: "first bar"}, {name: "bar", alias: "b"}, {name: "buzz", alias: "b"}, {name: "fuzz"}, }) var tests = []struct { name string expectedIndex int given string }{ {"find by name", 3, "buzz"}, {"find by name - searches first match", 1, "bar"}, {"find by alias - searches first match", 2, "b"}, } for _, tt := range tests { tt := tt t.Run(tt.name, func(t *testing.T) { actual := underTest.Find(tt.given) assert.Equal(t, underTest[tt.expectedIndex], actual) }) } assert.Nil(t, underTest.Find("not_existent")) } type errReader struct { err error } func (r *errReader) Read(p []byte) (n int, err error) { return 0, r.err }
C++
UTF-8
1,795
3.390625
3
[]
no_license
#include <iostream> #include <fstream> #include "Maltsev_Container.h" using namespace std; void menu() { cout << endl; cout << "1. добавить элемент" << endl; cout << "2. вывести список" << endl; cout << "3. вывести список из файла" << endl; cout << "4. вывести список в файл" << endl; cout << "5. очистка" << endl; cout << "0. выход" << endl; } int main() { setlocale(LC_ALL, "Russian"); Container students; while (true) { menu(); cout << "Введите число: "; int number; cin >> number; switch (number) { case 1: { students.input(); break; } case 2: { students.output(); system("pause"); break; } case 3: { ifstream fromfile("fromfile.txt", ios::binary); if (fromfile.is_open()) { students.input_file(fromfile); fromfile.close(); } else cout << "Файл не удалось открыть" << endl; system("pause"); break; } case 4: { ofstream tofile("tofile.txt", ios::binary); if (tofile.is_open()) { students.output_file(tofile); tofile.close(); } else cout << "Файл не удалось открыть" << endl; system("pause"); break; } case 5: { students.delete_smth(); system("pause"); break; } case 0: return 0; } } }
C#
UTF-8
2,988
3.1875
3
[]
no_license
using System; using Mono.Cecil.Cil; using System.Collections.Generic; namespace LinearIr { /// <summary> /// Static Extension class for Cecil Instruction Objects. /// </summary> public static class InstructionExtensions { /// <summary> /// Checks if an instruction changes control flow. /// </summary> /// <param name="i"> An instruction </param> /// <returns> /// True if instruction is branch, conditional /// branch or return, false otherwise /// </returns> public static bool IsControlFlowInstruction(this Instruction i) { switch (i.OpCode.FlowControl) { case FlowControl.Branch: case FlowControl.Cond_Branch: case FlowControl.Return: case FlowControl.Throw: return true; default: return false; } } /// <summary> /// Get's the instructions of a method that are targets of a /// control flow instruction. For example if a jump instruction 'i' /// has instruction 't' as it's target then this method returns 't'. /// </summary> /// <param name="i"> A control flow instruction </param> /// <returns> A target instruction (first instruction after a label) </returns> public static IEnumerable<Instruction> GetControlFlowInstructionTargets(this Instruction i) { if (i.OpCode.FlowControl == FlowControl.Return || i.OpCode.FlowControl == FlowControl.Throw) return new Instruction[] { }; else if (i.Operand is Instruction) return new Instruction[] { (Instruction)i.Operand }; else if (i.Operand is Instruction[]) // This case is for the switch instruction. return i.Operand as Instruction[]; throw new InvalidOperationException( @"The given instruction is not a control transfer instruction"); } /// <summary> /// Get's whether a control flow instruction has a fallthrough block. /// Instructions that don't have fallthrough blocks include: ret, throw and rethrow. /// </summary> /// <param name="i"> The instruction to check against </param> /// <returns> A boolean value indicating the result </returns> public static bool HasFallthroughInstruction(this Instruction i) { return i.OpCode.FlowControl != FlowControl.Branch && i.OpCode.FlowControl != FlowControl.Return && i.OpCode.FlowControl != FlowControl.Throw; } /// <summary> /// Get's the label of a stack based instruction in the method body. /// This label is ultimately the address of the instruction /// in hexadecimal, counting from 0 from the first instruction of the /// method body. /// </summary> /// <param name="i"> The cil instruction </param> /// <returns> String representation of the instruction label </returns> public static String GetLabel(this Instruction i) { return String.Format("IL_{0}", i.Offset.ToString("X4")); } } }
Java
UTF-8
3,182
3.140625
3
[]
no_license
package com.example.demo.java8.steam.comparator; import com.google.common.base.Function; import org.apache.tomcat.jni.Address; import org.junit.Test; import java.util.*; import java.util.stream.Collectors; /** * created by zhenzhong on 2020/4/6 * https://blog.csdn.net/aitangyong/article/details/54880228 */ public class LambdaCompatarator2 { // Stream.sort对集合进行排序,sort有2个重载方法 //1.Stream<T>sort(); :必须实现Comparable 接口,否则会抛出异常。而且对于未排序的列表,是不稳定排序 //2.Stream<T> sort(Comparator<? super T> comparator) 使用自定义的比较器,不要求实现Comparable 接口 //使用实现了Comparable的 对象Student //stream().sorted()/Comparator.naturalOrder()/Comparator.reverseOrder(),要求元素必须实现Comparable接口。 @Test public void doTestComparator() { List<Student> students = buildStudents(); // 按照默认顺序排序 List<Student> ascList1 = students.stream().sorted().collect(Collectors.toList()); System.out.println(ascList1); // 按照自然序排序(其实就是默认顺序) List<Student> ascList2 = students.stream().sorted(Comparator.naturalOrder()).collect(Collectors.toList()); System.out.println(ascList2); // 按照默认顺序的相反顺序排序 List<Student> descList = students.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList()); System.out.println(descList); } private static List<Student> buildStudents() { List<Student> students = new ArrayList<>(); students.add(new Student(10, 20, "aty", "d")); students.add(new Student(1, 22, "qun", "c")); students.add(new Student(1, 26, "Zen", "b")); students.add(new Student(5, 23, "aty", "a")); return students; } @Test public void doTest2() { final List<Student> students = buildStudents(); final Function<Student, Integer> getName = Student::getId; // Comparator.comparing(Function keyExtractor) final Comparator<Student> comparing = Comparator.comparing(getName); //升序 final List<Student> collect = students.stream().sorted(comparing).collect(Collectors.toList()); System.out.println(collect); //降序 final List<Student> collect1 = students.stream().sorted(comparing.reversed()).collect(Collectors.toList()); System.out.println(collect1); } // https://blog.csdn.net/frankenjoy123/article/details/70739800 @Test public void doTest3() { final List<Student> students = buildStudents(); final Map<Integer, Set<String>> collect = students.stream().collect(Collectors.groupingBy(Student::getId, Collectors.mapping(Student::getName, Collectors.toSet()))); System.out.println(collect); } public interface test{ public static void test1(){ System.out.println("test1"); } default void test2(){ System.out.println("test2"); } } public interface test1 extends test{ } }
Java
UTF-8
2,426
2.109375
2
[]
no_license
package g3dtest; import g3dtest.game.GamePanel; import g3dtest.simple.SimplePanel; import org.mini.gui.*; import org.mini.gui.event.GSizeChangeListener; import org.mini.layout.UITemplate; import org.mini.layout.XContainer; import org.mini.layout.XForm; /** * @author gust */ public class G3d extends GApplication { GForm form; GMenu menu; SimplePanel simplePanel; GamePanel gamePanel; GameUIEventHandle eventHandle; @Override public GForm getForm() { if (form != null) { return form; } GLanguage.setCurLang(GLanguage.ID_CHN); eventHandle = new GameUIEventHandle(this); XContainer.registerGUI("g3dtest.simple.XSimplePanel"); XContainer.registerGUI("g3dtest.game.XGamePanel"); String xmlStr = GToolkit.readFileFromJarAsString("/res/ui/G3dForm.xml", "utf-8"); UITemplate uit = new UITemplate(xmlStr); for (String key : uit.getVariable()) { uit.setVar(key, GLanguage.getString(key)); } XForm xform = (XForm) XContainer.parseXml(uit.parse()); xform.build(GCallBack.getInstance().getDeviceWidth(), GCallBack.getInstance().getDeviceHeight(), eventHandle); form = (GForm) xform.getGui(); eventHandle.setForm(form); simplePanel = (SimplePanel) form.findByName("GLP_SIMPLE"); form.remove(simplePanel); gamePanel = (GamePanel) form.findByName("GLP_GAME"); form.remove(gamePanel); menu = (GMenu) form.findByName("MENU_MAIN"); form.setSizeChangeListener(new GSizeChangeListener() { @Override public void onSizeChange(int width, int height) { ((XContainer) form.getAttachment()).reSize(width, height); simplePanel.reSize(); gamePanel.reSize(); } }); showGamePanel(); return form; } void showGamePanel() { form.remove(simplePanel); gamePanel.setLocation(0, (int) (form.getH() * .1)); form.add(gamePanel); gamePanel.reSize(); } void showSimplePanel() { form.remove(gamePanel); simplePanel.setLocation(0, (int) (form.getH() * .1)); form.add(simplePanel); simplePanel.reSize(); } void exit() { if (simplePanel != null) { } if (gamePanel != null) { gamePanel.exit(); } } }
Markdown
UTF-8
330
3.390625
3
[ "MIT" ]
permissive
# 78. Subsets > Medium ------ Given an integer array `nums`, return all possible subsets (the power set). Note that the solution set must not contain duplicate subsets. **Example 1:** ``` Input: nums = [1,2,3] Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]] ``` **Example 2:** ``` Input: nums = [0] Output: [[],[0]] ```
Java
UTF-8
1,382
2.5625
3
[ "MIT" ]
permissive
/* * 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 com.dmdirc.util.annotations.observable; import static org.junit.Assert.assertEquals; import org.junit.Test; public class ObservableModelTest { @Test public void testOldValueTestModel() { final String oldValue = "Foo"; final String newValue = "Bar"; ObservableOldValueTestModel model = new ObservableOldValueTestModel(oldValue); model.addStringListener(new ObservableOldValueTestModel.StringListener() { public void stringChanged(String testOldValue, String testNewValue) { assertEquals(oldValue, testOldValue); assertEquals(newValue, testNewValue); } }); model.setString(newValue); } @Test public void testNewValueTestModel() { final String oldValue = "Foo"; final String newValue = "Bar"; ObservableNewValueTestModel model = new ObservableNewValueTestModel(oldValue); model.addStringListener(new ObservableNewValueTestModel.StringListener() { public void stringChanged(String testNewValue) { assertEquals(newValue, testNewValue); } }); model.setString(newValue); } }
Java
UTF-8
5,738
2.515625
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 jcanpoll; import java.sql.*; import java.util.ArrayList; import java.util.Collections; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.util.Iterator; import javax.swing.DefaultListModel; import javax.swing.SwingUtilities; /** * * @author deh */ public class Jcanpoll { private static String driverName = "org.apache.derby.jdbc.EmbeddedDriver"; private static String clientDriverName = "org.apache.derby.jdbc.ClientDriver"; private static String databaseConnectionName = "jdbc:derby://localhost:1527/pcc"; private static Object LocalDateTime; public static ArrayList<Canmsginfo> canidlist; /** * @param args the command line arguments * @throws java.sql.SQLException * @throws java.lang.ClassNotFoundException * @throws java.io.IOException */ public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException { Connection connection = null; PreparedStatement pstmt = null; Statement stmt = null; //Check for DB drivers try{ Class.forName(clientDriverName); Class.forName(driverName); }catch(java.lang.ClassNotFoundException e) { System.out.println("client Driver Name, or driver Name exception\n"); throw e; } // ==== Try to connect to the specified database =============================== try{ System.out.println("List of CANIDs sorted by HEX "); java.util.Date date= new java.util.Date(); System.out.format("// %s\n",new Timestamp(date.getTime())); connection = DriverManager.getConnection(databaseConnectionName); // System.out.println("// Seems to have made the database connection\n"); stmt = connection.createStatement(); ResultSet rs; Integer totalct = 0; // ===== Fill ArrayList with database data ===================================== Jcanpoll.canidlist = new ArrayList<>(); CanmsginfoBuild cmib = new CanmsginfoBuild(); cmib.genlist_Canid(stmt, canidlist); // ===== Experimenting with constants PccConst pccconst = new PccConst(); pccconst.fillList(stmt); // ===== Test/debugging search ================================================= Long L1 = 0x0E1C00000L; // Needed for comparisons Canmsginfo cmi2 = new Canmsginfo (L1); // CAN ID w remainder nulls int index = Collections.binarySearch(canidlist, cmi2); // Lookup System.out.format("####11####### search test binarySearch: index: %d %08X\n",index, L1); // ===== Setup connection to socket ============================================ String ip; ip = "127.0.0.1"; // Default ip address //String ip = new String("10.1.1.80"); int port = 32123; // Default port /* Deal with the arguments on the command line */ if (args.length > 2){ System.out.format("Only two args allowed, we saw %d\n", args.length); System.exit(-1); } if (args.length == 2){ ip = args[0]; port = Integer.parseInt(args[1]); } Socket socket = new Socket(ip, port); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream()); Canmsg2j can1; can1 = new Canmsg2j(); // Received CAN message DbPayload dbpay = new DbPayload(); // ===== socket communication ================================================== MessagePipeline pipe = MessagePipeline.getInstance(); Thread pipeThread = new Thread(pipe); pipeThread.start();//runs in background, not connected yet pipe.connect(ip, port); // ===== Set up display windows =============================================== /* Create and display the form */ /* Create and display the form */ java.awt.EventQueue.invokeLater(() -> { new NewJFrame().setVisible(true); }); } catch(SQLException e) { throw e; } finally { if (pstmt != null) pstmt.close(); } } public static int lookUp(Long L1){ Canmsginfo cmi7 = new Canmsginfo (L1); // CAN ID w remainder nulls int index5 = Collections.binarySearch(canidlist , cmi7); if (index5 < 0){ // When not found add a dummy to list System.out.format("Type code lookup: CANID not in arraylist: %08X size: %s\n",cmi7.can_hex,canidlist.size()); return PccFinal.NONE; // Use default } System.out.format("Type code lookup: CANID found arraylist: %08X decript: %s code: %d size: %d\n", cmi7.can_hex, canidlist.get(index5).descript_payload, canidlist.get(index5).pay_type_code, canidlist.size()); Canmsginfo cmi9 = new Canmsginfo(); cmi9 = canidlist.get(index5); return cmi9.pay_type_code; } }
C++
UTF-8
1,539
2.65625
3
[ "BSD-3-Clause" ]
permissive
#include "Enemy.h" #include "Player.h" #include <cmath> Enemy::Enemy(Level* level, const std::string& mediaPath, irr::core::vector3df position, irr::core::vector3df rotation, int id, EnemyInfo info): Entity(level, mediaPath, position, rotation, id), Damageable(info.health, info.damage), aggroRange(info.aggroRange), state(info.defaultState) { player = level->getPlayer(); } void Enemy::setPlayer(Player* play) { player = play; } void Enemy::update(float delta) { //entityNode->setMaterialFlag(irr::video::EMF_LIGHTING, false); updateStates(); rot = entityNode->getRotation(); pos = entityNode->getPosition(); entityNode->updateAbsolutePosition(); } void Enemy::updateAggroState(const irr::core::vector3df playerPos) { if(!isPlayerNearby(aggroRange)) { state = STATIONARY; } else { rotateTowardsPosition(playerPos); entityNode->setRotation(rot); rotateTowardsPosition(playerPos); irr::core::vector3df direction = (playerPos - pos).normalize(); entityNode->setPosition(entityNode->getPosition() + direction * speed); } } void Enemy::updateStationaryState() { if(isPlayerNearby(aggroRange)) state = AGGRO; } bool Enemy::isPlayerNearby(float range) { return player->getCamera()->getPosition().getDistanceFrom(entityNode->getPosition()) <= range; } bool Enemy::onClick(bool MouseEvent) { return true; } void Enemy::updateStates() { switch(state) { case AGGRO: updateAggroState(player->getCamera()->getPosition()); break; case STATIONARY: updateStationaryState(); break; default: break; } }
Java
UTF-8
4,301
2.546875
3
[ "MIT" ]
permissive
package il.org.spartan.spartanizer.engine; import static il.org.spartan.azzert.*; import static il.org.spartan.spartanizer.engine.into.*; import org.junit.*; import org.junit.runners.*; import il.org.spartan.*; @FixMethodOrder(MethodSorters.NAME_ASCENDING) @SuppressWarnings({ "javadoc", "static-method" }) public final class SpecificityTest { private static final specificity SPECIFICITY = new specificity(); @Test public void characterGreaterThanNull() { azzert.that(SPECIFICITY.compare(e("'a'"), e("null")), greaterThan(0)); } @Test public void characterLessThanThis() { azzert.that(SPECIFICITY.compare(e("'1'"), e("this")), lessThan(0)); } @Test public void defined() { azzert.that(specificity.defined(e("12")), is(true)); azzert.that(specificity.defined(e("a+b")), is(false)); } @Test public void generalGreaterThanClassConstant() { azzert.that(SPECIFICITY.compare(e("a+b"), e("AB_C")), greaterThan(0)); } @Test public void generalGreaterThanInteger() { azzert.that(SPECIFICITY.compare(e("a+b"), e("12")), greaterThan(0)); } @Test public void generalGreaterThanMutlipleParenthesizedNegativeInteger() { azzert.that(SPECIFICITY.compare(e("a+b"), e("(-(12))")), greaterThan(0)); } @Test public void generalGreaterThanNegativeInteger() { azzert.that(SPECIFICITY.compare(e("a+b"), e("-12")), greaterThan(0)); } @Test public void generalGreaterThanNull() { azzert.that(SPECIFICITY.compare(e("a+b"), e("null")), greaterThan(0)); } @Test public void generalGreaterThanParenthesizedClassConstant() { azzert.that(SPECIFICITY.compare(e("a+b"), e("(AB_C)")), greaterThan(0)); } @Test public void generalGreaterThanParenthesizedNegativeInteger() { azzert.that(SPECIFICITY.compare(e("a+b"), e("(-12)")), greaterThan(0)); } @Test public void generalGreaterThanSingleLetterClassConstant() { azzert.that(SPECIFICITY.compare(e("a+b"), e("A")), greaterThan(0)); } @Test public void generalGreaterThanSingleLetterClassConstantWithUnderscore() { azzert.that(SPECIFICITY.compare(e("a+b"), e("A__")), greaterThan(0)); } @Test public void generalGreaterThanThis() { azzert.that(SPECIFICITY.compare(e("a+b"), e("this")), greaterThan(0)); } @Test public void hexadecimalConstant() { azzert.that(specificity.defined(e("0xff")), is(true)); azzert.that(specificity.defined(e("0x7f")), is(true)); } @Test public void hexadecimalConstantIsInteger() { azzert.that(specificity.Level.of(e("0xff")), is(specificity.Level.of(e("12")))); } @Test public void hexadecimalConstantIsSame() { azzert.that(specificity.Level.of(e("0xff")), is(specificity.Level.of(e("0x7f")))); } @Test public void integerConstantGreaterThanBooleanConstant() { azzert.that(SPECIFICITY.compare(e("12"), e("true")), greaterThan(0)); } @Test public void integerGreaterThanNull() { azzert.that(SPECIFICITY.compare(e("12"), e("null")), greaterThan(0)); } @Test public void integerLessThanThis() { azzert.that(SPECIFICITY.compare(e("12"), e("this")), lessThan(0)); } @Test public void nullLessThanThis() { azzert.that(SPECIFICITY.compare(e("null"), e("this")), lessThan(0)); } @Test public void pseudoConstantGreaterThanInteger() { azzert.that(SPECIFICITY.compare(e("AB_C"), e("(-(12))")), greaterThan(0)); } @Test public void stringGreaterThanNull() { azzert.that(SPECIFICITY.compare(e("\"12\""), e("null")), greaterThan(0)); } @Test public void stringLessThanThis() { azzert.that(SPECIFICITY.compare(e("\"12\""), e("this")), lessThan(0)); } @Test public void thisGreaterThanNull() { azzert.that(SPECIFICITY.compare(e("this"), e("null")), greaterThan(0)); } @Test public void twoDistinctClassConstants() { azzert.that(specificity.Level.of(e("BOB")), is(specificity.Level.of(e("SPONGE")))); } @Test public void twoDistinctClassConstantsWithDigits() { azzert.that(specificity.Level.of(e("BOB")), is(specificity.Level.of(e("B2B")))); } @Test public void twoIdenticalClassConstants() { azzert.that(specificity.Level.of(e("SPONGE")), is(specificity.Level.of(e("SPONGE")))); } @Test public void undefinedLevel() { azzert.that(specificity.Level.of(e("a+b")), is(specificity.Level.values().length)); } }
PHP
UTF-8
2,700
3.015625
3
[ "BSD-3-Clause" ]
permissive
<?php /* * OPEN POWER LIBS <http://www.invenzzia.org> * * This file is subject to the new BSD license that is bundled * with this package in the file LICENSE. It is also available through * WWW at this URL: <http://www.invenzzia.org/license/new-bsd> * * Copyright (c) Invenzzia Group <http://www.invenzzia.org> * and other contributors. See website for details. */ namespace Opl\Cache; use Opl\Cache\Exception\KeyNotFoundException; /** * Represents an atomic, distributed integer. The integer is guaranteed to be * updateable and shared across all the servers, providing the correct configuration. * As a backend, it uses Memcached. APC-based integers make no practical sense. * * @author Tomasz Jędrzejewski * @copyright Invenzzia Group <http://www.invenzzia.org/> and contributors. * @license http://www.invenzzia.org/license/new-bsd New BSD License */ class AtomicInteger { /** * The integer name. * @var string */ protected $name; /** * The caching strategy * @var AtomicIntegerStrategy */ protected $strategy; /** * Creates a new atomic integer with the given name. If the atomic * integer has not been created yet, you will encounter lots * of exceptions coming out of this class. * * @param string $name The integer name. * @param Memcached $memcached The storage. */ public function __construct($name, AtomicIntegerStrategy $strategy) { $this->name = (string) $name; $this->strategy = $strategy; } // end __construct(); /** * Increments the value by the given amount, and returns the new value. * * @throws KeyNotFoundException * @param integer $amount The amount, by which we increment the integer. * @return integer The new value. */ public function increment($amount = 1) { return $this->strategy->increment($this->name, $amount); } // end increment(); /** * Decrements the value by the given amount, and returns the new value. * * @throws KeyNotFoundException * @param integer $amount The amount, by which we decrement the integer. * @return integer The new value. */ public function decrement($amount = 1) { return $this->strategy->decrement($this->name, $amount); } // end decrement(); /** * Returns the current value of the integer. * * @throws KeyNotFoundException * @return integer */ public function get() { return $this->strategy->get($this->name); } // end get(); /** * Stores the new value within the integer, and returns this value. * * @param integer $value The stored value * @return integer The stored value */ public function set($value) { $this->strategy->set($this->name, $this->value); return $value; } // end set(); } // end AtomicInteger;
Markdown
UTF-8
629
2.859375
3
[]
no_license
# Human-Activity-Classification Using a variety of supervised learning algorithms to classify user activity based on smartphone gyroscope and accelerometer data. ## Data [Dataset from Kaggle](https://www.kaggle.com/uciml/human-activity-recognition-with-smartphones) ### Activity Categories: #### Moving: - Walking - Walking Upstairs - Walking Downstains #### Not Moving: - Sitting - Standing - Laying ## Methods ### SVM ### Neural Net A multilayer perceptron with multiple hidden layers was used. Tweaking: - Feature Selection - Number of hidden layers - Activation function - Learning Rate ### K-Means ## Results
Markdown
UTF-8
2,236
3.921875
4
[]
no_license
## Why Python emoji length is different than Java? ### Background Recently I built a text processing API for a working project. The API is called in Java and runs on Python. Later, I encountered a bug that caused by offset difference that processed text in Python and used the result on Java. 💩 ### Reproduce the Problem Let's use poop emoji as an example. In python the emoji length is 1: ``` print(len("💩")) # print out 1 ``` However, in Java the emoji length is 2: ``` System.out.println("💩".length()); // print out 2 ``` ### Code Unit VS Code Point in Unicode There are two terms we need to understand before solving this problem. A *code point* is a numerical value that represents a Unicode character. You can think of this number as an index in to the Unicode character set. A code point is encoded as a sequence of integers(called *code unit*), whose bit size depends upon the selected character encoding methods. An example of character encoding method would be UTF-8. The size of UTF-8 code unit is 8 bits. ### Why the length of 💩 is 2 in Java Java uses UTF-16 to encode characters. The `.length()` function in Java returns the number of 16-bit Unicode characters in string. It equals to the number of code unit in string. In UTF-16, "💩" contains only one code point that is encoded by 2 code units each 16-bits in length. Therefore the length of 💩 is 2. ### Why the length of 💩 is 1 in Python Python uses UTF-8 to encode characters. The `len()` function in Python returns the number of characters in the string. It equals to the number of code point in string. Therefore the length of 💩 is 1. ### How to get the Java length of String in Python Since the length of the string in Java equals to the number of 16-bit Unicode characters, It should also equals to the byte size of the string times 2. Therefore we can calculate the byte size of the string in Python to calculate the Java length. ``` poop_in_java = "💩".encode("utf-16") poop_byte_size = len(poop_in_java) poop_len_in_java = int(poop_byte_size / 2) print(poop_len_in_java) # print out 2 ``` ### How to get the Java length of String in Python ``` System.out.println("💩".codePoints().count()); // print out 1 ```
Java
UTF-8
705
3.09375
3
[]
no_license
package com.udemy.injection.annotations.java_based.qualifier; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; public class Student { private String name; @Autowired @Qualifier(value = "2") private Address address; public String getName() { return name; } public void setName(String name) { this.name = name; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public void showInfo() { System.out.println(name + "s Address is " + address.getAddress()); } }
Java
UTF-8
4,812
2.328125
2
[]
no_license
package com.example.android.chaoshi.adapter; import android.content.Context; import android.content.Intent; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CompoundButton; import android.widget.RadioButton; import android.widget.TextView; import com.example.android.chaoshi.R; import com.example.android.chaoshi.entity.Address; import com.example.android.chaoshi.ui.activity.EditAddressActivity; import com.example.android.chaoshi.ui.activity.ManageAddressActivity; import com.example.android.chaoshi.util.DatabaseUtil; import java.util.ArrayList; import java.util.List; public class ManageAddressAdapter extends BaseAdapter { private Context context; private List<Address> addresses; private Address address; private int radioCurrentPosition = ManageAddressActivity.getDefaultAddressPosition(); public ManageAddressAdapter(Context context, List<Address> addresses) { super(); this.context = context; this.addresses = addresses; } @Override public View getView(int position, View convertView, ViewGroup parent) { address = (Address) addresses.get(position); ViewHolder holder; if (convertView == null) { holder = new ViewHolder(); convertView = LayoutInflater.from(context).inflate(R.layout.address, null); holder.tvName = (TextView) convertView.findViewById(R.id.tv_name_mode); holder.tvNumber = (TextView) convertView.findViewById(R.id.tv_number_mode); holder.tvAddress = (TextView) convertView.findViewById(R.id.tv_address_mode); holder.rbSetDefault = (RadioButton) convertView.findViewById(R.id.rb_set_default_mode); holder.tvEdit = (TextView) convertView.findViewById(R.id.tv_edit_address_mode); holder.tvDelete = (TextView) convertView.findViewById(R.id.tv_delete_address_mode); convertView.setTag(holder); } holder = (ViewHolder) convertView.getTag(); holder.tvName.setText(address.getName()); holder.tvNumber.setText(address.getPhoneNumber()); holder.tvAddress.setText(address.getAddrezz()); holder.rbSetDefault.setOnCheckedChangeListener(new RadioButtonAddressAdapterListener(position)); if (radioCurrentPosition == position) {//�� holder.rbSetDefault.setChecked(true); setDefaultState(radioCurrentPosition); } else { holder.rbSetDefault.setChecked(false); address.setDefault(0); } InnerOnClickListener listener = new InnerOnClickListener(position); holder.tvEdit.setOnClickListener(listener); holder.tvDelete.setOnClickListener(listener); return convertView; } private void setDefaultState(int a) { for (int i = 0; i < addresses.size(); i++) { if (i == a) { address.setDefault(1); }else { address.setDefault(0); } } } private class InnerOnClickListener implements OnClickListener { private int position; private DatabaseUtil dbUtil = new DatabaseUtil(context); InnerOnClickListener(int position) { this.position = position; } @Override public void onClick(View view) { switch (view.getId()) { case R.id.tv_edit_address_mode: Intent i = new Intent(context,EditAddressActivity.class); i.putExtra("position", position); context.startActivity(i); break; case R.id.tv_delete_address_mode: dbUtil.delete(addresses.get(position).getId()); addresses.remove(position); ManageAddressActivity.count--; notifyDataSetChanged(); break; } } } /** * 添加地址 * @param a */ public void addAddress(Address a) throws Exception { if (addresses == null) { addresses = new ArrayList<Address>(); } addresses.add(a); ManageAddressActivity.count++; new DatabaseUtil(context).insert(a); notifyDataSetChanged(); } private class RadioButtonAddressAdapterListener implements CompoundButton.OnCheckedChangeListener { private int position; RadioButtonAddressAdapterListener(int position) { this.position = position; } public void onCheckedChanged(CompoundButton compoundButton, boolean b) { if(b){ radioCurrentPosition = position; DatabaseUtil dbUtil = new DatabaseUtil(context); for (int i = 0; i < addresses.size(); i++) { if (i == radioCurrentPosition) { addresses.get(i).setDefault(1); }else { addresses.get(i).setDefault(0); } dbUtil.update(addresses.get(i)); } notifyDataSetChanged(); } } } class ViewHolder { TextView tvName; TextView tvNumber; TextView tvAddress; RadioButton rbSetDefault; TextView tvEdit; TextView tvDelete; } @Override public int getCount() { return addresses.size(); } @Override public Object getItem(int position) { return addresses.get(position); } @Override public long getItemId(int position) { return position; } }
C
UTF-8
1,118
2.984375
3
[]
no_license
/* ID: jitenmt1 LANG: C PROG: milk2 */ #include <stdio.h> int main() { FILE* in=fopen("milk2.in", "r"); FILE* out=fopen("milk2.out", "w"); unsigned int time[1000000]={0}; int N,i,very_start,very_end; fscanf(in, "%d", &N); int start, end; for(i=0; i<N; i++) { fscanf(in, "%d %d", &start, &end); int j; if(i==0) { very_start=start; very_end=end; }else{ if(start<very_start) very_start=start; if(end>very_end) very_end=end; } for(j=start; j<end; j++) time[j]++; } int one=0,no_one=0,temp_one=0,temp_no_one=0,prev_no=-1,j; for(j=very_start; j<very_end; j++) { if(time[j]==0) { if(prev_no>0) { if(temp_one>one) one=temp_one; temp_one=0; } temp_no_one++; }else { if(prev_no==0) { if(temp_no_one>no_one) no_one=temp_no_one; temp_no_one=0; } temp_one++; } prev_no=time[j]; } if(temp_one>one) one=temp_one; if(temp_no_one>no_one) no_one=temp_no_one; fprintf(out, "%d %d\n", one, no_one); return 0; }
Markdown
UTF-8
6,069
2.9375
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: 將 V2 Azure IoT Central 應用程式遷移至 V3 |Microsoft Docs description: 以系統管理員身分,瞭解如何將 V2 Azure IoT Central 應用程式遷移至 V3 author: troyhopwood ms.author: troyhop ms.date: 01/18/2021 ms.topic: conceptual ms.service: iot-central services: iot-central ms.openlocfilehash: 3f81ae72af48ec934d1c2c2567ebdd212d8e0499 ms.sourcegitcommit: 3c3ec8cd21f2b0671bcd2230fc22e4b4adb11ce7 ms.translationtype: MT ms.contentlocale: zh-TW ms.lasthandoff: 01/25/2021 ms.locfileid: "98763350" --- # <a name="migrate-your-v2-iot-central-application-to-v3"></a>將 V2 IoT Central 應用程式遷移至 V3 *本文適用于系統管理員。* 目前,當您建立新的 IoT Central 應用程式時,它是 V3 應用程式。 如果您先前已建立應用程式,則取決於建立應用程式的時間,它可能是 V2。 本文說明如何將 V2 遷移至 V3 應用程式,以確定您使用的是最新的 IoT Central 功能。 若要瞭解如何識別 IoT Central 應用程式的版本,請參閱 [應用程式的相關資訊](howto-get-app-info.md)。 將應用程式從 V2 遷移至 V3 的步驟如下: 1. 從 V2 應用程式建立新的 V3 應用程式。 1. 設定 V3 應用程式。 1. 刪除 V2 應用程式。 ## <a name="create-a-new-v3-application"></a>建立新的 V3 應用程式 使用 [遷移嚮導] 來建立新的 V3 應用程式。 IoT Central 不支援遷移至現有的 V3 應用程式。 若要自動移動現有的裝置,請使用 [遷移嚮導] 來建立 V3 應用程式。 [遷移嚮導]: - 建立新的 V3 應用程式。 - 檢查您的裝置範本是否與 V3 相容。 - 將您所有的裝置範本複製到新的 V3 應用程式。 - 將所有使用者和角色指派複製到新的 V3 應用程式。 > [!NOTE] > 為確保裝置與 V3 相容,裝置範本中的基本型別會變成物件屬性。 您不需要對裝置程式碼進行任何變更。 您必須是系統管理員,才能將應用程式遷移到 V3。 1. 在 [ **管理** ] 功能表上,選取 [ **遷移至 V3 應用程式**]: :::image type="content" source="media/howto-migrate/migrate-menu.png" alt-text="顯示應用程式遷移嚮導的螢幕擷取畫面"::: 1. 輸入新的 **應用程式名稱** ,並選擇性地變更自動產生的 **URL**。 URL 不能與您目前 V2 應用程式的 URL 相同。 不過,您稍後可以在刪除 V2 應用程式之後變更 URL。 1. 選取 [ **建立新的 V3 應用程式**]。 :::image type="content" source="media/howto-migrate/create-app.png" alt-text="顯示應用程式遷移嚮導中之選項的螢幕擷取畫面"::: 視裝置範本的數量和複雜度而定,此程式可能需要幾分鐘的時間才能完成。 > [!Warning] > 如果有任何裝置範本的欄位以數位開頭,或包含下列任何字元 (、、、、、、、、、、、) ,您的 V3 應用程式建立將會失敗 `+` `*` `?` `^` `$` `(` `)` `[` `]` `{` `}` `|` `\` 。 V3 應用程式使用的 DTDL 裝置範本架構不允許使用這些字元。 在遷移至 V3 之前,請先更新您的裝置範本以解決此問題。 1. 當您的新 V3 應用程式就緒時,請選取 [ **開啟新的應用程式** ] 以開啟它。 :::image type="content" source="media/howto-migrate/open-app.png" alt-text="螢幕擷取畫面,顯示應用程式遷移之後的應用程式遷移嚮導"::: ## <a name="configure-the-v3-application"></a>設定 V3 應用程式 建立新的 V3 應用程式之後,請先進行任何設定變更,再將裝置從 V2 應用程式移至 V3 應用程式。 > [!TIP] > 請花點時間 [熟悉 V3](overview-iot-central-tour.md#navigate-your-application) ,因為它與前一版有一些差異。 以下是一些建議考慮的設定步驟: - [設定儀表板](howto-add-tiles-to-your-dashboard.md) - [設定資料匯出](howto-export-data.md) - [設定規則和動作](quick-configure-rules.md) - [自訂應用程式 UI](howto-customize-ui.md) 當您的 V3 應用程式設定為符合您的需求時,您就可以開始將您的裝置從 V2 應用程式移至 V3 應用程式。 ## <a name="move-your-devices-to-the-v3-application"></a>將您的裝置移至 V3 應用程式 完成此步驟後,您的所有裝置都只會與新的 V3 應用程式通訊。 > [!IMPORTANT] > 將裝置移至 V3 應用程式之前,請先刪除您在 V3 應用程式中建立的任何裝置。 此步驟會將您所有現有的裝置移至新的 V3 應用程式。 不會複製您的裝置資料。 選取 [ **移動所有裝置** ] 以開始移動您的裝置。 此步驟可能需要幾分鐘的時間才能完成。 :::image type="content" source="media/howto-migrate/move-devices.png" alt-text="螢幕擷取畫面,顯示 [移動裝置] 選項的應用程式遷移嚮導"::: 移動完成之後,請重新開機您的所有裝置,以確保它們連接到新的 V3 應用程式。 > [!WARNING] > 請勿刪除您的 V3 應用程式,因為您的 V2 應用程式現在無法運作。 ## <a name="delete-your-old-v2-application"></a>刪除舊的 V2 應用程式 在您驗證新 V3 應用程式中的所有專案都如預期般運作之後,請刪除舊的 V2 應用程式。 此步驟可確保您不會因為不再使用的應用程式而向您收費。 > [!Note] > 若要刪除應用程式,您必須有權刪除您在建立應用程式時所選擇的 Azure 訂用帳戶中的資源。 若要深入了解,請參閱[使用角色型存取控制來管理 Azure 訂用帳戶資源的存取](../../active-directory/role-based-access-control-configure.md)。 1. 在您的 V2 應用程式中,選取功能表中的 [系統 **管理** ] 索引標籤 2. 選取 [ **刪除** ] 以永久刪除您的 IoT Central 應用程式。 此選項會永久刪除與該應用程式相關聯的所有資料。 ## <a name="next-steps"></a>後續步驟 現在您已瞭解如何遷移您的應用程式,建議的下一個步驟是複習 [AZURE IOT CENTRAL UI](overview-iot-central-tour.md) ,以查看 V3 中有哪些變更。
Markdown
UTF-8
768
2.625
3
[]
no_license
--- title: nuxt中每个页面引入sass全局变量和mxins date: 2019-07-03 14:13:34 tags: nuxt --- 在页面中经常用到一些常用的变量和mixins,避免每个页面都要导入,可以使用@nuxtjs/style-resources > 可参考nuxt官方文档 https://zh.nuxtjs.org/api/configuration-build/#styleresources ## 配置 - 安装@nuxtjs/style-resources模块 ```bash npm install @nuxtjs/style-resources --save-dev ``` - 修改nuxt.config.js ```javascript export default { modules: [ '@nuxtjs/style-resources' ], styleResources: { scss: ['./assets/_mixins.scss', './assets/_variables.scss'] // 定义的全局mixins、变量文件路径 less: './assets/****.less' ... // 根据需要添加相应文件 } } ```
JavaScript
UTF-8
7,434
2.671875
3
[]
no_license
const menus = [ {id: 1, name: 'USERS', icon:'./public/img/icon1.png'}, {id: 2, name: 'LINKS', icon:'./public/img/icon2.png'}, {id: 3, name: 'COLLECTIONS', icon:'./public/img/icon3.png'}, ]; class User extends React.Component { render() { return ( <ul className='biglist'> <li>id : {this.props.id}</li> <li>nickname : {this.props.nickname}</li> <li>mail : {this.props.mail}</li> </ul> ); } } class Tag extends React.Component { render() { return ( <li> {this.props.tagname}</li> ); } } class Link extends React.Component { createTagsList() { const tags = ['Videos','Information','Article','Books','Movies']; const tagsList = tags.map( (t) => <Tag key={t} tagname={t} /> ); return tagsList; } render() { const list = this.createTagsList(); return ( <ul className='biglist'> <li>id : {this.props.id}</li> <li>url : {this.props.url}</li> <li>tags : <ul>{list}</ul> </li> </ul> ) } } class Collection extends React.Component { createLinksList() { const links = [ {id:'1',url:'youtube.com'}, {id:'2',url:'google.com'}, {id:'3',url:'facebook.com'}, ]; const linksList = links.map( (l)=>{ return <li key={l.id}><Link id={l.id} url={l.url} /></li>; }); return linksList; } render() { const list = this.createLinksList(); return ( <ul className='biglist'>{list}</ul> ); } } class Container extends React.Component { render() { return ( <div id='container' className='container'> <Header /> <Content /> <Footer /> </div> ); } } class Header extends React.Component { render() { return ( <div className="header"> <h1>MY POCKET</h1> <Headmenu /> </div> ) } } class Headmenu extends React.Component { render() { return ( <div className="headmenu"> <ul className="headmenulist"> <li><a href="#">USERS</a></li> <li><a href="#">LINKS</a></li> <li><a href="#">COLLECTIONS</a></li> </ul> </div> ); } } class Content extends React.Component { constructor(props) { super(props); this.getLeftColToggles = this.getLeftColToggles.bind(this); this.state = { displayToggles: { hideusers : false, hidelinks : true, hidecollections : true } }; } getLeftColToggles(childToggles) { this.setState({ displayToggles : childToggles }) } render() { return ( <div className="content"> <LeftCol toggles={this.getLeftColToggles}/> <RightCol toShow={this.state.displayToggles} /> </div> ); } } class LeftCol extends React.Component { constructor(props) { super(props); this.getSideMenuToggles = this.getSideMenuToggles.bind(this); } getSideMenuToggles(childToggles) { this.props.toggles(childToggles); //Then sending the toggles to <Content /> } render() { return ( <div className="leftcol"> <Sidemenu menus={menus} toggles={this.getSideMenuToggles}/> </div> ) } } class Sidemenu extends React.Component { constructor(props) { super(props); this.getMenuToggles = this.getMenuToggles.bind(this); } getMenuToggles(childToggles) { this.props.toggles(childToggles); //Then sending the toggles to <LeftCol /> } render() { const listMenus = this.props.menus.map(m=><Menu toggles={this.getMenuToggles} key={m.id} name={m.name} icon={m.icon} /> ); return ( <div className="sidemenu"> <ul className="sidemenulist"> {listMenus} </ul> </div> ); } } class Menu extends React.Component { constructor(props) { super(props); this.setToggles = this.setToggles.bind(this); } setToggles(e) { e.preventDefault(); const target = e.target.innerText.toLowerCase(); //get clicked menu let displayToggles = {}; if (target==="users") { displayToggles = { hideusers : false, hidelinks : true, hidecollections : true }; } else if (target==="links") { displayToggles = { hideusers : true, hidelinks : false, hidecollections : true }; } else if (target==="collections") { displayToggles = { hideusers : true, hidelinks : true, hidecollections : false }; } this.props.toggles(displayToggles); // Sending toggles to <SideMenu /> } render() { return ( <li><a href="#" onClick={this.setToggles} className="singlemenu"> <span className="leftmenupart"> <img width="30" src={this.props.icon}/> </span> <span className="rightmenupart"> {this.props.name} </span> </a></li> ); } } class RightCol extends React.Component { render() { return ( <div className="rightcol"> <AllUsers hide={this.props.toShow.hideusers}/> <AllLinks hide={this.props.toShow.hidelinks}/> <AllCollections hide={this.props.toShow.hidecollections}/> </div> ) } } class AllUsers extends React.Component { render() { return ( <div className='section users' hidden={this.props.hide}> <h2>All Users</h2> <User id='1' nickname="Jacquard Le Gueux" mail='jacquard@lvstr.com' /> <User id='2' nickname="Dame Ginette" mail='dg@lvstr.com' /> <User id='3' nickname="Cousin Hub'" mail='hubofmontmirail@lvstr.com' /> <User id='4' nickname="Dame Béatrice" mail='beaofmontrailmi@lvstr.com' /> <User id='5' nickname="Jean-Pierre" mail='jplegueux@bg.com' /> </div> ) } } class AllLinks extends React.Component { render() { return ( <div className='section links' hidden={this.props.hide}> <h2>All Links</h2> <Link id='1' url='youtube.com'/> <Link id='2' url='google.com'/> <Link id='3' url='facebook.com'/> <Link id='4' url='slack.com'/> <Link id='5' url='react.com'/> </div> ) } } class AllCollections extends React.Component { render() { return ( <div className='section collections' hidden={this.props.hide}> <h2>All Collections</h2> <Collection id='1'/> <Collection id='2'/> <Collection id='3'/> </div> ) } } class Footer extends React.Component { render() { return ( <div className="footer"> </div> ) } } class App extends React.Component { render() { return ( <Container /> ); } } ReactDOM.render(<App />,document.getElementById('root'));
Java
UTF-8
575
1.96875
2
[]
no_license
package com.eight.group.vo; import com.eight.group.pojo.Order; import lombok.Getter; import lombok.Setter; import lombok.ToString; import java.sql.Date; /** * @author:xingquanxiang createTime:2019/11/13 20:27 * description: */ @Setter @Getter @ToString public class OrderVO extends Order { private String member; private String setmeal; public OrderVO() {} public OrderVO(Date orderDate, String orderType, String member, String setmeal) { super(orderDate, orderType); this.member = member; this.setmeal = setmeal; } }
Java
UTF-8
659
2.71875
3
[]
no_license
package com.gToons.api.game.effects; import com.gToons.api.model.Card; import com.gToons.api.game.Location; import java.util.ArrayList; public class LastCardPlayed extends Effect { LastCardPlayed(int v, boolean m, String attr[]){ super(v,m,attr); } public Effect copy(){ LastCardPlayed effect = new LastCardPlayed(value,multiplier,attributes); return effect; } @Override public ArrayList<Location> getImpactedLocations() { return null; } @Override public boolean appliesTo(Card c, Card cardsInPlay[]) { return c.getLocation().getX() == 2 && c.getLocation().getY() == 1; } }
Python
UTF-8
1,700
2.984375
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Sat Sep 19 13:00:48 2020 Task 2 - textCNN Model @author: apple """ import torch import torch.nn as nn import torch.nn.functional as F class textCNN(nn.Module): def __init__(self,vocab_size,vocab_dim,kernel_num,kernel_list,class_num,dropout_rate,embedding_matrix): super(textCNN,self).__init__() in_channel = 1 self.embed = nn.Embedding(vocab_size,vocab_dim) #self.embed.weight.data.copy_(embedding_matrix) #self.embed.weight.require_grad=False #使词向量在训练中保持固定 self.convs = nn.ModuleList([nn.Conv2d(in_channel,kernel_num,(k,vocab_dim)) for k in kernel_list]) self.dropout = nn.Dropout(dropout_rate) self.fc = nn.Linear(len(kernel_list)*kernel_num,class_num) def forward(self,x): # x.shape = [batch_size,fix_length] x = x.t() embedding_x = self.embed(x) # embedding_x.shape = [batch_size,fix_length,vocab_dim] x = embedding_x.unsqueeze(1) # x.shape = [batch_size,in_channel,fix_length,vocab_dim] # 使用不同的卷积核进行卷积 conv_out = [F.relu(conv(x)).squeeze(3) for conv in self.convs] #len(kernel_list) * kernel_num # 池化操作 max_pool_out = [F.max_pool1d(line,line.size(2)).squeeze(2) for line in conv_out] # len(kernel_list) * (N,kernel_num) # 向量拼接 out = torch.cat(max_pool_out,1) #(N,kernel_num*len(kernel_list)) out = self.dropout(out) y = self.fc(out) # (N,C) return y
Java
UTF-8
1,210
2.265625
2
[]
no_license
package be.haexnet.fusio.processor; import be.haexnet.fusio.data.simplechilorigintargetnullable.OriginData; import be.haexnet.fusio.data.simplechilorigintargetnullable.TargetData; import be.haexnet.fusio.data.simplechilorigintargetnullable.TargetDataElement; import org.junit.Test; import static org.fest.assertions.api.Assertions.assertThat; public class FusioProcessorSimpleChildOriginTargetNullableDataTest extends FusioProcessorTest<OriginData, TargetData> { @Test public void fusioReturnsTargetObjectWithFieldValuesOfOriginObjectWhenNull() throws Exception { final OriginData origin = OriginData.empty(); final TargetData target = TargetData.of("Martijn Haex", TargetDataElement.of("Java Consultant", "Writing (web-)applications")); final TargetData processedTarget = processor.process(origin, target); validateProcessing(origin, processedTarget); assertThat(processedTarget.getName()).isEqualTo(target.getName()); } @Override protected void validateProcessing(final OriginData origin, final TargetData processedTarget) { assertThat(processedTarget.getName()).isNotNull(); assertThat(processedTarget.getJob()).isNull(); } }
Java
UTF-8
1,124
2.0625
2
[]
no_license
package org.macula.cloud.gateway.route; import org.macula.cloud.core.domain.GatewayRoute; import org.macula.cloud.gateway.event.GatewayRouteChangeEvent; import org.macula.cloud.gateway.util.GatewayRouteUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; import reactor.core.publisher.Mono; @Slf4j @Component public class GatewayRouteChangeListener implements ApplicationListener<GatewayRouteChangeEvent> { @Autowired private GatewayRouteDefinitionRepository routeRepository; public GatewayRouteChangeListener(GatewayRouteDefinitionRepository routeRepository) { this.routeRepository = routeRepository; } @Override public void onApplicationEvent(GatewayRouteChangeEvent event) { log.info("Handle GatewayRouteChangeEvent ..."); GatewayRoute route = event.getSource(); if (route.isDeleted()) { routeRepository.delete(Mono.just(String.valueOf(route.getId()))); } else { routeRepository.save(Mono.just(GatewayRouteUtils.cast(route))); } } }
Java
UTF-8
380
2.046875
2
[]
no_license
package testrenicredit.pages; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; public class MainPage extends BasePage { @FindBy(xpath = "//div[@class='service__title']//a[@href='/contributions/']") private WebElement contributionsElement; public void goToContributionsPage() { clickToElement(contributionsElement); } }
JavaScript
UTF-8
843
2.984375
3
[]
no_license
import React, { Component } from 'react' class Counter extends Component { render () { return ( <p> Clicked: {this.props.counter} times <button onClick={ e => this.eventAdd(e) } >+</button> <button onClick={e=>this.eventDem(e)} >-</button> <button onClick={e => this.eventAddIfOdd(e)}>Increment if odd</button> <button>Increment async</button> </p> ) } eventAdd (e) { this.props.increment(); } eventDem(e) { this.props.decrement(); } eventAddIfOdd (e) { var counter = this.props.counter; if (counter % 2 === 0) { return; } this.props.increment(); } } export default Counter
Go
UTF-8
1,154
4.125
4
[]
no_license
package main import "fmt" /** 题目: 给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。 如果你最多只允许完成一笔交易(即买入和卖出一支股票),设计一个算法来计算你所能获取的最大利润。 注意你不能在买入股票前卖出股票。 示例 1: 输入: [7,1,5,3,6,4] 输出: 5 解释: 在第 2 天(股票价格 = 1)的时候买入,在第 5 天(股票价格 = 6)的时候卖出,最大利润 = 6-1 = 5 。 注意利润不能是 7-1 = 6, 因为卖出价格需要大于买入价格。 示例 2: 输入: [7,6,4,3,1] 输出: 0 解释: 在这种情况下, 没有交易完成, 所以最大利润为 0。 */ func main() { nums := []int{7, 1, 5, 3, 6, 4} r := maxProfit(nums) fmt.Println(r) } /** 方法1: 记录当前最小的值,和最大的差值。 时间复杂度:O(n) 空间复杂度:O(1) */ func maxProfit(prices []int) int { minPrice := int(^uint(0) >> 1) maxDiff := 0 for _, price := range prices { if price < minPrice { minPrice = price } if price-minPrice > maxDiff { maxDiff = price - minPrice } } return maxDiff }
JavaScript
UTF-8
6,166
2.546875
3
[]
no_license
// ------------------------------------------------- // CJKnob V0.1.1 // STARTED DATE 19-06-2013 || END DATE 00-07-2013 // UPDATED DATE 30-06-2022 - Fixed bug // https://github.com/tanghoong/cj-knob // ------------------------------------------------- (function ($) { $.fn.extend({ cjknob: function (obj) { var defaults = { // Option mode: 'sknob', // default {sknob,dknob,gauge} showMeter: true, // default // Color bgcolor: '#D2D2D2', // Background color for the path which not overlay cBenchmark: '#94CEFE', // Color of Benchmark cColor: '#019AE6', // '#B30000' or 'red', default is serials color which in re-use // Digit cBenchmarkD: '50', // Expected mimimun of Benchmark height: '220', width: '220', // String cClass: 'cjknob', // Addition class, multiple then just add space meterTitle: '', meterFont: '1rem Arial', cjIcon: 'images/icons/sun-svgrepo-com.svg' }; var o = $.extend(defaults, obj); // ------------------------------------------------- // DO ONCE FUNCTION // ------------------------------------------------- // Variables var canvasID = $(this).attr('id'); var data = $(this).text(); var data2 = 0; var mode = o.mode; var ctx = null; if (data > 100) { data2 = data - 100; mode = 'dknob'; } var knobCanvas = canvasID + '-canvas'; var knobIcon = canvasID + '-icon'; if ($(`#${canvasID}`).html() != '') { // dump html to it var degrees = 0, new_degrees = 0, difference = 0; var degrees2 = 0, new_degrees2 = 0, difference2 = 0; var animation_loop, animation_loop2; $(this).html('<img id="' + knobIcon + '"src="' + o.cjIcon + '" style="width:24%;"/>' + '<canvas id="' + knobCanvas + '" width="' + o.width + '" height="' + o.height + '"></canvas>'); // Element Set Style var wrapper = $(`#${canvasID}`); var canvas = $(`#${knobCanvas}`); var icon = $(`#${knobIcon}`); wrapper.css({ 'position': 'relative', }); //dimensions var W = o.width; var H = o.height - 50; var W_icon = 24; var H_icon = 24; icon.css({ 'position': 'absolute', 'top': '40%', 'left': '50%', 'margin-top': '-' + H_icon / 2 + '%', 'margin-left': '-' + W_icon / 2 + '%', }); } ctx = canvas[0].getContext("2d"); function init() { // Clear the canvas everytime a chart is drawn ctx.clearRect(0, 0, W, H); // Background 360 degree arc, Part 1 ctx.beginPath(); ctx.strokeStyle = o.bgcolor; ctx.lineWidth = 10; ctx.arc(W / 2, H / 2 + 30, 80, 0, Math.PI * 2, false); //you can see the arc now ctx.stroke(); if (mode == 'dknob') { //Background 360 degree arc, Part 2 ctx.beginPath(); ctx.strokeStyle = o.bgcolor; ctx.lineWidth = 5; ctx.arc(W / 2, H / 2 + 30, 90, 0, Math.PI * 2, false); //you can see the arc now ctx.stroke(); } //Benchmark Background Color //Angle in radians = angle in degrees * PI / 180 var radians2 = o.cBenchmarkD * Math.PI * 2 / 100; ctx.beginPath(); ctx.strokeStyle = o.cBenchmark; ctx.lineWidth = 10; ctx.arc(W / 2, H / 2 + 30, 80, 0 - 90 * Math.PI / 180, radians2 - 90 * Math.PI / 180, false); //you can see the arc now ctx.stroke(); //gauge will be a simple arc //Angle in radians = angle in degrees * PI / 180 var radians = degrees * Math.PI / 180; ctx.beginPath(); ctx.strokeStyle = o.cColor; ctx.lineWidth = 10; //The arc starts from the rightmost end. If we deduct 90 degrees from the angles //the arc will start from the topmost end ctx.arc(W / 2, H / 2 + 30, 80, 0 - 90 * Math.PI / 180, radians - 90 * Math.PI / 180, false); //you can see the arc now if (Math.round(parseInt(data) / 100 * 360) >= 1) { ctx.stroke(); } if (mode == 'dknob' && Math.round(parseInt(degrees) * 100 / 360) >= 100) { var radians2 = degrees2 * Math.PI / 180; ctx.beginPath(); ctx.strokeStyle = o.cColor; ctx.lineWidth = 5; ctx.arc(W / 2, H / 2 + 30, 90, 0 - 90 * Math.PI / 180, radians2 - 90 * Math.PI / 180, false); if (Math.round(parseInt(data2) / 100 * 360) >= 1) { ctx.stroke(); } } //Lets add the text ctx.fillStyle = '#000'; ctx.font = o.meterFont; text = Math.ceil(degrees / 360 * 100); //Lets center the text //deducting half of text width from position x text_width = ctx.measureText(text).width; //adding manual value to position y since the height of the text cannot //be measured easily. There are hacks but we will keep it manual for now. ctx.fillText(text + '%', W / 2 - text_width / 2 - 10, H / 2 + 80); } function draw(data) { //Cancel any movement animation if a new chart is requested if (typeof animation_loop != undefined) clearInterval(animation_loop); if (typeof animation_loop2 != undefined) clearInterval(animation_loop2); //degree from 0 to 360 new_degrees = Math.round(parseInt(data) / 100 * 360); new_degrees2 = Math.round(parseInt(data2) / 100 * 360); console.log(data); console.log(data2); difference = new_degrees - degrees; difference2 = new_degrees2 - degrees2; animation_loop = setInterval(animate_to, 500 / difference); animation_loop2 = setInterval(animate_to, 500 / difference2); } //function to make the chart move to new degrees function animate_to() { //clear animation loop if degrees reaches to new_degrees if (degrees == new_degrees) { clearInterval(animation_loop); } if (degrees < new_degrees) { degrees++; if (degrees > 360) { if (degrees2 < new_degrees2) degrees2++; } } else { degrees--; if (degrees < 360) { if (degrees2 > new_degrees2) degrees2--; } } if (degrees2 == new_degrees2) { clearInterval(animation_loop2); } init(); } //Lets add some animation for fun draw(data); } // End: cjknob() }); })(jQuery); // ------------------------------------------------- // FUNCTION FOR PLUGIN TO USE // -------------------------------------------------
Swift
UTF-8
845
2.65625
3
[]
no_license
// // RNDemoView.swift // RNBridgeDemo // // Created by admin on 2018/10/23. // Copyright © 2018年 paradise. All rights reserved. // import Foundation import UIKit @objc(RNView) class RNView: UIView { @objc var txt: String = "嘿嘿" @objc(someAction) var someAction: (([String: Any])->Void)? { didSet { someAction?([:]) } } private var label: UILabel! override func draw(_ rect: CGRect) { super.draw(rect) setup() } private func setup() { layer.masksToBounds = true print("我起來囉, frame=\(frame)") label = UILabel() label.text = txt label.textColor = UIColor.blue label.frame = bounds addSubview(label) } func setConfig(_ config: String!) { print("我開始囉\(config)") } }
JavaScript
UTF-8
805
2.546875
3
[ "LGPL-2.1-or-later", "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // The input binding executes the `select * from Products where Cost = @Cost` query, returning the result as json object in the body. // The *parameters* argument passes the `{cost}` specified in the URL that triggers the function, // `getproducts/{cost}`, as the value of the `@Cost` parameter in the query. // *commandType* is set to `Text`, since the constructor argument of the binding is a raw query. module.exports = async function (context, req, products) { context.log('JavaScript HTTP trigger function processed a request.'); context.log(JSON.stringify(products)); return { status: 200, body: products }; }
C#
UTF-8
851
2.640625
3
[]
no_license
public static class IgnoreReadOnlyExtensions { public static IMappingExpression<TSource, TDestination> IgnoreReadOnly<TSource, TDestination>( this IMappingExpression<TSource, TDestination> expression) { var destType = typeof(TDestination); foreach (var property in destType.GetProperties()) { PropertyDescriptor descriptor = TypeDescriptor.GetProperties(destType)[property.Name]; ReadOnlyAttribute attribute = (ReadOnlyAttribute) descriptor.Attributes[typeof(ReadOnlyAttribute)]; if(attribute.IsReadOnly == true) expression.ForMember(property.Name, opt => opt.Ignore()); } return expression; } }
Java
UTF-8
9,418
2.390625
2
[]
no_license
package com.bot.KaworiSpring.web.controller; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.bot.KaworiSpring.model.Guilda; import com.bot.KaworiSpring.model.Membro; import com.bot.KaworiSpring.service.GuildaService; import com.bot.KaworiSpring.service.MembroService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; // TODO: Auto-generated Javadoc /** * The Class WebGuildaController. */ @RestController @RequestMapping("/guilds") public class WebGuildaController { /** The membro service. */ @Autowired private MembroService membroService; /** The guilda service. */ @Autowired private GuildaService guildaService; /** * Gets the guilds. * * @param id the id * @return the guilds */ @Secured("USER") @GetMapping(path = "/{id}") public ResponseEntity<DataResponse> getGuilds(@PathVariable String id) { ArrayList<MembroResponse> membros = new ArrayList<>(); membroService.findById(id).forEach((membro) -> { Guilda guild = guildaService.findById(membro.getIdGuild()); MembroResponse respoMembro = new MembroResponse(membro, guild); membros.add(respoMembro); }); DataResponse response = new DataResponse(membros); return new ResponseEntity<>(response, HttpStatus.OK); } /** * The Class DataResponse. */ class DataResponse { /** The membros. */ List<MembroResponse> membros; /** * Instantiates a new data response. * * @param membros the membros */ public DataResponse(List<MembroResponse> membros) { this.membros = membros; } /** * Gets the membros. * * @return the membros */ public List<MembroResponse> getMembros() { return membros; } /** * Sets the membros. * * @param membros the new membros */ public void setMembros(List<MembroResponse> membros) { this.membros = membros; } } /** * The Class MembroResponse. */ class MembroResponse { /** * Instantiates a new membro response. * * @param membro the membro * @param guilda the guilda */ public MembroResponse(Membro membro, Guilda guilda) { // TODO Auto-generated constructor stub // TODO Auto-generated constructor stub this.nick = membro.getNick(); this.familyName = membro.getFamilyName(); this.banned = membro.isBanned(); this.gear = membro.isGear(); this.gearUpdate = membro.getGearUpdate(); this.hero = membro.isHero(); this.visitor = membro.isVisitor(); this.novice = membro.isNovice(); this.guild = new GuildResponse(guilda); } /** The guild. */ private GuildResponse guild; /** The nick. */ private String nick; /** The family name. */ private String familyName; /** The banned. */ private boolean banned; /** The gear. */ private boolean gear; /** The gear update. */ private Date gearUpdate; /** The hero. */ private boolean hero; /** The visitor. */ private boolean visitor; /** The novice. */ private boolean novice; /** * Gets the guild. * * @return the guild */ public GuildResponse getGuild() { return guild; } /** * Sets the guild. * * @param guild the new guild */ public void setGuild(GuildResponse guild) { this.guild = guild; } /** * Gets the nick. * * @return the nick */ public String getNick() { return nick; } /** * Sets the nick. * * @param nick the new nick */ public void setNick(String nick) { this.nick = nick; } /** * Gets the family name. * * @return the family name */ public String getFamilyName() { return familyName; } /** * Sets the family name. * * @param familyName the new family name */ public void setFamilyName(String familyName) { this.familyName = familyName; } /** * Checks if is banned. * * @return true, if is banned */ public boolean isBanned() { return banned; } /** * Sets the banned. * * @param banned the new banned */ public void setBanned(boolean banned) { this.banned = banned; } /** * Checks if is gear. * * @return true, if is gear */ public boolean isGear() { return gear; } /** * Sets the gear. * * @param gear the new gear */ public void setGear(boolean gear) { this.gear = gear; } /** * Gets the gear update. * * @return the gear update */ public Date getGearUpdate() { return gearUpdate; } /** * Sets the gear update. * * @param gearUpdate the new gear update */ public void setGearUpdate(Date gearUpdate) { this.gearUpdate = gearUpdate; } /** * Checks if is hero. * * @return true, if is hero */ public boolean isHero() { return hero; } /** * Sets the hero. * * @param hero the new hero */ public void setHero(boolean hero) { this.hero = hero; } /** * Checks if is visitor. * * @return true, if is visitor */ public boolean isVisitor() { return visitor; } /** * Sets the visitor. * * @param visitor the new visitor */ public void setVisitor(boolean visitor) { this.visitor = visitor; } /** * Checks if is novice. * * @return true, if is novice */ public boolean isNovice() { return novice; } /** * Sets the novice. * * @param novice the new novice */ public void setNovice(boolean novice) { this.novice = novice; } } /** * The Class GuildResponse. */ class GuildResponse { /** * Instantiates a new guild response. * * @param guilda the guilda */ public GuildResponse(Guilda guilda) { // TODO Auto-generated constructor stub this.name = guilda.getName(); this.active = guilda.isActive(); this.region = guilda.getRegion(); this.block = guilda.isBlock(); this.defaultWelcomeMessage = guilda.getDefaultWelcomeMessage(); this.cmdCount = guilda.getCmdCount(); this.level = guilda.getLevel(); this.exp = guilda.getExp(); this.expRequired = guilda.getExpRequired(); } /** The name. */ private String name; /** The active. */ private boolean active; /** The region. */ private String region; /** The block. */ private boolean block; /** The default welcome message. */ private String defaultWelcomeMessage; /** The cmd count. */ private int cmdCount; /** The level. */ private int level; /** The exp. */ private int exp; /** The exp required. */ private int expRequired; /** * Gets the name. * * @return the name */ public String getName() { return name; } /** * Sets the name. * * @param name the new name */ public void setName(String name) { this.name = name; } /** * Checks if is active. * * @return true, if is active */ public boolean isActive() { return active; } /** * Sets the active. * * @param active the new active */ public void setActive(boolean active) { this.active = active; } /** * Gets the region. * * @return the region */ public String getRegion() { return region; } /** * Sets the region. * * @param region the new region */ public void setRegion(String region) { this.region = region; } /** * Checks if is block. * * @return true, if is block */ public boolean isBlock() { return block; } /** * Sets the block. * * @param block the new block */ public void setBlock(boolean block) { this.block = block; } /** * Gets the default welcome message. * * @return the default welcome message */ public String getDefaultWelcomeMessage() { return defaultWelcomeMessage; } /** * Sets the default welcome message. * * @param defaultWelcomeMessage the new default welcome message */ public void setDefaultWelcomeMessage(String defaultWelcomeMessage) { this.defaultWelcomeMessage = defaultWelcomeMessage; } /** * Gets the cmd count. * * @return the cmd count */ public int getCmdCount() { return cmdCount; } /** * Sets the cmd count. * * @param cmdCount the new cmd count */ public void setCmdCount(int cmdCount) { this.cmdCount = cmdCount; } /** * Gets the level. * * @return the level */ public int getLevel() { return level; } /** * Sets the level. * * @param level the new level */ public void setLevel(int level) { this.level = level; } /** * Gets the exp. * * @return the exp */ public int getExp() { return exp; } /** * Sets the exp. * * @param exp the new exp */ public void setExp(int exp) { this.exp = exp; } /** * Gets the exp required. * * @return the exp required */ public int getExpRequired() { return expRequired; } /** * Sets the exp required. * * @param expRequired the new exp required */ public void setExpRequired(int expRequired) { this.expRequired = expRequired; } } }
Markdown
UTF-8
6,190
2.515625
3
[ "Unlicense" ]
permissive
# Color-space [![test](https://github.com/colorjs/color-space/actions/workflows/test.yml/badge.svg)](https://github.com/colorjs/color-space/actions/workflows/test.yml) [![stable](https://img.shields.io/badge/stability-stable-brightgreen.svg)](http://github.com/badges/stability-badges) [![npm](https://img.shields.io/npm/v/color-space)](https://npmjs.org/color-space) [![size](https://img.shields.io/bundlephobia/minzip/color-space/latest)](https://bundlephobia.com/package/color-space) <img src="https://raw.githubusercontent.com/colorjs/color-space/gh-pages/logo.png" width="100%" height="150"/> Collection of color spaces conversions & data. [Demo](http://colorjs.github.io/color-space). ## Usage ```js import space from 'color-space'; //convert lab to lch var result = space.lab.lch([80,50,60]); ``` Spaces can be imported separately: ```js import rgb from 'color-space/rgb.js'; import hsl from 'color-space/hsl.js'; //convert rgb to hsl rgb.hsl([200,230,100]); ``` <!-- New space can be registered as: ```js import space, {register} from 'color-space'; register(spaceDefiniton) ``` --> ## API ```js <fromSpace>.<toSpace>(array); <space>.name //space name <space>.min //channel minimums <space>.max //channel maximums <space>.channel //channel names <space>.alias //alias space names ``` ## Spaces * [x] [RGB](https://en.wikipedia.org/wiki/CIE_1931_color_space#CIE_RGB_colour_space) — additive color model based on red, green and blue primary colors. * [x] [HSL](https://en.wikipedia.org/wiki/HSL_and_HSV) — cylindrical-coordinates representation of RGB. * [x] [HSV, HSB](https://en.wikipedia.org/wiki/HSL_and_HSV) * [x] [HWB](http://dev.w3.org/csswg/css-color/#the-hwb-notation) * [x] [HSI](https://en.wikipedia.org/wiki/HSL_and_HSV) — used for computer vision due to better separation of shapes in an image, comparing to HSL/HSB. * [x] [CMYK](https://en.wikipedia.org/wiki/CMYK_color_model) * [x] [CMY](https://en.wikipedia.org/wiki/CMYK_color_model) * [x] [XYZ](http://en.wikipedia.org/wiki/CIE_1931_color_space) * [x] [XYY (YXY)](https://en.wikipedia.org/wiki/CIE_1931_color_space#CIE_xy_chromaticity_diagram_and_the_CIE_xyY_color_space) * [x] [LAB](http://en.wikipedia.org/wiki/Lab_color_space) * [x] [LCH<sub>ab</sub>](https://en.wikipedia.org/wiki/Lab_color_space#Cylindrical_representation:_CIELCh_or_CIEHLC) * [x] [LUV](http://en.wikipedia.org/wiki/CIELUV) * [x] [LCH<sub>uv</sub>](http://en.wikipedia.org/wiki/CIELUV#Cylindrical_representation) * [x] [HSL<sub>uv</sub>](http://www.hsluv.org/) * [x] [HPL<sub>uv</sub>](http://www.hsluv.org/) * [x] [LAB<sub>Hunter</sub>](http://en.wikipedia.org/wiki/Lab_color_space#Hunter_Lab) * [x] [YUV](https://en.wikipedia.org/?title=YUV) * [x] [YIQ](https://en.wikipedia.org/?title=YIQ) * [x] [YC<sub>g</sub>C<sub>o</sub>](https://en.wikipedia.org/wiki/YCgCo) * [x] [YD<sub>b</sub>D<sub>r</sub>](https://en.wikipedia.org/wiki/YDbDr) * [x] [YP<sub>b</sub>P<sub>r</sub>](https://en.wikipedia.org/wiki/YPbPr) * [x] [YC<sub>b</sub>C<sub>r</sub>](https://en.wikipedia.org/wiki/YCbCr) * [x] [Y<sub>c</sub>C<sub>bc</sub>C<sub>rc</sub>](https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.2020_conversion) * [x] [JPEG](https://en.wikipedia.org/wiki/YCbCr#JPEG_conversion) * [x] [XvYCC](https://en.wikipedia.org/wiki/XvYCC) * [x] [UCS](https://en.wikipedia.org/wiki/CIE_1960_color_space) * [x] [UVW](https://en.wikipedia.org/wiki/CIE_1964_color_space) * [ ] [Munsell](https://en.wikipedia.org/wiki/Munsell_color_system) * [ ] [NCS](https://en.wikipedia.org/wiki/Natural_Color_System) * [ ] [PMS](https://en.wikipedia.org/wiki/Pantone) * [ ] [RAL](https://en.wikipedia.org/wiki/RAL_colour_standard) * [x] [TSL](https://en.wikipedia.org/wiki/TSL_color_space) – color space designed for face detection purpose. * [ ] [RG](https://en.wikipedia.org/wiki/RG_color_space) * [ ] [RGK](https://en.wikipedia.org/wiki/RG_color_space) * [x] [Coloroid](https://en.wikipedia.org/wiki/Coloroid) — color space for architects and visual constructors, Hungarian Standard MSZ 7300 since 2000. * [ ] [OSA-UCS](https://en.wikipedia.org/wiki/OSA-UCS) — accurately reprsenting uniform color differences, developed by the Optical Society of America’s Committee on Uniform Color Scales. * [ ] [HKS](https://en.wikipedia.org/wiki/HKS_(colour_system)) * [x] [LMS](http://en.wikipedia.org/wiki/LMS_color_space) — represents sensitivity of the human eye to Long, Medium and Short wavelengths. * [x] [Cubehelix](https://www.mrao.cam.ac.uk/~dag/CUBEHELIX/) — colormaps for data visualization. * [ ] [Gray](http://dev.w3.org/csswg/css-color/#grays) * [ ] [CIECAM02](https://en.wikipedia.org/wiki/CIECAM02) * [ ] [US Federal Standard 595](https://en.wikipedia.org/wiki/Federal_Standard_595) * [ ] [Toyo](http://mytoyocolor.com/) * [ ] [PhotoYCC](http://www5.informatik.tu-muenchen.de/lehre/vorlesungen/graphik/info/csc/COL_34.htm) * [x] [HCG](https://github.com/acterhd/hcg-legacy) * [ ] [HCL](http://www.chilliant.com/rgb2hsv.html) * [x] [HSP](http://alienryderflex.com/hsp.html) * [ ] [HCY](http://chilliant.blogspot.ca/2012/08/rgbhcy-in-hlsl.html) * [x] [YES](http://www.atlantis-press.com/php/download_paper.php?id=198) — computationally effective color space for face recognition. * [ ] [British Standard Colour](http://www.britishstandardcolour.com/) * [ ] [RG chromacity](https://en.wikipedia.org/wiki/Rg_chromaticity) * [ ] [CIE DSH](https://en.wikipedia.org/wiki/Rg_chromaticity) * [ ] [HSM](http://seer.ufrgs.br/rita/article/viewFile/rita_v16_n2_p141/7428) ## Contribute Please fork, add color space with basic _conversions_ to/from XYZ or RGB and _tests_. The goal of the project is the most complete set of color spaces with minimal uniform API. ## Credits Thanks to all scientists, who devoted their time to color research and conveyed their knowledge, for now we can use their formulas and code. ## Alternatives * [color-convert](https://github.com/harthur/color-convert) * [chromatist](https://github.com/jrus/chromatist) * [spectra](https://github.com/avp/spectra) * [colorspaces.js](https://github.com/boronine/colorspaces.js) ## See also * [color-api](https://github.com/LeaVerou/color-api) - color API proposal by Lea Verou
PHP
UTF-8
820
2.609375
3
[]
no_license
<?php namespace App\Models\Admin; use Core\Model; class Slider extends Model { protected $table = 'sliders'; public function create($data) { return $this->insertArray($data, $this->table); } public function get() { $sql = "SELECT * FROM $this->table "; return $this->query($sql); } public function show($id) { return $this->fetch("SELECT * from $this->table where id = $id "); } public function update($data, $id) { return $this->updateArray($data, $this->table, $id); } public function delete($slider, $id) { $link = _PUBLIC_PATH_ . $slider['file']; if (file_exists($link)) { unlink($link); } return $this->query("DELETE FROM $this->table where id = $id "); } }
Java
UTF-8
710
2.96875
3
[]
no_license
package com.src; import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc=new Scanner(System.in); int choice; System.out.println("enter your choice: "); do { StudentSampleData.doList(); choice=sc.nextInt(); switch(choice) { case 1: { StudentSampleData.data(); System.out.println("values got inserted"); break; } case 2: { System.out.println("Enter student id to remove: "); break; } } } while(choice!=1); } }
Markdown
UTF-8
696
2.765625
3
[]
no_license
# Learning Objectives At the end of this project, you are expected to be able to explain to anyone, without the help of Google: - Immutable objects. Who, what, when, where, and why? - How to use the Immutable.js library to bring immutability to Javascript - The differences between List and Map - How to use Merge, Concat, and Deep Merging - What a lazy Seq is ## Requirements - Allowed editors: vi, vim, emacs, Visual Studio Code - A README.md file, at the root of the folder of the project, is mandatory - All of your files will be interpreted/compiled on Ubuntu 18.04 LTS using node 12.x.x and npm 6.x.x - All of your files should end with a new line - All of your functions must be exported
SQL
UTF-8
1,372
3.078125
3
[ "CC0-1.0" ]
permissive
-- TransactionObligatedAmount required on rows that do not include values for USSGL accounts balances or subtotals SELECT row_number, transaction_obligated_amou FROM award_financial WHERE submission_id = {0} AND transaction_obligated_amou IS NULL AND COALESCE(ussgl480100_undelivered_or_cpe, 0) = 0 AND COALESCE(ussgl480100_undelivered_or_fyb, 0) = 0 AND COALESCE(ussgl480200_undelivered_or_cpe, 0) = 0 AND COALESCE(ussgl480200_undelivered_or_fyb, 0) = 0 AND COALESCE(ussgl483100_undelivered_or_cpe, 0) = 0 AND COALESCE(ussgl483200_undelivered_or_cpe, 0) = 0 AND COALESCE(ussgl487100_downward_adjus_cpe, 0) = 0 AND COALESCE(ussgl487200_downward_adjus_cpe, 0) = 0 AND COALESCE(ussgl488100_upward_adjustm_cpe, 0) = 0 AND COALESCE(ussgl488200_upward_adjustm_cpe, 0) = 0 AND COALESCE(ussgl490100_delivered_orde_cpe, 0) = 0 AND COALESCE(ussgl490100_delivered_orde_fyb, 0) = 0 AND COALESCE(ussgl490200_delivered_orde_cpe, 0) = 0 AND COALESCE(ussgl490800_authority_outl_cpe, 0) = 0 AND COALESCE(ussgl490800_authority_outl_fyb, 0) = 0 AND COALESCE(ussgl493100_delivered_orde_cpe, 0) = 0 AND COALESCE(ussgl497100_downward_adjus_cpe, 0) = 0 AND COALESCE(ussgl497200_downward_adjus_cpe, 0) = 0 AND COALESCE(ussgl498100_upward_adjustm_cpe, 0) = 0 AND COALESCE(ussgl498200_upward_adjustm_cpe, 0) = 0;
Python
UTF-8
783
2.53125
3
[]
no_license
# this is a test file, to test how spacy tokeniser performs import json,ndjson, spacy with open(r'C:\Users\spenc\OneDrive - The University of Auckland\Study\UoA\Project\OCR - Sample of the Sample\OCR - Sample of the Sample\ocr-metadata.ndjson') as f: data = ndjson.load(f) jsonFormat = json.loads(json.dumps(data)) textRact = json.loads(jsonFormat[0]['textractResponse']) text = [] for block in textRact['blocks']: if block['blocktype'] == 'WORD': #print(block['text']) text.append(block['text']) text = str(text).replace("'", '')[1:-1] print(text) nlp = spacy.load("en_core_web_lg") doc = nlp(text) for token in doc: print(token.text, token.lemma_, token.pos_, token.tag_, token.dep_, token.shape_, token.is_alpha, token.is_stop)
Markdown
UTF-8
5,214
2.703125
3
[ "MIT" ]
permissive
# chronic *adjective*: from Greek *khronikos* ‘of time,’ from *khronos* ‘time.’ [![NPM](https://nodei.co/npm/chronic.png)](https://nodei.co/npm/chronic/) [![Build Status](https://travis-ci.org/RnbWd/chronic.svg?branch=master)](https://travis-ci.org/RnbWd/chronic) [![Dependency Status](https://img.shields.io/david/rnbwd/chronic.svg?style=flat-square)](https://david-dm.org/rnbwd/chronic) [![Stability Status](https://img.shields.io/badge/stability-stable-green.svg?style=flat-square)](https://github.com/dominictarr/stability#experimental) ```bash npm install chronic --save-dev ``` ## Background My goal is to provide a balance between *configuration and customization* through the creation of *task-transducers*. This library is now a heavily modified version of azer's [bud](https://github.com/azer/bud) and gulp's [vinyl-fs](https://github.com/wearefractal/vinyl-fs). Rationale for this project can be found [here](https://github.com/rnbwd/chronic/blob/master/RATIONALE.md). Please read the [CHANGELOG](https://github.com/rnbwd/chronic/blob/master/CHANGELOG.md) The API internals recently went through some final namespace orientation, which may result in breaking changes to current code, but the API is now stable. ## Usage ``` js var chron = require('chronic'); chron('default', chron.after('task2'), function(t) { t.exec('echo dat {bud}!', t.params); }); chron('task1', chron.source('./one/**').dest('./two'), chron.build) chron('task2', chron.after('task1'), tasktwo); function tasktwo(t) { t.build(t.src('./two/**'), t.dest('./three')); } ``` - Run: ```bash $ node <filename> --bud=chronic ``` - Should run 'task1', 'task2', then 'default' in that order, returning this output: ```bash default Running... task2 Running... task1 Running... task1 Completed in 6ms task2 Completed in 7ms default Executing "echo dat chronic!" default dat chronic! default Completed in 10ms ``` ### Command Line Usage - To run tasks: ```bash $ node <filename> <tasks> <params> ``` - to watch files: ```bash $ node <filename> -w # or --watch ``` - to list available tasks in a file: ```bash $ node <filename> -l # or --list ``` ## API ### chronic(task, [opts, func]) * `task` a string used to name tasks. * `opts` a chainable series chronic methods. * `func` a function that contains the paramater `t`, optionally use [chronic.build](#chronicbuild) #### opts: * `chronic.after` a comma separated list of tasks (strings) - list of tasks that should be *run and completed* prior calling `func` - may be used without `func` eg: `chron('default', chron.after('task'))` * `chronic.source` an array or commma separated list of globby strings passed to `vinyl.src` (see [globby](https://github.com/sindresorhus/globby)) - passed down to `t.src()` and `t.files` * `chronic.dest` a single string - passed down to `t.dest()` and `t.path` * `chronic.watch` an array or commma separated list of globby strings to watch (see [globby](https://github.com/sindresorhus/globby)) - passed down to `t.watching` * `chronic.transform` a comma separated list of functions that are stream transforms - these functions are piped inbetween `t.src` and `t.dest` if `chronic.build` is used - only gulp-plugins can safely be used at the moment #### *func(* **t** *)* : * `t.done` - callback which determines if a task has completed - optionally pass in an error `t.done([err])` * `t.src` - returns `vinyl.src` *(gulp.src)* - if `chronic.source` is defined, calling `t.src()` is populated with the content of `t.files` - this can be easily overridden by defining `t.src('glob')` manually * `t.dest` - returns `vinyl.dest` *(gulp.dest)* - if `chronic.dest` is defined, calling `t.dest()` is populated with the content of `t.path` - this can also be overriden * `t.build` - returns an instance of [pump](https://github.com/mafintosh/pump) that calls `t.done` upon completion or error of stream - example: `t.build(t.src(), t.dest())` * `t.exec` - returns formatted [npm-execspawn](https://github.com/mafintosh/npm-execspawn) calling `t.done()` upon completion - uses [format-text](https://www.npmjs.com/package/format-text) instead of looking for env variables - example: `t.exec('echo hello {place}!', {place: 'world'})` ------ * `t.params` - paramaters returned from command line * `t.files` - returns an array of strings from `chronic.source` * `t.path` - returns an array of strings from `chronic.dest` * `t.watching` - returns an array of files from `chronic.watch` - used internally to watch files being watched, * `t.source` - returns [vinyl-source-stream](https://www.npmjs.com/package/vinyl-source-stream) * `t.buffer` - return [vinyl-buffer](https://www.npmjs.com/package/vinyl-buffer) * `t.pump` - returns [pump](https://www.npmjs.com/package/pump) * `t.eos` - returns [end-of-stream](https://www.npmjs.com/package/end-of-stream) #### chronic.build - returns `function(t)` with `pump(t.src(), -> [transforms], -> t.dest())`, returning `t.done` upon completion or error - this method is syntactical sugar over the most common use pattern of this library ## TODO More examples and tests and stuff coming soon!! ## License MIT
C++
UTF-8
4,912
2.75
3
[ "BSD-3-Clause" ]
permissive
#include <QJsonObject> #include <QJsonArray> #include <QJsonValue> #include "wirenet.h" #include "wire.h" #include "label.h" #include "itemfactory.h" using namespace QSchematic; WireNet::WireNet(QObject* parent) : QObject(parent) { // Label _label = std::make_shared<Label>(); _label->setPos(0, 0); connect(_label.get(), &Label::highlightChanged, this, &WireNet::labelHighlightChanged); } WireNet::~WireNet() { qDeleteAll(_wires); } QJsonObject WireNet::toJson() const { QJsonObject object; object.insert("name", name()); QJsonArray wiresArray; for (const Wire* wire : _wires) { wiresArray.append(wire->toJson()); } object.insert("wires", wiresArray); return object; } bool WireNet::fromJson(const QJsonObject& object) { setName(object["name"].toString()); QJsonArray wiresArray = object["wires"].toArray(); for (const QJsonValue& wireValue : wiresArray) { QJsonObject wireObject = wireValue.toObject(); if (wireObject.isEmpty()) continue; Wire* newWire = dynamic_cast<Wire*>(ItemFactory::instance().fromJson(wireObject).release()); if (!newWire) continue; newWire->fromJson(wireObject); addWire(*newWire); } connect(_label.get(), &Label::highlightChanged, this, &WireNet::labelHighlightChanged); return true; } bool WireNet::addWire(Wire& wire) { // Update the junctions // Do this before we add the wire so that lineSegments() doesn't contain the line segments // of the new wire. Otherwise all points will be marked as junctions. for (int i = 0; i < wire.points().count(); i++) { const WirePoint& point = wire.points().at(i); for (const Line& line : lineSegments()) { if (line.containsPoint(point.toPoint(), 0)) { wire.setPointIsJunction(i, true); break; } wire.setPointIsJunction(i, false); } } // Add the wire connect(&wire, &Wire::pointMoved, this, &WireNet::wirePointMoved); connect(&wire, &Wire::highlightChanged, this, &WireNet::wireHighlightChanged); _wires.append(&wire); return true; } bool WireNet::removeWire(Wire& wire) { disconnect(&wire, nullptr, this, nullptr); _wires.removeAll(&wire); updateWireJunctions(); return true; } bool WireNet::contains(const Wire& wire) const { for (const Wire* w : _wires) { if (w == &wire) { return true; } } return false; } void WireNet::simplify() { for (Wire* wire : _wires) { wire->simplify(); } } void WireNet::setName(const QString& name) { _name = name; _label->setText(_name); _label->setVisible(!_name.isEmpty()); } void WireNet::setHighlighted(bool highlighted) { // Wires for (Wire* wire : _wires) { if (!wire) { continue; } wire->setHighlighted(highlighted); } // Label _label->setHighlighted(highlighted); emit highlightChanged(highlighted); } QString WireNet::name()const { return _name; } QList<Wire*> WireNet::wires() const { return _wires; } QList<Line> WireNet::lineSegments() const { QList<Line> list; for (const Wire* wire : _wires) { if (!wire) { continue; } list.append(wire->lineSegments()); } return list; } QList<QPoint> WireNet::points() const { QList<QPoint> list; for (const Wire* wire : _wires) { list.append(wire->points().toList()); } return list; } std::shared_ptr<Label> WireNet::label() { return _label; } void WireNet::wirePointMoved(Wire& wire, WirePoint& point) { // Clear the junction point.setIsJunction(false); // Let the others know too emit pointMoved(wire, point); } void WireNet::labelHighlightChanged(const Item& item, bool highlighted) { Q_UNUSED(item) setHighlighted(highlighted); } void WireNet::wireHighlightChanged(const Item& item, bool highlighted) { Q_UNUSED(item) setHighlighted(highlighted); } void WireNet::updateWireJunctions() { for (Wire* wire : _wires) { // Create a list of wire segments which dont't contains the current wire QList<Line> lineSegments; for (const Wire* w : _wires) { if (w != wire) { lineSegments.append(w->lineSegments()); } } // Check for each point whether it's part of a line segment for (int i = 0; i < wire->points().count(); i++) { const WirePoint& point = wire->points().at(i); for (const Line& line : lineSegments) { if (line.containsPoint(point.toPoint(), 0)) { wire->setPointIsJunction(i, true); break; } wire->setPointIsJunction(i, false); } } } }
Python
UTF-8
2,713
2.984375
3
[]
no_license
class Client: def __init__(self, id_client, nume, cnp, inchirieri): self.__id_client = id_client self.__nume = nume self.__cnp = cnp self.__inchirieri = inchirieri def get_id(self): return self.__id_client def get_nume(self): return self.__nume def get_cnp(self): return self.__cnp def get_inchirieri(self): return self.__inchirieri def set_nume(self, value): self.__nume = value def set_cnp(self, value): self.__cnp = value def inchiriaza(self): self.__inchirieri = self.__inchirieri + 1 def returneaza(self): self.__inchirieri = self.__inchirieri - 1 def __str__(self): return "Id: " + str(self.__id_client) + "\n" + "Nume: " + self.__nume + "\n" +"CNP: " + self.__cnp + "\n" + "Filme inchiriate: " + str(self.__inchirieri) class Film: def __init__(self, id_film, titlu, descriere, gen, inchirieri): self.__id_film = id_film self.__titlu = titlu self.__descriere = descriere self.__gen = gen self.__inchirieri = inchirieri def get_id(self): return self.__id_film def get_titlu(self): return self.__titlu def get_descriere(self): return self.__descriere def get_gen(self): return self.__gen def get_inchirieri(self): return self.__inchirieri def set_titlu(self, value): self.__titlu = value def set_descriere(self, value): self.__descriere = value def set_gen(self, value): self.__gen = value def inchiriaza(self): self.__inchirieri = self.__inchirieri + 1 def returneaza(self): self.__inchirieri = self.__inchirieri - 1 def __str__(self): return "Id: " + str(self.__id_film) + "\n" + "Titlu: " + self.__titlu + "\n" + "Descriere: " + self.__descriere + "\n" + "Gen: " + self.__gen + "\n" + "Inchirieri: " + str(self.__inchirieri) class Inchiriere: def __init__(self, client, film): self.__client = client self.__film = film def __str__(self): return "Id client: " + str(self.__client.get_id()) + "\n" + "Nume client: " + self.__client.get_nume() + "\n" + "Id film: " + str(self.__film.get_id()) + "\n" + "Ttlu film: " + self.__film.get_titlu() def get_film(self): return self.__film def get_id_film(self): film = self.get_film() return film.get_id() def get_client(self): return self.__client def get_id_client(self): client = self.get_client() return client.get_id()
Java
UTF-8
238
1.710938
2
[ "Apache-2.0" ]
permissive
package commons.boot.upload; import lombok.Data; import java.io.Serializable; @Data public class ChangeUploadFileMaxSize implements Serializable { private Long maxFileSize = 500L; private Long maxRequestSize = 500L; }
Java
UTF-8
479
1.882813
2
[]
no_license
package app.lucidalarm2; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class FinalAlarmBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent arg1) { Log.d("graw", "FinalAlarmBroadcastReveiver onRecieve()"); Intent intent = new Intent(context, FinalAlarmPlayerService.class); context.startService(intent); } }
C
UTF-8
273
3.21875
3
[]
no_license
#include <stdio.h> //Факториал. Для целого числа k(0≤k≤12) посчитать k!. int main() { int k, counter=1; scanf("%d", &k); for (int i = 1; i <= k; i++) { counter = counter * i; } printf("%d\n", counter); return 0; }
JavaScript
UTF-8
449
3.015625
3
[]
no_license
export function objectSize(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; } export function objectHasValue(obj, value) { if (Object.values(obj).indexOf(value) > -1) { return true; } else return false; } export function cleanObject(obj) { for (var propName in obj) { if (obj[propName] === null || obj[propName] === undefined) { delete obj[propName]; } } }
Python
UTF-8
1,350
2.640625
3
[]
no_license
import numpy as np import pandas as pd import matplotlib.pyplot as plt # Importing Dataset dataset = pd.read_csv('dataset2.csv') X = dataset.iloc[:, 1:27].values y = dataset.iloc[:, 27].values # Splitting the dataset into Training Set and Testing Set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, train_size = 0.7, random_state = 42) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.fit_transform(X_test) from keras.wrappers.scikit_learn import KerasClassifier from sklearn.model_selection import cross_val_score,GridSearchCV,RandomizedSearchCV from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout def build_classifier(optimizer = 'adam'): classifier = Sequential() classifier.add(Dense(output_dim = 128, init = 'uniform', activation = 'relu', input_dim = 23 )) classifier.add(Dense(output_dim = 128, init = 'uniform', activation = 'relu')) classifier.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid')) classifier.compile(optimizer = optimizer, loss = 'binary_crossentropy', metrics = ['accuracy']) return classifier classifier = KerasClassifier(build_fn = build_classifier, batch_size = 10000, nb_epoch = 1)
TypeScript
UTF-8
3,328
2.8125
3
[ "MIT" ]
permissive
import { Context, Middleware } from '@curveball/core'; import highlight from 'highlight.js'; /** * Options that may be passed to the middleware. */ type Options = { title?: string stylesheets?: string[] }; /** * Options after clean-up. * * Basically the same but nothing is optional. */ type SureOptions = { title: string, stylesheets: string[] }; const parsedContentTypes = [ 'application/json', 'application/hal+json', 'application/problem+json', ]; export default function browser(options?: Options): Middleware { if (typeof options === 'undefined') { options = {}; } if (!options.title) { options.title = 'HAL Browser'; } if (!options.stylesheets) { options.stylesheets = []; } return async (ctx, next) => { // Check to see if the client even wants html. if (!ctx.request.accepts('text/html')) { return next(); } // Doing the inner request await next(); // We only care about transforming a few content-types if (!parsedContentTypes.includes(ctx.response.type)) { return; } // Find out the client prefers HTML over the content-type that was actually // returned. // // This is useful if the client submitted a lower q= score for text/html if (ctx.request.accepts('text/html', ...parsedContentTypes) === 'text/html') { ctx.response.headers.set('Content-Type', 'text/html'); generateHtmlIndex(ctx, ctx.response.body, <SureOptions> options); } }; } function generateHtmlIndex(ctx: Context, body: any, options: SureOptions) { const jsonBody = syntaxHighlightJson(body); const links = generateLinks(body); const stylesheets = options.stylesheets.map(ss => { return ` <link rel="stylesheet" href="${h(ss)}" type="text/css" />\n`; }).join(''); ctx.response.body = ` <!DOCTYPE html> <html> <head> <title>${h(options.title)}</title> ${stylesheets} </head> <body> <header> <h1>${h(options.title)}</h1> </header> <main> ${links} <h2>Body</h2> <code class="hljs"><pre>${jsonBody}</pre></code> </main> </body> </html> `; } function h(input: string): string { const map: { [s: string]: string } = { '&' : '&amp;', '<' : '&lt;', '>' : '&gt;', '"' : '&quot' }; return input.replace(/&<>"/g, s => map[s]); } function syntaxHighlightJson(body: any): string { return highlight.highlight('json', JSON.stringify(body, undefined, ' ')).value; } function generateLinks(body: any): string { if (!body._links) { return ''; } let linkHtml = ''; for (const rel of Object.keys(body._links)) { const links = Array.isArray(body._links[rel]) ? body._links[rel] : [body._links[rel]]; const linkCount = links.length; let first = true; for (const link of links) { linkHtml += '<tr>'; if (first) { linkHtml += `<td rowspan="${linkCount}">${h(rel)}</td>`; first = false; } linkHtml += `<td><a href="${h(link.href)}">${h(link.href)}</a></td>`; linkHtml += '<td>' + (link.title ? h(link.title) : '') + '</td>'; linkHtml += '</tr>\n'; } } return ` <h2>Links</h2> <table> <tr> <th>Relationship</th><th>Url</th><th>Title</th> </tr> ${linkHtml} </table> `; }
TypeScript
UTF-8
3,047
2.515625
3
[]
no_license
import { Monster } from './monster'; export const MONSTERS: Monster[] = [ { id: 11, name: "Goblin", ac: 12, size: "Medium", type: "humonoid", alignment: "choatic evil", hitPointAvg: 7, hitDice: "1d6 +2", speed: 30, str: 20, dex: 10, con: 10, int: 5, wis: 6, cha: 4, cr: 0.25, xp: 100 }, { id: 12, name: "Goblin Shaman", ac: 12, size: "Medium", type: "humonoid", alignment: "choatic evil", hitPointAvg: 7, hitDice: "1d6 +2", speed: 30, str: 20, dex: 10, con: 10, int: 5, wis: 6, cha: 4, cr: 0.25, xp: 100 }, { id: 13, name: "Kobold", ac: 12, size: "Medium", type: "humonoid", alignment: "choatic evil", hitPointAvg: 7, hitDice: "1d6 +2", speed: 30, str: 20, dex: 10, con: 10, int: 5, wis: 6, cha: 4, cr: 0.25, xp: 100 }, { id: 14, name: "Winged Kobold", ac: 12, size: "Medium", type: "humonoid", alignment: "choatic evil", hitPointAvg: 7, hitDice: "1d6 +2", speed: 30, str: 20, dex: 10, con: 10, int: 5, wis: 6, cha: 4, cr: 0.25, xp: 100 }, { id: 15, name: "Kobold Sorcerer", ac: 12, size: "Medium", type: "humonoid", alignment: "choatic evil", hitPointAvg: 7, hitDice: "1d6 +2", speed: 30, str: 20, dex: 10, con: 10, int: 5, wis: 6, cha: 4, cr: 0.25, xp: 100 }, { id: 16, name: "Kobold Inventor", ac: 12, size: "Medium", type: "humonoid", alignment: "choatic evil", hitPointAvg: 7, hitDice: "1d6 +2", speed: 30, str: 20, dex: 10, con: 10, int: 5, wis: 6, cha: 4, cr: 0.25, xp: 100 }, { id: 17, name: "Young Red Dragon", ac: 18, size: "Large", type: "draconic", alignment: "choatic evil", hitPointAvg: 170, hitDice: "8d12 +20", speed: 30, str: 20, dex: 10, con: 10, int: 5, wis: 6, cha: 4, cr: 13,xp:3400, abilities: [ { title: "Hoarder", description: "The dragon has a vast collection of gold and magical items. It will always consider adding more to its collection if asked to bargain" }, { title: "Out of reach", description: "The dragon can make tail attacks while flying without provoking opportunity attacks when passing by" } ], actions: [ { title:"Multi Attack: ", description: "The dragon can make either two Claw attacks or a Tail and a Claw attack" }, { title: "Claw: ", description: "+8 to hit, reach 5ft, one target. Hit 2d8 + 5 slashing damage" }, { title: "Tail: ", description: "+8 to hit, reach 10ft, one target. Hit 3d8 + 5 bludgeoning damage " } ], legendaryActions: [ { title: "Fire Breath (recharge 5-6): ", description: "Each creature in a 30ft cone makes a Dexterity saving throw. On Fail take 6d8 fire damage half on success" } ], languages: ["Draconic", "Common"], conditionImunities: ["Fear", "Charmed"], damageImmunities: ["Fire"], senses: ["Darkvision 120ft", "Blindsight 60ft", "Passive Perception 17"] }, ]
Markdown
UTF-8
2,082
3.015625
3
[]
no_license
## Activity API This API uses Google DataStore as storage, there is not local storage on Heroku or Postgress. We need Google DataStore because we plan to store hugh amounts of activities that the user can do inside breathecode. Possible activities (so far): ``` "breathecode_login" //every time it logs in "online_platform_registration" //first day using breathecode "public_event_attendance" //attendy on an eventbrite event "classroom_attendance" //when the student attent to class "classroom_unattendance" //when the student miss class "lesson_opened" //when a lessons is opened on the platform "office_attendance" //when the office raspberry pi detects the student "nps_survey_answered" //when a nps survey is answered by the student "exercise_success" //when student successfuly tests exercise ``` Any activity has the following inputs: ``` 'cohort', 'data', 'day', 'slug', 'user_agent', ``` ## Endpoints for the user Get recent user activity ``` GET: activity/user/{email_or_id}?slug=activity_slug ``` Add a new user activity (requiers autentication) ``` POST: activity/user/{email_or_id} { 'slug' => 'activity_slug', 'data' => 'any aditional data (string or json-encoded-string)' } 💡 Node: You can pass the cohort in the data json object and it will be possible to filter on the activity graph like this: { 'slug' => 'activity_slug', 'data' => "{ \"cohort\": \"mdc-iii\" }" (json encoded string with the cohort id) } ``` Endpoints for the Cohort Get recent user activity ``` GET: activity/cohort/{slug_or_id}?slug=activity_slug ``` Endpoints for the coding_error's ``` Get recent user coding_errors GET: activity/coding_error/{email_or_id}?slug=activity_slug ``` ``` Add a new coding_error (requiers autentication) POST: activity/coding_error/ { "user_id" => "my@email.com", "slug" => "webpack_error", "data" => "optiona additional information about the error", "message" => "file not found", "name" => "module-not-found, "severity" => "900", "details" => "stack trace for the error as string" } ```