language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Python
UTF-8
1,517
2.578125
3
[]
no_license
import sys import re foods = [] ingrs = set() allergs = set() candidates = dict() rcandidates = dict() for line in sys.stdin: ingr, allerg = line.split(" (contains ") ingr = ingr.split(" ") allerg = allerg.split(", ") allerg[-1] = allerg[-1][:-2] foods.append((ingr, allerg)) allergs |= set(allerg) ingrs |= set(ingr) for x in ingr: candidates[x] = set(allerg) for x in allerg: rcandidates[x] = set(ingr) canbe = set() def solve(solution, candidates, rcandidates, used, foods): global canbe if len(rcandidates) == 0: assert len(used) == len(allergs) canbe |= set(solution.values()) print(":", solution) return allerg, ingrs = rcandidates.popitem() for ingr in ingrs: if ingr in used: continue solution[allerg] = ingr candidates_ = dict() for key,val in candidates.items(): if key != ingr: candidates_[key] = val - set([allerg]) rcandidates_ = dict((k,v - set([ingr])) for k,v in rcandidates.items()) foods_ = [] try: for fi, fa in foods: fi = set(fi) fa = set(fa) if allerg in fa: fi.remove(ingr) fa.remove(allerg) foods_.append((fi, fa)) except KeyError: continue sol = solve(solution, candidates_, rcandidates_, used | set([ingr]), foods_) # if sol: # return sol # print(candidates) # print(rcandidates) solve(dict(), candidates, rcandidates, set(), foods) print(canbe) print(ingrs - canbe) ret = 0 for food in foods: for ingr in food[0]: if ingr not in canbe: # print(ingr) ret += 1 print(ret) # print(sol)
TypeScript
UTF-8
1,305
2.953125
3
[ "MIT" ]
permissive
interface LatticeSecureRequest { // Message header header: LatticeMessageHeader; // Request data payload: LatticeSecureRequestPayload; } interface LatticeSecureRequestPayload { // Indicates whether this is a connect (0x01) or // encrypted (0x02) secure request // [uint8] requestType: LatticeSecureMsgType; // Request data // [connect = 65 bytes, encrypted = 1732] data: Buffer; } interface LatticeSecureConnectResponsePayload { // [214 bytes] data: Buffer; } interface LatticeSecureEncryptedResponsePayload { // Error code responseCode: LatticeResponseCode; // Response data // [3392 bytes] data: Buffer; } interface LatticeSecureConnectRequestPayloadData { // Public key corresponding to the static Client keypair // [65 bytes] pubkey: Buffer; } interface LatticeSecureEncryptedRequestPayloadData { // SHA256(sharedSecret).slice(0, 4) // [uint32] ephemeralId: number; // Encrypted data envelope // [1728 bytes] encryptedData: Buffer; } interface LatticeSecureDecryptedResponse { // ECDSA public key that should replace the client's ephemeral key // [65 bytes] ephemeralPub: Buffer; // Decrypted response data // [Variable size] data: Buffer; // Checksum on response data (ephemeralKey | data) // [uint32] checksum: number; }
C++
BIG5
1,114
3.125
3
[]
no_license
/*ҡG * qӱ誺dp(i)=dp(i-1)+dp(i-2)tܦӨ * ѩnOثeB * ]Adp(i,k)=q0iWLkBk * AӡAdp(i,k) = dp(i-1,k-1) + dp(i-2,k-1) * ]G@Ҥldp(3,2)q03WL2Bk * [|{Odp(2,1)+dp(1,1)AzѬOJMAn3SnWLB * bҼ{n1BF1β2ɭԡAp@ӦAWh@BĤT~|WLB */ #include<bits/stdc++.h> #define endl '\n' #define maxn 1001 #define MOD_N 1000000009 using namespace std; int n, k , dp[maxn][maxn]; int main(){ ios::sync_with_stdio(false); cin.tie(0); int n, k; cin >> n >> k; dp[0][0]=dp[2][1]=1; for(int row = 1; row <= n; row++) dp[row][0] = 0; for(int col = 1; col <= k; col++){ dp[0][col] = 1; dp[1][col] = 1; } for(int row = 2; row <= n; row++){ for(int col = 2; col <= k; col++){ dp[row][col] = (dp[row - 1][col - 1] + dp[row - 2][col - 1]) % MOD_N; } } cout << dp[n][k]; return 0; }
Java
UTF-8
836
2.625
3
[]
no_license
package classes.security; import java.io.Serializable; import java.util.ArrayList; public class EncryptionKey implements Serializable { private String id, value; private ArrayList<String> signatures; public EncryptionKey(String arrIndex, String arrValue) { this.id = arrIndex; this.value = arrValue; this.signatures = new ArrayList<>(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public ArrayList<String> getSignatures() { return signatures; } public void setSignatures(ArrayList<String> signatures) { this.signatures = signatures; } }
Shell
UTF-8
556
2.59375
3
[]
no_license
#!/bin/bash username='ubuntu' sudo apt-get update sudo apt-get install nano git apt-transport-https -y curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add - sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" sudo apt-get update apt-cache policy docker-ce sudo apt-get install -y docker-ce sudo systemctl status docker | grep docker.service sudo usermod -aG docker $username && echo 'dockerjog OK' cd docker docker build -t nginx . docker run -p 80:80 -d nginx
C#
UTF-8
3,059
2.578125
3
[]
no_license
using UnityEngine; using System; using System.Collections; using System.Collections.Generic; namespace Data.Remote { public class BaseRequest : MonoBehaviour { public Action<string> OnFailed; public Action<string> OnComplete; public Action<string> OnTimeout; public enum EStatus { WAITING, REQUESTING, FAILED, COMPLETE } public string id; public EStatus status = EStatus.WAITING; public bool hasFailed = false; public bool persistAfterFailed = false; public int tryoutsBeforeDefinitelyFail = 10;//Maximos intentos permitidos antes de fallar por completo public int tryouts = 0;//Intentos de hacer la request public int timeBeforeTimeout = 20; public List<BaseRequest> dependantRequests = new List<BaseRequest>(); protected float elapsedWhenRequested; protected float elapsedWhenFailed; public bool showDebugInfo = true; public virtual void stop() { status = EStatus.WAITING; } public virtual void start() { tryouts++; //La request recuerda si antes fallo hasFailed = failed; status = EStatus.REQUESTING; elapsedWhenRequested = Time.realtimeSinceStartup; } protected virtual void OnRequestFailed() { status = EStatus.FAILED; elapsedWhenFailed = Time.realtimeSinceStartup; if(tryoutsBeforeDefinitelyFail > 0 && tryouts >= tryoutsBeforeDefinitelyFail) { //Ya no es persistente persistAfterFailed = false; } if(OnFailed != null) { OnFailed(id); } } protected virtual void OnRequestTimeout() { //La marcamos como fallida status = EStatus.FAILED; elapsedWhenFailed = Time.realtimeSinceStartup; if(tryoutsBeforeDefinitelyFail > 0 && tryouts >= tryoutsBeforeDefinitelyFail) { //Ya no es persistente persistAfterFailed = false; } if(OnTimeout != null) { OnTimeout(id); } } protected virtual void OnRequestComplete() { status = EStatus.COMPLETE; if(OnComplete != null) { OnComplete(id); } } public float getTimeSinceRequested() { return Time.realtimeSinceStartup - elapsedWhenRequested; } public float getTimeSinceFailed() { return Time.realtimeSinceStartup - elapsedWhenFailed; } public bool isRequesting { get{return (status == EStatus.REQUESTING);} } public bool isComplete { get{return (status == EStatus.COMPLETE);} } public bool isWaiting { get{return (status == EStatus.WAITING);} } public bool failed { get{return (status == EStatus.FAILED);} } protected void Update() { if(isRequesting) { if(getTimeSinceRequested() > timeBeforeTimeout) { OnRequestTimeout(); } } } public string quotedString(string input) { return "\""+input+"\""; } public void secureLog(object message) { if(showDebugInfo) {Debug.Log(message);} } public void secureLogError(object message) { if(showDebugInfo) {Debug.LogError(message);} } public void secureLogWarning(object message) { if(showDebugInfo) {Debug.LogWarning(message);} } } }
C#
UTF-8
915
2.53125
3
[]
no_license
namespace eCat.Repository.Mapped { public class ParametroConfiguration : System.Data.Entity.ModelConfiguration.EntityTypeConfiguration<eCat.Data.Entities.Parametro> { public ParametroConfiguration() : this("dbo") { } public ParametroConfiguration(string schema) { ToTable("Parametros", schema); HasKey(x => x.Parametro_); Property(x => x.Parametro_).HasColumnName(@"Parametro").HasColumnType("nvarchar").IsRequired().HasMaxLength(50).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.None); Property(x => x.Valor).HasColumnName(@"Valor").HasColumnType("nvarchar").IsRequired().HasMaxLength(200); Property(x => x.Descripcion).HasColumnName(@"Descripcion").HasColumnType("varchar").IsOptional().IsUnicode(false).HasMaxLength(1000); } } }
SQL
UTF-8
759
2.734375
3
[]
no_license
BEGIN pkg_drop.drop_proc(object_name => 'cls_employees_scd', object_type => 'table'); END; CREATE TABLE cls_employees_scd ( employee_surr_id NUMBER(38) NOT NULL, employee_id VARCHAR2(50 BYTE) NOT NULL, first_name VARCHAR2(50 BYTE) NOT NULL, last_name VARCHAR2(50 BYTE) NOT NULL, store_number VARCHAR2(50 BYTE) NOT NULL, position_name VARCHAR2(50 BYTE) NOT NULL, position_grade VARCHAR2(50 BYTE) NOT NULL, work_experience NUMBER(10) NOT NULL, email VARCHAR2(50 BYTE) NOT NULL, phone VARCHAR2(50 BYTE) NOT NULL, start_dt DATE DEFAULT '01-JAN-1990', end_dt DATE DEFAULT '31-DEC-9999', is_active VARCHAR2 ( 200 CHAR ) NOT NULL );
PHP
UTF-8
153
2.625
3
[ "MIT" ]
permissive
<?php namespace App\Repositories\Exception; class RepositoryException { public function __construct($exception) { echo $exception; } }
C#
UTF-8
2,875
2.953125
3
[ "Apache-2.0" ]
permissive
using OpenTK; using System; namespace OpenTKbuild { enum Camera_Movement { forward, backward, left, right }; class Camera { public float Yaw = -90.0f; public float Pitch = 0.0f; public float Movespeed = 3.0f; public float Sensitivity = 0.25f; public float Zoom = 45.0f; Vector3 Position; Vector3 Front; Vector3 Up; Vector3 Right; Vector3 WorldUp; public Camera(float posX, float posY, float posZ, float upX, float upY, float upZ, float yaw, float pitch) { this.Position = new Vector3(posX, posY, posZ); this.WorldUp = new Vector3(upX, upY, upZ); this.Yaw = yaw; this.Pitch = pitch; this.updateCameraVectors(); } public Matrix4 GetViewMatrix() { return Matrix4.LookAt(this.Position, this.Position + this.Front, this.Up); } public void ProcessKeyboard(Camera_Movement direction, float deltaTime) { float velocity = this.Movespeed * deltaTime; if (direction == Camera_Movement.forward) this.Position += this.Front * velocity; if (direction == Camera_Movement.backward) this.Position -= this.Front * velocity; if (direction == Camera_Movement.left) this.Position -= this.Right * velocity; if (direction == Camera_Movement.right) this.Position += this.Right * velocity; } public void ProcessMouseMovement(float xoffset, float yoffset, bool constrainPitch = true) { xoffset *= this.Sensitivity; yoffset *= this.Sensitivity; this.Yaw += xoffset; this.Pitch += yoffset; if (constrainPitch) { if (this.Pitch > 89.0f) this.Pitch = 89.0f; if (this.Pitch < -89.0f) this.Pitch = -89.0f; } this.updateCameraVectors(); } public void ProcessMouseScroll(float yoffset) { if (this.Zoom >= 1.0f && this.Zoom <= 45.0f) this.Zoom -= yoffset; if (this.Zoom <= 1.0f) this.Zoom = 1.0f; if (this.Zoom >= 45.0f) this.Zoom = 45.0f; } public void updateCameraVectors() { Vector3 front; front.X = (float)Math.Cos(Yaw) * (float)Math.Cos(Pitch); front.Y = (float)Math.Sin(Pitch); front.Z = (float)Math.Sin(Yaw) * (float)Math.Cos(Pitch); Front = front.Normalized(); Right = Vector3.Cross(Front, WorldUp).Normalized(); Up = Vector3.Cross(Right, Front).Normalized(); } } }
Java
UTF-8
4,286
3.453125
3
[]
no_license
package dkeep.logic; import dkeep.logic.Map; import dkeep.logic.GameState; public class Hero extends Character { private boolean armed; /** * Constructor of the class. The Hero is initially unarmed. * * @param x The x coordinate of the new hero. * @param y The y coordinate of the new hero. * */ public Hero(int x, int y) { super(x,y); armed = false; } /** * Returns true if the the hero is armed. * * @return The value of variable armed. * */ public boolean isArmed() { return armed; } /** * Modifies the value of the variable armed. * * @param armed New value for the armed variable. * */ public void setArmed(boolean armed) { this.armed = armed; } /** * Sets the value of the (possible) next X and Y coordinates according to the move argument. * * @param move The string correspondent to the side which the hero should move to. * @param gs The current gamestate. */ public void heroMove(String move, GameState gs) { if(gs.isGame_over() || gs.isVictory()) return; switch(move) { case "w": ny = y - 1; nx = x; break; case "s": ny = y + 1; nx = x; break; case "a": ny = y; nx = x - 1; break; case "d": ny = y; nx = x + 1; break; } action(gs); } /** * Defines what the hero will do according to level and coordinates. * * @param gs The current gamestate. */ public void action(GameState gs) { switch(gs.getLevel_no()) { case 0: actionLevel1(gs); break; case 1: actionLevel1(gs); break; case 2: actionLevel2(gs); break; default: break; } } /** * Defines what the hero will do if playing on the first level. The hero will only move if the * ny and nx coordinates point to an empty space, lever or open door. * If the hero moves, the guard will also move. * * @param gs The current gamestate. */ public void actionLevel1(GameState gs) { switch(gs.getCurrent_map()[ny][nx]) { case "X": break; case "I": break; case "_": if(gs.isLever()) { gs.getCurrent_map()[y][x] = "k"; gs.setLever(false); } else gs.getCurrent_map()[y][x] = "_"; x = nx; y = ny; if(gs.getLevel_no() == 1) gs.getGuard().guard_move(gs); break; case "k": gs.setLever(true); gs.getCurrent_map()[y][x] = "_"; x = nx; y = ny; if(gs.getLevel_no() == 1) { gs.getCurrent_map()[Map.getDoor1_1().y][Map.getDoor1_1().x] = "S"; gs.getCurrent_map()[Map.getDoor1_2().y][Map.getDoor1_2().x] = "S"; gs.getCurrent_map()[Map.getDoor1_3().y][Map.getDoor1_3().x] = "S"; gs.getCurrent_map()[Map.getDoor1_4().y][Map.getDoor1_4().x] = "S"; gs.getCurrent_map()[Map.getDoor1_5().y][Map.getDoor1_5().x] = "S"; gs.getCurrent_map()[Map.getDoor1_6().y][Map.getDoor1_6().x] = "S"; gs.getCurrent_map()[Map.getDoor1_7().y][Map.getDoor1_7().x] = "S"; gs.getGuard().guard_move(gs); } if(gs.getLevel_no() == 0) { gs.getCurrent_map()[Map.getDoor_t1().y][Map.getDoor_t1().x] = "S"; gs.getCurrent_map()[Map.getDoor_t2().y][Map.getDoor_t2().x] = "S"; } break; case "S": gs.setLevel_no(2); break; default: break; } } /** * Defines what the hero will do if playing on the second level. The hero will only move if the * ny and nx coordinates point to an empty space, an open door (or closed if he has the key) or * the key. * When the hero moves the ogres also move (or try to at least). * * @param gs The current gamestate. */ public void actionLevel2(GameState gs) { switch(gs.getCurrent_map()[ny][nx]) { case "X": break; case "I": if(gs.isKey()) { gs.getCurrent_map()[ny][nx] = "S"; gs.moveOgres(); } break; case "S": if(gs.isKey()) gs.setVictory(true); break; case "k": gs.getCurrent_map()[y][x] = "_"; y = ny; x = nx; gs.setKey(true); gs.moveOgres(); break; case "_": gs.getCurrent_map()[y][x] = "_"; y = ny; x = nx; gs.moveOgres(); break; default: break; } } }
Python
UTF-8
2,948
2.78125
3
[]
no_license
import codecs import re from typing import List from commons import data_io def doc_generator(file_path): """ PubTator docs are of the form: UID|TITLE|TEXT UID|ABSTRACT|TEXT UID SPAN MENTION ENTITY_TYPE MESH_ID ... See -- data/bioconcepts2pubtator_offsets.sample """ with codecs.open(file_path, "rU", encoding="utf-8") as fp: lines = [] for line in fp: if len(line.rstrip()) == 0: if len(lines) > 0: # filter docs to target set doc_id = re.split(r'\|', lines[0].rstrip(), maxsplit=2) yield lines lines = [] else: lines.append(line) def get_stable_id(doc_id): return "%s::document:0:0" % doc_id def pubtator_parser(content:List[str]): """ 1. PMID: PubMed abstract identifier 2. start: Start-char-idx of Mention 3. end: End-char-idx of Mention 7. Mention: 4. Type: i.e., gene, disease, chemical, species, and mutation 6. Concept ID: Corresponding database identifier """ # First line is the title split = re.split(r'\|', content[0].rstrip(), maxsplit=2) doc_id = int(split[0]) stable_id = get_stable_id(doc_id) doc_text = split[2] # Second line is the abstract # Assume these are newline-separated; is this true? # Note: some articles do not have abstracts, however they still have this line doc_text += ' ' + re.split(r'\|', content[1].rstrip(), maxsplit=2)[2] # Rest of the lines are annotations annos = [] for line in content[2:]: anno = line.rstrip('\n').rstrip('\r').split('\t') if anno[3] == 'NO ABSTRACT': continue else: # Handle cases where no CID is provided... if len(anno) == 5: anno.append("") # Handle leading / trailing whitespace if anno[3].lstrip() != anno[3]: d = len(anno[3]) - len(anno[3].lstrip()) anno[1] = int(anno[1]) + d anno[3] = anno[3].lstrip() if anno[3].rstrip() != anno[3]: d = len(anno[3]) - len(anno[3].rstrip()) anno[2] = int(anno[2]) - d anno[3] = anno[3].rstrip() annos.append({ 'start_end':[anno[1],anno[2]], 'mention':anno[3], 'type':anno[4], 'concept-id':anno[5], }) return {'PMID':doc_id, 'stable_id':stable_id, 'text':doc_text, 'annos':annos} if __name__ == '__main__': from pathlib import Path home = str(Path.home()) file_path = home+'/data/PubTator/bioconcepts2pubtator_offsets.sample' g = (pubtator_parser(content) for content in doc_generator(file_path)) data_io.write_jsons_to_file('./parsed.jsonl',g)
Java
UTF-8
2,025
1.921875
2
[]
no_license
package generalassembly.yuliyakaleda.startercode; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import org.w3c.dom.Text; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { ArrayList<String> mWishList; ArrayAdapter<String> mAdapter; ListView wishListOut; TextView wishOut; EditText userInput; Button wishButton; Animation mSpinIn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mSpinIn = AnimationUtils.loadAnimation(MainActivity.this,R.anim.animation); wishListOut = (ListView)findViewById(R.id.wishListView); mWishList = new ArrayList<String>(); mAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, mWishList); wishListOut.setAdapter(mAdapter); wishOut = (TextView) findViewById(R.id.wishOutTv); userInput = (EditText) findViewById(R.id.userInput); wishButton = (Button) findViewById(R.id.wishMakerButton); wishButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { wishOut.setText(userInput.getText()); wishOut.startAnimation(mSpinIn); mWishList.add(userInput.getText().toString()); mAdapter.notifyDataSetChanged(); userInput.setText(""); } }); wishListOut.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { mWishList.remove(position); mAdapter.notifyDataSetChanged(); } }); } }
Swift
UTF-8
12,861
2.703125
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
// // Copyright 2022 The Matrix.org Foundation C.I.C // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // import Foundation import XCTest @testable import MatrixSDK class MXTaskQueueUnitTests: XCTestCase { /// Dummy error that can be thrown by a task enum Error: Swift.Error { case dummy } /// An operation within or outside of a task used to assert test results struct Operation: Hashable { enum Kind: String, CaseIterable, CustomStringConvertible { case taskStart case taskEnd case nonTask var description: String { return rawValue } } let id: String let kind: Kind } /// A timeline of operation that records exact order of execution of individual operations. /// It can be used to assert order of operations, or check whether various tasks overap or not. actor Timeline { struct OperationRecord { let operation: Operation let time: Int } private var time = 0 private var values = [Operation: Int]() /// Get number of recorded operations var numberOfOperations: Int { return values.count } /// Create a new record for an operation by adding current time func record(_ operation: Operation) { time += 1 values[operation] = time } /// Retrieve the order of operation kinds for a specific id func operationOrder(for id: String) -> [Operation.Kind] { return values .filter { $0.key.id == id } .sorted { $0.value < $1.value } .map { $0.key.kind } } /// Determine whether two different tasks overlap or not func overlapsTasks(id1: String, id2: String) -> Bool { let start1 = values[.init(id: id1, kind: .taskStart)] ?? 0 let end1 = values[.init(id: id1, kind: .taskEnd)] ?? 0 let start2 = values[.init(id: id2, kind: .taskStart)] ?? 0 let end2 = values[.init(id: id2, kind: .taskEnd)] ?? 0 return !(start1 < end1 && start2 < end2 && (end1 < start2 || end2 < start1)) } } private var timeline: Timeline! private var queue: MXTaskQueue! override func setUp() { timeline = Timeline() queue = MXTaskQueue() } // MARK: - No queue tests func test_noQueue_performsAllOperations() async { let taskIds = ["A", "B", "C"] for id in taskIds { let exp = expectation(description: "exp\(id)") executeWorkWithoutQueue(id) { exp.fulfill() } } await waitForExpectations(timeout: 1) await XCTAssertAllOperationsPerformed(taskIds) } func test_noQueue_overlapsTasks() async { let taskIds = ["A", "B", "C"] for id in taskIds { let exp = expectation(description: "exp\(id)") executeWorkWithoutQueue(id) { exp.fulfill() } } await waitForExpectations(timeout: 1) await XCTAssertTasksOverlap(taskIds) } // MARK: - Sync queue tests func test_syncQueue_performsAllOperations() async { let taskIds = ["A", "B", "C"] for id in taskIds { let exp = expectation(description: "exp\(id)") executeWorkOnSyncQueue(id) { exp.fulfill() } } await waitForExpectations(timeout: 1) await XCTAssertAllOperationsPerformed(taskIds) } func test_syncQueue_doesNotOverlapTasks() async { let taskIds = ["A", "B", "C"] for id in taskIds { let exp = expectation(description: "exp\(id)") executeWorkOnSyncQueue(id) { exp.fulfill() } } await waitForExpectations(timeout: 1) await XCTAssertTasksDoNotOverlap(taskIds) } func test_syncQueue_addsNonTaskLast() async { let taskIds = ["A", "B", "C"] for id in taskIds { let exp = expectation(description: "exp\(id)") executeWorkOnSyncQueue(id) { exp.fulfill() } } await waitForExpectations(timeout: 1) await XCTAssertOperationOrderEquals(taskIds, order: [.taskStart, .taskEnd, .nonTask]) } func test_syncQueue_throwsError() async throws { do { try await queue.sync { throw Error.dummy } XCTFail("Should not succeed") } catch Error.dummy { XCTAssert(true) } catch { XCTFail("Incorrect error type \(error)") } } func test_syncQueue_performsDifferentTaskTypes() async throws { var results = [Any]() try await queue.sync { results.append(1) } try await queue.sync { results.append("ABC") } try await queue.sync { results.append(true) } XCTAssertEqual(results.count, 3) XCTAssertEqual(results[0] as? Int, 1) XCTAssertEqual(results[1] as? String, "ABC") XCTAssertEqual(results[2] as? Bool, true) } // MARK: - Async queue tests func test_asyncQueue_performsAllOperations() async { let taskIds = ["A", "B", "C"] for id in taskIds { let exp = expectation(description: "exp\(id)") executeWorkOnAsyncQueue(id) { exp.fulfill() } } await waitForExpectations(timeout: 1) await XCTAssertAllOperationsPerformed(taskIds) } func test_asyncQueue_doesNotOverlapTasks() async { let taskIds = ["A", "B", "C"] for id in taskIds { let exp = expectation(description: "exp\(id)") executeWorkOnAsyncQueue(id) { exp.fulfill() } } await waitForExpectations(timeout: 1) await XCTAssertTasksDoNotOverlap(taskIds) } func test_asyncQueue_addsNonTaskBeforeTaskEnd() async { let taskIds = ["A", "B", "C"] for id in taskIds { let exp = expectation(description: "exp\(id)") executeWorkOnAsyncQueue(id) { exp.fulfill() } } await waitForExpectations(timeout: 1) // For the async variant `nonTask` could happen before or after `taskStart` but // always before `taskEnd`. Instead of asserting the entire flow deterministically // we assert relative positions await XCTAssertOperationOrder(taskIds, first: .taskStart, second: .taskEnd) await XCTAssertOperationOrder(taskIds, first: .nonTask, second: .taskEnd) } // MARK: - Execution helpers /// Performs some long task (e.g. suspending thread) whilst marking start and end private func performLongTask(id: String) async { await timeline.record( .init(id: id, kind: .taskStart) ) await doSomeHeavyWork() await timeline.record( .init(id: id, kind: .taskEnd) ) } /// Performs short task that executes right away private func performShortNonTask(id: String) async { await timeline.record( .init(id: id, kind: .nonTask) ) } /// Execute long and short task without using any queues, meaning individual async operations can overlap private func executeWorkWithoutQueue(_ taskId: String, completion: @escaping () -> Void) { randomDetachedTask { await self.performLongTask(id: taskId) await self.performShortNonTask(id: taskId) completion() } } /// Execute long and short task using queue synchronously, meaning individual tasks cannot overlap private func executeWorkOnSyncQueue(_ taskId: String, completion: @escaping () -> Void) { randomDetachedTask { try await self.queue.sync { await self.performLongTask(id: taskId) completion() } await self.performShortNonTask(id: taskId) } } /// Execute long and short task using queue asynchronously, meaning individual tasks cannot overlap private func executeWorkOnAsyncQueue(_ taskId: String, completion: @escaping () -> Void) { randomDetachedTask { await self.queue.async { await self.performLongTask(id: taskId) completion() } await self.performShortNonTask(id: taskId) } } /// Perform work on detached task with random priority, so that order of tasks is unpredictable private func randomDetachedTask(completion: @escaping () async throws -> Void) { let priorities: [TaskPriority] = [.high, .medium, .low] Task.detached(priority: priorities.randomElement()) { try await completion() } } // MARK: - Other helpers private func doSomeHeavyWork(timeInterval: TimeInterval = 0.1) async { do { try await Task.sleep(nanoseconds: UInt64(timeInterval * 1e9)) } catch { XCTFail("Error sleeping \(error)") } } /// Assert that for every task id all operations (task start, task end and non task) are performed private func XCTAssertAllOperationsPerformed(_ taskIds: [String], file: StaticString = #file, line: UInt = #line) async { let count = await timeline.numberOfOperations XCTAssertEqual(count, taskIds.count * Operation.Kind.allCases.count, file: file, line: line) } /// Assert that operations for each task happen in the exact order specified private func XCTAssertOperationOrderEquals(_ taskIds: [String], order: [Operation.Kind], file: StaticString = #file, line: UInt = #line) async { for id in taskIds { let realOrder = await timeline.operationOrder(for: id) XCTAssertEqual(realOrder, order, "Order for task \(id) is incorrect", file: file, line: line) } } /// Assert that for every task a given operation occurs before another operation private func XCTAssertOperationOrder(_ taskIds: [String], first: Operation.Kind, second: Operation.Kind, file: StaticString = #file, line: UInt = #line) async { for id in taskIds { let realOrder = await timeline.operationOrder(for: id) guard let firstIndex = realOrder.firstIndex(of: first), let secondIndex = realOrder.firstIndex(of: second) else { XCTFail("Cannot find given operations", file: file, line: line) return } XCTAssertLessThan(firstIndex, secondIndex, "Operation \(first) does not happen before \(second)", file: file, line: line) } } /// Assert that the operations of different tasks overlap (i.e. second task starts before the first task finishes) private func XCTAssertTasksOverlap(_ taskIds: [String], file: StaticString = #file, line: UInt = #line) async { for i in 0 ..< taskIds.count { for j in i + 1 ..< taskIds.count { let overlapsTasks = await timeline.overlapsTasks(id1: taskIds[i], id2: taskIds[j]) XCTAssertTrue(overlapsTasks, "Tasks \(taskIds[i]) and \(taskIds[j]) do not overlap when they should", file: file, line: line) } } } /// Assert that the operations of different tasks do not overlap (i.e. second task does not start until the firs task has finished) private func XCTAssertTasksDoNotOverlap(_ taskIds: [String], file: StaticString = #file, line: UInt = #line) async { for i in 0 ..< taskIds.count { for j in i + 1 ..< taskIds.count { let overlapsTasks = await timeline.overlapsTasks(id1: taskIds[i], id2: taskIds[j]) XCTAssertFalse(overlapsTasks, "Tasks \(taskIds[i]) and \(taskIds[j]) overlap when they should not", file: file, line: line) } } } }
PHP
UTF-8
796
3.25
3
[]
no_license
<?php // The concrete Robot class based on the RobotPlan interface require_once "RobotPlan.php"; class Robot implements RobotPlan { private $robotHead; private $robotTorso; private $robotArms; private $robotLegs; public function setRobotHead($head) { $this->robotHead = $head; } public function getRobotHead() { return $this->robotHead; } public function setRobotTorso($torso) { $this->robotTorso = $torso; } public function getRobotTorso() { return $this->robotTorso; } public function setRobotArms($arms) { $this->robotArms = $arms; } public function getRobotArms() { return $this->robotArms; } public function setRobotLegs($legs) { $this->robotLegs = $legs; } public function getRobotLegs() { return $this->robotLegs; } }
Python
UTF-8
689
2.71875
3
[]
no_license
# _*_ coding: utf-8 _*_ # 找到probase中的实体 def leaf(): hypoList = [] hypeList = [] i = 0 with open('data-concept-instance-relations.txt', 'r', encoding='utf-8')as f: for line in f.readlines(): i += 1 hype = line.strip().split('\t')[0] hypo = line.strip().split('\t')[1] hypoList.append(hypo) hypeList.append(hype) if i == 100000: print(i) hypoSet = set(hypoList) hypeSet = set(hypeList) diffSet = hypoSet - hypeSet with open('leaf.txt', 'w', encoding='utf-8')as f: for item in diffSet: f.write(item + '\n') if __name__ == '__main__': leaf()
JavaScript
UTF-8
460
3.046875
3
[ "MIT" ]
permissive
// a random number generator var generator = fc.randomGeometricBrownianMotion() .steps(11); // some formatters var dateFormatter = d3.timeFormat('%b'); // randomly generated sales data starting at one var data = generator(1).map(function(d, i) { return { month: dateFormatter(new Date(0, i + 1, 0)), sales: d + i / 2 }; }); // let's see what the data looks like d3.select('#sales-data') .text(JSON.stringify(data.slice(0, 3), null, 2));
C++
UTF-8
1,072
3.59375
4
[]
no_license
void insert(node** root, int item){ node* temp = new node; node* ptr; temp->data = item; temp->next = NULL; if (*root == NULL) *root = temp; else { ptr = *root; while (ptr->next != NULL) ptr = ptr->next; ptr->next = temp; } } node *arrayToList(vector<int>A, int n) { node *root = NULL; for (int i = 0; i < n; i++) insert(&root, A[i]); return root; } node* findIntersection(node* head1, node* head2){ map<int,int>mp; node * current=head1; while(current!=NULL){ int index=current->data; mp[index]++; current=current->next; } node * current2=head2; while(current2!=NULL){ int index=current2->data; mp[index]++; current2=current2->next; } map<int,int>:: iterator it; vector<int>A; for(it=mp.begin();it!=mp.end();++it){ if(it->second==2){ A.push_back(it->first); } } int n=A.size(); node* p=arrayToList(A,n) ; return p; }
Ruby
UTF-8
392
3.375
3
[]
no_license
class CrewMember attr_reader :country def initialize(country) @country = country @on_the_ship = true end def receive_order(_order) say "\e[31mThe water is cold!\e[0m" if @on_the_ship end def jump if @on_the_ship say "\e[32mJumping!!\e[0m" @on_the_ship = false end end def say(message) puts "\e[1m#{@country}\e[0m: #{message}" end end
Ruby
UTF-8
1,032
3.109375
3
[ "MIT" ]
permissive
require 'pry' require 'open-uri' class StellingBanjos::Scraper @@all = [] def self.scrape_catalog_page(link) catalog = Nokogiri::HTML(open(link)) catalog.css("div.ProductItem").each do |banjo| name = banjo.css("h2").text.strip if banjo.css("span").text.strip.include?("Sold out") sold_out = "Yes" #This removes "Sold out" from the end of each price price = "$" + banjo.css("span").text.strip.split("$").pop.to_s else sold_out = "No" price = banjo.css("span").text.strip end link = "https://www.elderly.com" + banjo.css("a").map{|link| link['href']}[0] @@all << {name: name, price: price, link: link, sold_out: sold_out} end end def self.scrape_info_page(link) info = Nokogiri::HTML(open(link)) info.css("div.ProductMeta__Description.Rte").text.strip.split("More").shift.to_s.strip #This was the only way I found to remove the "More Details..." at the end of each description end def self.all @@all end end
C#
UTF-8
5,770
2.5625
3
[]
no_license
using System; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Api; using Api.Models; using Domain.Models; using FluentAssertions; using Newtonsoft.Json; using NUnit.Framework; namespace SmokeTests { public class CustomersControllerTests { private HttpClient _client; private CustomWebApplicationFactory<Startup> _factory; [OneTimeSetUp] public void GivenARequestToTheController() { _factory = new CustomWebApplicationFactory<Startup>(); _client = _factory.CreateClient(); } private static readonly (string, string, string, string, HttpStatusCode)[] _authTestMappings = { ("valid credentials", "api/customers","administrator", "password", HttpStatusCode.OK), ("valid credentials", "api/customers", "test", "password", HttpStatusCode.OK), ("in valid credentials", "api/customers", "test123", "password", HttpStatusCode.Unauthorized), ("in valid credentials", "api/customers/123", "test123", "password", HttpStatusCode.Unauthorized) }; [TestCaseSource(nameof(_authTestMappings))] public async Task BasicAuthTests((string, string, string, string, HttpStatusCode) testData) { var (_, relativePath,username, password, expectedHttpStatusCode) = testData; _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String( System.Text.Encoding.ASCII.GetBytes( $"{username}:{password}"))); var response = await _client.GetAsync(relativePath); response.StatusCode.Should().BeEquivalentTo(expectedHttpStatusCode); } [Test] public async Task GetAllCustomersShouldReturnOkResponseWithDefaultSetup() { _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String( System.Text.Encoding.ASCII.GetBytes( $"test:password"))); var response = await _client.GetAsync("api/customers"); response.EnsureSuccessStatusCode(); var responseStrong = await response.Content.ReadAsStringAsync(); responseStrong.Should().Be("[]"); } private static readonly (string, CustomersApiRequestModel, HttpStatusCode)[] _requestModelMappings = { ("bad request", new CustomersApiRequestModel(), HttpStatusCode.BadRequest), ("bad request", new CustomersApiRequestModel {FirstName = ""}, HttpStatusCode.BadRequest), ("bad request", new CustomersApiRequestModel {FirstName = "", Surname = ""}, HttpStatusCode.BadRequest), ("bad request", new CustomersApiRequestModel {FirstName = "", Surname = "", Email = ""}, HttpStatusCode.BadRequest), ("string <min chars", new CustomersApiRequestModel {FirstName = "", Surname = "", Email = "", Password = ""}, HttpStatusCode.BadRequest), ("valid model", new CustomersApiRequestModel {FirstName = "tester", Surname = "test", Email = "test@tester.com", Password = "tester123"}, HttpStatusCode.OK) }; [TestCaseSource(nameof(_requestModelMappings))] public async Task CreateCustomerEndpointValidationTests((string, CustomersApiRequestModel, HttpStatusCode) testData) { var (_, inputRequest, expectedHttpStatusCode) = testData; _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String( System.Text.Encoding.ASCII.GetBytes( $"test:password"))); var response = await _client.PostAsync("/api/customers", new StringContent(JsonConvert.SerializeObject(inputRequest),Encoding.UTF8,"application/json")); response.StatusCode.Should().Be(expectedHttpStatusCode); } [TestCaseSource(nameof(_requestModelMappings))] public async Task UpdateCustomerEndpointValidationTests((string, CustomersApiRequestModel, HttpStatusCode) testData) { _factory.OperationResult.SetupGet(x => x.Success).Returns(true); var (_, inputRequest, expectedHttpStatusCode) = testData; _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String( System.Text.Encoding.ASCII.GetBytes( $"test:password"))); var response = await _client.PutAsync("/api/customers", new StringContent(JsonConvert.SerializeObject(inputRequest), Encoding.UTF8, "application/json")); response.StatusCode.Should().Be(expectedHttpStatusCode); } [Test] public async Task GetCusomterByIdEndpointTests() { _factory.OperationResult.SetupGet(x => x.Success).Returns(true); _factory.OperationResult.SetupGet(x => x.Value).Returns(JsonConvert.SerializeObject(new Customer("","","",""))); _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String( System.Text.Encoding.ASCII.GetBytes( $"test:password"))); var id = "123"; var response = await _client.GetAsync($"/api/customers/{id}"); response.StatusCode.Should().Be(HttpStatusCode.OK); } } }
TypeScript
UTF-8
1,383
3.578125
4
[]
no_license
interface Day1Reducer { (accumulator: number[], value: number, _: number, array: number[]): number[]; } const reduceTheTwoUsing = (yourTotal: number): Day1Reducer => ( accumulator, value, _, array, ) => { if (accumulator.length === 2) { return accumulator; } const otherNumber = yourTotal - value; const isTheOtherNumberInThere = array.find(number => number === otherNumber); if (isTheOtherNumberInThere) { return [value, isTheOtherNumberInThere]; } return [0]; }; const reduceTheThree: Day1Reducer = (accumulator, value, _, array) => { if (accumulator.length === 3) { return accumulator; } const theRemainderFrom2020 = 2020 - value; const theNumbersThatDontExceedTheRemainder = array.filter( number => number <= theRemainderFrom2020, ); if (theNumbersThatDontExceedTheRemainder.length === 0) { return [0]; } const filterOutTheCurrentValue = theNumbersThatDontExceedTheRemainder.filter( number => number !== value, ); const reduceTheTwo = reduceTheTwoUsing(theRemainderFrom2020); const theTwoNumbersThatSumToTheRemainder = filterOutTheCurrentValue.reduce( reduceTheTwo, [0], ); if (theTwoNumbersThatSumToTheRemainder.length === 2) { const [one, two] = theTwoNumbersThatSumToTheRemainder; return [value, one, two]; } return [0]; }; export { reduceTheTwoUsing, reduceTheThree };
Markdown
UTF-8
2,893
2.78125
3
[]
no_license
--- title: Spring Boot CLI使用 date: 2017-10-18 19:40:59 categories: [Java,Spring] tags: [java,spring] --- Spring Boot CLI是Spring Boot项目提供的一个用于快速运行Spring Boot应用的命令行工具,通过结合Groovy,可以实现一个文件的WEB应用,用于快速实验原型是最好不过的了。 <!--more--> ## 安装 手动安装:https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#getting-started-installing-the-cli 下载spring-boot-cli-1.5.8.RELEASE-bin.zip,解压,然后把spring-1.5.8.RELEASE\bin的路径加入PATH环境变量。 ## 一个文件的web应用 一般Java想要启动一个web应用需要很多样板代码与配置,一个基于Spring的web应用就更加可怕了,如果没有IDE的帮助,新建一个估计得查半天资料。而使用Spring Boot CLI我们只需要一个文件! 新建文件`app.groovy`: ``` @RestController class ThisWillActuallyRun { @RequestMapping("/") String home() { "Hello World!" } } ``` 然后执行`$ spring run app.groovy`,第一次执行会下载依赖,会慢一些,之后就很快了,通过`localhost:8080`可以访问这个应用。 如果想指定别的端口: ``` $ spring run hello.groovy -- --server.port=9000 ``` 这里的`--`用于区分传递给spring应用的参数和传递给cli的参数。 ## 新建项目 Spring Boot CLI可以新建项目,他其实是调用start.spring.io来新建项目。比如: ``` $ spring init --dependencies=web,data-jpa my-project Using service at https://start.spring.io Project extracted to '/Users/developer/example/my-project' ``` 这样就不用去网站上新建项目再下载下来了。通过可以查看有哪些可以使用的构建工具和依赖: ``` $ spring init --list ======================================= Capabilities of https://start.spring.io ======================================= Available dependencies: ----------------------- actuator - Actuator: Production ready features to help you monitor and manage your application ... web - Web: Support for full-stack web development, including Tomcat and spring-webmvc websocket - Websocket: Support for WebSocket development ws - WS: Support for Spring Web Services Available project types: ------------------------ gradle-build - Gradle Config [format:build, build:gradle] gradle-project - Gradle Project [format:project, build:gradle] maven-build - Maven POM [format:build, build:maven] maven-project - Maven Project [format:project, build:maven] (default) ... ``` 一个更加完整的用法: ``` $ spring init --build=gradle --java-version=1.8 --dependencies=websocket --packaging=war sample-app.zip Using service at https://start.spring.io Content saved to 'sample-app.zip' ``` ## 参考资料 - [Spring Boot Reference Guide](https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#cli)
JavaScript
UTF-8
1,619
2.75
3
[ "MIT" ]
permissive
/* This is an example of 2D rendering, simply using bitmap fonts in orthographic space. var geom = createText({ multipage: true, ... other options }) */ global.THREE = require('three') var createOrbitViewer = require('three-orbit-viewer')(THREE) var createText = require('../../src/engine/three-bmfont-text') require('./load')({ font: 'fnt/Lato-Regular-64.fnt', image: 'fnt/lato.png' }, start) function start (font, texture) { var app = createOrbitViewer({ clearColor: 'rgb(80, 80, 80)', clearAlpha: 1.0, fov: 65, position: new THREE.Vector3() }) app.camera = new THREE.OrthographicCamera() app.camera.left = 0 app.camera.top = 0 app.camera.near = -100 app.camera.far = 100 var geom = createText({ text: 'this bitmap text\nis rendered with \nan OrthographicCamera', font: font, align: 'left', width: 700, flipY: texture.flipY }) var material = new THREE.MeshBasicMaterial({ map: texture, transparent: true, color: 'rgb(230, 230, 230)' }) var layout = geom.layout var text = new THREE.Mesh(geom, material) var padding = 40 text.position.set(padding, -layout.descender + layout.height + padding, 0) var textAnchor = new THREE.Object3D() textAnchor.add(text) textAnchor.scale.multiplyScalar(1 / (window.devicePixelRatio || 1)) app.scene.add(textAnchor) // update orthographic app.on('tick', function () { // update camera var width = app.engine.width var height = app.engine.height app.camera.right = width app.camera.bottom = height app.camera.updateProjectionMatrix() }) }
Java
UTF-8
4,264
3.46875
3
[]
no_license
import java.util.Comparator; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; public class Assn6_3 { public static void main(String[] args) { class Employee implements Comparable<Employee> { String id, name, department; double salary; void displayDetails() { System.out.println(this); } Employee(String id, String name, double salary, String department) { this.department = department; this.id = id; this.name = name; this.salary = salary; } @Override public String toString() { return "{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", salary='" + salary + '\'' + ", department='" + department + '\'' + '}' + "\n"; } @Override public int compareTo(Employee o) { return this.id.compareTo(o.id); } } Employee e1=new Employee("a","vishnu",234000000,"fullstack"); Employee e2=new Employee("c","srivishnu",234000,"fullstack"); Employee e3=new Employee("g","Bhargavi kavalnekar",234000,"fullstack"); Employee e4=new Employee("12304","nihal",234000,"fullstack"); Employee e5=new Employee("123000","vishnu",234000000,"fullstack"); Employee e6=new Employee("12300","bakul",234000,"fullstack"); Employee e7=new Employee("12003","hingula",234000,"fullstack"); Employee e8=new Employee("12304","samrudhi",234000,"fullstack"); Set<Employee> employeeSet=new TreeSet<Employee>(); employeeSet.add(e1); employeeSet.add(e2); employeeSet.add(e3); employeeSet.add(e4); employeeSet.add(e5); employeeSet.add(e6); employeeSet.add(e7); employeeSet.add(e8); employeeSet.add(e1); System.out.println("choose an option"); System.out.println("a)ID"); System.out.println("b)name"); System.out.println("c)Department"); System.out.println("d)Salary"); Scanner s=new Scanner(System.in); String op= s.next(); if(op.equals("b")) { class AccordingName implements Comparator<Employee> { @Override public int compare(Employee o1, Employee o2) { return o1.name.compareTo(o2.name); } } Set<Employee> emp = new TreeSet<>(new AccordingName()); emp.addAll(employeeSet); System.out.println(emp); } if(op.equals("a")) { class AccordingID implements Comparator<Employee> { @Override public int compare(Employee o1, Employee o2) { return o1.id.compareTo(o2.id); } } Set<Employee> emp = new TreeSet<>(new AccordingID()); emp.addAll(employeeSet); System.out.println(emp); } if(op.equals("c")) { class AccordingDept implements Comparator<Employee> { @Override public int compare(Employee o1, Employee o2) { if(o1.department.equals(o2.department)){ return 0; } return o1.department.compareTo(o2.department); } } Set<Employee> emp = new TreeSet<>(new AccordingDept()); emp.addAll(employeeSet); System.out.println(emp); } if(op.equals("d")) { class AccordingSal implements Comparator<Employee> { @Override public int compare(Employee o1, Employee o2) { if(o1.salary==o2.salary) return -1; return (int)((o1.salary)-(o2.salary)); } } Set<Employee> emp = new TreeSet<>(new AccordingSal()); emp.addAll(employeeSet); System.out.println(emp); } } }
Java
UTF-8
751
2.671875
3
[]
no_license
import java.applet.*; import java.io.*; import javax.swing.*; import javax.sound.sampled.*; public class GameAmbientSound { public static final String RAIN = "sounds/amb_rain.wav"; public static final String FULL_TREES = "sounds/amb_trees1.wav"; public static final String DEAD_TREES = "sounds/amb_trees2.wav"; public static final String NIGHTTIME = "sounds/amb_night.wav"; private AudioClip clip = null; public GameAmbientSound(String F) { try { File file = new File(F); clip = JApplet.newAudioClip(file.toURL()); } catch (Exception e) { throw new RuntimeException("Couldn't find ambient sound \'" + F + "\'"); } clip.loop(); } public void stop() { clip.stop(); } }
Markdown
UTF-8
1,508
2.515625
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: Числовые пределы (C++) ms.date: 11/04/2016 helpviewer_keywords: - numerical limits ms.assetid: 5ebc9837-e273-4ea6-ac7d-14b3c2c974c7 ms.openlocfilehash: 54854150b484e2caf66b8e9bc0cb97597d693b49 ms.sourcegitcommit: 6052185696adca270bc9bdbec45a626dd89cdcdd ms.translationtype: MT ms.contentlocale: ru-RU ms.lasthandoff: 10/31/2018 ms.locfileid: "50569862" --- # <a name="numerical-limits-c"></a>Числовые пределы (C++) Два стандартных включаемых файлов, \<limits.h > и \<float.h >, определяют числовые ограничения или минимальное и максимальное значения, которые может хранить переменная данного типа. Эти минимальные и максимальные значения гарантированно можно перенести в любой компилятор с ++, который использует то же представление данных в качестве ANSI C. \<Limits.h > включают файл определяет [числовые ограничения для целочисленных типов](../cpp/integer-limits.md), и \<float.h > определяет [числовые ограничения для типов с плавающей запятой](../cpp/floating-limits.md). ## <a name="see-also"></a>См. также [Основные понятия](../cpp/basic-concepts-cpp.md)
Java
UTF-8
13,323
2.390625
2
[]
no_license
package com.natallia.shoppinglist.database; import android.app.Activity; import android.util.Log; import com.natallia.shoppinglist.R; import java.util.ArrayList; import java.util.List; import io.realm.Realm; import io.realm.RealmObject; import io.realm.RealmResults; import io.realm.Sort; /** * Класс для работы с бд (в данном случае realm) */ public class DataManager { public static final String TAG = DataManager.class.getName(); public Activity activity; public static Realm realm; public DataManager(Activity activity) { this.activity = activity; realm = Realm.getInstance(activity); } public static List<Category> getCategories() { final RealmResults<Category> results = realm.where(Category.class).findAll(); return results; } // получаем список всех ShoppingList, отсортированный по позиции public static List<ShoppingList> getShoppingLists() { final RealmResults<ShoppingList> results = realm.where(ShoppingList.class).findAllSorted("position", Sort.DESCENDING); return results; } // сортируем список всех ShoppingList, вычеркнутые списки внизу public static void sortShoppingLists() { realm.beginTransaction(); RealmResults<ShoppingList> results = realm.where(ShoppingList.class).findAllSorted("isChecked", Sort.DESCENDING, "id", Sort.ASCENDING); for (int i = 0; i < results.size(); i++) { results.get(i).setPosition(i); } realm.commitTransaction(); } // устанавливаем название списка public static void setNameShoppingList(ShoppingList shoppingList, String name) { realm.beginTransaction(); shoppingList.setName(name); realm.commitTransaction(); } // устанавливаем name элемента списка (item) public static void setNameShoppingListItem(Item item, String name) { realm.beginTransaction(); item.setName(name); realm.commitTransaction(); } // устанавливаем необходимое количество элемента списка (item) public static void setAmountShoppingListItem(ShoppingListItem shoppingListItem, Float amount) { realm.beginTransaction(); shoppingListItem.setAmount(amount); realm.commitTransaction(); } // получаем список по id public static ShoppingList getShoppingListById(int id){ ShoppingList shoppingList = realm.where(ShoppingList.class).equalTo("id",id).findFirst(); return shoppingList; } // меняем признак expanded у Shopping list public static void toggleExpanded(ShoppingList shoppingList) { realm.beginTransaction(); shoppingList.setExpanded(!shoppingList.isExpanded()); realm.commitTransaction(); } // меняем признак favorite (избранный) у Shopping list public static void toggleFavorite(ShoppingList shoppingList) { realm.beginTransaction(); shoppingList.setFavorite(!shoppingList.isFavorite()); realm.commitTransaction(); } public static void deleteCategory(Category category) { realm.beginTransaction(); category.removeFromRealm(); realm.commitTransaction(); } // удаляем элемент из списка public static void deleteShoppingListItem(ShoppingListItem shoppingListItem) { realm.beginTransaction(); shoppingListItem.removeFromRealm(); realm.commitTransaction(); } // удаляем список из базы public static void deleteShoppingList(ShoppingList shoppingList) { realm.beginTransaction(); shoppingList.removeFromRealm(); realm.commitTransaction(); } public static boolean shoppingListIsChecked(ShoppingList shoppingList) { Long count = shoppingList.getItems().where().equalTo("checked",false).count(); if (count == 0){ return true; } else { return false;} } public static void setShoppingListIsChecked(ShoppingList shoppingList, boolean isChecked) { realm.beginTransaction(); shoppingList.setIsChecked(isChecked); realm.commitTransaction(); } public static int shoppingListGetChecked(ShoppingList shoppingList) { Long count = shoppingList.getItems().where().equalTo("checked",true).count(); return count.intValue(); } public static List<ShoppingList> getFavoriteShoppingLists(int idShoppingList) { List <ShoppingList> favoritesShoppingList = realm.where(ShoppingList.class).equalTo("favorite",true).notEqualTo("id",idShoppingList).findAll(); for (int i = 0; i <favoritesShoppingList.size() ; i++) { } return favoritesShoppingList; } public static int getNextId(Class<? extends RealmObject> clazz) { final Number currentMaxId = realm.where(clazz).max("id"); if (currentMaxId == null) { return 1; } return currentMaxId.intValue() + 1; } public static int getNextPositionOfShoppingListItem(ShoppingList shoppingList) { final Number currentMaxPosition = shoppingList.getItems().where().max("position"); if (currentMaxPosition == null) { return 1; } return currentMaxPosition.intValue() + 1; } public static int getNextPositionOfShoppingList() { final Number currentMaxPosition = realm.where(ShoppingList.class).findAll().where().max("position"); if (currentMaxPosition == null) { return 1; } return currentMaxPosition.intValue() + 1; } // первоначальное заполнение базы public static ShoppingList createShoppingList() { realm.beginTransaction(); ShoppingList shoppingList = realm.createObject(ShoppingList.class); shoppingList.setId(getNextId(ShoppingList.class)); shoppingList.setPosition(getNextPositionOfShoppingList()); shoppingList.setName("Новый список"); shoppingList.setExpanded(true); realm.commitTransaction(); return shoppingList; } public static ShoppingListItem createShoppingListItem(ShoppingList shoppingList) { realm.beginTransaction(); Item item = realm.createObject(Item.class); item.setId(getNextId(Item.class)); shoppingList.setExpanded(true); ShoppingListItem shoppingListItem = realm.createObject(ShoppingListItem.class); shoppingListItem.setId(getNextId(ShoppingListItem.class)); shoppingListItem.setPosition(getNextPositionOfShoppingListItem(shoppingList)); shoppingListItem.setItem(item); shoppingListItem.setChecked(false); shoppingListItem.setAmount(1f); shoppingList.getItems().add(shoppingListItem); realm.commitTransaction(); return shoppingListItem; } public static void addShoppingListItem(ShoppingList shoppingList,ShoppingListItem shoppingListItem) { realm.beginTransaction(); ShoppingListItem newShoppingListItem = realm.createObject(ShoppingListItem.class); newShoppingListItem.setAmount(shoppingListItem.getAmount()); newShoppingListItem.setItem(shoppingListItem.getItem()); newShoppingListItem.setChecked(false); newShoppingListItem.setId(getNextId(ShoppingListItem.class)); newShoppingListItem.setPosition(getNextPositionOfShoppingListItem(shoppingList)); shoppingList.getItems().add(newShoppingListItem); realm.commitTransaction(); } public static void InitializeData() { realm.beginTransaction(); Category category; // Add a category if (realm.allObjects(Category.class).size() == 0) { int id = 0; category = realm.createObject(Category.class); category.setId(getNextId(Category.class)); category.setName("Продукты"); category = realm.createObject(Category.class); category.setId(getNextId(Category.class)); category.setName("Бытовая химия"); category = realm.where(Category.class).findFirst(); Log.d(TAG, category.getName()); } // создаем пару элементов if (realm.allObjects(Item.class).size() == 0) { int id = 0;//realm.allObjects(Category.class).max("id").intValue(); ; category = realm.where(Category.class).findFirst(); Item item = realm.createObject(Item.class); item.setId(getNextId(Item.class)); item.setName("Молоко"); item.setCategory(category); item = realm.createObject(Item.class); item.setId(getNextId(Item.class)); item.setName("Капуста"); item.setCategory(category); item = realm.createObject(Item.class); item.setId(getNextId(Item.class)); item.setName("Сметана"); item.setCategory(category); } if (realm.allObjects(ShoppingListItem.class).size() == 0) { int id = 0;//realm.allObjects(Category.class).max("id").intValue(); ; Item item = realm.where(Item.class).equalTo("name","Молоко").findFirst(); ShoppingListItem shoppingListItem = realm.createObject(ShoppingListItem.class); shoppingListItem.setId(getNextId(ShoppingListItem.class)); shoppingListItem.setPosition(1); shoppingListItem.setItem(item); shoppingListItem.setChecked(false); shoppingListItem.setAmount(1f); shoppingListItem = realm.createObject(ShoppingListItem.class); shoppingListItem.setId(getNextId(ShoppingListItem.class)); shoppingListItem.setPosition(2); shoppingListItem.setItem(realm.where(Item.class).equalTo("name", "Капуста").findFirst()); shoppingListItem.setChecked(false); shoppingListItem.setAmount(1f); shoppingListItem = realm.createObject(ShoppingListItem.class); shoppingListItem.setId(getNextId(ShoppingListItem.class)); shoppingListItem.setPosition(3); shoppingListItem.setItem(realm.where(Item.class).equalTo("name", "Сметана").findFirst()); shoppingListItem.setChecked(false); shoppingListItem.setAmount(1f); } if (realm.allObjects(ShoppingList.class).size() == 0) { int id = 0;//realm.allObjects(Category.class).max("id").intValue(); ; //Item item = realm.where(Item.class).equalTo("name","Молоко").findFirst(); ShoppingList shoppingList = realm.createObject(ShoppingList.class); shoppingList.setId(getNextId(ShoppingList.class)); shoppingList.setPosition(getNextPositionOfShoppingList()); Log.d("shopping position", String.valueOf(shoppingList.getPosition())); shoppingList.setName("Голубцы"); shoppingList.getItems().addAll(realm.where(ShoppingListItem.class).findAll()); // TODO перенести в стринги shoppingList.setExpanded(true); Item item = realm.where(Item.class).equalTo("name","Молоко").findFirst(); ShoppingListItem shoppingListItem = realm.createObject(ShoppingListItem.class); shoppingListItem.setId(getNextId(ShoppingListItem.class)); shoppingListItem.setPosition(1); shoppingListItem.setItem(item); shoppingListItem.setChecked(false); shoppingListItem.setAmount(1f); shoppingList = realm.createObject(ShoppingList.class); shoppingList.setId(getNextId(ShoppingList.class)); shoppingList.setPosition(getNextPositionOfShoppingList()); Log.d("shopping position", String.valueOf(shoppingList.getPosition())); shoppingList.setName("Продукты"); shoppingList.getItems().add(shoppingListItem); shoppingList.setExpanded(true); } realm.commitTransaction(); } public static void toggleChecked(ShoppingListItem shoppingListItem) { realm.beginTransaction(); shoppingListItem.setChecked(!shoppingListItem.isChecked()); realm.commitTransaction(); } // меняем позиции элементов в списке public static void swapShoppingListItems(List<ShoppingListItem> shoppingListItems, int fromPosition, int toPosition) { if (fromPosition > toPosition) { int x = toPosition; toPosition = fromPosition; fromPosition = x; } realm.beginTransaction(); ShoppingListItem from = shoppingListItems.get(fromPosition); ShoppingListItem to = shoppingListItems.get(toPosition); int temp = from.getPosition(); from.setPosition(to.getPosition()); to.setPosition(temp); realm.commitTransaction(); } }
Swift
UTF-8
4,762
4.03125
4
[]
no_license
/*: ## Упражнение для приложения — информирование об успехах >Эти упражнения закрепляют понимание Swift в контексте фитнес-приложения. Довольно часто вам нужно передавать в функцию вводную информацию. К примеру, функция информирования об успехах, которую вы написали в упражнении «Работающее приложение», может быть расположена в такой области вашего проекта, что она не будет иметь доступа к значениям `steps` и `goal`. В этом случае при вызове функции вам нужно сообщить ей количество шагов, которое было пройдено, и цель на день, чтобы она могла вывести релевантные сообщения об успехах. Перепишите функцию `progressUpdate` таким образом, чтобы она принимала два параметра типа `Int`, называющиеся `steps` и `goal`. Как и ранее, функция должна вывести «Хорошее начало!» в случае, если `steps` меньше 10% от `goal`, «Вы на пути к половине цели!», если `steps` меньше, чем половина `goal`, «Вы уже выполнили больше половины своей цели!», если `steps` меньше, чем 90% от `goal`, «Вы почти достигли цели!», если `steps` меньше `goal`, и «Вы выполнили вашу цель!» в противном случае. Вызовите функцию и зафиксируйте результат. Вызовите функцию несколько раз, передавая ей различные значения `steps` и `goal`. Зафиксируйте результаты и убедитесь, что она выдаёт то, что вы ожидаете, для каждой из пары параметров, переданных в функцию. */ func progressUpdate(steps: Int, goal: Int) -> Void { let result = Double(steps) / Double(goal) * 100 switch result { case 0...10: print("Хорошее начало!") break case 10...50: print("Вы на пути к половине цели!") break case 50...90: print("Вы уже выполнили больше половины своей цели!") break case 90...99: print("Вы почти достигли цели!") break default: print("Вы выполнили вашу цель") } } progressUpdate(steps: 200,goal: 10000) progressUpdate(steps: 3000,goal: 5000) progressUpdate(steps: 6000,goal: 20000) progressUpdate(steps: 9200, goal: 10000) progressUpdate(steps: 11000, goal: 12000) /*: Ваше фитнесс-приложение поможет бегунам не выбиться из графика для достижения их целей. Напишите функцию `pacing`, принимающую четыре параметра типа `Double`, называющиеся `currentDistance` (текущее расстояние), `totalDistance` (общее расстояние), `currentTime` (текущее время) и `goalTime` (целевое время). Функция должна вычислить, не выбивается ли бегун из графика, чтобы достичь или побить цель `goalTime`. Если не выбивается, напечатайте «Держите темп!», в противном случае напечатайте «Вам нужно ускорить темп, чтобы успеть!» */ func pacing(currentDistance: Double, goalDistance: Double, currentTime: Double, goalTime: Double) -> Void { let goalSpeed = goalDistance / goalTime let currentSpeed = currentDistance / currentTime if currentSpeed >= goalSpeed { print("Держите темп!") } else { print("Вам нужно ускорить темп, чтобы успеть!") } } pacing(currentDistance: 1000, goalDistance: 10000, currentTime: 350, goalTime: 3000) pacing(currentDistance: 1000, goalDistance: 3000, currentTime: 20, goalTime: 800) //: [Ранее](@previous) | страница 4 из 6 | [Далее: Упражнение — Возвращение результатов](@next)
C#
UTF-8
693
2.515625
3
[ "MIT" ]
permissive
using Amadevus.RecordGenerator.TestsBase; using System; using Xunit; namespace Amadevus.RecordGenerator.Test { public class RecordConstructorTests : RecordTestsBase { [Fact] public void Ctor_HasParametersNamedLikeProperties() { new Item(id: ItemId, name: ItemName); } [Fact] public void Ctor_InvokesOnConstructed_Throwing() { Assert.Throws<ArgumentNullException>(nameof(Item.Name), () => new ValidatingRecord(null, "a")); } [Fact] public void Ctor_InvokesOnConstructed_Passing() { Assert.NotNull(new ValidatingRecord(ItemName, "test")); } } }
Markdown
UTF-8
10,199
2.640625
3
[]
no_license
# Pretraining language models on SNLI This repository contains code for pre-training and evaluating 4 different language models pre-trained on the SNLI (inference) task. The inference is performed by a shallow linear classifier that works on the output of one of the 4 encoder models: * The baseline encoder averages the word vectors of a sentence * A unidiractional LSTM encoder * A bidirectional LSTM encoder * A bidirectional LSTM encoder with max pooling ## Pre-requisits The reuired packages can be installed using the requirements.txt. Besides that, the SentEval package has to be installed for evaluation. For that, follow the installation and download guide in https://github.com/facebookresearch/SentEval. Note: the SentEval package has to be in the root directory of this project The models are not included in the github repository nor in the archive as they are too large. They can be downloaded from [this drive](https://drive.google.com/drive/folders/1I5Mj2E7MUxBeyYA-mjkpHKqAxtRHc2dc?usp=sharing). The drive contains the full "runs" folder with all the runs, models included, in case you want to use them, just replace the "runs" folder here with the one on the drive. This project is available at [this repository](https://github.com/BalintHompot/SemanticsPrcticalSNLI). ## Usage The main entry point of the project is trainMain which calls the separate functions from trainFunctions and performs the whole task end-to-end from parameter sweeping through model trainig and storing to SentEval results. When called, the full task is performed with the arguments coded into the script, however it can be customized and the train functions can be called separately (e.g. sweeping can be skipped to directly train a model). For customization, the easiest way to change which encoders are investigated, what parameter ranges are used for sweeping, and what are the default parameters is to edit this main script at the corresponding sections. The easiest way to construct a model with custom parameters is to define a config file and use it at constructions. The examples.ipynb closely follows the trainMain to show how the separate functions of the project can be used. It also gives easy to use examples to show how customization can be done. It also contains the analysis of the project results. I recommend to start at this file and the usage will quickly become clear. Note: the usage of the project is centered around "run"-s. The user can pass runName to the functions that involve storing, loading or checking for files: the outputs will be stored in the corresponding directory (created automatically), loaded from there, and the functions will check in those directories if there are already stored params/models for the run with the given name. In all functions this runName defaults to "best" (the idea is that the sweeping is performed so we are storing the best). For further information on the files and functions, see the documentation below. ## Documentation The scripts and folders in the project's root directory are listed here. ### trainMain.py This is the main function of the project which calls or imports the rest. In this, we import the data, define a set of default encoder parameters and ranges for the parameters to be optimized. Then for each encoder class the code will: * Run parameter sweeping and store the best parameters (this is skipped if best params are found, and sweep is not forced) * Construct a model with the found parameters and train it (this is skipped if stored trained best model is found and retrain is not forced) * Test the model on the test set and save the model and results * Test the model using SentEval. The details for these are in the following files. ### encoder.py Contains the classes of the 4 encoder models and their parent class ### model.py Contains the SNLI predictor class. It takes an encoder as an argument and uses it as it's encoder, extending it with the shallow classifier ### utils.py Contains data loading and accuracy calculation script as well as the results printing function which can be called separately: **printResults**: * input: * encoderNames: list of encoder names to be included in the table * resultType: the results to be included, SNLI for dev and test, SentEval, or SNLI+transfer, the latter contains micro and macro avg of senteval tasks * runName: the name of the run for which results are printed * output: None, only printing ### trainFunctions.py This file contains the model training functions that are called when performing the pretraining. The most important ones that are directly called: **paramSweep** Runs parameter sweeping and stores the best ones in the corresponding folder. Note: the parameters are searched one by one while leaving the rest at default. This is to reduce search time, although in principle it does not neccessarily give the best parameter setting as they are not properly searched on a grid. * input: * encoderClass: an encoder class (not an instance) * data: the data as imported using the utils * default_config: a dictionary of default parameters, containing the ones that are sweeped: lr for starting learning rate, lr_decrease_factor for the decrease factor when val accuracy drops, lr_stopping for stopping the training when lr drops below this, layer_num for the number of hidden layers (not used in baseline encoder), layer_size for the dimensionality of hidden layers (not used in baseline encoder) * param_ranges: a dictionary of parameter ranges to be investigated. Same parameters as in the default config. * metadata: a dictionary of metadata, params that are not optimized: vector_size, vocab_size, pretrained for pretrained embeddings and pad_idx for the index of the padding token * forceOptimize: boolean, when set to true, the sweeping will be performed een if there is already a stored best param for the encoder. Checked for each param separately. * runName: string, the name of the run. The script creates a folder for _configs with this prefix to store the output. Defaults to "best" * output: a dict with the best params **construct_and_train_model_with_config** Constructs the SNLI classifier model with a given config, then calls train. * input * encoderClass: the encoder class to be used (not an instance) * data: the data as imported using utils * config: dict with the params that are sweeped * metadata: dict with the params that are not searched * forceRetrain: boolean, when set to true, construction and training is performed even if a best model is stored for the given encoder * runName: string, the name of the run. The script checks if there is a stored model in the folder _models with this prefix and the given encoderClass's name. Defaults to "best" * output: the trained model **trainModel** The function that performs the actual training * input * model: an SNLI classifier model instance * data: the data as imported using utils * optimizer: the optimizer for the training * lr_threshold: training stops when lr drops below this * lr_decrease_factor: lr is decreased by this factor when an epoch drops in validation accuracy * plotting: boolean, when True, a plot will be saved with the losses and accuracies (not tested on the current version, leave it False) * output: the trained model and the last validation accuracy **testModel** The function that performs testing on the set aside data. * input * model: a trained SNLI encoder instance * data: the data as imported using utils * output: dev and test accuracy in a dict **save_model_and_res** Stores the model and the results in the corresponding folders (folders are hard coded, edit script to change) * input * model: a trained SNLI encoder instance * results: a dict with the results * runName: string, the name of the run. The script creates folders _models and _model_results with this prefix to store the outputs. Defaults to "best" * output: none **testExample** Prompts the user to give premises and hypotheses (in a loop). For each pair, prints the model's verdict on entailment * input: * modelName: string, the model's name to be tested * texField: torchtext Field that contains the preprocessing. If nothing givem, the code creates automatically * labelField: torchtext Field that contains the mapping from output index to verdict. If nothing givem, the code creates automatically. * runName: the name of the run from which the model is loaded * output: None, only printing ### sentEval.py Contains the code for running the sentEval benchmark. The function runSentEval can be called with passing a model, a torchtext Field that contains the text preprocessing pipeline (this is normally obtained when getting the data with utils), and optionally a list of tests that will be performed. This defaults to 'all' which runs all tests, but the string 'paper' can also be passed which performs the tasks reported in [the Conneau et al paper](https://arxiv.org/pdf/1705.02364.pdf). The runName can be passed similarly to the other functions to store the output. ### example.ipynb This is a jupyter notebook to present the usage and results of the project. It follows trainMain closely with some added examples on how to customize the pipeline. It also contains the analysis of results ### trainMain.job The job file that was submitted to the Lisa cluster ### requirements.txt The packages needed to run the project ### runs The user can give names to runs when performing the functions. For each run, a directory will be placed under the the runs directory with the given name. The new directory will contain 3 subdirectories: runName_configs with the used configs (either created by user or found during sweeping), runName_models with the trained models for each encoder, and runName_model_results with the SNLI and SentEval results for each encoder. Currently there are two run outputs: the "best" was done with the reported params in the paper with Adam and appropriately changed lr, the "sgd" is the same but with SGD optimizer and lr changed back. ### logs slurm output of the runs on the Lisa cluster
C++
UTF-8
681
3.28125
3
[]
no_license
#include<iostream> #include<vector> #include<algorithm> using namespace std; int main() { vector<int> intVec; INSERT_ELEMENTS(intVec,1,9); vector<int>::iterator pos; pos = find(intVec.begin(),intVec.end(),5); if(pos != intVec.end()) cout << "The value 5 exists,and its position is " << distance(intVec.begin(),pos) + 1 << endl; else cout << "The value 4 not found!" << endl; pos = find(intVec.begin(),intVec.end(),12); if(pos != intVec.end()) cout << "The value 12 exists,and its position is " << distance(intVec.begin(),pos) + 1 << endl; else cout << "The value 12 not found!" << endl; }
TypeScript
UTF-8
2,252
2.546875
3
[ "MIT" ]
permissive
import { Component, Input, ViewChild } from '@angular/core'; import { AbstractControl, ControlContainer, ControlValueAccessor, FormControlDirective, NG_VALUE_ACCESSOR } from '@angular/forms'; import { get, has } from 'lodash-es'; @Component({ selector: 'error-messages', template: `<span *ngFor="let item of filteredErrors"> {{ item }}<br /></span>`, providers: [ { provide: NG_VALUE_ACCESSOR, useExisting: ErrorMessagesComponent, multi: true, }, ], }) export class ErrorMessagesComponent implements ControlValueAccessor { @ViewChild(FormControlDirective, { static: true }) formControlDirective!: FormControlDirective; @Input() formControl: FormControl | undefined; @Input() formControlName: string | undefined; // Substitute messages for these error types private replacements: { [id: string]: string } = { matDatepickerMax: 'Date must be before {max}', matDatepickerMin: 'Date must be after {min}', matDatepickerParse: 'Invalid date', min: 'Cannot be less than {min}', required: 'This field is required', }; get filteredErrors(): string[] { const ctrl = this.getControl(); if (!ctrl || !ctrl.errors) return []; return Object.keys(ctrl.errors || {}).map((key: string) => this.processedMessage(key, ctrl.errors![key])); } constructor(private controlContainer: ControlContainer) {} private processedMessage(key: string, originalValue: string): string { return !has(this.replacements, key) ? originalValue : this.replacements[key].replace(/{([^}]*)}/, (str: string, match: string) => { let value = get(originalValue, match, ''); return value; }); } /* Resolve FormControl instance no matter `formControl` or `formControlName` is given. If formControlName is given, then this.controlContainer.control is the parent FormGroup (or FormArray) instance. */ private getControl(): AbstractControl | undefined { return this.formControl || (!!this.formControlName && this.controlContainer.control?.get(this.formControlName)) || undefined; } /* As we don't manipulate with control, provide a stub on 'ControlValueAccessor' implementation */ registerOnChange(_: (value?: string) => void): void {} registerOnTouched(_: () => {}): void {} writeValue(_: string): void {} }
Python
UTF-8
1,916
2.6875
3
[ "Apache-2.0" ]
permissive
#!/usr/bin/evn python #coding:utf-8 import MySQLdb class MysqlHelper(object): def __init__(self): self.__Host = 'kali' self.__User = 'dbuser' self.__Passwd = '0110' self.__DB = 'web' def __Conn(self): try: conn = MySQLdb.connect(host=self.__Host,user=self.__User,passwd=self.__Passwd,db=self.__DB) except Exception,e: conn = None return conn def GetSingle(self,sql,paramters): conn = self.__Conn() if not conn: return None try: cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) cur.execute(sql,paramters) #cur.execute("select Name,Nickname from admin where Name=%s",(admin,)) data = cur.fetchone() print data except Exception,e: data =None #写个日志 finally: cur.close() conn.close() return data def AddUser(self,sql,paramters): conn = self.__Conn() cursor = conn.cursor() print sql,paramters try: cursor.execute(sql,paramters) conn.commit() except: conn.rollback() class admin(object): def __init__(self): self.__helper = MysqlHelper() def GetSingle(self,param): sql = "select Name,Nickname from admin where Name=%s" para = (param,) return self.__helper.GetSingle(sql,para) def AddUser(self,param,password): sql = "INSERT INTO userinfo(username,password) VALUES (%s,%s)" #INSERT INTO `web`.`userinfo` (`id`, `username`, `password`) VALUES ('3', 'abc', 'abc'); para = (param,password,) return self.__helper.AddUser(sql, para) if __name__=="__main__": a = admin() print a.GetSingle('admin') #print a.AddUser('a01','a01')
Python
UTF-8
1,588
3.421875
3
[]
no_license
import random import numpy as np import matplotlib.pyplot as plt ''' creates random coords, used to generate data for testing other functions number: amount of coords desired a, b: ranges, must be a > b return: arrayx = x only coords arrayy = y only coords other = xy coords ''' def nCoords(number, a, b): arrayx = [] arrayy = [] other = [] for i in range(number): x = random.randint(a, b) y = random.randint(a, b) c = [x, y] arrayx.append(x) arrayy.append(y) other.append(c) return arrayx, arrayy, other def file_len(filename): with open(filename) as doc: for i, l in enumerate(doc): pass return i + 1 def cleanLine(line): char = "[]\n" for c in char: line = line.replace(c, "") line = line.lower() return line def openCoords(filename): x, y, xy = [], [], [] a = file_len(filename) doc = open(filename, 'r') for i in range(a): line = doc.readline() line = cleanLine(line) coord = line.split(',') xx = float(coord[0]) yy = float(coord[1]) x.append(xx) y.append(yy) xxyy = [xx, yy] c = np.array(xxyy) xy.append(c) return x, y, xy def graphPoints(arrayx, arrayy): plt.scatter(arrayx, arrayy) plt.xlabel('x') plt.ylabel('y') plt.show() def maxmins(x, y): a = max(x) b = min(x) c = max(y) d = min(y) v = [a, b, c, d] return v
PHP
UTF-8
5,701
3.203125
3
[]
no_license
<?php use Resource\Native\Object; use Resource\Native\Mystring; /** * The URL Class, it is part of the utility package and extends from the Object Class. * It implements PHP basic url functions, and adds enhanced features upon them. * a URL object is immutable, once set it cannot be altered with setter methods. * @category Resource * @package Utility * @author Hall of Famer * @copyright Mysidia Adoptables Script * @link http://www.mysidiaadoptables.com * @since 1.3.2 * @todo Not sure, but will come in handy. */ final class URL extends Object { /** * REGEX constant, it is used to identify valid and invalid url. */ const REGEX = "/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i"; /** * The scheme property, stores the scheme of the url. * @access private * @var String */ private $scheme; /** * The host property, stores the host of the url. * @access private * @var String */ private $host; /** * The path property, specifies the path portion of the url string. * @access private * @var String */ private $path; /** * The query property, specifies the query portion of this string. * @access private * @var String */ private $query; /** * The fragment property, determines the fragment section of the sting, if it exists. * @access private * @var String */ private $fragment; /** * The url property, defines the entire url string that can be referenced later. * @access private * @var String */ private $url; /** * Constructor of URL Class, it validates and sets up a URL object, can perform parser operations. * @param String $url * @param Boolean $parse * @access publc * @return Void */ public function __construct($url, $validate = false, $parse = false) { $mysidia = Registry::get("mysidia"); if ($validate and !$this->isValid($url)) { throw new UrlException('The specified URL is invalid.'); } $this->url = (!preg_match(self::REGEX, $url))?$mysidia->path->getAbsolute().$url:$url; if ($parse) { $this->parseURL(); } } /** * The getScheme method, getter method for property $scheme. * @access public * @return String */ public function getScheme() { return $this->scheme; } /** * The getHost method, getter method for property $host. * @access public * @return String */ public function getHost() { return $this->host; } /** * The getPath method, getter method for property $path. * @access public * @return String */ public function getPath() { return $this->path; } /** * The getQuery method, getter method for property $query. * @access public * @return String */ public function getQuery() { return $this->query; } /** * The getFragment method, getter method for property $fragment. * @access public * @return String */ public function getFragment() { return $this->fragment; } /** * The getURL method, getter method for property $url. * @access public * @return String */ public function getURL() { return $this->url; } /** * The isValid method, checks if the url is valid. * For absolute path, it validates the url string. For relative path, it checks if the file exists. * @param String $url * @access private * @return String */ private function isValid($url) { if (preg_match(self::REGEX, $url)) { return true; } elseif (file_exists($url)) { return true; } else { return false; } } /** * The parseURL method, parses the url and assigns useful URL properties. * @access public * @return Void */ public function parseURL() { $url = parse_url($this->url); $this->scheme = $url['scheme']; $this->host = $url['host']; if (isset($url['path'])) { $this->path = $url['path']; } if (isset($url['query'])) { $this->query = $url['query']; } if (isset($url['fragment'])) { $this->fragment = $url['fragment']; } } /** * The addQueryString method, create a new URL object from the given additional parameters. * @param Array $params * @access public * @return String */ public function addQueryString(array $params) { if (empty($params)) { throw new UrlException('The specified query string parameters are invalid.'); } $queryString = ''; foreach ($params as $key => $value) { $queryString .= '&' . $key . '=' . urlencode($value); } $queryString = $this->queryString === null ?trim($queryString, '&'):$this->queryString . $queryString; $url = $this->scheme . '://' . $this->host . $this->path . '?' . $query; return new URL($url); } /** * Magic method __toString for URL class, it outputs the parsed url in string format. * It should only be used if the URL has been parsed, otherwise use URL::getURL instead. * @access public * @return String */ public function __toString() { return $this->host.$this->path.$this->query.$this->fragment; } }
C#
UTF-8
1,773
2.515625
3
[ "MIT" ]
permissive
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemyController2 : MonoBehaviour { public float fireDelay = 1f; public int onFireProjectileCount = 3; // private int projectilesFired = 0; public GameObject projectile; private float timeSinceLastFire = 0f; private float maxPositionX = 1f; private float minPositionX = 0f; private bool movingRight = true; public float movementSpeed = .1f; // Start is called before the first frame update void Start() { // tamaño pantalla // Screen.width // tamaño de la nave // SpriteRenderer sr = GetComponent<SpriteRenderer>(); // float spriteWidth = sr.sprite.rect.width; // maxPositionX = Screen.width - (spriteWidth / 2); // minPositionX = 0 + (spriteWidth / 2); } // Update is called once per frame void Update() { var pos = Camera.main.WorldToViewportPoint(transform.position); pos.x = Mathf.Clamp01(pos.x); pos.y = Mathf.Clamp01(pos.y); timeSinceLastFire += Time.deltaTime; if (movingRight) { // El enemigo se movera a la derecha transform.Translate(new Vector2(movementSpeed, 0f)); if (pos.x >= maxPositionX) { // El enemigo se movera a la izquierda movingRight = false; } } else { // el enemigo se movera a la izquierda transform.Translate(new Vector2(-movementSpeed, 0f)); //el enemigo se movera a la derecha if (pos.x <= minPositionX) { movingRight = true; } } } }
JavaScript
UTF-8
1,498
2.703125
3
[]
no_license
document.addEventListener("DOMContentLoaded", function(event) { getStartTransactionActionElement() .addEventListener("click", onStartTransactionClicked); getViewProductsActionElement().addEventListener( "click", () => { window.location.assign("/productListing"); }); getCreateEmployeeActionElement().addEventListener( "click", () => { window.location.assign("/employeeDetail"); }); getProductSalesReportActionElement().addEventListener( "click", () => { displayError("Functionality has not yet been implemented."); }); getCashierSalesReportActionElement().addEventListener( "click", () => { displayError("Functionality has not yet been implemented."); }); }); function onStartTransactionClicked() { ajaxPost("/api/transaction/", {}, (callbackResponse) => { if (isErrorResponse(callbackResponse)) { return; } window.location.assign(callbackResponse.data.redirectUrl); }); } // Getters and setters function getViewProductsActionElement() { return document.getElementById("viewProductsButton"); } function getCreateEmployeeActionElement() { return document.getElementById("createEmployeeButton"); } function getStartTransactionActionElement() { return document.getElementById("startTransactionButton"); } function getProductSalesReportActionElement() { return document.getElementById("productSalesReportButton"); } function getCashierSalesReportActionElement() { return document.getElementById("cashierSalesReportButton"); } // End getters and setters
Java
UTF-8
1,836
2.140625
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.logikas.kratos.core.osgi; import com.google.common.eventbus.EventBus; import com.google.inject.Inject; import com.logikas.kratos.core.module.Module; import com.logikas.kratos.core.module.event.CoreEventBus; import com.logikas.kratos.core.module.event.ModuleInitializedEvent; import com.logikas.kratos.core.module.event.ModuleShutdownEvent; import com.logikas.kratos.core.module.impl.CoreModule; import java.util.Map; import org.ops4j.peaberry.Import; import org.ops4j.peaberry.util.AbstractWatcher; /** * kratos Core OSGI Bundle * * Documentation of Class WatcherCore * * * Package: com.logikas.kratos.core.osgi Last modification: 06/11/2012 File: * WatcherCore.java * * @author Cristian Rinaldi cristian.rinaldi@logikas.com Logikas - Conectando * Ideas. * */ public class WatcherCore extends AbstractWatcher<Module> { private final CoreEventBus eventBus; @Inject public WatcherCore(final CoreEventBus eventBus) { System.out.println("\nCreando el Watcher\n"); this.eventBus = eventBus; } @Override protected Module adding(Import<Module> service) { System.out.println("\nLanzando el Evento "+service.get().getName()+"\n"); this.eventBus.post(new ModuleInitializedEvent(service.get())); return super.adding(service); } @Override protected void removed(Module instance) { System.out.println("\nLanzando el Evento "+instance.getName()+"\n"); this.eventBus.post(new ModuleShutdownEvent(instance)); super.removed(instance); } @Override protected void modified(Module instance, Map<String, ?> attributes) { System.out.print("\n" + instance.getName() + "is ADD\n"); super.modified(instance, attributes); } }
Python
UTF-8
5,116
3.046875
3
[]
no_license
import numpy as np import pandas as pd import matplotlib.pyplot as plt import random import pdb class ff_net: '''Class represents a generalized, fully-connected neural network using the frame work discussed in Rojas Chpt. 7''' def __init__(self, layers): self.layers = layers #List of layer sizes self.input = None #Input layer - 'o' vector in Rojas self.output = None #Output layer self.e = None #Error for current data point self.activations = [] #list of activation values throughout each forward prop self.W_bar = [] #list of connection matrices (num layers - 1) self.D = [] #list of gradient matrices self.d = [] #list of backpropagated erros self.rmse = np.array([]) #variable to hold data for plotting rmse during training self.learn_rate = 1.0 #Learning rate self.decay_rate = 1.0 #Learning rate decay self.lr_decay = np.array([]) #variable to hold data for plotting learning rate decay for i in range(len(layers) - 1): self.W_bar.append(np.random.randn(self.layers[i] + 1, self.layers[i+1])) #self.W_bar.append(np.random.normal(0, 0.1, (self.layers[i] + 1, self.layers[i+1]))) def clear_rmse(self): self.rmse = np.array([]) def set_lr_stats(self, learn_rate, decay_rate = 1.0): self.learn_rate = learn_rate self.decay_rate = decay_rate def decay(self): self.learn_rate *= self.decay_rate def plot_lr_decay(self, path = None): if self.lr_decay.shape == (0,): print ('ERROR: No Learning-rate decay data') return plt.figure() plt.plot(self.lr_decay) plt.xlabel('Number of training examples seen') plt.title('Learning-rate Decay During Backprop') if path is None: plt.show() else: plt.savefig(path) def plot_rmse(self, win1 = 100, win2 = 500, path = None): if self.rmse.shape == (0,): print ('ERROR: No RMSE data') return df = pd.DataFrame(self.rmse) ma1 = df.iloc[:,0].rolling(window = win1).mean().values ma2 = df.iloc[:,0].rolling(window = win2).mean().values plt.figure() plt.plot(self.rmse, color = 'gray', alpha = 0.6, label = 'Raw') plt.plot(ma1, color = 'red', label = 'MA - ' + str(win1) + ' periods') plt.plot(ma2, color = 'blue', label = 'MA - ' + str(win2) + ' periods') plt.xlabel('Number of examples seen') plt.ylabel('RMSE') plt.title('RMSE During Backprop') plt.legend() if path is None: plt.show() else: plt.savefig(path) def set_input(self, data_in): self.activations = [] # If input is a row vector, assign to class and add bias term for activation if data_in.shape == (1, self.layers[0]): self.input = data_in elif data_in.shape == (self.layers[0], 1): self.input = data_in.T else: print ('Input data dim doesn\'t match network input layer dim') return self.activations.append(np.hstack((self.input, np.array([[1]])))) #Add bias term def sigmoid(self, x): return 1.0 / (1.0 + np.exp(-x)) def d_sig(self, x): sig = self.sigmoid(x) return np.multiply(sig, (1 - sig)) def forward_prop(self, label): if self.input is None: print ('No input data') return ## Loop through all but last activation as last activation ## excludes bias term self.D = [] for i in range(len(self.W_bar) - 1): z = np.dot(self.activations[i], self.W_bar[i]) self.activations.append(np.hstack((self.sigmoid(z), np.array([[1]])))) #Add bias term self.D.append(np.diagflat(self.d_sig(z))) #Exclude bias term in gradients z = np.dot(self.activations[-1], self.W_bar[-1]) self.activations.append(self.sigmoid(z)) #Exclude bias term for output activation self.D.append(np.diagflat(self.d_sig(z))) #Exclude bias term in gradients self.output = self.activations[-1].copy() self.e = self.output.T - label # e is supposed to be a column vector #self.e += (self.output.T - label) # e is supposed to be a column vector self.rmse = np.append(self.rmse, np.sqrt(np.dot(self.e.T, self.e))) def back_prop(self): if self.output is None: print ('No output data') return self.d = [] self.d.append(np.dot(self.D[-1], self.e)) if len(self.D) > 1: for i in range(len(self.D) - 2, -1, -1): self.d.insert(0, np.dot(np.dot(self.D[i], self.W_bar[i+1][:-1,:]), self.d[0])) for i in range(len(self.d)): self.W_bar[i] += (-self.learn_rate * np.dot(self.d[i], self.activations[i])).T self.lr_decay = np.append(self.lr_decay, self.learn_rate)
Markdown
UTF-8
614
2.71875
3
[ "MIT" ]
permissive
# libeuler `libeuler` calculates an approximation of the base `e` of the [natural logarithm](https://en.wikipedia.org/wiki/Natural_logarithm). ### Method The approximation is done using the equation ![](doc/formula.png) where the value of `e` gets more accurate as `n` gets bigger and bigger. ### Dependencies * [libexponent](https://github.com/mathinjenkins/libexponent) ### Build * `git clone git@github.com:mathinjenkins/libeuler.git` * `cd libeuler` * `mkdir build && cd build` * `cmake ../` * `make` * `./test/euler_test` ### License [MIT License](https://github.com/mathinjenkins/libeuler/blob/master/LICENSE)
Python
UTF-8
3,357
2.515625
3
[]
no_license
if __name__ == "__main__": import os import time import signal # --------------------------- LOAD ENV VARIABLES --------------------------- from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) os.environ["PY_ENV"] = "production" print('----------------------------------') print('Running in {} mode'.format(os.getenv('PY_ENV'))) print('----------------------------------') # --------------------------- LOGGING --------------------------- from pathlib import Path from logging.handlers import RotatingFileHandler import logging # Ensure logs directory exists logs_filepath = os.getenv('LOGGING_FILEPATH') if '~' in logs_filepath: logs_filepath = logs_filepath.replace('~', str(Path.home())) logs_filepath = Path(logs_filepath) logs_filepath.parent.mkdir(exist_ok=True, parents=True) max_bytes = 10 * 1024 * 1024 # 10MB rh = RotatingFileHandler(logs_filepath, maxBytes=max_bytes, backupCount=5) sh = logging.StreamHandler() logging.basicConfig( handlers=[rh, sh], format=os.getenv('LOGGING_FORMAT'), datefmt=os.getenv("LOGGING_DATEFMT"), level=getattr(logging, os.getenv("LOGGING_LEVEL")) ) PID_FILEPATH = os.getenv('PID_FILEPATH') while True: try: # --------------------------- Handle PID --------------------------- with open(PID_FILEPATH, 'r+') as pid_file: pid = pid_file.read() if pid: for pid in pid.strip().split('\n'): logging.info('Killing: {}'.format(pid)) # kill previous instance try: os.kill(int(pid), signal.SIGTERM) except ProcessLookupError: pass pid_file.seek(0) pid_file.truncate() except FileNotFoundError as e: pass except Exception as e: logging.error(e) # wait before retrying time.sleep(0.05) pid = os.getpid() logging.info('Starting PID: {}'.format(pid)) with open(PID_FILEPATH, 'a') as pid_file: pid_file.write(str(pid) + '\n') # --------------------------- UNHANDLED EXPCETIONS --------------------------- # Only catches exceptions that occur outside of application import sys, traceback from lib import mac_dialogs def handle_uncaught_exceptions(exctype, value, tb): exception_string = ''.join(traceback.format_list(traceback.extract_tb(tb))) logging.error(exception_string) mac_dialogs.confirm(message='Application encountered a fatal error\nContact the developer', title='WeChat Downloads Fatal Error') excepthook(exctype, value, tb) excepthook = sys.excepthook sys.excepthook = handle_uncaught_exceptions # --------------------------- START APP --------------------------- from src.WeChatDownloadsApp import WeChatDownloadsApp app = WeChatDownloadsApp(name=os.getenv('APP_NAME'), settings=os.getenv('SETTINGS_FILENAME')) logging.info('Running in {} mode'.format(os.getenv('PY_ENV'))) app.run()
Java
UTF-8
762
2.34375
2
[ "MIT" ]
permissive
package com.mpatric.mp3agic; import org.junit.Test; import static org.junit.Assert.*; public class ID3v1GenresTest { @Test public void returnsMinusOneForNonExistentGenre() { assertEquals(-1, ID3v1Genres.matchGenreDescription("non existent")); } @Test public void returnsCorrectGenreIdForFirstExistentGenre() { assertEquals(0, ID3v1Genres.matchGenreDescription("Blues")); } @Test public void returnsCorrectGenreIdForPolka() { assertEquals(75, ID3v1Genres.matchGenreDescription("Polka")); } @Test public void returnsCorrectGenreIdForLastExistentGenre() { assertEquals(147, ID3v1Genres.matchGenreDescription("Synthpop")); } @Test public void ignoresCase() { assertEquals(137, ID3v1Genres.matchGenreDescription("heavy METAL")); } }
C++
UTF-8
1,851
2.75
3
[]
no_license
/* MD_AButton.h - Arduino library to handle multiple buttons on one analog input. Copyright (C) 2013 Marco Colli All rights reserved. This library 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 2.1 of the License, or (at your option) any later version. This library 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 this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _MD_ABUTTON_H #define _MD_ABUTTON_H #include <Arduino.h> // Miscellaneous defines #define KEY_ADC_PORT A0 #define KEY_NONE '\0' #define ARRAY_SIZE(x) (sizeof(x)/sizeof(x[0])) // MD_AButton class to one analog input button stream class MD_AButton { public: MD_AButton(uint8_t keyPin); ~MD_AButton(void); // Data handling void setKeyId(uint8_t id, char c); // set the return value for key with id void setDetectTime(uint16_t t); // set the detect time for a key void setRepeatTime(uint16_t t); // set the repeat time for a key char getKey(void); // read value and determine the key pressed // returns KEY_NONE if no key found protected: uint8_t _keyPin; // analog input port uint32_t _lastReadTime; // last time the pin was read uint32_t _lastKeyTime; // last time a key was returned char _lastKey; // last key value read uint16_t _timeDetect; // time between keys detected uint16_t _timeRepeat; // time for auto-repeat }; #endif
JavaScript
UTF-8
1,538
2.75
3
[]
no_license
const sqlite3 = require('sqlite3').verbose(); const fs = require('fs'); const db_path = 'db.sqlite3'; const populateFlag = !fs.existsSync(db_path); let db = new sqlite3.Database(db_path); if (populateFlag) { populateDB(); } function resetDB(cb) { db.close(function() { try { fs.unlinkSync(db_path); } catch (e) { // Ignore Error } db = new sqlite3.Database(db_path); populateDB(); cb(); }); } function populateDB() { db.serialize(function() { db.run("CREATE TABLE IF NOT EXISTS comments (id INTEGER PRIMARY KEY, name TEXT, comment TEXT)"); createComment("Grant", "Hi everybody!"); createComment("Baxter", "What an amazing and wonderful site!"); db.run("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, username TEXT, password TEXT)"); const userStmt = db.prepare("INSERT INTO users(username, password) VALUES(?, ?)"); userStmt.run("admin", "supersecretReallyUnbreakableAdmin"); userStmt.run("user", "password123"); userStmt.finalize(); }); } function createComment(name, comment, cb) { const stmt = db.prepare("INSERT INTO comments(name, comment) VALUES(?, ?)"); stmt.run(name, comment); stmt.finalize(cb); } function getComments(cb) { const query = "SELECT * FROM comments"; let comments = []; db.serialize(function() { db.all(query, function(err, rows) { if (err) { throw err; } cb(rows); }) }); } module.exports = { db: db, getComments: getComments, createComment: createComment, resetDB: resetDB, };
Python
UTF-8
3,067
2.65625
3
[ "MIT" ]
permissive
import numpy as np import cv2 from time import sleep import math from threading import Thread # -------------------V--OPENCV--V---------------------- cap = cv2.VideoCapture(0) ##fgbg = cv2.createBackgroundSubtractorMOG2() tempret, initframe = cap.read() #sleep(1) calib = cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2GRAY) prev_frame = cv2.cvtColor(initframe, cv2.COLOR_BGR2GRAY) height, width = initframe.shape[:2] fov = 75.0 # Degrees trackball_radius = 2.0 pixel_ang_size = fov/width font = cv2.FONT_HERSHEY_SIMPLEX def opencv_loop(): while(True): _, frame = cap.read() ##gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) ##res = cv2.subtract(calib, gray) ##_, blurskinthresh = cv2.threshold(cv2.medianBlur(res,5), 50, 255, cv2.THRESH_BINARY) lower_blue = np.array([70,10,75]) upper_blue = np.array([100,255,255]) mask = cv2.inRange(hsv, lower_blue, upper_blue) mask = cv2.medianBlur(mask, 5) blue = cv2.bitwise_and(frame,frame, mask= mask) ##graythresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1) ##_, graythresh = cv2.threshold(gray, 115, 255, cv2.THRESH_BINARY) ##change = cv2.subtract(gray, prev_frame) ##fgmask = fgbg.apply(frame) ##_, fg = cv2.threshold(fgmask, 250, 255, cv2.THRESH_BINARY) ##_, changethresh = cv2.threshold(change, 115, 255, cv2.THRESH_BINARY) ##changethresh = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 115, 1) circles = cv2.HoughCircles(cv2.medianBlur(mask, 5),cv2.HOUGH_GRADIENT,1,20,param1=1,param2=10,minRadius=5,maxRadius=0) try: if circles.any(): circles = np.uint16(np.around(circles)) # draw the outer circle cv2.circle(frame,(circles[0][0][0],circles[0][0][1]),circles[0][0][2],(0,0,255),2) # draw the center of the circle cv2.circle(frame,(circles[0][0][0],circles[0][0][1]),2,(0,0,255),3) # calculate positional data ang_size = float(circles[0][0][2]) * pixel_ang_size distance = trackball_radius / math.tan(math.radians(ang_size)) cv2.putText(frame,'ang_size: ' + str(ang_size),(50,400), font, 1,(255,255,255),2,cv2.LINE_AA) cv2.putText(frame,'distance: ' + str(distance/100) + "m",(50,470), font, 1,(255,255,255),2,cv2.LINE_AA) except: pass cv2.imshow('Original',frame) cv2.imshow('Blue', blue) ##cv2.imshow('Arms', blurskinthresh) ##cv2.imshow('Foreground', res) ##cv2.imshow('Foreground', fg) ##cv2.imshow('Movement Threshold', changethresh) ##prev_frame = gray k = cv2.waitKey(30) & 0xff if k == 27: break # -------------------V-- THREADING MANAGEMENT --V------------------ opencv_loop() cap.release() cv2.destroyAllWindows()
Python
UTF-8
16,985
2.921875
3
[]
no_license
# --------------------------------------- Description --------------------------------------- # # Python Vein Processor. This python file runs on a Laptop and receives near-infrared # hand images from a Raspberry Pi IoT device over wifi using a the custom I2P # appication protocol. It then applies various image processing techniques to extract # information about the veins in the hand. It then either enrols this information, or # attempts to match it to existing information. It returns PASS/FAIL to the IoT device. # Author: Bryan McSweeney 31/01/21 # Version: 1.0 # ----------------------------------- Imports and variables --------------------------------- # import socket import i2p import sys import os import numpy import pickle from cv2 import cv2 path = 'C:/Users/bryan/Desktop/College/FYP/Python Server/Hough/x1y1/' # folder to store images/vein data def convolve2d(image, kernel): kernel = numpy.flipud(numpy.fliplr(kernel)) # convolution output output = numpy.zeros_like(image) # Add zero padding to the input image image_padded = numpy.zeros((image.shape[0] + 2, image.shape[1] + 2)) image_padded[1:-1, 1:-1] = image # Loop over every pixel of the image for x in range(image.shape[1]): for y in range(image.shape[0]): # element-wise multiplication of the kernel and the image output[y, x]=(kernel * image_padded[y: y+3, x: x+3]).sum() return output # ------------------------------------- Set up I2P Server ----------------------------------- # try: My_Server = i2p.I2P_Server('',9916) except socket.error as error: print(error) My_Server.shutdown() sys.exit() # ----------------------------------------- Main Loop --------------------------------------- # try: while True: My_Server.accept() # Wait for new connection (!! BUG HERE !! CTRL+C does not Trigger KeyboardInterrupt # on windows while scipt is in a blocking wait) try: command = My_Server.receive() # command from client (enrol/identify) print('Command Received: ' + command) except socket.error as error: print(error) My_Server.close_connection() continue # means client closed connection. go back to accept a new connection try: image_data_bytes = My_Server.receive() # Receives image as byte-stream except socket.error as error: print(error) My_Server.close_connection() continue # means client closed connection. go back to accept a new connection image_data_array = numpy.frombuffer(image_data_bytes,dtype=numpy.uint8) # convert to numpy array image_data_array = image_data_array.reshape(1232,1640) # reshape array to match image size print('image received successfully') #---------------------------------------------------------------------------- # Thresholding, contour, Convex hull, hull defects, and mask creation #---------------------------------------------------------------------------- ret, silhouette = cv2.threshold(image_data_array,8,255,cv2.THRESH_BINARY) # create silhouette kernel = numpy.ones((5,5),numpy.uint8) # erosion kernel mask = cv2.erode(silhouette,kernel,iterations = 1) # mask creation by erosion contours, hierarchy = cv2.findContours(silhouette, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) # find contours of silhouette contours = max(contours, key=lambda x: cv2.contourArea(x)) # pick out biggest contour hull = cv2.convexHull(contours, returnPoints=False,clockwise=True) # construct convex hull hull[::-1].sort(axis=0) # sort hull (fix for BUG in the convexHull function) defects = cv2.convexityDefects(contours, hull) # get indices of defects #---------------------------------------------------------------------------- # Finger gap detection and Affline transformations #---------------------------------------------------------------------------- cnt = 0 finger_gaps = [] for i in range(defects.shape[0]): # loop over number of rows in defects s, e, f, d = defects[i][0] start = tuple(contours[s][0]) end = tuple(contours[e][0]) far = tuple(contours[f][0]) a = numpy.sqrt((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2) # distance formula b = numpy.sqrt((far[0] - start[0]) ** 2 + (far[1] - start[1]) ** 2) c = numpy.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2) angle = numpy.arccos((b ** 2 + c ** 2 - a ** 2) / (2 * b * c)) # cosine theorem if (angle <= numpy.pi / 2) & (a>25) & (b>45): # angle less than 90 degree, treat as fingers finger_gaps.append(far) cnt = cnt+1 if (cnt < 4): # if not enough fingers detected print('ERROR: not enough fingers detected..\n\n') try: My_Server.transmit('FAIL', None) # Report Failure to IoT Device except socket.error as error: print(error) My_Server.close_connection() continue except TypeError as error: print(error) My_Server.close_connection() except ValueError as error: print(error) My_Server.close_connection() My_Server.close_connection() continue # go back and wait for new connection finger_gap0 = finger_gaps[0] # seperate each tuple from the list finger_gap1 = finger_gaps[1] finger_gap2 = finger_gaps[2] finger_gap3 = finger_gaps[3] if (finger_gap0[0]>finger_gap3[0]): # Determine reference points point1 = finger_gap1 point2 = finger_gap3 else: point1 = finger_gap0 point2 = finger_gap2 slope = (point1[1]-point2[1])/(point1[0]-point2[0]) # determine slope of line between reference points angle = float(90) - (abs(numpy.arctan(slope))*180/numpy.pi) # determine angle of hand if (slope>0): # determine direction of desired rotation based on slope polarity angle = angle*-1 rot = cv2.getRotationMatrix2D(point1, angle, 1.0) # generate affline rotation matrix image_data_array = cv2.warpAffine(image_data_array, rot, image_data_array.shape[1::-1], flags=cv2.INTER_LINEAR) # rotate image mask = cv2.warpAffine(mask, rot, mask.shape[1::-1], flags=cv2.INTER_LINEAR) # rotate mask #---------------------------------------------------------------------------- # Median filtering and CLAHE #---------------------------------------------------------------------------- image_data_array = cv2.medianBlur(image_data_array, 5) # apply median blur clahe = cv2.createCLAHE(clipLimit=2,tileGridSize=(8,8)) # create CLAHE filter image_data_array = clahe.apply(image_data_array) # apply CLAHE #---------------------------------------------------------------------------- #Resizing #---------------------------------------------------------------------------- image_resized = cv2.resize(image_data_array, (410,308), interpolation=cv2.INTER_AREA) mask_resized = cv2.resize(mask, (410,308), interpolation=cv2.INTER_AREA) # resize mask to fit final image #---------------------------------------------------------------------------- # Gaussian Blur #---------------------------------------------------------------------------- image_resized = cv2.GaussianBlur(image_resized, (3,3),0) #---------------------------------------------------------------------------- # Ridge Detection, thresholding, thinning, hand-edge removal, and vein cropping #---------------------------------------------------------------------------- ridge_filter = cv2.ximgproc.RidgeDetectionFilter_create() # create ridge filter image_resized = ridge_filter.getRidgeFilteredImage(image_resized) # apply ridge filter ret,image_resized = cv2.threshold(image_resized,85,255,cv2.THRESH_BINARY) # apply binary threshold image_resized = cv2.ximgproc.thinning(image_resized, thinningType= cv2.ximgproc.THINNING_ZHANGSUEN) image_resized = cv2.bitwise_and(image_resized, image_resized, mask=mask_resized) # apply mask to remove hand-edges # crop area where veins should be, based on reference points cropped_veins = image_resized[((point1[1]//4)-50):((point2[1]//4)+50), ((point1[0]//4)-20):((point2[0]//4)+160)].copy() #---------------------------------------------------------------------------- # Line Detection with the Probabilistic Hough Transform #---------------------------------------------------------------------------- # lines = cv2.HoughLinesP(cropped_veins,rho=1,theta=numpy.pi/180,threshold=10,minLineLength=10, maxLineGap=6) # Hough Transform # lines = cv2.HoughLinesP(cropped_veins,rho=1,theta=numpy.pi/180,threshold=9,minLineLength=5, maxLineGap=6) # Hough Transform <--- THIS ONE cropped_veins_BGR = cv2.merge([cropped_veins,cropped_veins,cropped_veins]) # lines_polar = [] # for line in lines: # x1,y1,x2,y2 = line[0] # cv2.line(cropped_veins_BGR,(x1,y1),(x2,y2),(0,0,255),1) # if (y2==y1): # theta = 90 # rho = y2 # elif (x2==x1): # theta = 0 # rho = x2 # else: # m = (y2-y1)/(x2-x1) # c = y2-(m*x2) # theta = 90 + (numpy.arctan(m)*180/numpy.pi) # rho = c*numpy.sin(theta) # lines_polar.append([x1,y1,x2,y2,rho,theta]) cropped_veins_norm = cv2.threshold(cropped_veins,1,1,cv2.THRESH_BINARY) bifurcation_kernel = numpy.array([[1, 2, 4],[128, 256, 8],[64, 32, 16]]) print(cropped_veins_norm) print(type(cropped_veins_norm)) cropped_veins_norm = cropped_veins_norm[1].astype(numpy.uint32) print(cropped_veins_norm) bifurcation_table = numpy.array([424,394,298,418,297,402,325,340,337,277,330, 420,329,404,293,338,426,341,331,466,436,301,346, 406,421,361,362,425,422,410,458,299,428,434,363,474,438,429]) # bifurcated_veins = cv2.filter2D(cropped_veins_norm,cv2.CV_16U,bifurcation_kernel) # print(bifurcated_veins) bifurcated_veins = convolve2d(cropped_veins_norm,bifurcation_kernel) print(bifurcated_veins) bifurcation_coords = [] for x in range(bifurcated_veins.shape[1]): for y in range(bifurcated_veins.shape[0]): for z in bifurcation_table: if (bifurcated_veins[y][x] == z): cv2.circle(cropped_veins_BGR,(x,y),2,[0,0,255],1) bifurcation_coords.append([x,y]) #---------------------------------------------------------------------------- # Enrollment/Identification #---------------------------------------------------------------------------- if (command == ' enrol'): try: My_Server.transmit('PASS', None) # Report PASS to IoT Device except socket.error as error: print(error) My_Server.close_connection() continue except TypeError as error: print(error) My_Server.close_connection() except ValueError as error: print(error) My_Server.close_connection() My_Server.close_connection() # name = input('Please enter name of individual: ') # with open(path+name+'.p','wb') as f: # pickle.dump(lines_polar, f) # save line data in binary file # cv2.imwrite(path+name+'_img.png',cropped_veins_BGR) # cv2.imshow('cropped_veins_BGR', cropped_veins_BGR) # cv2.waitKey(0) # continue # go back and wait for new connection elif (command == 'identify'): # for filename in os.listdir(path): # if filename.endswith(".p"): # with open(path+filename,'rb') as f: # enrolled_lines = pickle.load(f) # load line data from binary file # match = 0 # # similarity = 0 # # lines_polar_count = 0 # # enrolled_lines_count = 0 # # multiplier1 = 1 # # multiplier2 = 1 # # for [x1,y1,x2,y2,rho,theta] in lines_polar: # # # # if (lines_polar_count == 30): # # # # break # # for [x11,y11,x21,y21,rho1, theta1] in enrolled_lines: # # # # if (enrolled_lines_count == 50): # # # # break # # # multiplier1 = 1 # # # multiplier2 = 1 # # if ((abs(rho-rho1)<3) and (abs(theta-theta1)<3)): # # # if ( (lines_polar_count<=(len(lines_polar)/2)) and (lines_polar_count>(len(lines_polar)/4)) ): # # # multiplier1 = 0.75 # # # elif ( (lines_polar_count<=(3*(len(lines_polar)/4))) and (lines_polar_count>(len(lines_polar)/2)) ): # # # multiplier1 = 0.5 # # # elif ( (lines_polar_count<=len(lines_polar)) and (lines_polar_count>(3*(len(lines_polar)/4))) ): # # # multiplier1 = 0.25 # # if ((abs(x1-x11)<10) and (abs(x2-x21)<10)): # # match = match + 1 # # break # # # if ( (enrolled_lines_count<=(len(enrolled_lines)/2)) and (enrolled_lines_count>(len(enrolled_lines)/4)) ): # # # multiplier2 = 0.75 # # # elif ( (enrolled_lines_count<=(3*(len(enrolled_lines)/4))) and (enrolled_lines_count>(len(enrolled_lines)/2)) ): # # # multiplier2 = 0.5 # # # elif ( (enrolled_lines_count<=len(enrolled_lines)) and (enrolled_lines_count>(3*(len(enrolled_lines)/4))) ): # # # multiplier2 = 0.25 # # # match = match + (multiplier1*multiplier2) # # # break # # # enrolled_lines_count = enrolled_lines_count + 1 # # # lines_polar_count = lines_polar_count + 1 # for [rho,theta] in lines_polar: # for [rho1,theta1] in enrolled_lines: # if ((abs(rho-rho1)<3) and (abs(theta-theta1)<3)): # match = match + 1 # break # similarity = match/len(lines_polar) # print(filename) # # # print(enrolled_lines) # # # print('\n\n\n') # # # print(lines_polar) # print(match) # print(similarity) try: My_Server.transmit('PASS', None) # Report PASS to IoT Device except socket.error as error: print(error) My_Server.close_connection() continue except TypeError as error: print(error) My_Server.close_connection() except ValueError as error: print(error) My_Server.close_connection() My_Server.close_connection() cv2.imshow('cropped_veins_BGR', cropped_veins_BGR) cv2.waitKey(0) continue # go back and wait for new connection except KeyboardInterrupt: print('CTRL+C input detected. Closing Server Application...') My_Server.shutdown() sys.exit()
Markdown
UTF-8
1,184
2.515625
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: "String constants must end with a double quote | Microsoft Docs" ms.date: "2015-07-20" ms.prod: ".net" ms.reviewer: "" ms.suite: "" ms.technology: - "devlang-visual-basic" ms.topic: "article" f1_keywords: - "vbc30648" - "bc30648" dev_langs: - "VB" helpviewer_keywords: - "BC30648" ms.assetid: eefb77a4-efbc-4000-8871-edce7ef7f2df caps.latest.revision: 14 author: "stevehoag" ms.author: "shoag" caps.handback.revision: 14 --- # String constants must end with a double quote [!INCLUDE[vs2017banner](../../../visual-basic/developing-apps/includes/vs2017banner.md)] Le costanti stringa devono iniziare e terminare con le virgolette. **ID errore:** BC30648 ### Per correggere l'errore - Accertarsi che la stringa letterale termini con un carattere di virgolette \("\). Se si incollano valori da altri editor di testo, assicurarsi che il carattere di virgolette incollato sia valido. I caratteri simili alle virgolette, ad esempio le virgolette inglesi \(""\) o due virgolette semplici \(''\), non sono validi. ## Vedere anche [Strings](../../../visual-basic/programming-guide/language-features/strings/index.md)
Python
UTF-8
4,339
3.390625
3
[]
no_license
#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import scipy.io as sio # 读取mat文件 import matplotlib.pyplot as plt import scipy.optimize as opt import pandas as pd data = sio.loadmat("ex3data1.mat") """ # 图像数据data.get('X')X中表示为400维向量(其中有5,000个)。 400维“特征”是原始20 x 20图像中每个像素的灰度强度。 # 图像数据data.get('y')表示图像中数字的数字类,共5000个。 """ # 接下来对数据进行向量化,向量化代码可以利用线性代数,通常比迭代代码快一些。 def sigmoid(z): # 构建一个常用的逻辑函数(logistic function)为S形函数(Sigmoid function) return 1 / (1 + np.exp(-z)) def neural_cost(theta, X, y, learningRate): # 转换为矩阵乘法,也可以使用操作符@计算ndarray间的矩阵乘法 theta = np.matrix(theta) X = np.matrix(X) y = np.matrix(y) first_item = np.multiply(-y, np.log(sigmoid(X * theta.T))) # np.multiply计算逐元素相乘;(5000,400) * (1,400).T second_item = np.multiply((1 - y), np.log(1 - sigmoid(X * theta.T))) reg = (learningRate / (2 * len(X))) * np.sum(np.power(theta[:, 1:theta.shape[1]], 2)) return np.sum(first_item - second_item) / len(X) + reg # 返回代价函数计算值 def gradient(theta, X, y, learningRate): # 向量化的梯度函数,使用正则化逻辑算法中的梯度下降法 theta = np.matrix(theta) # (1,401) X = np.matrix(X) # (5000,401) Y = np.matrix(y) # (1,5000) error = sigmoid(X * theta.T) - y # (5000,1) # print('error.shape', error.shape) # 验证 grad = ((X.T * error) / len(X)).T + (learningRate / len(X)) * theta # 截距梯度没有进行正则化 grad[0, 0] = np.sum(np.multiply(error, X[:, 0])) / len(X) # X[:, 0]表示只取特征值x0,一共5000个 return np.array(grad).ravel() # 转换为一维数据格式 def one_vs_all(X, y, num_labels, learning_rate): """ :param X:(5000,400) :param y:(5000,1) :param num_labels: 建立k维分类器,在这里k=10,由num_labels决定 :param learning_rate: :return: all_theta """ rows = X.shape[0] params = X.shape[1] all_theta = np.zeros((num_labels, params + 1)) # (num_labels, params + 1) X = np.insert(X, 0, values=np.ones(rows), axis=1) # 接下来将每个y值转换为10维的数组,只有一维的值为1,其它维的值为0 # 数字是从1开始的 for i in range(1, num_labels + 1): theta = np.zeros(params + 1) # (401,) y_i = np.array([1 if label == i else 0 for label in y]) # 一维(5000,),对每个y值进行矢量化 # print('y_i_prep.shape:', y_i.shape) y_i = np.reshape(y_i, (rows, 1)) # 转换为二维数组(5000,1) # print('y_i_reshape.shape', y_i.shape) fmin = opt.minimize(fun=neural_cost, x0=theta, args=(X, y_i, learning_rate), method='TNC', jac=gradient) # print('fmin.x.shape:', fmin.x.shape) # (401,) all_theta[i-1, :] = fmin.x return all_theta # 各数据维度测试 """ print('X.shape:', data.get('X').shape) print('Y.shape:', data.get('y').shape) y_test = np.array([1 if label == 1 else 0 for label in data.get('y')]) print('y_test.shape:', y_test.shape) y_test_reshape = np.reshape(y_test, (5000, 1)) print('y_test_reshape:', y_test_reshape.shape) """ # 各数据维度测试end # print("the classes of y:", np.unique(data.get('y'))) # 查看所有类别 all_theta = one_vs_all(data.get('X'), data.get('y'), 10, 1) # print('all_theta:', all_theta.shape) def predict_all(X, all_theta): # 预测图像标签 rows = X.shape[0] params = X.shape[1] # num_labels = all_theta.shape[0] # 标签类别总数目 X = np.insert(X, 0, values=np.ones(rows), axis=1) X = np.matrix(X) all_theta = np.matrix(all_theta) h = sigmoid(X * all_theta.T) h_armax = np.argmax(h, axis=1) # 取得每行中的最大值的索引 h_armax = h_armax + 1 # 索引是0-9,而数字是1-10 return h_armax y_pred = predict_all(data['X'], all_theta) result_compare = [1 if a == b else 0 for (a, b) in zip(y_pred, data['y'])] accuracy = (sum(map(int, result_compare)) / float(len(result_compare))) print("accuracy = {}%".format(accuracy * 100))
Java
UTF-8
782
2.140625
2
[]
no_license
package com.example.demo.service; import com.example.demo.model.Classroom; import com.example.demo.repository.ClassroomRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ClassroomService { @Autowired private ClassroomRepository repository; public List<Classroom> findAll() { return repository.findAll(); } public Classroom findById(Long id) { return repository.findById(id).get(); } public void create(Classroom model) { repository.save(model); } public void save(Classroom model) { repository.save(model); } public void delete(Long id) { repository.deleteById(id); } }
Python
UTF-8
407
2.84375
3
[]
no_license
import six import socket def get_host_ip(): try: s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.connect(('8.8.8.8', 80)) ip = s.getsockname()[0] finally: s.close() return ip def bytes_to_str(s, encoding='utf-8'): """Returns a str if a bytes object is given.""" if six.PY3 and isinstance(s, bytes): return s.decode(encoding) return s
Markdown
UTF-8
2,317
2.75
3
[]
no_license
# Функциональные требования ФТ-01. Показать различия текущего и требуемого портфелей, чтобы понимать, какие бумаги следует продать, а какие купить. Различие отображать в виде таблицы: ```text |название | количество | купить/продать | | | текущее | требуемое | шт | руб | | VTBE | 100 | 120 | 20 | 2000 | ``` ФТ-02. Оповестить о внеплановой ребалансировке, чтобы не только привести риски в соответствии с индексом, но и заработать на формирующемся портфеле. (Опровергнуто исследованием vanguard) Триггер, когда просадка на указанную пользователем величину. * выставить предел между рынком акций и облигаций * получить отчет о том на сколько превышен выставленный предел * получить рекомендацию сколько купить продать бумаг ФТ-03. Вывести стоимость портфеля, чтобы понять, достигли ли мы цель. * вывести отчет о весе портфеля в рублях (долларах, евро) ФТ-04. Учитывать дробление ценных бумаг, чтобы корректно получать количество ценных бумаг в портфеле. Когда ты покупаешь 1 ценную бумагу, а через некоторое время, она делится на 10, и теперь у тебя 10 ценных бумаг. ФТ-05. Учесть продажу / покупку ценной бумаги, чтобы вести учет в приложении, поскольку доступ до биржи или брокера неоправдан. ФТ-06. Портфели не существуют сами по себе, они формируются под цели.
Java
UTF-8
996
2.484375
2
[]
no_license
package autonomous; import arm.Arm; import drive.DriveBase; import elevator.Elevator; import gripper.Gripper; import interfaces.AutFunction; public class BoxDrop implements AutFunction { private final int duration = 250; private final Gripper gripper; private final Arm arm; private final Elevator elevator; private double height; private long endTime; public BoxDrop(Gripper gripper, Arm arm, Elevator elevator) { this.gripper = gripper; this.arm = arm; this.elevator = elevator; } @Override public void update(long deltaTime) { if (elevator.getPosition() > Elevator.deadzone && arm.isUp()) { arm.moveDown(); } } @Override public void init() { height = elevator.getPosition(); elevator.setTarget(height); elevator.enablePID(); gripper.open(); endTime = System.currentTimeMillis() + duration; } @Override public boolean isDone() { return System.currentTimeMillis() > endTime; } @Override public void cleanUp() { gripper.setSpeed(0); } }
Java
UTF-8
976
3.28125
3
[]
no_license
//package ru.geekbrains; // //public class hw0231 { // // // public static void main(String[] args) { // // if (checkBalans() == true){ // System.out.println("есть такое место"); // } else { // System.out.println("нет такого места"); // } // // // } // // // // // static boolean checkBalans() { // boolean check; // int sum; // int sum1; // int[] arr1 = {1, 8, 6, 9, 9, 1}; // for (int i = 0; i < arr1.length; i++) { // // sum = 0; // sum = arr1[i] + sum; // sum1 = 0; // for (int j = i + 1; j < arr1.length; j++) { // // sum1 = arr1[j] + sum1; // // // } // if (sum == sum1) {check = true; // System.out.println("est"); // } // // // } // if (check == true) // // return true; // else {return false; // } // } //}
C#
UTF-8
808
2.625
3
[ "MIT" ]
permissive
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class SplashFade : MonoBehaviour { public Image splashImage; IEnumerator Start() { splashImage.canvasRenderer.SetAlpha(0.0f); FadeIn(); yield return new WaitForSeconds(2.5f); FadeOut(); yield return new WaitForSeconds(2.5f); // scene we wnat to load after splash screen SceneManager.LoadScene("Main Menu"); } void FadeIn() { // fade the alph for 0 to 100 % for 1.5 seconds splashImage.CrossFadeAlpha(1.0f, 1.5f, false); } void FadeOut() { // it reverses from 100 % fade to 0 splashImage.CrossFadeAlpha(0.0f, 2.5f, false); } }
Java
UTF-8
351
2.359375
2
[]
no_license
package com.example.radhakrishnan.codechallenge.database; public class CityTable { private String cityName; public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } public CityTable(String cityName) { this.cityName = cityName; } }
Python
UTF-8
406
2.765625
3
[]
no_license
# encoding:utf-8 import urllib class Download: def download(url, num_retries=2): print('Downloading', url) try: html = urllib.request.urlopen(url).read() except (URLError, HTTPError, ContentTooShortError) as e: print('Download error:', e.reason) html = None if num_retries > 0: if hasattr(e, 'code') and 500 <= e.code < 600: return download(url, num_retries-1) return html
Shell
UTF-8
997
3.65625
4
[ "BSD-2-Clause" ]
permissive
#!/bin/bash # Volume Down script STEP=5000 MINVOLUME=0 #as a percentage defindex="" volumel= volumer= ready=false # retrieve volume for default output while read line do if [ -z "$defindex" ] then defindex="$(echo "$line" | awk '/* index:/{print $3}')" elif [ -z "$volume" ] then read volumel volumer <<<$(echo "$line" | awk '/volume:/{print $5" "$12}') if [[ "$volumer" =~ "%"$ ]] && [[ "$volumel" =~ "%"$ ]] then volumer=${volumer%\%} volumel=${volumel%\%} ready=true break else volumer= volumel= fi fi done<<<$(pacmd list-sinks | grep -e "index:" -e "volume:") # execute only if volume is greater than MINVOLUME for both channels if $ready && [[ "$volumer" -gt $MINVOLUME ]] && [[ "$volumel" -gt $MINVOLUME ]] then pactl set-sink-volume @DEFAULT_SINK@ -$STEP aplay $HOME/.local/share/Steam/tenfoot/resource/sounds/volume_change.wav &>/dev/null else aplay $HOME/.local/share/Steam/tenfoot/resource/sounds/activation_change_fail.wav &>/dev/null fi
Java
UTF-8
2,156
2.28125
2
[]
no_license
package com.jerry.lottery_draw.domain; import com.baomidou.mybatisplus.annotation.IdType; import com.baomidou.mybatisplus.annotation.TableId; import java.util.Date; public class TEmployee { @TableId(type = IdType.AUTO) private Long id; private String employeeId; private String employeeName; private String department; private String groupId; private Date createdAt; private Date updatedAt; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getEmployeeId() { return employeeId; } public void setEmployeeId(String employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } public String getDepartment() { return department; } public void setDepartment(String department) { this.department = department; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public Date getCreatedAt() { return createdAt; } public void setCreatedAt(Date createdAt) { this.createdAt = createdAt; } public Date getUpdatedAt() { return updatedAt; } public void setUpdatedAt(Date updatedAt) { this.updatedAt = updatedAt; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", employeeId=").append(employeeId); sb.append(", employeeName=").append(employeeName); sb.append(", department=").append(department); sb.append(", groupId=").append(groupId); sb.append(", createdAt=").append(createdAt); sb.append(", updatedAt=").append(updatedAt); sb.append("]"); return sb.toString(); } }
Java
UTF-8
2,644
1.757813
2
[]
no_license
/******************************************************************************* * Copyright (c) 2013 IBM Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package com.ibm.wala.core.tests.callGraph; import java.io.IOException; import org.junit.Test; import com.ibm.wala.core.tests.util.TestConstants; import com.ibm.wala.ipa.callgraph.AnalysisScope; import com.ibm.wala.ipa.callgraph.CallGraph; import com.ibm.wala.ipa.callgraph.Entrypoint; import com.ibm.wala.ipa.callgraph.cha.CHACallGraph; import com.ibm.wala.ipa.callgraph.impl.Util; import com.ibm.wala.ipa.cha.ClassHierarchyException; import com.ibm.wala.ipa.cha.ClassHierarchyFactory; import com.ibm.wala.ipa.cha.IClassHierarchy; import com.ibm.wala.util.CancelException; import com.ibm.wala.util.functions.Function; public class CHACallGraphTest { @Test public void testJava_cup() throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { testCHA(TestConstants.JAVA_CUP, TestConstants.JAVA_CUP_MAIN, CallGraphTestUtil.REGRESSION_EXCLUSIONS); } public static CallGraph testCHA(String scopeFile, final String mainClass, final String exclusionsFile) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { return testCHA(scopeFile, exclusionsFile, new Function<IClassHierarchy, Iterable<Entrypoint>>() { @Override public Iterable<Entrypoint> apply(IClassHierarchy cha) { return Util.makeMainEntrypoints(cha.getScope(), cha, mainClass); } }); } public static CallGraph testCHA(String scopeFile, String exclusionsFile, Function<IClassHierarchy, Iterable<Entrypoint>> makeEntrypoints) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { AnalysisScope scope = CallGraphTestUtil.makeJ2SEAnalysisScope(scopeFile, exclusionsFile); IClassHierarchy cha = ClassHierarchyFactory.make(scope); CHACallGraph CG = new CHACallGraph(cha); CG.init(makeEntrypoints.apply(cha)); return CG; } public static void main(String[] args) throws ClassHierarchyException, IllegalArgumentException, CancelException, IOException { testCHA(args[0], args.length>1? args[1]: null, "Java60RegressionExclusions.txt"); } }
Markdown
UTF-8
2,605
2.765625
3
[]
no_license
# Markdown Basics ## Headlines, paragraphs, basic programming ### Headlines #### Headline 4 ##### Headline 5 ###### Headline 6 ### Paragraphs and Line Breaks Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima repellendus delectus fugiat laborum reprehenderit. Cupiditate aspernatur dicta ipsa corporis illo at, laudantium nisi recusandae quia! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima repellendus delectus fugiat laborum reprehenderit. Cupiditate aspernatur dicta ipsa corporis illo at, laudantium nisi recusandae quia! Place its toothpicked pit in water, watch the grisof its insides grow. Witness its populous bloom, honeycombed with rough Its cobblestones grip the heart in its mitt, a closed fist thickened by complexities or cries. It is a house in which we cannot live, the quiver on the arrow Flaps awkwardly, at its edges, a heron. At its center, a wide bottom perfect with fish. ## Empasis and bolding #### italics This _works_, and this *works* too. #### Bolding This __works__, and this **works** too. This ___works___, and this ***works***too. ### Blockquotes >Learn how to format all the basic parts of a document, including headlines, paragraphs, bolding, italics, block quotes, and horizontal rules. We'll be practicing all of these concepts by building a cheat sheet document that you can use as a reference later. We'll continue building upon this document as we go. > >Remember, you can get copies of the cheat sheet in its current state as well as a complete version from the downloads tab associated with this video. Everything comes together in a single .zip file. ### Horizontal Rule --- *** ___ ### Lists #### Numbered List 1. Item 1 2. Item 2 3. Item 3 #### Nesting 1. Nest 1 1. Inner nest 1 2. Inner nest 2 #### Bulleted List * Item * Item * Item * Inner * inner 1. try 2. Try
Java
UTF-8
124
2.265625
2
[]
no_license
package factorypattern; /** * Created by ZhangHongbin on 2017/1/5. */ public interface Color { public void fill(); }
Java
UTF-8
592
1.992188
2
[]
no_license
package com.dalv1k.bstorage.server.service; import com.dalv1k.bstorage.server.entity.*; import java.util.List; import java.util.Map; public interface IncomeService { List<Income> getAllIncomeGoods(); int getLastIncomePrice (Model model); List<Brand> getAllBrands(); List<Model> getAllModels(); List<Type> getAllTypes(); List<Supplier> getAllSuppliers(); Income getIncomeById(Integer id); Income updateIncome(Integer id, Income income); void saveIncomeGoods(Income income, boolean isUpdate); Map<String, Boolean> deleteIncome(Integer id); }
Markdown
UTF-8
23,110
2.6875
3
[ "MIT" ]
permissive
[{]: <region> (header) # Step 2: Chats page [}]: # [{]: <region> (body) ## First Ionic Component Now that we're finished with the initial setup, we can start building our app. An application created by Ionic's CLI will have a very clear methodology. The app is made out of pages, each page is made out of 3 files: - `.html` - A view template file written in HTML based on Angular2's new [template engine](https://angular.io/docs/ts/latest/guide/template-syntax.html). - `.scss` - A stylesheet file written in a CSS pre-process language called [SASS](https://sass-lang.com). - `.ts` - A script file written in Typescript. By default, the application will be created with 3 pages - `about`, `home` and `contact`. Since our app's flow doesn't contain any of them, we first gonna clean them up by running the following commands: $ rm -rf src/pages/about $ rm -rf src/pages/home $ rm -rf src/pages/contact Second, we will remove their declaration in the app module: [{]: <helper> (diff_step 2.1 src/app/app.module.ts) #### Step 2.1: Remove irrelevant pages ##### Changed src/app/app.module.ts ```diff @@ -1,17 +1,11 @@ ┊ 1┊ 1┊import { NgModule, ErrorHandler } from '@angular/core'; ┊ 2┊ 2┊import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; ┊ 3┊ 3┊import { MyApp } from './app.component'; -┊ 4┊ ┊import { AboutPage } from '../pages/about/about'; -┊ 5┊ ┊import { ContactPage } from '../pages/contact/contact'; -┊ 6┊ ┊import { HomePage } from '../pages/home/home'; ┊ 7┊ 4┊import { TabsPage } from '../pages/tabs/tabs'; ┊ 8┊ 5┊ ┊ 9┊ 6┊@NgModule({ ┊10┊ 7┊ declarations: [ ┊11┊ 8┊ MyApp, -┊12┊ ┊ AboutPage, -┊13┊ ┊ ContactPage, -┊14┊ ┊ HomePage, ┊15┊ 9┊ TabsPage ┊16┊10┊ ], ┊17┊11┊ imports: [ ``` ```diff @@ -20,9 +14,6 @@ ┊20┊14┊ bootstrap: [IonicApp], ┊21┊15┊ entryComponents: [ ┊22┊16┊ MyApp, -┊23┊ ┊ AboutPage, -┊24┊ ┊ ContactPage, -┊25┊ ┊ HomePage, ┊26┊17┊ TabsPage ┊27┊18┊ ], ┊28┊19┊ providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}] ``` [}]: # And finally, will their usage in that tabs component: [{]: <helper> (diff_step 2.2) #### Step 2.2: Removed tabs from the Component ##### Changed src/pages/tabs/tabs.ts ```diff @@ -1,19 +1,9 @@ ┊ 1┊ 1┊import { Component } from '@angular/core'; ┊ 2┊ 2┊ -┊ 3┊ ┊import { HomePage } from '../home/home'; -┊ 4┊ ┊import { AboutPage } from '../about/about'; -┊ 5┊ ┊import { ContactPage } from '../contact/contact'; -┊ 6┊ ┊ ┊ 7┊ 3┊@Component({ ┊ 8┊ 4┊ templateUrl: 'tabs.html' ┊ 9┊ 5┊}) ┊10┊ 6┊export class TabsPage { -┊11┊ ┊ // this tells the tabs component which Pages -┊12┊ ┊ // should be each tab's root Page -┊13┊ ┊ tab1Root: any = HomePage; -┊14┊ ┊ tab2Root: any = AboutPage; -┊15┊ ┊ tab3Root: any = ContactPage; -┊16┊ ┊ ┊17┊ 7┊ constructor() { ┊18┊ 8┊ ┊19┊ 9┊ } ``` [}]: # Now we're gonna define 4 tabs: `chats`, `contacts`, `favorites` and `recents`. In this tutorial we want to focus only on the messaging system, therefore we only gonna implement the chats tab, the rest is just for the layout: [{]: <helper> (diff_step 2.3) #### Step 2.3: Edit tabs template to contain the necessary tabs ##### Changed src/pages/tabs/tabs.html ```diff @@ -1,5 +1,6 @@ ┊1┊1┊<ion-tabs> -┊2┊ ┊ <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab> -┊3┊ ┊ <ion-tab [root]="tab2Root" tabTitle="About" tabIcon="information-circle"></ion-tab> -┊4┊ ┊ <ion-tab [root]="tab3Root" tabTitle="Contact" tabIcon="contacts"></ion-tab> +┊ ┊2┊ <ion-tab tabIcon="chatboxes"></ion-tab> +┊ ┊3┊ <ion-tab tabIcon="contacts"></ion-tab> +┊ ┊4┊ <ion-tab tabIcon="star"></ion-tab> +┊ ┊5┊ <ion-tab tabIcon="clock"></ion-tab> ┊5┊6┊</ion-tabs> ``` [}]: # If you will take a closer look at the view template we've just defined, you can see that one of the tab's attributes is wrapped with \[square brackets\]. This is part of Angular2's new template syntax and what it means is that the property called `root` of the HTML element is bound to the `chatsTabRoot` property of the component. Our next step would be implementing the `chats` tab; First let's start by adding `moment` as a dependency - a utility library in JavaScript which will help us parse, validate, manipulate, and display dates: $ npm install --save moment We will start by implementing a view stub, just so we can get the idea of Ionic's components: [{]: <helper> (diff_step 2.5) #### Step 2.5: Added ChatsPage view ##### Added src/pages/chats/chats.html ```diff @@ -0,0 +1,11 @@ +┊ ┊ 1┊<ion-header> +┊ ┊ 2┊ <ion-navbar> +┊ ┊ 3┊ <ion-title> +┊ ┊ 4┊ Chats +┊ ┊ 5┊ </ion-title> +┊ ┊ 6┊ </ion-navbar> +┊ ┊ 7┊</ion-header> +┊ ┊ 8┊ +┊ ┊ 9┊<ion-content padding> +┊ ┊10┊ Hello! +┊ ┊11┊</ion-content> ``` [}]: # Once creating an Ionic page it's recommended to use the following layout: - &lt;ion-header&gt; - The header of the page. Will usually contain content that should be bounded to the top like navbar. - &lt;ion-content&gt; - The content of the page. Will usually contain it's actual content like text. - &lt;ion-footer&gt; - The footer of the page. Will usually contain content that should be bounded to the bottom like toolbars. To display a view, we will need to have a component as well, whose basic structure should look like so: [{]: <helper> (diff_step 2.6) #### Step 2.6: Added ChatsPage Component ##### Added src/pages/chats/chats.ts ```diff @@ -0,0 +1,64 @@ +┊ ┊ 1┊import * as moment from 'moment'; +┊ ┊ 2┊import { Component } from '@angular/core'; +┊ ┊ 3┊import { Observable } from "rxjs"; +┊ ┊ 4┊ +┊ ┊ 5┊@Component({ +┊ ┊ 6┊ templateUrl: 'chats.html' +┊ ┊ 7┊}) +┊ ┊ 8┊export class ChatsPage { +┊ ┊ 9┊ chats: Observable<any[]>; +┊ ┊10┊ +┊ ┊11┊ constructor() { +┊ ┊12┊ this.chats = this.findChats(); +┊ ┊13┊ } +┊ ┊14┊ +┊ ┊15┊ private findChats(): Observable<any[]> { +┊ ┊16┊ return Observable.of([ +┊ ┊17┊ { +┊ ┊18┊ _id: '0', +┊ ┊19┊ title: 'Ethan Gonzalez', +┊ ┊20┊ picture: 'https://randomuser.me/api/portraits/thumb/men/1.jpg', +┊ ┊21┊ lastMessage: { +┊ ┊22┊ content: 'You on your way?', +┊ ┊23┊ createdAt: moment().subtract(1, 'hours').toDate() +┊ ┊24┊ } +┊ ┊25┊ }, +┊ ┊26┊ { +┊ ┊27┊ _id: '1', +┊ ┊28┊ title: 'Bryan Wallace', +┊ ┊29┊ picture: 'https://randomuser.me/api/portraits/thumb/lego/1.jpg', +┊ ┊30┊ lastMessage: { +┊ ┊31┊ content: 'Hey, it\'s me', +┊ ┊32┊ createdAt: moment().subtract(2, 'hours').toDate() +┊ ┊33┊ } +┊ ┊34┊ }, +┊ ┊35┊ { +┊ ┊36┊ _id: '2', +┊ ┊37┊ title: 'Avery Stewart', +┊ ┊38┊ picture: 'https://randomuser.me/api/portraits/thumb/women/1.jpg', +┊ ┊39┊ lastMessage: { +┊ ┊40┊ content: 'I should buy a boat', +┊ ┊41┊ createdAt: moment().subtract(1, 'days').toDate() +┊ ┊42┊ } +┊ ┊43┊ }, +┊ ┊44┊ { +┊ ┊45┊ _id: '3', +┊ ┊46┊ title: 'Katie Peterson', +┊ ┊47┊ picture: 'https://randomuser.me/api/portraits/thumb/women/2.jpg', +┊ ┊48┊ lastMessage: { +┊ ┊49┊ content: 'Look at my mukluks!', +┊ ┊50┊ createdAt: moment().subtract(4, 'days').toDate() +┊ ┊51┊ } +┊ ┊52┊ }, +┊ ┊53┊ { +┊ ┊54┊ _id: '4', +┊ ┊55┊ title: 'Ray Edwards', +┊ ┊56┊ picture: 'https://randomuser.me/api/portraits/thumb/men/2.jpg', +┊ ┊57┊ lastMessage: { +┊ ┊58┊ content: 'This is wicked good ice cream.', +┊ ┊59┊ createdAt: moment().subtract(2, 'weeks').toDate() +┊ ┊60┊ } +┊ ┊61┊ } +┊ ┊62┊ ]); +┊ ┊63┊ } +┊ ┊64┊} ``` [}]: # The logic is simple. Once the component is created we gonna a define dummy chats array just so we can test our view. As you can see we're using the `moment` package to fabricate date values. The `Observable.of` syntax is used to create an Observable with a single value. Now let's load the newly created component in the module definition so our Angular 2 app will recognize it: [{]: <helper> (diff_step 2.7) #### Step 2.7: Added ChatsPage to the module definition ##### Changed src/app/app.module.ts ```diff @@ -2,10 +2,12 @@ ┊ 2┊ 2┊import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular'; ┊ 3┊ 3┊import { MyApp } from './app.component'; ┊ 4┊ 4┊import { TabsPage } from '../pages/tabs/tabs'; +┊ ┊ 5┊import { ChatsPage } from "../pages/chats/chats"; ┊ 5┊ 6┊ ┊ 6┊ 7┊@NgModule({ ┊ 7┊ 8┊ declarations: [ ┊ 8┊ 9┊ MyApp, +┊ ┊10┊ ChatsPage, ┊ 9┊11┊ TabsPage ┊10┊12┊ ], ┊11┊13┊ imports: [ ``` ```diff @@ -14,6 +16,7 @@ ┊14┊16┊ bootstrap: [IonicApp], ┊15┊17┊ entryComponents: [ ┊16┊18┊ MyApp, +┊ ┊19┊ ChatsPage, ┊17┊20┊ TabsPage ┊18┊21┊ ], ┊19┊22┊ providers: [{provide: ErrorHandler, useClass: IonicErrorHandler}] ``` [}]: # Let's define it on the tabs component: [{]: <helper> (diff_step 2.8) #### Step 2.8: Added chats tab root ##### Changed src/pages/tabs/tabs.ts ```diff @@ -1,9 +1,12 @@ ┊ 1┊ 1┊import { Component } from '@angular/core'; +┊ ┊ 2┊import { ChatsPage } from "../chats/chats"; ┊ 2┊ 3┊ ┊ 3┊ 4┊@Component({ ┊ 4┊ 5┊ templateUrl: 'tabs.html' ┊ 5┊ 6┊}) ┊ 6┊ 7┊export class TabsPage { +┊ ┊ 8┊ chatsTab = ChatsPage; +┊ ┊ 9┊ ┊ 7┊10┊ constructor() { ┊ 8┊11┊ ┊ 9┊12┊ } ``` [}]: # And define it as the root tab, which means that once we enter the tabs view, this is the initial tab which is gonna show up: [{]: <helper> (diff_step 2.9) #### Step 2.9: Added root to the tab element ##### Changed src/pages/tabs/tabs.html ```diff @@ -1,5 +1,5 @@ ┊1┊1┊<ion-tabs> -┊2┊ ┊ <ion-tab tabIcon="chatboxes"></ion-tab> +┊ ┊2┊ <ion-tab [root]="chatsTab" tabIcon="chatboxes"></ion-tab> ┊3┊3┊ <ion-tab tabIcon="contacts"></ion-tab> ┊4┊4┊ <ion-tab tabIcon="star"></ion-tab> ┊5┊5┊ <ion-tab tabIcon="clock"></ion-tab> ``` [}]: # ## TypeScript Interfaces Now, because we use TypeScript, we can define our own data-types and use then in our app, which will give you a better auto-complete and developing experience in most IDEs. In our application, we have 2 models at the moment: a `chat` model and a `message` model. We will define their interfaces in a file located under the path `/modes/whatsapp-models.d.ts`: [{]: <helper> (diff_step 2.10) #### Step 2.10: Added chat and message models ##### Added models/whatsapp-models.d.ts ```diff @@ -0,0 +1,15 @@ +┊ ┊ 1┊declare module 'api/models/whatsapp-models' { +┊ ┊ 2┊ interface Chat { +┊ ┊ 3┊ _id?: string; +┊ ┊ 4┊ title?: string; +┊ ┊ 5┊ picture?: string; +┊ ┊ 6┊ lastMessage?: Message; +┊ ┊ 7┊ } +┊ ┊ 8┊ +┊ ┊ 9┊ interface Message { +┊ ┊10┊ _id?: string; +┊ ┊11┊ chatId?: string; +┊ ┊12┊ content?: string; +┊ ┊13┊ createdAt?: Date; +┊ ┊14┊ } +┊ ┊15┊} ``` [}]: # The `d.ts` extension stands for `declaration - TypeScipt`, which basically tells the compiler that this is a declaration file, just like C++'s header files. In addition, we will need to add a reference to our models declaration file, so the compiler will recognize it: [{]: <helper> (diff_step 2.11) #### Step 2.11: Added models typings into the config ##### Changed src/declarations.d.ts ```diff @@ -11,4 +11,6 @@ ┊11┊11┊ For more info on type definition files, check out the Typescript docs here: ┊12┊12┊ https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html ┊13┊13┊*/ -┊14┊ ┊declare module '*';🚫↵ +┊ ┊14┊/// <reference path="../models/whatsapp-models.d.ts" /> +┊ ┊15┊declare module '*'; +┊ ┊16┊ ``` [}]: # Now we can finally use the chat model in the `ChatsPage`: [{]: <helper> (diff_step 2.12) #### Step 2.12: Use Chat model in ChatsPage ##### Changed src/pages/chats/chats.ts ```diff @@ -1,18 +1,19 @@ ┊ 1┊ 1┊import * as moment from 'moment'; ┊ 2┊ 2┊import { Component } from '@angular/core'; ┊ 3┊ 3┊import { Observable } from "rxjs"; +┊ ┊ 4┊import { Chat } from "api/models/whatsapp-models"; ┊ 4┊ 5┊ ┊ 5┊ 6┊@Component({ ┊ 6┊ 7┊ templateUrl: 'chats.html' ┊ 7┊ 8┊}) ┊ 8┊ 9┊export class ChatsPage { -┊ 9┊ ┊ chats: Observable<any[]>; +┊ ┊10┊ chats: Observable<Chat[]>; ┊10┊11┊ ┊11┊12┊ constructor() { ┊12┊13┊ this.chats = this.findChats(); ┊13┊14┊ } ┊14┊15┊ -┊15┊ ┊ private findChats(): Observable<any[]> { +┊ ┊16┊ private findChats(): Observable<Chat[]> { ┊16┊17┊ return Observable.of([ ┊17┊18┊ { ┊18┊19┊ _id: '0', ``` [}]: # ## Ionic Themes Ionic 2 provides us with a comfortable theming system which is based on SASS variables. The theme definition file is located in `src/theme/variable.scss`. Since we want our app to have a "Whatsappish" look, we will define a new SASS variable called `whatsapp` in the variables file: [{]: <helper> (diff_step 2.13) #### Step 2.13: Added theme color definition ##### Changed src/theme/variables.scss ```diff @@ -28,7 +28,8 @@ ┊28┊28┊ secondary: #32db64, ┊29┊29┊ danger: #f53d3d, ┊30┊30┊ light: #f4f4f4, -┊31┊ ┊ dark: #222 +┊ ┊31┊ dark: #222, +┊ ┊32┊ whatsapp: #075E54 ┊32┊33┊); ``` [}]: # The `whatsapp` color can be used by adding an attribute called `color` with a value `whatsapp` to any Ionic component: [{]: <helper> (diff_step 2.14) #### Step 2.14: Apply whatsapp theme on tabs view ##### Changed src/pages/tabs/tabs.html ```diff @@ -1,4 +1,4 @@ -┊1┊ ┊<ion-tabs> +┊ ┊1┊<ion-tabs color="whatsapp"> ┊2┊2┊ <ion-tab [root]="chatsTab" tabIcon="chatboxes"></ion-tab> ┊3┊3┊ <ion-tab tabIcon="contacts"></ion-tab> ┊4┊4┊ <ion-tab tabIcon="star"></ion-tab> ``` [}]: # Now let's implement the chats view properly in the `ChatsView` by showing all available chat items: [{]: <helper> (diff_step 2.15) #### Step 2.15: Added chats page view with a list of chats ##### Changed src/pages/chats/chats.html ```diff @@ -1,11 +1,32 @@ ┊ 1┊ 1┊<ion-header> -┊ 2┊ ┊ <ion-navbar> +┊ ┊ 2┊ <ion-navbar color="whatsapp"> ┊ 3┊ 3┊ <ion-title> ┊ 4┊ 4┊ Chats ┊ 5┊ 5┊ </ion-title> +┊ ┊ 6┊ <ion-buttons end> +┊ ┊ 7┊ <button ion-button icon-only class="add-chat-button"> +┊ ┊ 8┊ <ion-icon name="person-add"></ion-icon> +┊ ┊ 9┊ </button> +┊ ┊10┊ <button ion-button icon-only class="options-button"> +┊ ┊11┊ <ion-icon name="more"></ion-icon> +┊ ┊12┊ </button> +┊ ┊13┊ </ion-buttons> ┊ 6┊14┊ </ion-navbar> ┊ 7┊15┊</ion-header> ┊ 8┊16┊ -┊ 9┊ ┊<ion-content padding> -┊10┊ ┊ Hello! +┊ ┊17┊<ion-content class="chats-page-content"> +┊ ┊18┊ <ion-list class="chats"> +┊ ┊19┊ <button ion-item *ngFor="let chat of chats | async" class="chat"> +┊ ┊20┊ <img class="chat-picture" [src]="chat.picture"> +┊ ┊21┊ +┊ ┊22┊ <div class="chat-info"> +┊ ┊23┊ <h2 class="chat-title">{{chat.title}}</h2> +┊ ┊24┊ +┊ ┊25┊ <span *ngIf="chat.lastMessage" class="last-message"> +┊ ┊26┊ <p class="last-message-content">{{chat.lastMessage.content}}</p> +┊ ┊27┊ <span class="last-message-timestamp">{{chat.lastMessage.createdAt}}</span> +┊ ┊28┊ </span> +┊ ┊29┊ </div> +┊ ┊30┊ </button> +┊ ┊31┊ </ion-list> ┊11┊32┊</ion-content> ``` [}]: # We use `ion-list` which Ionic translate into a list, and use `ion-item` for each one of the items in the list. A chat item includes an image, the receiver's name, and its recent message. > The `async` pipe is used to iterate through data which should be fetched asynchronously, in this case, observables Now, in order to finish our theming and styling, let's create a stylesheet file for our component: [{]: <helper> (diff_step 2.16) #### Step 2.16: Added some styles ##### Added src/pages/chats/chats.scss ```diff @@ -0,0 +1,20 @@ +┊ ┊ 1┊.chats-page-content { +┊ ┊ 2┊ .chat-picture { +┊ ┊ 3┊ border-radius: 50%; +┊ ┊ 4┊ width: 50px; +┊ ┊ 5┊ float: left; +┊ ┊ 6┊ } +┊ ┊ 7┊ +┊ ┊ 8┊ .chat-info { +┊ ┊ 9┊ float: left; +┊ ┊10┊ margin: 10px 0 0 20px; +┊ ┊11┊ +┊ ┊12┊ .last-message-timestamp { +┊ ┊13┊ position: absolute; +┊ ┊14┊ top: 10px; +┊ ┊15┊ right: 10px; +┊ ┊16┊ font-size: 14px; +┊ ┊17┊ color: #9A9898; +┊ ┊18┊ } +┊ ┊19┊ } +┊ ┊20┊} ``` [}]: # Ionic will load newly defined stylesheet files automatically, so you shouldn't be worried for importations. ## External Angular 2 Modules Since Ionic 2 uses Angular 2 as the layer view, we can load Angular 2 modules just like any other plain Angular 2 application. One module that may come in our interest would be the `angular2-moment` module, which will provide us with the ability to use `moment`'s utility functions in the view using pipes. It requires us to install `angular2-moment` module using the following command: $ npm install --save angular2-moment Now we will need to declare this module in the app's main component: [{]: <helper> (diff_step 2.18) #### Step 2.18: Import MomentModule into the module definition ##### Changed src/app/app.module.ts ```diff @@ -3,6 +3,7 @@ ┊3┊3┊import { MyApp } from './app.component'; ┊4┊4┊import { TabsPage } from '../pages/tabs/tabs'; ┊5┊5┊import { ChatsPage } from "../pages/chats/chats"; +┊ ┊6┊import { MomentModule } from "angular2-moment"; ┊6┊7┊ ┊7┊8┊@NgModule({ ┊8┊9┊ declarations: [ ``` ```diff @@ -11,7 +12,8 @@ ┊11┊12┊ TabsPage ┊12┊13┊ ], ┊13┊14┊ imports: [ -┊14┊ ┊ IonicModule.forRoot(MyApp) +┊ ┊15┊ IonicModule.forRoot(MyApp), +┊ ┊16┊ MomentModule ┊15┊17┊ ], ┊16┊18┊ bootstrap: [IonicApp], ┊17┊19┊ entryComponents: [ ``` [}]: # Which will make `moment` available as a pack of pipes, as mentioned earlier: [{]: <helper> (diff_step 2.19) #### Step 2.19: Apply calendar pipe to chats view template ##### Changed src/pages/chats/chats.html ```diff @@ -24,7 +24,7 @@ ┊24┊24┊ ┊25┊25┊ <span *ngIf="chat.lastMessage" class="last-message"> ┊26┊26┊ <p class="last-message-content">{{chat.lastMessage.content}}</p> -┊27┊ ┊ <span class="last-message-timestamp">{{chat.lastMessage.createdAt}}</span> +┊ ┊27┊ <span class="last-message-timestamp">{{chat.lastMessage.createdAt | amCalendar }}</span> ┊28┊28┊ </span> ┊29┊29┊ </div> ┊30┊30┊ </button> ``` [}]: # ## Ionic Touch Events Ionic provides us with components which can handle mobile events like: slide, tap and pinch. In the `chats` view we're going to take advantage of the slide event, by implementing sliding buttons using the `ion-item-sliding` component: [{]: <helper> (diff_step 2.20) #### Step 2.20: Add chat removal button to view template ##### Changed src/pages/chats/chats.html ```diff @@ -16,17 +16,22 @@ ┊16┊16┊ ┊17┊17┊<ion-content class="chats-page-content"> ┊18┊18┊ <ion-list class="chats"> -┊19┊ ┊ <button ion-item *ngFor="let chat of chats | async" class="chat"> -┊20┊ ┊ <img class="chat-picture" [src]="chat.picture"> +┊ ┊19┊ <ion-item-sliding *ngFor="let chat of chats | async"> +┊ ┊20┊ <button ion-item class="chat"> +┊ ┊21┊ <img class="chat-picture" [src]="chat.picture"> ┊21┊22┊ -┊22┊ ┊ <div class="chat-info"> -┊23┊ ┊ <h2 class="chat-title">{{chat.title}}</h2> +┊ ┊23┊ <div class="chat-info"> +┊ ┊24┊ <h2 class="chat-title">{{chat.title}}</h2> ┊24┊25┊ -┊25┊ ┊ <span *ngIf="chat.lastMessage" class="last-message"> -┊26┊ ┊ <p class="last-message-content">{{chat.lastMessage.content}}</p> -┊27┊ ┊ <span class="last-message-timestamp">{{chat.lastMessage.createdAt | amCalendar }}</span> -┊28┊ ┊ </span> -┊29┊ ┊ </div> -┊30┊ ┊ </button> +┊ ┊26┊ <span *ngIf="chat.lastMessage" class="last-message"> +┊ ┊27┊ <p class="last-message-content">{{chat.lastMessage.content}}</p> +┊ ┊28┊ <span class="last-message-timestamp">{{chat.lastMessage.createdAt | amCalendar }}</span> +┊ ┊29┊ </span> +┊ ┊30┊ </div> +┊ ┊31┊ </button> +┊ ┊32┊ <ion-item-options class="chat-options"> +┊ ┊33┊ <button ion-button color="danger" class="option option-remove" (click)="removeChat(chat)">Remove</button> +┊ ┊34┊ </ion-item-options> +┊ ┊35┊ </ion-item-sliding> ┊31┊36┊ </ion-list> ┊32┊37┊</ion-content> ``` [}]: # This implementation will reveal a `remove` button once we slide a chat item to the left. The only thing left to do now would be implementing the chat removal event handler in the chats component: [{]: <helper> (diff_step 2.21) #### Step 2.21: Add chat removal stub method to chats component ##### Changed src/pages/chats/chats.ts ```diff @@ -62,4 +62,12 @@ ┊62┊62┊ } ┊63┊63┊ ]); ┊64┊64┊ } +┊ ┊65┊ +┊ ┊66┊ removeChat(chat: Chat): void { +┊ ┊67┊ this.chats = this.chats.map<Chat[]>(chatsArray => { +┊ ┊68┊ const chatIndex = chatsArray.indexOf(chat); +┊ ┊69┊ chatsArray.splice(chatIndex, 1); +┊ ┊70┊ return chatsArray; +┊ ┊71┊ }); +┊ ┊72┊ } ┊65┊73┊} ``` [}]: # [}]: # [{]: <region> (footer) [{]: <helper> (nav_step) | [< Previous Step](step1.md) | [Next Step >](step3.md) | |:--------------------------------|--------------------------------:| [}]: # [}]: #
Shell
UTF-8
111
2.921875
3
[]
no_license
#!/bin/sh if [ -n "$1" ] then docker rmi -f trickbooter/$1 echo "" docker build -t trickbooter/$1 $1/ fi
C
UTF-8
1,727
3.921875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct { // 成績を格納する構造体を定義 char name[8]; unsigned char kokugo; // 0 ~ 100を表現できればいいのでunsigned char型でもいいはず unsigned char sugaku; unsigned char English; } Grades; int main() { char title[][13] = {"出席番号", "名前", "国語", "数学", "英語"}; // タイトル char names[][10] = {"Aさん", "Bさん", "Cさん", "Dさん"}; // 名前や成績 unsigned char kokugo_Arr[] = {41, 59, 78, 90}; unsigned char sugaku_Arr[] = {77, 54, 62, 83}; unsigned char English_Arr[] = {79, 65, 81, 73}; Grades* Grade_Arr = (Grades*)malloc(sizeof(Grades) * 4); // ヒープ領域にメモリ確保 if (Grade_Arr == NULL) { puts("動的メモリを確保できませんでした"); exit(1); } for (int i = 0; i < 4; i++) { // 構造体配列に必要なデータを入れる strcpy(Grade_Arr[i].name, names[i]); Grade_Arr[i].kokugo = kokugo_Arr[i]; Grade_Arr[i].sugaku = sugaku_Arr[i]; Grade_Arr[i].English = English_Arr[i]; } FILE* fp = fopen("grade_table.csv", "w"); // 書き込むファイルを作成 if (fp == NULL) { puts("ファイルを作成できませんでした"); exit(1); } fprintf(fp, "%s,%s,%s,%s,%s\n", title[0], title[1], title[2], title[3], title[4]); // for (int i = 0; i < 4; i++) { // ファイルへ書き込み fprintf(fp, "%04d,%s,%3d,%3d,%3d\n", (i + 1), Grade_Arr[i].name, Grade_Arr[i].kokugo, Grade_Arr[i].sugaku, Grade_Arr[i].English); } fclose(fp); // 閉じる free(Grade_Arr); return 0; }
C#
UTF-8
999
2.71875
3
[]
no_license
using System; using EventDomain; namespace EventReceiver { class Program { static void Main(string[] args) { ScheduleManager scheduleManager = new ScheduleManager(); NotificationSender notificationSender = new NotificationSender(); ShowNotification eventReceiver = new ShowNotification(); ShowNotificationShort showNotificationShort = new ShowNotificationShort(); scheduleManager.AddedSchedule += eventReceiver.OnAddedSchedule; // EventReceiver nasłuchuje na event scheduleManager.AddedSchedule += notificationSender.OnAddedSchedule; // NotificationSender nasłuchuje na event scheduleManager.AddedScheduleShort += showNotificationShort.OnAddedScheduleShort; // Nasłuchiwanie na drugi event scheduleManager.AddSchedule(new Schedule() { ScheduleDate = DateTime.Now, ScheduleName = "Kupić masło" }); Console.WriteLine("Zakończono działanie programu....."); Console.ReadKey(); } } }
Java
UTF-8
148
1.617188
2
[]
no_license
package com.sa.task.ui.base; /** * Created by temp on 19/11/17. */ public interface BasePresenter { void onStart(); void onStop(); }
Markdown
UTF-8
2,335
2.953125
3
[ "BSD-3-Clause", "BSD-2-Clause", "Apache-2.0" ]
permissive
--- title: 'User Feedback' sidebar_order: 3 --- Sentry provides the ability to collect additional feedback from the user upon hitting an error. This is primarily useful in situations where you might generally render a plain error page (the classic `500.html`). To collect the feedback, an embeddable JavaScript widget is available, which can then be shown on demand to your users. The following pieces of information are requested and collected: - The user’s name - The user’s email address - A description of what happened When feedback is collected, Sentry will pair it up with the original event giving you additional insights into issues. ## Collecting Feedback The integration process consists of running our JavaScript SDK (2.1 or newer), authenticating with your public DSN, and passing in the client-side generated Event ID: {% include components/platform_content.html content_dir='user-feedback-example' %} If you don't want to use Sentry's native widget, you can also send feedback using our [_User Feedback API_]({%- link _documentation/api/projects/post-project-user-reports.md -%}). ## Customizing the Widget Several parameters are available to customize the widget, specifically for localization. All options can be passed through the `showReportDialog` call. An override for Sentry’s automatic language detection (e.g. `lang=de`) | Param | Default | | --- | --- | | `eventId` | Manually set the id of the event. | | `dsn` | Manually set dsn to report to. | | `user` | Manually set user data _[an object with keys listed above]_. | | `user.email` | User's email address. | | `user.name` | User's name. | | `lang` | _[automatic]_ – **override for Sentry’s language code** | | `title` | It looks like we’re having issues. | | `subtitle` | Our team has been notified. | | `subtitle2` | If you’d like to help, tell us what happened below. – **not visible on small screen resolutions** | | `labelName` | Name | | `labelEmail` | Email | | `labelComments` | What happened? | | `labelClose` | Close | | `labelSubmit` | Submit | | `errorGeneric` | An unknown error occurred while submitting your report. Please try again. | | `errorFormEntry` | Some fields were invalid. Please correct the errors and try again. | | `successMessage` | Your feedback has been sent. Thank you! | | `onLoad` | n/a |
Java
UTF-8
314
1.78125
2
[]
no_license
package com.cgwx.dao; import com.cgwx.data.entity.PdmIndustryElectricPowerSegmentationInfo; import java.util.List; public interface PdmIndustryElectricPowerSegmentationInfoMapper { int insert(PdmIndustryElectricPowerSegmentationInfo record); List<PdmIndustryElectricPowerSegmentationInfo> selectAll(); }
C#
UTF-8
3,074
2.546875
3
[]
no_license
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; #if UNITY_EDITOR using UnityEditor; #endif /// <summary> /// マップ生成 /// </summary> public class MapMaker : MonoBehaviour { [SerializeField, Header("読込むテキストファイル")] TextAsset textAsset; [SerializeField, Header("マップチップ設定")] List<MapChip> mapChipList; string[][] mapChip; //マップチップ /// <summary> /// マップ生成処理 /// </summary> public void Make() { ReadText(); if (mapChip == null) return; DeleteChildren(); InstanceChip(); } /// <summary> /// テキスト読込 /// </summary> void ReadText() { if (textAsset == null) { return; } StringReader reader = new StringReader(textAsset.text); List<string[]> txtList = new List<string[]>(); while (reader.Peek() != -1) { string line = reader.ReadLine(); txtList.Add(line.Split(',')); } mapChip = new string[txtList.Count][]; for (int i = 0; i < txtList.Count; i++) { mapChip[i] = txtList[i]; } } /// <summary> /// 子オブジェクト全削除 /// PrefabだとError /// </summary> public void DeleteChildren() { while (transform.childCount > 0) { DestroyImmediate(transform.GetChild(0).gameObject); } } /// <summary> /// マップチップ追加 /// </summary> void InstanceChip() { if (mapChip == null || mapChip.Length <= 0) return; float yLength = mapChip.Length; float xLength = mapChip[0].Length; for (int i = 0; i < mapChip.Length; i++) { for (int j = 0; j < mapChip[i].Length; j++) { int number; bool parsed = int.TryParse(mapChip[i][j], out number); if (!parsed) continue; var chip = mapChipList.Find(c => c.number == number); if (chip == null) continue; var obj = new GameObject(); obj.name = chip.name; obj.transform.parent = transform; var sr = obj.AddComponent<SpriteRenderer>(); sr.sprite = chip.sprite; Vector2 size = sr.size; obj.transform.position = new Vector2( /*-xLength / 2*/ +j, /*yLength / 2*/ -i) * size; if (!chip.isCollision) continue; #if UNITY_EDITOR var col = Undo.AddComponent<BoxCollider2D>(obj); #else var col = obj.AddComponent<BoxCollider2D>(); #endif col.size = size; } } } /// <summary> /// リストの始めから順に番号を指定していく /// </summary> public void SetNumber() { for (int i = 0; i < mapChipList.Count; i++) { mapChipList[i].number = i; } } }
Java
UTF-8
6,335
1.929688
2
[]
no_license
package edu.hendrix.huynhem.seniorthesis.UI; import android.app.Fragment; import android.app.FragmentTransaction; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import java.io.File; import edu.hendrix.huynhem.seniorthesis.R; import edu.hendrix.huynhem.seniorthesis.Threading.TrainerManager; public class ContainerActivity extends AppCompatActivity implements CapturePhotoMenu.capturePhotoMenuInteractions, TrainFragment.LabelFragmentNavigation, TrainOrClassifyFragment.TrainOrClassifyInterface, TestFragment.TestFragemntNavigation, TestWithTrainedDataFragment.TestWithTrainedDataInter, TrainerManager.NotificationInterface { public final static int NOTIFICATION_ID = 1; private Notification.Builder notification; private static final String LOG_TAG = "CONTAINER_ACTIVITY"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); CapturePhotoMenu frag = CapturePhotoMenu.newInstance(); getFragmentManager().beginTransaction() .add(R.id.FragmentView,frag).commit(); setContentView(R.layout.activity_container); notification = buildNotification(); TrainerManager.setmListener(this); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); } @Override public void pictureCaptured(String filename) { galleryAddPic(filename); TrainFragment lf = new TrainFragment(); Bundle args = new Bundle(); args.putStringArray(TrainFragment.PICTUREARRAY,new String[]{filename}); replaceFragment(lf, args); } @Override public void goToTestWithTrained() { TestWithTrainedDataFragment tf = new TestWithTrainedDataFragment(); replaceFragment(tf, new Bundle()); } @Override public void goToTrainMany(String[] files) { TrainFragment lf = new TrainFragment(); Bundle args = new Bundle(); args.putStringArray(TrainFragment.PICTUREARRAY,files); replaceFragment(lf, args); } @Override public void goToCurrentJobs() { // TODO: Add a job queue } @Override public void goToMenu() { CapturePhotoMenu frag = new CapturePhotoMenu(); Bundle args = new Bundle(); replaceFragment(frag, args); } @Override public void goToTest(String filename) { TestFragment tf = new TestFragment(); Bundle args = new Bundle(); args.putString(TrainFragment.PICTUREARRAY,filename); replaceFragment(tf, args); } @Override public void toTrainingFragment(String filename) { TrainFragment tf = new TrainFragment(); Bundle args = new Bundle(); args.putStringArray(TrainFragment.PICTUREARRAY,new String[]{filename}); replaceFragment(tf, args); } @Override public void toTestingFragment(String filename) { goToTest(filename); } @Override public void pickNewPhoto() { goToMenu(); } private void galleryAddPic(String photoPath) { Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE); File f = new File(photoPath); Uri contentUri = Uri.fromFile(f); mediaScanIntent.setData(contentUri); this.sendBroadcast(mediaScanIntent); } private void replaceFragment(Fragment f, Bundle args){ f.setArguments(args); FragmentTransaction transaction = getFragmentManager().beginTransaction(); transaction.replace(R.id.FragmentView, f); transaction.addToBackStack(null); transaction.commit(); } @Override public void onFragmentInteraction(Uri uri) { } private Notification.Builder buildNotification(){ Bitmap bm = Bitmap.createScaledBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher), getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_width), getResources().getDimensionPixelSize(android.R.dimen.notification_large_icon_height), true); Intent intent = new Intent(this, ContainerActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, NOTIFICATION_ID, intent, PendingIntent.FLAG_UPDATE_CURRENT); Notification.Builder builder = new Notification.Builder(getApplicationContext()); builder.setContentTitle("Training Jobs running"); builder.setContentText("Waiting for Jobs"); builder.setSubText("0 Jobs"); builder.setContentIntent(pendingIntent); builder.setTicker("Fancy Notification"); builder.setSmallIcon(R.drawable.ic_launcher_foreground); builder.setLargeIcon(bm); builder.setAutoCancel(false); builder.setPriority(Notification.PRIORITY_DEFAULT); // builder.setOngoing(false); builder.setProgress(0,0,true); Notification notification = builder.build(); NotificationManager notificationManger = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); assert notificationManger != null; notificationManger.notify(NOTIFICATION_ID, notification); return builder; } @Override public void setProgressVals(int done, int total) { NotificationManager notificationManger = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); if(done == total){ notification.setSubText("No jobs running"); notification.setContentText(""); notification.setProgress(0,0,false); } else { notification.setSubText(total - done + " jobs remaining"); notification.setContentText(String.format("%d jobs done out of %d total", done, total)); notification.setProgress(total,done,false); } notificationManger.notify(NOTIFICATION_ID,notification.build()); } }
Python
UTF-8
80
3
3
[]
no_license
def celsius_para_fahrenheit(x): fahrenheit= x*(9/5)+32 return farenheit
Java
UTF-8
9,526
2.375
2
[ "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
/* Copyright (C) 2013-2023 TU Dortmund * This file is part of AutomataLib, http://www.automatalib.net/. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.automatalib.util.automata.minimizer.paigetarjan; import net.automatalib.automata.AutomatonCreator; import net.automatalib.automata.MutableDeterministic; import net.automatalib.automata.UniversalDeterministicAutomaton; import net.automatalib.automata.UniversalDeterministicAutomaton.FullIntAbstraction; import net.automatalib.automata.concepts.InputAlphabetHolder; import net.automatalib.automata.fsa.DFA; import net.automatalib.automata.fsa.MutableDFA; import net.automatalib.automata.fsa.impl.compact.CompactDFA; import net.automatalib.automata.transducers.MealyMachine; import net.automatalib.automata.transducers.MutableMealyMachine; import net.automatalib.automata.transducers.impl.compact.CompactMealy; import net.automatalib.util.automata.minimizer.hopcroft.HopcroftMinimization; import net.automatalib.util.partitionrefinement.AutomatonInitialPartitioning; import net.automatalib.util.partitionrefinement.PaigeTarjan; import net.automatalib.util.partitionrefinement.PaigeTarjanExtractors; import net.automatalib.util.partitionrefinement.PaigeTarjanInitializers; import net.automatalib.util.partitionrefinement.StateSignature; import net.automatalib.words.Alphabet; /** * A utility class that offers short-hand methods for minimizing automata using the partition refinement approach of * {@link PaigeTarjan}. * <p> * This implementation is specifically tailored towards partial automata by allowing to provide a custom {@code * sinkClassification}, which will be used as the on-demand "successor" of undefined transitions. When extracting * information from the {@link PaigeTarjan} datastructure via {@link PaigeTarjanExtractors}, the original automaton is * used to determine the state-transitions from one partition block to another. If the {@code sinkClassification} did * not match the signature of any existing state, no transition will enter the artificial partition block of the sink. * Consequently, this class will always prune unreachable states, because otherwise we might not return a minimal * automaton. * <p> * For minimizing complete automata, use {@link HopcroftMinimization}. * * @author frohme * @see PaigeTarjan * @see HopcroftMinimization */ public final class PaigeTarjanMinimization { private PaigeTarjanMinimization() {} /** * Minimizes the given DFA. The result is returned in the form of a {@link CompactDFA}, using the input alphabet * obtained via <code>dfa.{@link InputAlphabetHolder#getInputAlphabet() getInputAlphabet()}</code>. * * @param dfa * the DFA to minimize * * @return a minimized version of the specified DFA */ public static <S, I, A extends DFA<S, I> & InputAlphabetHolder<I>> CompactDFA<I> minimizeDFA(A dfa) { return minimizeDFA(dfa, dfa.getInputAlphabet()); } /** * Minimizes the given DFA. The result is returned in the form of a {@link CompactDFA}. * * @param dfa * the DFA to minimize * @param alphabet * the input alphabet (this will be the input alphabet of the returned DFA) * * @return a minimized version of the specified DFA */ public static <I> CompactDFA<I> minimizeDFA(DFA<?, I> dfa, Alphabet<I> alphabet) { return minimizeDFA(dfa, alphabet, new CompactDFA.Creator<>()); } /** * Minimizes the given DFA. The result is returned in the form of a {@link MutableDFA}, constructed by the given * {@code creator}. * * @param dfa * the DFA to minimize * @param alphabet * the input alphabet (this will be the input alphabet of the returned DFA) * @param creator * the creator for constructing the automata instance to return * * @return a minimized version of the specified DFA */ public static <A extends MutableDFA<?, I>, I> A minimizeDFA(DFA<?, I> dfa, Alphabet<I> alphabet, AutomatonCreator<A, I> creator) { return minimizeUniversal(dfa, alphabet, creator, AutomatonInitialPartitioning.BY_STATE_PROPERTY, Boolean.FALSE); } /** * Minimizes the given Mealy machine. The result is returned in the form of a {@link CompactMealy}, using the * alphabet obtained via <code>mealy.{@link InputAlphabetHolder#getInputAlphabet() getInputAlphabet()}</code>. * * @param mealy * the Mealy machine to minimize * * @return a minimized version of the specified Mealy machine */ public static <S, I, T, O, A extends MealyMachine<S, I, T, O> & InputAlphabetHolder<I>> CompactMealy<I, O> minimizeMealy( A mealy) { return minimizeMealy(mealy, mealy.getInputAlphabet()); } /** * Minimizes the given Mealy machine. The result is returned in the form of a {@link CompactMealy}. * * @param mealy * the Mealy machine to minimize * @param alphabet * the input alphabet (this will be the input alphabet of the resulting Mealy machine) * * @return a minimized version of the specified Mealy machine */ public static <I, O> CompactMealy<I, O> minimizeMealy(MealyMachine<?, I, ?, O> mealy, Alphabet<I> alphabet) { return minimizeMealy(mealy, alphabet, new CompactMealy.Creator<>()); } /** * Minimizes the given Mealy machine. The result is returned in the form of a {@link MutableMealyMachine}, * constructed by the given {@code creator}. * * @param mealy * the Mealy machine to minimize * @param alphabet * the input alphabet (this will be the input alphabet of the resulting Mealy machine) * @param creator * the creator for constructing the automata instance to return * * @return a minimized version of the specified Mealy machine */ public static <A extends MutableMealyMachine<?, I, ?, O>, I, O> A minimizeMealy(MealyMachine<?, I, ?, O> mealy, Alphabet<I> alphabet, AutomatonCreator<A, I> creator) { return minimizeUniversal(mealy, alphabet, creator, AutomatonInitialPartitioning.BY_TRANSITION_PROPERTIES, StateSignature.byTransitionProperties(new Object[alphabet.size()])); } /** * Minimizes the given automaton depending on the given partitioning function. The {@code sinkClassification} is * used to describe the signature of the sink state ("successor" of undefined transitions) and may introduce a new, * on-thy-fly equivalence class if it doesn't match a signature of any existing state. See the {@link * StateSignature} class for creating signatures for existing states. * * @param automaton * the automaton to minimize * @param alphabet * the input alphabet (this will be the input alphabet of the resulting Mealy machine) * @param creator * the creator for constructing the automata instance to return * @param ap * the initial partitioning function, determining how states will be distinguished * @param sinkClassification * the classification used when an undefined transition is encountered * * @return the minimized automaton, initially constructed from the given {@code creator}. * * @see AutomatonInitialPartitioning * @see StateSignature */ public static <I, T, SP, TP, A extends MutableDeterministic<?, I, ?, SP, TP>> A minimizeUniversal( UniversalDeterministicAutomaton<?, I, T, SP, TP> automaton, Alphabet<I> alphabet, AutomatonCreator<A, I> creator, AutomatonInitialPartitioning ap, Object sinkClassification) { final PaigeTarjan pt = new PaigeTarjan(); final FullIntAbstraction<T, SP, TP> abs = automaton.fullIntAbstraction(alphabet); PaigeTarjanInitializers.initDeterministic(pt, abs, ap.initialClassifier(abs), sinkClassification); pt.initWorklist(false); pt.computeCoarsestStablePartition(); return PaigeTarjanExtractors.toDeterministic(pt, creator, alphabet, abs, abs::getStateProperty, abs::getTransitionProperty, true); } }
Markdown
UTF-8
1,379
3.046875
3
[]
no_license
# SUMMARY # ## CSS Grid ## - CSS Grid Layout is the most powerful layout system available in CSS. - It is a 2-dimensional system, meaning it can handle both columns and rows, unlike flexbox which is largely a 1-dimensional system. - Grid gives us control over how wide or narrow each of the ‘grid cells’ get. This allows us to maintain a sensible aspect ratio to their height. ![img](https://blog.mido.pp.ua/wp-content/uploads/2018/07/css-grid-framework.png) ## Regex Summary ## - Regular expressions (regex or regexp) are extremely useful in extracting information from any text by searching for one or more matches of a specific search pattern (i.e. a specific sequence of ASCII or unicode characters). - A regex usually comes within this form /abc/, where the search pattern is delimited by two slash characters /. At the end we can specify a flag with these values (we can also combine them each other): - g (global) does not return after the first match, restarting the subsequent searches from the end of the previous match. - m (multi-line) when enabled ^ and $ will match the start and end of a line, instead of the whole string. - i (insensitive) makes the whole expression case-insensitive (for instance /aBc/i would match AbC). ![img](https://lh3.googleusercontent.com/proxy/zuGFLk-fWWMFbU8evVh2T1Y16MhcepG-mY2VqGYD0hmbcIXACgMxDkzFQItPqE_fji1y6OIFHWAPe2Q)
C#
UTF-8
550
3.21875
3
[]
no_license
using System; namespace lesson3HandsOn { class Program { static void Main(string[] args) { string[] names = new string[] {"Emily", "Harry", "Rupert", "Clara", "Lily", "Michael"}; for(int i = 0; i < names.Length; i++) { Console.WriteLine("Have you seen " + names[i]); } for(int idx = names.Length; idx >= 0; idx--) { Console.WriteLine("Have you seen " + names[idx]); } } } }
C
UTF-8
1,439
3.15625
3
[]
no_license
#include "rooms.h" struct Room *room(char *description, struct Item *items, struct Room *current, struct Room *north, struct Room *south, struct Room *east, struct Room *west, struct Room *up, struct Room *down) { struct Room *newRoom = (struct Room *)malloc(sizeof(struct Room)); newRoom->description = description; newRoom->items = items; newRoom->current = current; newRoom->north = north; newRoom->south = south; newRoom->east = east; newRoom->west = west; newRoom->up = up; newRoom->down = down; } void room_exit_north(struct Room *current, struct Room *other) { current->north = other; other->south = current; } void room_exit_south(struct Room *current, struct Room *other) { current->south = other; other->north = current; } void room_exit_east(struct Room *current, struct Room *other) { current->east = other; other->west = current; } void room_exit_west(struct Room *current, struct Room *other) { current->west = other; other->east = current; } void room_exit_up(struct Room *current, struct Room *other) { current->up = other; other->down = current; } void room_exit_down(struct Room *current, struct Room *other) { current->down = other; other->up = current; }
Shell
UTF-8
2,307
3.4375
3
[]
no_license
#!/bin/bash JAVA_NAME=$1 JAVA_PORT=$2 JAVA_TYPE=$3 JAVA_DO=$4 if [ "$JAVA_NAME" = "" ]; then echo "参数不为空,使用sh $0 JAVA_NAME JAVA_PORT JAVA_DO";exit 1 fi if [ "$JAVA_PORT" = "" ]; then echo "参数不为空,使用sh $0 JAVA_NAME JAVA_PORT JAVA_DO";exit 1 fi if [ "$JAVA_TYPE" = "" ]; then echo "参数不为空,使用sh $0 JAVA_NAME JAVA_PORT JAVA_DO";exit 1 fi if [ "$JAVA_DO" = "" ]; then echo "参数不为空,使用sh $0 JAVA_NAME JAVA_PORT JAVA_DO";exit 1 fi JAVA_KILL(){ /bin/ps aux | grep -w $JAVA_NAME | grep -v -w grep | grep -w $JAVA_PORT | awk '{print $2}' |xargs kill -9 } JAVA_START(){ if [ "$JAVA_TYPE" = "war" ]; then nohup sh /data/$JAVA_PORT-$JAVA_NAME/bin/startup.sh 2>&1 & elif [ "$JAVA_TYPE" = "jar" ]; then JAVA_DEBUG_OPTS="" JAVA_MEM_DIR=" -Duser.dir=$1 " JAVA_MEM_JMX=" -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=2${java_port} -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Djava.rmi.server.hostname=${TOMCAT_IP} " JAVA_MEM_SIZE_OPTS="-Xms2548m -Xmx2548m -XX:PermSize=64m -XX:MaxPermSize=256m -Dfile.encoding=UTF-8" JAVA_MEM_OPTS=" -server -XX:+DisableExplicitGC -XX:+UseConcMarkSweepGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection $JAVA_MEM_SIZE_OPTS $JAVA_MEM_JMX $JAVA_MEM_DIR" cd /tmp nohup /usr/local/jdk1.8/bin/java $JAVA_MEM_OPTS $JAVA_DEBUG_OPTS -jar /data/$JAVA_PORT-$JAVA_NAME/$JAVA_NAME.jar >/dev/null 2>&1 & echo "[INFO]$JAVA_PORT-$JAVA_NAME deploy end" else echo "JAVA_TYPE error" exit 1 fi } JAVA_RESTART(){ JAVA_KILL sleep 3 JAVA_START } JAVA_REDEPLOY(){ JAVA_KILL sleep 3 if [ "$JAVA_TYPE" = "war" ]; then nohup sh /jenkins/data/deploy_war.sh /data/$JAVA_PORT-$JAVA_NAME/ $JAVA_NAME.war 2>&1 & elif [ "$JAVA_TYPE" = "jar" ]; then nohup sh /jenkins/data/deploy_jar.sh /data/$JAVA_PORT-$JAVA_NAME/ $JAVA_NAME.jar 2>&1 & else echo "JAVA_TYPE error" exit 1 fi } if [ "$JAVA_DO" = "kill" ]; then JAVA_KILL echo "killed" elif [ "$JAVA_DO" = "start" ]; then JAVA_START echo "started" elif [ "$JAVA_DO" = "restart" ]; then JAVA_RESTART echo "restarted" elif [ "$JAVA_DO" = "redeploy" ]; then JAVA_REDEPLOY echo "redeplayed" else echo "do nothing" exit 1 fi
JavaScript
UTF-8
667
3.390625
3
[]
no_license
function rollDice() { return -1 * Math.floor(Math.random() * 6) + 1; } require('chai').should(); var expect = require('chai').expect; describe('When a customer rolls a dice', function(){ it('should return an integer number', function() { expect(rollDice()).to.be.an('number'); }); it('should get a number below 7', function(){ rollDice().should.be.below(7); }); it('should get a number bigger than 0', function(){ rollDice().should.be.above(0); }); it('should not be null', function() { expect(rollDice()).to.not.be.null; }); it('should not be undefined', function() { expect(rollDice()).to.not.be.undefined; }); });
Markdown
UTF-8
1,012
3.296875
3
[ "MIT", "Unlicense" ]
permissive
--- title: How does the GC handle circular references? categories: .Net date: 2007-04-13 15:35:30 +10:00 --- I am a little curious about how the garbage collector cleans up CLR objects. From what I understand, it will wait until objects are de-referenced and then will go through a couple of generations (as required) to release objects from memory. The following is a simple scenario of GC: > Object A that has a reference to B that has a reference to C. When A goes out of scope, the GC can collect it. When it removes A, B is has a reference count of 0 and can also be removed and then likewise for C as B is removed. Side question: does this happen in the same GC cycle or is this over three GC cycles? Ok, simple enough. But how does the GC handle the following scenario: > Object A has a reference to B which has a reference to C. C has a reference back to B. When A goes out of scope, is B available for the GC as it is still referenced by C? How does the GC handle these circular references?
Java
UTF-8
724
2.515625
3
[]
no_license
package com.sudhir; public class LoggerFinder { static{ System.out.println("First here"); Package objPackage = org.apache.log4j.Logger.class.getPackage(); System.out.println("Logging vendor"+objPackage.getImplementationVendor()); System.out.println("Logging version"+objPackage.getSpecificationVersion()); Package objPackage1 = java.util.logging.Logger.class.getPackage(); System.out.println("Logging vendor"+objPackage1.getImplementationVendor()); System.out.println("Logging version"+objPackage1.getSpecificationVersion()); } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("then here"); } }
C++
UHC
2,123
3.15625
3
[]
no_license
#include <iostream> #include <algorithm> using namespace std; const int INF = 1<<21; struct segtree{ int start; long long arr[INF], lazy[INF]; // segtree(){ start = INF/2; fill(arr, arr+INF, 0); fill(lazy, lazy+INF, 0); } //leaf Է ü segment tree void construct(){ for(int i=start-1; i>0; i--){ arr[i] = arr[i*2] + arr[i*2+1]; } } //(ns, ne) node lazy void propagate(int node, int ns, int ne){ //lazy ϸ if(lazy[node]){ //leaf node ƴϸ ڽĵ鿡 lazy if(node < start){ lazy[node*2] += lazy[node]; lazy[node*2 + 1] += lazy[node]; } //شϴ ŭ ϱ arr[node] += lazy[node] * (ne-ns); lazy[node] = 0; } } // (s, e) k ϱ void add(int s, int e, int k){ return add(s, e, k, 1, 0, start); } void add(int s, int e, int k, int node, int ns, int ne){ // propagate(node, ns, ne); if(e <= ns || ne <= s) return; if(s <= ns && ne <= e){ //lazy ο lazy[node] += k; propagate(node, ns, ne); return; } int mid = (ns + ne) / 2; add(s, e, k, node*2, ns, mid); add(s, e, k, node*2 + 1, mid, ne); // ڽĵ ڽ arr[node] = arr[node*2] + arr[node*2 + 1]; } // (s, e) ϱ long long sum(int s, int e){ return sum(s, e, 1, 0, start); } long long sum(int s, int e, int node, int ns, int ne){ // propagate(node, ns, ne); if(e <= ns || ne <= s) return 0; if(s <= ns & ne <= e) return arr[node]; int mid = (ns+ne)/2; return sum(s, e, node*2, ns, mid) + sum(s, e, node*2 + 1, mid, ne); } }segtree; int main(){ int n,m,k; cin>>n; cin>>m; cin>>k; struct segtree st; for(int i=0; i<n; i++){ cin>>*(st.arr+st.start+i); } st.construct(); int a,b,c,d, ret; for(int i=0; i<m+k; i++){ cin>>a; if(a==1){ cin>>b; cin>>c; cin>>d; st.add(b-1, c, d); } else{ cin>>b; cin>>c; ret = st.sum(b-1, c); } cout<<ret<<endl; } }
Python
UTF-8
362
2.59375
3
[]
no_license
import pymysql db = pymysql.connect(host='192.168.33.30',user='root',password='root',db='test',port=3306) cur = db.cursor() sql_insert = "insert into user(name,url) values('test','test.com')" try: affected_rows = cur.execute(sql_insert) db.commit() print(cur.lastrowid) except Exception as e: print(e) finally: db.close()
JavaScript
UTF-8
5,249
2.984375
3
[]
no_license
const socket = io() socket.on('connect', function () { console.log('Connected') }) socket.on('disconnect', function () { console.log('Disconnected') }) socket.on('webhook-event', function (e) { if (e.type === 'note') { console.log('Type of webhook event: ' + e.type) createNotification(e, 'New comment added to an issue') updateAmountOfComments(e) } else if (e.type === 'issue') { if (e.state === 'closed') { console.log('Type of webhook event: ' + e.type) createNotification(e, 'Issue has been closed') removeClosedIssue(e) } else { console.log('Type of webhook event: ' + e.type) createNotification(e, 'New issue has been added') newIssueEvent(e) } } }) /** Function to create notifications * * @param {*} event Event that triggered the update * @param {*} type Type of notification */ const createNotification = (event, type) => { const notification = document.getElementById('notificationList') const notificationBox = document.createElement('div') notificationBox.setAttribute('class', 'notificationBox') // Header creation const header = document.createElement('header') header.setAttribute('class', 'notificationHeader') header.innerHTML = `<h4>${type}</h4>` notificationBox.append(header) const content = document.createElement('div') content.setAttribute('class', 'notificationContent') const createdDate = document.createElement('p') createdDate.innerText = 'Created date: ' + event.created_at const link = document.createElement('a') link.setAttribute('href', event.link) link.innerText = 'Link to the issue' const title = document.createElement('p') title.innerText = 'Title: ' + event.title const author = document.createElement('p') author.innerText = 'Author: ' + event.author if (event.type === 'note') { const description = document.createElement('p') description.innerText = 'Comment: ' + event.description content.append(description) const underIssue = document.createElement('p') underIssue.innerText = 'Issue: ' + event.title content.append(underIssue) } else if (event.type === 'issue') { content.append(title) } content.append(author) content.append(createdDate) content.append(link) notificationBox.append(content) notification.append(notificationBox) } /** * Function for addressing new issues * * @param {*} event Event that triggered the update */ const newIssueEvent = (event) => { const ul = document.getElementById('issues') const li = document.createElement('li') li.setAttribute('class', 'issues', 'id' + event.id) const div = document.createElement('div') div.setAttribute('id', 'ribbon') const h4 = document.createElement('h4') h4.setAttribute('id', 'title') const text = document.createTextNode('Title: ' + event.title) const spanBody = document.createElement('span') spanBody.setAttribute('class', 'body') const body = document.createTextNode('Description: ' + event.description) const br = document.createElement('br') const a = document.createElement('a') a.setAttribute('href', event.link) const links = document.createTextNode('Link to issue') const pComment = document.createElement('p') pComment.setAttribute('id', 'comments') const comment = document.createTextNode('Comments: ' + 0) const pAuthor = document.createElement('p') pAuthor.setAttribute('id', 'author') const author = document.createTextNode('Author: ' + event.author) const pCreated = document.createElement('p') pComment.setAttribute('id', 'createdAt') const created = document.createTextNode('Created at: ' + event.created_at) const pUpdated = document.createElement('p') pComment.setAttribute('id', 'updatedAt') const updated = document.createTextNode('Updated at: ' + event.created_at) h4.appendChild(text) spanBody.appendChild(body) a.appendChild(links) pComment.appendChild(comment) pAuthor.appendChild(author) pCreated.appendChild(created) pUpdated.appendChild(updated) div.appendChild(h4) div.appendChild(spanBody) div.appendChild(br) div.appendChild(a) div.appendChild(pComment) div.appendChild(pAuthor) div.appendChild(pCreated) div.appendChild(pUpdated) li.appendChild(div) ul.insertBefore(li, ul.childNodes[0]) } /** * Function to update number of comments in real-time * * @param {*} event Event that triggered the update */ const updateAmountOfComments = (event) => { const issue = document.getElementById(event.id) const comments = issue.querySelector('#comments') let commentNumber = comments.textContent commentNumber = commentNumber.replace(/[^0-9]/g, '') const newCommentsNumber = parseInt(commentNumber) + 1 comments.textContent = 'Comments: ' + newCommentsNumber const update = issue.querySelector('#updatedAt') update.textContent = 'Updated at: ' + event.updated_at } /** * Function to remove closed issue from the page * * @param {*} event Event that triggered the update */ const removeClosedIssue = (event) => { document.getElementById(event.id).remove() }
Java
UTF-8
12,446
1.679688
2
[]
no_license
package jdhe.iyibank.com.iyimeal.sqlitedb.db; /** * Created by Administrator on 2017/8/8. */ public class TableConfig { public static final String TABLE_ACCOUNTS = "accounts" ; /** * Accounts数据表的字段 */ public static class Accounts{ //Accounts public static final String ID="ID"; public static final String BALANCE="Balance"; public static final String CREATETIME="CreateTime"; public static final String RECHARGE="Recharge"; public static final String REMARKS="Remarks"; public static final String SHOPID="ShopID"; public static final String TOTALFREEMONEY="TotalFreeMoney"; public static final String UNIONID="UnionID"; public static final String USERID="UserID"; } public static final String TABLE_DESKS = "desks"; /** * Desks数据表的字段 */ public static class Desks{ //Desks public static final String ID="ID"; public static final String COGNATEID="CognateId" ; public static final String CREATETIME="CreateTime"; public static final String CREATEUSER="CreateUser"; public static final String CUSTOMERLIMIT="CustomerLimit"; public static final String DESKFEE="DeskFee"; public static final String ENABLE="Enable"; public static final String UNIONID="UnionID"; public static final String NAME="Name"; public static final String RANKNUM="RankNum"; public static final String REGIONID="RegionId"; public static final String REMARKS="Remarks"; public static final String SORTNAME="SortName"; public static final String STATE="State"; public static final String STATEDINING="StateDining"; } public static final String TABLE_ODRERITEMS="orderitems" ; /** * Orderitems数据表的字段 */ public static class Orderitems{ public static final String ID="ID"; public static final String COUNT="Count" ; public static final String DESKID="DeskId"; public static final String DESKNAME="DeskName"; public static final String ISFREE="IsFree"; public static final String MONEY="Money"; public static final String ORDERID="OrderID"; public static final String UNIONID="UnionID"; public static final String PRODUCTID="ProductId"; public static final String PRODUCTNAME="ProductName"; public static final String PRODUCTTYPEID="ProductTypeId"; public static final String PRODUCTTYPENAME="ProductTypeName"; } public static final String TABLE_ORDERS = "orders" ; /** * Orders数据表的字段 */ public static class Orders{ public static final String ID="ID"; public static final String CREATEDATE="CreateDate" ; public static final String DESKCOUNT="DeskCount"; public static final String DISCOUNTLIST="DiscountList"; public static final String ORDERNUMBER="OrderNumber"; public static final String ORDERSTATU="OrderStatu"; public static final String ORDERTATALAMOUNT="OrderTotalAmount"; public static final String USERREMARK="UserRemark"; public static final String ORDERTYPE="OrderType"; public static final String OTHERFEETOTALAMOUNT="OtherFeeTotalAmount"; public static final String PAYDATA="PayDate"; public static final String PLATFORM="Platform"; public static final String PRODUCTCOUNT="ProductCount"; public static final String PRODUCTTOTALAMOUNT="ProductTotalAmount"; public static final String SELLERREMARK="SellerRemark"; public static final String SELLERUSER="SellerUser"; public static final String SHOPID="ShopID"; } public static final String TABLE_PAYSETTINGS = "paysettings"; /** * Paysettings数据表的字段 */ public static class Paysettings{ public static final String ID="ID"; public static final String DESCRIPTION="Description" ; public static final String ENCODE="Encode" ; public static final String IMAGURL="ImgUrl"; public static final String LASTMODIFYTIME="LastModifyTime"; public static final String NAME="Name"; public static final String SCANTYPE="ScanType"; } public static final String TABLE_PERMISSIONS = "permissions" ; /** * Permissions数据表的字段 */ public static class Permissions{ public static final String ID="ID"; public static final String NAME="Name"; public static final String UNIONID="UnionID" ; } public static final String TABLE_PRODUCTS = "products" ; /** * Products数据表的字段 */ public static class Products{ public static final String ID="ID"; public static final String CREATETIME="CreateTime" ; public static final String CREATEUSERID="CreateUserID" ; public static final String ENABLE="Enable"; public static final String IMAGEURL="ImageURL"; public static final String ISRECEIVELOGO="IsReceiveLogo"; public static final String MEMBERPRICE="MemberPrice"; public static final String NAME="Name"; public static final String NAMEEN="NameEN"; public static final String PRICE="Price"; public static final String PRODUCTCODE="ProductCode" ; public static final String RPODUCTTYPE="ProductType" ; public static final String RANKNUM="RankNum" ; public static final String REMARKS="Remarks" ; public static final String SHOPID="ShopId"; public static final String SPECIALPRICE="SpecialPrice"; public static final String UNIONID="UnionID"; public static final String UNITFORMAT="UnitFormat" ; public static final String UNITSIZE="UnitSize"; } public static final String TABLE_PRODUCTTYPES = "producttypes" ; /** * Producttypes数据表的字段 */ public static class Producttypes{ public static final String ID="ID"; public static final String CREATETIME="CreateTime" ; public static final String CREATEUSERID="CreateUserID" ; public static final String ENABLE="Enable"; public static final String NAME="Name"; public static final String NUM="Num"; public static final String PARENTTYPEID="ParentTypeID"; public static final String RANKNUM="RankNum" ; public static final String REMARKS="Remarks" ; public static final String SHOPID="ShopID"; public static final String UNIONID="UnionID"; } public static final String TABLE_REGISONS = "regions" ; /** * Regions数据表的字段 */ public static class Regions{ public static final String ID="ID"; public static final String CREATETIME="CreateTime" ; public static final String CREATEUSERID="CreateUserID" ; public static final String ENABLE="Enable"; public static final String NAME="Name"; public static final String REMARKS="Remarks" ; public static final String SHOPID="ShopId"; public static final String UNIONID="UnionID"; } public static final String TABLE_SHOPMEMBERS = "shopmembers" ; /** * Shopmembers数据表的字段 */ public static class Shopmembers{ public static final String ID="ID"; public static final String ACCOUNTBALANCE="AccountBalance" ; public static final String ACCOUNTID="AccountID" ; public static final String ADDRESS="Address"; public static final String BIRTHDAY ="Birthday"; public static final String CARDNO="CardNo"; public static final String CREATETIME="CreateTime"; public static final String CREATEUSERID="CreateUserID" ; public static final String ENABLE="Enable"; public static final String NAME="Name"; public static final String PHONE="Phone"; public static final String REMARKS="Remarks" ; public static final String SHOPID="ShopID"; public static final String UNIONID="UnionID"; } public static final String TABLE_SHOPPRINTSETINGS = "shopprintsettings" ; /** * Shopprintsettings数据表的字段 */ public static class Shopprintsettings{ public static final String ID="ID"; public static final String LASTUPDATATEDATE="LastUpdateDate" ; public static final String CREATETIME="CreateTime"; public static final String CREATEUSERID="CreateUserID" ; public static final String SHOPID="ShopID"; public static final String UNIONID="UnionID"; } public static final String TABLE_SHOPS = "shops" ; /** * Shops数据表的字段 */ public static class Shops{ public static final String ID="ID"; public static final String BLUETOOTHPRINT="BlueToothPrint" ; public static final String CONTRACTOR="Contractor" ; public static final String ADDRESS="Address"; public static final String CREATEDATE ="CreateDate"; public static final String DESCRIPTION="Description"; public static final String ISKITCHENPRINT="IsKitchenPrint"; public static final String NAME="Name"; public static final String UNIONID="UnionID"; } public static final String TABLE_TRADERECORDS = "traderecords" ; /** * Traderecords数据表的字段 */ public static class Traderecords{ public static final String ID="ID"; public static final String MONEY="Money" ; public static final String REMARKS="Remarks" ; public static final String SHOPID="ShopID"; public static final String TRADETIME ="TradeTime"; public static final String TRADETYPE="TradeType"; public static final String USERID="UserID"; public static final String UNIONID="UnionID"; } public static final String TABLE_USERS = "users" ; /** * Users数据表的字段 */ public static class Users{ public static final String ID="ID"; public static final String EMAIL="Email" ; public static final String FESTUREPASSWORD="Gesturepassword" ; public static final String GEATUREPASSWORDSTATE="GesturepasswordState"; public static final String HEADIMAURL ="HeadImgUrl"; public static final String LASTLOGINTIME="LastLoginTime"; public static final String MASTERID="MasterID"; public static final String MOBILENUMBER="MobileNumber" ; public static final String ENABLE="Enable"; public static final String NICKNAME="NickName"; public static final String PASSWORD="Password"; public static final String PERMISSION="Permission" ; public static final String SHOPID="ShopID"; public static final String UNIONID="UnionID"; public static final String REGTIME="RegTime"; public static final String USERNAME="Username"; } public static final String TABLE_WORKSHIFTCHANGERECORDS= "workshiftchangerecords" ; /** * Workshiftchangerecords数据表的字段 */ public static class Workshiftchangerecords{ public static final String ID="ID"; public static final String CHANGETIME="ChangeTime" ; public static final String CREATETIME="CreateTime" ; public static final String REAMRKS="Reamrks"; public static final String TOTALRECEIVEMONEY ="TotalReceiveMoney"; public static final String WORKSHIFTSID="WorkShiftsID"; public static final String USERID="UserID"; public static final String UNIONID="UnionID"; } public static final String TABLE_WORKSHIFTS = "workshifts" ; /** * Workshifts数据表的字段 */ public static class Workshifts{ public static final String ID="ID"; public static final String CREATEUSERID="CreateUserID" ; public static final String CREATETIME="CreateTime" ; public static final String REAMRKS="Reamrks"; public static final String ENABLE ="Enable"; public static final String ENDTIME="EndTime"; public static final String ISOVERDAYSHIFTS="IsOverDayShifts"; public static final String STARTTIME="StartTime"; public static final String NAME="Name"; public static final String UNIONID="UnionID"; } }
Python
UTF-8
5,631
3.09375
3
[]
no_license
import os, sys, time import subprocess import hashlib # ##################################################################### def leer_texto_claro(num): hash = list() texto_claro = list() file = open('C:/tarea4/cracked/crack_'+ num +'.txt', 'r') if(num == "1"): for hash_texto in file: texto_claro.append(hash_texto[33:len(hash_texto)-1]) return (texto_claro) elif(num == "2"): for hash_texto in file: texto_claro.append(hash_texto[50:len(hash_texto)-1]) return (texto_claro) elif(num == "3"): char = 0 indice_dos_puntos = 0 #auxiliar que observa : y espacios password = "" for hash_texto in file: while char < len(hash_texto): if (indice_dos_puntos == 2): password += hash_texto[char] if (hash_texto[char] == ":"): indice_dos_puntos += 1 char += 1 texto_claro.append(password) password = "" indice_dos_puntos = 0 char = 0 return (texto_claro) elif(num == "4"): for hash_texto in file: texto_claro.append(hash_texto[33:len(hash_texto)-1]) return (texto_claro) elif(num == "5"): for hash_texto in file: indice_dos_puntos = hash_texto.index(':') texto_claro.append(hash_texto[indice_dos_puntos+1:len(hash_texto)-1]) return (texto_claro) def sha512(txt_claro): s = hashlib.sha3_512() list_sha512 = list() for pwd in txt_claro: s.update(pwd.encode('utf-8')) list_sha512.append(s.hexdigest()) return(list_sha512) # ####################ARCHIVO 1######################### # timeINIT_hash = time.time() # os.system("hashcat.exe -m 0 -a 0 -D 2 -o C:/tarea4/cracked/crack_1.txt C:/tarea4/hash/archivo_1 C:/tarea4/diccionario_1.dict C:/tarea4/diccionario_2.dict --potfile-disable") # timeEND_hash = time.time() # tiempo_hash1= timeEND_hash - timeINIT_hash # txt_claro_1 = leer_texto_claro("1") # print("lista de password archivo 1",txt_claro_1) # print("\n\n\n\ntiempo que se demoro en crackear el archivo 1 ", tiempo_hash1) # timeINIT_sha512 = time.time() # list_sha512_1 = sha512(txt_claro_1) # timeEND_sha512 = time.time() # tiempo_sha5121= timeEND_sha512 - timeINIT_sha512 # print(list_sha512_1) # print("\n\n\n\ntiempo que se demoro en hashear con sha512 el archivo 1", tiempo_sha5121) # #################ARCHIVO 2############################ # timeINIT_hash = time.time() # os.system("hashcat.exe -m 10 -a 0 -D 2 -o C:/tarea4/cracked/crack_2.txt C:/tarea4/hash/archivo_2 C:/tarea4/diccionario_1.dict C:/tarea4/diccionario_2.dict --potfile-disable") # timeEND_hash = time.time() # tiempo_hash2= timeEND_hash - timeINIT_hash # txt_claro_2 = leer_texto_claro("2") # print("lista de password archivo 2",txt_claro_2) # print("tiempo que se demoro en crackear el archivo 2", tiempo_hash2) # timeINIT_sha512 = time.time() # list_sha512_2 = sha512(txt_claro_2) # timeEND_sha512 = time.time() # tiempo_sha5122= timeEND_sha512 - timeINIT_sha512 # print(list_sha512_2) # print("tiempo que se demoro en hashear con sha512 el archivo 2", tiempo_sha5122) # ################ARCHIVO 3############################## # timeINIT_hash = time.time() # os.system("hashcat.exe -m 10 -a 0 -D 2 -o C:/tarea4/cracked/crack_3.txt C:/tarea4/hash/archivo_3 C:/tarea4/diccionario_1.dict C:/tarea4/diccionario_2.dict --potfile-disable") # timeEND_hash = time.time() # tiempo_hash3= timeEND_hash - timeINIT_hash # txt_claro_3 = leer_texto_claro("3") # print("lista de password archivo 3",txt_claro_3) # print("tiempo que se demoro en crackear el archivo 3", tiempo_hash3) # timeINIT_sha512 = time.time() # list_sha512_3 = sha512(txt_claro_3) # timeEND_sha512 = time.time() # tiempo_sha5123= timeEND_sha512 - timeINIT_sha512 # print(list_sha512_3) # print("tiempo que se demoro en hashear con sha512 el archivo 3", tiempo_sha5123) # ###############ARCHIVO 4############################## # timeINIT_hash = time.time() # os.system("hashcat.exe -m 1000 -a 0 -D 2 -o C:/tarea4/cracked/crack_4.txt C:/tarea4/hash/archivo_4 C:/tarea4/diccionario_1.dict C:/tarea4/diccionario_2.dict --potfile-disable") # timeEND_hash = time.time() # tiempo_hash4= timeEND_hash - timeINIT_hash # txt_claro_4 = leer_texto_claro("4") # print("lista de password archivo 4",txt_claro_4) # print("tiempo que se demoro en crackear el archivo 4", tiempo_hash4) # timeINIT_sha512 = time.time() # list_sha512_4 = sha512(txt_claro_4) # timeEND_sha512 = time.time() # tiempo_sha5124= timeEND_sha512 - timeINIT_sha512 # print(list_sha512_4) # print("tiempo que se demoro en hashear con sha512 el archivo 4", tiempo_sha5124) # ################ARCHIVO 5############################# timeINIT_hash = time.time() os.system("hashcat.exe -m 1800 -a 0 -D 2 -o C:/tarea4/cracked/crack_5.txt C:/tarea4/hash/archivo_5 C:/tarea4/diccionario_1.dict C:/tarea4/diccionario_2.dict --potfile-disable") timeEND_hash = time.time() tiempo_hash5= timeEND_hash - timeINIT_hash txt_claro_5 = leer_texto_claro("5") print("lista de password archivo 5",txt_claro_5) print("tiempo que se demoro en crackear el archivo 5", tiempo_hash5) timeINIT_sha512 = time.time() list_sha512_5 = sha512(txt_claro_5) timeEND_sha512 = time.time() tiempo_sha5125 = timeEND_sha512 - timeINIT_sha512 print(list_sha512_5) print("tiempo que se demoro en hashear con sha512 el archivo 5", tiempo_sha5125)
Java
UTF-8
975
1.90625
2
[]
no_license
package ru.fondorg.mytracksrv.domain; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import javax.persistence.*; import javax.validation.constraints.NotNull; import java.time.LocalDateTime; import java.util.Set; @Getter @Setter @Entity @NoArgsConstructor public class Issue { @Id @GeneratedValue private Long id; @NotNull // @Column(nullable = false) private Long pid; @Column(columnDefinition = "TIMESTAMP") private LocalDateTime created; @NotNull @Column(name = "title", nullable = false) private String title; @Column(name = "description", length = 2048) private String description; @ManyToOne(fetch = FetchType.LAZY) private Project project; @ManyToOne(fetch = FetchType.LAZY) private User author; @Column(nullable = false) private Boolean closed = false; @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) private Set<Tag> tags; }
C++
UTF-8
10,197
2.515625
3
[]
no_license
/* * StreamListView.cc * * Created on: Apr 4, 2015 * Author: amyznikov */ #include "msmwctl.h" #include "StreamListView.h" #define count_of(x) (sizeof(x)/sizeof((x)[0])) namespace { struct column_decs { const char * name; WLength width; }; #define INPUT_COLUMN_NAME 0 #define INPUT_COLUMN_STATE 1 #define INPUT_COLUMN_ENABLED 2 #define INPUT_COLUMN_START_TIME 3 #define INPUT_COLUMN_STATUS 4 static const column_decs input_columns[] = { { "input name", WLength(20, WLength::FontEx) }, { "state", WLength(20, WLength::FontEx) }, { "enabled", WLength(20, WLength::FontEx) }, { "start time", WLength(20, WLength::FontEx) }, { "status", WLength(20, WLength::FontEx) }, }; #define OUTPUT_COLUMN_NAME 0 #define OUTPUT_COLUMN_STATE 1 #define OUTPUT_COLUMN_ENABLED 2 static const column_decs output_columns[] = { { "output name", WLength(20, WLength::FontEx)}, { "state", WLength(20, WLength::FontEx)}, { "enabled", WLength(20, WLength::FontEx)}, }; #define SINK_COLUMN_NAME 0 #define SINK_COLUMN_STATE 1 #define SINK_COLUMN_FORMAT 2 #define SINK_COLUMN_URL 3 static const column_decs sink_columns[] = { { "sink name", WLength(20,WLength::FontEx)}, { "state", WLength(20, WLength::FontEx)}, { "format", WLength(20, WLength::FontEx)}, { "URL", WLength(20, WLength::FontEx)}, }; #define SESSION_COLUMN_NAME 0 #define SESSION_COLUMN_ADDRESS 1 #define SESSION_COLUMN_AGENT 2 static const column_decs session_columns[] = { { "session name", WLength(20, WLength::FontEx) }, { "address", WLength(20, WLength::FontEx)}, { "agent", WLength(20, WLength::FontEx)}, }; } static void setRowCount(WStandardItemModel * model, int count) { const int rc = model->rowCount(); if ( rc < count ) { model->insertRows(rc, count - rc); } else { model->removeRows(count, rc - count); } } static inline void setColumnWidth(WTableView * table, int index, size_t width) { table->setColumnWidth(index, WLength(width, WLength::FontEx)); } static inline void adjustTableSize(WTableView * tbl, const column_decs columns[], const size_t cw[], size_t nb_columns) { size_t i, n, x; for ( i = 0, n = 0; i < nb_columns; ++i ) { n += (x = std::max(cw[i], strlen(columns[i].name) + 4)); tbl->setColumnWidth(i, WLength(x, WLength::FontEx)); } } static WTableView * createTable(const column_decs columns[], int nb_columns, WContainerWidget * parent = 0) { WTableView * table; WStandardItemModel * model; table = new WTableView(parent); table->setModel(model = new WStandardItemModel(0, 0, table)); model->insertColumns(0, nb_columns); table->setSortingEnabled(true); table->setColumnResizeEnabled(true); for ( int i = 0, n = nb_columns; i < n; ++i ) { model->setHeaderData(i, Wt::Orientation::Horizontal, boost::any(WString::fromUTF8(columns[i].name))); table->setHeaderAlignment(i, Wt::AlignLeft); table->setColumnAlignment(i, Wt::AlignLeft); setColumnWidth(table, i, strlen(columns[i].name) + 4); } return table; } class StreamsTab : public WContainerWidget { protected: WTableView * table; WPushButton * refreshButton; StreamsTab(const column_decs columns[], int nb_columns, WContainerWidget * parent = 0) : WContainerWidget(parent) { addStyleClass("streamstab"); WVBoxLayout * vbox = new WVBoxLayout(this); vbox->addWidget(table = createTable(columns, nb_columns)); vbox->addWidget(refreshButton = new WPushButton("Refresh"),1, Wt::AlignLeft); refreshButton->clicked().connect(this, &StreamsTab::populateTable); } public: virtual void populateTable() = 0; }; class InputsTab : public StreamsTab { public: InputsTab(WContainerWidget* parent = 0) : StreamsTab(input_columns, count_of(input_columns), parent) {} void populateTable() { WStandardItemModel * model; std::vector<MsmInput> inputs; if ( !msmLoadInputs(&inputs) ) { setRowCount((WStandardItemModel*) table->model(), 0); } else { size_t cw [count_of(input_columns)] = {0}; size_t i, n, x; std::string s; setRowCount(model = (WStandardItemModel*) table->model(), n = inputs.size()); for ( i = 0; i < n; ++i ) { const MsmInput & input = inputs[i]; cw[INPUT_COLUMN_NAME] = std::max(cw[INPUT_COLUMN_NAME], (s = input.getName()).size()); model->setData(i, INPUT_COLUMN_NAME, boost::any(s)); cw[INPUT_COLUMN_STATE] = std::max(cw[INPUT_COLUMN_STATE], (s = msm_state_string(input.getState())).size()); model->setData(i, INPUT_COLUMN_STATE, boost::any(s)); cw[INPUT_COLUMN_ENABLED] = std::max(cw[INPUT_COLUMN_ENABLED], (s = t2s(input.getEnabled())).size()); model->setData(i, INPUT_COLUMN_ENABLED, boost::any(s)); cw[INPUT_COLUMN_START_TIME] = std::max(cw[INPUT_COLUMN_START_TIME], (s = input.getStartTime()).size()); model->setData(i, INPUT_COLUMN_START_TIME, boost::any(s)); } adjustTableSize(table, input_columns, cw, count_of(input_columns)); } } }; class OutputsTab : public StreamsTab { public: OutputsTab(WContainerWidget* parent = 0) : StreamsTab(output_columns, count_of(output_columns), parent) {} void populateTable() { WStandardItemModel * model; std::vector<MsmOutput> outputs; if ( !msmLoadOutputs(&outputs) ) { setRowCount((WStandardItemModel*) table->model(), 0); } else { size_t cw [count_of(output_columns)] = {0}; size_t i, n; std::string s; WString ws; setRowCount(model = (WStandardItemModel*) table->model(), n = outputs.size()); for ( i = 0; i < n; ++i ) { const MsmOutput & output = outputs[i]; ws = WString("{1}/{2}").arg(output.getInputName()).arg(output.getName()); cw[OUTPUT_COLUMN_NAME] = std::max(cw[OUTPUT_COLUMN_NAME], ws.toUTF8().size()); model->setData(i, OUTPUT_COLUMN_NAME, boost::any(ws)); cw[OUTPUT_COLUMN_STATE] = std::max(cw[OUTPUT_COLUMN_STATE], (s = msm_state_string(output.getState())).size()); model->setData(i, OUTPUT_COLUMN_STATE, boost::any(s)); cw[OUTPUT_COLUMN_ENABLED] = std::max(cw[OUTPUT_COLUMN_ENABLED],(s=t2s(output.getEnabled())).size()); model->setData(i, OUTPUT_COLUMN_ENABLED, boost::any(s)); } for ( i = 0; i < count_of(output_columns); ++i ) { setColumnWidth(table, i, std::max(cw[i], strlen(output_columns[i].name) + 4)); } } } }; class SinksTab : public StreamsTab { public: SinksTab(WContainerWidget* parent = 0) : StreamsTab(sink_columns, count_of(sink_columns), parent) {} void populateTable() { WStandardItemModel * model; std::vector<MsmSink> sinks; if ( !msmLoadSinks(&sinks) ) { setRowCount((WStandardItemModel*) table->model(), 0); } else { size_t cw [count_of(sink_columns)] = {0}; size_t i, n; std::string s; WString ws; setRowCount(model = (WStandardItemModel*) table->model(), n = sinks.size()); for ( i = 0; i < n; ++i ) { const MsmSink & sink = sinks[i]; ws = WString("{1}/{2}/{3}").arg(sink.getInputName()).arg(sink.getOutputName()).arg(sink.getName()); cw[SINK_COLUMN_NAME] = std::max(cw[SINK_COLUMN_NAME],ws.toUTF8().size()); model->setData(i, SINK_COLUMN_NAME, boost::any(ws)); cw[SINK_COLUMN_STATE] = std::max(cw[SINK_COLUMN_STATE], (s = msm_state_string(sink.getState())).size()); model->setData(i, SINK_COLUMN_STATE, s); cw[SINK_COLUMN_FORMAT] = std::max(cw[SINK_COLUMN_FORMAT], (s = sink.getFormat()).size()); model->setData(i, SINK_COLUMN_FORMAT, s); cw[SINK_COLUMN_URL] = std::max(cw[SINK_COLUMN_URL], (s = sink.getUrl()).size()); model->setData(i, SINK_COLUMN_URL, s); } for ( i = 0; i < count_of(sink_columns); ++i ) { setColumnWidth(table, i, std::max(cw[i], strlen(sink_columns[i].name) + 4)); } } } }; class SessionsTab : public StreamsTab { public: SessionsTab(WContainerWidget* parent = 0) : StreamsTab(session_columns, count_of(session_columns), parent) {} void populateTable() { WStandardItemModel * model; std::vector<MsmSession> sessions; if ( !msmLoadSessions(&sessions) ) { setRowCount((WStandardItemModel*) table->model(), 0); } else { size_t cw[count_of(session_columns)] = { 0 }; size_t i, n; std::string s; setRowCount(model = (WStandardItemModel*) table->model(), n = sessions.size()); for ( i = 0; i < n; ++i ) { const MsmSession & session = sessions[i]; cw[SESSION_COLUMN_NAME] = std::max(cw[SESSION_COLUMN_NAME],(s=session.getName()).size()); model->setData(i, SESSION_COLUMN_NAME, s); cw[SESSION_COLUMN_ADDRESS] = std::max(cw[SESSION_COLUMN_ADDRESS], (s = session.getAddress()).size()); model->setData(i, SESSION_COLUMN_ADDRESS, s); cw[SESSION_COLUMN_AGENT] = std::max(cw[SESSION_COLUMN_AGENT], (s = session.getAgent()).size()); model->setData(i, SESSION_COLUMN_AGENT, s); } for ( i = 0; i < count_of(session_columns); ++i ) { setColumnWidth(table, i, std::max(cw[i], strlen(session_columns[i].name) + 4)); } } } }; StreamListView::StreamListView(WContainerWidget * parent) : Base(parent) { tab = new WTabWidget(this); tab->setStyleClass("tabwidget"); tab->addTab(inputs = new InputsTab(), "Inputs"); tab->addTab(outputs = new OutputsTab(), "Outputs"); tab->addTab(sinks = new SinksTab(), "Sinks"); tab->addTab(sessions = new SessionsTab(), "Sessions"); } void StreamListView::refreshStreams() { StreamsTab * currentPage; switch (tab->currentIndex()) { case 0: currentPage = (StreamsTab * ) inputs; break; case 1: currentPage = (StreamsTab * ) outputs; break; case 2: currentPage = (StreamsTab * ) sinks; break; case 3: currentPage = (StreamsTab * ) sessions; break; default: currentPage = 0; break; } if ( currentPage != 0 ) { currentPage->populateTable(); } }
JavaScript
UTF-8
2,692
2.8125
3
[ "MIT" ]
permissive
/** * A specialized form used to select from a checklist of attributes, traits, or properties * @extends {DocumentSheet} */ export default class TraitSelector extends DocumentSheet { /** @inheritdoc */ static get defaultOptions() { return foundry.utils.mergeObject(super.defaultOptions, { id: "trait-selector", classes: ["dnd5e", "trait-selector", "subconfig"], title: "Actor Trait Selection", template: "systems/dnd5e/templates/apps/trait-selector.html", width: 320, height: "auto", choices: {}, allowCustom: true, minimum: 0, maximum: null, valueKey: "value", customKey: "custom" }); } /* -------------------------------------------- */ /** @inheritdoc */ get title() { return this.options.title || super.title; } /* -------------------------------------------- */ /** * Return a reference to the target attribute * @type {string} */ get attribute() { return this.options.name; } /* -------------------------------------------- */ /** @override */ getData() { const attr = foundry.utils.getProperty(this.object.data, this.attribute); const o = this.options; const value = (o.valueKey) ? foundry.utils.getProperty(attr, o.valueKey) ?? [] : attr; const custom = (o.customKey) ? foundry.utils.getProperty(attr, o.customKey) ?? "" : ""; // Populate choices const choices = Object.entries(o.choices).reduce((obj, e) => { let [k, v] = e; obj[k] = { label: v, chosen: attr ? value.includes(k) : false }; return obj; }, {}) // Return data return { allowCustom: o.allowCustom, choices: choices, custom: custom } } /* -------------------------------------------- */ /** @override */ async _updateObject(event, formData) { const o = this.options; // Obtain choices const chosen = []; for ( let [k, v] of Object.entries(formData) ) { if ( (k !== "custom") && v ) chosen.push(k); } // Object including custom data const updateData = {}; if ( o.valueKey ) updateData[`${this.attribute}.${o.valueKey}`] = chosen; else updateData[this.attribute] = chosen; if ( o.allowCustom ) updateData[`${this.attribute}.${o.customKey}`] = formData.custom; // Validate the number chosen if ( o.minimum && (chosen.length < o.minimum) ) { return ui.notifications.error(`You must choose at least ${o.minimum} options`); } if ( o.maximum && (chosen.length > o.maximum) ) { return ui.notifications.error(`You may choose no more than ${o.maximum} options`); } // Update the object this.object.update(updateData); } }
Java
UTF-8
759
1.554688
2
[]
no_license
package com.yonyou.aco.docquery.service; import com.yonyou.aco.docquery.entity.SearchBean; import com.yonyou.cap.common.util.PageResult; public interface IDocqueryService { public PageResult<SearchBean> getAllBasicinfo(int pageNum,int pageSize,String[] params,String title,String sortName,String sortOrder); PageResult<SearchBean> getAllBasicinfo_fw(int pageNum, int pageSize,String[] params,String title,String sortName,String sortOrder); public boolean updateSignTime(String bizId,String date); public String getExcel_fw(String[] params,String inputWordfw,String gwbt_fw,String bwzt_fw,String regUser, String jjcd_fw,String sfgd_fw); public String getExcel(String[] params,String InputWordsw,String gwbt,String regUser,String sfgd,String bwzt); }
Java
UTF-8
471
1.84375
2
[ "MIT" ]
permissive
package com.example.easyhelp.Construction.Activity; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import com.example.easyhelp.R; public class ConstructionActivity extends AppCompatActivity { /* * This is for construction when server goes down */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_construction); } }
Python
UTF-8
143
3.53125
4
[]
no_license
num = input("请输入数字") if int(num) < 10: print(num) if 10 <= int(num) < 50: print(int(num) + 1) else: print(int(num) + 10)
C++
UTF-8
469
2.84375
3
[]
no_license
#include<iostream> using namespace std; int main() { bool ch = true; char x[30],y[30]; char *p1, *p2; cin >> x; cin >> y; p1 = x; p2 = y; while (*p1 != '\0' && *p2 != '\0') { if (*p1 == *(p1 + 1)) { p1++; } if (*p2 == *(p2 + 1)) { p2++; } if (*p1 != *(p1 + 1) && *p2 != *(p2 + 1)) { if (*p1 != *p2) { ch = false; break; } p1++; p2++; } } if (ch) cout << "Uniq"; else cout << "Not Uniq"; system("pause"); }
Markdown
UTF-8
3,482
2.546875
3
[]
no_license
--- title: mysql的json字段查询 date: 2020-06-12 20:49:49 tags: mysql --- ## mysql对JSON数据进行查询 这篇文章主要介绍了mysql查询字段类型为json时的查询方式. <!-- more --> ### 创建表 ```sql -- ---------------------------- -- Table structure for user_json -- ---------------------------- DROP TABLE IF EXISTS `user_json`; CREATE TABLE `user_json` ( `uid` int(11) NOT NULL AUTO_INCREMENT, `data_json` json, PRIMARY KEY (`uid`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 4 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic; -- ---------------------------- -- Records of user_json -- ---------------------------- INSERT INTO `user_json` VALUES (1, '{\"mail\": \"jiangchengyao@gmail.com\", \"name\": \"David\", \"address\": \"Shangahai\"}'); INSERT INTO `user_json` VALUES (2, '{\"mail\": \"amy@gmail.com\", \"name\": \"Amy\"}'); INSERT INTO `user_json` VALUES (3, '{\"input_1591829818808\": \"\", \"select_1591829823429\": \"累计参数\", \"switch_1591829820974\": false, \"checkbox_1591829830409\": [\"社会\"]}'); INSERT INTO `work-flow`.`user_json`(`uid`, `data_json`) VALUES (5, '{\"meter\": {\"item_id\": \"1002\", \"item_name\": \"水厂组态\"}, \"input_1591829818808\": \"\", \"select_1591829823429\": \"累计参数\", \"switch_1591829820974\": false, \"checkbox_1591829830409\": [\"社会\"]}'); SET FOREIGN_KEY_CHECKS = 1; ``` ### 非法插入数据 ```sql -- 非法数据,插入的数据做JSON格式检查,会报错, 3140 - Invalid JSON text: "Invalid value." at position 1 in value for column 'user_json.data_json'. insert into user_json values (NULL,"test"); ``` ### mysql对json字段查询 ```sql -- MySQL 5.7提供了一系列函数来高效地处理JSON字符,而不是需要遍历所有字符来查找 -- https://www.cnblogs.com/zoucaitou/p/4424575.html -- https://blog.csdn.net/Code_shadow/article/details/100055002 SELECT json_extract ( data_json, '$.name' ), json_extract ( data_json, '$.address' ) , json_extract ( data_json, '$.checkbox_1591829830409' ) FROM user_json; -- 根据json数组查询,用 JSON_CONTAINS(字段, JSON_OBJECT('json属性', "内容")) SELECT uid, JSON_CONTAINS ( data_json, JSON_OBJECT('select_1591829823429',"累计参数") ) FROM user_json; SELECT uid, JSON_CONTAINS ( data_json, JSON_OBJECT('select_1591829823429',"累计参数") ) FROM user_json; SELECT uid FROM user_json where JSON_CONTAINS( data_json -> '$[*]','["累计参数"]') -- 使用 字段->’$.json属性’进行查询条件 select * from user_json where data_json->'$.select_1591829823429' = '累计参数'; -- 用JSON_CONTAINS(字段,JSON_OBJECT(‘json属性’, “内容”)) select * from user_json where JSON_CONTAINS(data_json,JSON_OBJECT('select_1591829823429','累计参数')) -- 需要对其中的f开头的Json key值所对的value进行模糊查询,方法如下: select * from user_json where data_json->'$.select_1591829823429' LIKE '%累计%'; -- 找多层的json数据,条件查询,方法一 SELECT * FROM user_json WHERE json_extract(json_extract(data_json,"$.meter"),"$.item_name") = '水厂组态'; -- 找多层的json数据,条件查询,方法二 SELECT uid, json_extract( t.data_json, '$.meter.item_name' ) FROM user_json t WHERE json_extract( t.data_json, '$.meter.item_name' ) = '水厂组态'; -- 多层 SELECT * ,JSON_EXTRACT (`data_json`, '$.select_1591829823429') ,JSON_EXTRACT (`data_json`, '$**.item_name') FROM `user_json` ```
Python
UTF-8
1,313
3.0625
3
[]
no_license
""" Made by Sikanaama """ import sopel.module import math import urllib from bs4 import BeautifulSoup as BS URL = 'https://www.etaisyys.com/etaisyys/%s/%s/' @sopel.module.rule(r'^.matka (\w+) (\w+)(?: (\d+))?') @sopel.module.example('!matka Helsinki Riihimäki 100') def module(bot, trigger): start = trigger.group(1) end = trigger.group(2) speed = float(trigger.group(3) or 80) if not start or not end: bot.reply('Tarvitaan lähtö- ja saapumispaikat') try: response = urllib.request.urlopen(URL % (start, end)) dom = BS(response.read(), 'html.parser') map = int(dom.find(id='totaldistancekm').get('value'), 10) road = int(dom.find(id='distance').get('value'), 10) if map == 0 or road == 0: bot.reply('Eipä löytyny') return time = road / speed hours = math.floor(time) minutes = math.floor((time - hours) * 60) bot.reply('Välimatka %s - %s: %d km linnuntietä, %d km tietä pitkin (%d h %d min nopeudella %d km/h)' % ( start, end, map, road, hours, minutes, speed, )) except Exception as e: bot.reply('En nyt saanut vastausta' % (e)) raise e
Java
UTF-8
3,554
1.898438
2
[]
no_license
package com.novsu.antonivanov.exampleproject.TestNotification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.res.AssetFileDescriptor; import android.content.res.AssetManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.RingtoneManager; import android.net.Uri; import android.support.v4.app.NotificationCompat; import android.support.v4.app.NotificationManagerCompat; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.novsu.antonivanov.exampleproject.MainActivity; import com.novsu.antonivanov.exampleproject.R; import java.io.IOException; public class NotificationActivity extends AppCompatActivity { private static final String fileName = "tlumru_sound"; private TextView tv; private int k = 1; private AssetManager mAssetManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notification); tv = (TextView) findViewById(R.id.textView); Button btn = (Button) findViewById(R.id.button); if (btn != null) btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onClickButton(); } }); mAssetManager = getAssets(); } private void onClickButton() { Context context = getApplicationContext(); Intent notificationIntent = new Intent(context, MainActivity.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher); /*AssetFileDescriptor afd; try { afd = mAssetManager.openFd(fileName); } catch (IOException e) { e.printStackTrace(); Toast.makeText(getApplicationContext(), "Не могу загрузить файл ", Toast.LENGTH_SHORT).show(); }*/ Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); Uri path = Uri.parse("android.resource://com.novsu.antonivanov.exampleproject/raw/" + fileName); //PendingIntent pendingIntent = stackBuilder.getPendingIntent(Constants.PUSH_NOTIFICATION_REQUEST + push.getId(), PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.mipmap.ic_tlum_statusbar) .setLargeIcon(largeIcon) .setContentTitle(getString(R.string.app_name)) .setTicker("Ticker notification !!!!") .setContentText("ContentText notification !!!!") .setAutoCancel(true) .setSound(path) .setDefaults(NotificationCompat.DEFAULT_LIGHTS | NotificationCompat.DEFAULT_VIBRATE) .setContentIntent(contentIntent) .setStyle(null); NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this); notificationManager.notify(k, notificationBuilder.build()); tv.setText(String.valueOf(k)); k++; } }
Python
UTF-8
853
3.125
3
[]
no_license
#!/usr/bin/env python # encoding: utf-8 """ Given: A collection of n (n≤10) GenBank entry IDs. Return: The shortest of the strings associated with the IDs in FASTA format. """ from sys import argv from Bio import Entrez from Bio import SeqIO __author__ = "Ethan Hart" def get_nuc_fasta(nucleotide_ids): """nucleotide_ids should be string of nucleotide ids separated by a comma """ Entrez.email = "email@email.com" handle = Entrez.efetch(db="nucleotide", id=[nucleotide_ids], rettype="fasta") records = list(SeqIO.parse(handle, "fasta")) shortest = min(records, key=lambda x: len(x.seq)) print shortest.format('fasta') def main(): with open(argv[1], 'r') as inf: data = inf.read() nucleotide_ids = ', '.join(data.strip().split()) get_nuc_fasta(nucleotide_ids) if __name__ == "__main__": main()
JavaScript
UTF-8
3,566
2.609375
3
[ "MIT" ]
permissive
function contactSendEmail() { let product = $("#contact_product option:selected").text() let jobDescription = $("#contact_description").val(); let postcode = $("#contact_postcode").val(); let businessName = $("#contact_businessName").val(); let name = $("#contact_name").val(); let email = $("#contact_email").val(); let telephone = $("#contact_tel").val(); let mode = $("#contact_mode option:selected").text() let subscribe = $("#contact_subscribe").prop("checked"); // upload file let types = "file"; let formData = new FormData(); let file = $("#contact_file1").val(); if (file == '') { } else { // type check let type = $("#contact_file1")[0].files[0].type; let typeChange = 0; for ( let i = 0 ; i < fileType.length ; ++i ) { // 判断一下格式对不对 if ( type.indexOf(fileType[i]) != -1 ) { typeChange = 1; } else { } }; if ( typeChange != 1) { alert("Files in this format are not supported"); return false; } // name check let fileName = $("#contact_file1")[0].files[0].name; let nameCheck = 0; for ( let i = 0 ; i < fileSuffix.length ; ++i ) { if ( fileName.indexOf(fileSuffix[i]) != -1 ) { nameCheck = 1; } else { } }; if ( nameCheck != 1) { alert("Files in this format are not supported"); return false; } let size = $("#contact_file1")[0].files[0].size; if (size > 52428800) { alert("The uploaded file cannot exceed 50MB"); return false; } else { formData.append(types,$("#contact_file1")[0].files[0]); contactFileUp(formData); } } //get date let date = new Date(); let seperator1 = "-"; let year = date.getFullYear(); let month = date.getMonth() + 1; let strDate = date.getDate(); if (month >= 1 && month <= 9) { month = "0" + month; } if (strDate >= 0 && strDate <= 9) { strDate = "0" + strDate; } let currentdate = year + seperator1 + month + seperator1 + strDate; $.ajax({ headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, type: "POST", url: "api/contactUs", // processData: false, // contentType: false, dataType:'json', data:{ product:product, jobDescription:jobDescription, postcode:postcode, businessName:businessName, name:name, email:email, telephone:telephone, mode:mode, subscribe:subscribe, // formData, data:currentdate }, success:function () { alert("send email success"); }, error:function () { alert("error"); } }); } function contactFileUp(formData) { $.ajax({ headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, type: "POST", url: "api/uploadFile", processData: false, contentType: false, dataType:'json', data:formData, success:function () { alert("upload file success"); }, error:function () { alert("upload file error"); } }); }
JavaScript
UTF-8
4,102
2.875
3
[]
no_license
$(function() { // 字符验证 jQuery.validator.addMethod("stringCheck", function(value, element) { return this.optional(element) || /^[\u0391-\uFFE5\w]+$/.test(value); }, "只能包括中文字、英文字母、数字和下划线"); // 中文字两个字节 jQuery.validator.addMethod("byteRangeLength", function(value, element, param) { var length = value.length; for (var i = 0; i < value.length; i++) { if (value.charCodeAt(i) > 127) { length++; } } return this.optional(element) || (length >= param[0] && length <= param[1]); }, "请确保输入的值在3-15个字节之间(一个中文字算2个字节)"); // 身份证号码验证 jQuery.validator.addMethod("isIdCardNo", function(value, element) { return this.optional(element) || idCardNoUtil.checkIdCardNo(value); }, "请正确输入您的身份证号码"); // 护照编号验证 jQuery.validator.addMethod("passport", function(value, element) { return this.optional(element) || checknumber(value); }, "请正确输入您的护照编号"); // 手机号码验证 jQuery.validator.addMethod("isMobile", function(value, element) { var length = value.length; var mobile = /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(17[0-9]{1})|(18[0-9]{1}))+\d{8})$/; return this.optional(element) || (length == 11 && mobile.test(value)); }, "请正确填写您的手机号码"); // 电话号码验证 jQuery.validator.addMethod("isTel", function(value, element) { var tel = /^\d{3,4}-?\d{7,9}$/; // 电话号码格式010-12345678 return this.optional(element) || (tel.test(value)); }, "请正确填写您的电话号码"); // 联系电话(手机/电话皆可)验证 jQuery.validator.addMethod("isPhone", function(value, element) { var length = value.length; var mobile = /^(((13[0-9]{1})|(15[0-9]{1}))+\d{8})$/; var tel = /^\d{3,4}-?\d{7,9}$/; return this.optional(element) || (tel.test(value) || mobile.test(value)); }, "请正确填写您的联系电话"); // 邮政编码验证 jQuery.validator.addMethod("isZipCode", function(value, element) { var tel = /^[0-9]{6}$/; return this.optional(element) || (tel.test(value)); }, "请正确填写您的邮政编码"); // 开始验证 $('#commentForm').validate({ rules : { "userInfo.username" : { required : true, stringCheck : true, byteRangeLength : [ 3, 15 ] }, "userInfo.name" : { required : true, stringCheck : true, byteRangeLength : [ 3, 15 ] }, "userInfoDetail.email" : { email : true }, "userInfoDetail.mobilePhone" : { isMobile : true }, newpassword: { minlength: 5 }, checkpassword: { minlength: 5, equalTo: "#newpassword" }, "userInfoDetail.qq": { digits:true } }, messages : { "userInfo.username" : { required : "请填写用户名", stringCheck : "用户名只能包括中文字、英文字母、数字和下划线", byteRangeLength : "用户名必须在3-15个字符之间" }, "userInfo.name" : { required : "请填写用户名", stringCheck : "用户名只能包括中文字、英文字母、数字和下划线", byteRangeLength : "用户名必须在3-15个字符之间" }, "userInfoDetail.email" : { required : "<font color=red>请输入一个Email地址</fond>", email : "请输入一个有效的Email地址" }, "userInfoDetail.mobilePhone" : { required : "请输入您的联系电话", isPhone : "请输入一个有效的联系电话" }, newpassword: { required: "请输入密码", minlength: "密码长度不能小于 5 个字母" }, checkpassword: { required: "请输入密码", minlength: "密码长度不能小于 5 个字母", equalTo: "两次密码输入不一致" } }, focusInvalid : false, onkeyup : false, errorPlacement : function(error, element) { error.appendTo(element.parent()); } // ,success: function(label) { // label.html("&nbsp;").addClass("checked"); // } }); })
Python
UTF-8
243
2.734375
3
[]
no_license
import re import requests requisicao = requests.get('http://carmodorioclaro.mg.gov.br/portal/?Link=Contato') padrao = re.findall(r'[\w\.-]+@[\w\.-]+', requisicao.text) if padrao: print(padrao) else: print("Padrão não encontrado")