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
PHP
UTF-8
892
2.640625
3
[]
no_license
<?php include_once ($_SERVER['DOCUMENT_ROOT'].'/ProjektiF/models/userMapper.php'); include_once ($_SERVER['DOCUMENT_ROOT'].'/ProjektiF/models/userModel.php'); class UserController { public function InsertUser($username,$email, $passwordU, $roli) { //therrasim funksionet qe bejne kalkulimin e kerkeses //insert user ndatabase $user = new User($username,$email, $passwordU, $roli); $userMapper2 = new UserMapper(); $userMapper2->Insert($user); return true; } public function GetUser($username,$email, $passwordU , $roli) { $user = new User($username,$email, $passwordU, $roli); $userMapper3= new UserMapper(); $userMapper3->LogIn($user); $res = $userMapper3->LogIn($user); if($res){ return true; }else{ return false; } } }
Java
UTF-8
1,186
1.953125
2
[]
no_license
package com.snda.grand.mobile.as.rest.model; import org.codehaus.jackson.annotate.JsonIgnoreProperties; import org.joda.time.DateTime; @JsonIgnoreProperties(ignoreUnknown=true) public class Authorization { private String uid; private String appId; private String refreshToken; private DateTime authorizedTime; private String publisherName; private String scope; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getAppId() { return appId; } public void setAppId(String appId) { this.appId = appId; } public String getRefreshToken() { return refreshToken; } public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; } public DateTime getAuthorizedTime() { return authorizedTime; } public void setAuthorizedTime(DateTime authorizedTime) { this.authorizedTime = authorizedTime; } public String getPublisherName() { return publisherName; } public void setPublisherName(String publisherName) { this.publisherName = publisherName; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } }
C#
UTF-8
2,098
2.84375
3
[]
no_license
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace FetchCurrentWeather { public class UazipnetRegionParser : IRegionParser { private const string urlAddress = "http://ua-zip.net/script/suggest.php"; private const string prefixParameter = "prefix={0}"; private const string typeParameter = "type={0}"; public IWeatherCodeGetter WeatherCodeGetter { private get => throw new NotImplementedException(); set => throw new NotImplementedException(); } public string[] GetParsedRegion(string zipCode) { string siteResponse = GetResponseFromSite(zipCode); return siteResponse.Split(','); } private static string GetResponseFromSite(string zipCode) { HttpWebRequest request = CreateRequestToSite(zipCode); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream stream = response.GetResponseStream()) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { string responseString = String.Empty; string parsedString = String.Empty; while ((responseString = reader.ReadLine()) != null) { parsedString = RequestStringParserHelper.ParseUTF8EscapeSequenceToUTF8Char(responseString, new CultureInfo("uk-UA")); } return parsedString; } } } private static HttpWebRequest CreateRequestToSite(string zipCode) { string FullRequestString = urlAddress + "?" + string.Format(prefixParameter, zipCode) + "&" + String.Format(typeParameter, "index"); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(FullRequestString); return request; } } }
Markdown
UTF-8
963
3.53125
4
[]
no_license
# JavaScript and DOM Manipulation ## Overview This project takes UFO sighting data (including date, location and observations) and uses javascript to populate an HTML table. The table is filterable for select columns of the table. ### Level 1: Automatic Table and Date Search * Creates a basic HTML web page. * Uses the UFO dataset to append a table to the web page and then add new rows of data for each UFO sighting. * Uses a date form in the HTML document and writes listeners for events and search through the `date/time` column to find rows that match user input. ![](images/Capture.png) ### Level 2: Multiple Search Categories * Using multiple `input` tags, writes listeners so the user can to set multiple filters and search for UFO sightings using the following criteria based on the table columns: 1. `date/time` 2. `city` 3. `state` 4. `country` 5. `shape` * Otherwise, functionality is identical to Level 1 ![](images/Capture1.png)
Java
UTF-8
822
2.34375
2
[]
no_license
package de.entrecode.datamanager_java_sdk.requests.tags; import com.squareup.okhttp.Request; import de.entrecode.datamanager_java_sdk.requests.ECDeleteRequest; /** * Created by simon, entrecode GmbH, Stuttgart (Germany) on 10.09.15. */ public class ECTagDeleteRequest extends ECDeleteRequest { private final String selfRef; /** * Default constructor with authorization header value. * * @param authHeaderValue The authorization header values to use with this request. */ public ECTagDeleteRequest(String authHeaderValue, String selfRef) { super(authHeaderValue); this.selfRef = selfRef; } @Override public Request build() { return new Request.Builder().url(selfRef).addHeader("Authorization", "Bearer " + mAuthHeaderValue).delete().build(); } }
C++
UTF-8
630
2.6875
3
[ "MIT" ]
permissive
#pragma once #include <memory> class BaseMaterial; class Vector; class RNG; class Ray; class Object { public: std::shared_ptr<BaseMaterial> material; Object(); Object(std::shared_ptr<BaseMaterial> mat): material(mat) {} virtual float intersect(const Ray& ray) const = 0; virtual Vector getNormalAt(const Vector &point) const = 0; virtual void getUVAt(const Vector &point, float& u, float& v) const = 0; virtual bool isFinite() const = 0; virtual Vector getSample(RNG& rng) const = 0; virtual void getSamples(RNG& rng, int s1, int s2, Vector* samples) const = 0; virtual float getInversePDF() const = 0; };
Java
UTF-8
1,556
2.84375
3
[]
no_license
package es.iespuertolacruz.developers.api; import java.util.Objects; public class Mercado { Moneda moneda; Wallet wallet; Double cantidad; /** * Constructor vacio */ public Mercado() { } /** * Constructor con todos los parametros de Mercado * @param moneda * @param wallet * @param cantidad */ public Mercado(Moneda moneda, Wallet wallet, Double cantidad) { this.moneda = moneda; this.wallet = wallet; this.cantidad = cantidad; } /** * Getters y Setters */ public Moneda getMoneda() { return this.moneda; } public void setMoneda(Moneda moneda) { this.moneda = moneda; } public Wallet getWallet() { return this.wallet; } public void setWallet(Wallet wallet) { this.wallet = wallet; } public Double getCantidad() { return this.cantidad; } public void setCantidad(Double cantidad) { this.cantidad = cantidad; } @Override public String toString() { return "Mercado [cantidad=" + cantidad + ", moneda=" + moneda + ", wallet=" + wallet + "]"; } @Override public boolean equals(Object o) { if (o == this) return true; if (!(o instanceof Mercado)) { return false; } Mercado mercado = (Mercado) o; return Objects.equals(moneda, mercado.moneda) && Objects.equals(wallet, mercado.wallet) && Objects.equals(cantidad, mercado.cantidad); } }
Ruby
UTF-8
958
4.5
4
[]
no_license
# Reversed Arrays (Part 2) # # Write a method that takes an Array, and returns a new Array with the elements of the original list in reverse order. Do not modify the original list. # # You may not use Array#reverse or Array#reverse!, nor may you use the method you wrote in the previous exercise. def reverse(array) reverse_array = [] copy_array = array.dup array.size.times { reverse_array << copy_array.pop } reverse_array end puts reverse([1,2,3,4]) == [4,3,2,1] # => true puts reverse(%w(a b c d e)) == %w(e d c b a) # => true puts reverse(['abc']) == ['abc'] # => true puts reverse([]) == [] # => true p list = [1, 2, 3] # => [1, 2, 3] p new_list = reverse(list) # => [3, 2, 1] puts list.object_id != new_list.object_id # => true puts list == [1, 2, 3] # => true puts new_list == [3, 2, 1] # => true
Markdown
UTF-8
6,465
3.84375
4
[]
no_license
## 1920. 수찾기 전형적인 이분 탐색 문제 A배열을 정렬하고 M개의 숫자를 받을 때마다 이분탐색을 실행해서 해당 숫자가 존재하는지 아닌지를 판단했다. ```cpp bool binary_search(int num){ int left = 0, right = n; while(left <= right){ int mid = (left+right)/2; if(arr[mid] == num) return true; if(arr[mid] <= num){ left = mid + 1; } else{ right = mid - 1; } } return false; } ``` ## 1654. 랜선 자르기 이분 탐색의 기준을 랜선의 길이라고 생각하고 문제를 풀었다. 우선 K개의 랜선 중에서 최대 길이를 Right값으로 잡는다. 그 이유는 이 최대 길이보다 긴 랜선으로는 자를 수가 없기 때문이다. 그리고나서 mid값을 잡고 K개의 랜선을 Mid값으로 몇개를 만들 수 있는지를 세고나서 이 갯수가 N보다 작으면 랜선의 길이를 좀 더 줄이고 (right = mid), N보다 크면 랜선의 길이를 좀 더 늘린다. (Left = mid + 1) (최대 랜선의 길이를 찾고 싶으므로.) ```cpp while(left < right){ long long int mid = (left + right)/2; int cnt = 0; for(int i=0; i<arr.size(); i++){ cnt += arr[i] / mid; } if(cnt < n){ right = mid; } else if(cnt >= n){ left = mid + 1; answer = max(answer, mid); } } ``` ## 2110. 공유기 설치 (실버 1) ### 시간 복잡도 이분 탐색 문제! 문제를 보고 처음에는 인덱스 0 부터 마지막 집의 인덱스까지를 보고 거리를 하나하나 계산하는 생각을 했다. 근데 이렇게 되면 집의 좌표의 최대가 십억이라 O(N)으로 봐도 10초가 걸리기 때문에 시간 초과가 나올 것이다. 그래서 이분 탐색을 이용해서 logN, 집의 개수 만큼 보니까 N, 합해서 O(NlogN)이면 되겠다 싶었다. ### 구현 **두 공유기 사이의 최대 거리**를 구하는 것이니까 이걸 기준으로 이분 탐색을 진행하였다. 우선 배열에서 나올 수 있는 최대 거리를 right로 잡고 최소 거리를 left로 설정했다. Mid 값을 최대 거리로 보고, 첫번째 집부터 최대 거리 이상의 거리에 있는 집에 공유기를 놓도록 했다. for문을 다 돌고나서 공유기의 수가 c보다 크거나 같다면 공유기를 놓을 수 있다는 말이니까 최대 공유기 수를 조금 늘려도 되겠지? 하면서 left = mid + 1을 해준다. 물론 이 부분에 mid 값과 Max값을 비교해서 더 큰 값을 Max에 넣어준다. 만약 공유기 수가 c보다 작으면 최대 공유기 수가 크구나! 그럼 줄여야지 라고 해서 right = mid - 1 을 해준다. ```cpp int left = 1; int right = arr.back(); int Max = -1; while(left <= right){ int mid = (left + right)/2; int start = arr[0]; int cnt = 1; for(int i=1; i<arr.size(); i++){ if(arr[i]-start >= mid){ start = arr[i]; cnt++; } } if(cnt >= c){ left = mid + 1; Max = max(Max, mid); } else{ right = mid - 1; } } ``` ## 3079. 입국 심사 (실버 1) ### 구현 이분 탐색 문제. 이분 탐색의 기준은 심사를 마치는데 걸리는 시간이다. Right 값을 심사대의 최댓값에 사람수/심사대수 + 1로 설정했다. (모든 심사대를 최댓값으로 설정하면 사람수/심사대수번 로테이션이 돌기 때문) mid값의 의미는 전체 심사시간이고, mid/arr[i]의 의미는 심사시간동안 해결할 수 있는 사람의 수이다. 그래서 mid값에 각 심사대의 시간으로 나누는 값을 더한 값이 사람의 수보다 크면 해당 시간 내에 m보다 큰 사람을 수용할 수 있다는 얘기니까 right = mid로 시간을 줄인다. (최소 시간을 원하므로) 이렇게 해서 나온 right값이 정답이다! ```cpp long long int s = Max*(m/n+1); long long int left = 0, right = s; while(left < right){ long long int mid = (left+right)/2; long long int sum = 0; for(int i=0; i<arr.size(); i++){ sum += mid/arr[i]; } if(sum >= m){ right = mid; } else{ left = mid + 1; } } ``` ## 2343. 기타 레슨 (실버 1) 이분 탐색 문제! 이분 탐색의 기준은 블루레이 크기이다. mid값이 의미하는게 블루레이 크기이고, 레슨의 길이가 블루레이의 크기를 넘기면 다음 블루레이에 레슨을 저장하도록 한다. 만약 모든 레슨을 블루레이에 넣지 않았다면 ( ss != 0 ) 시간이 부족하다는 말이므로 left = mid + 1;이고 모든 레슨이 블루에이에 들어갔다면 시간이 충분하다는 말이므로 시간을 더 줄여본다. (Right = mid) (블루레이의 크기가 최소가 되어야 하므로) ```cpp int left = 0, right = Max*n; while(left < right){ int blue = m; int mid = (left + right) / 2; int s=0; int ss = sum; bool flag = true; for(int i=0; i<arr.size(); i++){ if(arr[i] > mid){ flag = false; } if(s + arr[i] > mid){ blue--; if(blue == 0){ break; } s = arr[i]; ss -= arr[i]; } else{ s += arr[i]; ss -= arr[i]; } } if(ss != 0 || !flag){ left = mid + 1; } else{ right = mid; } } ``` ### 틀렸습니다. 만약 레슨의 길이가 시간(mid)보다 길면 어떤 블루레이에도 들어갈 수 없으므로 시간을 늘려야 하는데 이 부분을 빼먹었다. ## 1389. 케빈 베이컨의 6단계 법칙 가장 기본적인 플로이드-와샬 문제 우선 배열을 최대 값으로 모두 초기화를 시킨 다음에 i노드와 j노드 사이의 거리와 i-k, k-j 사이의 거리 중 더 짧은 거리를 배열 arr[i][j]에 넣어준다. 이렇게 해서 각 노드의 케빈 베이컨 수를 구해서 가장 작은 사람을 출력한다. ```cpp for(int k=1; k<=n; k++){ for(int i=1; i<=n; i++){ for(int j=1; j<=n; j++){ if(i == j || i == k || j == k){ continue; } if(arr[i][j] > arr[i][k] + arr[k][j]){ arr[i][j] = arr[i][k] + arr[k][j]; } } } } ```
Java
UTF-8
2,226
3.4375
3
[]
no_license
import java.util.Scanner; /* Sample Input : 2 3 <-no of bags 3 <- max capacity (weight) 1 2 3 <-weights 2 4 8 <-values 4 8 2 4 5 7 4 9 7 5 Sample output : 8 13 */ public class Knapsack { public static void main(String args[]) throws Exception { //System.out.println(getCommon("ADDA","BDAA")); Scanner in = new Scanner(System.in); int T = in.nextInt(); for (int i = 0 ;i < T; i++) { int N = in.nextInt(); int maxCapacity = in.nextInt(); int[] values = new int[N]; int[] weight = new int[N]; for (int j = 0; j < N; j++) { weight[j] = in.nextInt(); } for (int j = 0; j < N; j++) { values[j] = in.nextInt(); } //System.out.println(knapSack(maxCapacity, weight, values, N)); System.out.println(knapsackRecursive(maxCapacity, weight, values, N)); } } static int max(int a, int b) { return (a > b) ? a : b; } // Returns the maximum value that can // be put in a knapsack of capacity W static int knapSack(int W, int wt[], int val[], int n) { int i, w; int K[][] = new int[n + 1][W + 1]; // Build table K[][] in bottom up manner for (i = 0; i <= n; i++) { for (w = 0; w <= W; w++) { if (i == 0 || w == 0) K[i][w] = 0; else if (wt[i - 1] <= w) K[i][w] = max( val[i - 1] + K[i - 1][w - wt[i - 1]], K[i - 1][w]); else K[i][w] = K[i - 1][w]; } } return K[n][W]; } public static int knapsackRecursive(int W, int[] wt, int[] val, int n) { if(n==0) return 0; if(wt[n-1]<=W) { return Math.max(val[n-1]+knapsackRecursive(W-wt[n-1],wt,val,n-1), knapsackRecursive(W,wt,val,n-1)); } else return knapsackRecursive(W,wt,val,n-1); } }
Markdown
UTF-8
7,321
2.5625
3
[]
no_license
<ul id="nav"> <li class="nav_element" id="nav_Dom"> <a href="/Dom%26%23367%3B.htm" class="menu">Dom&#367;</a></li> <li class="nav_element" id="nav_Manipultorznakyobrana"> <a href="/Manipul%E1tor-_-znaky%2C-obrana%2C-.--.--.-.htm" class="menu">Manipul&#225;tor - znaky, obrana,...</a></li> <li class="nav_element" id="nav_Jakpoznatmanipultora"> <a href="/Jak-poznat-manipul%E1tora-f-.htm" class="menu">Jak poznat manipul&#225;tora?</a></li> <li class="nav_element" id="nav_Kdomanipuluje"> <a href="/Kdo-manipuluje.htm" class="menu">Kdo manipuluje</a></li> <li class="nav_element" id="nav_Manipulacejenefrovzpsobchovnajednn"> <a href="/Manipulace-je-nef-e2-rov%FD-zp%26%23367%3Bsob-chov%E1n%ED-a-jedn%E1n%ED.htm" class="menu">Manipulace je nef&#233;rov&#253; zp&#367;sob chov&#225;n&#237; a jedn&#225;n&#237;</a></li> <li class="nav_element" id="nav_Manipulanmanvry"> <a href="/Manipula%26%23269%3Bn%ED-man-e2-vry.htm" class="menu">Manipula&#269;n&#237; man&#233;vry</a></li> <li class="nav_element" id="nav_Blokada"> <a href="/Blokada.htm" class="menu">Blokada</a></li> <li class="nav_element" id="nav_Obrana"> <a href="/Obrana.htm" class="menu">Obrana</a></li> <li class="nav_element" id="nav_Asertivita"> <a href="/Asertivita.htm" class="menu">Asertivita</a></li> <li class="nav_element" id="nav_Manipulacevlsce"> <a href="/Manipulace-v-l%E1sce.htm" class="menu">Manipulace v l&#225;sce</a></li> <li class="nav_element" id="nav_Manipulacevenickmprojevu"> <a href="/Manipulace-v-%26%23345%3Be%26%23269%3Bnick-e2-m-projevu.htm" class="menu">Manipulace v &#345;e&#269;nick&#233;m projevu</a></li> <li class="nav_element" id="nav_Manipulacezwebu"> <a href="/Manipulace-_-z-webu.htm" class="menu">Manipulace - z webu</a></li> <li class="nav_element" id="nav_Manipulaceknihy"> <a href="/Manipulace-_-knihy.htm" class="menu">Manipulace - knihy</a></li> <li class="nav_element" id="nav_Manipulacetokstup"> <a href="/Manipulace-_-%FAtok%2C-%FAstup.htm" class="menu">Manipulace - &#250;tok, &#250;stup</a></li> <li class="nav_element" id="nav_Rozhovor"> <a href="/Rozhovor.htm" class="menu">Rozhovor</a></li> <li class="nav_element checked_menu" id="nav_Spojky"> <a href="/Spojky.htm" class="menu">Spojky</a></li> <li class="nav_element" id="nav_Ostatn"> <a href="/Ostatn%ED.htm" class="menu">Ostatn&#237;</a></li> <li class="nav_element" id="nav_Kontakt"> <a href="/Kontakt.htm" class="menu">Kontakt</a></li> <li class="nav_element" id="nav_Admin"> <a href="/Admin.htm" class="menu">Admin</a></li> </ul> </div> <div id="content_container"> <div id="pre_content"></div> <div id="content"> <h2 id="title"><span>Spojky</span></h2> <br /> <p> Verbální komunikace je pouhých 10% celé komunikace. V&#283;t&#353;ina je neverbální ( Intonace, gesta, oble&#269;ení,.. ). Nezajímá násco &#345;íká &#269;lov&#283;k, který nám není sympatický. </p> <p> <a href="https://www.youtube.com/watch?v=Dv4IChzSdAo" class="urlextern" target="_blank" title="https://www.youtube.com/watch?v=Dv4IChzSdAo" rel="nofollow">Mít vliv - Jak ovládat lidskou pozornost?</a> </p> <p> <strong>komunikace,v&#283;ta</strong> - vytvá&#345;í mentální obraz a spojkami v&#283;tám dáváme r&#367;znou hodnotu </p> <p> <em class="u">Spojky:</em> </p> <p> <strong>ale</strong> - zd&#367;razní v&#283;tu po ale &#8594; (pop&#345;e, vynuluje p&#345;edchozí v&#283;tu) /neg.,ale poz./ </p> <p> <em>Cítím, &#382;e jste roz&#269;ílený, ale v&#283;&#345;ím, &#382;e Vás to brzy p&#345;ejde.</em> </p> <p> <strong>p&#345;esto&#382;e</strong> - zd&#367;razní v&#283;tu p&#345;ed p&#345;esto&#382;e &#8592; (pop&#345;e, vynuluje následující v&#283;tu) /poz., p&#345;esto&#382;e neg./ </p> <p> <em>Jste vnímavý &#269;lov&#283;k, p&#345;esto&#382;e jste te&#271; roz&#269;ílený.</em> </p> <p> <strong>pokud</strong> - /motivující,pokud demotivující / </p> <p> <em>Doká&#382;ete v&#353;e co si p&#345;edstavíte, pokud budete.</em> </p> <p> &#8212; </p> <p> <strong>a</strong> - (ob&#283;ma v&#283;tám dává stejnou intenzitu) /shodné významy v&#283;t/ </p> <p> <strong>jestli&#382;e</strong> - men&#353;í vliv ne&#382; spojka pokud /jesli&#382;e demotivující, motivující / </p> <p> <a href="https://www.youtube.com/watch?v=vGPRRnEzl5c" class="urlextern" target="_blank" title="https://www.youtube.com/watch?v=vGPRRnEzl5c" rel="nofollow">Protiútok - p&#345;i urá&#382;kách</a> </p> <p> kopírujeme vzor, jen obm&#283;&#328;ujeme slova ( &#382;ena na mu&#382;, &#269;erná na bílá,&#8230;) </p> <p> <a href="https://www.youtube.com/watch?v=w4utjkipwC4" class="urlextern" target="_blank" title="https://www.youtube.com/watch?v=w4utjkipwC4" rel="nofollow">Jak pohotov&#283; reagovat</a> </p> <p> kdykoliv m&#367;&#382;eme pou&#382;ít sáhnout do mém výb&#283;ru p&#345;ep&#345;ipravených, nau&#269;ených v&#283;t p&#345;íkladn&#283; </p> <p> - kdybych cht&#283;l znát Vá&#353; názor, &#345;eknu si o n&#283;j - já se Vám jen p&#345;izp&#367;sobuji, jste m&#367;j vzor - to je pro moji kulatou hlavu moc hranaté </p> <p> (pokud p&#345;emý&#353;líme nad rutinními v&#283;cmi, vznikne chaos; ve stresu a v nap&#283;tí moc nep&#345;emý&#353;líme, jsme kreativní kdy&#382; jsme v pohod&#283;; &#345;e&#353;ení - vytvo&#345;it si pohodové rutiny) </p> <p> <a href="https://www.youtube.com/watch?v=I8NE7cdMr88" class="urlextern" target="_blank" title="https://www.youtube.com/watch?v=I8NE7cdMr88" rel="nofollow">Jak vtipn&#283; reagovat</a> </p> <p> smích je pojítko, z trapného d&#283;lá snesitelné </p> <p> - vytvá&#345;íme o&#269;ekávání a ty pak zbo&#345;íme ( reagovat tak jak lidé </p> <p> neo&#269;ekávají ) </p> <p> - m&#367;&#382;eme pou&#382;ít kdy&#382; druhou stranu nechápeme, m&#367;&#382;eme si s tím </p> <p> hrát (význam slova p&#345;eto&#269;it, slova mají více význam&#367; - ud&#283;lat </p> <p> si seznam) </p> <p> - v&#353;ímat si neutrálních a podstatných jmen jaký mají </p> <p> vlastnosti a jaký mají významy </p> <p> (tob&#283; snad vyoperovali mozek,pro&#269; pot&#345;ebuje&#353; n&#283;jakej; ty má&#353; </p> <p> mozek na m&#283;ko, zato ty jse&#353; p&#283;kn&#283; natvrdlej; ty se&#353; idiot, za </p> <p> to tys to nedotáh ani na polovi&#269;ního; ty se&#353; ale p&#283;knej v&#367;l, </p> <p> to myslí&#353; &#382;e to tady táhnu; ty se&#353; nejv&#283;t&#353;i idiot kerýho znám, </p> <p> a kolik jich zná&#353;) </p> <p> <a href="https://www.youtube.com/watch?v=lpm82HS2EJg" class="urlextern" target="_blank" title="https://www.youtube.com/watch?v=lpm82HS2EJg" rel="nofollow">Co d&#283;lá &#382;eny neatraktivní?</a> </p> <p> - tvá&#345; buldoka, p&#345;ehlídka ná&#345;k&#367;, p&#345;í&#269;ina je potla&#269;ování </p> <p> radosti a vzteku </p> <p> <a href="https://www.youtube.com/watch?v=43pR-vHneA8" class="urlextern" target="_blank" title="https://www.youtube.com/watch?v=43pR-vHneA8" rel="nofollow">Jak být opravdu p&#345;ita&#382;livý</a> </p> <p> - bojíme se toho co bychom v&#353;echno mohli dokázat, d&#283;ti dávají </p> <p> na jevo co cht&#283;jí, jsme schopni se u&#269;it, okolí na nás &#353;pínu </p> <p> hází, ale uvnit&#345; jsme diamanty, jsme ta nejlep&#353;í v&#283;c </p><br /><br /><br /><hr>
PHP
UTF-8
5,521
2.90625
3
[ "MIT" ]
permissive
<?php namespace Wn\GitSplitter; /** * The entry point * * @param array $config * @param array $args * @return void */ function run($config, $args) { echo shell_exec(handle($config, $args)); } /** * generates the shell code to be executed according to given arguments. * * @param array $config * @param array $args * @return string */ function handle($config, $args) { if (count($args) < 2 || !in_array($args[0], ['add', 'checkout', 'commit', 'pull', 'push', 'tag', 'merge'])) { // Forward to git return call('git', $args); } $cmd = $args[0]; array_shift($args); switch ($cmd) { case 'add': return git_add($config, $args); case 'checkout': return git_checkout($config, $args); case 'commit': return git_commit($config, $args); case 'pull': return git_pull($config, $args); case 'push': return git_push($config, $args); case 'tag': return git_tag($config, $args); case 'merge': return git_merge($config, $args); default: return error("Something went really wrong !"); // should never happen ! } } /** * generates the shell code corresponding to running `git add` on the parent repo. * * @param array $config * @param array $args * @return string */ function git_add($config, $args) { if (count($args) < 1) return 'git add'; $flags = array_filter($args, function($arg) { return '-' == substr($arg, 0, 1); }); $args = array_filter($args, function($arg) { return '-' != substr($arg, 0, 1); }); $args = array_map('Wn\\GitSplitter\\normalize_path', $args); $commands = [ call('git add', array_merge($args, $flags))]; foreach (splits_paths($config) as $splitPath) { $splitPath = normalize_path($splitPath); $innerPaths = paths_inside($splitPath, $args); if (count($innerPaths) > 0) { $commands[] = call('cd', [$splitPath]); $commands[] = call('git add', array_merge($innerPaths, $flags)); $commands[] = call('cd', [back_path($splitPath)]); } } return implode(' && ', $commands); } function git_checkout($args) { return error("Not implemented yet!"); } function git_commit($args) { return error("Not implemented yet!"); } function git_pull($args) { return error("Not implemented yet!"); } function git_push($args) { return error("Not implemented yet!"); } function git_tag($args) { return error("Not implemented yet!"); } function git_merge($args) { return error("Not implemented yet!"); } /** * generates a shell code corresponding to an error. * * @param string $msg * @return string */ function error($msg) { return "echo \"Error: {$msg}\""; } /** * generates the shell code corresponding to the call of $command with $args. * * @param string $command * @param array $args * @return string */ function call($command, $args = []) { return $command . ' ' . join_args($args); } /** * Returns the splits paths from the configuration array. * * @param array $config * @return array */ function splits_paths($config) { if (!isset($config['splits'])) return []; return array_keys($config['splits']); } /** * Gets the path to go back from the given one. * * @param string $path * @return string */ function back_path($path) { $level = path_level($path); if ($level < 0) { throw new \InvalidArgumentException("Error: {$path} is outside the repository !"); } return (0 == $level) ? '.' : str_repeat('../', $level); } /** * Returns the level of a relative path. * ```php * path_level('aa/bb/'); //=> 2 * path_level('aa'); //=> 1 * path_level('../..'); //=> -2 * path_level('.'); //=> 0 * path_level('../aa/bb'); //=> 1 * path_level('../aa/bb/../cc'); //=> 1 * ``` * * @param string $path * @return int */ function path_level($path) { $path = rtrim($path, '/'); $level = 0; foreach (explode('/', $path) as $dir) { if ($dir == '..') { $level --; } else if ($dir != '.') { $level ++; } } return $level; } /** * Gets the intersection of $subPath with the given $paths. * * @param string $subPath * @param array $paths * @return array */ function paths_inside($subPath, $paths) { $subLevel = path_level($subPath); $subPathLength = strlen($subPath); $result = []; foreach ($paths as $path) { $pathLength = strlen($path); $pathLevel = path_level($path); if ($path == $subPath || ( $pathLevel < $subLevel && $pathLength < $subPathLength && '/' == $subPath[$pathLength] && substr($subPath, 0, $pathLength) == $path )) { return ['.']; } if(substr($path, 0, $subPathLength) == $subPath && '/' == $path[$subPathLength]) { $result[] = '.' . substr($path, $subPathLength); } } return $result; } /** * Construct command line arguments string from an array. * * @param array $args * @return string */ function join_args($args) { return implode(' ', array_map(function($arg) { return '"' . str_replace('"', '\"', $arg) . '"'; }, $args)); } /** * Normalizes a relative path. * * @param string $path * @return string */ function normalize_path($path) { if($path == '.') { return $path; } if ('./' != substr($path, 0, 2)) $path = './' . $path; return rtrim($path, '/'); }
Markdown
UTF-8
4,822
2.890625
3
[ "BSD-2-Clause" ]
permissive
# Nginx Html Head Filter A Simple Nginx Response Body Filter Module ## Introduction The repository contains an Nginx Resonse Body Filter Module that will filter a HTTP response and insert a specific text string after the html &lt;head&gt; tag. For example, it can insert a monitoring javascript after the &lt;head&gt; tag. The filter module can be used together with Nginx proxy_pass, to insert text string into HTTP responses from an upstream web server. The module will process HTTP 200 OK responses where the content type is text/html. If the content from the upstream server is compressed (gzip, deflate etc...), it will not be modified. The &lt;head&gt; tag must appear within the first 256 characters of the HTTP response, otherwise the response will not be modified. Refer to the Further Details below for more information on how the module is implemented and how it can be used. ## Module Directives The module takes a single directive that can be configured in the Nginx 's location context. **html_head_filter** * syntax: html_head_filter [text string] * default: none * context: Location This directive enables the html head filter module. The argument "text string" will be inserted after the first &lt;head&gt; tag in the HTTP response body. If the &lt;head&gt; tag is not found, the module will log an alert message in the nginx error log. ## Example Configuration An example showing the insertion of a mymonitor1.js script after the &lt;head&gt; tag of html content. In this case, nginx is configured as a reverse proxy to a backend service running on localhost at port 8080. location / { index index.html index.htm; proxy_set_header HOST $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://127.0.0.1:8080; html_head_filter "<script src=\"mymonitor1.js\"></script>"; } ## Compiling and Installation The module works with the latest stable version of [Nginx 1.18.0](https://nginx.org/download/). Download the latest stable version of Nginx and its corresponding pgp signature. Verify the signature of the downloaded tarball. Refer to [Nginx website](https://nginx.org/en/pgp_keys.html) for the public signing keys that can be used to verify the signature. Extract the nginx source tarball if the signature verification is ok. To obtain a copy of the Filter Module. git clone https://github.com/ngchianglin/NginxHtmlHeadFilter.git Refer to the Source signature section below for instructions on verifying the module 's signature. To compile the module statically into nginx. The following configure option can be used. --add-module=<Path to>/NginxHtmlHeadFilter For example, the following commands can be used to compile the module and install nginx into **/usr/local/nginx** Note: These example commands do not include signature verification of the downloaded packages. For security, do verify the signatures of the downloads. git clone https://github.com/ngchianglin/NginxHtmlHeadFilter.git wget https://nginx.org/download/nginx-1.18.0.tar.gz tar -zxvf nginx-1.18.0.tar.gz cd nginx-1.18.0 ./configure --with-cc-opt="-Wextra -Wformat -Wformat-security -Wformat-y2k -fPIE -O2 -D_FORTIFY_SOURCE=2 -fstack-protector-all" --with-ld-opt="-pie -Wl,-z,relro -Wl,-z,now -Wl,--strip-all" --add-module=../NginxHtmlHeadFilter make sudo make install ## Further Details Please note that there is a customized version of the module that displays a blank page if the &lt;head> tag is not found. The customized version is available at [https://github.com/ngchianglin/NginxHtmlHeadBlankFilter](https://github.com/ngchianglin/NginxHtmlHeadBlankFilter) Displaying an empty page can be a useful security feature if it is mandatory that a specific monitoring script must be present on all the html pages of a website. The customized module should not be installed together with this version on the same instance of nginx. Refer to [https://www.nighthour.sg/articles/2017/writing-an-nginx-response-body-filter-module.html](https://www.nighthour.sg/articles/2017/writing-an-nginx-response-body-filter-module.html) for an in-depth article on how this module is implemented and how it can be used. ## Source signature Gpg Signed commits are used for committing the source files. > Look at the repository commits tab for the verified label for each commit, or refer to [https://www.nighthour.sg/git-gpg.html](https://www.nighthour.sg/git-gpg.html) for instructions on verifying the git commit. > A userful link on how to verify gpg signature [https://github.com/blog/2144-gpg-signature-verification](https://github.com/blog/2144-gpg-signature-verification)
Python
UTF-8
7,444
2.890625
3
[ "MIT" ]
permissive
''' Class BLayerNormalizedLSTMCell: Two parallele Layer Norm LSTM cell blocks that share the same weights for each channel Class LayerNormalizedLSTMCell: adapted from BasicLSTMCell to use Layer Norm ''' import numpy as np import tensorflow as tf import ipdb from tensorflow.python.util import nest from tensorflow.python.ops import variable_scope as vs from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import nn_ops def _blinear(args, args2, output_size, bias, bias_start=0.0): '''Apply _linear ops to the two parallele layers with same wights''' if args is None or (nest.is_sequence(args) and not args): raise ValueError("`args` must be specified") if not nest.is_sequence(args): args = [args] total_arg_size = 0 shapes = [a.get_shape() for a in args] for shape in shapes: if shape.ndims != 2: raise ValueError("linear is expecting 2D arguments: %s" % shapes) if shape[1].value is None: raise ValueError( "linear expects shape[1] to be provided for shape %s, " "but saw %s" % (shape, shape[1])) else: total_arg_size += shape[1].value dtype = [a.dtype for a in args][0] # Now the computation. scope = vs.get_variable_scope() with vs.variable_scope(scope) as outer_scope: weights = vs.get_variable( 'weight', [total_arg_size, output_size / 2], dtype=dtype) # apply weights if len(args) == 1: res = math_ops.matmul(args[0], weights) res2 = math_ops.matmul(args2[0], weights) else: # ipdb.set_trace() res = math_ops.matmul(array_ops.concat(1, args), weights) res2 = math_ops.matmul(array_ops.concat(1, args2), weights) if not bias: return res, res2 # apply bias with vs.variable_scope(outer_scope) as inner_scope: inner_scope.set_partitioner(None) biases = vs.get_variable( 'bias', [output_size] / 2, dtype=dtype, initializer=init_ops.constant_initializer( bias_start, dtype=dtype)) return nn_ops.bias_add(res, biases), nn_ops.bias_add(res2, biases) def ln(tensor, scope=None, epsilon=1e-5): """ Layer normalizes a 2D tensor along its second axis """ assert(len(tensor.get_shape()) == 2) m, v = tf.nn.moments(tensor, [1], keep_dims=True) if not isinstance(scope, str): scope = '' with tf.variable_scope(scope + 'layer_norm'): scale = tf.get_variable('scale', shape=[tensor.get_shape()[1]], initializer=tf.constant_initializer(1)) shift = tf.get_variable('shift', shape=[tensor.get_shape()[1]], initializer=tf.constant_initializer(0)) LN_initial = (tensor - m) / tf.sqrt(v + epsilon) return LN_initial * scale + shift class BLayerNormalizedLSTMCell(tf.nn.rnn_cell.RNNCell): """ Two parallele Layer Norm LSTM cell blocks that share the same weights for each channel """ def __init__(self, num_units, forget_bias=1.0, activation=tf.nn.tanh): self._num_units = num_units self._forget_bias = forget_bias self._activation = activation @property def state_size(self): return tf.nn.rnn_cell.LSTMStateTuple(self._num_units, self._num_units) @property def output_size(self): return self._num_units def __call__(self, inputs, state, scope=None): '''Add layer norm to the two channels''' with tf.variable_scope(scope or type(self).__name__): c, h = state n_length = c.get_shape()[1] i_length = inputs.get_shape()[1] # import ipdb; ipdb.set_trace() c1 = c[:, 0:n_length / 2] c2 = c[:, n_length / 2:n_length] h1 = h[:, 0:n_length / 2] h2 = h[:, n_length / 2:n_length] inputs1 = inputs[:, 0:i_length / 2] inputs2 = inputs[:, i_length / 2:i_length] # change bias argument to False since LN will add bias via shift concat1, concat2 = _blinear( [inputs1, h1], [inputs2, h2], 4 * self._num_units, False) i1, j1, f1, o1 = tf.split(1, 4, concat1) i2, j2, f2, o2 = tf.split(1, 4, concat2) # add layer normalization to each gate with tf.variable_scope('l1') as scope: i1 = ln(i1, scope='i/') j1 = ln(j1, scope='j/') f1 = ln(f1, scope='f/') o1 = ln(o1, scope='o/') # ipdb.set_trace() new_c1 = (c1 * tf.nn.sigmoid(f1 + self._forget_bias) + tf.nn.sigmoid(i1) * self._activation(j1)) new_h1 = self._activation( ln(new_c1, scope='new_h/')) * tf.nn.sigmoid(o1) with tf.variable_scope('l2') as scope: i2 = ln(i2, scope='i/') j2 = ln(j2, scope='j/') f2 = ln(f2, scope='f/') o2 = ln(o2, scope='o/') new_c2 = (c2 * tf.nn.sigmoid(f2 + self._forget_bias) + tf.nn.sigmoid(i2) * self._activation(j2)) new_h2 = self._activation( ln(new_c2, scope='new_h/')) * tf.nn.sigmoid(o2) # add layer_normalization in calculation of new hidden state new_c = tf.concat(1, (new_c1, new_c2)) new_h = tf.concat(1, (new_h1, new_h2)) new_state = tf.nn.rnn_cell.LSTMStateTuple(new_c, new_h) return new_h, new_state class LayerNormalizedLSTMCell(tf.nn.rnn_cell.RNNCell): """ Adapted from TF's BasicLSTMCell to use Layer Normalization. Note that state_is_tuple is always True. """ def __init__(self, num_units, forget_bias=1.0, activation=tf.nn.tanh): self._num_units = num_units self._forget_bias = forget_bias self._activation = activation @property def state_size(self): return tf.nn.rnn_cell.LSTMStateTuple(self._num_units, self._num_units) @property def output_size(self): return self._num_units def __call__(self, inputs, state, scope=None): """Long short-term memory cell (LSTM).""" with tf.variable_scope(scope or type(self).__name__): c, h = state # change bias argument to False since LN will add bias via shift concat = tf.nn.rnn_cell._linear( [inputs, h], 4 * self._num_units, False) # ipdb.set_trace() i, j, f, o = tf.split(1, 4, concat) # add layer normalization to each gate i = ln(i, scope='i/') j = ln(j, scope='j/') f = ln(f, scope='f/') o = ln(o, scope='o/') new_c = (c * tf.nn.sigmoid(f + self._forget_bias) + tf.nn.sigmoid(i) * self._activation(j)) # add layer_normalization in calculation of new hidden state new_h = self._activation( ln(new_c, scope='new_h/')) * tf.nn.sigmoid(o) new_state = tf.nn.rnn_cell.LSTMStateTuple(new_c, new_h) return new_h, new_state
C++
UTF-8
3,453
3.53125
4
[]
no_license
//QCMs grid demo example for SFML & replit #include <SFML/Graphics.hpp> #include <cstdlib> // For rand() and srand() #include <ctime> // For time() #include <chrono> // For std::chrono #include <thread> // For std::this_thread::sleep_for int main() { // Seed the random number generator std::srand(static_cast<unsigned int>(std::time(nullptr))); // Timer for updating colors std::chrono::time_point<std::chrono::system_clock> lastUpdateTime = std::chrono::system_clock::now(); // Create the window sf::RenderWindow window(sf::VideoMode(800, 800), "QCMs SFML Grid Demo"); // Sleep duration for the logic loop int sleepDuration = 100; // Set the desired sleep duration in milliseconds // Define the size of the grid const int gridSize = 16; // Calculate the size of each grid cell const int cellSize = window.getSize().x / gridSize; // Create a 2D array to hold the colors for each grid cell sf::Color gridColors[gridSize][gridSize]; // Randomly fill each grid cell with a random color for (int row = 0; row < gridSize; ++row) { for (int col = 0; col < gridSize; ++col) { // Generate a random color sf::Uint8 red = std::rand() % 256; sf::Uint8 green = std::rand() % 256; sf::Uint8 blue = std::rand() % 256; gridColors[row][col] = sf::Color(red, green, blue); } } // Main Logic loop while (window.isOpen()) { // Process events sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) window.close(); } // Check if it's time to update a block auto currentTime = std::chrono::system_clock::now(); std::chrono::duration<double> elapsedSeconds = currentTime - lastUpdateTime; if (elapsedSeconds.count() >= sleepDuration / 1000.0) // Use the defined sleep duration variable { // Update a random block with a random color int row = std::rand() % gridSize; int col = std::rand() % gridSize; sf::Uint8 red = std::rand() % 256; sf::Uint8 green = std::rand() % 256; sf::Uint8 blue = std::rand() % 256; gridColors[row][col] = sf::Color(red, green, blue); // Update the last update time lastUpdateTime = currentTime; } else { // Sleep to reduce CPU usage std::this_thread::sleep_for(std::chrono::milliseconds(sleepDuration)); // Use the defined sleep duration variable } // Clear the window window.clear(); // Draw the grid with random colors for (int row = 0; row < gridSize; ++row) { for (int col = 0; col < gridSize; ++col) { // Create a rectangle shape for each grid cell sf::RectangleShape cell(sf::Vector2f(cellSize, cellSize)); // Set the position of the cell based on the row and column cell.setPosition(col * cellSize, row * cellSize); // Set the color of the cell based on the random color cell.setFillColor(gridColors[row][col]); // Draw the cell window.draw(cell); } } // Display the window window.display(); } return 0; }
Java
UTF-8
3,097
2.25
2
[ "Apache-2.0" ]
permissive
package com.github.kubenext.uaa.service.mapper; import com.github.kubenext.uaa.domain.Authority; import com.github.kubenext.uaa.domain.User; import com.github.kubenext.uaa.service.dto.CreateUserDTO; import com.github.kubenext.uaa.service.dto.UpdateUserDTO; import com.github.kubenext.uaa.service.dto.UserDTO; import org.mapstruct.*; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * @author lishangjin */ @Mapper(componentModel = "spring") public interface UserMapper { @Mapping(source = "authorities", target = "authorities", qualifiedByName = "formatAuthorityToSet") User toUser(CreateUserDTO createUserDTO); @Mapping(source = "authorities", target = "authorities", qualifiedByName = "formatAuthorityToSet") User toUser(UpdateUserDTO updateUserDTO); /** * User mapping UserDTO * @param user * @return */ @Mapping(source = "authorities", target = "authorities", qualifiedByName = "formatAuthorityToArray") UserDTO toUserDTO(User user); /** * UserDTO mapping User * @param userDTO * @return */ @Mapping(source = "authorities", target = "authorities", qualifiedByName = "formatAuthorityToSet") User toUser(UserDTO userDTO); /** * Users mapping UserDTOs * @param users * @return */ List<UserDTO> toUserDTOs(List<User> users); /** * UserDTOs mapping Users * @param userDTOs * @return */ List<User> toUsers(List<UserDTO> userDTOs); /** * UserDTO update User * @param user * @param userDTO */ @Mapping(source = "authorities", target = "authorities", qualifiedByName = "formatAuthorityToSet") @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) void updateUser(@MappingTarget User user, UserDTO userDTO); @Mapping(source = "authorities", target = "authorities", qualifiedByName = "formatAuthorityToSet") @BeanMapping(nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE) void updateUser(@MappingTarget User user, UpdateUserDTO updateUserDTO); /** * Params Update User * @param user * @param firstName * @param lastName * @param email * @param langKey * @param imageUrl */ void updateUser(@MappingTarget User user, String firstName, String lastName, String email, String langKey, String imageUrl); @Named("formatAuthorityToSet") default Set<Authority> formatAuthorityToSet(String[] source) { if (source == null) { return null; } return Arrays.stream(source).map(authority -> { Authority auth = new Authority(); auth.setName(authority); return auth; }).collect(Collectors.toSet()); } @Named("formatAuthorityToArray") default String[] formatAuthorityToArray(Set<Authority> source) { if (source == null) { return null; } return source.stream().map(Authority::getName).toArray(String[]::new); } }
Markdown
UTF-8
916
2.953125
3
[]
no_license
## G.2 All Our ideas ### ![image alt text](image_0.png) **Figura G.2.0:** Portada de [http://allourideas.org/](http://allourideas.org/) *Cómo funciona una Encuesta Wiki* 1. *Crear: Empieza con una pregunta y unas ideas semilla, y puedes crear una encuesta wiki en un instante.* 2. *Participa: Los participantes que tu invites disfrutaran nuestro proceso simple de votación y creación de nuevas ideas.* 3. *Descubre: Las mejores ideas se engloban usando nuestro sistema que es abierto, transparente y poderoso.* [^1] [^1]: Traducido de http://allourideas.org Texto original: How a Wiki Survey works Create: Start with a question and some seed ideas, and you can create a wiki survey in moments. Participate: The participants you invite will enjoy our simple process of voting and adding new ideas. Discover: The best ideas will bubble to the top using our system that is open, transparent, and powerful.
JavaScript
UTF-8
8,624
2.796875
3
[]
no_license
import { Game } from "../../../src/server/model/game"; import { GameHand } from "../../../src/common/model/game-hand.model"; import { Card } from "../../../src/common/model/card.model"; import { Player } from '../../../src/common/model/player.model'; describe('Game Server Model', () => { let game; let playerDealer; let playerTrump; let player3; let player4; beforeEach(() => { game = new Game('new test game'); playerDealer = new Player('t', 'trump-player-1', true); playerTrump = new Player('t', 'trump-player-1'); player3 = new Player('3', 'test-player-3'); player4 = new Player('4', 'test-player-4'); }); it('should create new game object', () => { game = new Game('new test game'); expect(game).toBeDefined(); }); describe('Set Trump', () => { it('should set trump J-&clubs;', () => { game.addPlayer(playerDealer); game.addPlayer(playerTrump); playerTrump.isActivePlayer = true; const trumpCard = new Card('&clubs;', 'J'); game.setTrump(playerTrump, trumpCard.id); expect(game.trump).toEqual(trumpCard); }) }) describe('Get Winning Hand', () => { describe('when 1 hand is trump', () => { it('should have trump hand1 as winner', () => { game.addPlayer(playerDealer); game.addPlayer(playerTrump); game.addPlayer(player3); game.addPlayer(player4); playerTrump.isActivePlayer = true; game.setTrump(playerTrump, new Card('&hearts;', 'A').id); const card1 = new Card('&hearts;', 'K'); const hand1 = new GameHand(card1, player3); const card2 = new Card('&spades;', 'A'); const hand2 = new GameHand(card2, player4); const winningHand = game.getWinningHand(hand1, hand2, '&diams;'); expect(winningHand).toEqual(hand1); }); it('should have trump hand2 as winner', () => { game.addPlayer(playerDealer); game.addPlayer(playerTrump); game.addPlayer(player3); game.addPlayer(player4); playerTrump.isActivePlayer = true; game.setTrump(playerTrump, new Card('&hearts;', 'A').id); const card1 = new Card('&spades;', 'A'); const hand1 = new GameHand(card1, player3); const card2 = new Card('&hearts;', 'K'); const hand2 = new GameHand(card2, player4); const winningHand = game.getWinningHand(hand1, hand2, '&diams;'); expect(winningHand).toEqual(hand2); }); }); describe('when both hands are trump', () => { it('should have hand1 as winner', () => { game.addPlayer(playerDealer); game.addPlayer(playerTrump); game.addPlayer(player3); game.addPlayer(player4); playerTrump.isActivePlayer = true; game.setTrump(playerTrump, new Card('&hearts;', 'A').id); const card1 = new Card('&hearts;', 'J'); const hand1 = new GameHand(card1, player3); const card2 = new Card('&hearts;', 'A'); const hand2 = new GameHand(card2, player4); const winningHand = game.getWinningHand(hand1, hand2, '&diams;'); expect(winningHand).toEqual(hand1); }); it('should have hand2 as winner', () => { game.addPlayer(playerDealer); game.addPlayer(playerTrump); game.addPlayer(player3); game.addPlayer(player4); playerTrump.isActivePlayer = true; game.setTrump(playerTrump, new Card('&hearts;', 'A').id); const card1 = new Card('&hearts;', 'Q'); const hand1 = new GameHand(card1, player3); const card2 = new Card('&hearts;', 'A'); const hand2 = new GameHand(card2, player4); const winningHand = game.getWinningHand(hand1, hand2, '&diams;'); expect(winningHand).toEqual(hand2); }); }) describe('when both hands are following suit', () => { it('should have hand1 as winner', () => { game.addPlayer(playerDealer); game.addPlayer(playerTrump); game.addPlayer(player3); game.addPlayer(player4); playerTrump.isActivePlayer = true; game.setTrump(playerTrump, new Card('&hearts;', 'A').id); const card1 = new Card('&diams;', 'J'); const hand1 = new GameHand(card1, player3); const card2 = new Card('&diams;', 'A'); const hand2 = new GameHand(card2, player4); const winningHand = game.getWinningHand(hand1, hand2, '&diams;'); expect(winningHand).toEqual(hand1); }); it('should have hand2 as winner', () => { game.addPlayer(playerDealer); game.addPlayer(playerTrump); game.addPlayer(player3); game.addPlayer(player4); playerTrump.isActivePlayer = true; game.setTrump(playerTrump, new Card('&hearts;', 'A').id); const card1 = new Card('&diams;', 'Q'); const hand1 = new GameHand(card1, player3); const card2 = new Card('&diams;', 'A'); const hand2 = new GameHand(card2, player4); const winningHand = game.getWinningHand(hand1, hand2, '&diams;'); expect(winningHand).toEqual(hand2); }); }) describe('when both hands are not following suit', () => { it('should have hand1 as winner', () => { game.addPlayer(playerDealer); game.addPlayer(playerTrump); game.addPlayer(player3); game.addPlayer(player4); playerTrump.isActivePlayer = true; game.setTrump(playerTrump, new Card('&hearts;', 'A').id); const card1 = new Card('&spades;', 'J'); const hand1 = new GameHand(card1, player3); const card2 = new Card('&spades;', 'A'); const hand2 = new GameHand(card2, player4); const winningHand = game.getWinningHand(hand1, hand2, '&diams;'); expect(winningHand).toEqual(hand1); }); it('should have hand2 as winner', () => { game.addPlayer(playerDealer); game.addPlayer(playerTrump); game.addPlayer(player3); game.addPlayer(player4); playerTrump.isActivePlayer = true; game.setTrump(playerTrump, new Card('&hearts;', 'A').id); const card1 = new Card('&spades;', 'Q'); const hand1 = new GameHand(card1, player3); const card2 = new Card('&spades;', 'A'); const hand2 = new GameHand(card2, player4); const winningHand = game.getWinningHand(hand1, hand2, '&diams;'); expect(winningHand).toEqual(hand2); }); }) describe('when 1 hand is following suit', () => { it('should have hand1 as winner', () => { game.addPlayer(playerDealer); game.addPlayer(playerTrump); game.addPlayer(player3); game.addPlayer(player4); playerTrump.isActivePlayer = true; game.setTrump(playerTrump, new Card('&hearts;', 'A').id); const card1 = new Card('&diams;', 'K'); const hand1 = new GameHand(card1, player3); const card2 = new Card('&spades;', 'A'); const hand2 = new GameHand(card2, player4); const winningHand = game.getWinningHand(hand1, hand2, '&diams;'); expect(winningHand).toEqual(hand1); }); it('should have hand2 as winner', () => { game.addPlayer(playerDealer); game.addPlayer(playerTrump); game.addPlayer(player3); game.addPlayer(player4); playerTrump.isActivePlayer = true; game.setTrump(playerTrump, new Card('&hearts;', 'A').id); const card1 = new Card('&spades;', 'J'); const hand1 = new GameHand(card1, player3); const card2 = new Card('&diams;', 'A'); const hand2 = new GameHand(card2, player4); const winningHand = game.getWinningHand(hand1, hand2, '&diams;'); expect(winningHand).toEqual(hand2); }); }) }) });
JavaScript
UTF-8
1,749
2.953125
3
[ "MIT" ]
permissive
let buttonUserName = document.getElementById('id-button-username') let userName = document.getElementById('userName') let repeatUserName = document.getElementById('repeatUserName') let oldPasswordUserName = document.getElementById('oldPasswordUserName') let errorNewUserName = document.getElementById('errorNewUserName') let errorRepeatUserName = document.getElementById('errorRepeatUserName') let errorPasswordNotFound = document.getElementById('errorPasswordNotFound') let userNameCredential = document.querySelectorAll('.user_name_credential') buttonUserName.addEventListener('click', checkUserName) function checkUserName() { if(repeatUserName.value!="" && userName.value!="") { if(userName.value!=repeatUserName.value) { errorNewUserName.innerText='' errorRepeatUserName.innerText='Repita correctamente su nuevo usuario' errorPasswordNotFound.innerText='' } else { errorRepeatUserName.innerText='' if(oldPasswordUserName.value!="") { errorPasswordNotFound.innerText='' changeUserName() } else { errorNewUserName.innerText='' errorRepeatUserName.innerText='' errorPasswordNotFound.innerText='El campo no debe estar vacio' } } } } function changeUserName() { let formData = new FormData() formData.append("userName",userName.value) formData.append("oldPasswordUserName",oldPasswordUserName.value) fetch(`/api/user/updateUserName`, { method : 'POST', body : formData }).then(response => response.json()) .catch(error => console.error('Error: '+error)) .then(response => { userName.value='' repeatUserName.value='' oldPasswordUserName.value='' errorNewUserName.innerText='' errorRepeatUserName.innerText='' errorPasswordNotFound.innerText='' alert(response.message) }) }
Markdown
UTF-8
7,959
3.375
3
[]
no_license
--- id: 1799 title: Writing unit test for Android with Easymock date: 2013-11-07T00:44:53+00:00 author: adrian.ancona layout: post guid: http://ncona.com/?p=1799 permalink: /2013/11/writing-unit-test-for-android-with-easymock/ tags: - android - java - mobile - programming - testing --- I already wrote a post about [how to create a test suite for Android](http://ncona.com/2013/09/unit-testing-android-apps/ "Unit testing Android Apps"), but while trying more complex tests I noticed that a lot of things are not as easy as I would have expected. Unit testing Java is different that unit testing JavaScript, but unit testing Android is even a little harder. The problem with Android is that a lot of things depend on the Activity life cycle and most of the methods have been made final so they are impossible to mock. ## Alternatives Easymock wasn&#8217;t my first alternative. My first choice was Robolectric because I heard a lot of people say good things about it, the problem is that it has very little documentation and most of it is specific for eclipse. They also have a sample project but I wasn&#8217;t able to make it work. I also tried Mockito but I wasn&#8217;t able to make it work with my project. The reason I chose Easymock is because it was really easy to make it work and it seems to have a lot of support and documentation. <!--more--> ## Installing Easymock From now on I&#8217;m going to assume that you have a project set up as I explain on [unit testing Android apps](http://ncona.com/2013/09/unit-testing-android-apps/ "Unit testing Android Apps"). The first step is to get EasyMock. You can get the latest version from [Easymock&#8217;s download page](http://easymock.org/Downloads.html "Easymock downloads"). Choose the latest version and you will get a zip file. You only need easymock-3.2.jar (3.2 will change depending on the version you choose). You will also need dexmaker for Easymock to work on Android. You can get the jar from [Dexmaker&#8217;s website](http://code.google.com/p/dexmaker/downloads/list "Dexmaker homepage"). Once you have both jar files put them in <project_path>/tests/libs. Now you have EasyMock available in your tests. ## Mocking stuff It is time to use this new library that we just installed. One thing to have in mind when using EasyMock is that it is not possible to mock private or final methods so you might want to change your methods to protected if possible. Lets look at an example of a test for a custom view: ```java // Some other imports go in here import static org.easymock.EasyMock.*; public class SomeViewTest extends AndroidTestCase { public void testSomeFunction() { // Create a mock of SomeView class // Since this is a custom view the constructor needs the // context as an argument. Since this is an AndroidTestCase // we can use getContext() to get a mock context and pass // it to the constructor // When using createMockBuilder all methods for the class // you are mocking will remain with the same functionality // except for the ones you specify with addMockedMethod. // Finally we need to call createMock() to get the mock. SomeView sv = createMockBuilder(SomeView.class) .withConstructor(getContext()) .addMockedMethod("someOtherFunction") .createMock(); // By default when using createMock() your test will // fail if a mocked method is called unless you set // expectations for the call. If you want a different // behavior you can use createNiceMock(). // This expects someOtherFunction to be called once // with 3 as an argument and it will return 300 expect(sv.someOtherFunction(3)).andReturn(300); // This tells EasyMock that you are done setting // expectations and that it is ready to replay it replay(sv); // Call the function to test sv.someFunction(); // Verify the expectations verify(sv); } } ``` ## Easymock matchers The previous example shows how to create a mock and set some expectations but there are many times when you want to verify that you are calling a specific functions with some specific arguments. To do this kind of verifications you can use EasyMock matchers. They allow you to expect a function call that with arguments that match different criteria. Here are some examples: ```java // Matches a call with the only argument being the int 3 mock.mockedFunction(3); // Matches any int mock.mockedFunction(anyInt()); // Matches null mock.mockedFunction(isNull()); // Matches an array with the same values as the given array mock.mockedFunction(aryEq(someArray)); ``` One thing to keep in mind is that you can&#8217;t mix matchers and specific values, so this will fail: ```java mock.mockedFunction(3, anyObject()); ``` Instead you can use eq() to convert an specific value to a matcher: ```java mock.mockedFunction(eq(3), anyObject()); ``` Another gotcha is there aren&#8217;t matchers for all possible scenarios that you could imagine. One functionality that I needed was to expect a function to be called with a bi-dimensional array as an argument. None of these work for bi-dimensional arrays: ```java mock.mockedFunction(someBiDimensionalArray); mock.mockedFunction(eq(someBiDimensionalArray)); mock.mockedFunction(aryEq(someBiDimensionalArray)); ``` So I had to create a custom matcher. ## EasyMock custom matchers Creating a custom matcher is not complicated but the documentation wasn&#8217;t completely clear about it. What I did is create a new class for my custom matcher and put it in <project_path>/tests/src/com/domain/project/lib and called it twoDimensionalArrayMatcher.java: ```java import org.easymock.IArgumentMatcher; import java.util.Arrays; import static org.easymock.EasyMock.*; // All custom matchers must implement IArgumentMatcher public class twoDimensionalArrayMatcher implements IArgumentMatcher { private int[][] expected; public twoDimensionalArrayMatcher(int[][] expected) { this.expected = expected; } // This is the actual code that defines if the argument is // a match. If this function returns true it is considered // a match, otherwise it is not a match. public boolean matches(Object actual) { return Arrays.deepEquals(expected, (int[][])actual); } public void appendTo(StringBuffer buffer) { buffer.append("towAryEq failed"); } // This is how you will access this matcher from outside public static int[][] twoAryEq(int[][] in) { reportMatcher(new twoDimensionalArrayMatcher(in)); return null; } } ``` Once you have your custom matcher you can use it as any other matcher: ```java // Some other imports go in here import static org.easymock.EasyMock.*; // Our custom matcher import static com.domain.project.lib.twoDimensionalArrayMatcher.*; public class SomeViewTest extends AndroidTestCase { public void testSomeFunction() { // Some hidden code where we create the mock expect(sv.someOtherFunction(twoAryEq(someBidimensionalArray))); // More hidden code } } ``` ## The ugly part Android has defined a lot of it&#8217;s native functionality as final which makes it impossible to mock. This was a big problem for my view test because I wanted to mock calls to functions like getHeight() so I could specify a mocked screen size. What I ended up doing was creating proxy methods for those functions in my view: ```java protected int getViewWidth() { return getWidth(); } ``` This is not an elegant solution but it was the easiest way I found to mock those calls. In the future I&#8217;ll probably create a TestableView class that extends view so my custom views get those proxy methods automatically. With all this I think I will be able to correctly unit test most of my Android code.
Java
UTF-8
2,070
2.3125
2
[]
no_license
package com.example.sonu.jaquar.Models; import android.content.Context; import android.support.annotation.NonNull; import android.support.constraint.ConstraintLayout; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.RelativeLayout; import com.example.sonu.jaquar.R; public class SliderActivity extends AppCompatActivity { ViewPager viewPager; Adapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_slider); viewPager =findViewById(R.id.viewpager); adapter =new Adapter(getApplicationContext()); viewPager.setAdapter(adapter); } private class Adapter extends PagerAdapter{ Context context; int[] images ={R.drawable.image1,R.drawable.image2,R.drawable.image3}; public Adapter(Context context) { this.context = context; } @Override public int getCount() { return images.length; } @Override public boolean isViewFromObject(@NonNull View view, @NonNull Object object) { return view == ((ConstraintLayout)object); } @NonNull @Override public Object instantiateItem(@NonNull ViewGroup container, int position) { View view = LayoutInflater.from(context).inflate(R.layout.slide,container,false); ImageView imageView =view.findViewById(R.id.slideNewImage); imageView.setImageResource(images[position]); container.addView(imageView); return view; } @Override public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) { container.removeView((ConstraintLayout) object); } } }
Java
UTF-8
1,840
3.09375
3
[]
no_license
package paquete1; public class Estudiante { // 1. Declarar // se declaran datos o atributos con visibilidad protegido // # nombresEstudiante: Cadena protected String nombresEstudiante; // # apellidosEstudiante: Cadena protected String apellidosEstudiante; // # identificacionEstudiante: Cadena protected String identificacionEstudiante; // # edadEstudiante: Entero protected int edadEstudiante; // Métodos establecer y calcular para los datos o atributos de la clase // 2. Método establecerNombresEstudiante(nom: Cadena) public void establecerNombresEstudiante(String nom){ nombresEstudiante = nom.toLowerCase(); } // 3. Método establecerApellidoEstudiante(ape: Cadena) public void establecerApellidoEstudiante(String ape){ apellidosEstudiante = ape; } // 4. Método establecerIdentificacionEstudiante(iden: Cadena) public void establecerIdentificacionEstudiante(String iden){ identificacionEstudiante = iden; } // 5. Método establecerEdadEstudiante(ed: Edad) public void establecerEdadEstudiante(int ed){ edadEstudiante = ed; } // Métodos obtener para los datos o atributos de la clase // 6. Método obtenerNombresEstudiante() : Cadena public String obtenerNombresEstudiante(){ return nombresEstudiante; } //7. Método obtenerApellidoEstudiante() : Cadena public String obtenerApellidoEstudiante(){ return apellidosEstudiante; } // 8. Método obtenerIdentificacionEstudiante() : Cadena public String obtenerIdentificacionEstudiante(){ return identificacionEstudiante; } // 9. Método obtenerEdadEstudiante() : Entero public int obtenerEdadEstudiante(){ return edadEstudiante; } }
C#
UTF-8
4,733
3.34375
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace Euro_diffusion { public static class UI { public static List<string[]> ConsoleReader() { Console.WriteLine($"Enter number of countries from {Constants.MIN_COUNTRY_COUNT} to {Constants.MAX_COUNTRY_COUNT}"); var isNum = int.TryParse(Console.ReadLine(), out int countryNumber); while (!isNum || countryNumber > Constants.MAX_COUNTRY_COUNT || countryNumber < Constants.MIN_COUNTRY_COUNT) { Console.WriteLine($"Number of countries should be integer ana belong between {Constants.MIN_COUNTRY_COUNT} and {Constants.MAX_COUNTRY_COUNT}"); isNum = int.TryParse(Console.ReadLine(), out countryNumber); } Console.WriteLine($"Enter the country description in format 'name xl yl xh yh', where position pointers should be between " + $"{Constants.MIN_POS} and {Constants.MAX_POS}, and display lower left and upper right angles of country"); var countryList = new List<string[]>(); for (int i = 0; i < countryNumber; i++) { string[] countryString = Console.ReadLine().Split(' '); while (!CountryInputParser(countryString)) countryString = Console.ReadLine().Split(' '); countryList.Add(countryString); } return countryList; } public static bool CountryInputParser(string[] str) { if (str.Length != Constants.PARAMETER_COUNT) { Console.WriteLine("Wrong format. Use fomat 'name xl yl xh yh'"); return false; } if (str[0].Length > Constants.MAX_COUNTRY_LENGTH || !Regex.IsMatch(str[0], @"^[a-zA-Z]+$")) { Console.WriteLine($"Country name should be alphabetic and and not exceed {Constants.MAX_COUNTRY_LENGTH} symbols"); return false; } for (int i = 1; i < Constants.PARAMETER_COUNT; i++) if (!int.TryParse(str[i], out int position) || position > Constants.MAX_POS || position < Constants.MIN_POS) { Console.WriteLine($"Position pointers should be integer and belong between {Constants.MIN_POS} and {Constants.MAX_POS}"); return false; } if (int.Parse(str[1]) > int.Parse(str[3]) || int.Parse(str[2]) > int.Parse(str[4])) { Console.WriteLine("Position pointers should display lower left and upper right angles of country"); return false; } return true; } public static List<string> FileReader(string path = "D:\\Studing\\University\\!Магистратура\\Хицко\\Лабы\\Euro Diffusion\\Euro_Diffusion\\Euro_diffusion\\Test_files\\test.txt") { using StreamReader sr = new StreamReader(path, System.Text.Encoding.Default); var buffer = new List<string>(); string line; while ((line = sr.ReadLine()) != null) buffer.Add(line); return buffer; } public static List<List<string[]>> BufferReader(List<string> buffer) { var count = 0; var europeList = new List<List<string[]>>(); while (count < buffer.Count) { var isNum = int.TryParse(buffer[count], out int countryNumber); if (isNum && countryNumber <= Constants.MAX_COUNTRY_COUNT && countryNumber >= Constants.MIN_COUNTRY_COUNT) { var countryList = new List<string[]>(); for (int i = count + 1; i < count + countryNumber + 1; i++) { string[] countryString = buffer[i].Split(' '); if (CountryInputParser(countryString)) countryList.Add(countryString); } count += countryNumber + 1; europeList.Add(countryList); } else count++; } return europeList; } public static int Mode() { Console.WriteLine("Choose test mode (1) or console mode (2)"); var modeString = int.TryParse(Console.ReadLine(), out int mode); while (!modeString || mode < 1 || mode > 2) { modeString = int.TryParse(Console.ReadLine(), out mode); } return mode; } } }
Python
UTF-8
2,028
4.1875
4
[ "BSD-2-Clause" ]
permissive
""" Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element. Your KthLargest class will have a constructor which accepts an integer k and an integer array nums, which contains initial elements from the stream. For each call to the method KthLargest.add, return the element representing the kth largest element in the stream. Example: int k = 3; int[] arr = [4,5,8,2]; KthLargest kthLargest = new KthLargest(3, arr); kthLargest.add(3); // returns 4 kthLargest.add(5); // returns 5 kthLargest.add(10); // returns 5 kthLargest.add(9); // returns 8 kthLargest.add(4); // returns 8 Note: You may assume that nums' length ≥ k-1 and k ≥ 1. """ from heapq import heappush, heappop class KthLargest0: """without heapq modules, 428ms""" def __init__(self, k, nums): self.k = k if not nums: self.nums = [] else: if len(nums) < k: self.nums = sorted(nums) else: self.nums = sorted(nums)[-k:] self.res = self.nums[0] def add(self, val): if not self.nums: self.nums.append(val) self.res = val elif len(self.nums) < self.k or self.res < val: self.nums.append(val) self.nums.sort() if len(self.nums) > self.k and self.res < val: self.nums.pop(0) self.res = self.nums[0] return self.res class KthLargest: # 96ms def __init__(self, k, nums): self.minHeap = [] self.k = k for num in nums: self.add(num) def add(self, val): heappush(self.minHeap, val) if len(self.minHeap) > self.k: heappop(self.minHeap) return self.minHeap[0] # Your KthLargest object will be instantiated and called as such: # obj = KthLargest(k, nums) # param_1 = obj.add(val)
Java
UTF-8
1,339
2.6875
3
[ "Apache-2.0" ]
permissive
package io.github.dunwu.tool.lang; import io.github.dunwu.tool.text.StrSpliter; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.List; /** * {@link StrSpliter} 单元测试 * * @author Looly */ public class StrSpliterTest { @Test public void splitByCharTest() { String str1 = "a, ,efedsfs, ddf"; List<String> split = StrSpliter.split(str1, ',', 0, true, true); Assertions.assertEquals("ddf", split.get(2)); Assertions.assertEquals(3, split.size()); } @Test public void splitByStrTest() { String str1 = "aabbccaaddaaee"; List<String> split = StrSpliter.split(str1, "aa", 0, true, true); Assertions.assertEquals("ee", split.get(2)); Assertions.assertEquals(3, split.size()); } @Test public void splitByBlankTest() { String str1 = "aa bbccaa ddaaee"; List<String> split = StrSpliter.split(str1, 0); Assertions.assertEquals("ddaaee", split.get(2)); Assertions.assertEquals(3, split.size()); } @Test public void splitPathTest() { String str1 = "/use/local/bin"; List<String> split = StrSpliter.splitPath(str1, 0); Assertions.assertEquals("bin", split.get(2)); Assertions.assertEquals(3, split.size()); } }
C++
UTF-8
1,880
2.625
3
[ "MIT" ]
permissive
#include "WAVReader.h" #include "AudioFile.h" #include <stdint.h> #include <string> #include <stdlib.h> AudioFile* WAVReader::getRawAudio(const char* relative_path, FILE* file){ //FILE* fp = fopen(fname,"rb"); if (file) { char id[5]; short* bufferData; unsigned long size; short format_tag, channels, block_align, bits_per_sample; unsigned long format_length, sample_rate, avg_bytes_sec, data_size; fread(id, sizeof(uint8_t), 4, file); id[4] = '\0'; if (!strcmp(id, "RIFF")) { fread(&size, sizeof(uint32_t), 1, file); fread(id, sizeof(uint8_t), 4, file); id[4] = '\0'; if (!strcmp(id,"WAVE")) { fread(id, sizeof(uint8_t), 4, file); fread(&format_length, sizeof(uint32_t),1,file); fread(&format_tag, sizeof(uint16_t), 1, file); fread(&channels, sizeof(uint16_t),1,file); fread(&sample_rate, sizeof(uint32_t), 1, file); fread(&avg_bytes_sec, sizeof(uint32_t), 1, file); fread(&block_align, sizeof(uint16_t), 1, file); fread(&bits_per_sample, sizeof(uint16_t), 1, file); fread(id, sizeof(uint8_t), 4, file); fread(&data_size, sizeof(uint32_t), 1, file); bufferData = (short*) malloc(data_size); fread(bufferData, sizeof(uint16_t), data_size/sizeof(uint16_t), file); } else { //cout<<"Error: RIFF file but not a wave file\n"; } } else { //cout<<"Error: not a RIFF file\n"; } return new AudioFile(channels, bits_per_sample, data_size, sample_rate, (void*) bufferData); } return NULL; //fclose(fp); }
Swift
UTF-8
3,522
2.953125
3
[ "MIT" ]
permissive
// // CubicCurvedPath.swift // Bezier // // Created by Чингиз Б on 02.07.17. // Copyright © 2017 Y Media Labs. All rights reserved. // import UIKit class CubicCurvedPath { private var data: [CGPoint] = [] init(data : [CGPoint]) { self.data = data } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func cubicCurvedPath() -> UIBezierPath { let path = UIBezierPath() var p1 = data[0] path.move(to: p1) var oldControlP = p1 for i in 0..<data.count { let p2 = data[i] var p3: CGPoint? = nil if i < data.count - 1 { p3 = data [i+1] } let newControlP = controlPointForPoints(p1: p1, p2: p2, p3: p3) //uncomment the following four lines to graph control points //if let controlP = newControlP { // path.drawWithLine(point:controlP, color: UIColor.blue) //} //path.drawWithLine(point:oldControlP, color: UIColor.gray) path.addCurve(to: p2, controlPoint1: oldControlP , controlPoint2: newControlP ?? p2) oldControlP = imaginFor(point1: newControlP, center: p2) ?? p1 //***added to algorithm if let p3 = p3 { if oldControlP.x > p3.x { oldControlP.x = p3.x } } //*** p1 = p2 } return path; } private func imaginFor(point1: CGPoint?, center: CGPoint?) -> CGPoint? { //returns "mirror image" of point: the point that is symmetrical through center. //aka opposite of midpoint; returns the point whose midpoint with point1 is center) guard let p1 = point1, let center = center else { return nil } let newX = center.x + center.x - p1.x let newY = center.y + center.y - p1.y return CGPoint(x: newX, y: newY) } private func midPointForPoints(p1: CGPoint, p2: CGPoint) -> CGPoint { return CGPoint(x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2); } private func clamp(num: CGFloat, bounds1: CGFloat, bounds2: CGFloat) -> CGFloat { //ensure num is between bounds. if (bounds1 < bounds2) { return min(max(bounds1,num),bounds2); } else { return min(max(bounds2,num),bounds1); } } private func controlPointForPoints(p1: CGPoint, p2: CGPoint, p3: CGPoint?) -> CGPoint? { guard let p3 = p3 else { return nil } let leftMidPoint = midPointForPoints(p1: p1, p2: p2) let rightMidPoint = midPointForPoints(p1: p2, p2: p3) let imaginPoint = imaginFor(point1: rightMidPoint, center: p2) var controlPoint = midPointForPoints(p1: leftMidPoint, p2: imaginPoint!) controlPoint.y = clamp(num: controlPoint.y, bounds1: p1.y, bounds2: p2.y) let flippedP3 = p2.y + (p2.y-p3.y) controlPoint.y = clamp(num: controlPoint.y, bounds1: p2.y, bounds2: flippedP3); //***added: controlPoint.x = clamp (num:controlPoint.x, bounds1: p1.x, bounds2: p2.x) //*** // print ("p1: \(p1), p2: \(p2), p3: \(p3), LM:\(leftMidPoint), RM:\(rightMidPoint), IP:\(imaginPoint), fP3:\(flippedP3), CP:\(controlPoint)") return controlPoint } }
Python
UTF-8
11,510
2.75
3
[]
no_license
from tkinter import * from tkinter import ttk, messagebox import socket from time import sleep import threading import json from db_connection import * # network client client = None SERVER = '127.0.0.1' PORT = 5050 FORMAT = 'utf-8' board_checked_fields = [] your_turn = False your_details = { "name": "Player1", "symbol": "X", "color": "", "score": 0 } opponent_details = { "name": "Player2", "symbol": "O", "color": "", "score": 0 } def start_the_game(player_id, room_id): # in case is someone go out and come back global board_checked_fields, your_turn board_checked_fields = [] your_turn = False # MAIN GAME WINDOWma window = Tk() window.title("Tic-Tac-Toe by Jędrzej Jagiełło") content = Frame(window) content.grid(row=0, column=0) gameInfo = ttk.Frame(content, width=600, height=150) gameBoard = ttk.Frame(content, borderwidth=5, relief="ridge", width=450, height=450) gamePoints = ttk.Frame(content, borderwidth=5, relief="ridge") gameHistory = ttk.Frame(content, borderwidth=5, relief="ridge") gameInfo.grid(column=0, row=0, columnspan=2) gameBoard.grid(column=0, row=1, rowspan=2) gamePoints.grid(column=1, row=1) gameHistory.grid(column=1, row=2) lbl_status = ttk.Label(gameInfo, text="Status: Not connected to server", font="Helvetica 14 bold") lbl_status.grid(row=1, pady="3") player_scores = ttk.Label(gamePoints, text="Players scores:\n{}: {}\n{}: {}".format(your_details["name"], "200", opponent_details["name"], "100"), font=('consolas 8'), justify=CENTER) player_scores.grid(row=1) moves_history = ttk.Label(gameHistory, text="Round history:\n...", font=('consolas 10'), justify=CENTER) moves_history.grid(row=1) buttonsList = [[], [], []] for i in range(3): for j in range(3): buttonsList[i].append( Button(gameBoard, text=" ", width=3, padx=5, bd=5, bg="gold2", font=('arial', 60, 'bold'), relief="sunken")) buttonsList[i][j].config(command=lambda row=i, col=j: click(row, col)) buttonsList[i][j].grid(row=i, column=j) def check(): # Checks for victory or Draw global your_details for i in range(3): if (buttonsList[i][0]["text"] == buttonsList[i][1]["text"] == buttonsList[i][2]["text"] == your_details["symbol"] or buttonsList[0][i]["text"] == buttonsList[1][i]["text"] == buttonsList[2][i]["text"] == your_details["symbol"]): client.send(json.dumps({"command": "game_won", "winner_symbol": your_details["symbol"]}).encode(FORMAT)) if (buttonsList[0][0]["text"] == buttonsList[1][1]["text"] == buttonsList[2][2]["text"] == your_details[ "symbol"] or buttonsList[0][2]["text"] == buttonsList[1][1]["text"] == buttonsList[2][0]["text"] == your_details["symbol"]): client.send(json.dumps({"command": "game_won", "winner_symbol": your_details["symbol"]}).encode(FORMAT)) # DRAW elif (buttonsList[0][0]["state"] == buttonsList[0][1]["state"] == buttonsList[0][2]["state"] == buttonsList[1][0]["state"] == buttonsList[1][1]["state"] == buttonsList[1][2]["state"] == buttonsList[2][0]["state"] == buttonsList[2][1]["state"] == buttonsList[2][2][ "state"] == DISABLED): client.send(json.dumps({"command": "draw"}).encode(FORMAT)) def click(row, col): global your_turn, board_checked_fields if your_turn == True: new_move = {"row": row, "col": col, "symbol": your_details["symbol"]} if board_checked_fields == []: board_checked_fields = [new_move] else: board_checked_fields.append(new_move) buttonsList[row][col].config(text=your_details["symbol"], state=DISABLED, disabledforeground=your_details["color"]) your_turn = False moves_history["text"] = moves_history["text"].replace("\n...", "") moves_history["text"] = moves_history["text"] + "\n{} -> [{},{}]".format(your_details["symbol"], row, col) client.send(json.dumps( {"command": "new_move", "updated_board": board_checked_fields, "next_turn_symbol": opponent_details["symbol"]}).encode( FORMAT)) lbl_status["text"] = "STATUS: " + opponent_details["name"] + "'s turn! (" + opponent_details["symbol"] + ")" check() def update_board(updated_board): global your_turn, your_details, board_checked_fields if len(updated_board) > len(board_checked_fields): board_checked_fields = updated_board # update current board and update game history moves_history["text"] = "Game history:" if len(updated_board) > 0 else "Game history:\n..." for single_move in board_checked_fields: color = your_details["color"] if single_move["symbol"] == your_details["symbol"] else opponent_details["color"] buttonsList[single_move["row"]][single_move["col"]].config(text=single_move["symbol"], state=DISABLED, disabledforeground=color) moves_history["text"] = moves_history["text"] + "\n{} -> [{},{}]".format(single_move["symbol"], single_move["row"], single_move["col"]) def connect_to_server(game_data): global client, PORT, SERVER try: client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((SERVER, PORT)) client.send(game_data.encode(FORMAT)) threading._start_new_thread(receive_message_from_server, (client, "m")) except Exception as e: messagebox.showerror(title="ERROR!!!", message=e) def receive_message_from_server(client_socket, m): global your_details, opponent_details, your_turn while True: from_server = client_socket.recv(4096).decode(FORMAT) if not from_server: break msg = json.loads(from_server) if msg["command"].startswith("welcome"): your_details["symbol"] = msg["your_symbol"] your_details["name"] = msg["your_nick"] your_details["score"] = msg["your_score"] player_scores["text"] = "Players scores:\n{}: {}".format(your_details["name"], your_details["score"]) if your_details["symbol"] == "X": opponent_details["symbol"] = "O" else: opponent_details["symbol"] = "X" if msg["opponent_nick"] != "": opponent_details["name"] = msg["opponent_nick"] opponent_details["score"] = msg["opponent_score"] player_scores["text"] = "Players scores:\n{}: {}\n{}: {}".format(your_details["name"], your_details["score"], opponent_details["name"], opponent_details["score"]) # if it's continuation of the game if msg["current_turn"] == your_details["symbol"]: if len(msg["updated_board"]) > 0: your_turn = True lbl_status["text"] = "STATUS: Your turn! (" + your_details["symbol"] + ")" else: your_turn = False if len(msg["updated_board"]) > 0: lbl_status["text"] = "STATUS: " + opponent_details["name"] + "'s turn! (" + opponent_details["symbol"] + ")" if msg["command"] == "welcome_first_player": your_details["color"] = "firebrick3" opponent_details["color"] = "Dodgerblue2" if len(msg["updated_board"]) == 0: lbl_status["text"] = "Server: Welcome " + your_details["name"] + "! Waiting for second player" elif msg["command"] == "welcome_second_player": your_details["color"] = "Dodgerblue2" opponent_details["color"] = "firebrick3" if len(msg["updated_board"]) == 0: lbl_status["text"] = "Server: Welcome " + your_details["name"] + "! Game will start soon" update_board(msg["updated_board"]) # it's turned on only if match is from the start elif msg["command"] == "first_game_start": #adding missing data for player1 if your_details["symbol"] == "X": opponent_details["name"] = msg["opponent_nick"] opponent_details["score"] = msg["opponent_score"] player_scores["text"] = "Players scores:\n{}: {}\n{}: {}".format(your_details["name"], your_details["score"], opponent_details["name"], opponent_details["score"]) lbl_status["text"] = "STATUS: " + opponent_details["name"] + " is connected!" sleep(3) your_turn = True if msg["current_turn"] == your_details["symbol"] else False if your_turn == True: lbl_status["text"] = "STATUS: Your turn! (" + your_details["symbol"] + ")" else: lbl_status["text"] = "STATUS: " + opponent_details["name"] + "'s turn! (" + opponent_details["symbol"] + ")" elif msg["command"] == "new_move": update_board(msg["updated_board"]) if msg["current_turn"] == your_details["symbol"]: your_turn = True lbl_status["text"] = "STATUS: Your turn! (" + your_details["symbol"] + ")" else: lbl_status["text"] = "STATUS: " + opponent_details["name"] + "'s turn! (" + opponent_details["symbol"] + ")" elif msg["command"] == "game_won": your_turn = False lbl_status["text"] = "GAME OVER! {} is the winner!".format(msg["winner_nick"]) if your_details["name"] == msg["winner_nick"]: lbl_status.config(foreground=your_details["color"]) else: lbl_status.config(foreground=opponent_details["color"]) elif msg["command"] == "draw": your_turn = False lbl_status["text"] = "GAME OVER! It's a DRAW!" lbl_status.config(foreground=your_details["color"]) client_socket.close() def on_closing(): if messagebox.askokcancel("Quit", "Do you want to quit?"): window.destroy() client.send(json.dumps({"command": "!DISCONNECT"}).encode(FORMAT)) class JSONEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, ObjectId): return str(o) return json.JSONEncoder.default(self, o) game_data = (JSONEncoder().encode({"player_id": player_id, "room_id": room_id})) connect_to_server(game_data) window.protocol("WM_DELETE_WINDOW", on_closing) window.resizable(False, False) window.mainloop() # start_the_game() # room_id = "60cbe1348cc92a7085bbaadc" # player_id = "60c3d0ae531e2ceec167b23a" # #player_id = "60c3d13127d155fbbdb05592" # start_the_game(player_id, room_id)
Java
UTF-8
803
2.0625
2
[]
no_license
package com.amber.ShoppingApp.dao; import java.sql.SQLException; import java.util.List; import java.util.Map; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import com.amber.ShoppingApp.model.ProductBean; public interface ProductDAO { List<ProductBean> selectAll() throws SQLException, Exception; ProductBean selectByPrimaryKey(String productId) throws SQLException, Exception; int insert(ProductBean record) throws SQLException, Exception; int insertSelective(ProductBean record) throws SQLException, Exception; int updateByPrimaryKeySelective(ProductBean record) throws SQLException, Exception; int updateByPrimaryKey(ProductBean record) throws SQLException, Exception; int deleteByPrimaryKey(String productId) throws SQLException, Exception; }
PHP
UTF-8
7,797
2.65625
3
[ "MIT" ]
permissive
<?php namespace Syscover\Pulsar\Libraries; /** * @package Pulsar * @author Jose Carlos Rodríguez Palacín * @copyright Copyright (c) 2015, SYSCOVER, SL. * @license * @link http://www.syscover.com * @since Version 1.0 * @filesource Librarie that instance helper functions */ use Illuminate\Support\Facades\Mail; use Illuminate\Support\Facades\Crypt; use Illuminate\Support\Facades\Config; use Illuminate\Support\MessageBag; class EmailServices { /** * Function that sends a email * * @access public * @param array $data * @return boolean */ public static function sendEmail($data) { $data = self::setTemplate($data); if(isset($data['html']) && isset($data['text'])) { Mail::send(['pulsar::common.views.html_display', 'pulsar::common.views.text_display'], $data, function ($message) use ($data) { $message->to($data['email'], $data['name'])->subject($data['subject']); if(isset($data['replyTo'])) $message->replyTo($data['replyTo']); }); return true; } elseif(isset($data['html'])) { Mail::send(['html' =>'pulsar::common.views.html_display'], $data, function ($message) use ($data) { $message->to($data['email'], $data['name'])->subject($data['subject']); if(isset($data['replyTo'])) $message->replyTo($data['replyTo']); }); return true; } elseif(isset($data['text'])) { Mail::send(['text' =>'pulsar::common.views.text_display'], $data, function ($message) use ($data) { $message->to($data['email'], $data['name'])->subject($data['subject']); if(isset($data['replyTo'])) $message->replyTo($data['replyTo']); }); return true; } return false; } /** * Function that checks the output of a server mail account * * @access public * @param array $account * @return boolean || string */ public static function testEmailAccount($account) { $data['name'] = $account['name_013']; $data['email'] = $account['email_013']; $data['subject'] = "Send test - Envío de pruebas"; $data['text'] = " Congratulations, this is a test email, if you are receiving this email, your account has been configured correctly. Enhorabuena, este es un envío de pruebas, si está recibiendo este correo, su cuenta se ha configurado correctamente."; //set outgoingserver Config::set('mail.host', $account['outgoing_server_013']); Config::set('mail.port', $account['outgoing_port_013']); Config::set('mail.from', ['address' => $account['email_013'], 'name' => $account['name_013']]); Config::set('mail.encryption', $account['outgoing_secure_013'] == ''? null : $account['outgoing_secure_013']); Config::set('mail.username', $account['outgoing_user_013']); Config::set('mail.password', Crypt::decrypt($account['outgoing_pass_013'])); try { self::sendEmail($data); } catch (\Swift_TransportException $swiftTransportException) { $messageBag = new MessageBag; $messageBag->add('error', $swiftTransportException->getMessage()); return $messageBag; } return true; } /** * Patterns function to replace their values * * @access public * @return array */ public static function setTemplate($data) { /*********************************** * Message Subject ************************************/ // if (isset($data['message'])) $data['subject'] = str_replace("#message#", $data['message'], $data['subject']); // Message coded ID, to track (comunik) if (isset($data['contact'])) $data['subject'] = str_replace("#contact#", $data['contact'], $data['subject']); // Contact coded ID, to track (comunik) if (isset($data['company'])) $data['subject'] = str_replace("#company#", $data['company'], $data['subject']); // Company name (comunik) if (isset($data['name'])) $data['subject'] = str_replace("#name#", $data['name'], $data['subject']); // Contact name (comunik) if (isset($data['surname'])) $data['subject'] = str_replace("#surname#", $data['surname'], $data['subject']); // Contact surname (comunik) if (isset($data['birthday'])) $data['subject'] = str_replace("#birthday#", $data['birthday'], $data['subject']); // Birthdate (comunik) if (isset($data['email'])) $data['subject'] = str_replace("#email#", $data['email'], $data['subject']); // Contact email (comunik) $data['subject'] = str_replace("#date#", date('d-m-Y'), $data['subject']); // Current date if(isset($data['html'])) { $data = self::replaceWildcard($data, 'html'); } if(isset($data['text'])) { $data = self::replaceWildcard($data, 'text'); } return $data; } private static function replaceWildcard($data, $index) { // Message body $data[$index] = str_replace("#link#", url(config('pulsar::pulsar.rootUri')) . '/comunik/email/services/campanas/show/#message#/#contact#', $data[$index]); $data[$index] = str_replace("#unsubscribe#", url(config('pulsar::pulsar.rootUri')) . '/comunik/contactos/unsubscribe/email/#contact#', $data[$index]); $data[$index] = str_replace("#pixel#", url(config('pulsar::pulsar.rootUri')) . '/comunik/email/services/campanas/analytics/#campana#/#envio#', $data[$index]); if (isset($data['message'])) $data[$index] = str_replace("#message#", $data['message'], $data[$index]); // Message coded ID, to track (comunik) if (isset($data['contact'])) $data[$index] = str_replace("#contact#", $data['contact'], $data[$index]); // Contact coded ID, to track (comunik) if (isset($data['company'])) $data[$index] = str_replace("#company#", $data['company'], $data[$index]); // Company name (comunik) if (isset($data['name'])) $data[$index] = str_replace("#name#", $data['name'], $data[$index]); // Contact name (comunik) if (isset($data['surname'])) $data[$index] = str_replace("#surname#", $data['surname'], $data[$index]); // Contact surname (comunik) if (isset($data['birthday'])) $data[$index] = str_replace("#birthday#", $data['birthday'], $data[$index]); // Birthdate (comunik) if (isset($data['email'])) $data[$index] = str_replace("#email#", $data['email'], $data[$index]); // Contact email (comunik) if (isset($data['campaign'])) $data[$index] = str_replace("#campaign#", $data['campaign'], $data[$index]); // Campaign coded ID, to track (comunik) if (isset($data['sending'])) $data[$index] = str_replace("#sending#", $data['sending'], $data[$index]); // Sending coded ID, to track (comunik) $data[$index] = str_replace("#date#", date('d-m-Y'), $data[$index]); // Current date // function designed to replace the word #subject# in the title of HTML templates if (isset($data['subject'])) $data[$index] = str_replace("#subject#", $data['subject'], $data[$index]); return $data; } }
C
UTF-8
1,945
2.90625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* test.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ddruart <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/09/26 08:33:53 by ddruart #+# #+# */ /* Updated: 2020/09/26 16:26:32 by ddruart ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> int ft_shownb(char *str) { int i; int j; i = 0; j = 0; while (str[i]) { j = 0; while (str[i + j] >= 'a' && str[i + j] <= 'z') { write(1, &str[i + j], 1); if (str[i + j + 1] == '\n') { write(1, "\n", 1); return (1); } j++; } i++; } return (0); } char *ft_strstr(char *str, char *cmp) { int i; int j; i = 0; j = 0; while (str[i]) { j = 0; while (str[i + j] == cmp[j]) { if (cmp[j + 1] == '\0' && str[i + j + 1] != '0') return (&str[i]); j++; } i++; } return (0); } void ft_putstr(char *str) { int i; i = 0; while (str[i]) { write(1, &str[i], 1); i++; } write(1, "\n", 1); } int main(int argc, char *argv[]) { int file; int ret; char buffer[1024]; int BUF_SIZE; char *cheese; BUF_SIZE = 1024; file = open("numbers.dict", O_RDONLY); ret = read(file, buffer, BUF_SIZE); buffer[ret] = '\0'; if (argc == 2) { cheese = ft_strstr(buffer, argv[1]); ft_shownb(cheese); } return (0); }
Shell
UTF-8
341
3.359375
3
[ "MPL-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#!/bin/sh set -e TEST_VERSION=${1:-canary} for dir in $(ls -d -- */); do test="${dir}run.sh" echo "################################################" echo "Now running $test" echo "################################################" echo "" TEST_VERSION=$TEST_VERSION /bin/sh $test echo "" echo "$test passed" echo "" done
Python
UTF-8
7,005
2.703125
3
[]
no_license
from elsie import SlideDeck, TextStyle as s from branch_prediction import branch_prediction from cache_conflicts import cache_conflicts from denormals import denormals from false_sharing import false_sharing from utils import COLOR_NOTE, code, finish_slides, list_item, new_slide, new_slides, slide_header COLOR1 = "black" COLOR2 = "#f74f00" FONT = "Raleway" def intro(slides: SlideDeck): slide = new_slide(slides) slide.box().text("""CPU design effects that can degrade performance of your programs""", s(bold=True, size=40)) slide.box(p_top=40).text("""Jakub Beránek jakub.beranek@vsb.cz""", s(bold=False, size=30)) slide = new_slide(slides) content = slide_header(slide, "~tt{whoami}") list_wrapper = content.box() list_item(list_wrapper).text("PhD student @ VSB-TUO, Ostrava, Czech Republic") list_item(list_wrapper).text("Research assistant @ IT4Innovations (HPC center)") list_item(list_wrapper).text("HPC, distributed systems, program optimization") slide = new_slide(slides) content = slide_header(slide, "How do we get maximum performance?") list_wrapper = content.box() list_item(list_wrapper).text("Select the right algorithm") list_item(list_wrapper, show="next+").text("Use a low-overhead language") list_item(list_wrapper, show="next+").text("Compile properly") list_item(list_wrapper, show="next+").text("~bold{Tune to the underlying hardware}") def hw_complexity(slides: SlideDeck): slide = new_slide(slides) content = slide_header(slide, "Why should we care?") list_wrapper = content.box() list_item(list_wrapper).text("We write code for the C++ abstract machine") list_item(list_wrapper, show="next+").text( "Intel CPUs fulfill the contract of this abstract machine") list_item(list_wrapper, level=1, show="next+").text( "But inside they can do whatever they want") list_item(list_wrapper, show="next+").text( "Understanding CPU trade-offs can get us more performance") slide = new_slide(slides) slide.update_style("code", s(size=50)) content = slide_header(slide, "C++ abstract machine example") code(content.box(), """void foo(int* arr, int count) { for (int i = 0; i < count; i++) { arr[i]++; } }""") content.box(p_top=20).text("How fast are the individual array increments?", s(size=40)) slide = new_slide(slides) content = slide_header(slide, "Hardware effects") list_wrapper = content.box() list_item(list_wrapper).text( "Performance effects caused by a specific CPU/memory implementation") list_item(list_wrapper, show="next+").text( "Demonstrate some CPU/memory trade-off or assumption") list_item(list_wrapper, show="next+").text("Impossible to predict from (C++) code alone") slide = new_slide(slides) content = slide_header(slide, "Hardware is getting more and more complex") content.box(height=600).image("images/moores-law.png") content.box().text("Source: karlrupp.net", s(size=30)) slide = new_slide(slides) content = slide_header(slide, "Microarchitecture (Haswell)") content.box(height=600).image("images/haswell-diagram.svg") # Heuristics, assumptions, fast paths/slow paths content.box().text("Source: Intel Architectures Optimization Reference Manual", s(size=30)) slide = new_slide(slides) content = slide_header(slide, "How bad is it?") list_wrapper = content.box() cpp = list_item(list_wrapper).box(horizontal=True) cpp.box().text("C++ 17 final draft: ") cpp.box(show="next+").text(" 1622 pages") intel = list_item(list_wrapper, show="next+").box(horizontal=True) intel.box().text("Intel x86 manual: ") intel.box(show="next+").text(" ~bold{5764} pages!") content.box(y=580).text("""http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2017/n4659.pdf https://software.intel.com/sites/default/files/managed/39/c5/325462-sdm-vol-1-2abcd-3abcd.pdf https://software.intel.com/sites/default/files/managed/9e/bc/64-ia-32-architectures-optimization-manual.pdf""", s( size=14, align="left" )) slide = new_slide(slides) content = slide_header(slide, "Plan of attack") list_wrapper = content.box() list_item(list_wrapper).text("Show example C++ programs") list_item(list_wrapper, level=1, show="next+").text("short, (hopefully) comprehensible") list_item(list_wrapper, level=1, show="next+").text("compiled with ~tt{-O3}") list_item(list_wrapper, show="next+").text("Demonstrate weird performance behaviour") list_item(list_wrapper, show="next+").text("Let you guess what might cause it") list_item(list_wrapper, show="next+").text("Explain (a possible) cause") list_item(list_wrapper, show="next+").text("Show how to measure and fix it") list_item(list_wrapper, show="next+", p_top=20).text( "Disclaimer #1: Everything will be Intel x86 specific") list_item(list_wrapper, show="next+").text( "Disclaimer #2: I'm not an expert on this and I may be wrong :-)") slide = new_slide(slides) slide.box().text("""Let's see some examples...""", s(bold=True, size=40)) def outro(slides: SlideDeck): slide = new_slide(slides) content = slide_header(slide, "There are many other effects") list_wrapper = content.box() list_item(list_wrapper).text("NUMA") list_item(list_wrapper).text("4k aliasing") list_item(list_wrapper).text("Misaligned accesses, cache line boundaries") list_item(list_wrapper).text("Instruction data dependencies") list_item(list_wrapper).text("Software prefetching") list_item(list_wrapper).text("Non-temporal stores & cache pollution") list_item(list_wrapper).text("Bandwidth saturation") list_item(list_wrapper).text("DRAM refresh intervals") list_item(list_wrapper).text("AVX/SSE transition penalty") list_item(list_wrapper).text("...") slide = new_slide(slides) slide.box().text("Thank you!", s(bold=True, size=60)) slide.box(p_top=60).text("""For more examples visit: ~tt{github.com/kobzol/hardware-effects}""", s(size=44)) slide.box(p_top=80).text("Jakub Beránek") slide.box(p_top=100).text("Slides built with ~tt{github.com/spirali/elsie}", s(size=30)) def make_presentation(path: str, backup: bool): slides = new_slides(1280, 720) slides.update_style("default", s(font=FONT, size=36, color=COLOR1)) # Default font slides.update_style("emph", s(color=COLOR2)) # Emphasis slides.update_style("code", s(size=32)) slides.set_style("bold", s(bold=True)) slides.set_style("notice", s(color=COLOR_NOTE, bold=True)) intro(slides) hw_complexity(slides) branch_prediction(slides, backup) cache_conflicts(slides, backup) denormals(slides, backup) outro(slides) finish_slides(slides) false_sharing(slides, backup) slides.render(path) make_presentation("slides.pdf", True)
Markdown
UTF-8
5,017
2.921875
3
[ "MIT" ]
permissive
## Civil Air Patrol Fuel Reporting System ### Vision & Scope ### 1. Business Requirements #### 1.1 Background The Civil Air Patrol is the official auxiliary of the United States Air Force and a non-profit organization. CAP supports America’s communities through emergency/disaster relief, aerospace education for youth and the general public, and cadet programs for teenage youth. #### 1.2 Opportunity By creating this application we hope to standardize receipt submissions for all CAP and lower Air Force receipt rejection rates. Although CAP here will receive a copy, more can be made available to others around the US at a fee. #### 1.3 Objectives and Success Criteria The CAP-FRS will streamline and simplify the process through which CAP members submit fuel receipts to the US Air Force for reimbursement. Success will be measured by a reduced percentage of rejected submissions due to error, and a reduction in operator time required for submission. #### 1.4 Customer Needs CAP members must be able to submit their fuel receipts to the US Air Force system quickly and correctly. The CAP-FRS must be accessible to the majority of CAP members and improve on their current process. #### 1.5 Risks As with any system utilizing Internet connectivity and submission of user data, any possible security and privacy issues must be investigated as potential risk factors. ### 2. Vision of the Solution #### 2.1 Vision Statement Our goal will be to completely streamline the process that the Civil Air Patrol uses and create one standardized method in an internet web application. This application would create a PDF document for any Civil Air Patrol member that used it and would take in all data that is necessary for a fuel receipt submission. The final product will be able to pass the inspection of the documents that occurs in the Air Force and decrease rejection rates of fuel receipt submissions by at least 5%. #### 2.2 Major Features - web application - guided fields necessary submission - thorough explanation on fields on what could get input rejected - image upload - complete formatting of PDF #### 2.3 Assumptions and Dependencies The provided application is an internet application, and therefore requires users to have a working internet connection. ### 3. Scope and Limitations #### 3.1 Scope of Initial Release The initial release of the Civil Air Patrol web application will provide an online user interface for Civil Air Patrol members with a streamlined online method to create their PDF. It will cover all necessary fields that must be on a fuel receipt submission and give thorough explanations on each field of what needs to be put in to avoid rejection from the Air Force. After this it will create a pdf for the user that they can attach on the official website and submit for evaluation by the Air Force. #### 3.2 Scope of Subsequent Releases In the future one of the goals is to obtain access to the official website to link with the application. This will avoid a redundancy in filling out some of the information, and will accelerate the process of submitting fuel receipts even further. Another take on the same goal will be to link the official submission website with an automated script to fill in both fields at the same time while either filling out the website or filling out the form. Once again this will take away the redundancy of putting in information that was already inserted, and accelerate the process of submitting the fuel receipts to the Air Force. #### 3.3 Limitations and Exclusions The original version of the application will not have any connection to the Air Force website. It will be completed as its own stand alone application CAP members can fill out online which will create a pdf for them with their fuel receipt to attach to the Air Force online application. There will also be no autofill options with the original and everything will have to be done manually at first. Internet will be required to complete this as it will be an online application, sometimes requiring the pilots to return home before beginning to work on their fuel receipt submission, or before finalizing it. ### 4. Business Context #### 4.1 Stakeholder Profiles |Stakeholder| Description | |--------|---------| |CAP Members| Primary users| |US Air Force | Secondary users: read| #### 4.2 Project Priorities |Dimensions |Driver| Constraint| Degree of Freedom| |-----------|------|-----------|------------------| |Schedule| Probable release by Fall 2015| Internet connection required |N/A| |Features|Included in each release which is stated in the “Vision of the Solution” section| Will not sync with Air Force website| N/A| |Quality|Decrease the rejection rates of fuel receipt submissions by 5%| N/A|N/A #### 5. Versions 0.1 Base template 0.2 Additions to Background, Objectives & Success, and Customer Needs 0.3 Additions to Vision of Solution, and Scope and Limitations
Markdown
UTF-8
2,880
2.875
3
[]
no_license
--- type: post title: "Vegan Eggplant Curry with Fresh Mint" author: "nt_bella" category: lunch photo: "https://imagesvc.meredithcorp.io/v3/mm/image?url=https%3A%2F%2Fimages.media-allrecipes.com%2Fuserphotos%2F5454067.jpg" prep_time: "P0DT0H20M" cook_time: "P0DT0H15M" recipe_yield: "2 servings" rating_value: 4.25 review_count: 8 calories: "549.3 calories" date_published: 05/27/2018 03:27 AM description: "Delicious eggplants are gently cooked with peppers, spring onions, and mint then simmered in coconut milk with curry to create this vegan curry. Best served over rice." recipe_ingredient: ['2 tablespoons vegetable oil', '2 eggplants, cubed', '1 bunch spring onions, minced', '2 cloves garlic, minced', '2 red bell peppers, seeded and cut into strips', '¼ teaspoon curry powder', '1 cup coconut milk', 'salt and ground black pepper to taste', '1 bunch fresh mint, minced'] recipe_instructions: [{'@type': 'HowToStep', 'text': 'Line a plate with paper towels. Heat vegetable oil in a wok or large saucepan over high heat. Add eggplant; cook and stir until softened, 2 to 3 minutes. Remove eggplant from wok; drain on paper towels.\n'}, {'@type': 'HowToStep', 'text': 'Combine onions and garlic in the same pan. Add red bell peppers; cook and stir for 3 minutes. Season with curry powder. Pour in coconut milk and season with salt and pepper. Bring to a simmer and add eggplant. Increase heat to high and bring to a boil. Cook, stirring constantly, until flavors are combined, about 3 minutes. Sprinkle with mint.\n'}] --- Delicious eggplants are gently cooked with peppers, spring onions, and mint then simmered in coconut milk with curry to create this vegan curry. Best served over rice. {{< boldheading >}} {{< checkbox "2 tablespoons vegetable oil" >}} {{< checkbox "2 eggplants, cubed" >}} {{< checkbox "1 bunch spring onions, minced" >}} {{< checkbox "2 cloves garlic, minced" >}} {{< checkbox "2 red bell peppers, seeded and cut into strips" >}} {{< checkbox "¼ teaspoon curry powder" >}} {{< checkbox "1 cup coconut milk" >}} {{< checkbox "salt and ground black pepper to taste" >}} {{< checkbox "1 bunch fresh mint, minced" >}} {{< direction >}} **Step: 1** Line a plate with paper towels. Heat vegetable oil in a wok or large saucepan over high heat. Add eggplant; cook and stir until softened, 2 to 3 minutes. Remove eggplant from wok; drain on paper towels.{{< span >}} **Step: 2** Combine onions and garlic in the same pan. Add red bell peppers; cook and stir for 3 minutes. Season with curry powder. Pour in coconut milk and season with salt and pepper. Bring to a simmer and add eggplant. Increase heat to high and bring to a boil. Cook, stirring constantly, until flavors are combined, about 3 minutes. Sprinkle with mint.{{< span >}} {{< nutrition >}} **Per Serving:** 549 calories; protein 12g; carbohydrates 50.9g; fat 39.4g; sodium 126mg.
Python
UTF-8
988
4.03125
4
[]
no_license
#i is an odd number generated. #change i into a string #revi will be the reverse of the number produced #if i ==revi then the number is palindromic #if i is palindromic check if dividing by 3,5,7,9,11 will produce a remainder. if not then i is NOT a prime if a remainder is formed then i is a prime. N=eval(input("Enter the starting point N:\n")) M=eval(input("Enter the ending point M:\n")) print("The palindromic primes are:") for i in range(N+1,M): if (str(i)==str(i)[::-1]): #checking palindromes #print(i) for j in range(2,int(i**0.5)+1): #of those odd palindromes we want to get prime numbers if i%j==0: #or i==2 or i==3 or i==5 or i==7 or i==11: #we want it to take every palindrome odd number and divide it by cetain integers. if any of those integers return no remainder then not a prime number break else: print(i)
Markdown
UTF-8
620
2.515625
3
[ "Apache-2.0" ]
permissive
# spiderPlus 爬取网站文章到Excel 安装 go get github.com/PeterYangs/spiderPlus 使用 ```go import "github.com/PeterYangs/spiderPlus" spiderPlus.Rule( "https://www.azg168.cn",//域名 "/bazisuanming/index_[PAGE].html",//栏目,分页用[PAGE]替代 10,//爬取页数 2,//起始页面 "body > div.main.clearfix.w960 > div.main_left.fl.dream_box > ul > li",//列表选择器 "a",//a链接选择器(相对于列表) "body > div.main.clearfix.w960 > div.main_left.fl > div.art_con_left > h1",//标题选择器 "#azgbody",//内容选择器 "demo",//下载图片路径 "ttt",//内容中的图片前缀 ) ```
JavaScript
UTF-8
370
2.640625
3
[]
no_license
$(document).ready(function() { var radiorel = 0; $('input[name="radio-1"]').on('change', function(e) { radiorel = e.target.value; $('.task-link').each(function() { var href = $(this).attr('href'); var value = href.replace(/(sort=)[^&]+/ig, '$1' + radiorel); $(this).attr('href', value); }); }); });
C++
UTF-8
539
2.734375
3
[]
no_license
#include <iostream> #include <vector> using namespace std; vector <int> g[111]; bool used[111]; int cnt = 0; void dfs(int v){ if (used[v]) return; used[v] = 1; cnt++; for(int i = 0; i < g[v].size(); i++) dfs(g[v][i]); } int main(){ int n, s; cin >> n >> s; for (int i = 1; i <= n; i++){ for (int j = 1; j <= n; j++){ int k; cin >> k; if (k == 1) g[i].push_back(j); } } dfs(s); cout << cnt << endl; return 0; }
C
UTF-8
805
3.609375
4
[]
no_license
#include <stdio.h> #include <string.h> int Alphacode ( char digits[] ) { int sum[100000]; int temp; int length = strlen ( digits ); int i = 0; if ( length == 1 ) return 1; sum[i++] = 1; if ( (digits[i]-'0' + (digits[i-1]-'0')*10) <= 26 && digits[i] != '0' ) sum[i++] = 2; else sum[i++] = 1; /* Initialize finished. */ while ( i < length ) { if ( digits[i] == '0') sum[i] = sum[i-2]; else if ( digits[i-1] == '0' ) sum[i] = sum[i-1]; else if ( (digits[i]-'0' + (digits[i-1]-'0')*10) <= 26 ) sum[i] = sum[i-1] + sum[i-2]; else sum[i] = sum[i-1]; i++; } return sum[i-1]; } int main() { char digits[100000]; digits[0] = 0; while ( 1 ) { scanf ( "%s", digits ); if ( digits[0] == '0' ) break; printf ( "%d\n", Alphacode(digits) ); } return 0; }
Java
UTF-8
762
2.078125
2
[]
no_license
package pl.niewiemmichal.underhiseye.services; import pl.niewiemmichal.underhiseye.commons.dto.VisitClosureDto; import pl.niewiemmichal.underhiseye.commons.dto.VisitRegistrationDto; import pl.niewiemmichal.underhiseye.commons.dto.VisitWithExaminationsDto; import pl.niewiemmichal.underhiseye.entities.Visit; import java.util.List; public interface VisitService { void cancel(Long visitId, String reason); Visit register(VisitRegistrationDto visitRegistration); void end(Long visitId, VisitClosureDto visitClosure); Visit get(Long id); VisitWithExaminationsDto getFatVisit(Long id); List<Visit> getAll(); List<VisitWithExaminationsDto> getAllFatVisits(); List<VisitWithExaminationsDto> getAllFatVisitsByDoctor(Long doctorId); }
C++
UTF-8
2,269
2.546875
3
[ "Apache-2.0" ]
permissive
/*! * Copyright (c) 2019 by Contributors if not otherwise specified * \file random_file_order_sampler.cc * \brief Randomly shuffle file order but not internal frame order */ #include "random_sampler.h" #include <algorithm> #include <dmlc/logging.h> namespace decord { namespace sampler { RandomSampler::RandomSampler(std::vector<int64_t> lens, std::vector<int64_t> range, int bs, int interval, int skip) : bs_(bs), curr_(0) { CHECK(range.size() % 2 == 0) << "Range (begin, end) size incorrect, expected: " << lens.size() * 2; CHECK_EQ(lens.size(), range.size() / 2) << "Video reader size mismatch with range: " << lens.size() << " vs " << range.size() / 2; // output buffer samples_.resize(bs); // visit order for shuffling visit_order_.clear(); for (size_t i = 0; i < lens.size(); ++i) { auto begin = range[i*2]; auto end = range[i*2 + 1]; if (end < 0) { // allow negative indices, e.g., -20 means total_frame - 20 end = lens[i] - end; } CHECK_GE(end, 0) << "Video{" << i << "} has range end smaller than 0: " << end; CHECK(begin < end) << "Video{" << i << "} has invalid begin and end config: " << begin << "->" << end; CHECK(end < lens[i]) << "Video{" << i <<"} has range end larger than # frames: " << lens[i]; int64_t bs_skip = bs * (1 + interval) - interval + skip; int64_t bs_length = bs_skip - skip; for (int64_t b = begin; b + bs_length < end; b += bs_skip) { int offset = 0; for (int j = 0; j < bs; ++j) { samples_[j] = std::make_pair(i, b + offset); offset += interval + 1; } visit_order_.emplace_back(samples_); } } } void RandomSampler::Reset() { // shuffle orders std::random_shuffle(visit_order_.begin(), visit_order_.end()); // reset visit idx curr_ = 0; } bool RandomSampler::HasNext() const { return curr_ < visit_order_.size(); } const Samples& RandomSampler::Next() { CHECK(HasNext()); CHECK_EQ(samples_.size(), bs_); samples_ = visit_order_[curr_++]; return samples_; } size_t RandomSampler::Size() const { return visit_order_.size(); } } // sampler } // decord
JavaScript
UTF-8
2,721
3.265625
3
[]
no_license
// hide any error messages + movie info $(".desc").hide(); $(".errorMessage").hide(); $(".searchResults").hide(); $(".movieDetails").hide(); function displayInfo() { // wipe out all existing html $(".searchResults").html(""); $(".movieDetails").html(""); // first, a little validation to make sure there is some text var tomatoes = ""; if ($(".movieVal").val()) { var title = encodeURI($(".movieVal").val()); // clear the error message if it existed before $(".errorMessage").hide(); // check to see if the user wants Rotten Tomatoes data if ($(".includeTomatoData").is(":checked")) { tomatoes = "&tomatoes=true"; } else { tomatoes = ""; } //make an ajax call to get the omdb data $.getJSON( "http://www.omdbapi.com/?t=" + title + tomatoes + "", function( response ) { var movieData = []; // push each key value pair into an array of list items (make the class lowercase to avoid calling classes that start with a capital letter) $.each( response, function( key, val ) { // let's show the poster image not just the URL if (key === "Poster") { movieData.push( "<p><li class='" + key.toLowerCase() + "'>" + key + " : "+ "<img src = " + val + " alt ='Movie poster'>" + "</li><p>" ); } else { movieData.push( "<li class='" + key.toLowerCase() + "'>" + key + " : "+ val + "</li>" ); } }); // pick the first four things (title, year, rating, release date) to appear as our "Movie Description" var searchResults = movieData.splice(0, 4) $(".desc").fadeIn(); $(".searchResults").fadeIn(); $(".searchResults").append(searchResults); $(".movieDetails").fadeIn(); $(".movieDetails").append(movieData); //we don't really need to show the user if the response was true... $(".response").hide(); // clear the input field after a search $(".movieVal").val(""); }); } // if no title is inputted, show the error message else { $(".errorMessage").show(); } } // save the title of the movie for the leaderboard $("form").on("submit", function(e){ var url = "/add" var parameters = { title: $(".movieVal").val() } console.log(parameters) $.ajax({ type: "POST", url: url, data: parameters, // serializes the form's elements. success: function(data) { console.log("Success!"); }, cache: false }); // run this display function when enter is pressed on the form or when the search button is clicked + prevent form submission displayInfo(); return false; })
Java
GB18030
1,922
3.375
3
[]
no_license
package other.basic.java.set; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.Spliterator; /** * <PRE> * * </PRE> * * ĿƣjavaStudy</BR> * ֧֣㶫ͨƼɷ޹˾ (c) 2017</BR> * * @version 1.0 2019529 * @author xiangning * @since JDK1.8 */ public class HashSetDemo01 { public static void main(String[] args) { { System.out.println("HashSet ------------------------------------"); HashSet<String> set = new HashSet<String>(); SetUtils.getHashSetData(set); set.forEach(s -> { /** * hashSet */ System.out.println(s); }); System.out.println("spliterator------------------------------------"); Spliterator<String> spliterator = set.spliterator(); spliterator.forEachRemaining((s) -> { System.out.println(s); }); System.out.println("setת"); String[] strings = set.toArray(new String[set.size()]); System.out.println(strings[0]); set.remove("songjiang"); System.out.println(strings[0]); System.out.println("תַ"); String string = Arrays.toString(strings); System.out.println(string); System.out.println("תlist"); List<String> asList = Arrays.asList(strings); System.out.println(asList.size()); System.out.println("תset"); Set hashSet = new HashSet<>(Arrays.asList(strings)); System.out.println(hashSet); } { System.out.println("LinkedHashSet ------------------------------------"); float a = 0.75F; LinkedHashSet<String> hashSet = new LinkedHashSet<String>(); SetUtils.getHashSetData(hashSet); hashSet.forEach(s -> { /** * LinkedHashSet */ System.out.println(s); }); } } }
Markdown
UTF-8
3,288
2.578125
3
[]
no_license
# Packet Tracer: Configuración inicial del router ## Parte 1: Verificar la configuración predeterminada del router #### Paso 1: Establecer una conexión de consola con el R1 #### Paso 2: Ingresar al modo con privilegios y examinar la configuración actual. ~~~ enable show running-config show startup-config ~~~ ##### c) **¿Cuál es el nombre de host del router?** Router **¿Cuántas interfaces Fast Ethernet tiene el router?** 4 **¿Cuántas interfaces Gigabit Ethernet tiene el router?** 2 **¿Cuántas interfaces seriales tiene el router?** 2 **¿Cuál es el rango de valores que se muestra para las líneas vty?** 0-4 ##### d) **¿Por qué el router responde con el mensaje startup-config is not present?** El archivo de configuración solo está en la RAM aún. ## Parte 2: Configurar y verificar la configuración inicial del router #### Paso 1: Configurar los parámetros iniciales del R1. ~~~ configure terminal hostname R1 exit configure terminal line console 0 password letmein login exit exit enable configure terminal enable password cisco exit config t enable secret itsasecret exit config t service password-encryption exit config t banner motd "Unauthorized access is strictly prohibited (El acceso no autorizado queda terminantemente prohibido)" ~~~ #### Paso 2: Verificar los parámetros iniciales del R1. **Para verificar los parámetros iniciales, observe la configuración de R1. ¿Qué comando utiliza?** `show running-config` **¿Por qué todos los routers deben tener un mensaje del día (MOTD)?** Para informar que solo el personal autorizado debe intentar obtener acceso al dispositivo, y que en caso de hacerlo sin estar autorizado puede suponer una infracción legal. O para enviar mensajes al personal autorizado. **Si no se le pide una contraseña, ¿qué comando de la línea de consola se olvidó de configurar?** `login` despues de `password letmein` **¿Por qué la contraseña de enable secret permitiría el acceso al modo EXEC privilegiado y la contraseña de enable dejaría de ser válida?** La contraseña de `enable secret` sobreescribe a la de `enabled` **Si configura más contraseñas en el router, ¿se muestran como texto no cifrado o en forma cifrada en el archivo de configuración? Explique.** Se mostrarán como texto cifrado, ya que `service password-encryption` encripta las contraseñas que están en el archivo de configuración, sean presentes o futuras. ## Parte 3: Guardar el archivo de configuración en ejecución #### Paso 1: Guardar el archivo de configuración en la NVRAM. ~~~ copy running-config startup-config ~~~ **¿Qué comando introdujo para guardar la configuración en la NVRAM?** `copy running-config startup-config` **¿Cuál es la versión más corta e inequívoca de este comando?** `copy r s` **¿Qué comando muestra el contenido de la NVRAM?** `show start` #### Paso 2: Puntos extra opcional: guarde el archivo de configuración de inicio en la memoria flash. ~~~ show flash ~~~ **¿Cuántos archivos hay almacenados actualmente en la memoria flash?** 3 **¿Cuál de estos archivos cree que es la imagen de IOS?** El 3: `c1900-universalk9-mz.SPA.151-4.M4.bin` **¿Por qué cree que este archivo es la imagen de IOS?** Porque es un `.bin` ~~~ copy startup-config flash show flash ~~~
Java
UTF-8
651
3.515625
4
[ "MIT" ]
permissive
package Collection; import java.util.ArrayList; import java.util.Iterator; public class ListDemo { public static void getListDemo() { System.out.println("List实例开始*************************"); ArrayList arraylist = new ArrayList(); arraylist.add("java"); arraylist.add("php"); // 使用Iterator遍历ArrayList Iterator iterator = arraylist.iterator(); while(iterator.hasNext()) { System.out.println(iterator.next()); } // 使用for循环遍历arraylist System.out.println("使用for循环遍历arraylist *******************"); for (int i = 0;i<arraylist.size();i++) { System.out.println(arraylist.get(i)); } } }
Python
UTF-8
263
2.796875
3
[]
no_license
class Solution: def sumZero(self, n: int) -> List[int]: num, rem = n//2, n%2 answer = [] if rem != 0: answer.append(0) for i in range(1, num+1): answer.append(-i) answer.append(i) return answer
Java
UTF-8
449
1.921875
2
[]
no_license
package com.nisum.employee.ref.repository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.stereotype.Repository; import com.nisum.employee.ref.domain.InfoEntity; @Repository public class InformationRepository { @Autowired private MongoOperations mongoOperation; public void save(InfoEntity info) { mongoOperation.save(info); } }
Java
UTF-8
895
2.796875
3
[]
no_license
package server; import java.sql.DriverManager; import java.sql.ResultSet; import com.mysql.jdbc.Statement; public class DB { /* * Connect the database * Use singletone pattern */ private static DB db; final static String ip ="jdbc:mysql://localhost?characterEncoding=utf-8"; final static String id ="root"; final static String pw ="12345"; java.sql.Connection con = null; ResultSet rs; Statement stmt = null; private DB() { connectDB(); } private void connectDB() { try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection(ip, id, pw); stmt = (Statement) con.createStatement(); rs = stmt.executeQuery("use mysql"); } catch (Exception e) { e.printStackTrace(); } } public static DB getInstance() { if (db == null) { synchronized(DB.class) { if (db == null) { db = new DB(); } } } return db; } }
Java
UTF-8
1,765
2.25
2
[]
no_license
/** * This class is generated by jOOQ */ package com.school.cbis.domain.tables.pojos; import java.io.Serializable; import javax.annotation.Generated; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.7.3" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class SystemInform implements Serializable { private static final long serialVersionUID = 851069291; private Integer id; private String systemInform; private Integer systemInformShow; public SystemInform() {} public SystemInform(SystemInform value) { this.id = value.id; this.systemInform = value.systemInform; this.systemInformShow = value.systemInformShow; } public SystemInform( Integer id, String systemInform, Integer systemInformShow ) { this.id = id; this.systemInform = systemInform; this.systemInformShow = systemInformShow; } @NotNull public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } @Size(max = 1000) public String getSystemInform() { return this.systemInform; } public void setSystemInform(String systemInform) { this.systemInform = systemInform; } public Integer getSystemInformShow() { return this.systemInformShow; } public void setSystemInformShow(Integer systemInformShow) { this.systemInformShow = systemInformShow; } @Override public String toString() { StringBuilder sb = new StringBuilder("SystemInform ("); sb.append(id); sb.append(", ").append(systemInform); sb.append(", ").append(systemInformShow); sb.append(")"); return sb.toString(); } }
PHP
UTF-8
2,214
2.84375
3
[ "MIT" ]
permissive
<!-- templete :https://getbootstrap.com/ login:https://www.tutorialrepublic.com/php-tutorial/php-mysql-login-system.php login:https://www.tutorialspoint.com/php/php_mysql_login.htm login:https://www.formget.com/login-form-in-php/ --> <?php session_start(); // Starting Session $error=''; // Variable To Store Error Message if (isset($_POST['submit'])) { if (empty($_POST['username']) || empty($_POST['password'])) { $error = "Username orphpinfo(); Password is invalid"; } else { // Define $username and $password $username= ($_POST['john']?? 'john'); $password= ($_POST['1234']?? '1234'); // Establishing Connection with Server by passing server_name, user_id and password as a parameter $connection = mysqli_connect("localhost", "root", "*********"); // To protect MySQL injection for Security purpose $username = stripslashes($username); $password = stripslashes($password); $username = mysqli_real_escape_string($connection,$username); $password = mysqli_real_escape_string($connection,$password); // if ($stmt = $connection->prepare("SELECT id FROM company where username=? and password=?")) { // $stmt->bind_param("ss", $username, $password); // Bind variables in order // $stmt->execute(); // Execute query // $stmt->bind_result($userID); // Result 'id' from database is set to $userID // $stmt->fetch(); // ...and fetch it // } // // // $result = $stmt->get_result(); // if ($rows = $result->fetch_assoc()) { // $_SESSION['login_user']=$username; // Initializing Session // header("location: profile.php"); // Redirecting To Other Page // // } // Selecting Database $db = mysqli_select_db( $connection,"company"); // SQL query to fetch information of registerd users and finds user match. $query = mysqli_query($connection, "select * from company where password='$password' AND username='$username'"); $rows = mysqli_num_rows($query); if ($rows == 1) { $_SESSION['login_user']=$username; // Initializing Session header("location: profile.php"); // Redirecting To Other Page } else { $error = "Username or Password is invalid"; } mysqli_close($connection); // Closing Connection } } ?>
Python
UTF-8
2,635
4.0625
4
[]
no_license
""" Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: Each row must contain the digits 1-9 without repetition. Each column must contain the digits 1-9 without repetition. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition. A partially filled sudoku which is valid. The Sudoku board could be partially filled, where empty cells are filled with the character '.'. Example 1: Input: [ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ] Output: true Example 2: Input: [ ["8","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ] Output: false Explanation: Same as Example 1, except with the 5 in the top left corner being modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid. Note: A Sudoku board (partially filled) could be valid but is not necessarily solvable. Only the filled cells need to be validated according to the mentioned rules. The given board contain only digits 1-9 and the character '.'. The given board size is always 9x9. """ # 108ms. 78 percentile. from collections import defaultdict class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: rows, columns, squares = defaultdict(set), defaultdict(set), defaultdict(set) for i in range(len(board)): for j in range(len(board[0])): value = board[i][j] if value != ".": square = ( i//3, j//3) if value in rows[i] or value in columns[j] or value in squares[square]: return False else: rows[i].add(value) columns[j].add(value) squares[square].add(value) return True """ Notes: One tricky bit in this is dealing with the squares. Easy approach is to produce a mapping from row and column to square. We can do that with ( i//3, j//3 ) """
C++
UTF-8
1,379
3.25
3
[]
no_license
#include <dictionary/DictionaryApplication.h> #include <iostream> #include <functional> void DictionaryApplication::RequestTranslation(const std::string& wordToTranslate) { std::cout << "Неизвестное слово \"" << wordToTranslate << "\". Введите перевод или пустую строку для отказа.\n"; std::string userTranslation; getline(std::cin, userTranslation); if (userTranslation.empty()) { std::cout << "Слово \"" << wordToTranslate << "\" проигнорировано.\n"; } else { m_workingDictionary.SaveTranslation(wordToTranslate, userTranslation); m_hasUnsavedChanges = true; std::cout << "Слово \"" << wordToTranslate << "\" сохранено в словаре как \"" << userTranslation << "\"\n"; } } void DictionaryApplication::RequestSavingChanges(const std::function<void(bool)>& hasUserAgreedCallback) { std::cout << "В словарь были внесены изменения. Введите Y или y для сохранения перед выходом.\n"; std::string action; getline(std::cin, action); bool hasUserAgreed = ( !action.empty() && tolower(action[0]) == 'y' ); hasUserAgreedCallback(hasUserAgreed); } bool DictionaryApplication::HasUnsavedChanges() const { return m_hasUnsavedChanges; }
TypeScript
UTF-8
1,989
3.484375
3
[]
no_license
export const Day15 = { id: '15', star1, star2 }; function star1 (lines: string[]): string { const startingNumbers = parseStartingNumbers(lines[0]); const turnHistory = playGame(startingNumbers, 2020); return `${turnHistory.lastValue}`; } function star2 (lines: string[]): string { const startingNumbers = parseStartingNumbers(lines[0]); const turnHistory = playGame(startingNumbers, 30000000); return `${turnHistory.lastValue}`; } interface TurnHistory { map: Map<number, number> lastValue: number turnCount: number }; function playGame (startingNumbers: number[], numberOfTurns: number): TurnHistory { const turnHistory: TurnHistory = initialiseTurnHistory(startingNumbers); while (turnHistory.turnCount < numberOfTurns) { // if (turnHistory.turnCount % 1000000 === 0) { // console.log(`${Math.round(100 * turnHistory.turnCount / numberOfTurns)}%`); // } addToTurnHistory(turnHistory, nextTurn(turnHistory)); } return turnHistory; } export function parseStartingNumbers (numbers: string): number[] { return numbers.split(',') .map(numberString => parseInt(numberString, 10)); } export function nextTurn (turnHistory: TurnHistory): number { if (!turnHistory.map.has(turnHistory.lastValue)) { return 0; } else { const turnLastSpoken = turnHistory.map.get(turnHistory.lastValue) ?? 0; const turnsSinceLastSpoken = turnHistory.turnCount - turnLastSpoken; return turnsSinceLastSpoken; } } export function initialiseTurnHistory (turns: number[]): TurnHistory { const turnHistory = { map: new Map(), lastValue: -1, turnCount: 0 }; turns.forEach(value => { addToTurnHistory(turnHistory, value); }); return turnHistory; } export function addToTurnHistory (turnHistory: TurnHistory, value: number): void { if (turnHistory.lastValue !== -1) { turnHistory.map.set(turnHistory.lastValue, turnHistory.turnCount); } turnHistory.turnCount++; turnHistory.lastValue = value; }
C#
UTF-8
1,215
2.703125
3
[]
no_license
using System; namespace Graphe.Collations.Commands { public class EditSacrumCommand : Command { #region Constructor /// <summary> /// Constructor for initializing the command. /// </summary> /// <param name="sacrum">The sacrum to be edited.</param> public EditSacrumCommand(Sacrum sacrum, string text, string representation) { _sacrum = sacrum; _text = text; _representation = representation; } #endregion #region Private Instance Fields private Sacrum _sacrum; private string _text; private string _representation; private string _oldText; private string _oldRepresentation; #endregion public override void Execute() { _oldText = _sacrum.Text; _oldRepresentation = _sacrum.Representation; _sacrum.Text = _text; _sacrum.Representation = _representation; } public override void Undo() { _sacrum.Text = _oldText; _sacrum.Representation = _oldRepresentation; } } }
SQL
UTF-8
358
3.40625
3
[]
no_license
-- Consulta da Ficha de Exercícios SELECT F.CD_FICHA 'Código', F.CD_ALU 'Código Aluno', A.NOME_ALU 'Nome Aluno', F.NM_EXERCICIO 'Nome Exercício', F.REPETICOES 'Repetições', F.SERIES 'Séries', F.TREINO 'Treino', F.DATA_INICIO 'Data de Início' FROM FICHA_EXERCICIOS F LEFT OUTER JOIN ALUNO A ON F.CD_ALU = A.CD_ALU WHERE F.CD_FICHA = {0}
Java
UTF-8
336
2.703125
3
[]
no_license
#include<iostream> int main() { // Type your code here int n, i, id, flag=0; std::cin>>n; int a[n]; for(i=0;i<n;i++) { std::cin>>a[i]; } std::cin>>id; for(i=0;i<n;i++) { if(a[i]==id) flag=1; } if(flag==1) std::cout<<"She passed her exam"; else std::cout<<"She failed"; return 0; }
Markdown
UTF-8
9,691
2.90625
3
[ "CC-BY-NC-SA-4.0", "CC-BY-NC-ND-4.0", "MIT" ]
permissive
# HTTPS 概述与运行机制 在进行 HTTP 通信时,信息可能会监听、服务器或客户端身份伪装等安全问题,HTTPS 则能有效解决这些问题。在使用原始的 HTTP 连接的时候,因为服务器与用户之间是直接进行的明文传输,导致了用户面临着很多的风险与威胁。攻击者可以用中间人攻击来轻易的 截获或者篡改传输的数据。攻击者想要做些什么并没有任何的限制,包括窃取用户的 Session 信息、注入有害的代码等,乃至于修改用户传送至服务器的数据。 我们并不能替用户选择所使用的网络,他们很有可能使用一个开放的,任何人都可以窃听的网络,譬如一个咖啡馆或者机场里面的开放 WiFi 网络。普通的 用户很有可能被欺骗地随便连上一个叫免费热点的网络,或者使用一个可以随便被插入广告的网路当中。如果攻击者会窃听或者篡改网路中的数据,那么用户与服务 器交换的数据就好不可信了,幸好我们还可以使用 HTTPS 来保证传输的安全性。HTTPS 最早主要用于类似于经融这样的安全要求较高的敏感网络,不过现在日渐被各种各样的网站锁使用,譬如我们常用的社交网络或者搜索引擎。HTTPS 协议使用的是 TLS 协议,一个优于 SSL 协议的标准来保障通信安全。只要配置与使用得当,就能有效抵御窃听与篡改,从而有效保护我们将要去访问 的网站。用更加技术化的方式说,HTTPS 能够有效保障数据机密性与完整性,并且能够完成用户端与客户端的双重验证。 随着面临的风险日渐增多,我们应该将所有的网络数据当做敏感数据并且进行加密传输。已经有很多的浏览器厂商宣称要废弃所有的非 HTTPS 的请求,乃 至于当用户访问非 HTTPS 的网站的时候给出明确的提示。很多基于 HTTP/2 的实现都只支持基于 TLS 的通信,所以我们现在更应当在全部地方使用 HTTPS。目前如果要大范围推广使用 HTTPS 还是有一些障碍的,在一个很长的时间范围内使用 HTTPS 会被认为造成很多的计算资源的浪费,不过随着现代硬件 与浏览器的发展,这点计算资源已经不足为道。早期的 SSL 协议与 TLS 协议只支持一个 IP 地址分配一个整数,不过现在这种限制所谓的 SNI 的协议扩展来解 决。另外,从一个证书认证机构获取证书也会打消一些用户使用 HTTPS 的念头,不过下面我们介绍的像 Let's Encrypt 这样的免费的服务就可以打破这种障碍。 ## Definition **HTTPS = HTTP + 加密 + 认证 + 完整性保护**,HTTPS 也就是 HTTP 加上加密处理、认证以及完整性保护。使用 HTTPS 通信时,用的是 https://,而不是 http://。另外,当浏览器访问 HTTPS 的 Web 网站时,浏览器地址栏会出现一个带锁的标记。要注意,HTTPS 并非是应用层的新协议,而是 HTTP 通信接口部分用 SSL 协议代替而已。本来,HTTP 是直接基于 TCP 通信。在 HTTPS 中,它先和 SSL 通信,SSL 再和 TCP 通信。所以说 HTTPS 是披了层 SSL 外壳的 HTTP。SSL 是独立于 HTTP 的协议,所以其他类似于 HTTP 的应用层 SMTP 等协议都可以配合 SSL 协议使用,也可以给它们增强安全性。整个架构如下图所示: ![](https://segmentfault.com/image?src=http://sean-images.qiniudn.com/tls-ssl-_tcp-ip_protocol.png&objectId=1190000004523659&token=6517aceb1d4a4e88003533f1c268c256) ## Performance HTTPS 使用 SSL 通信,所以它的处理速度会比 HTTP 要慢。一是通信慢。它和 HTTP 相比,网络负载会变慢 2 到 100 倍。除去和 TCP 连接、发送 HTTP 请求及响应外,还必须进行 SSL 通信,因此整体上处理通信量会不可避免的增加。二是 SSL 必须进行加密处理。在服务器和客户端都需要进行加密和解密的去处处理。所以它比 HTTP 会更多地消耗服务器和客户端的硬件资源。 # SSL/TLS Protocol SSL 协议,是一种安全传输协议,最初是由 Netscape 在 1996 年发布,由于一些安全的原因 SSL v1.0 和 SSL v2.0 都没有公开,直到 1996 年的 SSL v3.0。TLS 是 SSL v3.0 的升级版,目前市面上所有的 Https 都是用的是 TLS,而不是 SSL。本文中很多地方混用了 SSL 与 TLS 这个名词,大家能够理解就好。 下图描述了在 TCP/IP 协议栈中 TLS( 各子协议)和 HTTP 的关系: ![](https://cattail.me/assets/how-https-works/tcp-ip-model.png) 其中 Handshake protocol,Change Ciper Spec protocol 和 Alert protocol 组成了 SSL Handshaking Protocols。Record Protocol 有三个连接状态 (Connection State),连接状态定义了压缩,加密和 MAC 算法。所有的 Record 都是被当前状态(Current State )确定的算法处理的。 TLS Handshake Protocol 和 Change Ciper Spec Protocol 会导致 Record Protocol 状态切换。 ``` empty state -------------------> pending state ------------------> current state Handshake Protocol Change Cipher Spec ``` 初始当前状态(Current State )没有指定加密,压缩和 MAC 算法,因而在完成 TLS Handshaking Protocols 一系列动作之前,客户端和服务端的数据都是**明文传输**的;当 TLS 完成握手过程后,客户端和服务端确定了加密,压缩和 MAC 算法及其参数,数据(Record )会通过指定算法处理。 ## Why HTTPS? HTTP 日常使用极为广泛的协议,它很优秀且方便,但还是存在一些问题,如: – 明文通信,内容可以直接被窃听 – 无法验证报文的完整性,可能被篡改 – 通信方身份不验证,可能遇到假的客户端或服务器 ### 中间人攻击与内容窃听 HTTP 不会对请求和响应的内容进行加密,报文直接使用明文发送。报文在服务器与客户端流转中间,会经过若干个结点,这些结点中随时都可能会有窃听行为。因为通信一定会经过中间很多个结点,所以就算是报文经过了加密,也一样会被窃听到,不过是窃听到加密后的内容。要窃听相同段上的通信还是很简单的,比如可以使用常用的抓包工具 Wireshark。这种情况下,保护信息安全最常用的方式就是采取加密了,加密方式可以根据加密对象分以下几种:( 1)通信加密 HTTP 协议基于 TCP/IP 协议族,它没有加密机制。但可以通过 SSL(Secure Socket Layer ,安全套接层)建立安全的通信线路,再进行 HTTP 通信,这种与 SSL 结合使用的称为 HTTPS(HTTP Secure ,超文本传安全协议)。(2 )内容加密还可以对通信内容本身加密。HTTP 协议中没有加密机制,但可以对其传输的内容进行加密,也就是对报文内容进行加密。这种加密方式要求客户端对 HTTP 报文进行加密处理后再发送给服务器端,服务器端拿到加密后的报文再进行解密。这种加密方式不同于 SSL 将整个通信线路进行加密,所以它还是有被篡改的风险的。 ### 报文篡改 #### 接收到的内容可能被做假 HTTP 协议是无法证明通信报文的完整性的。因此请求或响应在途中随时可能被篡改而不自知,也就是说,没有任何办法确认,发出的请求 / 响应和接收到的请求 / 响应是前后相同的。比如浏览器从某个网站上下载一个文件,它是无法确定下载的文件和服务器上有些话的文件是同一个文件的。文件在传输过程中被掉包了也是不知道的。这种请求或响应在传输途中,被拦截、篡改的攻击就是中间人攻击。比如某运营商或者某些 DNS 提供商会偷偷地在你的网页中插入广告脚本,就是典型的例子。 #### 防篡改 也有一些 HTTP 协议确定报文完整性的方法,不过这些方法很不方便,也不太可靠。用得最多的就是 MD5 等哈希值校验的方法。很多文件下载服务的网站都会提供相应文件的 MD5 哈希值,一来得用户亲自去动手校验(中国估计只有 0.1% 不到的用户懂得怎么做吧),二来如果网站提供的 MD5 值也被改写的话呢?所以这种方法不方便也不可靠。 ### 仿冒服务器 / 客户端 #### DDOS 攻击与钓鱼网站 在 HTTP 通信时,由于服务器不确认请求发起方的身份,所以任何设备都可以发起请求,服务器会对每一个接收到的请求进行响应(当然,服务器可以限制 IP 地址和端口号)。由于服务器会响应所有接收到的请求,所以有人就利用这一点,给服务器发起海量的无意义的请求,造成服务器无法响应正式的请求,这就是 Dos 攻击(Denial Of Service ,拒绝服务攻击)。由于客户端也不会验证服务器是否真实,所以遇到来自假的服务器的响应时,客户端也不知道,只能交由人来判断。钓鱼网站就是利用了这一点。 #### 身份认证 HTTP 协议无法确认通信方,而 SSL 则是可以的。SSL 不仅提供了加密处理,还提供了叫做 “ 证书 ” 的手段,用于确定通信方的身份。证书是由值得信任的第三方机构颁发(已获得社会认可的企业或组织机构)的,用以证明服务器和客户端的身份。而且伪造证书从目前的技术来看,是一件极为难的事情,所以证书往往可以确定通信方的身份。以客户端访问网页为例。客户端在开始通信之前,先向第三机机构确认 Web 网站服务器的证书的有效性,再得到其确认后,再开始与服务器进行通信。
Python
UTF-8
1,326
4.09375
4
[]
no_license
import random # Limit number of guesses allowed # Catch when someone submits a non-integer # generate a random number between 1 and 10 def secret_num(): secret_num = random.randint(1, 10) return secret_num def get_guess_from_user(): while True: try: guess = int(input("Guess a number between 1 and 10 > ")) break except ValueError: print("Must enter a valid number 1 - 10.") return guess # Play again option def play_again(): while True: new_game = input("Would you like to play again? Y/N > ") if new_game == "Y": start = main() start elif new_game == "N": break return play_again def main(): secret_number = secret_num() while True: # get a number guess from the player users_guess = get_guess_from_user() # compare guess to secret number if users_guess == secret_number: print("Congrats you've won! My number was {}.".format(secret_number)) break elif users_guess > secret_number: print("Guess lower") continue elif users_guess < secret_number: print("Guess higher") continue return main main() play_again()
Markdown
UTF-8
3,201
3.03125
3
[ "MIT" ]
permissive
--- title: Operating at scale outline: problem: | I have 300 sites to manage. Help! draft: false type: deck notes: title: | Operating at scale doesn't just mean meeting the demands of a single application. problem: | As your business grows, you may have multiple application across an entire fleet that each require diligent management. --- {{< slide >}} <h3>Large fleets pose large problems</h3> <ul> <li>Provisioning</li> <li>Updating</li> <li>Access control</li> <li>Support and problem resolution</li> </ul> <aside class="notes"> Managing fleets introduces new and large problems. How do you efficiently provision new sites? How do you manage updates for each site when needed across the whole fleet? How do you control your developer's access to each of them? What's the support lifecycle for problems? </aside> {{< /slide >}} {{< slide >}} <p style="font-style: italic;">Provisioning - automate it</p> <asciinema-player src="../assets/1-create-project.cast"></asciinema-player> <p>Our API is fully scriptable.</p> <aside class="notes"> With Platform.sh, provisioning can be completely automated since our API is fully scriptable. </aside> {{< /slide >}} {{< slide >}} <p style="font-style: italic; margin-bottom: 1em;">Updating - automate it</p> <ul> <li>Manage your source code and push it out via Git and scripts.</li> <li>You decide what the workflow is.</li> <li>Update into a testing branch or straight to prod, your choice.</li> </ul> <aside class="notes"> Platform.sh doesn't restrict your updates workflow at all, so you can decide to test pushed updates on dedicated testing branches. </aside> {{< /slide >}} {{< slide >}} <p style="font-style: italic;">Access control - automate it</p> <asciinema-player src="../assets/2-multi-add-users.cast"></asciinema-player> <p>Run commands on multiple projects using the CLI or API calls.</p> <aside class="notes"> Through the CLI or our API, controlling developer access can be fully automated as well, giving you fine grained control over who can contribute to which project. </aside> {{< /slide >}} {{< slide >}} <h3>Support and problem resolution</h3> <div class="two-col top-align"> <img src="../assets/3-create-ticket.png" style="justify-self: center; height: 450px" alt="Create tickets using ZenDesk" /> <ul> <li>We've got your back with 24/7 infrastructure support.</li> <li>Your helpdesk team can escalate relevant tickets to us directly via ticket sharing.</li> </ul> </div> <aside class="notes"> And when it comes to support, Platform.sh provides 24/7 infrastructure support where you can open and share pressing tickets we can escalate quickly to resolution. </aside> {{< /slide >}} {{< slide >}} <p>Platform.sh is a one-stop solution for web hosting.</p> <p style="margin-top: 2em;">The more sites you need to manage,<br />the greater the benefit of our fully automatable solution.</p> <aside class="notes"> All of this makes Platform.sh a one-stop solution for web hosting. As the number of sites your team manages grows, the greater the benefit you'll receive from the fully automatable solutions we provide. </aside> {{< /slide >}}
C++
UTF-8
3,451
2.609375
3
[]
no_license
#include "Transform.h" using namespace cv; Mat cylinderTrans(Mat img, double focusSet) { int width = img.cols; int height = img.rows; double focus; double fov; if (focusSet > 0) { fov = focusSet / 360 * 3.1415926; focus = width / 2 / tan(fov); } else { focus = sqrtf(img.rows * img.rows + img.cols * img.cols); fov = atanf(width / 2 / focus); } // printf("fov=%f, newwidth=%f, focus=%f\n", tan(fov), focus * sin(fov) * 2 + 1, focus); Mat cylImg(img.rows, int(focus * sin(fov) * 2 + 1), CV_8UC3, Scalar(0, 0, 0)); for (int i = 0; i < width; i++) for (int j = 0; j < height; j++) { int x = focus * sin(atan((i - width / 2) / focus)) + focus * sin(fov); int y = focus * (j - height / 2) / sqrtf(powf(i - width / 2, 2) + focus * focus) + height / 2; uchar* data = img.ptr<uchar>(j); uchar* data_out = cylImg.ptr<uchar>(y); data_out[3 * x] = data[3 * i]; data_out[3 * x + 1] = data[3 * i + 1]; data_out[3 * x + 2] = data[3 * i + 2]; } return cylImg; } Mat getHomographyByOpenCV(std::vector<Point2f> obj, std::vector<Point2f> sce) { Mat H = findHomography(obj, sce, CV_LMEDS); return H; } Mat getHomographyBySelf(vector<Point2f> obj, vector<Point2f> sce) { //cvSolve Mat H = findHomography(obj, sce, CV_LMEDS); return H; } newBound getNewBound(cv::Mat H, int obj_col, int obj_row, int sce_col, int sce_row) { std::vector<Point2f> obj_corners(4); obj_corners[0] = cvPoint(0, 0); obj_corners[1] = cvPoint(obj_col, 0); obj_corners[2] = cvPoint(obj_col, obj_row); obj_corners[3] = cvPoint(0, obj_row); std::vector<Point2f> scene_corners(4); perspectiveTransform(obj_corners, scene_corners, H); newBound newBound; newBound.top = newBound.top_in = 0; newBound.bottom = newBound.bottom_in = sce_row; newBound.left = newBound.left_in = 0; newBound.right = newBound.right_in = sce_col; for (int i = 0; i<4; i++) { if (newBound.top > scene_corners[i].y) { newBound.top = scene_corners[i].y; newBound.topP = scene_corners[i]; } if (newBound.bottom < scene_corners[i].y) { newBound.bottom = scene_corners[i].y; newBound.bottomP = scene_corners[i]; } if (newBound.left > scene_corners[i].x) { newBound.left = scene_corners[i].x; newBound.leftP = scene_corners[i]; } if (newBound.right < scene_corners[i].x) { newBound.right = scene_corners[i].x; newBound.rightP = scene_corners[i]; } if (newBound.top_in < scene_corners[i].y && (i == 0 || i == 1)) newBound.top_in = scene_corners[i].y; if (newBound.bottom_in > scene_corners[i].y && (i == 2 || i == 3)) newBound.bottom_in = scene_corners[i].y; if (newBound.left_in < scene_corners[i].x && (i == 0 || i == 3)) newBound.left_in = scene_corners[i].x; if (newBound.right_in > scene_corners[i].x && (i == 1 || i == 2)) newBound.right_in = scene_corners[i].x; } return newBound; } void matrixTo8(double num1[4][2], double num2[4][2], double A[9][9], double B[9]) { int i, j, n = 4; for (i = 0; i<9; i++) for (j = 0; j<9; j++) A[i][j] = 0; for (i = 1; i <= n; i++) { A[i][1] = num1[i - 1][0]; A[i + n][4] = num1[i - 1][0]; A[i][2] = num1[i - 1][1]; A[i + n][5] = num1[i - 1][1]; A[i][3] = 1.0; A[i + n][6] = 1.0; A[i][7] = -num1[i - 1][0] * num2[i - 1][0]; A[i][8] = -num1[i - 1][1] * num2[i - 1][0]; A[i + n][7] = -num1[i - 1][0] * num2[i - 1][1]; A[i + n][8] = -num1[i - 1][1] * num2[i - 1][1]; B[i] = num2[i - 1][0]; B[i + n] = num2[i - 1][1]; } }
Java
UTF-8
4,607
2.296875
2
[]
no_license
package com.r.bigconf.core.processing; import com.r.bigconf.core.model.ConferenceUsers; import com.r.bigconf.core.processing.model.ConferenceChannelsData; import com.r.bigconf.core.processing.model.ConferenceProcessData; import com.r.bigconf.core.sound.wav.WavUtils; import lombok.extern.slf4j.Slf4j; import java.nio.ByteBuffer; import java.util.HashMap; import java.util.Map; @Slf4j public class BaseConferenceProcess { public boolean minimizeTotalChannel = false; public void processInterval(ConferenceProcessData processData) { log.trace("Processing interval for conference started"); Map<String, ByteBuffer> incoming = processData.getUsersIncomingData(); ConferenceChannelsData building = processData.getChannelsDataObjectToFill(); buildBuffers(building, incoming); processData.replaceWithNewChannelsData(building); markSpeakingUsers(processData, incoming); log.trace("Processing interval for conference finished"); } private void markSpeakingUsers(ConferenceProcessData processData, Map<String, ByteBuffer> incoming) { ConferenceUsers users = processData.getUsersInstantDataToModify(); users.getUsersData().forEach(conferenceUserInstantData -> { conferenceUserInstantData.setSpeaking(incoming.containsKey(conferenceUserInstantData.getUserId())); }); } private void buildBuffers(ConferenceChannelsData toBuild, Map<String, ByteBuffer> incomingDataMap) { if (incomingDataMap.size() == 0) { return; } final Map<String, Integer> lengthsMap = new HashMap<>(); int maxLength = 0; for (Map.Entry<String, ByteBuffer> entry : incomingDataMap.entrySet()) { int dataLength = WavUtils.getDataLength(entry.getValue()); if (dataLength > maxLength) { maxLength = dataLength; } lengthsMap.put(entry.getKey(), dataLength); } int dataStartIndex = 44; int buffersSize = maxLength + dataStartIndex; toBuild.setCommonChannel(ByteBuffer.allocate(buffersSize)); for (String id : incomingDataMap.keySet()) { toBuild.getAudioChannels().put(id, ByteBuffer.allocate(buffersSize)); } //copy headers ByteBuffer value = incomingDataMap.entrySet().iterator().next().getValue(); value.position(0); for (int i = 0; i < dataStartIndex; i++) { byte headerByte = value.get(i); toBuild.getCommonChannel().put(i, headerByte); for (ByteBuffer buffer : toBuild.getAudioChannels().values()) { buffer.put(i, headerByte); } } for (int i = dataStartIndex; i < buffersSize; i = i + 2) { int total = 0; for (Map.Entry<String, ByteBuffer> entry : incomingDataMap.entrySet()) { if (checkLength(lengthsMap, i, entry)) { byte hi = entry.getValue().get(i + 1); byte lo = entry.getValue().get(i); total = total + WavUtils.getaShort(hi, lo); } } int totalMinimized = minimizeTotalChannel ? total / incomingDataMap.size() : total; byte totalHi = WavUtils.getHiPart(totalMinimized); byte totalLo = WavUtils.getLoPart(totalMinimized); WavUtils.putBytes(toBuild.getCommonChannel(), i, totalHi, totalLo); for (Map.Entry<String, ByteBuffer> entry : incomingDataMap.entrySet()) { final byte hiPart; final byte loPart; if (checkLength(lengthsMap, i, entry)) { byte hi = entry.getValue().get(i + 1); byte lo = entry.getValue().get(i); int specific = total - WavUtils.getaShort(hi, lo); int specificMinimized = minimizeTotalChannel ? specific / incomingDataMap.size() - 1 : specific; hiPart = WavUtils.getHiPart(specificMinimized); loPart = WavUtils.getLoPart(specificMinimized); } else { hiPart = totalHi; loPart = totalLo; } WavUtils.putBytes(toBuild.getAudioChannels().get(entry.getKey()), i, hiPart, loPart); } } //building.compressedCommonChannel = codec.compress(building.commonChannel); } private boolean checkLength(Map<String, Integer> lengthsMap, int i, Map.Entry<String, ByteBuffer> entry) { return i + 1 < lengthsMap.get(entry.getKey()) + 44; } }
Python
UTF-8
617
2.71875
3
[]
no_license
import os, time, picamera os.system("mkdir -p output && rm -rf output/*" ) with picamera.PiCamera() as camera: camera.resolution = (1240, 1024) camera.start_preview() for i, filename in enumerate(camera.capture_continuous('output/image_{counter:03d}.jpg')): print( f"[{i +1:02d}] filename = {filename}" ) time.sleep(1) if i > 9 : break pass camera.stop_preview() pass print( "Converting images to a video file ... " ) os.system("sudo apt install ffmpeg -y" ) os.system("ffmpeg -framerate 1 -i output/image_%03d.jpg output/my_video.mp4" ) print( "Done converting." )
Java
UTF-8
2,789
2.59375
3
[ "BSD-3-Clause" ]
permissive
/* * Copyright (c) 2012-2020 University Corporation for Atmospheric Research/Unidata. * See LICENSE for license information. */ package edu.ucar.unidata.rosetta.util; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.FileReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import edu.ucar.unidata.rosetta.domain.RosettaGlobalAttribute; import edu.ucar.unidata.rosetta.domain.Template; public class TemplateFactory { private static String nameValueSep = ":"; private static String groupNameSep = "\\."; /** * Convert a line from a .metadata file into a RosettaGlobalAttribute * * @param line one entry from a .metadata file * @return a RosettaGlobalAttribute representation of a single .metadata file entry */ private static RosettaGlobalAttribute convertMetadataFileLine(String line) { String group = "root"; String name = ""; String value = ""; String[] groupNameAndValue = line.split(nameValueSep, 2); if (groupNameAndValue.length > 1) { value = groupNameAndValue[groupNameAndValue.length - 1].trim(); String[] groupAndName = groupNameAndValue[0].split(groupNameSep, 2); if (groupAndName.length == 2) { group = groupAndName[0].trim(); name = groupAndName[1].trim(); } else { name = groupAndName[0].trim(); } } else { // error - no metadata pair found } return new RosettaGlobalAttribute(name, value, "STRING", group); } /** * Construct a template object from a .metadata file * * @param metadataFile the .metadata file * @return a template representation of the .metadata file */ public static Template makeTemplateFromMetadataFile(Path metadataFile) throws IOException { Template template = new Template(); List<RosettaGlobalAttribute> globalAttrs = new ArrayList<>(); try (Stream<String> stream = Files.lines(metadataFile)) { globalAttrs = stream.map(line -> convertMetadataFileLine(line)).collect(Collectors.toList()); } template.setGlobalMetadata(globalAttrs); return template; } /** * Construct a template object from a JSON representation of a template * * @param jsonFile the json template file * @return a template object based on the json file */ public static Template makeTemplateFromJsonFile(Path jsonFile) throws IOException { ObjectMapper templateMapper = new ObjectMapper(); Template template; try (FileReader templateFileReader = new FileReader(jsonFile.toFile())) { template = templateMapper.readValue(templateFileReader, Template.class); } return template; } }
C++
UTF-8
490
2.609375
3
[]
no_license
#include<stdlib.h> #include<unistd.h> #include<stdio.h> #include<sys/shm.h> #include<fcntl.h> #include<semaphore.h> #include<iostream> using namespace std; int main() { cout<<"child opened"<<endl; sem_t *S1 = sem_open("mysem1", 0); sem_t *S2 = sem_open("mysem2", 0); int rfd; // int wfd; // dup2(0, rfd); // dup2(1, wfd); int i = 4; char buffer[100]; while(i) { sem_wait(S2); read(0, buffer, 6); cout<<"Process2 :"<<buffer<<endl; sem_post(S1); i--; } return 0; }
Java
UTF-8
1,337
2.265625
2
[]
no_license
package com.project2.DAOImpl; import java.util.List; import javax.transaction.Transactional; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.project2.DAO.FriendDAO; import com.project2.model.Friends; import com.project2.model.User; @Repository @Transactional public class FriendsDAOImpl implements FriendDAO { @Autowired private SessionFactory sessionFactory; public void addFriend(Friends friend) { Session session=sessionFactory.getCurrentSession(); session.saveOrUpdate(friend); } public List<Friends> getallfriendrequest(String username) { Session session=sessionFactory.getCurrentSession(); Query query=session.createQuery("from Friends where toid=:username and accepted='0'"); query.setParameter("username",username); List<Friends> flist=query.list(); return flist; } public Friends getFriendId(long friendid) { Session session=sessionFactory.getCurrentSession(); Friends frd=(Friends)session.get(Friends.class, friendid); return frd; } public void deleteFriendId(long friendid) { Session session=sessionFactory.getCurrentSession(); Friends frd=(Friends)session.get(Friends.class, friendid); session.delete(frd); } }
Python
UTF-8
896
4.40625
4
[]
no_license
""" Daily Coding Problem - 10/23/2019 - Medium This problem was asked by Google. Given a string of parentheses, write a function to compute the minimum number of parentheses to be removed to make the string valid (i.e. each open parenthesis is eventually closed). For example, given the string "()())()", you should return 1. Given the string ")(", you should return 2, since we must remove all of them. """ #Time complexity O(N), where N is the string size def spare_parenthesis_counter(input_string): spare = 0 openning = 0 for c in input_string: if c != '(' and c !=')': raise Exception("Invalid char '{}' found, input should contain just ')' or '('. ".format(c)) if c == '(': spare = spare + 1 openning = openning + 1 elif c == ')' and openning > 0: spare = spare - 1 openning = openning - 1 else: spare = spare + 1 return spare
Java
UTF-8
319
1.828125
2
[]
no_license
package com.example.kapil.formtask1; public class ApiUtils { public ApiUtils() {} public static final String BASE_URL = "http://api.shoocal.com/test/manager/democalltesting"; public static APIService getAPIService() { return RetrofitClient.getClient(BASE_URL).create(APIService.class); } }
JavaScript
UTF-8
1,818
2.625
3
[]
no_license
const initialState = { access_token: localStorage.getItem('token'), expiryTime: localStorage.getItem('expiry_time'), userdata: localStorage.getItem('userdata'), artist: [], track: [], playliste: localStorage.getItem('playliste'), page: 'Home', search: [] }; function Reducer(state = initialState, action) { switch (action.type) { case "SET_TOKEN": return { ...state, access_token: action.token }; case "SET_EXPiR": return { ...state, expiryTime: action.expiryTime }; case "SET_USER": return { ...state, userdata: action.user }; case "SET_PLAYLISTE": return { ...state, playliste: action.play }; case "SET_ARTIST": return { ...state, page: action.artist }; case "SET_TRACK": return { ...state, track: action.track }; case "SET_PAGE": return { ...state, page: action.page }; case "SET_SEARCH": return { ...state, search: action.search }; case "DESTROY_SESSION": return { ...state, access_token: undefined, userdata: undefined, artist: undefined, playliste: undefined, expiryTime: undefined }; default: return state; } } export default Reducer;
Python
UTF-8
293
2.90625
3
[]
no_license
import sys sys.stdin = open("0402회전.txt", "r") T = int(input()) for tc in range(T): N, M = map(int, input().split()) data = list(map(int, input().split())) cnt = 0 while cnt < M: data.append(data.pop(0)) cnt += 1 print("#{} {}".format(tc+1, data[0]))
Java
UTF-8
2,482
1.9375
2
[]
no_license
package com.apps.multiboo; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Typeface; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.RelativeLayout; /** * Created by soumya on 1/24/2016. */ public class Screenshottwo extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.screenshotwo, container, false); RelativeLayout layout =(RelativeLayout)v.findViewById(R.id.scrren1); // layout.setBackgroundResource(R.mipmap.screenshottwo); layout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Boolean FirstTime; SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(getActivity()); SharedPreferences.Editor editor = preferences.edit(); FirstTime = preferences.getBoolean("FirstTime", true); Log.d(String.valueOf(FirstTime), "Firsttime"); if (FirstTime) { // Musiccontinue=true; Intent intent = new Intent(getActivity(), SelectnumberActivity.class); startActivity(intent); getActivity().finish(); //implement your first time logic editor.putBoolean("FirstTime", false); editor.commit(); Log.d(String.valueOf(FirstTime), "fnt"); }else{ //app open directly // Musiccontinue=true; Intent intent = new Intent(getActivity(), Menupage.class); startActivity(intent); Log.d(String.valueOf(FirstTime), "else"); getActivity(). finish(); } } }); return v; } public static Screenshottwo newInstance(String text) { Screenshottwo f = new Screenshottwo(); // Bundle b = new Bundle(); // b.putString("msg", text); // // f.setArguments(b); return f; } }
Markdown
UTF-8
367
2.71875
3
[ "MIT" ]
permissive
## Topic - News App - This Repository consists of A Basic News app. - Used API for fetching data of news. ## Softwares used - HTML5 - CSS3 - JavaScript ## Software needed to run this app - VSCode (as an editor) - Google Chrome as browser - Live Link: https://sumera222.github.io/NewsApp/ - Repository Link: https://github.com/Sumera222/NewsApp
Python
UTF-8
680
2.859375
3
[]
no_license
with open("day09.txt") as f: instructions = [l.strip().split() for l in f.readlines()] def sign(x): return 1 if x > 0 else -1 if x < 0 else 0 DIRS = { "U": 0 + 1j, "D": 0 - 1j, "R": 1 + 0j, "L": -1+ 0j, } L = 10 knots = [0j for _ in range(L)] visited = {0j} for direction, x in instructions: v = DIRS[direction] x = int(x) for i in range(x): knots[0] += v for i in range(L-1): h, t = knots[i], knots[i+1] dx, dy = (h - t).real, (h - t).imag if max(abs(dx), abs(dy)) > 1: knots[i+1] += sign(dx) + 1j * sign(dy) visited |= {knots[i+1]} print(len(visited))
Markdown
UTF-8
2,961
2.734375
3
[]
no_license
require; - стандартный модуль ноды http.createServer().listen createServer - стандартный метод listen(3000) - метод с портом который мы будем слушать http.createServer(function (request, responce) { request - то что отправляем на сервер - запрос responce - ответ сервера }) // следующий шаг такой http.createServer(function (request, responce) { responce.end(`Hello my first ever on Node`); }).listen(3000); // в брузере в нетворк - если статус 200 есть то это нормально // следующий шаг http.createServer(function (request, responce) { console.log(request.url); if (request.url == '/'){ responce.end(`Main`); } else if (request.url == '/cat') { responce.end(`Category`); } }).listen(3000); // в имени урл в браузере добавляем /cat и сервер дает другой ответ //- добавляем распознование тегов и кириллицу http.createServer(function (request, responce) { console.log(request.url); console.log(request.method); console.log(request.headers['user-agent']); responce.setHeader("Content-Type", "text/html; charset=utf-8;") // вот тут if (request.url == '/'){ responce.end(`Main <b>Hello</b> Привет`); } else if (request.url == '/cat') { responce.end(`Category <h2>Hello</h2>`); } }).listen(3000); // - создаем страницу Создали файл page_1.dat в нем написали теги и иконку с сайта https://www.iconfinder.com/search/?q=server в app.js > var fs = require('fs'); - добавляем модуль js которая позволяет работать с файлами const http = require ('http'); var fs = require('fs'); //http.createServer().listen(3000); http.createServer(function (request, responce) { console.log(request.url); console.log(request.method); console.log(request.headers['user-agent']); responce.setHeader("Content-Type", "text/html; charset=utf-8;") if (request.url == '/'){ responce.end('Main <b>Hello</b> Привет'); } else if (request.url == '/dat') { let myFile = fs.readFileSync('page_1.dat'); console.log(myFile); responce.end(myFile); } }).listen(3000); // данный метод - неизменяемый файл - это просто для обучения таким методом выводить ненадо Статику отдавать не обрабатывая может респонс ЕСЛИ ПРОСТО ОТДАТЬ ФАЙЛ _ (сохранить картинку в папку ) то ноду надо учить
C
UTF-8
1,998
2.5625
3
[ "MIT" ]
permissive
/* * lis.h * Copyright (C) 2008, 2009 Tomasz Koziara (t.koziara AT gmail.com) * -------------------------------------------------------------------- * list merge sort */ /* This file is part of Solfec. * Solfec is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * Solfec is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with Solfec. If not, see <http://www.gnu.org/licenses/>. */ #include <limits.h> #ifndef __lis__ #define __lis__ #define DOUBLY_LINKED(PREV, NEXT) for (i = list; i; j = i, i = i->NEXT) i->PREV = j; #define SINGLE_LINKED(PREV, NEXT) #define IMPLEMENT_LIST_SORT(KIND, CALL, LIST, PREV, NEXT, LE)\ static LIST* CALL (LIST *list)\ {\ LIST *i, *j, *k, *h, *t;\ int l, m, n;\ \ for (l = 1; l < INT_MAX;l *= 2)\ {\ h = t = NULL;\ \ for (j = list;;)\ {\ i = j;\ \ for (m = 0; m < l && j; j = j->NEXT, m ++);\ for (n = 0, k = j; n < l && k; k = k->NEXT, n ++);\ \ if (!j && i == list)\ {\ KIND (PREV, NEXT)\ return list;\ }\ else if (!(m+n)) break;\ \ if (!h) h = (LE (i, j) ? i : j);\ \ for (; m && n;)\ {\ if (LE (i, j))\ {\ if (t) t->NEXT = i;\ t = i;\ i = i->NEXT;\ m --;\ }\ else\ {\ if (t) t->NEXT = j;\ t = j;\ j = j->NEXT;\ n --;\ }\ }\ \ while (m)\ {\ t->NEXT = i;\ t = i;\ i = i->NEXT;\ m --;\ }\ \ while (n)\ {\ t->NEXT = j;\ t = j;\ j = j->NEXT;\ n --;\ }\ }\ \ t->NEXT = NULL;\ list = h;\ }\ \ return list;\ } #endif
Java
UTF-8
1,771
2.578125
3
[]
no_license
package com.top_adv.myapplication1.Alarm; import android.os.Parcel; import android.os.Parcelable; public class AlarmData implements Parcelable{ public int resource; public String uri; public String title; public String message; public String ticker; public AlarmData() { } public AlarmData(Parcel in) { readFromParcel(in); } private void readFromParcel(Parcel in) { resource = in.readInt(); uri = in.readString(); title = in.readString(); message = in.readString(); ticker = in.readString(); } public void writeToParcel(Parcel dest, int flags) { // TODO Auto-generated method stub dest.writeInt(resource); dest.writeString(uri); dest.writeString(title); dest.writeString(message); dest.writeString(ticker); } @Override public int describeContents() { // TODO Auto-generated method stub return 0; } public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { @Override public AlarmData createFromParcel(Parcel in) { return new AlarmData(in); } @Override public AlarmData[] newArray(int size) { // TODO Auto-generated method stub return new AlarmData[size]; } }; //get,set method public int getResource() { return resource; } public void setResource(int resource) { this.resource = resource; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getTicker() { return ticker; } public void setTicker(String ticker) { this.ticker = ticker; } }
Java
UTF-8
8,367
2.1875
2
[]
no_license
package cz.vity.freerapid.plugins.services.pinterest; import cz.vity.freerapid.plugins.exceptions.ErrorDuringDownloadingException; import cz.vity.freerapid.plugins.exceptions.PluginImplementationException; import cz.vity.freerapid.plugins.exceptions.ServiceConnectionProblemException; import cz.vity.freerapid.plugins.exceptions.URLNotAvailableAnymoreException; import cz.vity.freerapid.plugins.webclient.AbstractRunner; import cz.vity.freerapid.plugins.webclient.DownloadState; import cz.vity.freerapid.plugins.webclient.FileState; import cz.vity.freerapid.plugins.webclient.utils.PlugUtils; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.methods.GetMethod; import java.net.URI; import java.net.URLEncoder; import java.util.LinkedList; import java.util.List; import java.util.logging.Logger; import java.util.regex.Matcher; /** * Class which contains main code * * @author bircie */ class PinterestFileRunner extends AbstractRunner { private final static Logger logger = Logger.getLogger(PinterestFileRunner.class.getName()); @Override public void runCheck() throws Exception { //this method validates file super.runCheck(); final GetMethod getMethod = getGetMethod(fileURL);//make first request if (makeRedirectedRequest(getMethod)) { checkProblems(); checkNameAndSize(getContentAsString());//ok let's extract file name and size from the page } else { checkProblems(); throw new ServiceConnectionProblemException(); } } private void checkNameAndSize(String content) throws ErrorDuringDownloadingException { if (fileURL.contains("/pin/")) { final Matcher match = PlugUtils.matcher("<img src=\".+?/([^/]+?)\" class=\"pinImage\"", content); if (!match.find()) throw new PluginImplementationException("File name not found"); httpFile.setFileName(match.group(1).trim()); } else { httpFile.setFileName("Board: " + PlugUtils.getStringBetween(content, "<h1>", "</h1>")); final Matcher match = PlugUtils.matcher("<div.+?PinCount.+?PinCount.+?>\\s+?(.+?)Pins</div>", content); if (match.find()) httpFile.setFileSize(PlugUtils.getFileSizeFromString(match.group(1))); } httpFile.setFileState(FileState.CHECKED_AND_EXISTING); } @Override public void run() throws Exception { super.run(); logger.info("Starting download in TASK " + fileURL); final GetMethod method = getGetMethod(fileURL); //create GET request if (makeRedirectedRequest(method)) { //we make the main request checkProblems();//check problems final String content = getContentAsString(); checkNameAndSize(content);//extract file name and size from the page if (fileURL.contains("/pin/")) { final Matcher match = PlugUtils.matcher("<img src=\"(.+?)\" class=\"pinImage\"", content); if (!match.find()) throw new PluginImplementationException("Download link not found"); final String dlLink = match.group(1).trim(); if (!tryDownloadAndSaveFile(getGetMethod(dlLink))) { checkProblems();//if downloading failed throw new ServiceConnectionProblemException("Error starting download");//some unknown problem } } else { List<URI> list = new LinkedList<URI>(); final Matcher matchPin = PlugUtils.matcher("<a href=\"(.+?)\" class=\"pinImageWrapper", content); while (matchPin.find()) list.add(new URI("http://www.pinterest.com" + matchPin.group(1))); int maxSize = 25; // check for more links if (list.size() == maxSize) { final String source = PlugUtils.getStringBetween(content, "<link rel=\"canonical\" href=\"", "\">"); final Matcher matchD1 = PlugUtils.matcher("name\": \"BoardFeedResource\", (\"options\": \\{\"board_id\":.+?)\\},", content); if (!matchD1.find()) throw new PluginImplementationException("Error D1"); final Matcher matchD2 = PlugUtils.matcher("P.setContext\\((.+?)\\);", content); if (!matchD2.find()) throw new PluginImplementationException("Error D2"); final Matcher matchD3 = PlugUtils.matcher("26\"\\}\\], \"errorStrategy\": 1, \"data\": \\{\\}, (\"options\": \\{\"scrollable\": true.+?), \"uid\": \"Grid-20\"", content); if (!matchD3.find()) throw new PluginImplementationException("Error D3"); String data = "{" + matchD1.group(1).replaceAll("\\s", "") + ",\"context\":" + matchD2.group(1).replaceAll("\\s", "") + ",\"module\":{\"name\":\"GridItems\"," + matchD3.group(1).replaceAll("\\s", "") + "},\"append\":true,\"error_strategy\":1}"; long time = System.currentTimeMillis(); while (list.size() == maxSize) { maxSize += 25; time += 1; final HttpMethod httpMethod = getMethodBuilder() .setReferer(fileURL) .setAction("http://www.pinterest.com/resource/BoardFeedResource/get/") .setParameter("source_url", URLEncoder.encode(source, "UTF-8")) .setParameter("data", URLEncoder.encode(data, "UTF-8")) .setParameter("_", "" + time) .toGetMethod(); httpMethod.addRequestHeader("X-Requested-With", "XMLHttpRequest"); if (!makeRedirectedRequest(httpMethod)) { checkProblems(); throw new ServiceConnectionProblemException(); } final Matcher matchP2 = PlugUtils.matcher("<a href=\\\\\"(/pin/.+?)\\\\\" class=\\\\\"pinImageWrapper", getContentAsString()); while (matchP2.find()) list.add(new URI("http://www.pinterest.com" + matchP2.group(1))); final Matcher matchB = PlugUtils.matcher("bookmarks\": \\[\"(.+?)\"\\]", getContentAsString()); if (!matchB.find()) throw new PluginImplementationException("Error B"); final String d1 = data.substring(0, data.indexOf("bookmarks\":[\"") + ("bookmarks\":[\"").length()); final String d2 = data.substring(data.indexOf("\"]}")); data = d1 + matchB.group(1) + d2; } } if (list.isEmpty()) throw new PluginImplementationException("No links found"); getPluginService().getPluginContext().getQueueSupport().addLinksToQueue(httpFile, list); logger.info("Added " + list.size() + " links"); httpFile.setFileName("Link(s) Extracted !"); httpFile.setState(DownloadState.COMPLETED); httpFile.getProperties().put("removeCompleted", true); } } else { checkProblems(); throw new ServiceConnectionProblemException(); } } private void checkProblems() throws ErrorDuringDownloadingException { final String contentAsString = getContentAsString(); if (contentAsString.contains("We couldn't find that page")) { throw new URLNotAvailableAnymoreException("File not found"); //let to know user in FRD } if (contentAsString.contains("Something went wrong!") || contentAsString.contains("Our server is experiencing a mild case of the hiccups")) { throw new ErrorDuringDownloadingException("Internal Pinterest error"); } } }
Swift
UTF-8
834
2.65625
3
[]
no_license
// // ChannelTableCell.swift // QuickChat // // Created by thanhbh on 5/18/18. // Copyright © 2018 vinicorp. All rights reserved. // import UIKit class ChannelTableCell: UITableViewCell { @IBOutlet weak var txtChannel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state if selected { layer.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.2475385274) } else { layer.backgroundColor = UIColor.clear.cgColor } } func configureCell(channel: Channel) { txtChannel.text = "#\(channel.name)" } }
Python
UTF-8
260
2.953125
3
[]
no_license
def commonChars(self, A): """ :type A: List[str] :rtype: List[str] """ #Brute Force #Create a dictionary for all all the strings to track the count of letters. #Compare and keep the count of each letter.
Python
UTF-8
14,546
3.59375
4
[ "MIT" ]
permissive
#!/usr/bin/env python # coding: utf-8 # __Submitted by__: M. Hasnain Naeem (212728) from BSCS-7B, NUST # # # Digital Image Processing # ## Lab 4 - Transformation Functions and Geometric Transforms from Scratch and using OpenCV # __Objectives:__ # The objectives of this lab are: # - To apply Log transformation on images and visualize results. # - To apply power-law transform to correct gamma in images. # - To apply various geometric transformations (like translation, rotation, scaling, sheering and affine) on images and see their effects. # In[1]: import os import math import numpy as np import cv2 import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # In[2]: def get_gray_image(name, img_dir="files/imgs"): # open file and convert to grey scale filename = os.path.join(os.curdir, img_dir, name) img = cv2.imread(filename) gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) return gray_img # In[3]: def get_intensity_counts(gray_img): intensity_count = np.zeros(256, "int") for i, row in enumerate(gray_img): for j, intensity_val in enumerate(row): intensity_count[intensity_val] += 1 return intensity_count # In[4]: def plot_intensity_hists(bins, intensity_counts, saving_dir, filename): save_loc = os.path.join(saving_dir, filename+"_intensity_histogram"+".jpg") plt.bar(bins, intensity_counts, color='#0504aa') plt.grid(axis='y', alpha=0.75) plt.xlabel('Intensity Value') plt.ylabel('Intensity Value Count') plt.title("Intensity Value Histogram for "+filename) plt.savefig(save_loc, bbox_inches="tight", dpi=100) plt.show() # In[5]: # get all the filenames in the directory imgs_dir = os.path.join(os.curdir, "files", "imgs") img_names = os.listdir("files/imgs") # get filename --> gray_image mapping for future usage gray_imgs = dict() for img_name in img_names: gray_img = get_gray_image(img_name) gray_imgs[img_name] = gray_img plt.imshow(gray_img, cmap="gray") plt.show() # ### Task 1 # 1. Use python notebook and opencv’s imread function and load an image (e.g. dark.tif) # 2. Visualize histogram by plotting the histogram. # 3. Apply log transform on image and visualize the output histogram. # 4. Try to experiment by changing the scaling constant c # 5. Summarize your findings by providing a figure containing 4 plots (input image, histogram of input image, output image and histogram of output image) # #### Log Transformation # In[6]: def log_transform(img, args): log_transformed_img = np.zeros(img.shape, "int") # calculate scaling constant c = (255)/(math.log(1+np.max(img))) # transform all intensities for i, row in enumerate(img): for j, val in enumerate(row): # transform current intensity value log_transformed_img[i, j] = c * math.log(1+val) return log_transformed_img # In[7]: def transform_and_hists(img_name, gray_img, trans_func, saving_dir, **kwargs): print(img_name) print("************") print("Original Image:") plt.imshow(gray_img, cmap="gray") plt.show() bins = [i for i in range(256)] # plot intensity histogram intensity_count = get_intensity_counts(gray_img) plot_intensity_hists(bins, intensity_count, saving_dir, img_name) # transformation transformed_img = trans_func(gray_img, kwargs) # new file name & location new_path = os.path.join(saving_dir, "transformed", img_name+"_transformed.jpg") plt.imsave(new_path, transformed_img, cmap="gray") print("Transformed Image:") plt.imshow(transformed_img, cmap="gray") plt.show() # plot histogram of transformed image intensity_count = get_intensity_counts(transformed_img) plot_intensity_hists(bins, intensity_count, saving_dir, img_name+"_"+trans_func.__name__+"_transformed.jpg") # #### Draw Histogram of Image, Transform, Draw Histogram of Transformed Image # In[8]: task1_dir = os.path.join(os.curdir, "files", "task1") task1_transformed_dir = os.path.join(task1_dir, "transformed") # create directories doesn't exist if not os.path.exists(task1_dir): os.makedirs(task1_dir) if not os.path.exists(task1_transformed_dir): os.makedirs(task1_transformed_dir) # perform operations on all the images for img_name, gray_img in gray_imgs.items(): transform_and_hists(img_name, gray_img, log_transform, task1_dir) # ### Task 2 # - Read “aerial.tif” image in python notebook and store that in “img” variable. - Read the documentation of Interact from ipywidgets and create a slider named gamma. # - By using the value of gamma, apply a power-law transform on image and figure out which value of gamma can result in a contrast enhanced output. # - __HINT:__ since you have to apply this transformation to each pixel, nested for loops including the power-law operation should do the trick. # - Summarize your findings by providing a figure containing 4 plots (input image, histogram of input image, output image and histogram of output image) # #### Functions for Power Law Transformation & Histogram Generation # In[9]: def power_law(img, args): gamma_val = args["gamma_val"] c = args["c_val"] gamma_transformed_img = np.zeros(img.shape, "int") # transform all intensities for i, row in enumerate(img): for j, val in enumerate(row): # transform current intensity value gamma_transformed_img[i, j] = int(c * math.pow(val, gamma_val)) return gamma_transformed_img # In[10]: def power_law_pixel(intensity_val, args): gamma_val = args["gamma_val"] c = args["c_val"] transformed_intensity = int(c * math.pow(intensity_val, gamma_val)) return transformed_intensity # In[11]: def gen_power_law_table(args): # generate gamma table gamma_table = dict() for i in range(256): gamma_table[i] = power_law_pixel(i, args) return gamma_table # In[12]: def power_law_using_table(img, args): gamma_table = args["power_law_table"] gamma_transformed_img = np.zeros(img.shape, "int") # transform all intensities for i, row in enumerate(img): for j, val in enumerate(row): # transform current intensity value gamma_transformed_img[i, j] = gamma_table[val] return gamma_transformed_img # #### Make the required directories & open the file # In[13]: task2_dir = os.path.join(os.curdir, "files", "task2") task2_transformed_dir = os.path.join(task2_dir, "transformed") # create directories doesn't exist if not os.path.exists(task2_dir): os.makedirs(task2_dir) if not os.path.exists(task2_transformed_dir): os.makedirs(task2_transformed_dir) # transform using Power Law task2_img_name = "aerial.tif" task2_img = gray_imgs[task2_img_name] # #### Power Law Transformation with Gamma Value & Scaling Value Sliders # ##### Without using Transformation Table # In[54]: from ipywidgets import interact def gamma_slider(gamma_val, c_val): args = {"gamma_val": gamma_val, "c_val": c_val} transformed_img = power_law(task2_img, args) plt.imshow(transformed_img, cmap="gray") # gamma value & scaling factor sliders interact(gamma_slider, gamma_val=(0.0, 2.0), c_val=(0.0, 2.0)); # ignore below lines # for lab submission, load and show the slider output screenshot; because slider won't appear in HTML version of notebook plt.figure(figsize = (7,7)) screenshot_1 = cv2.imread("screenshot_1.PNG") plt.imshow(screenshot_1) plt.show() # ##### Using Transformation Table # In[55]: from ipywidgets import interact def gamma_slider(gamma_val, c_val): args = {"gamma_val": gamma_val, "c_val": c_val} args["power_law_table"] = gen_power_law_table(args) transformed_img = power_law_using_table(task2_img, args) plt.imshow(transformed_img, cmap="gray") # gamma value & scaling factor sliders interact(gamma_slider, gamma_val=(0.0, 2.0), c_val=(0.0, 2.0)); # ignore below lines # for lab submission, load and show the slider output screenshot; because slider won't appear in HTML version of notebook plt.figure(figsize = (7,7)) screenshot_2 = cv2.imread("screenshot_2.PNG") plt.imshow(screenshot_1) plt.show() # #### Histogram Comparisons # #### Without using Transformation Table # In[16]: transform_and_hists(task2_img_name, task2_img, power_law, task2_dir, gamma_val=0.4, c_val=1) # ##### Using Transformation Table # In[17]: args = {"gamma_val": 0.4, "c_val":1} power_law_table = gen_power_law_table(args) transform_and_hists(task2_img_name, task2_img, power_law_using_table, task2_dir, gamma_val=0.4, c_val=1, power_law_table=power_law_table) # ### Task 3 # Read “messi5.jpg” image and apply following transformations using cv2.warpaffine() function: # - Translation # - Rotation # - Sheering in x # - Sheering in y # - Random affine transform # # Summarize your findings by providing a figure which contains images before and after geometric transformation. # # In[18]: # open files task3_img_name = "messi5.jpg" task3_img = gray_imgs[task3_img_name] plt.imshow(task3_img, cmap="gray") plt.show() # #### Translation # In[19]: trans_x = 100 trans_y = 100 task3_img_rows, task3_img_cols =task3_img.shape img3_trans_shape = (task3_img_cols+100, task3_img_rows+100) trans_M = np.float32([[1,0,trans_x],[0,1,trans_y]]) # enlarged image to contain the translated image task3_img_translated = np.zeros((task3_img.shape[0]+100, task3_img.shape[1]+100)) # paste the image into the container image task3_img_translated[:task3_img.shape[0],:task3_img.shape[1]] = task3_img plt.imshow(task3_img_translated, cmap="gray") plt.show() # transform and show translated_img = cv2.warpAffine(task3_img, trans_M, img3_trans_shape) plt.imshow(translated_img, cmap="gray") plt.show() # #### Rotation # In[20]: rot_angle = 90 rotation_M = cv2.getRotationMatrix2D((img3_trans_shape[0]/2,img3_trans_shape[1]/2),rot_angle,1) # enlarged image to contain the translated image task3_img_rotated = np.zeros((task3_img.shape[0]+100, task3_img.shape[1]+100)) # paste the image into the container image task3_img_rotated[:task3_img.shape[0],:task3_img.shape[1]] = task3_img plt.imshow(task3_img_rotated, cmap="gray") plt.show() # transform and show rotated_img = cv2.warpAffine(task3_img_rotated, rotation_M, img3_trans_shape) plt.imshow(rotated_img, cmap="gray") plt.show() # #### Sheering in X # In[21]: shear_x = .1 shear_x_M = np.float32([[1,shear_x,0],[0,1,0]]) # enlarged image to contain the translated image task3_img_shear_x = np.zeros((task3_img.shape[0]+100, task3_img.shape[1]+100)) # paste the image into the container image task3_img_shear_x[:task3_img.shape[0],:task3_img.shape[1]] = task3_img plt.imshow(task3_img_shear_x, cmap="gray") plt.show() # transform and show shear_x_img = cv2.warpAffine(task3_img_shear_x, shear_x_M, img3_trans_shape) plt.imshow(shear_x_img, cmap="gray") plt.show() # #### Sheering in Y # In[22]: shear_y = .1 shear_y_M = np.float32([[1,0,0],[shear_y,1,0]]) # enlarged image to contain the translated image task3_img_shear_y = np.zeros((task3_img.shape[0]+100, task3_img.shape[1]+100)) # paste the image into the container image task3_img_shear_y[:task3_img.shape[0],:task3_img.shape[1]] = task3_img plt.imshow(task3_img_shear_y, cmap="gray") plt.show() # transform and show shear_y_img = cv2.warpAffine(task3_img_shear_y, shear_y_M, img3_trans_shape) plt.imshow(shear_y_img, cmap="gray") plt.show() # #### Random Affine Transformation # In[23]: pts1 = np.float32([[50,50],[200,50],[50,200]]) pts2 = np.float32([[10,100],[200,50],[100,250]]) # enlarged image to contain the translated image task3_img_random = np.zeros((task3_img.shape[0]+100, task3_img.shape[1]+100)) # paste the image into the container image task3_img_random[:task3_img.shape[0],:task3_img.shape[1]] = task3_img plt.imshow(task3_img_random, cmap="gray") plt.show() # transform and show random_M = cv2.getAffineTransform(pts1,pts2) random_trans_img = cv2.warpAffine(task3_img_random,random_M,img3_trans_shape) plt.imshow(random_trans_img, cmap="gray") plt.show() # ### Task 4 # You may have noticed that in task 2 when using interact with some real-time processing, the system takes some time to process. # - This is usually caused by applying exponential mathematical operation withing nested for loops. # - You can use the concept of mapping to apply the transformation function in an efficient manner! # - Try out both techniques (i.e. power-law in nested for loops and mapping) by increasing the size of input image and calculate the time take by each. # - Conclude your findings in the form of graph in which x-axis should indicate the increasing size of image and y-axis should indicate time taken for processing. # # #### Trying Power Law Transformation with & without Transformation Table for Processing Time Comparison # In[35]: # upscale the task 3 image for task 4 print('Original Dimensions : ', task3_img.shape) # increase size to 2X scale_percent = 1000 # percent of original size task4_img_width = int(task3_img.shape[1] * scale_percent / 100) task4_img_height = int(task3_img.shape[0] * scale_percent / 100) task4_img_dim = (task4_img_width, task4_img_height) task4_img = cv2.resize(task3_img, task4_img_dim, interpolation = cv2.INTER_AREA) print('Resized Dimensions : ', task4_img.shape) plt.imshow(task4_img, cmap="gray") plt.show() # In[38]: import time # In[43]: start_time = time.time() args = {"gamma_val": 0.4, "c_val":1} power_law_table = gen_power_law_table(args) args["power_law_table"] = power_law_table task4_img_with_table = power_law_using_table(task4_img, args) print("--- %s seconds ---" % (time.time() - start_time)) # In[40]: plt.imshow(task4_img_with_table, cmap="gray") plt.show() # In[41]: start_time = time.time() args = {"gamma_val": 0.4, "c_val":1} task4_img_without_table = power_law(task4_img, args) print("--- %s seconds ---" % (time.time() - start_time)) # In[42]: plt.imshow(task4_img_without_table, cmap="gray") plt.show() # #### Comparison Results # - Gray version of "Messi5.jpg" was upscaled to (2800, 4500) (10 times) for comparison of Power Law using Transformation Table and without the Transformation Table. # - It took __22.32 seconds when transformation table was not used__. # - It took __8 seconds when transformation table was used__. # In[ ]:
Java
UTF-8
667
1.8125
2
[]
no_license
package com.aiinterview.analysis.dao; import java.util.List; import java.util.Map; import com.aiinterview.analysis.vo.KeywordAnalysisVO; import com.aiinterview.analysis.vo.TalentAnalysisVO; import egovframework.rte.psl.dataaccess.mapper.Mapper; @Mapper("keywordAnalysisMapper") public interface KeywordAnalysisMapper { public List<KeywordAnalysisVO> retrieveList(String ansSq) throws Exception; public void create(KeywordAnalysisVO keywordAnalysisVO) throws Exception; public List<TalentAnalysisVO> retrieveTalentPercentList(String talentSq) throws Exception; public List<String> retrieveKeywordList(Map<String, String> selectMap) throws Exception; }
Java
UTF-8
521
2.921875
3
[ "Apache-2.0" ]
permissive
package irvine.oeis.a067; import irvine.math.z.Z; import irvine.oeis.Sequence; /** * A067107 Smallest number whose sum of digits is n!. * a(n) = concatenation of (n! mod 9 ) and ( n! div 9 ) nines. * @author Georg Fischer */ public class A067107 implements Sequence { private int mN = 0; private Z mF = Z.ONE; @Override public Z next() { ++mN; mF = mF.multiply(Z.valueOf(mN)); return new Z(String.valueOf(mF.mod(9)) + (mN > 3 ? Z.TEN.pow(mF.divide(9).intValue()).subtract(1).toString() : "")); } }
Java
UTF-8
2,572
2.25
2
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
package ie.gov.tracing.storage; import android.content.Context; import androidx.room.Database; import androidx.room.Room; import androidx.room.RoomDatabase; import androidx.room.TypeConverters; import net.sqlcipher.database.SupportFactory; import java.util.Date; import java.util.UUID; import ie.gov.tracing.common.Events; @Database( entities = { ExposureEntity.class, TokenEntity.class }, version = 1, exportSchema = false) @TypeConverters({ZonedDateTimeTypeConverter.class}) public abstract class ExposureNotificationDatabase extends RoomDatabase { private static final String DATABASE_NAME = "exposurenotifications_encrypted"; @SuppressWarnings("ConstantField") // Singleton pattern. private static volatile ExposureNotificationDatabase INSTANCE; abstract ExposureDao exposureDao(); abstract TokenDao tokenDao(); static synchronized ExposureNotificationDatabase getInstance(Context context) { if (INSTANCE == null) { Events.raiseEvent(Events.INFO, "buildDatabase - start: " + new Date()); INSTANCE = buildDatabase(context); Events.raiseEvent(Events.INFO, "buildDatabase - done: " + new Date()); } return INSTANCE; } private static ExposureNotificationDatabase buildDatabase(Context context) { try { String password = SharedPrefs.getString("password", context); if (password.isEmpty()) { Events.raiseEvent(Events.INFO, "buildDatabase - no password, creating..."); nukeDatabase(context); // just in case we had previous one, new password = new database password = UUID.randomUUID().toString(); SharedPrefs.setString("password", password, context); Events.raiseEvent(Events.INFO, "buildDatabase - password set"); } Events.raiseEvent(Events.INFO, "buildDatabase - building..."); SupportFactory sqlcipherFactory = new SupportFactory(password.getBytes()); return Room.databaseBuilder( context.getApplicationContext(), ExposureNotificationDatabase.class, DATABASE_NAME).openHelperFactory(sqlcipherFactory) .build(); } catch (Exception ex) { Events.raiseError("buildDatabase", ex); } return null; } public static void nukeDatabase (Context context) { try { Events.raiseEvent(Events.INFO, "Nuking database"); context.getApplicationContext().deleteDatabase(DATABASE_NAME); INSTANCE = null; Events.raiseEvent(Events.INFO, "Database nuked"); } catch(Exception e) { Events.raiseError("Error nuking database", e); } } }
Markdown
UTF-8
1,154
2.953125
3
[]
no_license
## 渲染流水线上: CSS如何影响首次加载时的白屏时间 ## 渲染流水线为什么需要CSSSOM - CSSOM的两个作用 - 为javaScript提供操作样式表的能力 - 为合成布局树提供基础样式信息 ## 影响页面展示的因素和优化策略 - 首屏渲染的三个阶段 - 请求发出后,到提交数据阶段,这时页面仍展示之前页面的内容 - 提交数据后渲染进程会创建一个空白页面,又叫解析白屏。并等待CSS文件和javaScript文件加载完成,生成CSSOM和DOM,然后合成布局树,准备首屏渲染。 - 等首屏渲染完成后,开始进入完整页面的生成阶段,然后页面被一点点绘制出来 ### 解析白屏 - 主要任务: 解析HTML、下载CSS、下载JavaScript、生成CSSOM和DOM、执行JavaScript、生成布局树、绘制页面 - 缩短白屏时间的策略: - 通过内联javascript、内联Css来减少这两种文件的下载 - 尽量减少文件大小、压缩文件、移除不必要的注释 - 在不需要解析HTML的javaScript文件使用异步加载 - 对于大的CSS文件,按需拆分成多个CSS文件
C++
UTF-8
1,477
3.203125
3
[ "MIT" ]
permissive
/* * Created by Francesco Frassineti on 06/12/2019. * LIST OF EDITS (reverse chronological order - add last on top): * + * + Francesco Frassineti [06/12/19] - Basic creation */ #include "HealthComponent.hpp" #include "AudioLocator.hpp" #include <iostream> HealthComponent::HealthComponent(GameObject* gameObject) : Component(gameObject) { } HealthComponent::~HealthComponent() { } void HealthComponent::setMaxHealth(int amount) { if (amount <= 0) throw "Setting a non positive amount of health as Maximum health."; max_health = amount; } int HealthComponent::getMaxHealth() { return max_health; } void HealthComponent::setCurrentHealth(int amount) { if (amount < 0) throw "Setting a negative amount of health as Current health."; current_health = amount; } int HealthComponent::getCurrentHealth() { return current_health; } void HealthComponent::addHealth(int amount) { if (amount < 0) throw "Adding a negative amount of health!"; current_health += amount; if (current_health > max_health) current_health = max_health; } void HealthComponent::removeHealth(int amount) { if (amount < 0) throw "Removing a negative amount of health!"; if(amount > 0) AudioLocator::getService()->playOneshot("Assets/Sounds/HurtSound.wav"); current_health -= amount; if (current_health < 0) current_health = 0; } bool HealthComponent::isAlive() { return current_health > 0; } void HealthComponent::print() { std::cout << current_health << "/" << max_health << std::endl; }
Java
UTF-8
1,337
3.1875
3
[]
no_license
class Account{ private int id; private double balance; private double annuallnterestRate = 0; private String dateCreated; public Account(){ } public int getId() { return id; } public void setId(int id) { this.id = id; } public double getBalance() { return balance; } public void setBalance(double balance) { this.balance = balance; } public double getAnnuallnterestRate() { return annuallnterestRate; } public void setAnnuallnterestRate(double annuallnterestRate) { this.annuallnterestRate = annuallnterestRate; } public String getDateCreated() { return dateCreated; } public double getMonthlyInterestRate(){ return this.annuallnterestRate % 12; } public double withDraw(double x){ double y = balance - x; System.out.println("账户余额:"+y); return x; } public void deposit(double x){ double y = balance + x; System.out.println("账户余额:"+y); } } public class ClassTest { public static void main(String[] args) { Account A = new Account(); A.setId(1122); A.setBalance(20000); A.setAnnuallnterestRate(0.045); A.withDraw(2500); A.deposit(3000); } }
Python
UTF-8
2,941
2.875
3
[]
no_license
from newspaper import Article, ArticleException from newsapi.newsapi_client import NewsApiClient import sys import json import time import asyncio def add_text_and_format(old_article): formatted_article = {} try: newspaper_article = Article(old_article['url']) newspaper_article.download() newspaper_article.parse() formatted_article = { 'title': old_article['title'], 'description': old_article['description'], 'text': newspaper_article.text, 'date': old_article['publishedAt'], 'url': old_article['url'] } except (ArticleException): print('Error: article skipped due to failure parsing: ' + old_article['url']) finally: return formatted_article def writeToJSONFile(path, fileName, data): filePathNameWExt = './' + path + '/' + fileName + '.json' with open(filePathNameWExt, 'w') as fp: json.dump(data, fp) def search_articles(query_string, domain_blacklist_string, domain_whitelist_string): newsapi = NewsApiClient(api_key='391c4cadc42a4a42aaf1ea266df4adfc') headlines = newsapi.get_everything( q=query_string, language='en', sort_by='relevancy', page_size=100, domains=domain_whitelist_string # exclude_domains=domain_blacklist_string ) return headlines # convert this to whitelist of domains? def get_whitelist(): filepath = './sources/whitelist.json' whitelist = [] with open(filepath) as json_file: data = json.load(json_file) whitelist = data["domains"] return ",".join(whitelist) def main(): domain_blacklist = 'castanet.net,calculatedriskblog.com' domain_whitelist = get_whitelist() query_string = 'Venezuela Crisis 2019' filename = 'venezuela' results_filename = filename + '-newsapi-results' articles_filename = filename + '-articles' start_time = time.time() search_results = search_articles(query_string, domain_blacklist, domain_whitelist) writeToJSONFile('newsapi-results', results_filename, search_results) end_time = time.time() newsapi_query_duration = (end_time - start_time) print(len(search_results['articles']), ' articles retrieved.') print('time to get query results: ' + str(newsapi_query_duration) + 's') articles = [] start_time = time.time() articles = list(map(add_text_and_format, search_results['articles'])) articles = list(filter(None, articles)) end_time = time.time() article_download_duration = (end_time - start_time) print(len(articles), ' successfully processed') print('time to download articles: ' + str(article_download_duration) + 's') writeToJSONFile('scraped-articles', articles_filename, articles) print('total results: ' + str(search_results['totalResults'])) print('len of articles: ', len(articles)) main() # print(get_whitelist())
Markdown
UTF-8
18,120
2.78125
3
[ "MIT" ]
permissive
--- templateKey: blog-post title: California Defamation Law date: 2019-03-08T15:04:10.000Z description: California defamation law consists of statutes and case law. Defamation law in California may include libel, slander, false light, intereference with business relations, and other torts. tags: - California defamation law - California reputaion laws --- ![California Defamation Law](/img/california.jpg) Below, we’ll take a look into **California defamation laws**, including California statutes as well as California case law regarding reputation offenses, as decided by the California Courts. This page will continue to be updated as important cases are decided by the California Courts and as the California Legislature enacts relevant legislation. Our focus will be on how California defamation laws apply when residents of California are the victims or the perpetrators of defamation on the Internet. ## California Defamation Statutes **Calififornia Civil Code DIVISION 1. PERSONS [38 - 86] ( Heading of Division 1 amended by Stats. 1988, Ch. 160, Sec. 12. ) PART 2. PERSONAL RIGHTS [43 - 53.7] ( Part 2 enacted 1872. )** **44** Defamation is effected by either of the following: (a) Libel. (b) Slander. **45** Libel is a false and unprivileged publication by writing, printing, picture, effigy, or other fixed representation to the eye, which exposes any person to hatred, contempt, ridicule, or obloquy, or which causes him to be shunned or avoided, or which has a tendency to injure him in his occupation. **45a** A libel which is defamatory of the plaintiff without the necessity of explanatory matter, such as an inducement, innuendo or other extrinsic fact, is said to be a libel on its face. Defamatory language not libelous on its face is not actionable unless the plaintiff alleges and proves that he has suffered special damage as a proximate result thereof. Special damage is defined in Section 48a of this code. **46** Slander is a false and unprivileged publication, orally uttered, and also communications by radio or any mechanical or other means which: 1. Charges any person with crime, or with having been indicted, convicted, or punished for crime; 2. Imputes in him the present existence of an infectious, contagious, or loathsome disease; 3. Tends directly to injure him in respect to his office, profession, trade or business, either by imputing to him general disqualification in those respects which the office or other occupation peculiarly requires, or by imputing something with reference to his office, profession, trade, or business that has a natural tendency to lessen its profits; 4. Imputes to him impotence or a want of chastity; or 5. Which, by natural consequence, causes actual damage. **47** A privileged publication or broadcast is one made: (a) In the proper discharge of an official duty. (b) In any (1) legislative proceeding, (2) judicial proceeding, (3) in any other official proceeding authorized by law, or (4) in the initiation or course of any other proceeding authorized by law and reviewable pursuant to Chapter 2 (commencing with Section 1084) of Title 1 of Part 3 of the Code of Civil Procedure, except as follows: (1) An allegation or averment contained in any pleading or affidavit filed in an action for marital dissolution or legal separation made of or concerning a person by or against whom no affirmative relief is prayed in the action shall not be a privileged publication or broadcast as to the person making the allegation or averment within the meaning of this section unless the pleading is verified or affidavit sworn to, and is made without malice, by one having reasonable and probable cause for believing the truth of the allegation or averment and unless the allegation or averment is material and relevant to the issues in the action. (2) This subdivision does not make privileged any communication made in furtherance of an act of intentional destruction or alteration of physical evidence undertaken for the purpose of depriving a party to litigation of the use of that evidence, whether or not the content of the communication is the subject of a subsequent publication or broadcast which is privileged pursuant to this section. As used in this paragraph, “physical evidence” means evidence specified in Section 250 of the Evidence Code or evidence that is property of any type specified in Chapter 14 (commencing with Section 2031.010) of Title 4 of Part 4 of the Code of Civil Procedure. (3) This subdivision does not make privileged any communication made in a judicial proceeding knowingly concealing the existence of an insurance policy or policies. (4) A recorded lis pendens is not a privileged publication unless it identifies an action previously filed with a court of competent jurisdiction which affects the title or right of possession of real property, as authorized or required by law. (c) In a communication, without malice, to a person interested therein, (1) by one who is also interested, or (2) by one who stands in such a relation to the person interested as to afford a reasonable ground for supposing the motive for the communication to be innocent, or (3) who is requested by the person interested to give the information. This subdivision applies to and includes a communication concerning the job performance or qualifications of an applicant for employment, based upon credible evidence, made without malice, by a current or former employer of the applicant to, and upon request of, one whom the employer reasonably believes is a prospective employer of the applicant. This subdivision applies to and includes a complaint of sexual harassment by an employee, without malice, to an employer based upon credible evidence and communications between the employer and interested persons, without malice, regarding a complaint of sexual harassment. This subdivision authorizes a current or former employer, or the employer’s agent, to answer, without malice, whether or not the employer would rehire a current or former employee and whether the decision to not rehire is based upon the employer’s determination that the former employee engaged in sexual harassment. This subdivision shall not apply to a communication concerning the speech or activities of an applicant for employment if the speech or activities are constitutionally protected, or otherwise protected by Section 527.3 of the Code of Civil Procedure or any other provision of law. (d) (1) By a fair and true report in, or a communication to, a public journal, of (A) a judicial, (B) legislative, or (C) other public official proceeding, or (D) of anything said in the course thereof, or (E) of a verified charge or complaint made by any person to a public official, upon which complaint a warrant has been issued. (2) Nothing in paragraph (1) shall make privileged any communication to a public journal that does any of the following: (A) Violates Rule 5-120 of the State Bar Rules of Professional Conduct. (B) Breaches a court order. (C) Violates any requirement of confidentiality imposed by law. (e) By a fair and true report of (1) the proceedings of a public meeting, if the meeting was lawfully convened for a lawful purpose and open to the public, or (2) the publication of the matter complained of was for the public benefit. **47.5** Notwithstanding Section 47, a peace officer may bring an action for defamation against an individual who has filed a complaint with that officer’s employing agency alleging misconduct, criminal conduct, or incompetence, if that complaint is false, the complaint was made with knowledge that it was false and that it was made with spite, hatred, or ill will. Knowledge that the complaint was false may be proved by a showing that the complainant had no reasonable grounds to believe the statement was true and that the complainant exhibited a reckless disregard for ascertaining the truth. **48** In the case provided for in subdivision (c) of Section 47, malice is not inferred from the communication. **48a** (a) In any action for damages for the publication of a libel in a daily or weekly news publication, or of a slander by radio broadcast, plaintiff shall only recover special damages unless a correction is demanded and is not published or broadcast, as provided in this section. Plaintiff shall serve upon the publisher at the place of publication, or broadcaster at the place of broadcast, a written notice specifying the statements claimed to be libelous and demanding that those statements be corrected. The notice and demand must be served within 20 days after knowledge of the publication or broadcast of the statements claimed to be libelous. (b) If a correction is demanded within 20 days and is not published or broadcast in substantially as conspicuous a manner in the same daily or weekly news publication, or on the same broadcasting station as were the statements claimed to be libelous, in a regular issue thereof published or broadcast within three weeks after service, plaintiff, if he or she pleads and proves notice, demand and failure to correct, and if his or her cause of action is maintained, may recover general, special, and exemplary damages. Exemplary damages shall not be recovered unless the plaintiff proves that defendant made the publication or broadcast with actual malice and then only in the discretion of the court or jury, and actual malice shall not be inferred or presumed from the publication or broadcast. (c) A correction published or broadcast in substantially as conspicuous a manner in the daily or weekly news publication, or on the broadcasting station as the statements claimed in the complaint to be libelous, before receipt of a demand for correction, shall be of the same force and effect as though the correction had been published or broadcast within three weeks after a demand for correction. (d) As used in this section, the following definitions shall apply: (1) “General damages” means damages for loss of reputation, shame, mortification, and hurt feelings. (2) “Special damages” means all damages that plaintiff alleges and proves that he or she has suffered in respect to his or her property, business, trade, profession, or occupation, including the amounts of money the plaintiff alleges and proves he or she has expended as a result of the alleged libel, and no other. (3) “Exemplary damages” means damages that may in the discretion of the court or jury be recovered in addition to general and special damages for the sake of example and by way of punishing a defendant who has made the publication or broadcast with actual malice. (4) “Actual malice” means that state of mind arising from hatred or ill will toward the plaintiff; provided, however, that a state of mind occasioned by a good faith belief on the part of the defendant in the truth of the libelous publication or broadcast at the time it is published or broadcast shall not constitute actual malice. (5) “Daily or weekly news publication” means a publication, either in print or electronic form, that contains news on matters of public concern and that publishes at least once a week. **48.5** (1) The owner, licensee or operator of a visual or sound radio broadcasting station or network of stations, and the agents or employees of any such owner, licensee or operator, shall not be liable for any damages for any defamatory statement or matter published or uttered in or as a part of a visual or sound radio broadcast by one other than such owner, licensee or operator, or agent or employee thereof, if it shall be alleged and proved by such owner, licensee or operator, or agent or employee thereof, that such owner, licensee or operator, or such agent or employee, has exercised due care to prevent the publication or utterance of such statement or matter in such broadcast. (2) If any defamatory statement or matter is published or uttered in or as a part of a broadcast over the facilities of a network of visual or sound radio broadcasting stations, the owner, licensee or operator of any such station, or network of stations, and the agents or employees thereof, other than the owner, licensee or operator of the station, or network of stations, originating such broadcast, and the agents or employees thereof, shall in no event be liable for any damages for any such defamatory statement or matter. (3) In no event, however, shall any owner, licensee or operator of such station or network of stations, or the agents or employees thereof, be liable for any damages for any defamatory statement or matter published or uttered, by one other than such owner, licensee or operator, or agent or employee thereof, in or as a part of a visual or sound radio broadcast by or on behalf of any candidate for public office, which broadcast cannot be censored by reason of the provisions of federal statute or regulation of the Federal Communications Commission. (4) As used in this Part 2, the terms “radio,” “radio broadcast,” and “broadcast,” are defined to include both visual and sound radio broadcasting. (5) Nothing in this section contained shall deprive any such owner, licensee or operator, or the agent or employee thereof, of any rights under any other section of this Part 2. **48.7** (a) No person charged by indictment, information, or other accusatory pleading of child abuse may bring a civil libel or slander action against the minor, the parent or guardian of the minor, or any witness, based upon any statements made by the minor, parent or guardian, or witness which are reasonably believed to be in furtherance of the prosecution of the criminal charges while the charges are pending before a trial court. The charges are not pending within the meaning of this section after dismissal, after pronouncement of judgment, or during an appeal from a judgment. Any applicable statute of limitations shall be tolled during the period that such charges are pending before a trial court. (b) Whenever any complaint for libel or slander is filed which is subject to the provisions of this section, no responsive pleading shall be required to be filed until 30 days after the end of the period set forth in subdivision (a). (c) Every complaint for libel or slander based on a statement that the plaintiff committed an act of child abuse shall state that the complaint is not barred by subdivision (a). A failure to include that statement shall be grounds for a demurrer. (d) Whenever a demurrer against a complaint for libel or slander is sustained on the basis that the complaint was filed in violation of this section, attorney’s fees and costs shall be awarded to the prevailing party. (e) Whenever a prosecutor is informed by a minor, parent, guardian, or witness that a complaint against one of those persons has been filed which may be subject to the provisions of this section, the prosecutor shall provide that person with a copy of this section. (f) As used in this section, child abuse has the meaning set forth in Section 11165 of the Penal Code. **48.8** (a) A communication by any person to a school principal, or a communication by a student attending the school to the student’s teacher or to a school counselor or school nurse and any report of that communication to the school principal, stating that a specific student or other specified person has made a threat to commit violence or potential violence on the school grounds involving the use of a firearm or other deadly or dangerous weapon, is a communication on a matter of public concern and is subject to liability in defamation only upon a showing by clear and convincing evidence that the communication or report was made with knowledge of its falsity or with reckless disregard for the truth or falsity of the communication. Where punitive damages are alleged, the provisions of Section 3294 shall also apply. **48.9** (a) An organization which sponsors or conducts an anonymous witness program, and its employees and agents, shall not be liable in a civil action for damages resulting from its receipt of information regarding possible criminal activity or from dissemination of that information to a law enforcement agency. (b) The immunity provided by this section shall apply to any civil action for damages, including, but not limited to, a defamation action or an action for damages resulting from retaliation against a person who provided information. (c) The immunity provided by this section shall not apply in any of the following instances: (1) The information was disseminated with actual knowledge that it was false. (2) The name of the provider of the information was disseminated without that person’s authorization and the dissemination was not required by law. (3) The name of the provider of information was obtained and the provider was not informed by the organization that the disclosure of his or her name may be required by law. (d) As used in this section, an “anonymous witness program” means a program whereby information relating to alleged criminal activity is received from persons, whose names are not released without their authorization unless required by law, and disseminated to law enforcement agencies. ## California Defamation Cases Case providing the interpretation of California defamation statutes and common law when a defendant files a Motion to Quash a subpoena seeking the identity of the author of allegedly defamatory content online. [In re Verifone](http://www.cyberdefamationlawyer.com/internet-defamation-subpoena-quash-case/) ## Additional California Defamation Law Resources Additional information related to defamation laws as well as consultation for California attorneys related to investigations of defamation for California clients can be obtained by contacting patent attorney, digital forensics, and cyber security expert [Domingo J Rivera](http://www.icyberlaw.com) of AVM Technology, a consulting firm that assists attorneys and defamation victims uncover the culprits of cyber defamation in California and throughout the U.S., Canada, and Europe.
Ruby
UTF-8
2,258
2.796875
3
[]
no_license
#!/usr/bin/ruby require 'yaml' require 'tzinfo' load 'YahooGroupModerator.rb' load 'GraphicsHelper.rb' class Text_Helper def print_text_report(title,date,data) report = File.open(title,'w') report.puts('============ Yahoo Groups Administration Report ============') report.puts("\n\n") report.puts('Reporting Period: ' + date) report.puts('Total Moderators active this period: ' + data.size.to_s) num_msgs = 0.0 cum_avg = 0.0 data.each_value do |val| num_msgs += val.mesgs_approved cum_avg += val.mesgs_approved * val.avg_resp end report.puts('Total Messages approved this period: ' + num_msgs.to_s) report.puts('Total Avg approval time (minutes): ' + ((cum_avg/num_msgs)/60.0).to_s) report.puts("\n***************************\n") report.puts("Individual Moderator Report\n") report.puts("***************************\n\n") data.each_value do |val| report.puts('Moderator name: ' + val.name.to_s) report.puts('Messages approved: ' + val.mesgs_approved.to_s) report.puts('Fastest response: ' + val.fast_resp.to_s) report.puts('Slowest response: ' + val.slow_resp.to_s) report.puts('Average response: ' + val.avg_resp.to_s) report.puts("\n") end report.puts("\n\n") report.puts('============ Report Generated: ' + Time.now.to_s + ' ============') report.close end end #raise "Error: invalid args. Want: filename_to_yaml" unless ARGV.length == 1 if ARGV.length == 1 filename = ARGV[0] else filename = 'yahoo_group[ClubPCR]_moderation_stats for 2012-05-01 to 2012-05-08.yaml' end puts filename group_name = filename.slice(/\[(.*)\]/) group_name = $1 results = YAML.load_file(filename) dates = filename.split.slice(2,3).join(' ').gsub('.yaml','') graphics = Graphics_Helper.new graphics.print_total_mesgs_moderated_by_mod('Totals for ' + dates,results) graphics.print_response_times('Response times for ' + dates,results) graphics.print_response_by_day(group_name,'Response of admins by day', results) graphics.print_response_by_hour(group_name, 'Response of admins by hour', results) text = Text_Helper.new text.print_text_report('[' + group_name + ']Yahoo Groups Report' + dates + '.txt',dates,results)
SQL
UTF-8
5,069
2.703125
3
[]
no_license
CREATE OR REPLACE PACKAGE EcBp_Flowline_Theoretical IS /**************************************************************** ** Package : EcBp_Flowline_Theoretical, header part ** ** $Revision: 1.11 $ ** ** Purpose : Calculates theoretical flowline values (rates etc) ** ** Documentation : www.energy-components.com ** ** Created : ** ** Modification history: ** ** Date Whom Change description: ** ------ ----- -------------------------------------- ** 14.04.14 leongwen ECPD-22866: Applied the calculation methods for multiple phases Flowline Performance Curve based on the similar logic from Well Performance Curve. ** 27.09.16 keskaash ECPD-35756: Added function getSubseaWellMassRateDay and findHCMassDay *****************************************************************/ FUNCTION getCurveRate( p_object_id flowline.object_id%TYPE, p_daytime DATE, p_phase VARCHAR2, p_curve_purpose VARCHAR2, p_choke_size NUMBER, p_flwl_press NUMBER, p_flwl_temp NUMBER, p_flwl_usc_press NUMBER, p_flwl_usc_temp NUMBER, p_flwl_dsc_press NUMBER, p_flwl_dsc_temp NUMBER, p_mpm_oil_rate NUMBER, p_mpm_gas_rate NUMBER, p_mpm_water_rate NUMBER, p_mpm_cond_rate NUMBER, p_pressure_zone VARCHAR2 DEFAULT 'NORMAL', p_calc_method VARCHAR2 DEFAULT NULL) RETURN NUMBER; -- FUNCTION getOilStdRateDay( p_object_id flowline.object_id%TYPE, p_daytime DATE, p_calc_method VARCHAR2 DEFAULT NULL) RETURN NUMBER; -- FUNCTION getGasLiftStdRateDay( p_object_id flowline.object_id%TYPE, p_daytime DATE, p_gas_lift_method VARCHAR2 default NULL) RETURN NUMBER; -- FUNCTION getGasStdRateDay( p_object_id flowline.object_id%TYPE, p_daytime DATE, p_calc_method VARCHAR2 DEFAULT NULL) RETURN NUMBER; -- FUNCTION getWatStdRateDay( p_object_id flowline.object_id%TYPE, p_daytime DATE, p_calc_method VARCHAR2 DEFAULT NULL) RETURN NUMBER; -- FUNCTION getCondStdRateDay( p_object_id flowline.object_id%TYPE, p_daytime DATE, p_calc_method VARCHAR2 DEFAULT NULL) RETURN NUMBER; -- FUNCTION getInjectedStdRateDay( p_object_id flowline.object_id%TYPE, p_inj_type VARCHAR2, p_daytime DATE, p_calc_inj_method VARCHAR2 DEFAULT NULL) RETURN NUMBER; -- FUNCTION findOilMassDay( p_object_id flowline.object_id%TYPE, p_daytime DATE, p_calc_method VARCHAR2 DEFAULT NULL) RETURN NUMBER; -- FUNCTION findGasMassDay( p_object_id flowline.object_id%TYPE, p_daytime DATE, p_calc_method VARCHAR2 DEFAULT NULL) RETURN NUMBER; -- FUNCTION findWaterMassDay( p_object_id flowline.object_id%TYPE, p_daytime DATE, p_calc_method VARCHAR2 DEFAULT NULL) RETURN NUMBER; -- FUNCTION findCondMassDay( p_object_id flowline.object_id%TYPE, p_daytime DATE, p_calc_method VARCHAR2 DEFAULT NULL) RETURN NUMBER; -- FUNCTION findHCMassDay( p_object_id flowline.object_id%TYPE, p_daytime DATE, p_calc_method VARCHAR2 DEFAULT NULL) RETURN NUMBER; -- FUNCTION getOilStdVolSubDay( p_object_id VARCHAR2, p_daytime DATE, p_calc_method VARCHAR2) RETURN NUMBER; -- FUNCTION getGasStdVolSubDay( p_object_id VARCHAR2, p_daytime DATE, p_calc_method VARCHAR2) RETURN NUMBER; -- FUNCTION getWatStdVolSubDay( p_object_id VARCHAR2, p_daytime DATE, p_calc_method VARCHAR2) RETURN NUMBER; -- FUNCTION getCondStdVolSubDay( p_object_id VARCHAR2, p_daytime DATE, p_calc_method VARCHAR2) RETURN NUMBER; -- FUNCTION findWaterCutPct( p_object_id VARCHAR2, p_daytime DATE, p_calc_method VARCHAR2 DEFAULT NULL, p_class_name VARCHAR2 DEFAULT NULL, p_result_no NUMBER DEFAULT NULL) RETURN NUMBER; -- FUNCTION findCondGasRatio( p_object_id VARCHAR2, p_daytime DATE, p_calc_method VARCHAR2 DEFAULT NULL, p_class_name VARCHAR2 DEFAULT NULL) RETURN NUMBER; -- FUNCTION findGasOilRatio( p_object_id VARCHAR2, p_daytime DATE, p_calc_method VARCHAR2 DEFAULT NULL, p_class_name VARCHAR2 DEFAULT NULL) RETURN NUMBER; -- FUNCTION findWaterGasRatio( p_object_id VARCHAR2, p_daytime DATE, p_calc_method VARCHAR2 DEFAULT NULL, p_class_name VARCHAR2 DEFAULT NULL) RETURN NUMBER; -- FUNCTION findWetDryFactor( p_object_id VARCHAR2, p_daytime DATE, p_calc_method VARCHAR2 DEFAULT NULL ) RETURN NUMBER; -- FUNCTION getAllocCondVolDay( p_flowline_id FLOWLINE.OBJECT_ID%TYPE, p_daytime DATE) RETURN NUMBER; -- FUNCTION getAllocGasVolDay( p_flowline_id FLOWLINE.OBJECT_ID%TYPE, p_daytime DATE) RETURN NUMBER; -- FUNCTION getAllocOilVolDay( p_flowline_id FLOWLINE.OBJECT_ID%TYPE, p_daytime DATE) RETURN NUMBER; -- FUNCTION getAllocWaterVolDay( p_flowline_id FLOWLINE.OBJECT_ID%TYPE, p_daytime DATE) RETURN NUMBER; FUNCTION getSubseaWellMassRateDay( p_object_id FLOWLINE.OBJECT_ID%TYPE, p_daytime DATE, p_phase VARCHAR2) RETURN NUMBER; END EcBp_Flowline_Theoretical;
Java
UTF-8
1,244
2.1875
2
[]
no_license
package net.aesircraft.ManaBags.Items; import java.util.logging.Level; import net.aesircraft.ManaBags.Config.Config; import net.aesircraft.ManaBags.ManaBags; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.Plugin; import org.getspout.spoutapi.SpoutManager; import org.getspout.spoutapi.inventory.SpoutItemStack; import org.getspout.spoutapi.inventory.SpoutShapedRecipe; import org.getspout.spoutapi.material.MaterialData; import org.getspout.spoutapi.material.item.GenericCustomItem; public class ManaCloth extends GenericCustomItem { public ManaCloth(Plugin plugin) { super(plugin, "Mana Cloth", Config.getManaClothTexture()); if (Config.getUseManaClothRecipe()){ RecipeCreator r=new RecipeCreator(); if (!r.setRecipe(this, Config.getManaClothRecipe())){ ManaBags.logger.log(Level.SEVERE, "[ManaCraft] Inproper Mana Cloth recipe, using default!"); } else{ return; } } ItemStack i = new SpoutItemStack(this, 1); SpoutShapedRecipe r = new SpoutShapedRecipe(i); r.shape("AAA", "BBB", "AAA"); r.setIngredient('A', ManaMaterial.manaThread); r.setIngredient('B', MaterialData.whiteWool); SpoutManager.getMaterialManager().registerSpoutRecipe(r); } }
Shell
UTF-8
937
3.890625
4
[]
no_license
#!/bin/bash # spawn.sh PIDS=$(pgrep sh $0) # Process IDs of the various instances of this script. P_array=( $PIDS ) # Put them in an array (why?). echo $PIDS # Show process IDs of parent and child processes. let "instances = ${#P_array[*]} - 1" # Count elements, less 1. # Why subtract 1? echo "$instances instance(s) of this script running." echo "[Hit Ctl-C to exit.]"; echo sleep 1 # Wait. sh $0 # Play it again, Sam. exit 0 # Not necessary; script will never get to here. # Why not? # After exiting with a Ctl-C, #+ do all the spawned instances of the script die? # If so, why? # Note: # ---- # Be careful not to run this script too long. # It will eventually eat up too many system resources. # Is having a script spawn multiple instances of itself #+ an advisable scripting technique. # Why or why not?
Java
UTF-8
9,243
1.90625
2
[]
no_license
package com.hongshi.wuliudidi.activity; import java.util.ArrayList; import java.util.List; import net.tsz.afinal.http.AjaxParams; import org.json.JSONException; import org.json.JSONObject; import com.alibaba.fastjson.JSON; import com.hongshi.wuliudidi.CommonRes; import com.hongshi.wuliudidi.DidiApp; import com.hongshi.wuliudidi.R; import com.hongshi.wuliudidi.adapter.DriverAdapter; import com.hongshi.wuliudidi.dialog.ListItemDeletingDialog; import com.hongshi.wuliudidi.impl.ChildAfinalHttpCallBack; import com.hongshi.wuliudidi.model.DriverBookListVO; import com.hongshi.wuliudidi.model.DriverModel; import com.hongshi.wuliudidi.params.GloableParams; import com.hongshi.wuliudidi.utils.ActivityManager; import com.hongshi.wuliudidi.utils.ToastUtil; import com.hongshi.wuliudidi.utils.UploadUtil; import com.hongshi.wuliudidi.view.DiDiTitleView; import com.hongshi.wuliudidi.view.NullDataView; import com.umeng.analytics.MobclickAgent; import android.annotation.SuppressLint; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.Button; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; /** * @author huiyuan */ public class ChooseDriverActivity extends Activity implements OnClickListener{ private List<DriverBookListVO> mDriverList; private ListView mDriverListView; private DriverAdapter mAdapter; private DiDiTitleView mTitle; private TextView mAddDriver; private final String get_driver_list = GloableParams.HOST + "carrier/mydrivers/listall.do?"; private final String driver_delete = GloableParams.HOST + "carrier/mydrivers/delete.do?"; private LinearLayout driverListLayout; private NullDataView mNullDataView; private DriverListType mType; private ListItemDeletingDialog mDeletingDialog; @Override protected void onPause() { super.onPause(); MobclickAgent.onPause(this); MobclickAgent.onPageEnd("ChooseDriverActivity"); } @Override protected void onResume() { super.onResume(); MobclickAgent.onResume(this); MobclickAgent.onPageStart("ChooseDriverActivity"); } private BroadcastReceiver mRefreshBroadcastReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(CommonRes.DriverModify)) { getDriverList(); } } }; @SuppressLint("HandlerLeak") private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case CommonRes.DELETE_DRIVER: String deletedDriverId; try { deletedDriverId = msg.getData().getString("itemId"); } catch (Exception e) { ToastUtil.show(ChooseDriverActivity.this, "删除失败"); return; } AjaxParams params = new AjaxParams(); params.put("id", deletedDriverId); DidiApp.getHttpManager().sessionPost(ChooseDriverActivity.this, driver_delete, params, new ChildAfinalHttpCallBack() { @Override public void onFailure(String errCode, String errMsg, Boolean errSerious) { ToastUtil.show(ChooseDriverActivity.this, "删除失败"); } @Override public void data(String t) { getDriverList(); } }); default: break; } } }; @SuppressLint("ResourceAsColor") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityManager.getInstance().addActivity(this); setContentView(R.layout.choose_driver_activity); initViews(); getDriverList(); } private void initViews(){ try { mType = DriverListType.valueOf(getIntent().getExtras().getString("driverListType")); } catch (Exception e) { mType = DriverListType.ChooseDriver; } driverListLayout = (LinearLayout) findViewById(R.id.driver_list_layout); mDriverListView = (ListView) findViewById(R.id.driver_list); mNullDataView = (NullDataView) findViewById(R.id.no_data_layout); mNullDataView.setInfoHint("您还没有司机"); mNullDataView.setInfo("请添加新司机"); Button button = mNullDataView.getInfoImage(); button.setId(R.id.button_id); button.setOnClickListener(this); button.setVisibility(View.VISIBLE); button.setBackgroundResource(R.drawable.solid_btn_style); button.setText("添加司机"); button.setTextColor(getResources().getColor(R.color.white)); mTitle = (DiDiTitleView) findViewById(R.id.title); if(mType == DriverListType.ChooseDriver){ mTitle.setTitle(getResources().getString(R.string.choose_driver)); }else if(mType == DriverListType.MyDriver){ mTitle.setTitle(getResources().getString(R.string.my_team_info)); } mTitle.setBack(ChooseDriverActivity.this); mAddDriver = mTitle.getRightTextView(); mAddDriver.setId(R.id.add_id); mAddDriver.setText(getResources().getString(R.string.add)); mAddDriver.setOnClickListener(this); if(mType == DriverListType.ChooseDriver){ mDriverListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DriverBookListVO model = mDriverList.get(position); Intent it = new Intent(); it.putExtra("phoneNumber", model.getCellphone()); it.putExtra("driverBookId", model.getDriverBookId()); setResult(Activity.RESULT_OK, it); finish(); } }); }else if(mType == DriverListType.MyDriver){ mDriverListView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { DriverBookListVO model = mDriverList.get(position); Intent it = new Intent(ChooseDriverActivity.this, DriverInfoActivity.class); it.putExtra("driverBookId", model.getDriverBookId()); it.putExtra("driverId", model.getDriverId()); it.putExtra("isOwner",model.isOwner()); startActivity(it); } }); mDriverListView.setOnItemLongClickListener(new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { if(mDriverList.get(position).getDriverId().equals(CommonRes.UserId)){ ToastUtil.show(ChooseDriverActivity.this, "不能删除车主本人"); return true; } mDeletingDialog = new ListItemDeletingDialog(ChooseDriverActivity.this, R.style.data_filling_dialog, mHandler); mDeletingDialog.setCanceledOnTouchOutside(true); mDeletingDialog.setText("删除所选司机", "取消"); mDeletingDialog.setItemId(mDriverList.get(position).getDriverBookId()); mDeletingDialog.setMsgNum(CommonRes.DELETE_DRIVER); mDeletingDialog.getExampleImg().setVisibility(View.GONE); UploadUtil.setAnimation(mDeletingDialog, CommonRes.TYPE_BOTTOM, false); mDeletingDialog.show(); return true; } }); } mDriverList = new ArrayList<DriverBookListVO>(); //注册刷新广播 IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(CommonRes.DriverModify); registerReceiver(mRefreshBroadcastReceiver, intentFilter); } private void getDriverList(){ AjaxParams params = new AjaxParams(); DidiApp.getHttpManager().sessionPost(ChooseDriverActivity.this, get_driver_list, params, new ChildAfinalHttpCallBack() { @Override public void onFailure(String errCode, String errMsg, Boolean errSerious) { driverListLayout.setVisibility(View.GONE); mNullDataView.setVisibility(View.VISIBLE); } @Override public void data(String t) { try { Log.d("huiyuan","司机信息 = " + t); JSONObject jsonObject = new JSONObject(t); String all = jsonObject.getString("body"); mDriverList = JSON.parseArray(all,DriverBookListVO.class); if(mDriverList.size() > 0){ mAdapter = new DriverAdapter(ChooseDriverActivity.this, mDriverList); mDriverListView.setAdapter(mAdapter); driverListLayout.setVisibility(View.VISIBLE); mNullDataView.setVisibility(View.GONE); mAddDriver.setVisibility(View.VISIBLE); }else{ driverListLayout.setVisibility(View.GONE); mNullDataView.setVisibility(View.VISIBLE); mAddDriver.setVisibility(View.GONE); } } catch (JSONException e) { e.printStackTrace(); } } }); } @Override public void onClick(View v) { switch(v.getId()){ case R.id.add_id: case R.id.button_id: Intent addDriverIntent = new Intent(ChooseDriverActivity.this,InvatePlayerActivity.class); addDriverIntent.putExtra("inviteType", "addDriver"); startActivity(addDriverIntent); break; default: break; } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mRefreshBroadcastReceiver); } public enum DriverListType{ ChooseDriver, MyDriver; } }
JavaScript
UTF-8
2,087
2.6875
3
[]
no_license
import { transformDate } from "../../script/utils/transformDate.js"; export class CommitCard { constructor(name, email, date, message, avatar_url) { this.name = name; this.email = email; this.date = date; this.message = message; this.avatar_url = avatar_url; this.commitElement = this._create(); } _create(name, email, date, message, avatar_url) { const commitContainer = document.createElement('div'); commitContainer.classList.add('slide'); commitContainer.classList.add('swiper-slide'); const commitDate = document.createElement('p'); commitDate.classList.add('slide__date'); commitDate.textContent = transformDate(this.date); commitContainer.appendChild(commitDate); const commitInfoBlock = document.createElement('div'); commitInfoBlock.classList.add('slide__info-block'); commitContainer.appendChild(commitInfoBlock); const commitIcon = document.createElement('img'); commitIcon.classList.add('slide__icon'); commitIcon.setAttribute('src', this.avatar_url); commitIcon.setAttribute('alt', 'аватар автора коммита'); commitInfoBlock.appendChild(commitIcon); const commitInfo = document.createElement('div'); commitInfo.classList.add('slide__info'); commitInfoBlock.appendChild(commitInfo); const commitName = document.createElement('h4'); commitName.classList.add('slide__name'); commitName.textContent = this.name; commitInfo.appendChild(commitName); const commitEmail = document.createElement('p'); commitEmail.classList.add('slide__email'); commitEmail.textContent = this.email; commitInfo.appendChild(commitEmail); const commitMessage = document.createElement('p'); commitMessage.classList.add('slide__text'); commitMessage.textContent = this.message; commitContainer.appendChild(commitMessage); return commitContainer; } }
C++
UTF-8
321
3.640625
4
[]
no_license
//displaying 5 students marks using function #include<iostream> using namespace std; void display(int mark[5]) int main() { int mark[5]={78,86,95,84,79}; display(mark); return 0; } void display(int mark[5]) { cout<<"5 students marks :"<<endl; for(int i=0 ;int i<=5 ;i++) { cout<<"student "<<i+1<<mark[i]; } }
Java
UTF-8
762
2.4375
2
[]
no_license
package com.bcd.fraud.bpmn.rule; import java.util.Calendar; import com.bcd.fraud.Transaction; public class CheckDatetimeRule extends FraudDetectionRule { public CheckDatetimeRule(Transaction transaction) { super(transaction); } @Override public void execute() { if (!isToday(getTransaction().getDateTime())) { trigger(); } } private boolean isToday(Calendar transactionDate) { if (transactionDate == null) { return false; } Calendar today = Calendar.getInstance(); return (transactionDate.get(Calendar.ERA) == today.get(Calendar.ERA) && transactionDate.get(Calendar.YEAR) == today.get(Calendar.YEAR) && transactionDate.get(Calendar.DAY_OF_YEAR) == today.get(Calendar.DAY_OF_YEAR)); } }
C
UTF-8
2,956
3.546875
4
[]
no_license
// program that computes P(O|M) for a given input utterance // the utterance must be entered as a sequence of acoustic vectors #include<stdio.h> #include<stdlib.h> #include "structs.h" #include "showgmm.h" #include "aposteriori.h" #include "loadconfig.h" #include "loadUtterance.h" #include "loadGMM.h" int main(int argc, char **argv) { struct mixture *l=NULL; // stores the elements of the GMM struct mixture *u=NULL; // stores the elements of the UBM int nGaussians; // number of gaussians in the mixture int nFrames; // number of frames in x int dim; // dimension of feature vectors int i,t; // counters double **x; // sequence of observation vectors double p; // P(O|M) for the GMM double g; // P(O|M) for the UBM char GMMFilename[512]; // file that stores the GMM char UBMFilename[512]; // file that stores the UBM char utteranceFilename[512]; // file with utterance to be verified // Reading arguments passed to the program if(argc != 2) { puts("\nUsage: gmm config.txt\n"); puts("where config.txt is a configuration file of the form:\n"); puts("Utterance=loc1.mel"); puts("GMM file=loc1.gmm"); puts("Number of Gaussians=2"); puts("Dimension of feature vectors=36"); puts("IMPORTANT: LEAVE A BLANK LINE AT THE END OF CONFIGURATION FILE!!!\n"); return 1; } else loadconfig(argv[1],&nGaussians,&dim,GMMFilename,UBMFilename,utteranceFilename); /* puts("Configuration settings:\n");*/ /* printf("Configuration file: %s\n",argv[1]);*/ /* printf("Number of Gaussians in the mixture: %d\n",nGaussians);*/ /* printf("Dimension of feature vectors: %d\n",dim);*/ /* printf("GMM file: %s\n",GMMFilename);*/ /* printf("UBM file: %s\n",UBMFilename);*/ /* printf("File with utterance: %s\n\n",utteranceFilename);*/ // Loading GMM (allocates memory for struct l=>MUST DEALLOCATE AT THE END OF THIS FUNCTION!) loadGMM(nGaussians,dim,&l,GMMFilename); // Loading UBM (allocates memory for struct u=>MUST DEALLOCATE AT THE END OF THIS FUNCTION!) loadGMM(nGaussians,dim,&u,UBMFilename); // Showing GMM in the screen showgmm(l,nGaussians,dim); // Showing UBM in the screen /* showgmm(u,nGaussians,dim); */ // Reading utterance to be verified loadUtterance(utteranceFilename,dim,&nFrames,&x); /* printf("Number of frames: %d\n",nFrames); for (t=0;t<nFrames;t++) { for(i=0;i<dim;i++) printf("%f\t",x[t][i]); puts(" "); } */ p = aposteriori(x,dim,nFrames,l,nGaussians); g = aposteriori(x,dim,nFrames,u,nGaussians); //printf("P(O|GMM)=%f\n",p); // printf("P(O|UBM)=%f\n",g); // printf("P(O|M)=%f\n",p-g); printf("%f\n",p-g); // Deallocating memory // GMM for (i=0;i<nGaussians;i++) { free(l[i].m); free(l[i].s); } free(l); // UBM for (i=0;i<nGaussians;i++) { free(u[i].m); free(u[i].s); } free(u); // utterance for (t=0;t<nFrames;t++) free(x[t]); free(x); return 0; }
Markdown
UTF-8
11,233
2.921875
3
[ "Apache-2.0" ]
permissive
# Cascading DropDownList in ASP.Net MVC ## Requires - Visual Studio 2010 ## License - Apache License, Version 2.0 ## Technologies - ASP.NET MVC - jQuery - ASP.NET MVC 3 - ASP.NET MVC 4 ## Topics - User Interface - Web Services ## Updated - 01/09/2012 ## Description <h1>Introduction</h1> <p>This sample shows&nbsp;how to implement cascading drop down lists in ASP.Net MVC.&nbsp; The user is presented with a list of countries. Once a country is selected, a new drop down list is displayed with the states in the selected country.</p> <p>&nbsp;</p> <p><img src="48388-1st.png" alt="" width="591" height="458"></p> <p>After selecting the Country, the State Drop Down List Box appears, populated with the Sates from the country you selected.</p> <p><img src="48389-canada.png" alt="" width="595" height="464"></p> <p>Selecting a State displays the Submit Button.</p> <p><img src="48390-state.png" alt="" width="603" height="471"></p> <p>Submitting your selection shows the Country and State you selected.</p> <p><img src="48391-submit.png" alt="" width="594" height="464"></p> <p>If JavaScrip is disable, You get a message <strong>This site requires JavaScript</strong>.</p> <p>That message is delivered with the new <a href="http://dev.w3.org/html5/spec-author-view/the-noscript-element.html"> HTML5&nbsp; <br> &lt;noscript&gt; element</a> in the <em>Views\Shared\_Layout.cshtml</em> <br> file.</p> <pre class="code"> <span style="color:blue">&lt;</span><span style="color:maroon">noscript</span><span style="color:blue">&gt; &lt;</span><span style="color:maroon">div</span><span style="color:blue">&gt; &lt;</span><span style="color:maroon">h2</span><span style="color:blue">&gt;</span>This site requires JavaScript<span style="color:blue">&lt;/</span><span style="color:maroon">h2</span><span style="color:blue">&gt; &lt;/</span><span style="color:maroon">div</span><span style="color:blue">&gt; &lt;/</span><span style="color:maroon">noscript</span><span style="color:blue">&gt; </span></pre> <p>I&rsquo;ve modified the <em>Site.css</em> file and set the main ID to not <br> display.</p> <pre class="code"><span style="color:maroon">#main </span>{ <span style="color:red">display</span>: <span style="color:blue">none</span>; <span style="color:red">padding</span>: <span style="color:blue">30px 30px 15px 30px</span>; } Browsers that have JavaScript enabled run <em>Scripts\myReady.js</em>, which shows the DOM element with ID main.</pre> <pre class="code">$(<span style="color:blue">function </span>() { $(<span style="color:maroon">'#main'</span>).show(); });</pre> <pre class="code"><p>The <strong>IndexDDL</strong> action method creates a <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.selectlist.aspx">SelectList</a> <br>of countries, stores it in the <a href="http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp.net-mvc-3-applications">ViewBag</a> <br>and passes it to the <strong>IndexDDL</strong> view.</p> <pre class="code"><span style="color:blue">public </span><span style="color:#2b91af">SelectList </span>GetCountrySelectList() { <span style="color:blue">var </span>countries = <span style="color:#2b91af">Country</span>.GetCountries(); <span style="color:blue">return new </span><span style="color:#2b91af">SelectList</span>(countries.ToArray(), <span style="color:#a31515">&quot;Code&quot;</span>, <span style="color:#a31515">&quot;Name&quot;</span>); } <span style="color:blue">public </span><span style="color:#2b91af">ActionResult </span>IndexDDL() { ViewBag.Country = GetCountrySelectList(); <span style="color:blue">return </span>View(); }</pre> <br> <p>The <strong>IndexDDL</strong> view is shown below.</p> <br>&lt;!-- .style1 { background-color: #ffffff; } .style2 { background-color: #ffff00; } --&gt;<br> <pre class="code"><span class="style1" style="">@{</span><span style="background:yellow"><span class="style1"> </span></span><span class="style1"> ViewBag.Title = </span><span class="style1" style="color:#a31515">&quot;Classic Cascading DDL&quot;</span>;<span class="style1"> </span><span style="background:yellow">} @</span><span style="color:blue">using </span>(Html.BeginForm(<span style="color:#a31515">&quot;IndexDDL&quot;</span>, <span style="color:#a31515">&quot;Home&quot;</span>, <span style="color:#2b91af">FormMethod</span>.Post, <span style="color:blue">new </span>{ id = <span style="color:#a31515">&quot;CountryStateFormID&quot;</span>, data_stateListAction = @Url.Action(<span style="color:#a31515">&quot;StateList&quot;</span>) })) { <span style="color:blue">&lt;</span><span style="color:maroon">fieldset</span><span style="color:blue">&gt; &lt;</span><span style="color:maroon">legend</span><span style="color:blue">&gt;</span>Country/State<span style="color:blue">&lt;/</span><span style="color:maroon">legend</span><span style="color:blue">&gt; </span><span style="background:yellow">@</span><span class="style2">Html.DropDownList(</span><span class="style2" style="color:#a31515">&quot;Countries&quot;</span><span class="style2">, ViewBag.Country </span><span class="style2" style="color:blue">as </span><span class="style2" style="color:#2b91af">SelectList</span>,<span class="style2"> </span><span class="style2" style="color:#a31515">&quot;Select a Country&quot;</span><span class="style2">, </span><span class="style2" style="color:blue">new </span><span class="style2">{ id = </span><span style="color:#a31515">&quot;<span class="style2">CountriesID&quot; </span></span><span class="style2">})</span> <span style="color:blue">&lt;</span><span style="color:maroon">div </span><span style="color:red">id</span><span style="color:blue">=&quot;StatesDivID&quot; &gt; &lt;</span><span style="color:maroon">label </span><span style="color:red">for</span><span style="color:blue">=&quot;States&quot;&gt;</span>States<span style="color:blue">&lt;/</span><span style="color:maroon">label</span><span style="color:blue">&gt; &lt;</span><span style="color:maroon">select </span><span style="color:red">id</span><span style="color:blue">=&quot;StatesID&quot; </span><span style="color:red">name</span><span style="color:blue">=&quot;States&quot;&gt;&lt;/</span><span style="color:maroon">select</span><span style="color:blue">&gt; &lt;/</span><span style="color:maroon">div</span><span style="color:blue">&gt; &lt;</span><span style="color:maroon">p</span><span style="color:blue">&gt; &lt;</span><span style="color:maroon">input </span><span style="color:red">type</span><span style="color:blue">=&quot;submit&quot; </span><span style="color:red">value</span><span style="color:blue">=&quot;Submit&quot; </span><span style="color:red">id</span><span style="color:blue">=&quot;SubmitID&quot; /&gt; &lt;/</span><span style="color:maroon">p</span><span style="color:blue">&gt; &lt;/</span><span style="color:maroon">fieldset</span><span style="color:blue">&gt; </span>} <span style="color:blue">&lt;</span><span style="color:maroon">script </span><span style="color:red">src</span><span style="color:blue">=&quot;</span><span style="background:yellow">@</span><span style="color:blue">Url.Content(</span><span style="color:#a31515">&quot;~/Scripts/countryState.js&quot;</span><span style="color:blue">)&quot;&gt;&lt;/</span><span style="color:maroon">script</span><span style="color:blue">&gt; </span></pre> <br> <p>The Countries DropDownList has an ID <strong>CountriesID</strong> (shown in <br>yellow highlight above) which enable the <em>Scripts/countryState.js</em> script to hook up changes in the country selection (yellow highlight below). The <em>Scripts/countryState.js</em> file is shown below.</p> </pre> <div class="scriptcode"> <div class="pluginEditHolder" pluginCommand="mceScriptCode"> <div class="title"><span>JavaScript</span></div> <div class="pluginLinkHolder"><span class="pluginEditHolderLink">Edit</span>|<span class="pluginRemoveHolderLink">Remove</span></div> <span class="hidden">js</span> <div class="preview"> <pre class="js">$(<span class="js__operator">function</span>&nbsp;()&nbsp;<span class="js__brace">{</span>&nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;$(<span class="js__string">'#StatesDivID'</span>).hide();&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;$(<span class="js__string">'#SubmitID'</span>).hide();&nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;$(<span class="js__string">'#CountriesID'</span>).change(<span class="js__operator">function</span>&nbsp;()&nbsp;<span class="js__brace">{</span>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="js__statement">var</span>&nbsp;URL&nbsp;=&nbsp;$(<span class="js__string">'#CountryStateFormID'</span>).data(<span class="js__string">'stateListAction'</span>);&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$.getJSON(URL&nbsp;&#43;&nbsp;<span class="js__string">'/'</span>&nbsp;&#43;&nbsp;$(<span class="js__string">'#CountriesID'</span>).val(),&nbsp;<span class="js__operator">function</span>&nbsp;(data)&nbsp;<span class="js__brace">{</span>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="js__statement">var</span>&nbsp;items&nbsp;=&nbsp;<span class="js__string">'&lt;option&gt;Select&nbsp;a&nbsp;State&lt;/option&gt;'</span>;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$.each(data,&nbsp;<span class="js__operator">function</span>&nbsp;(i,&nbsp;state)&nbsp;<span class="js__brace">{</span>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;items&nbsp;&#43;=&nbsp;<span class="js__string">&quot;&lt;option&nbsp;value='&quot;</span>&nbsp;&#43;&nbsp;state.Value&nbsp;&#43;&nbsp;<span class="js__string">&quot;'&gt;&quot;</span>&nbsp;&#43;&nbsp;state.Text&nbsp;&#43;&nbsp;<span class="js__string">&quot;&lt;/option&gt;&quot;</span>;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="js__sl_comment">//&nbsp;state.Value&nbsp;cannot&nbsp;contain&nbsp;'&nbsp;character.&nbsp;We&nbsp;are&nbsp;OK&nbsp;because&nbsp;state.Value&nbsp;=&nbsp;cnt&#43;&#43;;</span>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="js__brace">}</span>);&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$(<span class="js__string">'#StatesID'</span>).html(items);&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$(<span class="js__string">'#StatesDivID'</span>).show();&nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="js__brace">}</span>);&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;<span class="js__brace">}</span>);&nbsp; &nbsp; &nbsp;&nbsp;&nbsp;&nbsp;$(<span class="js__string">'#StatesID'</span>).change(<span class="js__operator">function</span>&nbsp;()&nbsp;<span class="js__brace">{</span>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$(<span class="js__string">'#SubmitID'</span>).show();&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;<span class="js__brace">}</span>);&nbsp; <span class="js__brace">}</span>);</pre> </div> </div> </div>
Go
UTF-8
1,874
3.140625
3
[ "MIT" ]
permissive
package main import "testing" func TestIncrementMaliciousRequests(t *testing.T) { a := attacker{maliciousRequests: 1} a.incrementMaliciousRequests() if got := a.maliciousRequests; got != 2 { t.Errorf("Expecting 2 malicious requests, got %d.", got) } } func TestUpdateStatusCodes(t *testing.T) { a := attacker{statusCodes: []string{"200"}} a.updateStatusCodes("200") a.updateStatusCodes("400") if got := a.statusCodes; len(got) != 2 { t.Errorf("Expecting 2 status codes, got %d.", len(got)) } } func TestUpdateLastRequestShouldKeepMostRecentDateTime(t *testing.T) { a := attacker{lastRequest: "11/Mar/2019:12:36:29 +0100"} a.updateLastRequest("11/Mar/2019:12:36:28 +0100") if a.lastRequest != "11/Mar/2019:12:36:29 +0100" { t.Errorf("updateLastRequest should have kept the most recent date/time.") } a.updateLastRequest("11/Mar/2019:12:39:28 +0100") if a.lastRequest != "11/Mar/2019:12:39:28 +0100" { t.Errorf("updateLastRequest should have updated the lastRequest field with the most recent date/time.") } } func TestQueryIpApi(t *testing.T) { res := queryIpApi("172.217.18.174") expected := `{"as":"AS15169 Google LLC","city":"Frankfurt am Main","country":"Germany","countryCode":"DE","isp":"Google LLC","lat":50.1109,"lon":8.68213,"org":"Google LLC","query":"172.217.18.174","region":"HE","regionName":"Hesse","status":"success","timezone":"Europe/Berlin","zip":"60313"}` if string(res) != expected { t.Errorf("Error: got %s", res) } } func TestGeoLocateExistingIp(t *testing.T) { ip := "172.217.18.174" locInfo, _ := geoLocate(ip) if locInfo["as"] != "AS15169 Google LLC" { t.Errorf("Expecting AS15169 Google LLC, got %s.", locInfo["as"]) } } func TestGeoLocateReservedIp(t *testing.T) { ip := "127.0.0.1" _, err := geoLocate(ip) if err == nil { t.Errorf("Expecting geoLocate() to fail, got a positive response instead..") } }
Java
UTF-8
1,070
2.390625
2
[]
no_license
package pages; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; public class LoginPage extends BasePage { public LoginPage(WebDriver driver) { super(driver); } By userNameBy = By.id("email"); By passwordBy = By.id("password"); By loginButtonBy = By.id("loginButton"); By errorMessageField1 = By.xpath("//form[@id='loginForm']/div[1]/div[@class='errorMessage']/div[@class='errorText']"); By errorMessageField2 = By.xpath("//form[@id='loginForm']/div[2]/div[@class='errorMessage']/div[@class='errorText']"); public LoginPage logInToN11(String username, String password){ writeText(userNameBy, username); writeText(passwordBy, password); click(loginButtonBy); return this; } public LoginPage verifyErrorMessage1(String expectedText){ assertEquals(errorMessageField1, expectedText); return this; } public LoginPage verifyErrorMessage2(String expectedText){ assertEquals(errorMessageField2, expectedText); return this; } }