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
Java
UTF-8
399
2.109375
2
[]
no_license
package org.natsna.pahu.AkkaStudy.ex06; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; public class AgentMain { public static void main(String[] args) { ActorSystem actorSystem = ActorSystem.create("TestSystem"); ActorRef agentActor = actorSystem.actorOf(Props.create(AgentActor.class),"agentActor"); agentActor.tell("Start", ActorRef.noSender()); } }
C++
UTF-8
3,017
2.578125
3
[]
no_license
#pragma once #include "BaseModel.h" #include <Matrix.h> #include "ModelLoader.h" struct ID3D11Texture2D; namespace Prism { class Sprite : public BaseModel { friend class Engine; friend class ModelLoader; public: void Render(const CU::Vector2<float>& aPosition, const CU::Vector2<float>& aScale = { 1.f, 1.f } , const CU::Vector4<float>& aColor = { 1.f, 1.f, 1.f, 1.f }, float aRotateValue = 0.f); void SetSize(const CU::Vector2<float>& aTextureSize, const CU::Vector2<float>& aHotSpot); const CU::Vector2<float>& GetSize() const; void SetUVZeroToOne(const CU::Vector2<float>& aTopLeft, const CU::Vector2<float>& aRightBottom); void ResizeTexture(ID3D11Texture2D* aSrcTexture); void Rotate(float aRadians); void CopyFromD3DTexture(ID3D11Texture2D* aTexture); const CU::Vector2<float>& GetHotspot() const; private: Sprite(const std::string& aFileName, const CU::Vector2<float>& aSpriteSize , const CU::Vector2<float>& aHotSpot = { 0.f, 0.f }); Sprite(ID3D11Texture2D* aTexture, const CU::Vector2<float>& aSpriteSize , const CU::Vector2<float>& aHotSpot = { 0.f, 0.f }); void CreateVertices(); ID3D11Texture2D* myTexture; ID3D11ShaderResourceView* myShaderView; CU::Matrix44<float> myOrientation; CU::Vector2<float> mySize; CU::Vector2<float> myHotspot; CU::Vector2<float> myNewSize; CU::Vector2<float> myNewHotSpot; CU::Vector2<float> myTopLeftUV; CU::Vector2<float> myRightBottomUV; }; } inline void Prism::Sprite::SetSize(const CU::Vector2<float>& aTextureSize, const CU::Vector2<float>& aHotSpot) { if (aTextureSize.x != mySize.x || aTextureSize.y != mySize.y || aHotSpot.x != myHotspot.x || aHotSpot.y != myHotspot.y) { bool shouldPause = !Prism::ModelLoader::GetInstance()->IsPaused(); if (shouldPause == true) { ModelLoader::GetInstance()->Pause(); } myHotspot = aHotSpot; mySize = aTextureSize; CreateVertices(); if (shouldPause == true) { ModelLoader::GetInstance()->UnPause(); } //Do the resizing on ModelLoader instead? so we dont have to pause } myNewSize = aTextureSize; myNewHotSpot = aHotSpot; //ModelLoader::GetInstance()->Pause(); //myHotspot = aHotSpot; //mySize = aTextureSize; //CreateVertices(); //ModelLoader::GetInstance()->UnPause(); ////Do the resizing on ModelLoader instead? so we dont have to pause } inline void Prism::Sprite::SetUVZeroToOne(const CU::Vector2<float>& aTopLeft, const CU::Vector2<float>& aRightBottom) { if (myTopLeftUV == aTopLeft && myRightBottomUV == aRightBottom) { return; } bool shouldPause = !Prism::ModelLoader::GetInstance()->IsPaused(); if (shouldPause == true) { ModelLoader::GetInstance()->Pause(); } myTopLeftUV = aTopLeft; myRightBottomUV = aRightBottom; CreateVertices(); if (shouldPause == true) { ModelLoader::GetInstance()->UnPause(); } } inline const CU::Vector2<float>& Prism::Sprite::GetSize() const { return mySize; } inline const CU::Vector2<float>& Prism::Sprite::GetHotspot() const { return myHotspot; }
Ruby
UTF-8
653
2.875
3
[]
no_license
# 當SketchUp遇見Ruby - 邁向程式化建模之路(碁峯出版) # http://books.gotop.com.tw/v_AEC009100 # ex_405.rb - 推擠切除部分立方體 mod = Sketchup.active_model ent = mod.entities depth = 10; width = 10 # 用分號區隔,可寫成一行 pts = [] pts[0] = [0, 0, 0] pts[1] = [width, 0, 0] pts[2] = [width, depth, 0] pts[3] = [0, depth, 0] # 建立矩形表面 test_face = ent.add_face pts test_face.reverse! # 變換方向 test_face.pushpull 10 # 拉成三維圖形 # 在矩形表面上建立一條直線 cut_line = ent.add_line [10, 8, 10], [8, 10, 10] cut_line.faces[1].pushpull -10 # 由上向下推擠移除一角邊
JavaScript
UTF-8
657
2.53125
3
[]
no_license
import React from 'react'; import SearchBox from './components/SearchBox'; import BookList from './components/BookList'; export default class App extends React.Component { constructor(props) { super(props); this.state = { books: [] } } handleSetState = (newBook) => { console.log('setting state', newBook); this.setState( { books: newBook }) } componentDidMount() { console.log('mounted'); } render(){ return ( <div className="App"> <h1>Google Books</h1> <SearchBox handleSetState={this.handleSetState}/> <BookList books={this.state.books}/> </div> ) } }
PHP
UTF-8
1,116
2.71875
3
[ "MIT" ]
permissive
<?php namespace Digitaliseringskataloget\SF1500\Organisation6\Organisationsystem; /** * Class representing AnonymiserInputType * * * XSD Type: AnonymiserInputType */ class AnonymiserInputType { /** * @var string $personUUID */ private $personUUID = null; /** * @var string $personCPR */ private $personCPR = null; /** * Gets as personUUID * * @return string */ public function getPersonUUID() { return $this->personUUID; } /** * Sets a new personUUID * * @param string $personUUID * @return self */ public function setPersonUUID($personUUID) { $this->personUUID = $personUUID; return $this; } /** * Gets as personCPR * * @return string */ public function getPersonCPR() { return $this->personCPR; } /** * Sets a new personCPR * * @param string $personCPR * @return self */ public function setPersonCPR($personCPR) { $this->personCPR = $personCPR; return $this; } }
Markdown
UTF-8
3,168
2.671875
3
[]
no_license
# SENZ007 Temperature and Humidity Sensor ###### Translation > For `English`, please click [`here.`](https://github.com/njustcjj/SENZ007-Temperature-and-Humidity-Sensor/blob/master/README.md) > For `Chinese`, please click [`here.`](https://github.com/njustcjj/SENZ007-Temperature-and-Humidity-Sensor/blob/master/README_CN.md) ![](https://github.com/njustcjj/SENZ007-Temperature-and-Humidity-Sensor/blob/master/pic/SENZ007.jpg "SENZ007") ### Introduction > SENZ007 features a calibrated digital signal output with the temperature and humidity sensor complex. Its technology ensures the high reliability and excellent long-term stability. A high-performance 8-bit microcontroller is connected. This sensor includes a resistive element and a sense of wet NTC temperature measuring devices. It has excellent quality, fast response, anti-interference ability and high cost performance advantages. >Each DHT11 sensors features extremely accurate calibration of humidity calibration chamber. The calibration coefficients stored in the OTP program memory, internal sensors detect signals in the process, we should call these calibration coefficients. The single-wire serial interface system is integrated to become quick and easy. Small size, low power, signal transmission distance up to 20 meters, making it a variety of applications and even the most demanding applications. The product is 4-pin single row pin package. Convenient connection, special packages can be provided according to users need. ### Specification * Supply Voltage: 3.3V ~ 5 V - Temperature range :0 - 50 °C, error of ± 2 °C - Humidity :20 - 90% RH, error of ± 5% RH - Interface: Digital ### Tutorial #### Pin Definition |Sensor Pin|Ardunio Pin|Function Description| |-|:-:|-| |VCC|3.3V~5V|Power| |GND|GND|| |DO|Digital pin|Digital Output| ![](https://github.com/njustcjj/SENZ007-Temperature-and-Humidity-Sensor/blob/master/pic/SENZ007_pin.jpg "Pin Definition") #### Connecting Diagram ![](https://github.com/njustcjj/SENZ007-Temperature-and-Humidity-Sensor/blob/master/pic/SENZ007_connect.png "Connecting Diagram") #### Sample Code #include <dht11.h> dht11 DHT; #define DHT11_PIN 4 void setup(){ Serial.begin(9600); Serial.println("DHT TEST PROGRAM "); Serial.print("LIBRARY VERSION: "); Serial.println(DHT11LIB_VERSION); Serial.println(); Serial.println("Type,\tstatus,\tHumidity (%),\tTemperature (C)"); } void loop(){ int chk; Serial.print("DHT11, \t"); chk = DHT.read(DHT11_PIN); // READ DATA switch (chk){ case DHTLIB_OK: Serial.print("OK,\t"); break; case DHTLIB_ERROR_CHECKSUM: Serial.print("Checksum error,\t"); break; case DHTLIB_ERROR_TIMEOUT: Serial.print("Time out error,\t"); break; default: Serial.print("Unknown error,\t"); break; } // DISPLAT DATA Serial.print(DHT.humidity,1); Serial.print(",\t"); Serial.println(DHT.temperature,1); delay(2000); } ### Purchasing [*SENZ007 Temperature and Humidity Sensor*](https://www.ebay.com/).
Python
UTF-8
4,080
4.03125
4
[]
no_license
# Authors: Willem Vidler # Date: December 14th, 2020 # Program Name: Temperature Conversion # Program Description: Program that converts celcius into fahrenheit and vice-versa from tkinter import * # Imports the tkinter module from tkinter.ttk import * # Replace the tk widget with the ttk ones # Constants CELCIUS = "Celcius" FAHRENHEIT = "Fahrenheit" CELCIUS_CONV = "Convert to Celcius" FAHRENHEIT_CONV = "Convert to Fahrenheit" def celciusToFahrenheit(celcius): """Converts Celcius to Fahrenheit""" fahrenheit = (celcius * 9/5) + 32 return fahrenheit def fahrenheitToCelcius(fahrenheit): """Coverts Fahrenheit to Celcius""" celcius = (fahrenheit - 32) * 5/9 return celcius def fahrenheitClick(): """ Called when the farhenheit radiobutton is clicked - Swap input/output labels """ inputLabel.configure(text=CELCIUS) outputLabel.configure(text=FAHRENHEIT) def celciusClick(): """ Called when the celcius radiobutton is clicked - Swap input/output labels """ inputLabel.configure(text=FAHRENHEIT) outputLabel.configure(text=CELCIUS) def convertButtonClick(): """ Called when the convert button is clicked - Converts temperature from celcius to fahrenheit and vice-versa - Displays an error message if input is invalid """ inputValue = inputText.get() # Get the input entry text # Validation try: inputValue = float(inputValue) isNumeric = True # Able to convert except: outputText.set("Error - Invalid Input!") # Write the error in the output entry isNumeric = False # Not able to convert # Valid Number if isNumeric: if conversionType.get() == CELCIUS: result = fahrenheitToCelcius(inputValue) else: result = celciusToFahrenheit(inputValue) outputText.set(round(result,1)) def clearButtonClick(): """ Called when the clear button is clicked" - Resets input/output text and radiobutton to fahrenheit """ conversionType.set(FAHRENHEIT) # Default selection inputText.set("0.0") # Set default Value outputText.set("0.0") # Set default Value fahrenheitClick() # Reset the labels def keyHandler(event:Event): if event.keysym == "Return": convertButtonClick() elif event.keysym == "Escape": clearButtonClick() # Window Properties tk = Tk() # Create a Tk object tk.title("Temperature Conversion - Willem Vidler and Jesse Talon") tk.resizable(width=False, height=False) tk.bind("<Key>", keyHandler) # 2 frames holding the widgets leftFrame = Frame() rightFrame = Frame() # Labels inputLabel = Label(leftFrame, text=CELCIUS) outputLabel = Label(rightFrame, text=FAHRENHEIT) # Entries inputText = StringVar() inputText.set("0.0") # Set the default inputEntry = Entry(leftFrame, width=30, textvariable=inputText) outputText = StringVar() outputText.set("0.0") # Set the default outputEntry = Entry(rightFrame, width=30, state="readonly", cursor="no", textvariable=outputText) # Radio buttons conversionType = StringVar() conversionType.set(FAHRENHEIT) # Default selection fahrenheitRadioButton = Radiobutton(leftFrame, text=FAHRENHEIT_CONV, variable=conversionType, value=FAHRENHEIT, command=fahrenheitClick) celciusRadioButton = Radiobutton(rightFrame, text=CELCIUS_CONV, variable=conversionType, value=CELCIUS, command=celciusClick) # Buttons clearButton = Button(leftFrame, text="Clear", command=clearButtonClick) convertButton = Button(rightFrame, text="Convert", command=convertButtonClick) # Position the widgets #left frame leftFrame.pack(side="left", padx=(10,5), pady=10) inputLabel.pack(anchor="w") inputEntry.pack() fahrenheitRadioButton.pack(anchor="w") clearButton.pack(fill="x") # Right frame rightFrame.pack(side="right", padx=(5,10), pady=10) outputLabel.pack(anchor="w") outputEntry.pack() celciusRadioButton.pack(anchor="w") convertButton.pack(fill="x") # Make the GUI visible tk.mainloop()
PHP
UTF-8
1,377
2.59375
3
[]
no_license
<?php class ToolsHelper { public static function getRandomString($length) { $characters = "0123456789abcdefghijklmnopqrstuvwxyz"; $string=""; for ($p = 0; $p < $length; $p++) { $string .= $characters[mt_rand(0, (strlen($characters))-1)]; } return $string; } public static function validateNotEmpty($value){ $validator = new Zend_Validate_NotEmpty(); $valid = $validator->isValid($value); return $valid; } } /*public static function sendMail($user) { // $subject="Alerta Spammer Spoora"; //Contenido del mensaje $message="From: ".$this->view->mail."\n"; $message.="User Name: ".$this->view->name."\n"; $message.="User Country: ".$this->view->country."\n"; $message.=$this->view->message; //envio del mail //mailTo $headers = "MIME-Version: 1.0\n"; $headers .= "Content-type: text/plain; charset=utf-8\n"; $headers .= "From: ".$this->view->name."<".$this->view->mail.">\n"; if (mail("contact@n2manager.com", $subject, $message, $headers)) { $this->view->mailSend=TRUE; }else{ $this->view->mailSend=FALSE; } }*/ ?>
C++
UTF-8
197
2.609375
3
[]
no_license
#ifndef _compare_h #define _compare_h template <typename T> int compare(const T &v1, const T &v2) { if(std::less<T>()(v1,v2)) return -1; if(std::less<T>()(v2,v1)) return 1; return 0; } #endif
C
UTF-8
488
3.234375
3
[]
no_license
#include <stdio.h> void printArray(int *,int); int main() { int A[10],i,n; printf("\nEnter n"); scanf("%d",&n); printf("Enter %d numbers",n); for(i=0;i<n;i++) scanf("%d",&A[i]); printf("\n"); printArray(A,n); printf("\n");//Address printArray(A,n); printf("\n"); printArray(A,n); return 1; } void printArray(int *ptr,int n) { int i; for ( i = 0; i < n; ++i) { printf("%5d",*(ptr+i)); } }
Java
UTF-8
1,522
2.234375
2
[]
no_license
package com.stars.modules.email.packet; import com.stars.core.player.Player; import com.stars.core.player.PlayerPacket; import com.stars.modules.MConst; import com.stars.modules.email.EmailModule; import com.stars.modules.email.EmailPacketSet; import com.stars.network.server.buffer.NewByteBuffer; /** * Created by zhaowenshuo on 2016/8/2. */ public class ServerEmail extends PlayerPacket { public static final byte S_GET_LIST = 1; // 获取邮件列表 public static final byte S_READ = 2; // 阅读邮件 public static final byte S_DELETE = 3; // 删除邮件 public static final byte S_FETCH_AFFIXS = 4; // 提取附件 public static final byte S_ALL_DELETE = 5; // 全部删除 public static final byte S_ALL_FETCH = 6; // 全部提取 private byte subtype; private int emailId; @Override public void execPacket(Player player) { EmailModule emailModule = (EmailModule) module(MConst.Email); emailModule.handleRequest(this); } @Override public short getType() { return EmailPacketSet.S_EMAIL; } @Override public void readFromBuffer(NewByteBuffer buff) { this.subtype = buff.readByte(); switch (this.subtype) { case S_READ: case S_DELETE: case S_FETCH_AFFIXS: this.emailId = buff.readInt(); break; } } public byte getSubtype() { return subtype; } public int getEmailId() { return emailId; } }
C#
UTF-8
1,256
2.703125
3
[]
no_license
using UnityEngine; using System.Collections; public class PlayerControl : MonoBehaviour { //Craeting variables for player. public static int _playerHP; float _playerSpeed = 1f; public float _bounds; float _playerX; float _playerY; //Setting up player hp and position. void Start() { _playerHP = 3; _playerX = this.transform.position.x; _playerY = this.transform.position.y; } //Player follows mouse, but only in x dimension. void Update () { Vector2 _mousePos = Camera.main.ScreenToWorldPoint(new Vector2(Input.mousePosition.x, Input.mousePosition.y)); this.transform.position = new Vector2(_mousePos.x, _playerY); //Check to prevent player going out of game bounds. if (this.transform.position.x < -_bounds) { transform.position = new Vector2(-_bounds, _playerY); } if (this.transform.position.x > _bounds) { transform.position = new Vector2(_bounds, _playerY); } } public void PlayerHPcount() { _playerHP--; } //displaying player hp. void OnGUI() { GUI.Label(new Rect(10, 10, 100, 50), "Lives: " + _playerHP); } }
Java
UTF-8
1,546
2.53125
3
[]
no_license
package app.habbo.xyz.Habbo; import java.util.HashMap; import app.habbo.xyz.Environment; public class Habbo { private int Id; private String Username; private String Look; private String Motto; private boolean isOnline = false; int relationship = 1; private String lastOnline ="01.01.1970"; public Habbo(int id, String username, String look, String motto) { this.Id = id; this.Username = username; this.Look = look; this.Motto = motto; } public void setId(int id) { this.Id = id; } public int getId() { return this.Id; } public void setUsername(String username) { this.Username = username; } public String getUsername() { return this.Username; } public void setLook(String look) { this.Look = look; } public String getLook() { return this.Look; } public void setMotto(String m) { this.Motto = m; } public String getMotto() { return this.Motto; } public void setIsOnline(boolean isonline){ this.isOnline = isonline; } public boolean getIsOnline(){ return this.isOnline; } public void setRelationship(int i) { this.relationship = i; } public int getRelationship() { return this.relationship; } public void setLastOnline(String s){ this.lastOnline = s; } public String getLastOnline(){ return this.lastOnline; } }
Python
UTF-8
846
3.828125
4
[]
no_license
# Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome. # # Example 1: # # Input: "aba" # Output: True # Example 2: # # Input: "abca" # Output: True # Explanation: You could delete the character 'c'. class Solution: def validPalindrome(self, s): left = 0 right = len(s) - 1 while left <= right: if s[left] != s[right]: try1 = self.isValid(s, left + 1, right) try2 = self.isValid(s, left, right - 1) return try1 or try2 left += 1 right -= 1 return True def isValid(self, word, left, right): while left <= right: if word[left] != word[right]: return False left += 1 right -= 1 return True
Java
UTF-8
2,680
2.015625
2
[ "MIT" ]
permissive
package com.rideaustin.rest; import javax.annotation.security.RolesAllowed; import javax.inject.Inject; import org.apache.http.HttpStatus; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.PatchMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.rideaustin.CheckedTransactional; import com.rideaustin.WebClientEndpoint; import com.rideaustin.model.enums.AvatarType; import com.rideaustin.rest.exception.BadRequestException; import com.rideaustin.rest.model.RatingUpdateDto; import com.rideaustin.service.rating.RatingUpdateService; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import lombok.RequiredArgsConstructor; @RestController @CheckedTransactional @RolesAllowed(AvatarType.ROLE_ADMIN) @RequestMapping("/rest/ratingupdates") @RequiredArgsConstructor(onConstructor = @__(@Inject)) public class RatingUpdatesAdministration { private final RatingUpdateService ratingUpdateService; @PatchMapping("/{id}/recalculate") @ApiOperation("Recalculate rating for an user") @ApiResponses({ @ApiResponse(code = HttpStatus.SC_OK, message = "OK") }) public void updateAll( @ApiParam(value = "Avatar ID", example = "1") @PathVariable long id, @ApiParam(value = "Avatar type", allowableValues = "RIDER,DRIVER", required = true) @RequestParam AvatarType type ) { this.ratingUpdateService.recalculate(id, type); } @WebClientEndpoint @DeleteMapping(value = "/{id}") @RolesAllowed(AvatarType.ROLE_ADMIN) @ApiOperation("Remove rating update") @ApiResponses({ @ApiResponse(code = HttpStatus.SC_OK, message = "OK") }) public void deleteRating(@ApiParam(value = "Rating update ID", example = "1") @PathVariable long id) { ratingUpdateService.deleteRating(id); } @WebClientEndpoint @PostMapping(value = "/{id}") @RolesAllowed(AvatarType.ROLE_ADMIN) @ApiOperation("Update rating update") @ApiResponses({ @ApiResponse(code = HttpStatus.SC_OK, message = "OK") }) public RatingUpdateDto updateRating( @ApiParam(value = "Rating update ID", example = "1") @PathVariable long id, @ApiParam(value = "New rating value", example = "5.0") @RequestParam double value ) throws BadRequestException { return ratingUpdateService.updateRating(id, value); } }
Java
UTF-8
6,661
2.0625
2
[]
no_license
package com.matteoveroni.views.translations; import com.matteoveroni.bus.events.EventChangeView; import com.matteoveroni.bus.events.EventGoToPreviousView; import com.matteoveroni.bus.events.EventViewChanged; import com.matteoveroni.views.ViewName; import com.matteoveroni.views.dictionary.events.EventShowTranslationsActionPanel; import com.matteoveroni.views.dictionary.listviews.cells.TranslationCell; import com.matteoveroni.views.dictionary.listviews.listeners.FocusChangeListenerTranslations; import com.matteoveroni.views.dictionary.listviews.listeners.SelectionChangeListenerTranslations; import com.matteoveroni.views.dictionary.model.pojo.Translation; import com.matteoveroni.views.translations.events.EventNewTranslationsToShow; import com.sun.media.jfxmediaimpl.MediaDisposer.Disposable; import de.jensd.fx.glyphs.fontawesome.FontAwesomeIcon; import de.jensd.fx.glyphs.fontawesome.utils.FontAwesomeIconFactory; import java.net.URL; import java.util.List; import java.util.ResourceBundle; import javafx.beans.value.ChangeListener; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ListCell; import javafx.scene.control.ListView; import javafx.scene.layout.BorderPane; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * FXML Translations Presenter (Controller class) * * @author Matteo Veroni */ public class TranslationsPresenter implements Initializable, Disposable { @FXML private Button btn_search; @FXML private Button btn_add; @FXML private ListView<Translation> listview_translations = new ListView<>(); @FXML private BorderPane actionPaneTranslations; private SelectionChangeListenerTranslations selectionChangeListenerTranslations; private FocusChangeListenerTranslations focusChangeListenerTranslations; private final Button btn_left = new Button(); private final Button btn_right = new Button(); private static final Logger LOG = LoggerFactory.getLogger(TranslationsPresenter.class); @Override public void initialize(URL location, ResourceBundle resources) { resetView(); initializeViewComponentsAndBehaviours(); } @Subscribe public void onViewChanged(EventViewChanged eventViewChanged) { } @Subscribe public void onEventNewTranslationsToShow(EventNewTranslationsToShow event) { List<Translation> newTranslationsToShow = event.getTranslations(); if (newTranslationsToShow != null) { resetView(); ObservableList<Translation> observableTranslationsList = FXCollections.observableList(event.getTranslations()); listview_translations.setItems(observableTranslationsList); } } @Subscribe public void onEventShowTranslationsActionPanelChange(EventShowTranslationsActionPanel eventShowTranslationsActionPanel) { showActionPanelButtons(eventShowTranslationsActionPanel.getShowValue()); } @Override public void dispose() { disposeAllListenersFromListView(); } @FXML void goBack(ActionEvent event) { EventBus.getDefault().post(new EventGoToPreviousView()); } @FXML void goToMain(ActionEvent event) { EventBus.getDefault().post(new EventChangeView(ViewName.MAINMENU)); } private void resetView() { showActionPanelButtons(false); listview_translations.getSelectionModel().select(null); listview_translations.setItems(null); } private void initializeViewComponentsAndBehaviours() { initializeViewButtons(); setCellFactoryForTranslationsListView(); defineListViewTranslationsBehaviours(); } private void initializeViewButtons() { btn_search.setGraphic(FontAwesomeIconFactory.get().createIcon(FontAwesomeIcon.SEARCH)); btn_add.setGraphic(FontAwesomeIconFactory.get().createIcon(FontAwesomeIcon.PLUS)); btn_left.setGraphic(FontAwesomeIconFactory.get().createIcon(FontAwesomeIcon.EDIT)); btn_left.setPrefWidth(50); btn_left.setOnAction((event) -> { Translation selectedTranslation = listview_translations.getSelectionModel().getSelectedItem(); if (selectedTranslation != null) { EventBus.getDefault().post(new EventChangeView(ViewName.EDIT, selectedTranslation)); } }); btn_right.setGraphic(FontAwesomeIconFactory.get().createIcon(FontAwesomeIcon.TRASH)); btn_right.setPrefWidth(50); btn_right.setOnAction((event) -> { Translation selectedTranslation = listview_translations.getSelectionModel().getSelectedItem(); if (selectedTranslation != null) { removeTranslation(); } }); } private void setCellFactoryForTranslationsListView() { listview_translations.setCellFactory((ListView<Translation> t) -> { ListCell<Translation> translationsListViewCell = new TranslationCell(); return translationsListViewCell; }); } private void defineListViewTranslationsBehaviours() { setSelectionChangeListenerForTranslationsListView(); // setFocusChangeListenerForTranslationsListView(); // if (listview_translations.getItems() != null) { // Collections.sort(listview_translations.getItems(), (Translation t1, Translation t2) -> t1.toString().compareTo(t2.toString())); // } } private void setSelectionChangeListenerForTranslationsListView() { disposeChangeListenerFromListView(selectionChangeListenerTranslations); selectionChangeListenerTranslations = new SelectionChangeListenerTranslations(); listview_translations.getSelectionModel().selectedItemProperty().addListener(selectionChangeListenerTranslations); } private void setFocusChangeListenerForTranslationsListView() { disposeChangeListenerFromListView(focusChangeListenerTranslations); focusChangeListenerTranslations = new FocusChangeListenerTranslations(listview_translations); listview_translations.focusedProperty().addListener(focusChangeListenerTranslations); } private void showActionPanelButtons(boolean isShown) { if (isShown) { actionPaneTranslations.setLeft(btn_left); actionPaneTranslations.setRight(btn_right); } else { actionPaneTranslations.setLeft(null); actionPaneTranslations.setRight(null); } } private void removeTranslation() { } private void disposeAllListenersFromListView() { disposeChangeListenerFromListView(selectionChangeListenerTranslations); disposeChangeListenerFromListView(focusChangeListenerTranslations); } private void disposeChangeListenerFromListView(ChangeListener listener) { if (listener != null) { try { listview_translations.getSelectionModel().selectedItemProperty().removeListener(listener); } catch (Exception ex) { LOG.error(ex.getMessage()); } } } }
JavaScript
UTF-8
8,955
3
3
[]
no_license
// SUSPECTS OBJECTS const mrGreen = { firstName: 'Jacob', lastName: 'Green', color: '#16a83d', description: 'He has a lot of connections', age: 45, image: 'assets/green.png', occupation: 'Entrepreneur', favoriteWeapon: 'knife' } const prPlum = { firstName: 'Peter', lastName: 'Plum', color: '#ff40ef', description: 'He is highly intelligent', age: 36, image: 'assets/plum.png', occupation: 'Professor', favoriteWeapon: 'bat' } const msScarlet = { firstName: 'Josephine', lastName: 'Scarlet', color: '#ff3030', description: 'She is always wearing red', age: 25, image: 'assets/scarlet.png', occupation: 'Actress', favoriteWeapon: 'poison' } const mrsPeacock = { firstName: 'Elizabeth', lastName: 'Peacock', color: '#4050ff', description: 'She enjoys ballroom dancing', age: 32, image: 'assets/peacock.png', occupation: 'Socialite', favoriteWeapon: 'candlestick' } const colMustard = { firstName: 'Michael', lastName: 'Mustard', color: '#f0fa32', description: 'He has a stiff right leg and walks with a limp', age: 60, image: 'assets/mustard.png', occupation: 'Colonel', favoriteWeapon: 'trophy' } const mrsWhite = { firstName: 'Blanche', lastName: 'White', color: 'white', description: 'She likes her surroundings spotless', age: 70, image: 'assets/white.png', occupation: 'Housekeeper', favoriteWeapon: 'pistol' } // WEAPON OBJECTS const rope = { name: 'rope', weight: 0.3, id: 'rope' } const knife = { name: 'knife', weight: 1, id: 'knife' } const candlestick = { name: 'candlestick', weight: 2, id: 'candlestick' } const dumbbell = { name: 'dumbbell', weight: 16, id: 'dumbbell' } const poison = { name: 'poison', weight: 0.2, id: 'poison' } const axe = { name: 'axe', weight: 7, id: 'axe' } const bat = { name: 'bat', weight: 3, id: 'bat' } const trophy = { name: 'trophy', weight: 15, id: 'trophy' } const pistol = { name: 'pistol', weight: 2, id: 'pistol' } // ROOM VARIABLES const roomDining = 'Dining Room'; const roomConservatory = 'Conservatory'; const roomKitchen = 'Kitchen'; const roomStudy = 'Study'; const roomLibrary = 'Library'; const roomBilliard = 'Billiard Room'; const roomLounge = 'Lounge'; const roomBallroom = 'Ballroom'; const roomHall = 'Hall'; const roomSpa = 'Spa'; const roomLiving = 'Living Room'; const roomObservatory = 'Observatory'; const roomTheather = 'Theater'; const roomGuest = 'Guest House'; const roomPatio = 'Patio'; // OBJECT THAT KEEPS THE MYSTERY. const mystery = { killer: null, weapon: null, room: null } // ARRAYS OF ALL SUSPECTS, WEAPONS AND ROOMS const suspects = [ mrGreen, prPlum, msScarlet, mrsPeacock, colMustard, mrsWhite ] const weapons = [ rope, knife, candlestick, dumbbell, poison, axe, bat, trophy, pistol ] const rooms = [ roomDining, roomConservatory, roomKitchen, roomStudy, roomLibrary, roomBilliard, roomLounge, roomBallroom, roomHall, roomSpa, roomLiving, roomObservatory, roomTheather, roomGuest, roomPatio ] // FUNCTION THAT RANDOMLY SELECT ONE ITEM FROM THE ARRAY THAT PASSES IN TO THE FUNCTION. const randomSelector = array => { return array[Math.floor(Math.random() * array.length)] } // Function to shuffle the suspects favorite weapon const shuffleFavoriteWeapon = () => { const favoriteWeapon = randomSelector(weapons); //Picks a random weapon from the array using randomSelector function and creates a favoriteWeapon object mystery.killer.favoriteWeapon = favoriteWeapon.name;// Assigns the name of favoriteWeapon to choosen killers object document.getElementById('favoriteWeapon').innerHTML = `Prefered weapon: ${mystery.killer.favoriteWeapon}`; //Prints favoriteweapon to card } // This function will be invoked in the loadingPickKiller function. const pickKiller = () => { document.getElementById("loader-wrapper-killer").style.display = "none"; document.getElementById("killer-info-wrapper").style.display = "block"; // Randomly selects a killer from the suspects. And add that to the mystery object. mystery.killer = randomSelector(suspects); // This will change the styling and content of the card after it is clicked document.getElementById('killerCard').style.backgroundColor = mystery.killer.color; document.getElementById('killerImage').src = mystery.killer.image; document.getElementById('killerName').innerHTML = `${mystery.killer.firstName} ${mystery.killer.lastName}`; document.getElementById('killerAge').innerHTML = `Age: ${mystery.killer.age}`; document.getElementById('killerOccupation').innerHTML = `${mystery.killer.occupation}`; document.getElementById('killerDescription').innerHTML = `${mystery.killer.description}`; shuffleFavoriteWeapon();//calls the function to shuffle the favorite weapon for choosen killer } const loadingPickKiller = () => { // Sets time for loader animation and calls pickKiller function after const loaderTime = setTimeout(pickKiller, 2000); // Hides the first "side"/ p-tag of the card document.getElementById("start-view-card-killer").style.display = "none"; // Hides the killer information document.getElementById('killer-info-wrapper').style.display = "none"; // Displays the loader document.getElementById('loader-wrapper-killer').style.display = "flex"; document.getElementById('killerCard').style.backgroundColor = '#000'; } // Calling the LoadingPickKiller function document.getElementById("killerCard").onclick = loadingPickKiller; //This function will be invoked in the loadingPickWeapon function. const pickWeapon = () => { document.getElementById("loader-wrapper-weapon").style.display = "none"; document.getElementById("weapon-info-wrapper").style.display = "block"; // Randomly selects a weapon from the array. And add that to the mystery object. mystery.weapon = randomSelector(weapons) // This will change the styling and the content of the card after it is clicked document.getElementById('weaponName').innerHTML = `type: ${mystery.weapon.name}`; document.getElementById('weaponWeight').innerHTML = `weight: ${mystery.weapon.weight} kg`; document.getElementById("start-view-card-weapon").style.display = "none"; } const loadingPickWeapon = () => { // Sets time for loader animation and calls pickKiller function after const loaderTime = setTimeout(pickWeapon, 2000); // Hides the first "side"/ p-tag of the card document.getElementById("start-view-card-weapon").style.display = "none"; // Hides the killer information document.getElementById('weapon-info-wrapper').style.display = "none"; // Displays the loader document.getElementById('loader-wrapper-weapon').style.display = "flex"; document.getElementById('weaponCard').style.backgroundColor = '#000'; } // Calling the loadingPickWeapon function when clicking the card document.getElementById("weaponCard").onclick = loadingPickWeapon; //This function will be invoked in the loadingPickRoom function. const pickRoom = () => { document.getElementById("loader-wrapper-room").style.display = "none"; document.getElementById("room-info-wrapper").style.display = "block"; // Randomly selects a room from the array. And add that to the mystery object. mystery.room = randomSelector(rooms) // This will change the styling and the content of the card after it is clicked document.getElementById('roomName').innerHTML = `${mystery.room}`; document.getElementById("start-view-card-room").style.display = "none"; } const loadingPickRoom = () => { // Sets time for loader animation and calls pickKiller function after const loaderTime = setTimeout(pickRoom, 2000); // Hides the first "side"/ p-tag of the card document.getElementById("start-view-card-room").style.display = "none"; // Hides the killer information document.getElementById('room-info-wrapper').style.display = "none"; // Displays the loader document.getElementById('loader-wrapper-room').style.display = "flex"; document.getElementById('roomCard').style.backgroundColor = '#000'; } // Calling the loadingPickRoom function when clicking the card document.getElementById("roomCard").onclick = loadingPickRoom; // Function to reveal mystery when clicking the button const revealMystery = () => { if (!mystery.killer) { document.getElementById('mystery').innerHTML = `Please pick a killer!`; } else if (!mystery.weapon) { document.getElementById('mystery').innerHTML = `Please pick a weapon!`; } else if (!mystery.room) { document.getElementById('mystery').innerHTML = `Please pick a room!`; } else { document.getElementById('mystery').innerHTML = `The murder was commited by ${mystery.killer.firstName} ${mystery.killer.lastName}, in the ${mystery.room} with a ${mystery.weapon.name}!`; } } // Calling the revealMystery function document.getElementById('revealButton').onclick = revealMystery;
Python
UTF-8
949
2.671875
3
[]
no_license
from produs import * def cautare_produs(listaProduse, prod, pret): for produs in listaProduse: # print(f' produs 1 {prod.nume} == produs 2 {produs.nume}') if prod.nume == produs.nume: produs.modif_pret(pret) return produs return False def are_potential(produs): try: zero_virgula5_la_suta = float(produs.pret_initial)/200 if float(produs.pret[0]) - float(produs.pret_initial) > zero_virgula5_la_suta: return True except ValueError: # print(" Eroare de calcul -- zero_virgula5_la_suta") return False return False def interesant(produs): try: cinci_la_suta = float(produs.pret_initial)/20 if float(produs.pret_initial) - float(produs.pret[0]) > cinci_la_suta: return True return False except ValueError: # print(" Eroare de calcul -- cinci_la_suta") return False return False
Ruby
UTF-8
143
3.09375
3
[]
no_license
arr = [["test", "hello", "world"],["example", "mem"]] puts arr.last.first #brings the last element and then brings the first from the last one
JavaScript
UTF-8
15,174
2.578125
3
[]
no_license
/* * WEB322 – Assignment 2 (Winter 2021) * I declare that this assignment is my own work in accordance with Seneca Academic * Policy. No part of this assignment has been copied manually or electronically from * any other source (including web sites) or distributed to other students. * * Name: Wonchul Choi * Student ID: 118362201 * Course: Web322 NDD * */ const mongoose = require("mongoose"); const Schema = mongoose.Schema; const dishSchema = new Schema({ name: { type:String, require: true, unique: true }, ingredient: { type:String, require: true }, category: { type:String, require: true }, description: { type:String, require: true }, price: { type:Number, require: true }, serving: { type:Number, require: true }, time: { type:Number, require: true }, calorie: { type:String, require: true }, isTopMeal: { type: Boolean, default: false, require: true }, imageUrl: { type: String, require: true }, rate: { type: Number, require: true }, }); const menuModel = mongoose.model("Menu", dishSchema); module.exports = menuModel; var dishes = [ { name: "Spring Asparagus Plate", ingredient: "Aspagus, mushroom, potato, homemade prociutto, cream, butter, balsamic reduction", category: "seasonal", description: "Grilled Asparagus with prosciutto, saute mushroom, potato mousse and balsamic reduction", price: 25.99, serving: 2, time: 15, calorie: "300 per Person", isTopMeal: false, imageUrl: '/image/food/asparagus_wrap.JPG', rate: 3.9 }, { name: "Beet leave wrap with Israeli couscous", ingredient: "Beet leave, Israeli couscous, plum jam, goat cheese, french dressing", category: "seasonal", description: "Israelli couscous salad wrapped with beet leaves with fresh plum jam", price: 19.99, serving: 2, time: 15, calorie: "300 per Person", isTopMeal: false, imageUrl: '/image/food/beet_leave_wrap.JPG', rate: 4.0 }, { name: "Beef Brisket Poutine", ingredient: "Fresh beef brisket, D's signature beef gravy, fresh chees curd, Potato", category: "casual", description: "Traditional Canadian Beef Brisket Poutine", price: 25.99, serving: 2, time: 15, calorie: "500 per Person", isTopMeal: false, imageUrl: '/image/food/brisket_poutine.JPG', rate: 4.0 }, { name: "Carbonara 2020 ver.", ingredient: "Homemade Fettuccine, Fresh Parmasan Cheese, Fresh egg yolk, Fresh garlic, Fresh parsley", category: "classic", description: "Traditional Carbonara was reborn by ours. Fit to Canadian taste", price: 32.99, serving: 2, time: 30, calorie: "500 per Person", isTopMeal: true, imageUrl: '/image/food/carbonara.JPG', rate: 4.5 }, { name: "Classic sunny-side up buger", ingredient: "Beef Petty, Letture, Bacon, Fresh egg, Sliced Mozzarella, Bun, French fries, Aioli", category: "classic", description: "Classic buger with sliced mozzarella, roasted bacon, sunny-side up, and aioli", price: 30.99, serving: 2, time: 30, calorie: "300 per Person", isTopMeal: false, imageUrl: '/image/food/classic_buger.JPG', rate: 4.1 }, { name: "Korean Cold Noodle", ingredient: "White kimchi broth, Egg, Pear, Steamed beef, Cucumber, Buckwheat noodles", category: "ethnic", description: "Korean tradition cold noodle from the first recipe in Korea was reborn by our team.", price: 25.99, serving: 2, time: 30, calorie: "350 per Person", isTopMeal: false, imageUrl: '/image/food/cold_noodle.JPG', rate: 4.0 }, { name: "Korean cucumber dumpling", ingredient: "Flour, Marinaded beef, Cucumber", category: "ethnic", description: "Korean tradition cucumber dumpling from the first recipe in Korea was reborn by our team.", price: 25.99, serving: 2, time: 60, calorie: "350 per Person", isTopMeal: false, imageUrl: '/image/food/cucumber_dumpling.JPG', rate: 3.5 }, { name: "Dessert plate", ingredient: "Goat cheese cake, Black forest cake, Pecan pie, Fresh Berries, Fruit coulis and Jam ", category: "casual", description: "Sweet dessert plate for the special people! everything is in there", price: 30.99, serving: 4, time: 10, calorie: "300 per Person", isTopMeal: false, imageUrl: '/image/food/dessert_plate.JPG', rate: 4.2 }, { name: "Duck congee with dry-aged beef", ingredient: "Duck confit, Rice, Grape fruit, Onion, carrot", category: "casual", description: "Homemade Duck confit with House dry-aged beef tender", price: 30.99, serving: 2, time: 45, calorie: "250 per Person", isTopMeal: false, imageUrl: '/image/food/duck_congee.JPG', rate: 4.3 }, { name: "European seabass with seasonal vegetable", ingredient: "European seabass, seasonal vegetable, lobster sauce", category: "ethnic", description: "Fresh European seabass with carmelized seasonal vegetable and lobster sauce", price: 32.99, serving: 2, time: 45, calorie: "300 per Person", isTopMeal: false, imageUrl: '/image/food/european_seabass.JPG', rate: 4.5 }, { name: "Heirloom Toamto Salad", ingredient: "Heirloom Tomato, Lonza, Baby spinich, Goat cheese, Avocado, Balsamic", category: "seasonal", description: "Fresh Heirloom Tomato, Baby sipnich salad with Homecured Lonza, Canadian goat cheese, guacamole and balsamic dressing", price: 25.99, serving: 2, time: 15, calorie: "200 per Person", isTopMeal: false, imageUrl: '/image/food/heirloom_toamto_salad.JPG', rate: 4.0 }, { name: "Kimchi Seafood Pilaf with fried egg", ingredient: "Kimchi, Seasonal seafood, Rice, Fresh Egg", calorie: "casual", description: "Homemade kimchi with seasonal seafood and Special taste for Spicy lover!", price: 25.99, serving: 2, time: 15, calorie: "270 per Person", isTopMeal: false, imageUrl: '/image/food/kimch_pilaf.JPG', rate: 4.1 }, { name: "Korean Braised Beef", ingredient: "Veal rip, Egg, pine nut, Special sauce", category: "ethnic", description: "Korean tradition Brasied Beef as known as Galbi from the first recipe in Korea is reborn by our team.", price: 32.99, serving: 2, time: 60, calory: "350 per Person", isTopMeal: false, imageUrl: '/image/food/korean_braised_beef.JPG', rate: 4.0 }, { name: "Korean Style Wrap Plate", ingredient: "Marinade pork, Bean paste, Beef, Seasonal vegetable, Mixed Lettures", category: "ethnic", description: "Korean tradition style wrap with marinade pork and special meat and bean paste sauce from the first recipe in Korea.", price: 35.99, serving: 2, time: 15, calory: "300 per Person", isTopMeal: false, imageUrl: '/image/food/korean_stlye_wrap.JPG', rate: 4.0 }, { name: "Lamb Burger ver 2020", ingredient: "Lamb petty, Aged whited chedder, Aged blue cheese, Hot aioli, Mixed Lettures", category: "casual", description: "Special flavor for meat lover! Our special lamb burger 2020 ver", price: 35.99, serving: 2, time: 30, calory: "250 per Person", isTopMeal: false, imageUrl: '/image/food/lamb_burger.JPG', rate: 4.0 }, { name: "Pizzaroll", ingredient: "Mixed Homecured meat, Aged chedder, Homemade Tomato sauce, Olive oil, Mixed green, Balsamic Dressing ", category: "casual", description: "Pizza roll with mixed homecured meat, Aged chedder and mixed green salad. ", price: 20.99, serving: 2, time: 45, calory: "300 per Person", isTopMeal: false, imageUrl: '/image/food/pizzaroll.JPG', rate: 3.9 }, { name: "Potato Pizza", ingredient: "Homemade Tomato suace, Potato, Mixed cheese", category: "casual", description: "Special flavor roasted potato Pizza! ", price: 15.99, serving: 2, time: 45, calory: "200 per Person", isTopMeal: false, imageUrl: '/image/food/potato_pizza.JPG', rate: 4.0 }, { name: "Farm Harvested Risotto", ingredient: "Arborio rice, Butternut Sqaush, Corn, Carrot, Onion, Parmigiano-Reggiano", category: "classic", description: "Farm Harvested Risotto make by traditional vegetable in North America.", price: 20.99, serving: 2, time: 60, calory: "200 per Person", isTopMeal: false, imageUrl: '/image/food/risotto.JPG', rate: 4.0 }, { name: "Spring Salad with Smoked Salmon", ingredient: "club-smoked Salmon, Mixed spring green, French dressing ", category: "ethnic", description: "Korean tradition style wrap with marinade pork and special meat and bean paste sauce from the first recipe in Korea.", price: 20.99, serving: 2, time: 15, calory: "150 per Person", isTopMeal: false, imageUrl: '/image/food/salad.JPG', rate: 4.0 }, { name: "Pan-fried Seabass with sous-vide vegetable", ingredient: "Seabass, Seasonal vegetable, Lemon-sauce", category: "seasonal", description: "Pan-fried tasty seabass! You will miss it all day! ", price: 50.99, serving: 2, time: 45, calory: "300 per Person", isTopMeal: true, imageUrl: '/image/food/seabass.JPG', rate: 4.8 }, { name: "Classic Italian Seafood Pasta", ingredient: "Homemade Tagliatelle, Mixed seafood, Oven-dried tomato, Olive oil-Extra Virgin", category: "classic", description: "Italian Classic Pasta on your table! Fresh seasonal seafood is going to you!", price: 52.99, serving: 2, time: 45, calory: "300 per Person", isTopMeal: true, imageUrl: '/image/food/seafood.JPG', rate: 4.9 }, { name: "Korean Steamed Tofu", ingredient: "Homemade Tofu, Chicken tenderloin, Egg, Pepper, Mushroom, Garlic", category: "ethnic", description: "Korean tradition Steamed Tofu with Chicken tenderloinfrom the first recipe in Korea is rebron by our team.", price: 35.99, serving: 2, time: 30, calory: "150 per Person", isTopMeal: false, imageUrl: '/image/food/steamed_tofu.JPG', rate: 4.0 }, { name: "watermelon_salad", ingredient: "Marinade pork, Bean paste, Beef, Seasonal vegetable, Mixed Lettures", category: "seasonal", description: "Korean tradition style wrap with marinade pork and special meat and bean paste sauce from the first recipe in Korea.", price: 35.99, serving: 2, time: 15, calory: "300 per Person", isTopMeal: false, imageUrl: '/image/food/watermelon_salad.JPG', rate: 4.0 }, { name: "Chicken Noodle Soup", ingredient: "Chicken breast, Chicken broth, Homemade pasta, Seasonal vegetable", category: "classic", description: "Chicken Noodle Soup for you. It makes you keep it warm.", price: 20.99, serving: 2, time: 30, calory: "150 per Person", isTopMeal: false, imageUrl: '/image/food/chicken_noodle_soup.JPG', rate: 4.0 },{ name: "Smoked BBQ Rib", ingredient: "Veal Rib, Special BBQ sauce", category: "casual", description: "TGIF! Really BBQ Rib is coming!", price: 30.99, serving: 2, time: 30, calory: "300 per Person", isTopMeal: false, imageUrl: '/image/food/Rib.JPG', rate: 4.0 }, { name: "French Lamb Rack", ingredient: "Lamb Rack ", category: "classic", description: "Chicken Noodle Soup for you. It makes you keep it warm.", price: 20.99, serving: 2, time: 30, calory: "150 per Person", isTopMeal: false, imageUrl: '/image/food/lamb_rack.JPG', rate: 4.0 } ]; module.exports.getAllMenu = function() { return dishes; }; module.exports.getTopMeal = function() { var topMeal = []; var temp; for (var i = 0; i < dishes.length; i++) { for(var j = 0; j < dishes.length; j++) if (dishes[i].rate < dishes[j].rate) { temp = dishes[i]; dishes[i] = dishes[j]; dishes[j] = temp; } } return topMeal; }; module.exports.getClassic = function() { var classicMeal = []; for (var i = 0; i < dishes.length; i++) { if (dishes[i].category == "classic") { classicMeal.push(dishes[i]); } } return classicMeal; }; module.exports.getCasual = function() { var casualMeal = []; for (var i = 0; i < dishes.length; i++) { if (dishes[i].category == "casual") { casualMeal.push(dishes[i]); } } return casualMeal; }; module.exports.returnCategory = function(arrary){ return arrary[0].category.toUpperCase(); } module.exports.getEthnic = function() { var ethnicMeal = []; for (var i = 0; i < dishes.length; i++) { if (dishes[i].category == "ethnic") { ethnicMeal.push(dishes[i]); } } return ethnicMeal; }; module.exports.getSeasonal = function() { var seasonalMeal = []; for (var i = 0; i < dishes.length; i++) { if (dishes[i].category == "seasonal") { seasonalMeal.push(dishes[i]); } } return seasonalMeal; };
Java
UTF-8
1,078
2.171875
2
[]
no_license
package uk.co.telegraph.core.commons.dynamiclistdata; import org.apache.commons.lang.math.NumberUtils; import org.apache.commons.lang3.StringUtils; import com.google.common.collect.Lists; import uk.co.telegraph.core.commons.curatedlist.CuratedList; import uk.co.telegraph.core.commons.mostviewedlist.MostViewedList; public class DynamicListData extends CuratedList { public static final String ITEM_COUNT_SELECTOR_PREFIX = "itemCount"; @Override public void activate() throws Exception { super.activate(); String[] selectors = getRequest().getRequestPathInfo().getSelectors(); Integer itemCount = MostViewedList.DEFAULT_ITEM_COUNT; for (String selector : selectors) { if (selector.startsWith(ITEM_COUNT_SELECTOR_PREFIX)) { String number = selector.replace(ITEM_COUNT_SELECTOR_PREFIX, StringUtils.EMPTY); if (NumberUtils.isNumber(number)) { itemCount = NumberUtils.toInt(number, MostViewedList.DEFAULT_ITEM_COUNT); } } } if (tiles.size() > itemCount) { tiles = Lists.newArrayList(tiles.subList(0, itemCount)); } return; } }
Java
UTF-8
1,261
3.421875
3
[]
no_license
package day1; public class Extwentyone { public static void main(String[] args) { int month = 2; int year = 2019; switch(month) { case 1: System.out.println("Number of Days is : 31"); break; case 2: if(checkYear(year)) System.out.println("Number of Days is : 29"); else System.out.println("Number of Days is : 28"); break; case 3: System.out.println("Number of Days is : 31"); break; case 4: System.out.println("Number of Days is : 30"); break; case 5: System.out.println("Number of Days is : 31"); break; case 6: System.out.println("Number of Days is : 30"); break; case 7: System.out.println("Number of Days is : 31"); break; case 8: System.out.println("Number of Days is : 31"); break; case 9: System.out.println("Number of Days is : 30"); break; case 10: System.out.println("Number of Days is : 31"); break; case 11: System.out.println("Number of Days is : 30"); break; case 12: System.out.println("Number of Days is : 31"); break; } } public static boolean checkYear(int year) { if (year % 400 == 0) return true; if (year % 100 == 0) return false; if (year % 4 == 0) return true; return false; } }
Java
UTF-8
960
2.421875
2
[]
no_license
package cn.com.yuzhushui.websocket.common.base; import java.util.HashMap; import java.util.Map; import lombok.Data; import qing.yun.hui.common.utils.StringUtil; /*** ** @category 请用一句话来描述其用途... ** @author qing.yunhui ** @email: 280672161@qq.com ** @createTime: 2016年11月17日下午9:18:19 **/ @Data public class BaseQuery { private Map<String, Object> queryData = new HashMap<String, Object>();// 一些查询条件 private int pageNum = 1;// 当前页 private int pageSize = 5;// 每页的数量 private String orderDirection;// 排序方向 private String orderColumns;// 排序字段(多个以半角逗号隔开) private String orderBy;// 排序 public void addParam(String key, Object value){ this.queryData.put(key, value); } public void setOrderBy() { if(!StringUtil.isEmpty(getOrderColumns())) { this.orderBy = getOrderColumns() + " " + (getOrderDirection() == null ? "" : getOrderDirection()); } } }
Python
UTF-8
494
3.171875
3
[]
no_license
import matplotlib.pyplot as plt import numpy as np # plot def show_result(title, x1, x2, xd, y1, y2, yd, y): plt.figure() plt.title(title, fontsize=18) plt.xlim(x1-xd/4, x2+xd/4) plt.xticks(np.arange(x1, x2+xd/4, xd)) plt.ylim(y1-yd/4, y2+yd/4) plt.yticks(np.arange(y1, y2+yd/4, yd)) plt.xlabel('Epoch') plt.ylabel('Accuracy(%)') x = [i for i in range(1, x2 + 1)] plt.plot(x, y, color='teal', marker='o', linewidth=1.0) plt.grid() plt.show()
C++
UTF-8
1,995
2.78125
3
[]
no_license
#include <mpi.h> #include <iostream> using namespace std; int main(int argc, char **argv) { int myid, numprocs, n, count, remainder, myBlockSize; int* data = NULL; int* sendcounts = NULL; int* displs = NULL; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &numprocs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); if (0 == myid) { cout << "Summation of numbers with advanced cascade algorithm" << endl << endl; cout << "Enter the quantity of elements for summation:" << endl; cin >> n; data = new int[n]; int sum = 0; for (int i = 0; i < n; ++i) { data[i] = rand() % 100; cout << data[i] << ' '; sum += data[i]; } cout << endl; cout << "Exact sum: " << sum << endl; sendcounts = new int[numprocs]; displs = new int[numprocs]; count = n / numprocs; remainder = n - count * numprocs; int prefixSum = 0; for (int i = 0; i < numprocs; ++i) { sendcounts[i] = (i < remainder) ? count + 1 : count; displs[i] = prefixSum; prefixSum += sendcounts[i]; } } MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD); if (0 != myid) { count = n / numprocs; remainder = n - count * numprocs; } myBlockSize = myid < remainder ? count + 1 : count; int* res = new int[myBlockSize]; MPI_Scatterv(data, sendcounts, displs, MPI_INT, res, myBlockSize, MPI_INT, 0, MPI_COMM_WORLD); if (0 == myid) { delete[] sendcounts; delete[] displs; delete[] data; } int total = 0; #pragma omp parallel for reduction(+:total) for (int i = 0; i < myBlockSize; ++i) total += res[i]; delete[] res; int temp; for (int i = 1; i < numprocs; i *= 2) { if (myid % (i*2) != 0) { MPI_Send(&total, 1, MPI_INT, myid - i, 0, MPI_COMM_WORLD); break; } else if (myid + i < numprocs) { MPI_Recv(&temp, 1, MPI_INT, myid + i, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); total += temp; } } MPI_Finalize(); if (myid == 0) { cout << "Computed sum: " << total << endl; #if _DEBUG system("pause"); #endif } return EXIT_SUCCESS; }
Go
UTF-8
4,031
2.703125
3
[]
no_license
package handlers import ( "encoding/json" "github.com/go-playground/validator/v10" "github.com/gorilla/mux" "go.uber.org/zap" "net/http" "strconv" "task-manager/adapters" "task-manager/models" "task-manager/repositories" "task-manager/services" ) type TaskHandler struct { service services.TaskService validator *validator.Validate } func NewTaskHandler(adapter adapters.IDbAdapter) *TaskHandler { return &TaskHandler{ service: services.TaskService{ Repository: repositories.TaskRepository{IDbAdapter: adapter}, }, validator: validator.New(), } } func (handler TaskHandler) GetByColumnId(w http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) columnId, err := strconv.ParseInt(vars["columnId"], 10, 64) if err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusBadRequest) return } tasks, err := handler.service.GetByColumnId(columnId) if err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusNotFound) return } w.Header().Add("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(tasks); err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusInternalServerError) } } func (handler TaskHandler) Get(w http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) id, err := strconv.ParseInt(vars["id"], 10, 64) if err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusBadRequest) return } task, err := handler.service.GetById(id) if err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusNotFound) return } w.Header().Add("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(task); err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusInternalServerError) } } func (handler TaskHandler) Create(w http.ResponseWriter, req *http.Request) { var task models.TaskModel err := json.NewDecoder(req.Body).Decode(&task) if err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusBadRequest) return } err = handler.validator.Struct(&task) if err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusBadRequest) return } newTask, err := handler.service.Create(task) if err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusInternalServerError) return } w.Header().Add("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(newTask); err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusInternalServerError) } } func (handler TaskHandler) Update(w http.ResponseWriter, req *http.Request) { var task models.TaskModel err := json.NewDecoder(req.Body).Decode(&task) if err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusBadRequest) return } err = handler.validator.Struct(&task) if err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusBadRequest) return } updatedTask, err := handler.service.Update(task) if err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusNotFound) return } w.Header().Add("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(updatedTask); err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusInternalServerError) } } func (handler TaskHandler) Delete(w http.ResponseWriter, req *http.Request) { vars := mux.Vars(req) id, err := strconv.ParseInt(vars["id"], 10, 64) if err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusBadRequest) return } err = handler.service.DeleteById(id) if err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusNotFound) return } w.Header().Add("Content-Type", "application/json") if err := json.NewEncoder(w).Encode("success"); err != nil { zap.L().Error(err.Error()) http.Error(w, err.Error(), http.StatusInternalServerError) } }
Java
UTF-8
412
2.796875
3
[ "MIT", "Apache-2.0" ]
permissive
package com.esafirm.imagepicker.model; public enum MediaType { IMAGE(0), VIDEO(1); public int value; MediaType(int value) { this.value = value; } public static MediaType fromInteger(int x) { switch (x) { case 0: return IMAGE; case 1: return VIDEO; default: return null; } } }
JavaScript
UTF-8
6,087
2.578125
3
[]
no_license
/* Will call the cb with as a parameter an array of lists on wich searches can be run. Each list of items corresponds to a relevant use case to test (relevance or performances) Usage : const prepareLists = require('this-file') const prepareLists((lists)=>{ `do what you want with the list of lists (of items)`}) The long list is in the file /tools/path-list.json wich you must prepare yourself with path-extractor.js (cf readme) */ const lists = [] let items const prepareLists = function (cb) { // get data from the the json file (/tools/path-list.json) for the long list (last list) let url = 'path-list.json'; fetch(url) .then(res => { return res.json() }) .then((out) => { lists.push({name:`long list (${out.length} items)`, id:'longList', defaultSearch:'banque pret', items:out}) cb(lists) }) .catch(err => console.error(err)); } // format a list of full path into [ {name:"fileName", path:"dirPath", type:"file or directory"} ] const _format = function (items) { let path_list = [] for (fullPath of items) { let i = fullPath.lastIndexOf('/') path_list.push({type:"file",path:fullPath.slice(0,i), name:fullPath.slice(i+1)}) } return path_list } /* list 1 */ items = [ '/Comptabilité/Fiscal/2015 12 30 - Controle fiscal/Documents clé USB/Banque' ] lists.push({name:'1 item for test', id:'1_items', defaultSearch:'banque pret', items:_format(items)}) /* list 2 */ items = [ '/Administratif/test-filesname.txt', '/Administratif/Bank statements/test-filesname.txt', '/Administratif/Bank statements/Bank Of America/test-filesname.txt', '/Administratif/Bank statements/Deutsche Bank/test-filesname.txt', '/Administratif/Bank statements/Société Générale/test-filesname.txt', '/Administratif/CPAM/test-filesname.txt', '/Administratif/EDF/test-filesname.txt', '/Administratif/EDF/Contrat/test-filesname.txt', '/Administratif/EDF/Factures/test-filesname.txt', '/Administratif/Emploi/test-filesname.txt', '/Administratif/Impôts/test-filesname.txt', '/Administratif/Logement/test-filesname.txt', '/Administratif/Logement/Loyer 158 rue de Verdun/test-filesname.txt', '/Administratif/Orange/test-filesname.txt', '/Administratif/Pièces identité/test-filesname.txt', '/Administratif/Pièces identité/Carte identité/test-filesname.txt', '/Administratif/Pièces identité/Passeport/test-filesname.txt', '/Administratif/Pièces identité/Permis de conduire/test-filesname.txt', '/Appareils photo/test-filesname.txt', '/Boulot/test-filesname.txt', '/Cours ISEN/test-filesname.txt', '/Cours ISEN/CIR/test-filesname.txt', '/Cours ISEN/CIR/LINUX/test-filesname.txt', '/Cours ISEN/CIR/MICROCONTROLEUR/test-filesname.txt', '/Cours ISEN/CIR/RESEAUX/test-filesname.txt', '/Cours ISEN/CIR/TRAITEMENT_SIGNAL/test-filesname.txt', '/Divers photo/test-filesname.txt', '/Divers photo/wallpapers/test-filesname.txt', '/Films/test-filesname.txt', '/Notes/test-filesname.txt', '/Notes/Communication/test-filesname.txt', '/Notes/Notes techniques/test-filesname.txt', '/Notes/Recrutement/test-filesname.txt', '/Projet appartement à Lyon/test-filesname.txt', '/Vacances Périgord"/test-filesname.txt' ] lists.push({name:'23 items', id:'23_items', defaultSearch:'admin', items:_format(items)}) /* list 3 */ $A='A666' $B='B666' $C='C666' $D='D666' $$='----' items = [ `/ExpectedRk:_08_/D0_${$A}/D1_${$$}/D2_${$$}`, `/ExpectedRk:_07_/D0_${$A}/D1_${$$}`, `/ExpectedRk:_06_/D0_${$$}/D1_${$$}/D2_${$A}/D3.6abc_${$A}.txt`, `/ExpectedRk:_05_/D0_${$$}/D1_${$$}/D2_${$A}/D3.6ab_${$A}.txt`, `/ExpectedRk:_04_/D0_${$$}/D1_${$$}/D2_${$A}/D3.6a_${$A}.txt`, `/ExpectedRk:_03_/D0_${$$}/D1_${$$}/D2_${$A}/D3.6_${$A}.txt`, `/ExpectedRk:_02_/D0_${$$}/D1_${$$}/D2_${$A}`, `/ExpectedRk:_01_/D0_${$A}`] lists.push({name:'test 1', id:'test_1', defaultSearch:'A66', items:_format(items)}) /* list 4 */ items = [ `/ExpectedRk_16_/D0_${$$}/D1_${$$}/D2_${$$}/D3_${$A}/D4_${$$}.txt`, `/ExpectedRk_12_/D0_${$$}/D1_${$$}/D2_${$A}/D3.1_${$$}.txt`, `/ExpectedRk_13_/D0_${$$}/D1_${$$}/D2_${$A}/D3.2_${$$}.txt`, `/ExpectedRk_14_/D0_${$$}/D1_${$$}/D2_${$A}/D3.3_${$$}.txt`, `/ExpectedRk_09_/D0_${$$}/D1_${$$}/D2_${$A}/D3.4_${$A}.txt`, `/ExpectedRk_10_/D0_${$$}/D1_${$$}/D2_${$A}/D3.5_${$A}.txt`, `/ExpectedRk_11_/D0_${$$}/D1_${$$}/D2_${$A}/D3.6_${$A}.txt`, `/ExpectedRk_15_/D0_${$A}/D1_${$$}/D2_${$A}.txt`, `/ExpectedRk_08_/D0_${$$}/D1_${$A}but relevance diluted.txt`, `/ExpectedRk_07_/D0_${$A}7.txt`, `/ExpectedRk_06_/D0_${$$}/D1_${$$}/D2_${$$}/D3_${$$}/D4_${$A}.txt`, `/ExpectedRk_05_/D0_${$$}/D1_${$A}.txt`, `/ExpectedRk_04_/D0_${$A}.txt`, `/ExpectedRk_03_/D0_${$$}/D1_${$$}/D2_${$$}/D3_${$A}`, `/ExpectedRk_02_/D0_${$$}/D1_${$$}/D2_${$A}`, `/ExpectedRk_01_/D0_${$A}` ] lists.push({name:'test 2', id:'test_2', defaultSearch:'A66', items:_format(items)}) /* list 5 */ items = [ `/A0_${$$}/A1_${$$}/A2_${$A}/A3.6_${$A}.txt`, `/A0_${$$}/A1_${$$}/A2_${$A}/A3.6a_${$A}.txt`, `/A0_${$$}/A1_${$$}/A2_${$A}/A3.6ab_${$A}.txt`, `/A0_${$$}/A1_${$$}/A2_${$A}/A3.6abc_${$A}.txt`, `/A0_${$$}/A1_${$$}/A2_${$A}/A3.6abcd_${$A}.txt`, `/A0_${$$}/A1_${$$}/A2_${$A}/A3.6abcde_${$A}.txt`, `/A0_${$$}/A1_${$$}/A2_${$A}/A3.6abcdef_${$A}.txt`, `/A0_${$$}/A1_${$$}/A2_${$A}/A3.6abcdefg_${$A}.txt`, `/A0_${$$}/A1_${$$}/A2_${$A}/A3.6abcdefgh_${$A}.txt`, `/A0_${$$}/A1_${$$}/A2_${$A}`, `/B0_${$A}.txt`, `/B0_${$A}/B1_${$A}.txt`, `/B0_${$A}/B1_${$A}/B2_${$A}.txt`, `/B0_${$A}/B1_${$A}/B2_${$A}/B3_${$A}.txt`, `/B0_${$A}/B1_${$A}/B2_${$A}/B3_${$A}/B4_${$A}.txt`, `/C0_${$A}.txt`, `/C0_${$A}/C1_${$$}/C2_${$A}/C3_${$$}/C4_${$A}.txt`, `/C0_${$A}/C1_${$$}/C2_${$A}/C3_${$$}`, `/C0_${$A}/C1_${$$}/C2_${$A}.txt`, `/C0_${$A}/C1_${$$}`, `/C0_${$A}`, `/D0_${$D}.txt`, `/D0_${$D}/D1_${$$}`, `/D0_${$D}/D1_${$$}/D2_${$D}`, `/D0_${$D}/D1_${$$}/D2_${$D}/D3_${$$}`, `/D0_${$D}/D1_${$$}/D2_${$D}/D3_${$$}/D4_${$D}.txt` ] lists.push({name:'test 3', id:'test_3', defaultSearch:'A66', items:_format(items)}) module.exports = prepareLists
Java
UTF-8
938
2.46875
2
[]
no_license
package com.n01216688.testing; public class DataStructure_Restaurantinfo { private String restaurant_name; private String restaurant_phone; private String restaurant_address; public DataStructure_Restaurantinfo() { } public DataStructure_Restaurantinfo(String name, String phone, String address) { this.restaurant_name = name; this.restaurant_phone = phone; this.restaurant_address = address; } public String getName() { return restaurant_name; } public void setName(String name) { this.restaurant_name = name; } public String getPhone() { return restaurant_phone; } public void setPhone(String phone) { this.restaurant_phone = phone; } public String getAddress() { return restaurant_address; } public void setAddress(String address) { this.restaurant_address = address; } }
Python
UTF-8
1,366
3.484375
3
[ "MIT" ]
permissive
#author: Rafa Arquero Gimeno #we need split import string #read field data in file def field_parser(raw_field): return tuple(string.split(raw_field, "&&")) def parser(): #init matrix M = [] #the file could not be here, so... try: raw = open("./peliculas100.dat") raw = file.readlines(raw) #trick: avoid append => performance boost M = [0] * len(raw) #each line in file is an entire film for id in xrange(len(raw)): #gets film's fields, and the field_parser function will parse them film = map(field_parser, string.split(raw[id], "|")) M[id] = film except IOError: #file not found print "[!] peliculas100.dat not found" return M def main(): data = parser() #field names film_headers = ["title", "director", "cast", "producer", "writer", "country", "language", "year", "genres", "votes", "rating", "runtime", "plot", "cover url"] for film_id in xrange(len(data)): print "Film", film_id, ":" for field_id in xrange(len(data[film_id])): field = data[film_id][field_id] #print header print (4 * " ") + film_headers[field_id] + ": ", #print field, multiples joined by commas print "\t" + string.join(field, ", ") main()
Java
UTF-8
154
1.8125
2
[ "MIT" ]
permissive
package fr.slaynash.communication.enums; public enum ConnectionState { STATE_DISCONNECTED, STATE_CONNECTING, STATE_CONNECTED, STATE_DISCONNECTING; }
C
UTF-8
2,115
3.453125
3
[]
no_license
/** * Extreme Edge Cases Lab * CS 241 - Fall 2018 */ #include <stdlib.h> #include <ctype.h> #include <string.h> #include <stdio.h> char **camel_caser(const char *input_str) { if (!input_str) { return NULL; } int count = 0; for (int i = 0; input_str[i] != '\0'; i++) { if (ispunct(input_str[i])) count++; } char** result = (char**)calloc(count + 1, sizeof(void*)); char buffer[100]; char string[100]; int str_start_index = 0; int b_end_index = 0; int num_words = 0; count = 0; for (int i = 0; input_str[i] != '\0'; i++) { char curp_str = input_str[i]; if ((isspace(curp_str) || ispunct(curp_str))) { if (b_end_index == 0 && (isspace(curp_str))) { continue; } if (num_words != 0) { buffer[0] = toupper(buffer[0]); } num_words++; strncpy(string + str_start_index, buffer, b_end_index); str_start_index += b_end_index; if (ispunct(curp_str)) { string[str_start_index] = '\0'; char* s = (char*)malloc(sizeof(char) * str_start_index); strncpy(s, string, str_start_index); result[count++] = s; str_start_index = 0; num_words = 0; } b_end_index = 0; } else { buffer[b_end_index] = tolower(input_str[i]); b_end_index++; } } return result; } void destroy(char **result) { while(*result) { free(*result); result++; } return; } int main(int argv, char** args) { char* a = "..."; char* b = "The Heisenbug is an incredible creature. Facenovel servers get their power from its indeterminism. Code smell can be ignored with INCREDIBLE use of air freshener. God objects are the new religion."; char** result = camel_caser(b); printf("Original string is :%s\n", b); while(*result) { printf("%s\n", *result); result++; } printf("\n"); }
Markdown
UTF-8
2,761
2.5625
3
[ "Unlicense" ]
permissive
# 800 رائد ورائدة أعمال في معرض الشرقية غدا Published at: **2019-11-02T22:17:56+00:00** Author: **صحيفة البلاد** Original: [صحيفة البلاد](https://albiladdaily.com/2019/11/03/800-%d8%b1%d8%a7%d8%a6%d8%af-%d9%88%d8%b1%d8%a7%d8%a6%d8%af%d8%a9-%d8%a3%d8%b9%d9%85%d8%a7%d9%84-%d9%81%d9%8a-%d9%85%d8%b9%d8%b1%d8%b6-%d8%a7%d9%84%d8%b4%d8%b1%d9%82%d9%8a%d8%a9-%d8%ba%d8%af%d8%a7/) الدمام-حمود الزهراني برعاية الأمير سعود بن نايف أمير المنطقة الشرقية ، ينطلق غدا الاثنين”ملتقى ومعرض (راد) لريادة الاعمال 2019 ” في مقر معارض شركة الظهران. وقال رئيس مجلس إدارة غرفة الشرقية عبدالحكيم الخالدي ، بأن المعرض سيستقبل زواره من الساعة 4 وحتى 10 مساء، مشيرا الى مشاركة نحو 800 رائد ورائدة اعمال ضمن فعاليات الملتقى الذي يعد اكبر حدث من نوعه في الشرق الأوسط ويشهد مشاركة خليجية واسعة. وأكد ان السوق السعودي متطور في العديد من المجالات ولا يخضع للتقليدية وهذا ما جعله يتفاعل مع المبادرات الحديثة التي يطرحها شباب وشابات الاعمال ويتجاوب معها بشكل متسارع، حيث اجبر الكثير من المستثمرين الى تغيير وجهات نظرهم التقليدية ومسايرة التحديث الحاصل في السوق، ولعلها ابرزها التطور التكنولوجي.من جهته قال رئيس مجلس شباب الاعمال بالغرفة عبدالله بن فيصل البريكان بان المعرض يشمل مبادرات شبابية بدأت بشكل جيد وواجهت تحديات السوق ، لكنها استطاعت الصمود والاستمرار بتطوير الافكار والتكيف مع ظروف السوق، مؤكداً بان الملتقى يعد فرصة ثمينة لرواد ورائدات الاعمال للاستفادة من الخبرات المشاركة. كما أكدت رئيس مجلس شابات الاعمال في الغرفة نجلاء بنت حمد العبدالقادر اهمية الأفكار الإبداعية التي تشهدها ريادة الأعمال في المملكة، والتي تعتمد على أفكار رائدة من شباب شابات الاعمال والتي بإمكانها التأثير على السوق وتحقيق تجربة وخبرة مميزة في مجالات متعددة وسباقة كونها تعتمد على الإبداع والمبادرة.
Markdown
UTF-8
4,120
2.703125
3
[]
no_license
--- name: 3.5.5.2 title: 3.5.5.2 - EIGRP Query Scoping with Summarization short-title: EIGRP Query Scoping with Summarization category: 3.5 EIGRP collection: eigrp layout: page exam: both sidebar: eigrp_sidebar permalink: 3.5.5.2.html folder: eigrp --- First we need to understand what is meant by Query Scoping… When something changes in network topology, the routers that detect a loss of network prefix will send out EIGRP QUERY messages that propagate in circular waves similar to the ripples on water surface. Every queried router will in turn query its neighbors and so on, until all routers that knew about the prefix affected. After this, the expanding circle will start collapsing back with EIGRP REPLY messages. The maximum radius of that circle may be viewed as the query scope. From scalability standpoint, it is very important to know what conditions will limit the average query scope, as this directly impact the network stability. You may compare the “query scope” with the concept of flooding domain in OSPF or ISIS. However, in contrast with the link-state protocols, you are very flexible with choosing the query scope boundaries, which is a powerful feature of EIGRP. There are four conditions that affect query propagation. Almost all of them are based on the fact that query stops once the queried router cannot find the **exact** match for the requested subnet in its topology table. After this the router responds back that the network is unknown. Based on this behavior, the following will stop a query from propagation. 1. Network Summarization 2. Route Filtering 3. Stub Routers 4. Different EIGRP AS Numbers This topic covers Network Summarization, but we will also cover Route Filtering and Different AS Number. Stub Routers are a separate topic. Network Summarization could be considered as one of the most effective methods of query scoping. If router A sends a summary prefix to router B, then any query from A to B with regards to the subnets encompassed by the summary route will not find the **exact** match in B’s topology table. Thus queries are stopped on the routers that are one-hop from point of summarization. Given the fact that EIGRP allows for introducing summarization virtually everywhere you may easily partition your network into query domains. However, one important thing here – this requires well-planned hierarchical addressing, based on the Core-Edge model. Sending a default route to isolated stub domain could be considered an extreme case of summarization and is very effective. You may filter EIGRP routes at any point using distribute-lists, route-maps etc. As soon as a route is filtered, the next-hop router will not learn it. When a query propagates to the next-hop, it will stop and return back. The use of route filtering is probably not as popular as route summarization, but could be used in some situations when you want to reduce the overall amount of queries but want to retain some routing information. In general, using proper route summarization should be enough. EIGRP processes run independently from each other, and queries from one system don’t leak into another. However, if redistribution is configured between two processes a behavior similar to query leaking is observed. Consider that router R runs EIGRP processes for AS1 and AS2 with mutual redistribution configured between the two processes. Assuming that a query from AS1 reaches R and bounces back, R is supposed to remove the route from the routing table. This in effect will trigger route removal from AS2 topology table, as redistribution is configured. Immediately after this R will originate a query into AS2, as the prefix becomes active. The query will travel across AS2 per the normal query propagation rules and eventually R will learn all replies and become passive for the prefixes. It’s even possible for R to learn the path to the lost prefix via AS2 and re-inject it back into AS1 if the network topology permits that. As per the regular query propagation rules, you may use prefix summarization when redistributing routes to limit the query scope.
Markdown
UTF-8
2,727
3.3125
3
[ "MIT" ]
permissive
# {%= name %} {%= badge("fury") %} > {%= description %} Also see [expand-object][], for doing the reverse of this library. ## Install {%= include("install-npm", {save: true}) %} ## Usage ```js var collapse = require('{%= name %}'); collapse({a: {b: {c: [1, 2, 3]}}}) //=> 'a.b.c:1,2,3' ``` Re-expand a collapsed string with [expand-object]: ```js var expand = require('expand-object'); //=> {a: {b: {c: [1, 2, 3]}}} ``` ### collapse an object ```js collapse({a: 'b'}) //=> 'a:b' expand('a:b') //=> {a: 'b'} ``` ### collapse objects with number values ```js collapse({a: 0}) //=> 'a:0' collapse({a: 1}) //=> 'a:1' expand('a:0') //=> {a: 0} expand('a:1') //=> {a: 1} ``` ### collapse objects with boolean values ```js collapse({a: false}) //=> 'a:false' collapse({a: true}) //=> 'a:true' expand('a:false') //=> {a: false} expand('a:true') //=> {a: true} ``` ### collapse array with boolean values ```js collapse({a: [1, 2, 3]}) //=> 'a:1,2,3' collapse({a: {b: [1, 2, 3]}, c: 'd'}) //=> 'a.b:1,2,3|c:d' expand('a:1,2,3') //=> {a: [1, 2, 3]} expand('a.b:1,2,3|c:d') //=> {a: {b: [1, 2, 3]}, c: 'd'} ``` ### collapse nested objects with boolean values ```js collapse({a: {b: true}}) //=> 'a.b:true' collapse({a: {b: [true]}}) //=> 'a.b:true,' collapse({a: {b: [true, false]}}) //=> 'a.b:true,false' collapse({a: {b: [true, false], c: {d: 'e'}}}) //=> 'a.b:true,false|a.c.d:e' expand('a.b:true') //=> {a: {b: true}} expand('a.b:true') //=> {a: {b: true}} expand('a.b:true,') //=> {a: {b: [true]}} expand('a.b:true,false') //=> {a: {b: [true, false]}} expand('a.b:true,false|a.c.d:e') //=> {a: {b: [true, false], c: {d: 'e'}}} ``` ### collapse complex objects ```js collapse({a: {b: 'c', d: 'e'}, f: 'g'}) //=> 'a.b:c|a.d:e|f:g' collapse({a: 'b', c: 'd', e: {f: 'g', h: 'i', j: {k: {l: 'm'}}}}) //=> 'a:b|c:d|e.f:g|e.h:i|e.j.k.l:m' collapse({a: 'b', c: 'd', e: {f: 'g', h: ['i', 'j', 'k']}}) //=> 'a:b|c:d|e.f:g|e.h:i,j,k' collapse({a: 'b', c: 'd', e: {f: 'g', h: ['i', 'j', 'k', {one: 'two'}]}}) //=> 'a:b|c:d|e.f:g|e.h:i,j,k,one:two' expand('a.b:c|a.d:e|f:g') //=> {a: {b: 'c', d: 'e'}, f: 'g'} expand('a:b|c:d|e.f:g|e.h:i|e.j.k.l:m') //=> {a: 'b', c: 'd', e: {f: 'g', h: 'i', j: {k: {l: 'm'}}}} expand('a:b|c:d|e.f:g|e.h:i,j,k') //=> {a: 'b', c: 'd', e: {f: 'g', h: ['i', 'j', 'k']}} expand('a:b|c:d|e.f:g|e.h:i,j,k,one:two') //=> {a: 'b', c: 'd', e: {f: 'g', h: ['i', 'j', 'k', {one: 'two'}]}} ``` ## Related projects {%= related(Object.keys(dependencies)) %} ## Running tests {%= include("tests") %} ## Contributing {%= include("contributing") %} ## Author {%= include("author") %} ## License {%= copyright() %} {%= license() %} *** {%= include("footer") %} {%= reflinks(['expand-object']) %}
Java
UTF-8
629
1.875
2
[ "MIT" ]
permissive
package com.virus.pt.db.service.impl; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.virus.pt.db.dao.RoleDao; import com.virus.pt.db.service.RoleService; import com.virus.pt.model.dataobject.Role; import org.springframework.stereotype.Service; import java.util.List; /** * @author intent * @version 1.0 * @date 2020/1/20 3:58 下午 * @email zzy.main@gmail.com */ @Service public class RoleServiceImpl extends ServiceImpl<RoleDao, Role> implements RoleService { @Override public List<Role> getByUserAuthId(long userAuthId) { return baseMapper.selectByUserAuthId(userAuthId); } }
C
UTF-8
1,280
3.453125
3
[]
no_license
#include"http_define.h" /* * 사용 API : memchr(읽을 버퍼 시작 포인터, 검색할 문자, 버퍼 총 길이), memchr을 이용하여 첫 포인터부터 기준문자까지의 길이를 구해 반환하는 함수 매개 변수 : char * start_line, int full_length, int parse_std_word 반환값 : int parsed_thing_length , 실패 시 -1, 문자 체크 NULL값은 -2로 체크*/ int get_parsing_length(char * start_line, int full_length, int parse_std_word) { char * end_of_element = NULL; char * error_msg = "ERROR"; int parsed_thing_length = 0; if ( start_line == NULL ){ printf("매개 변수 전달 에러입니다.(start_line)\n"); return -1; } if ( full_length <= 0 ){ printf("매개변수 전달 에러입니다.(full_length)\n"); return -1; } if ( parse_std_word <= 0 ){ printf("매개 변수 전달 에러입니다.(parse_std_word)\n"); return -1; } end_of_element = memchr(start_line, parse_std_word, full_length); if ( end_of_element == NULL ){ printf("지정문자를 찾을 수 없습니다. 함수 종료.\n"); return ERROR_MEMCHR; } parsed_thing_length = end_of_element - start_line; return parsed_thing_length; }
JavaScript
UTF-8
427
2.765625
3
[]
no_license
const initialState = { monster: 100, hero: 100, }; export default function healthReducer(state = initialState, action) { switch (action.type) { case 'SET_HERO_HEALTH': return { ...state, hero: state.hero + action.payload, }; case 'SET_MONSTER_HEALTH': return { ...state, monster: state.monster + action.payload, }; default: return state; } }
Java
UTF-8
1,488
2.90625
3
[]
no_license
import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.*; public class Login extends JFrame implements ActionListener{ JButton b1,b2,b3; JLabel l1; public Login(){ super("Alpha Bank"); JPanel panel = new JPanel(); setSize(700,700); b1=new JButton("Login"); b2=new JButton("Create Account"); b3=new JButton("Find my account"); l1=new JLabel("Hi,Welcome to Alpha Bank!"); b1.setBounds(200,250,300,30); b2.setBounds(200,350,300,30); b3.setBounds(200,450,300,30); l1.setBounds(200,150,300,40); panel.add(b1); panel.add(b2); panel.add(b3); panel.add(l1); add(b1); add(b2); add(b3); add(l1); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); this.getContentPane().add(panel); setLocationRelativeTo(null); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); } public void actionPerformed(ActionEvent e){ if(e.getSource()==b1){ dispose(); new LoginUI(); } if(e.getSource()==b2){ dispose(); new createUI(); } if(e.getSource()==b3){ dispose(); new findMyAccUI(); } } public static void main(String args[]){ new Login(); } }
C#
UTF-8
2,756
2.6875
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Threading; using System.Timers; using DatadogStatsD.Telemetering; using DatadogStatsD.Ticking; using DatadogStatsD.Transport; namespace DatadogStatsD.Metrics { /// <summary> /// <see cref="Gauge"/> measures the value of a metric at a particular time. /// </summary> /// <remarks>Documentation: https://docs.datadoghq.com/developers/metrics/types?tab=gauge#metric-types</remarks> public class Gauge : Metric { private readonly ITimer _tickTimer; private readonly Func<double>? _evaluator; private double _value = double.NaN; // NaN indicates that no value was recorded. internal Gauge(ITransport transport, ITelemetry telemetry, ITimer tickTimer, string metricName, Func<double>? evaluator, IList<KeyValuePair<string, string>>? tags) : base(transport, telemetry, metricName, MetricType.Gauge, 1.0, tags) { _tickTimer = tickTimer; _evaluator = evaluator; _tickTimer.Elapsed += OnTick; } /// <summary> /// Updates the value of the current <see cref="Gauge"/> instance. The value will be used for the next datapoint /// of this gauge over the one returned by the evaluator function. /// </summary> /// <param name="value">The value.</param> /// <exception cref="ArgumentException"><paramref name="value"/> is NaN.</exception> public void Update(double value) { ThrowHelper.ThrowIfNaN(value); Interlocked.Exchange(ref _value, value); } /// <summary> /// Break the bond between the <see cref="Count"/> and the <see cref="DogStatsD"/>. Not calling this method /// will result in CPU/Memory leak. /// </summary> public override void Dispose() { _tickTimer.Elapsed -= OnTick; OnTick(null, null); // flush } private void OnTick(object? _, ElapsedEventArgs? __) { double value = Interlocked.Exchange(ref _value, double.NaN); if (!double.IsNaN(value)) // If a value was recorded (using Record) since the last tick { Submit(value); return; } if (_evaluator == null) { // Don't send anything if no evaluator was specified and the Record method wasn't called return; } try { value = _evaluator(); } catch { // Don't send anything if the evaluator threw. return; } Submit(value); } } }
PHP
UTF-8
1,083
2.578125
3
[]
no_license
<?php header("Access-Control-Allow-Origin: *"); include "conn.php"; $role = isset($_POST['role']) ? $_POST['role'] : ""; if ($role=='admin' || $role=='user'){ $sql = "SELECT id, email, nama, role, created_at FROM users where role=?"; $stmt = $conn->prepare($sql); $stmt->bind_param('s', $role); $stmt->execute(); } else { $sql = "SELECT id, email, nama, role, created_at FROM users"; $stmt = $conn->prepare($sql); $stmt->execute(); } $result = $stmt->get_result(); if ($result->num_rows > 0) { $data = array(); $i = 0; while ($row = $result->fetch_assoc()) { $data[$i]['id'] = stripslashes($row['id']); $data[$i]['email'] = stripslashes($row['email']); $data[$i]['nama'] = stripslashes($row['nama']); $data[$i]['role'] = stripslashes($row['role']); $data[$i]['created_at'] = stripslashes($row['created_at']); $i++; } echo json_encode($data); } else { header("HTTP/1.1 210 Failed"); echo "Unable to process your request, please try again"; } $stmt->close(); $conn->close(); ?>
Python
UTF-8
326
3.140625
3
[ "MIT" ]
permissive
class Parking: def __init__(self, link, type_): self.link = link allowed_parking_types = ["parallel", "angle", "reverse-angle", "perpendicular"] if type_ not in allowed_parking_types: raise ValueError("Parking type must be from %s" % (allowed_parking_types)) self.type_ = type_
Markdown
UTF-8
5,938
2.890625
3
[ "MIT", "CC-BY-3.0", "CC-BY-4.0" ]
permissive
--- title: Host a single-page site description: Learn how to host a simple single-page website on the decentralized web using IPFS. --- # Host a single-page website A great way to get to know IPFS is to use it to host a simple, single-page website. Here's a step-by-step guide to doing just that. ::: tip We've put together a series of tutorials to walk you through hosting a full website on IPFS. [Take a look!](websites-on-ipfs/single-page-website.md) ::: ## Create your site Assume you have a static website in a directory `mysite`. In order to publish it as a site, [install IPFS](../install/README.md) and make sure your IPFS daemon is running: ```bash $ ipfs daemon ``` Then add the directory with your website: ```bash $ ls mysite img index.html $ ipfs add -r mysite added QmcMN2wqoun88SVF5own7D5LUpnHwDA6ALZnVdFXhnYhAs mysite/img/spacecat.jpg added QmS8tC5NJqajBB5qFhcA1auav14iHMnoMZJWfmr4k3EY6w mysite/img added QmYh6HbZhHABQXrkQZ4aRRSoSa6bb9vaKoHeumWex6HRsT mysite/index.html added QmYeAiiK1UfB8MGLRefok1N7vBTyX8hGPuMXZ4Xq1DPyt7 mysite/ ``` The last hash, next to the folder name, `mysite/` is the one to remember, call it `$SITE_CID` for now. You can test it out locally by opening `http://localhost:8080/ipfs/$SITE_CID` in a browser or with `wget` or `curl` from the command line. To view it from another ipfs node, you can try `http://gateway.ipfs.io/ipfs/$SITE_CID` in a browser. This will work from a browser on another device, inside or outside the network where you added the site's file. Those hashes are difficult to remember. Let's look at some ways to get rid of them. ## Edit your DNS records Assume you have the domain name `your.domain` and can access your registrar's control panel to manage DNS entries for it. Create a DNS TXT record ([DNSLink](../concepts/dnslink.md)), with the key `your.domain.` and the value `dnslink=/ipfs/$SITE_CID` where `$SITE_CID` is the value from the section above. Once you've created that record, and it has propagated you should be able to find it. ```bash $ dig +noall +answer TXT your.domain your.domain. 60 IN TXT "dnslink=/ipfs/$SITE_CID" ``` Now you can view your site at `http://localhost:8080/ipns/your.domain`. You can also try this on the gateway at `http://gateway.ipfs.io/ipns/your.domain`. More questions about DNSLink? Check out the [DNSLink website](http://dnslink.io/) for tutorials, examples, and FAQs. ## Use IPNS Each time you change your website, you will have to republish it, update the DNS TXT record with the new value of `$SITE_CID` and wait for it to propagate. You can get around that limitation by using IPNS, the [InterPlanetary Naming System](../concepts/ipns.md). You might have noticed `/ipns/` instead of `/ipfs/` in the updated links in the previous section. The IPNS is used for mutable content in the IPFS network. It's relatively easy to use, and will allow you to change your website without updating the DNS record every time. To enable the IPNS for your content, run the following command, where `$SITE_CID` is the hash value from the first step. ```bash $ ipfs name publish $SITE_CID Published to $PEER_ID: /ipfs/$SITE_CID ``` You will need to note and save that value of `$PEER_ID` for the next steps. Load the URLs `http://localhost:8080/ipns/$PEER_ID` and `http://gateway.ipfs.io/ipns/$PEER_ID` to confirm this step. Return to your registrar's control panel, change the DNS TXT record with the key of `your.domain` to `dnslink=/ipns/$PEER_ID`, wait for that record to propagate, and then try the URLs `http://localhost:8080/ipns/your.domain` and `http://gateway.ipfs.io/ipns/your.domain`. **Note:** When using IPNS to update websites, assets may be loaded from two different resolved hashes while the update propagates. This may result in outdated URLs or missing assets until the update has completely propagated. ## Point your domain to IPFS You now have a website on ipfs/ipns, but your visitors can't access it at `http://your.domain`. What we can do is have requests for `http://your.domain` resolved by an IPFS gateway daemon. Return to your registrar's control panel and add an A record with key of `your.domain` and value of the IP address of an ipfs daemon that listens on port 80 for HTTP requests (such as `gateway.ipfs.io`). If you don't know the IP address of the daemon you plan to use, you can find it using the command like: ```bash $ nslookup gateway.ipfs.io ``` 1. Note the IP addresses returned. 2. Create an A record for each IPv4 address (e.g. `209.94.90.1` for ipfs.io). 3. Create an AAAA record for each IPv6 address (e.g. use `2602:fea2:2::1` for ipfs.io). Note: The ipfs.io gateway IP addresses won't change, so you can set them and forget them. If you use a custom gateway where you don't control the IP address and they could change you may need to re-check them periodically and update your DNS records if they do. Visitors' browsers will send `your.domain` in the Host header of their requests. The ipfs gateway will recognize `your.domain`, look up the value of the DNS TXT for your domain, then serve the files in `/ipns/your.domain/` instead of `/`. If you point `your.domain`'s A and AAAA record to the IP addresses of `gateway.ipfs.io`, and then wait for the DNS to propagate, then anyone should be able to access your ipfs-hosted site without any extra configuration at `http://your.domain`. ## Use CNAMEs Alternatively, it is possible to use CNAME records to point at the DNS records of the gateway. This way, IP addresses of the gateway are automatically updated. However you will need to change the key for the TXT record from `your.domain` to `_dnslink.your.domain`. So by creating a CNAME for `your.domain` to `gateway.ipfs.io` and adding a `_dnslink.your.domain` record with `dnslink=/ipns/<your peer id>` you can host your website without explicitly referring to IP addresses of the ipfs gateway.
Python
UTF-8
27,937
3
3
[ "MIT" ]
permissive
import drawSvg as draw from matplotlib import cm,colors import pycatflow as pcf import math import copy debug_legend = False class Node: def __init__(self, index, col_index, x, y, size, value, width, label, category): self.x = x self.index = index self.col_index = col_index self.y = y self.size = size self.value = value self.width = width self.label = label self.category = category def nodify(data, sort_by="frequency"): """ Takes data and creates a list containing information about the nodes for the graph. Parameters: data (dict): output of the read_file/read functions, a dictionary with keys the temporal data, and values a dictionary with keys of the item and values or the frequency of the item or a tuple with the frequency and the category sort_by (str): "frequency" or "alphabetical" or "category", defaults to "frequency" Returns: (list): A list containing information about the nodes for the graph """ d = {} if sort_by == "frequency": for item in data.items(): if type(item[1][next(iter(item[1]))]) == tuple: d[item[0]] = {k: v for k, v in sorted(item[1].items(), key=lambda x: (-x[1][0], x[0]), reverse=False)} else: d[item[0]] = {k: v for k, v in sorted(item[1].items(), key=lambda x: (-x[1], x[0]), reverse=False)} elif sort_by == "category": for item in data.items(): d[item[0]] = {k: v for k, v in sorted(item[1].items(), key=lambda x: (x[1][1], x[0]), reverse=False)} elif sort_by == "alphabetical": for x, y in data.items(): d[x] = {k: v for k, v in sorted(y.items())} labels = [list(x[1].keys()) for x in d.items()] values = [[y[0] if type(y) == tuple else y for y in x[1].values()] for x in d.items()] categories = [[y[1] if type(y) == tuple else "null" for y in x[1].values()] for x in d.items()] headers = list(d.keys()) node_x = 0 count = 0 count2 = 0 nodes = [] sequence = {} for l, v, s in zip(labels, values, categories): if count2 < len(labels): count2 += 1 for x, y, z in zip(l, v, s): nodes.append(Node(count, count2, 0, 0, y, y, 1, x, z)) count += 1 for n in nodes: if n.label in sequence.keys(): sequence[n.label].append(n.index) else: sequence[n.label] = [] sequence[n.label].append(n.index) return [headers, nodes, sequence] def genSVG(nodes, spacing, node_size, width=None, height=None, minValue=1, maxValue=10, node_scaling="linear", connection_type="semi-curved", color_startEnd=True, color_categories=True, nodes_color="gray", start_node_color="green", end_node_color="red", palette=None, show_labels=True, label_text="item", label_font="sans-serif", label_color="black", label_size=5, label_shortening="clip", label_position="nodes", line_opacity=0.5, line_stroke_color="white", line_stroke_width=0.5, line_stroke_thick=0.5, legend=True): """ Generates an SVG from data loaded via the read functions. Parameters: nodes (list): The output of nodify(), a list containingg information about the nodes for the graph spacing (int): the space between the nodes, defaults to 50 node_size (int): default node size, defauults to 10 width (int): width of the visualization, defaults to None, if None they are generated from the size of the nodes, if they are specified the nodes will be rescaled to fit the space height (int): height of the visualization, defaults to None, if None they are generated from the size of the nodes, if they are specified the nodes will be rescaled to fit the space minValue (int): min size of a node , defaults to 1 maxValue (int): max size of a node, defaults to 10 node_scaling (str): "linear" or ... " ", defaults to "linear" connection_type (str): "semi-curved" or "curved" or "linear", defaults to "semi-curved" color_startEnd (bool) : if True it marks the colors of the first and last appearence of a category, defaults to True color_categories (bool): if True the nodes and the lines are colored depending by the subcategory, deafults to True nodes_color (str): the color of the nodes if the previous two options are false, defaults to "gray", used also for the lines and for the middle nodes in case of startEnd option start_node_color (str): Defaults to "green" end_node_color (str): Defaults to "red" palette (tuple): a tuple with the name of the matplotlib palette and the number of colors ("viridis",12), defaults to None show_labels (bool): Defaults to True label_text (str): "item" shows the category, defaults to "item", "item_count" shows the category and the frequency, "item_category" shows the category and the subcategory label_font (str): Defaults to "sans-serif" label_color (str): Defaults to "black" label_size (int): Defaults to 5 label_shortening (str): defaults to "clip", "clip" cuts the text when it overlaps the margin, "resize" changes the size of the font to fit the available space, "new_line" wraps the text when it overlaps the margin and it rescale the size if the two lines overlaps the bottom margin label_position (str): defaults to "nodes", "nodes" shows a label for each node, "start_end" shows a label for the first and last node of a sequence line_opacity (float): Defaults to 0.5 line_stroke_color (str): Defaults to "white" line_stroke_width (float): Defaults to 0.5 line_stroke_thick (float): Defaults to 0.5 legend (bool): If True a Legend is included, defaults to True Returns: (drawSvg.drawing.Drawing): The finished graph """ headers = nodes[0] nodes2 = copy.deepcopy(nodes[1]) sequence = nodes[2] if start_node_color == "green": start_node_color = "#4BA167" if end_node_color == "red": end_node_color = "#A04B83" if nodes_color == "gray": nodes_color = "#EAEBEE" # Resizing of the nodes in relation to the canvas size and to the scaling option m = max([v.value for v in nodes[1]]) new_nodes = [] if width is not None: dx = (width-(spacing*2))/len(headers) spacing2 = 2*(dx/3) node_size = dx/3 else: spacing2 = spacing if height is not None: l_col_index = [x.col_index for x in nodes2] l_col_index_max = max([l_col_index.count(y.col_index) for y in nodes2]) sum_values = sum([x.value for x in nodes2 if l_col_index.count(x.col_index) == l_col_index_max]) max_values = max([x.value for x in nodes2 if l_col_index.count(x.col_index) == l_col_index_max]) if node_scaling == "linear": dy = ((height-(spacing*2)-(spacing/5))*max_values)/(sum_values+((maxValue/2)*l_col_index_max)) else: dy = ((height-(spacing*2)-(spacing/5))*max_values)/(sum_values+((max_values/2)*l_col_index_max)) spacingy = dy/3 maxValue = 2*(dy/3) else: spacingy = spacing/5 node_x = 0 for n in nodes2: n.width = node_size if n.col_index != nodes2[n.index-1].col_index and n.index > 0: node_x += node_size n.x += node_x if node_scaling == "linear": n.size = (((n.value+1)*maxValue)/m)+minValue elif node_scaling == "log": n.size = (((maxValue-minValue)/math.log(m))*math.log(n.value))+minValue new_nodes.append(n) # positioning of the nodes on the canvas (x,y) n_x_spacing = spacing n_y_spacing = spacing+spacingy points = [] for n in new_nodes: if n.index > 0 and n.col_index == new_nodes[n.index-1].col_index: n_y_spacing += spacingy+n.size else: n_y_spacing = spacing+spacingy+n.size if n.index > 0 and n.col_index != new_nodes[n.index-1].col_index: n_x_spacing += spacing2 points.append(pcf.Node(n.index, n.col_index, n.x + n_x_spacing, n.y + n_y_spacing, n.size, n.value, n.width, n.label, n.category)) # sizing of the canvas if width is None and height is None: width = spacing*4+max([x.x for x in points]) height = spacing * 4 + max([x.y for x in points]) + ((sum([x.size for x in points]) / len(points)) * len(set([x.category for x in points]))) elif height is None: height = spacing * 4 + max([x.y for x in points]) + ((sum([x.size for x in points]) / len(points)) * len(set([x.category for x in points]))) elif width is None: width = spacing * 4 + max([x.x for x in points]) # COLORS if palette is not None: palette = cm.get_cmap(palette[0], palette[1]).colors count = 0 category_colors = {} for e in set([n.category for n in points]): if count < len(palette): count += 1 category_colors[e] = colors.to_hex(palette[count]) else: # DEFAULT PALETTE: the number of colors is set in relation to the length of the category list palette = cm.get_cmap("tab20c", len(set([n.category for n in points])) + 1).colors count = 0 category_colors = {} for e in set([n.category for n in points]): if count < len(palette)-1: count += 1 category_colors[e] = colors.to_hex(palette[count]) d = draw.Drawing(width, height, displayInline=True) r = draw.Rectangle(0, 0, width, height, stroke_width=2, stroke='black', fill="white") d.append(r) # headers h_x_shift = [points[0].x] for x in points: if x.x != points[x.index-1].x and x.index > 0: h_x_shift.append(x.x) n2 = h_x_shift[1]-h_x_shift[0] for h, x in zip(headers, h_x_shift): l = label_size if label_shortening == "resize": while len(h)*(l/2) > n2+points[0].size-(n2/8) and l > 1: if x != max(h_x_shift): l -= 1 else: break d.append(draw.Text(h, x=x, y=height - spacing, fontSize=l, font_family=label_font, fill=label_color)) elif label_shortening == "clip": clip = draw.ClipPath() clip.append(draw.Rectangle(x, height - spacing, n2, label_size)) d.append(draw.Text(h, x=x, y=height - spacing, fontSize=l, font_family=label_font, clip_path=clip, fill=label_color)) elif label_shortening == "new_line": if len(h)*(label_size/2) > n2+points[0].size-(n2/8): margin = int((n2+points[0].size-(n2/8))/(label_size/2)) txt = [h[x:x+margin] for x in range(0, len(h), margin)] while len(txt)*l > (l+n2/5) and l > 1: l -= 1 else: txt = h d.append(draw.Text(txt, x=x, y=height-spacing, fontSize=l, font_family=label_font, fill=label_color)) # lines for n in sequence.items(): if len(n[1]) > 1: for k in n[1][:-1]: if color_categories: color = category_colors[points[k].category] else: color = nodes_color if connection_type.lower() == "semi-curved": p = draw.Path(fill=color, stroke=line_stroke_color, opacity=line_opacity, stroke_width=line_stroke_width) p.M(points[k].x + points[k].width, height - points[k].y) p.L(points[k].x + points[k].width, height - points[k].y + points[k].size) if points[k].y == points[n[1][n[1].index(k)+1]].y: p.L(points[n[1][n[1].index(k)+1]].x, height - points[k].y + points[k].size) p.L(points[n[1][n[1].index(k)+1]].x, height - points[k].y) else: xMedium = ((points[n[1][n[1].index(k)+1]].x-(points[k].x+points[k].width))/2)+(points[k].x+points[k].width) yMedium = (((height - points[k].y + points[k].size) - (height - points[n[1][n[1].index(k) + 1]].y + points[k].size)) / 2) + (height - points[n[1][n[1].index(k) + 1]].y) yMedium2 = (((height - points[k].y) - (height - points[n[1][n[1].index(k) + 1]].y)) / 2) + (height - points[n[1][n[1].index(k) + 1]].y) p.Q(points[k].x + points[k].width + (spacing/2), height - points[k].y + points[k].size, xMedium + line_stroke_thick, yMedium + points[k].size) p.T(points[n[1][n[1].index(k)+1]].x, height - points[n[1][n[1].index(k) + 1]].y + points[n[1][n[1].index(k) + 1]].size) p.L(points[n[1][n[1].index(k)+1]].x, height - points[n[1][n[1].index(k) + 1]].y) p.Q(points[n[1][n[1].index(k)+1]].x - (spacing/2), height - points[n[1][n[1].index(k) + 1]].y, xMedium - line_stroke_thick, yMedium2) p.T(points[k].x + points[k].width, height - points[k].y) p.Z() d.append(p) elif connection_type.lower() == 'curved': p = draw.Path(fill=color, stroke=line_stroke_color, opacity=line_opacity, stroke_width=line_stroke_width) size_start = points[k].size size_end = points[n[1][n[1].index(k) + 1]].size x1_start = points[k].x + points[k].width y1_start = height - points[k].y + size_start x1_end = points[n[1][n[1].index(k) + 1]].x y1_end = height - points[n[1][n[1].index(k) + 1]].y + size_end x2_start = x1_start y2_start = y1_start - size_start x2_end = x1_end y2_end = y1_end - size_end x_diff = x1_end - x1_start y_diff = y2_start - y1_end height_factor = 2 width_factor = 0 if points[k].y == points[n[1][n[1].index(k) + 1]].y: p.M(x1_start, y1_start) p.L(x2_start, y2_start) p.L(x2_end, y2_end) p.L(x1_end, y1_end) p.Z() d.append(p) pass else: p.M(x1_start, y1_start) cx1 = x1_end - (x_diff / 4 * 3) cy1 = y1_start ex1 = x1_end - (x_diff / 2) ey1 = y1_end + (y_diff / 2) p.Q(cx1, cy1, ex1, ey1) cx2 = x1_start + (x_diff / 4 * 3) cy2 = y1_end - (size_end / height_factor) p.Q(cx2, cy2, x1_end, y1_end) p.L(x2_end, y2_end) cx3 = (x2_end - (x_diff / 4)) cy3 = (y2_end - (size_end / height_factor)) ex3 = (x2_end + ((x1_start - x1_end) / 2) - width_factor) ey3 = (y2_end + (((y1_start - y1_end) / 2) - (((size_start + size_end) / 2)) / height_factor)) p.Q(cx3, cy3, ex3, ey3) cx4 = x2_start + (x_diff / 4) cy4 = y2_start p.Q(cx4, cy4, x2_start, y2_start) p.Z() d.append(p) elif connection_type.lower() == 'straight': p = draw.Path(fill=color, stroke=line_stroke_color, opacity=line_opacity, stroke_width=line_stroke_width) size_start = points[k].size size_end = points[n[1][n[1].index(k) + 1]].size x1_start = points[k].x + points[k].width y1_start = height - points[k].y x1_end = points[n[1][n[1].index(k) + 1]].x y1_end = height - points[n[1][n[1].index(k) + 1]].y x2_start = x1_start y2_start = y1_start + size_start x2_end = x1_end y2_end = y1_end + size_end p.M(x1_start, y1_start) p.L(x2_start, y2_start) p.L(x2_end, y2_end) p.L(x1_end, y1_end) p.Z() d.append(p) else: print('This connection type is not implemented.') raise KeyError # nodes # return points col_index_max = 0 for node in points: if node.col_index > col_index_max: col_index_max = node.col_index for node in points: if color_startEnd == True and color_categories == True: if node.label not in [n.label for n in points][:node.index]: color = start_node_color elif node.label not in [n.label for n in points][node.index+1:] and node.col_index < col_index_max: #and node.index<len(points): color = end_node_color else: color = category_colors[node.category] elif color_startEnd and not color_categories: if node.label not in [n.label for n in points][:node.index]: color = start_node_color elif node.label not in [n.label for n in points][node.index+1:] and node.col_index < col_index_max: #and node.index<len(points): color = end_node_color else: color = nodes_color elif not color_startEnd and color_categories: color = category_colors[node.category] elif not color_startEnd and not color_categories: color = nodes_color if node.label != '': r = draw.Rectangle(node.x, height - node.y, node.width, node.size, fill=color, stroke=color) #stroke="black" d.append(r) if show_labels: if label_text == "item": txt = node.label elif label_text == "item_count": txt = node.label+' ('+str(node.value)+')' elif label_text == "item_category": txt = node.label + ' (' + str(node.category) + ')' l = label_size if label_shortening == "resize": while len(txt)*(l/2)>spacing-(spacing/8): if node.x != max([n.x for n in points]) and l > 1: l -= 1 else: break elif label_shortening == "clip": clip = draw.ClipPath() clip.append(draw.Rectangle(node.x, height-node.y-(spacing/5), n2-(n2/8), node.size+2*(spacing/5))) elif label_shortening == "new_line": if len(txt)*(label_size/2) > n2-2*(n2/8): margin = int((n2-2*(n2/8))/(label_size/2)) txt = [txt[x:x+margin] for x in range(0, len(txt), margin)] while len(txt)*l > node.size+2*(spacing/8) and l > 1: l -= 1 label_pos_y = height - node.y + (node.size/2) - (l/2) if label_position == "start_end": if node.label not in [n.label for n in points][:node.index] or node.label not in [n.label for n in points][node.index+1:] and node.index < len(points) and node.x != max([n.x for n in points]): if label_shortening == "clip": label = draw.Text(txt, x=node.x+node.width+(n2/8), y=label_pos_y, fontSize=l, font_family=label_font, fill=label_color, clip_path=clip) else: label = draw.Text(txt, x=node.x-(n2/8), y=label_pos_y, fontSize=l, font_family=label_font, fill=label_color, text_anchor="end") elif label_position == "nodes": if label_shortening == "clip": label = draw.Text(txt, x=node.x+node.width+(n2/8), y=label_pos_y, fontSize=l, font_family=label_font, fill=label_color, clip_path=clip) else: label = draw.Text(txt, x=node.x + node.width+(n2/8), y=label_pos_y, fontSize=l, font_family=label_font, fill=label_color) d.append(label) # Add legend to canvas if color_categories and legend: offset = 5 # Alternative: offset = spacing spacing_bottom = 5 # Alternative: spacing_bottom = spacing symbol_size = sum([x.size for x in points])/len(points) legend_height = (symbol_size+offset) * len(category_colors) legend_header_y = legend_height + symbol_size + spacing_bottom + (offset) legend_header = draw.Text("Legend", x=points[0].x, y=legend_header_y, fontSize=label_size, font_family=label_font, fill=label_color) if debug_legend: print('Legend Title') print('legend_height: {}'.format(legend_height)) print('legend_header_y: {}'.format(legend_header_y)) print('points[0].x: {}'.format(points[0].x)) print('legend_header_y'.format(legend_header_y)) print() d.append(legend_header) symbol_y_shift = 0 for e in category_colors.items(): legend_label_y = spacing_bottom + legend_height + (symbol_size/2) - (label_size/2) - offset - symbol_y_shift symbol = draw.Rectangle(points[0].x, spacing_bottom+legend_height-offset-symbol_y_shift, points[0].width, symbol_size, fill=e[1], stroke=e[1]) #stroke="black" if debug_legend: print(e) print('points[0].x: {}'.format(points[0].x)) print('spacing_bottom+legend_height-offset-symbol_y_shift: {}'.format(spacing_bottom+legend_height-offset-symbol_y_shift)) print('points[0].width: {}'.format(points[0].width)) print('symbol_size: {}'.format(symbol_size)) print() name = draw.Text(e[0], x=points[0].x+node.width+(n2/12), y=legend_label_y, fontSize=label_size, fill=label_color) d.append(symbol) d.append(name) if spacing_bottom+legend_height-(offset)-symbol_y_shift > spacing_bottom: symbol_y_shift += offset+symbol_size else: symbol_y_shift = 0 return d def visualize(data, spacing=50, node_size=10, width=None, height=None, minValue=1, maxValue=10, node_scaling="linear", connection_type="semi-curved", color_startEnd=True, color_categories=True, nodes_color="gray", start_node_color="green", end_node_color="red", palette=None, show_labels=True, label_text="item", label_font="sans-serif", label_color="black", label_size=5, label_shortening="clip", label_position="nodes", line_opacity=0.5, line_stroke_color="white", line_stroke_width=0.5, line_stroke_thick=0.5, legend=True, sort_by="frequency"): """ Generates an SVG from data loaded via the read functions. Parameters: data (dict): output of the read_file/read functions, a dictionary with keys the temporal data, and values a dictionary with keys of the item and values or the frequency of the item or a tuple with the frequency and the category spacing (int): the space between the nodes, defaults to 50 node_size (int): default node size, defauults to 10 width (int): width of the visualization, defaults to None, if None they are generated from the size of the nodes, if they are specified the nodes will be rescaled to fit the space height (int): height of the visualization, defaults to None, if None they are generated from the size of the nodes, if they are specified the nodes will be rescaled to fit the space minValue (int): min size of a node , defaults to 1 maxValue (int): max size of a node, defaults to 10 node_scaling (str): "linear" or ... " ", defaults to "linear" connection_type (str): "semi-curved" or "curved" or "linear", defaults to "semi-curved" color_startEnd (bool) : if True it marks the colors of the first and last appearence of a category, defaults to True color_categories (bool): if True the nodes and the lines are colored depending by the subcategory, deafults to True nodes_color (str): the color of the nodes if the previous two options are false, defaults to "gray", used also for the lines and for the middle nodes in case of startEnd option start_node_color (str): Defaults to "green" end_node_color (str): Defaults to "red" palette (tuple): a tuple with the name of the matplotlib palette and the number of colors ("viridis",12), defaults to None show_labels (bool): Defaults to True label_text (str): "item" shows the category, defaults to "item", "item_count" shows the category and the frequency, "item_category" shows the category and the subcategory label_font (str): Defaults to "sans-serif" label_color (str): Defaults to "black" label_size (int): Defaults to 5 label_shortening (str): defaults to "clip", "clip" cuts the text when it overlaps the margin, "resize" changes the size of the font to fit the available space, "new_line" wraps the text when it overlaps the margin and it rescale the size if the two lines overlaps the bottom margin label_position (str): defaults to "nodes", "nodes" shows a label for each node, "start_end" shows a label for the first and last node of a sequence line_opacity (float): Defaults to 0.5 line_stroke_color (str): Defaults to "white" line_stroke_width (float): Defaults to 0.5 line_stroke_thick (float): Defaults to 0.5 legend (bool): If True a Legend is included, defaults to True sort_by (str): "frequency" or "alphabetical" or "category", defaults to "frequency" Returns: (drawSvg.drawing.Drawing): The finished graph """ nodes = pcf.nodify(data, sort_by=sort_by) viz = genSVG(nodes, spacing, node_size, width=width, height=height, minValue=minValue, maxValue=maxValue, node_scaling=node_scaling, connection_type=connection_type, color_startEnd=color_startEnd, color_categories=color_categories, nodes_color=nodes_color, start_node_color=start_node_color, end_node_color=end_node_color, palette=palette, show_labels=show_labels, label_text=label_text, label_font=label_font, label_color=label_color, label_size=label_size, label_shortening=label_shortening, label_position=label_position, line_opacity=line_opacity, line_stroke_color=line_stroke_color, line_stroke_width=line_stroke_width, line_stroke_thick=line_stroke_thick, legend=legend) return viz
Java
UTF-8
756
2.046875
2
[]
no_license
package cn.test.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.test.dao.TourDao; import cn.test.entity.Tour; public class QueryServlet extends HttpServlet { public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ response.setContentType("text/html;charset=utf-8"); request.setCharacterEncoding("utf-8"); List<Tour> list = new TourDao().queryAll(); request.setAttribute("list",list); request.getRequestDispatcher("index.jsp").forward(request,response); } }
PHP
UTF-8
2,925
3.125
3
[ "MIT" ]
permissive
<?php /** * The function returns the current ID. * Returns zero if no ID is stored. * @return integer - ID session. */ function GetID() { // Search current ID... if (isset($_COOKIE['CURRENT_ID'])) { $id = (int)$_COOKIE['CURRENT_ID'] + 1; // ...or returns zero } else { $id = 0; } // We issue results return $id; } /** * Session initialization function. * Searches saved session, producing a new * init or returns zero on failure. * @param $token - The values of the token. * @param $bot - Initialized bot. * @return string - ID bot session. */ function GetSession($token, $bot) { // Search the old session if (isset($_COOKIE['BOT_SESSION'])) { $session = $bot->session($_COOKIE['BOT_SESSION']); } else { // Open a new one $session = $bot->session(); SetCookie("BOT_SESSION", $session); } // We issue results if (isset($session)) { return $session; } else { return 0; } } /** * The function overrides the current ID to * the specified or the next. If any missing ID * returns the one. * @param $id - Current ID. * @return integer - Next ID. */ function SetID($id) { // Process the specified ID... if (isset($id)) { $id = $id + 1; // ...Or are saved... } elseif (isset($_COOKIE['CURRENT_ID'])) { $id = (int)$_COOKIE['CURRENT_ID'] + 1; // ...Or return one } else { $id = 1; } SetCookie('CURRENT_ID', $id, time()+300); // Save the result return $id; // We issue results } /** * Cleaning function of the parameter that is passed to it. * @param $type - Type cleansed. */ function ClearingCache($type) { switch ($type) { // Clear the cookies case 'cookies': foreach ($_COOKIE as $key => $value) { SetCookie($key, $value, time()-1000); } break; // Clear the POST case 'post': $_POST = array(); break; // ... default: break; } } /** * The function maintains a history of conversations, * using a database of cookie files. * @param $currentid - Message ID. * @param $textarea - Message text. * @param $type - Who said (Man / Bot). */ function SavingStories($currentid, $textarea, $type) { // We form an array with values $cookie = array( 'type' => $type, 'textarea' => $textarea, 'time' => time()); // Save by encoding in JSON-string SetCookie("TALK".$currentid, json_encode($cookie), time()+60); } /** * Function line formation. * @param $id - Variable Message ID. */ function ShowRecord($id) { for ($i=0; $i < $id; $i++) { if (isset($_COOKIE['TALK'.$i])) { $cookie = json_decode($_COOKIE['TALK'.$i], true); echo("<tr>"); echo("<td>".$cookie['type']."</td>"); echo("<td>".$cookie['textarea']."</td>"); echo("<td>".date("H:i:s", $cookie['time'])."</td>"); echo("</tr>"); } } } ?>
Java
UTF-8
231
1.726563
2
[]
no_license
package net.es.oscars.utils.config; public class ConfigException extends Exception { private static final long serialVersionUID = 1; // make -Xlint happy public ConfigException(String msg) { super(msg); } }
Markdown
UTF-8
2,440
2.8125
3
[ "MIT" ]
permissive
<h1 align="center">Savignano-Flex</h1> <div align="center"> Write JavaScript Flex styles and have them served in css. [![NPM Version](https://img.shields.io/npm/v/savignano-flex.svg?style=flat)](https://www.npmjs.com/package/savignano-flex) [![NPM Downloads](https://img.shields.io/npm/dm/savignano-flex.svg?style=flat)](https://npmcharts.com/compare/savignano-flex?minimal=true) [![CircleCI](https://img.shields.io/circleci/build/github/PaulSavignano/savignano-flex/master.svg)](https://circleci.com/gh/PaulSavignano/savignano-flex/tree/master) [![codecov.io](https://codecov.io/gh/PaulSavignano/savignano-flex/branch/master/graph/badge.svg)](https://codecov.io/gh/PaulSavignano/savignano-flex) [![BundleSize](https://img.shields.io/bundlephobia/minzip/savignano-flex.svg)](https://bundlephobia.com/result?p=savignano-flex) [![Dependencies](https://david-dm.org/PaulSavignano/savignano-flex/master/status.svg)](https://david-dm.org/PaulSavignano/savignano-flex/master) [![DevDependencies](https://david-dm.org/PaulSavignano/savignano-flex/master/dev-status.svg)](https://david-dm.org/PaulSavignano/savignano-flex/master?type=dev) [![PeerDependencies](https://david-dm.org/PaulSavignano/savignano-flex/master/peer-status.svg)](https://david-dm.org/PaulSavignano/savignano-flex/master?type=peer) [![Patreon](https://img.shields.io/badge/patreon-support%20the%20author-blue.svg)](https://www.patreon.com/PaulSavignano) </div> Savignano-Flex is a JavaScript library for styling user interfaces. * **Declarative:** Define the styles you need and enjoy the benefit of cached css without the cost of inline style redefinition. * **Flexible:** No pun intended. Props that do not have css definitions will be inline styled. You may also pass a style prop. Have a className you'd like incorporated? Pass in a className prop and have it concatenated. <br /> ## Installation ``` npm install savignano-flex ``` ## Usage Here is an example to get you started: ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import Flex from 'savignano-flex'; function App() { return ( <Flex alignItems="center" flexFlow="row wrap" justifyContent="center"> <p>This</p> <p>content</p> <p>is horizontal</p> </Flex> ); } ReactDOM.render(<App />, document.querySelector('#app')); ``` ## Examples [Codesandbox](https://codesandbox.io/s/savignano-flex-m2ovj?fontsize=14) ## Contributing - see CONTRIBUTING.md
Java
UTF-8
524
1.757813
2
[ "Apache-2.0" ]
permissive
package cloud.antelope.lingmou.di.component; import dagger.Component; import com.jess.arms.di.component.AppComponent; import cloud.antelope.lingmou.di.module.CarDepotSearchDeviceModule; import com.jess.arms.di.scope.FragmentScope; import cloud.antelope.lingmou.mvp.ui.fragment.CarDepotSearchDeviceFragment; @FragmentScope @Component(modules = CarDepotSearchDeviceModule.class, dependencies = AppComponent.class) public interface CarDepotSearchDeviceComponent { void inject(CarDepotSearchDeviceFragment fragment); }
C++
UTF-8
1,754
2.78125
3
[]
no_license
#ifndef PLAYER_CURRENCIES_H #define PLAYER_CURRENCIES_H #include <memory> #include <unordered_map> struct CharacterCurrency { int8 WinStreak; int8 TopWinStreak; float RankPoints; float TopRankPoints; time_t DailyQuestTimer; uint8 DailyQuestAmount; int32 KillingSpree; uint16 TotalUpgradeRank; void ModifyRankPoints(float value, Player* player = nullptr); void ModifyKillingSpree(int32 points); void ModifyTotalUpgradeRank(int32 amount); void ModifyWinStreak(Player* player, int32 points); void HandleDailyQuests(Player* player); void ReduceDailyAmount(); }; struct AccountCurrency { uint32 Account; int32 VP; int32 DP; uint32 ExtraMask; void ModifyVP(int value); void ModifyDP(int value); bool HasExtraMask(uint32 mask); void SetExtraMask(uint32 mask); uint32 GetDP() const { return DP; } uint32 GetVP() const { return VP; } void SaveData(); }; class TC_GAME_API CurrencyHandler { public: CurrencyHandler(); static CurrencyHandler* instance(); CharacterCurrency* GetCharacterCurrency(ObjectGuid guid); void LoadCharacterCurrencies(); void AddCharacterCurrency(ObjectGuid guid); void SaveCharacterCurrencies(ObjectGuid guid); const std::unordered_map<ObjectGuid, CharacterCurrency> &GetCharacterCurrencies() const { return m_CharacterCurrencies; } AccountCurrency* GetAccountCurrency(uint32 account); void LoadAccountCurrencies(); void AddAccountCurrencyData(uint32 account); private: std::unordered_map<ObjectGuid, CharacterCurrency> m_CharacterCurrencies; std::unordered_map<uint32, AccountCurrency> m_AccountCurrencies; }; #define sCurrencyHandler CurrencyHandler::instance() #endif
C++
UTF-8
9,600
2.859375
3
[ "Apache-2.0" ]
permissive
/* Copyright (c) 2017-2018 Origin Quantum Computing. All Right Reserved. Licensed under the Apache License 2.0 ComplexMatrix.h Author: Wangjing Created in 2018-8-31 Classes for matrix caculate */ #ifndef COMPLEXMATRIX_H #define COMPLEXMATRIX_H #include <iostream> #include <complex> #include <exception> #include <vector> #include <stdexcept> #include <initializer_list> #include "ComplexVector.h" USING_QPANDA template<size_t qubit_number, typename precision_t=double> class ComplexMatrix { typedef std::complex<precision_t> data_t; public: ComplexMatrix() { static_assert(qubit_number > 0, "qubitnum must > 0"); initialize(); } ComplexMatrix<qubit_number,precision_t>(const std::initializer_list<data_t> &args) { static_assert(qubit_number > 0, "qubitnum must > 0"); initialize(); size_t dimension = getDimension(); auto p = args.begin(); for (size_t i = 0; i < dimension; i++) { for (size_t j = 0; j < dimension; j++) { if ((i* dimension + j) < args.size()) { m_data[i][j] = p[i * dimension + j]; } } } } ComplexMatrix(const ComplexMatrix<qubit_number, precision_t>& other_matrix) { initialize(); size_t dimension = other_matrix.getDimension(); for (size_t i = 0; i < dimension; i++) { for (size_t j = 0; j < dimension; j++) { m_data[i][j] = other_matrix.getElem(i,j); } } } ComplexMatrix<qubit_number, precision_t>& operator=(const ComplexMatrix<qubit_number, precision_t>& other) { if (this == &other) { return *this; } size_t dimension = other.getDimension(); for (size_t i = 0; i < dimension; i++) { for (size_t j = 0; j < dimension; j++) { m_data[i][j] = other.getElem(i, j); } } return *this; } friend std::ostream& operator<<(std::ostream& out, const ComplexMatrix<qubit_number, precision_t>& mat) { size_t size = mat.getDimension(); for (size_t i = 0; i < size; i++) { for (size_t j = 0; j < size; j++) { out << mat.getElem(i, j) << "\t"; } out << "\n"; } return out; } const data_t& getElem(const size_t x, const size_t y) const { assert(x < getDimension() && y < getDimension()); return this->m_data[x][y]; } static ComplexMatrix<qubit_number, precision_t> GetIdentity() { ComplexMatrix<qubit_number, precision_t> matrix; size_t dimension = matrix.getDimension(); for (size_t i = 0; i < dimension; i++) { for (size_t j = 0; j < dimension; j++) { if (i == j) { matrix.setElem(i, j, 1); } } } return matrix; } ComplexMatrix<qubit_number, precision_t> dagger() { ComplexMatrix<qubit_number, precision_t> matrix; size_t dimension = getDimension(); for (size_t i = 0; i < dimension; i++) { for (size_t j = 0; j < dimension; j++) { matrix.setElem(i, j, std::conj(m_data[j][i])); } } return matrix; } friend ComplexMatrix<qubit_number, precision_t> operator+(const ComplexMatrix<qubit_number, precision_t> &a, const ComplexMatrix<qubit_number, precision_t> &b) { ComplexMatrix<qubit_number, precision_t> result; size_t dimension = a.getDimension(); for (size_t i = 0; i < dimension; i++) { for (size_t j = 0; j < dimension; j++) { data_t tmp = a.m_data[i][j] + b.m_data[i][j]; result.setElem(i, j, tmp); } } return result; } friend ComplexMatrix<qubit_number, precision_t> operator+(const data_t &a, const ComplexMatrix<qubit_number, precision_t> &b) { ComplexMatrix<qubit_number, precision_t> result; size_t dimension = b.getDimension(); for (size_t i = 0; i < dimension; i++) { for (size_t j = 0; j < dimension; j++) { data_t tmp = a + b.m_data[i][j]; result.setElem(i, j, tmp); } } return result; } friend ComplexMatrix<qubit_number, precision_t> operator+(const ComplexMatrix<qubit_number, precision_t> &a, const data_t &b) { ComplexMatrix<qubit_number, precision_t> result; size_t dimension = a.getDimension(); for (size_t i = 0; i < dimension; i++) { for (size_t j = 0; j < dimension; j++) { data_t tmp = a.m_data[i][j] + b; result.setElem(i, j, tmp); } } return result; } friend ComplexMatrix<qubit_number, precision_t> operator-(const ComplexMatrix<qubit_number, precision_t> &a, const ComplexMatrix<qubit_number, precision_t> &b) { ComplexMatrix<qubit_number, precision_t> result; size_t dimension = a.getDimension(); for (size_t i = 0; i < dimension; i++) { for (size_t j = 0; j < dimension; j++) { data_t tmp = a.m_data[i][j] - b.m_data[i][j]; result.setElem(i, j, tmp); } } return result; } friend ComplexMatrix<qubit_number, precision_t> operator-(const data_t &a, const ComplexMatrix<qubit_number, precision_t> &b) { ComplexMatrix<qubit_number, precision_t> result; size_t dimension = b.getDimension(); for (size_t i = 0; i < dimension; i++) { for (size_t j = 0; j < dimension; j++) { data_t tmp = a - b.m_data[i][j]; result.setElem(i, j, tmp); } } return result; } friend ComplexMatrix<qubit_number, precision_t> operator-(const ComplexMatrix<qubit_number, precision_t> &a, const data_t &b) { ComplexMatrix<qubit_number, precision_t> result; size_t dimension = a.getDimension(); for (size_t i = 0; i < dimension; i++) { for (size_t j = 0; j < dimension; j++) { data_t tmp = a.m_data[i][j] - b; result.setElem(i, j, tmp); } } return result; } friend ComplexMatrix<qubit_number, precision_t> operator*(const ComplexMatrix<qubit_number, precision_t> &a, const ComplexMatrix<qubit_number, precision_t> &b) { ComplexMatrix<qubit_number, precision_t> result; size_t dimension = a.getDimension(); for(size_t i = 0; i < dimension; i++) { for(size_t j = 0; j < dimension; j++) { data_t tmp = 0; for(size_t k = 0; k < dimension; k++) { tmp += a.m_data[i][k] * b.m_data[k][j]; } result.setElem(i, j, tmp); } } return result; } friend ComplexMatrix<qubit_number, precision_t> operator*(const data_t &a, const ComplexMatrix<qubit_number, precision_t> &b) { ComplexMatrix<qubit_number, precision_t> result; size_t dimension = b.getDimension(); for(size_t i = 0; i < dimension; i++) { for(size_t j = 0; j < dimension; j++) { data_t tmp = 0; tmp = a * b.m_data[i][j]; result.setElem(i, j, tmp); } } return result; } friend ComplexMatrix<qubit_number, precision_t> operator*(const ComplexMatrix<qubit_number, precision_t> &a, const data_t &b) { ComplexMatrix<qubit_number, precision_t> result; size_t dimension = a.getDimension(); for(size_t i = 0; i < dimension; i++) { for(size_t j = 0; j < dimension; j++) { data_t tmp = 0; tmp = a.m_data[i][j] * b; result.setElem(i, j, tmp); } } return result; } friend ComplexVector<qubit_number, precision_t> operator *(const ComplexMatrix<qubit_number, precision_t> &mat, const ComplexVector<qubit_number, precision_t> &vec) { ComplexVector<qubit_number, precision_t> result; size_t size = mat.getDimension(); for (size_t i = 0; i < size; i++) { for (size_t j = 0; j < size; j++) { result[i] = result[i] + mat.m_data[i][j] * vec[j]; } } return result; } inline size_t getDimension() const { return 1u << qubit_number; } void setElem(const size_t x, const size_t y, const data_t &value) { assert(x < getDimension() && y < getDimension()); m_data[x][y] = value; return ; } void initialize() { size_t dimension = getDimension(); m_data.resize(dimension); for (size_t i = 0; i < dimension; i++) { m_data[i].resize(dimension, 0); } } ~ComplexMatrix() { } private: std::vector< std::vector<data_t> > m_data; }; #endif // COMPLEXMATRIX_H
Java
UTF-8
1,055
3.578125
4
[]
no_license
package cards; import data.CardNames; import game.Engine; import data.CardDescriptions; // class for the block card and superclass for all the sub block cards public class Block extends Card { // used to check which card wins @Override public int compareTo(Card card) { // if its a throw they lose if(card instanceof Throw) { return -1; } // if its a block they tie else if(card instanceof Block) { return 0; } // if its an attack they win else if(card instanceof Attack) { return 1; } else { return -2; } } // constructor calls the superclass one to set the name and description // only used for subclasses public Block(String name, String description) { super(name, description); } // if we make a regular block card, its name and description come from the data files public Block() { super(CardNames.BLOCK, CardDescriptions.BLOCK); } // used for a regular block @Override public void playCard() { // the block gets put back into the hand Engine.getRoundWinner().addCardToHand(this); } }
PHP
UTF-8
2,488
2.59375
3
[]
no_license
<?php defined('BASEPATH') OR exit('No direct script access allowed'); use Mpdf\Mpdf; class PdfManagement { function __construct() { $this->Mpdf = new \Mpdf\Mpdf(); } public function run ($config = []) { // var_dump($config);exit; // $this->Mpdf->WriteHTML($config['html'], 0); // $this->Mpdf->AddPage(); // $this->Mpdf->WriteHTML($config['html'], 0); if (isset($config['setFooterPageNumber'])) { // Set a simple Footer including the page number $this->Mpdf->setFooter('Halaman {PAGENO}'); } $this->writeHtml($config); if (isset($config['title'])) { // var_dump('a');exit; $this->setOutputFile($config); } else { $this->Mpdf->Output(); } } public function setOutputFile ($config) { $location = 'uploads/pdf/'.$config['title'].'.pdf'; // $this->Mpdf->Output(); $this->Mpdf->Output($location, \Mpdf\Output\Destination::FILE); // header('Content-type: application/pdf'); // header('Content-Disposition: inline; filename="' . $location . '"'); // header('Content-Transfer-Encoding: binary'); // header('Accept-Ranges: bytes'); // ob_clean(); // flush(); // if (readfile($location)) // { // unlink($location); // } } public function writeHtml ($config) { if (!isset($config['withBreak'])) { $config['withBreak'] = ''; } if ($config['withBreak'] === false && $config['html']) { foreach ($config['html'] as $key => $value) { $this->Mpdf->WriteHTML($value, 0); } } else if ($config['withBreak'] === true && $config['html']) { $arraySize = count($config['html']); $lastArray = $arraySize - 1; foreach ($config['html'] as $key => $value) { $this->Mpdf->WriteHTML($value, 0); if ($key === $lastArray) { return true; } else { $this->Mpdf->AddPage(); } } } else { foreach ($config['html'] as $key => $value) { $this->Mpdf->WriteHTML($value, 0); } } } }
Markdown
UTF-8
1,338
2.796875
3
[]
no_license
--- layout: post author: Jeff Watkins title: Augustus Versus the Squirrelly Minions of Satan date: 2004-10-02 categories: - Cats --- Augustus has come a long way since we first moved to Rhinebeck. He started out wearing a harness and leash when we went for our daily walks, but now he gets to roam totally unencumbered. That means he also gets to pursue his personal war against the squirrelly minions of Satan infesting the green where we walk. Augustus definitely has pure speed on his side. The squirrels simply can't out run him no matter how they try. But the squirrels have two advantages: they are considerably more manoeuvrable and they can climb trees. Many times Augustus has been gaining on the squirrel only to find he's now going in the wrong direction. Or worse, the squirrel leapt to safety and is chittering taunts from a branch high above. One thing that has truly impressed me is Augustus' growing understanding of the squirrels' evil methods. He now knows to watch the branches overhead to see where a squirrel is going. He'll follow slowly on the ground and is often waiting when the squirrel he just chased up a tree comes down on the other side of the green. Of course, it's not a great challenge to out think a critter with a brain the size of a small nut. I'm just surprised Augustus has picked this up so quickly.
Go
UTF-8
1,480
2.59375
3
[ "MIT" ]
permissive
package main import ( "io/ioutil" "gopkg.in/yaml.v2" ) type backendConfig map[string]string type configBridge struct { Backend string `yaml:"backend"` // DEPRECATE IN THE FUTURE Backends map[string]backendConfig `yaml:"backends"` PublicKey string `yaml:"public_key"` // DEPRECATE IN THE FUTURE PrivateKey string `yaml:"private_key"` // DEPRECATE IN THE FUTURE } type deliveryChannelConfig struct { Host string `yaml:"host"` Username string `yaml:"username"` Password string `yaml:"password"` From string `yaml:"from"` Port int64 `yaml:"port"` } type companyConfig struct { Name string `yaml:"name"` OfficialWeb string `yaml:"official_web"` SupportEmail string `yaml:"support_email"` SupportPhone string `yaml:"support_phone"` Custom map[string]interface{} `yaml:"custom"` } type configFile struct { Port int64 `yaml:"port"` Bridge configBridge `yaml:"bridge"` Delivery map[string]deliveryChannelConfig `yaml:"delivery"` Company companyConfig `yaml:"company"` } func readConfigFile(filename string) (*configFile, error) { data, err := ioutil.ReadFile(filename) if err != nil { return nil, err } config := new(configFile) err = yaml.Unmarshal(data, config) if err != nil { return nil, err } return config, nil }
Python
UTF-8
6,134
3.78125
4
[]
no_license
documents = [ {"type": "passport", "number": "2207 876234", "name": "Leia Organa"}, {"type": "invoice", "number": "11-2", "name": "Anakin Skywalker"}, {"type": "insurance", "number": "10006", "name": "Han Solo"} ] directories = { '1': ['2207 876234', '11-2'], '2': ['10006'], '3': [] } def show_commands(): commands = [ 'p – выводит имя человека по номеру документа', 's - выводит номер полки на которой хранится документ по его номеру', 'l - выводит список всех документов', 'a - добавление нового документа в каталог и перечень полок', 'd - удаление записи из базы по номеру документа', 'm - перемещение документа на новую полку', 'as - добавление новой полки', 'h - выводит список всех доступных команд', 'x - закончить работу с программой' ] return commands def get_name_by_document_number(document_number): doc_info = [item for item in documents if item['number'] == document_number] return doc_info[0]['name'] if doc_info else f"no document #{document_number} in base" def get_shelf_by_document_number(document_number): shelf_number = [shelf for shelf, values in directories.items() if document_number in values] return f"document #{document_number} stored on shelf#{shelf_number[0]}" if shelf_number \ else f"no document #{document_number} in base" def show_all_documents(): return [' '.join(item.values()) for item in documents] def add_new_shelf(shelf_number=''): if not shelf_number: shelf_number = input('Введите номер полки: ') if shelf_number not in directories.keys(): directories[shelf_number] = [] return shelf_number, True return shelf_number, False def append_document_to_shelf(document_number, shelf_number): add_new_shelf(shelf_number) directories[shelf_number].append(document_number) def add_new_document(document_number, document_type, name, shelf): documents.append(dict(type=document_type, number=document_number, name=name)) append_document_to_shelf(document_number, shelf) return shelf def remove_document_from_shelf(document_number): documents_list = [documents_list for documents_list in directories.values() if document_number in documents_list] documents_list[0].remove(document_number) def remove_document(document_number): documents_row_index = [index for index, item in enumerate(documents) if item['number'] == document_number] if documents_row_index: del documents[documents_row_index[0]] remove_document_from_shelf(document_number) return document_number, True def move_document(document_number, shelf_number): remove_document_from_shelf(document_number) append_document_to_shelf(document_number, shelf_number) def main(): print("Делопроизводство версия 0.1") print("введите 'h' что бы получить список всех доступных команд\n") while True: command = input('введите команду: ') if command in ('h', 'p', 's', 'l', 'a', 'd', 'm', 'as', 'x'): if command == 'h': print("Cписок всех доступных комманд: \n") print(*show_commands(), sep='\n') print() elif command == 'p': print("\nПоиск имени по номеру документа.") document_number = input("введите номер: ") print(get_name_by_document_number(document_number), '\n') elif command == 's': print("\nПоиск полки по номеру документа.") document_number = input("введите номер документа: ") print(get_shelf_by_document_number(document_number), '\n') elif command == 'l': print('\nСписок всех документов:') print(*show_all_documents(), sep='\n') print() elif command == 'a': print("\nДобавление нового документа:") document_number = input("номер документа: ") document_type = input("тип документа: ") name = input("имя владельца: ") shelf = input("номер полки: ") result = add_new_document(document_number, document_type, name, shelf) print(f"{document_number} добавлен на полку {result}") elif command == 'd': print("\nУдаление документа:") document_number = input("номер документа: ") remove_document(document_number) print(f"{document_number} удален\n") elif command == 'm': print('\nПеремещение документа на другую полку:') document_number = input('Введите номер документа: ') shelf_number = input('Введите номер полки для перемещения: ') move_document(document_number, shelf_number) print(f"{document_number} премещен на полку {shelf_number}") elif command == 'as': print('\nДобавление новой полки:') print(add_new_shelf()) elif command == 'x': break else: print('введена несуществующая команда') print("введите 'h' что бы получить список всех доступных команд\n") if __name__ == "__main__": main()
Python
UTF-8
11,845
3.03125
3
[]
no_license
import numpy as np from nndl.layers import * import pdb """ This code was originally written for CS 231n at Stanford University (cs231n.stanford.edu). It has been modified in various areas for use in the ECE 239AS class at UCLA. This includes the descriptions of what code to implement as well as some slight potential changes in variable names to be consistent with class nomenclature. We thank Justin Johnson & Serena Yeung for permission to use this code. To see the original version, please visit cs231n.stanford.edu. """ def conv_forward_naive(x, w, b, conv_param): """ A naive implementation of the forward pass for a convolutional layer. The input consists of N data points, each with C channels, height H and width W. We convolve each input with F different filters, where each filter spans all C channels and has height HH and width HH. Input: - x: Input data of shape (N, C, H, W) - w: Filter weights of shape (F, C, HH, WW) - b: Biases, of shape (F,) - conv_param: A dictionary with the following keys: - 'stride': The number of pixels between adjacent receptive fields in the horizontal and vertical directions. - 'pad': The number of pixels that will be used to zero-pad the input. Returns a tuple of: - out: Output data, of shape (N, F, H', W') where H' and W' are given by H' = 1 + (H + 2 * pad - HH) / stride W' = 1 + (W + 2 * pad - WW) / stride - cache: (x, w, b, conv_param) """ out = None pad = conv_param['pad'] stride = conv_param['stride'] # ================================================================ # # YOUR CODE HERE: # Implement the forward pass of a convolutional neural network. # Store the output as 'out'. # Hint: to pad the array, you can use the function np.pad. # ================================================================ # N,C,H,W = x.shape F,C,HH,WW = w.shape H_o = 1 + (H + 2 * pad - HH) // stride W_o = 1 + (W + 2 * pad - WW) // stride window_input=np.zeros((N,F,C,H_o,W_o)) out = np.zeros((N,F,H_o,W_o)) def pad_with(vector, pad_width, iaxis, kwargs): pad_value = kwargs.get('padder', 0) vector[:pad_width[0]] = pad_value vector[-pad_width[1]:] = pad_value return vector for i in range(0,N): for f in range(0,F): for m in range(0,H_o): hs = m*stride for n in range(0,W_o): ws = n*stride for c in range(0,C): x_pad = np.pad(x[i,c,:,:],pad,pad_with) window_input[i,f,c,m,n] += np.sum(x_pad[hs:hs+HH,ws:ws+WW]*w[f,c,:,:]) out[i,f,m,n] = np.sum(window_input[i,f,:,m,n]) out[i,f,:,:]+=b[f] # ================================================================ # # END YOUR CODE HERE # ================================================================ # cache = (x, w, b, conv_param) return out, cache def conv_backward_naive(dout, cache): """ A naive implementation of the backward pass for a convolutional layer. Inputs: - dout: Upstream derivatives. - cache: A tuple of (x, w, b, conv_param) as in conv_forward_naive Returns a tuple of: - dx: Gradient with respect to x - dw: Gradient with respect to w - db: Gradient with respect to b """ dx, dw, db = None, None, None N, F, out_height, out_width = dout.shape x, w, b, conv_param = cache stride, pad = [conv_param['stride'], conv_param['pad']] xpad = np.pad(x, ((0,0), (0,0), (pad,pad), (pad,pad)), mode='constant') num_filts, _, f_height, f_width = w.shape # ================================================================ # # YOUR CODE HERE: # Implement the backward pass of a convolutional neural network. # Calculate the gradients: dx, dw, and db. # ================================================================ # x,w,b,conv_param = cache pad = conv_param['pad'] stride = conv_param['stride'] N,C,H,W = x.shape F,C,HH,WW = w.shape H_o = 1 + (H + 2 * pad - HH) // stride W_o = 1 + (W + 2 * pad - WW) // stride x_pad = np.zeros((N,C,H+2*pad,W+2*pad)) dx_pad = np.zeros(x_pad.shape) dx = np.zeros(x.shape) dw = np.zeros(w.shape) db = np.zeros(b.shape) def pad_with(vector, pad_width, iaxis, kwargs): pad_value = kwargs.get('padder', 0) vector[:pad_width[0]] = pad_value vector[-pad_width[1]:] = pad_value return vector for i in range(0,N): for c in range(0,C): x_pad[i,c,:,:] = np.pad(x[i,c,:,:],pad,pad_with) dx_pad[i,c,:,:] = np.pad(dx[i,c,:,:],pad,pad_with) for i in range(0,N): for f in range(0,F): for m in range(0,H_o): hs = m*stride for n in range(0,W_o): ws = n*stride window_input = x_pad[i,:,hs:hs+HH,ws:ws+WW] dw[f]+=dout[i,f,m,n]*window_input db[f] +=dout[i,f,m,n] dx_pad[i,:,hs:hs+HH,ws:ws+WW]+=w[f,:,:,:]*dout[i,f,m,n] dx = dx_pad[:,:,pad:pad+H,pad:pad+W] # ================================================================ # # END YOUR CODE HERE # ================================================================ # return dx, dw, db def max_pool_forward_naive(x, pool_param): """ A naive implementation of the forward pass for a max pooling layer. Inputs: - x: Input data, of shape (N, C, H, W) - pool_param: dictionary with the following keys: - 'pool_height': The height of each pooling region - 'pool_width': The width of each pooling region - 'stride': The distance between adjacent pooling regions Returns a tuple of: - out: Output data - cache: (x, pool_param) """ out = None # ================================================================ # # YOUR CODE HERE: # Implement the max pooling forward pass. # ================================================================ # N,C,H,W = x.shape ph = pool_param['pool_height'] pw = pool_param['pool_width'] stride = pool_param['stride'] H_o = 1 + (H - ph) // stride W_o = 1 + (W - pw) // stride out = np.zeros((N,C,H_o,W_o)) for i in range(N): for c in range(C): for m in range(H_o): hs = m*stride for n in range(W_o): ws = n*stride window = x[i,c,hs:hs+ph,ws:ws+pw] out[i,c,m,n] = np.max(window) # ================================================================ # # END YOUR CODE HERE # ================================================================ # cache = (x, pool_param) return out, cache def max_pool_backward_naive(dout, cache): """ A naive implementation of the backward pass for a max pooling layer. Inputs: - dout: Upstream derivatives - cache: A tuple of (x, pool_param) as in the forward pass. Returns: - dx: Gradient with respect to x """ dx = None x, pool_param = cache pool_height, pool_width, stride = pool_param['pool_height'], pool_param['pool_width'], pool_param['stride'] # ================================================================ # # YOUR CODE HERE: # Implement the max pooling backward pass. # ================================================================ # x,pool_param = cache N,C,H,W = x.shape ph = pool_param['pool_height'] pw = pool_param['pool_width'] stride = pool_param['stride'] H_o = 1 + (H - ph) // stride W_o = 1 + (W - pw) // stride dx = np.zeros(x.shape) for i in range(N): for c in range(C): for m in range(H_o): hs = m*stride for n in range(W_o): ws = n*stride window = x[i,c,hs:hs+ph,ws:ws+pw] max_out = np.max(window) dx[i,c,hs:hs+ph,ws:ws+pw] += (window == max_out)*dout[i,c,m,n] # ================================================================ # # END YOUR CODE HERE # ================================================================ # return dx def spatial_batchnorm_forward(x, gamma, beta, bn_param): """ Computes the forward pass for spatial batch normalization. Inputs: - x: Input data of shape (N, C, H, W) - gamma: Scale parameter, of shape (C,) - beta: Shift parameter, of shape (C,) - bn_param: Dictionary with the following keys: - mode: 'train' or 'test'; required - eps: Constant for numeric stability - momentum: Constant for running mean / variance. momentum=0 means that old information is discarded completely at every time step, while momentum=1 means that new information is never incorporated. The default of momentum=0.9 should work well in most situations. - running_mean: Array of shape (D,) giving running mean of features - running_var Array of shape (D,) giving running variance of features Returns a tuple of: - out: Output data, of shape (N, C, H, W) - cache: Values needed for the backward pass """ out, cache = None, None # ================================================================ # # YOUR CODE HERE: # Implement the spatial batchnorm forward pass. # # You may find it useful to use the batchnorm forward pass you # implemented in HW #4. # ================================================================ # mode = bn_param['mode'] eps = bn_param.get('eps', 1e-5) momentum = bn_param.get('momentum', 0.9) N,C,H,W = x.shape x_t = x.transpose((0,2,3,1)) x_t = x_t.reshape(-1,C) running_mean = bn_param.get('running_mean', np.zeros(C, dtype=x.dtype)) running_var = bn_param.get('running_var', np.zeros(C, dtype=x.dtype)) x_mu = np.mean(x_t,axis = 0) x_var = np.var(x_t,axis = 0) running_mean = momentum * running_mean + (1 - momentum) * x_mu running_var = momentum * running_var + (1 - momentum) * x_var x_norm = (x_t-x_mu)/np.sqrt(x_var+eps) out = gamma*x_norm + beta cache = (x_t,x_norm,x_mu,x_var,gamma,beta,eps) out = out.reshape((N,H,W,C)).transpose(0,3,1,2) # ================================================================ # # END YOUR CODE HERE # ================================================================ # return out, cache def spatial_batchnorm_backward(dout, cache): """ Computes the backward pass for spatial batch normalization. Inputs: - dout: Upstream derivatives, of shape (N, C, H, W) - cache: Values from the forward pass Returns a tuple of: - dx: Gradient with respect to inputs, of shape (N, C, H, W) - dgamma: Gradient with respect to scale parameter, of shape (C,) - dbeta: Gradient with respect to shift parameter, of shape (C,) """ dx, dgamma, dbeta = None, None, None # ================================================================ # # YOUR CODE HERE: # Implement the spatial batchnorm backward pass. # # You may find it useful to use the batchnorm forward pass you # implemented in HW #4. # ================================================================ # x_t,x_norm,x_mu,x_var,gamma,beta,eps = cache N,C,H,W = dout.shape dout_t = dout.transpose((0,2,3,1)) dout_t = dout_t.reshape(-1,C) N_new,_=dout_t.shape new_mu = x_t-x_mu dbeta = np.sum(dout_t,axis = 0) dgamma = np.sum(dout_t*x_norm,axis = 0) dx_norm = dout_t*gamma divar = np.sum(dx_norm*new_mu,axis = 0) dxmu1 = dx_norm/np.sqrt(x_var+eps) dsqrtvar = -1./(x_var+eps)*divar dvar = 0.5*1./np.sqrt(x_var+eps)*dsqrtvar dsq = 1./N_new*np.ones((N_new,C))*dvar dxmu2 = 2*new_mu*dsq dx1 = dxmu1+dxmu2 dmu = -1*np.sum(dx1,axis=0) dx2 = 1./N_new*np.ones((N_new,C))*dmu dx = (dx1+dx2).reshape((N,H,W,C)).transpose(0,3,1,2) # ================================================================ # # END YOUR CODE HERE # ================================================================ # return dx, dgamma, dbeta
Java
UTF-8
535
2.828125
3
[ "MIT" ]
permissive
package com.infotamia.weather.pojos.entities; /** * @author Mohammed Al-Ani */ public class MainEntity { private double temp; public MainEntity() { } public double getTemp() { return (temp - 273.15); } public String getFormattedTemp() { return String.format("%dC",(int) getTemp()); } public void setTemp(double temp) { this.temp = temp; } @Override public String toString() { return "MainEntity{" + "temp=" + temp + '}'; } }
Python
UTF-8
1,756
2.734375
3
[ "MIT" ]
permissive
#!/usr/bin/env python # -*- coding: utf-8 -*- # test.py import sys import pytest import unittest import json import requests sys.path.append('../src/') from principal import * from usuario import * #url = 'https://proyecto-iv-19.herokuapp.com/status' class TestMethods(unittest.TestCase): with open('../json/datos.json','r') as usuarios: lista_usuario = json.load(usuarios) pruebaUsuario = Usuario() pruebaUsuario.crea_usu(lista_usuario) #print(lista_usuario) #for i in usuario: # for i in range(usuario.num_usuarios): # print(usuario.to_s(i)) with open('../json/datos_tabaco.json','r') as marcas: lista_tabaco = json.load(marcas) pruebaServicio = Servicio() pruebaServicio.crea_sistema(pruebaUsuario,pruebaUsuario.get_numUsuarios(),lista_tabaco) """ test nombre usuario """ def test_nombre(self): self.assertEqual(self.pruebaUsuario.get_nombre(self),False,"El campo nombre está vacío") self.assertEqual(self.pruebaUsuario.get_nombre(0),"Usuario 1", "Tiene nombre") """ test marca tabaco """ def test_marca(self): self.assertEqual(self.pruebaServicio.get_marca(self),False,"No marca") self.assertEqual(self.pruebaServicio.get_marca(0),'MarcaA', "La marca es correcta") """ test cambiar moneda """ def test_moneda(self): self.assertEqual(self.pruebaServicio.set_moneda(0),False, "Dato incorrecto") self.assertEqual(self.pruebaServicio.set_moneda("Libra"),True, "Dato correcto") def test_to_s(self): self.assertEqual(self.pruebaServicio.to_s(0,self.pruebaUsuario)['Nombre'],'Usuario 1', "Usuario correcto") if __name__ == '__main__': unittest.main()
JavaScript
UTF-8
527
2.890625
3
[]
no_license
$(document).ready(function(){ $('#boton1').click(function(){ $("tr:first").css("background", "#9cf"); }); $('#boton2').on('click',function(){ $("td:last").css("background", "#9cf"); }); $('#boton3').on('click',function(){ $("tr:even").css("background", "#9cf"); }); $('#boton4').on('click',function(){ $("td:eq(2)").css("background", "#9cf"); }); $('#boton5').on('click',function(){ $("td:gt(1)").css("background", "#9cf"); }); });
C
UTF-8
2,317
3.34375
3
[]
no_license
#include "reserva.h" int quartos(){ while (1) { int qua=0,cat=0; printf("Escolha a classe do seu quarto:\n\t1 - Luxo\n\t2 - Normal\n\t3 - Simples\n"); scanf("%d",&cat); if(cat==1 || cat==2 || cat==3){ if(cat==1){ printf("Classe de Luxo selecionada!"); }else if (cat==2){ printf("Classe de Normal selecionada!"); }else if (cat==3){ printf("Classe de Simples selecionada!"); } printf("\nEscolha o tamanho do quarto:\n\t1 - Quarto para uma pessoa\n\t2 - Quarto de casal\n\t3 - Quarto tamanho familía(4 pessoas)\n"); scanf("%d",&qua); if (qua==1 && cat==1){ printf("PLAYER SOLO! Quarto para uma pessoa de Luxo!"); return 0; }else if (qua==1 && cat==2){ printf("Quarto para um pessoa, categoria normal."); return 0; }else if (qua==1 && cat==3){ printf("Quarto para uma pessoa, categoria simples."); return 0; }else if (qua==2 && cat==1){ printf("Duo do AMOR! Quarto de casal,categoria Luxo!"); return 0; }else if (qua==2 && cat==2){ printf("Quarto para um casal, categoria normal."); return 0; }else if (qua==2 && cat==3){ printf("Quarto para um casal, categoria simples."); return 0; }else if (qua==3 && cat==1){ printf("Quarto tamanho familía,categoria Luxo!"); return 0; }else if (qua==3 && cat==2){ printf("Quarto para uma familía, categoria normal."); return 0; }else if (qua==3 && cat==3){ printf("Quarto para uma familía, categoria simples."); return 0; } }else if(cat!=1 && cat!=2 && cat!=3){ continue; } } };
C++
UTF-8
1,432
3.203125
3
[]
no_license
#include <iostream> #include <queue> #define size 8 using namespace std; int arr[size][size] = { 0,1,1,0,0,0,0,0, 1,0,0,1,1,0,0,0, 1,0,0,0,0,1,1,0, 0,1,0,0,0,0,0,1, 0,1,0,0,0,0,0,1, 0,0,1,0,0,0,0,1, 0,0,1,0,0,0,0,1, 0,0,0,1,1,1,1,0 }; int visited[size] = { 0 }; int graph[size]; int front = -1; int rear = -1; bool isEmpty() { if (rear == front) return true; else return false; } void enqueue(int data) { rear++; graph[rear]=data; } int dequeue() { if (isEmpty()) { return -1; } else return graph[front++]; } void DFS(int v) { cout << v << " "; visited[v] = 1; for (int i = 0; i < size; i++) { if (arr[v][i] == 1 && !visited[i]) DFS(i); } } void BFS(int d) { enqueue(d); if (visited[d] == 0) { cout << d << " "; visited[d] = 1; //visited vertex marking } while (!isEmpty()) { int t = dequeue(); for (int i = 0; i < size; i++) { if (arr[t][i] == 1 && visited[i] == 0) { enqueue(i); cout << i << " "; visited[i] = 1; } } } } void main() { cout << "Print Adjavent Matrix" << endl; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { cout << arr[i][j] << " "; } cout << endl; } cout << endl; cout << "DFS : "; DFS(0); cout << endl; for (int i = 0; i < size; i++) visited[i] = 0; cout << "BFS : "; BFS(0); }
Java
UTF-8
559
1.734375
2
[ "Apache-2.0", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
package org.apereo.cas.validation; import org.apereo.cas.authentication.principal.Service; import jakarta.servlet.http.HttpServletRequest; /** * This is {@link ServiceTicketValidationAuthorizer}. * * @author Misagh Moayyed * @since 5.2.0 */ @FunctionalInterface public interface ServiceTicketValidationAuthorizer { /** * Is authorized? * * @param request the request * @param service the service * @param assertion the assertion */ void authorize(HttpServletRequest request, Service service, Assertion assertion); }
Java
UTF-8
2,797
2.109375
2
[]
no_license
package com.imedcare.project.fnbj.cqbj.zzjl.domain; import org.apache.commons.lang3.builder.ToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import com.imedcare.framework.aspectj.lang.annotation.Excel; import com.imedcare.framework.web.domain.BaseEntity; import java.util.Date; /** * 产前保健转诊记录对象 fn_cqbj_zzjl * * @author liuyang * @date 2019-11-22 */ public class FnCqbjZzjl extends BaseEntity { private static final long serialVersionUID = 1L; /** null */ private Long id; /** 住院号 */ @Excel(name = "住院号") private String zyh; /** 姓名 */ @Excel(name = "姓名") private String xm; /** 出生日期 */ @Excel(name = "出生日期", width = 30, dateFormat = "yyyy-MM-dd") private Date birthday; /** 身份证件-类别代码 */ @Excel(name = "身份证件-类别代码") private String sfzjLbdm; /** 身份证件-号码 */ @Excel(name = "身份证件-号码") private String sfzjHm; /** 转诊记录 */ @Excel(name = "转诊记录") private String zzjl; /** 健康档案ID */ @Excel(name = "健康档案ID") private Long daid; public void setId(Long id) { this.id = id; } public Long getId() { return id; } public void setZyh(String zyh) { this.zyh = zyh; } public String getZyh() { return zyh; } public void setXm(String xm) { this.xm = xm; } public String getXm() { return xm; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Date getBirthday() { return birthday; } public void setSfzjLbdm(String sfzjLbdm) { this.sfzjLbdm = sfzjLbdm; } public String getSfzjLbdm() { return sfzjLbdm; } public void setSfzjHm(String sfzjHm) { this.sfzjHm = sfzjHm; } public String getSfzjHm() { return sfzjHm; } public void setZzjl(String zzjl) { this.zzjl = zzjl; } public String getZzjl() { return zzjl; } public void setDaid(Long daid) { this.daid = daid; } public Long getDaid() { return daid; } @Override public String toString() { return new ToStringBuilder(this,ToStringStyle.MULTI_LINE_STYLE) .append("id", getId()) .append("zyh", getZyh()) .append("xm", getXm()) .append("birthday", getBirthday()) .append("sfzjLbdm", getSfzjLbdm()) .append("sfzjHm", getSfzjHm()) .append("zzjl", getZzjl()) .append("daid", getDaid()) .toString(); } }
Java
UTF-8
545
1.664063
2
[]
no_license
package android.support.v4.app; final class FragmentManagerImpl$2 implements Runnable { FragmentManagerImpl$2(FragmentManagerImpl paramFragmentManagerImpl) {} public final void run() { FragmentManagerImpl localFragmentManagerImpl = this$0; FragmentHostCallback localFragmentHostCallback = this$0.mHost; localFragmentManagerImpl.popBackStackState$68507953(null, -1, 0); } } /* Location: * Qualified Name: android.support.v4.app.FragmentManagerImpl.2 * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
PHP
UTF-8
503
2.671875
3
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php namespace HaploMvc\Template; use HaploMvc\HaploApp; /** * Class HaploTemplateFactory * @package HaploMvc */ class HaploTemplateFactory { /** @var HaploApp */ protected $app; /** * @param HaploApp $app */ public function __construct(HaploApp $app) { $this->app = $app; } /** * @param $template * @return HaploTemplate */ public function create($template) { return new HaploTemplate($this->app, $template); } }
Python
UTF-8
926
3.296875
3
[]
no_license
from os import path, remove import datetime def random_name(name_base): """ Método para generar un nombre aleatorio. """ suffix = datetime.datetime.now().strftime("%y%m%d_%H%M%S") filename = "_".join([name_base, suffix]) return filename def directory_exists(url_path): """ Método para verificar existencia de directorio. """ if path.isdir(url_path): return True return False def file_exists(url_path): """ Método para verificar existencia de archivo. """ if path.isfile(url_path): return True return False def write_file(base_url, filename, content): """ Método para guardar un archivo. """ if directory_exists(base_url): with open(base_url + filename, "wb") as f: f.write(content) f.close() def remove_file(url_path): """ Método para eliminar un archivo. """ if file_exists(url_path): remove(url_path)
C++
UTF-8
6,583
2.84375
3
[ "BSD-2-Clause", "LGPL-2.0-or-later", "LicenseRef-scancode-unknown-license-reference", "GPL-3.0-only" ]
permissive
// // pedsim - A microscopic pedestrian simulation system. // Copyright (c) 2003 - 2004 by Christian Gloor // #include "ped_tree.h" #include "ped_agent.h" #include "ped_scene.h" #include <cassert> #include <cstddef> using namespace std; /// Description: set intial values /// \author chgloor /// \date 2012-01-28 Ped::Ttree::Ttree(Ped::Tscene* pscene, int pdepth, double px, double py, double pw, double ph) : scene(pscene) { // more initializations here. not really necessary to put them into the // initializator list, too. isleaf = true; x = px; y = py; w = pw; h = ph; depth = pdepth; tree1 = NULL; tree2 = NULL; tree3 = NULL; tree4 = NULL; } /// Destructor. Deleted this node and all its children. If there are any agents /// left, they are removed first (not deleted). /// \author chgloor /// \date 2012-01-28 Ped::Ttree::~Ttree() { clear(); } void Ped::Ttree::clear() { if (isleaf) { agents.clear(); } else { tree1->clear(); delete tree1; tree2->clear(); delete tree2; tree3->clear(); delete tree3; tree4->clear(); delete tree4; isleaf = true; } } /// Adds an agent to the tree. Searches the right node and adds the agent there. /// If there are too many agents at that node allready, a new child is created. /// \author chgloor /// \date 2012-01-28 /// \param *a The agent to add void Ped::Ttree::addAgent(const Ped::Tagent* a) { if (isleaf) { agents.insert(a); scene->treehash[a] = this; } else { if ((a->getx() >= x + w / 2) && (a->gety() >= y + h / 2)) tree3->addAgent(a); // 3 if ((a->getx() <= x + w / 2) && (a->gety() <= y + h / 2)) tree1->addAgent(a); // 1 if ((a->getx() >= x + w / 2) && (a->gety() <= y + h / 2)) tree2->addAgent(a); // 2 if ((a->getx() <= x + w / 2) && (a->gety() >= y + h / 2)) tree4->addAgent(a); // 4 } if (agents.size() > 8) { isleaf = false; addChildren(); while (!agents.empty()) { const Ped::Tagent* a = (*agents.begin()); if ((a->getx() >= x + w / 2) && (a->gety() >= y + h / 2)) tree3->addAgent(a); // 3 if ((a->getx() <= x + w / 2) && (a->gety() <= y + h / 2)) tree1->addAgent(a); // 1 if ((a->getx() >= x + w / 2) && (a->gety() <= y + h / 2)) tree2->addAgent(a); // 2 if ((a->getx() <= x + w / 2) && (a->gety() >= y + h / 2)) tree4->addAgent(a); // 4 agents.erase(a); } } } /// A little helper that adds child nodes to this node /// \author chgloor /// \date 2012-01-28 void Ped::Ttree::addChildren() { tree1 = new Ped::Ttree(scene, depth + 1, x, y, w / 2, h / 2); tree2 = new Ped::Ttree(scene, depth + 1, x + w / 2, y, w / 2, h / 2); tree3 = new Ped::Ttree(scene, depth + 1, x + w / 2, y + h / 2, w / 2, h / 2); tree4 = new Ped::Ttree(scene, depth + 1, x, y + h / 2, w / 2, h / 2); } Ped::Ttree* Ped::Ttree::getChildByPosition(double xIn, double yIn) { if ((xIn <= x + w / 2) && (yIn <= y + h / 2)) return tree1; if ((xIn >= x + w / 2) && (yIn <= y + h / 2)) return tree2; if ((xIn >= x + w / 2) && (yIn >= y + h / 2)) return tree3; if ((xIn <= x + w / 2) && (yIn >= y + h / 2)) return tree4; // this should never happen return NULL; } /// Updates the tree structure if an agent moves. Removes the agent and places /// it again, if outside boundary. /// If an this happens, this is O(log n), but O(1) otherwise. /// \author chgloor /// \date 2012-01-28 /// \param *a the agent to update void Ped::Ttree::moveAgent(const Ped::Tagent* a) { if ((a->getx() < x) || (a->getx() > (x + w)) || (a->gety() < y) || (a->gety() > (y + h))) { scene->placeAgent(a); agents.erase(a); } } bool Ped::Ttree::removeAgent(const Ped::Tagent* a) { if (isleaf) { size_t removedCount = agents.erase(a); return (removedCount > 0); } else { return getChildByPosition(a->getx(), a->gety())->removeAgent(a); } } /// Checks if this tree node has not enough agents in it to justify more child /// nodes. It does this by checking all /// child nodes, too, recursively. If there are not enough children, it moves /// all the agents into this node, and deletes the child nodes. /// \author chgloor /// \date 2012-01-28 /// \return the number of agents in this and all child nodes. int Ped::Ttree::cut() { if (isleaf) return agents.size(); int count = 0; count += tree1->cut(); count += tree2->cut(); count += tree3->cut(); count += tree4->cut(); if (count < 5) { assert(tree1->isleaf == true); assert(tree2->isleaf == true); assert(tree3->isleaf == true); assert(tree4->isleaf == true); agents.insert(tree1->agents.begin(), tree1->agents.end()); agents.insert(tree2->agents.begin(), tree2->agents.end()); agents.insert(tree3->agents.begin(), tree3->agents.end()); agents.insert(tree4->agents.begin(), tree4->agents.end()); isleaf = true; for (const Tagent* agent : agents) scene->treehash[agent] = this; delete tree1; delete tree2; delete tree3; delete tree4; } return count; } /// Returns the set of agents that is stored within this tree node /// \author chgloor /// \date 2012-01-28 /// \return The set of agents /// \todo This might be not very efficient, since all childs are checked, too. /// And then the set (set of pointer, but still) is being copied around. set<const Ped::Tagent*> Ped::Ttree::getAgents() const { if (isleaf) return agents; // fill a temporary output list with the agents vector<const Ped::Tagent*> tempList; getAgents(tempList); // convert list to set return set<const Ped::Tagent*>(tempList.begin(), tempList.end()); } void Ped::Ttree::getAgents(vector<const Ped::Tagent*>& outputList) const { if (isleaf) { for (const Ped::Tagent* currentAgent : agents) outputList.push_back(currentAgent); } else { tree1->getAgents(outputList); tree2->getAgents(outputList); tree3->getAgents(outputList); tree4->getAgents(outputList); } } /// Checks if a point x/y is within the space handled by the tree node, or /// within a given radius r /// \author chgloor /// \date 2012-01-29 /// \return true if the point is within the space /// \param px The x co-ordinate of the point /// \param py The y co-ordinate of the point /// \param pr The radius bool Ped::Ttree::intersects(double px, double py, double pr) const { if (((px + pr) > x) && ((px - pr) < (x + w)) && ((py + pr) > y) && ((py - pr) < (y + h))) return true; // x+-r/y+-r is inside else return false; }
Java
UTF-8
985
2.78125
3
[]
no_license
package net.coljate.graph; import net.coljate.set.impl.TwoSet; /** * * @author Ollie */ public interface MutableUndirectedGraph<V, E> extends MutableGraph<V, E>, UndirectedGraph<V, E> { @Override @Deprecated default boolean add(final Relationship<V, E> relationship) { return relationship instanceof UndirectedRelationship && this.add((UndirectedRelationship<V, E>) relationship); } default boolean add(final UndirectedRelationship<V, E> relationship) { final TwoSet<? extends V> vertices = relationship.vertices(); return this.addEdge(vertices.first(), vertices.last(), relationship.edge()); } @Override @Deprecated default boolean remove(final Relationship<?, ?> relationship) { return relationship instanceof UndirectedRelationship && this.remove((UndirectedRelationship<?, ?>) relationship); } boolean remove(UndirectedRelationship<?, ?> relationship); }
Python
UTF-8
1,767
3.6875
4
[]
no_license
import re def func(a): while True: #这个循环的作用就是用来四则运算的 if '*' in a: c = a.split('*') if '/' in c[0]: a = div(a) else: a = mul(a) elif '/' in a: a = div(a) else: a = add(a) return a def mul(a): b = re.search(r'\d+\.?\d*\*-?\d+\.?\d*', a) if b: b = b.group() l=b.split("*") c=float(l[0])*float(l[1]) res = re.sub(r'\d+\.?\d*\*-?\d+\.?\d*', str(c), a,1) return res def div(a): b = re.search(r'\d+\.?\d*/-?\d+\.?\d*', a) if b: b = b.group() l=b.split("/") c=float(l[0])/float(l[1]) res = re.sub(r'\d+\.?\d*/-?\d+\.?\d*', str(c), a,1) return res def add(a): if '--' in a: a = a.replace('--', '+') if "-+" in a: a = a.replace("-+","-") b = re.findall(r'-?\d+\.?\d*', a) #把负数两个字符看成一个整体 c=0 for i in b: c+=float(i) return c def caculate(): a = ''.join(input('你要算啥:').split())#把输入字符串以空格切片然后在拼接 while True: if '(' in a: #如果有括号就把括号里面的东西算出来替换掉 b = re.search(r'\([^()]+\)', a) #把最里面的(...)作为一个对象拿到 if b: #怕有二货输个空括号 c = b.group() #把(...)拿出来赋给c d = func(c) #包括号里面表达式计算出来 a = re.sub(r'\([^()]+\)', str(d), a, 1) #操操操,这个狗比1,害老子蒙圈一下午,用结果替换(...) else: #没要括号直接进行四则运算运算 print(func(a)) break caculate()
C++
UTF-8
1,209
3.546875
4
[]
no_license
/*Programma per l'inserimento, in una lista, di tre elementi, visualizzazione degli elementi, e rimozione del secondo elemento*/ //Relazione con i puntatori , elementi di tipo intero #include <stdio.h> #include <stdlib.h> //no operatori , no classi ,no tipo template typedef struct elemento_lista{ /* Definizione tipo nodo */ int valore; struct elemento_lista *succ; }nodo; typedef nodo* lista; /* Definizione tipo lista di interi */ int main(){ lista iter, supp; lista L = NULL; /* creazione della lista */ L = (lista) malloc (sizeof(nodo)); /* inserimento primo elemento */ L->valore = 1; L->succ = NULL; iter = L; iter->succ = (lista) malloc (sizeof(nodo)); /* inserimento secondo elemento */ iter->succ->valore = 2; iter->succ->succ = NULL; iter = iter->succ; iter->succ = (lista) malloc (sizeof(nodo)); /* inserimento terzo elemento */ iter->succ->valore = 3; iter->succ->succ = NULL; iter = L; /* visualizzazione elementi */ while (iter != NULL){ printf("%d ",iter->valore); iter = iter->succ; } iter = L->succ; /* eleminazione secondo elemento */ L->succ = iter->succ; free(iter); system("pause"); return 0; }
C++
UTF-8
2,042
2.765625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Character.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hdelanoe <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/03/28 15:25:41 by hdelanoe #+# #+# */ /* Updated: 2019/03/28 15:25:42 by hdelanoe ### ########.fr */ /* */ /* ************************************************************************** */ #include "Character.hpp" #include "AMateria.hpp" Character::Character(void) : _name("character"), _count(0) { for (int i = 0; i < 4; i += 1) { _materia[i] = NULL; } } Character::Character(std::string const & name) : _name(name), _count(0) { for (int i = 0; i < 4; i += 1) { _materia[i] = NULL; } } Character::Character(Character const & src) { *this = src; } Character::~Character(void) { return ; } Character & Character::operator=(Character const & rhs) { if (this != &rhs) { _name = rhs.getName(); for (int i = 0; i < 4; i += 1) { _materia[i] = NULL; _materia[i] = rhs._materia[0]->clone(); } _count = rhs._count; } return *this; } void Character::equip(AMateria* materia) { if (_count < 3) { _materia[_count] = materia; _count += 1; } } void Character::unequip(int idx) { if (idx >= 0 && idx <= 3) _materia[idx] = NULL; } void Character::use(int idx, ICharacter& target) { _materia[idx]->use(target); } int Character::getCount(void) const { return _count; } std::string const & Character::getName(void) const { return _name; }
TypeScript
UTF-8
3,363
3.578125
4
[]
no_license
interface vehiclesToParkType { slot: number, vehicleNumber: string } let vehiclesToPark: vehiclesToParkType[] = []; let availableParkingSlots: number[] = []; let lotSize = 0; /** * create_parking_lot command * @param howManyLots no. of slots in the parking */ export const create_parking_lot = async (howManyLots: any) => { lotSize = howManyLots; if (!lotSize || isNaN(lotSize)) { return "Error! Invalid parameter!"; } for (let i = 1; i <= lotSize; i++) { availableParkingSlots.push(i); } return `Created parking lot with ${lotSize} slots`; } export const status = async () => { if (!vehiclesToPark.length) { return `Error, no parking slots`; } else { vehiclesToPark = vehiclesToPark.sort((a, b) => { return a.slot - b.slot }); let status = `Slot No. Registration No.`; for (let i = 0; i < vehiclesToPark.length; i++) { status += `\n${vehiclesToPark[i].slot} ${vehiclesToPark[i].vehicleNumber} `; } return status; } } export const leave = async (vehicleNumber: string, parkingTime: number) => { let vehicleToLeave vehiclesToPark = vehiclesToPark.filter((vehicle) => { if (vehicle.vehicleNumber === vehicleNumber) vehicleToLeave = vehicle; return vehicle.vehicleNumber !== vehicleNumber; }); if (vehicleToLeave) { availableParkingSlots.push(vehicleToLeave.slot); //mark slot as available return `Registration number ${vehicleNumber} with Slot Number ${vehicleToLeave.slot} is free with Charge ${calculateParkingCharges(parkingTime)}`; } else { return `Registration number ${vehicleNumber} not found`; } } export const calculateParkingCharges = (parkingTime: number) => { if (parkingTime === 2) { return 10; } else { return ((parkingTime - 2) * 10) + 10 } } export const park = async (vehicleNumber: any) => { if (!vehicleNumber) { return `Error, vehicle registration number is needed`; } else if (lotSize === 0) { return `Error, please initate parking lot`; } else if (lotSize === vehiclesToPark.length) { return `Sorry, parking lot is full`; } else { let parkingSlot = availableParkingSlots[0]; vehiclesToPark.push({ 'slot': parkingSlot, 'vehicleNumber': vehicleNumber }); availableParkingSlots.shift(); //available parking slots are reduced return `Allocated slot number: ${parkingSlot}` } } export const commandParser = async (input: string) => { try { let inputSplit = input.split(" "); let result; switch (inputSplit[0].trim()) { case ('leave'): result = await leave(inputSplit[1], parseInt(inputSplit[2])); break; case ('create_parking_lot'): result = await create_parking_lot(parseInt(inputSplit[1])); break; case ('status'): result = await status(); break; case ('park'): result = await park(inputSplit[1].trim()); break; default: result = 'Error in command input!'; } return result; } catch (e) { return `Error ${e}`; } }
C++
UTF-8
763
3.046875
3
[]
no_license
/* UVa 10409 - Die Game To build using Visual Studio 2008: cl -EHsc -O2 UVa_10409_Die_Game.cpp */ #include <cstdio> using namespace std; int main() { while (true) { int n; scanf("%d", &n); if (!n) break; int top = 1, north = 2, south = 5, east = 4, west = 3; while (n--) { char direction[8]; scanf("%s", direction); int t = top; switch (direction[0]) { case 'n': top = south; north = t; south = 7 - t; break; case 's': top = north; south = t; north = 7 - t; break; case 'e': top = west; east = t; west = 7 - t; break; case 'w': top = east; west = t; east = 7 - t; break; } } printf("%d\n", top);; } return 0; }
PHP
UTF-8
205
3.328125
3
[]
no_license
<?php $a = 'hello world'; /* a comment */ echo 'something'; $b = 3; $c = 4; print $a; /* with indentation */ $a = 4; $b = 2; $c = 1; print $a; echo $a; ?>
Markdown
UTF-8
27,320
3.46875
3
[ "MIT" ]
permissive
--- layout: post title: 沉默的大多数-王小波 date: 2017-12-03 22:56:20 +0800 categories: 生活 tags: 人生 keywords: 沉默的大多数 王小波 description: 王小波《沉默的大多数》 --- 君特·格拉斯在《铁皮鼓》里,写了一个不肯长大的人。小奥斯卡发现周围的世界太过荒诞,就暗下决心要永远做小孩子。在冥冥之中,有一种力量成全了他的决心,所以他就成了个侏儒。这个故事太过神奇,但很有意思。人要永远做小孩子虽办不到,但想要保持沉默是能办到的。 在我周围,像我这种性格的人特多──在公众场合什么都不说,到了私下里则妙语连珠,换言之,对信得过的人什么都说,对信不过的人什么都不说。起初我以为这是因为经历了严酷的时期(文革),后来才发现,这是中国人的通病。龙应台女士就大发感慨,问中国人为什么不说话。她在国外住了很多年,几乎变成了个心直口快的外国人。她把保持沉默看做怯懦,但这是不对的。 沉默是一种人类学意义上的文化,一种生活方式。它的价值观很简单:开口是银,沉默是金。一种文化之内,往往有一种交流信息的独特方式,甚至是特有的语言,有一些独有的信息,文化可以传播,等等。这才能叫作文化。 <img src="//blog.lovejade.cn/assets/images/王小波.jpg" alt="王小波《沉默的大多数》"> 沉默有自己的语言。举个住楼的人都知道的例子:假设有人常把一辆自行车放在你门口的楼道上,挡了你的路,你可以开口去说:打电话给居委会;或者直接找到车主,说道:同志,五讲四美,请你注意。此后他会用什么样的语言来回答你,我就不敢保证。我估计他最起码要说你“事儿”,假如你是女的,他还会说你“事儿妈”,不管你有多大岁数,够不够做他妈。当然,你也可以选择沉默的方式来表达自己对这种行为的厌恶之情:把他车胎里的气放掉。干这件事时,当然要注意别被车主看见。 还有一种更损的方式,不值得推荐,那就是在车胎上按上个图钉。有人按了图钉再拔下来,这样车主找不到窟窿在哪儿,补带时更困难。假如车子可以搬动,把它挪到难找的地方去,让车主找不着它,也是一种选择。这方面就说这么多,因为我不想编沉默的辞典。 一种文化必有一些独有的信息,沉默也是有的。戈尔巴乔夫说过这样的话:有一件事是公开的秘密,假如你想给自己盖个小房子,就得给主管官员些贿赂,再到国家的工地上偷点建筑材料。这样的事干得说不得,属于沉默;再加上讲这些话时,戈氏是苏共总书记,所以当然语惊四座。还有一点要补充的,那就是:属于沉默的事用话讲了出来,总是这么怪怪的。 沉默也可以传播。在某些年代里,所有的人都不说话了,沉默就像野火一样四下漫延着。把这叫作传播,多少有点过甚其辞,但也不离大谱。在沉默的年代里,人们也在传播小道消息,这件事破坏了沉默的完整性。好在这种话语我们只在一些特定的场合说,比方说,公共厕所。最起码在追查谣言时,我们是这样交待的:这话我是在厕所里听说的!这样小道消息就成了包含着排便艰巨的呓语,不值得认真对待。另外,公厕虽然也是公共场合,但我有种强烈的欲望,要把它排除在外,因为它太脏了。我属于沉默的大多数。从我懂事的年龄就常听人们说:我们这一代,生于一个神圣的时代,多么幸福,而且肩负着解放天下三分之二受苦人的神圣使命等等;在甜蜜之余也有一点怀疑:这么多美事怎么都叫我赶上了。再说,含蓄是我们的家教。 在三年困难时期,有一天开饭时,每人碗里有一小片腊肉。我弟弟见了以后,按捺不住心中的狂喜,冲上阳台,朝全世界放声高呼:我们家吃大鱼大肉了!结果是被我爸爸拖回来臭揍了一顿。经过这样的教育,我一直比较深沉。所以听到别人说:我们多么幸福、多么神圣时,别人在受苦,我们没有受等等,心里老在想着:假如我们真遇上了这么多美事,不把它说出来会不会更好。当然,这不是说,我不想履行自己的神圣职责。对于天下三分之二的受苦人,我是这么想的:与其大呼小叫说要去解放他们、让人家苦等,倒不如一声不吭。忽然有一天把他们解放,给他们一个意外惊喜。 总而言之,我总是从实际的方面去考虑,而且考虑得很周到。智者千虑尚且难免一失,何况当年我只是个小孩子。我就没想到这些奇妙的话语只是说给自己听的,而且不准备当真去解放谁。总而言之,家教和天性谨慎,是我变得沉默的起因。 与沉默的大多数相反,任何年代都有人在公共场合喋喋不休。我觉得他们是少数人,可能有人会不同意。如福科先生所言,话语即权力。当我的同龄人开始说话时,给我一种极恶劣的印象。有位朋友写了一本书,写的是自己在文革中的遭遇,书名为《血统》。可以想见,她出身不好。她要我给她的书写个序。这件事使我想起来自己在那些年的所见所闻。 文革开始时,我十四岁,正上初中一年级。有一天,忽然发生了惊人的变化,班上的一部份同学忽然变成了红五类,另一部份则成了黑五类。我自己的情况特殊,还说不清是哪一类。当然,这红和黑的说法并不是我们发明出来,这个变化也不是由我们发起的。照我看来,红的同学忽然得到了很大的好处,这是值得祝贺的。黑的同学忽然遇上了很大的不幸,也值得同情。我不等对他们一一表示祝贺和同情,一些红的同学就把脑袋刮光,束上了大皮带,站在校门口,问每一个想进来的人:你什么出身?他们对同班同学问得格外仔细,一听到他们报出不好的出身,就从牙缝里迸出三个字:“狗崽子!”当然,我能理解他们突然变成了红五类的狂喜,但为此非要使自己的同学在大庭广众下变成狗崽子,未免也太过份。这使我以为,使用话语权是人前显贵,而且总都是为了好的目的。现在看来,我当年以为的未必对,但也未必全错。 话语有一个神圣的使命,就是想要证明说话者本身与众不同,是芸芸众生中的娇娇者。现在常听说的一种说法是:中国人拥有世界上最杰出的文化,在全世界一切人中最聪明。对此我不想唱任何一种反调,我也不想当人民公敌。我还持十几岁时的态度:假设这些都是实情,我们不妨把这些保藏在内心处不说,“闷兹蜜”。这些话讲出来是不好的,正如在文革时,你可以因自己是红五类而沾沾自喜,但不要到人前去显贵,更不要说别人是狗崽子。根除了此类话语,我们这里的话就会少很多,但也未尝不是好事。 现在我要说的是另一个题目:我上小学六年级时,暑期布置的读书作业是《南方来信》。那是一本记述越南人民抗美救国斗争的读物,其中充满了处决、拷打和虐杀。看完以后,心里充满了怪怪的想法。那时正在青春期的前沿,差一点要变成个性变态了。总而言之,假如对我的那种教育完全成功,换言之,假如那些园丁、人类灵魂的工程师对我的期望得以实现,我就想像不出现在我怎能不嗜杀成性、怎能不残忍,或者说,在我身上,怎么还会保留了一些人性。好在人不光是在书本上学习,还会在沉默中学习。这是我人性尚存的主因。 现在我就在发掘沉默,但不是作为一个社会科学工作者来发掘。这篇东西大体属于文学的范畴,所谓文学就是:先把文章写到好看,别的就管他妈的。现在我来说明自己为什么人性尚存。文化革命刚开始时,我住在一所大学里。有一天,我从校外回来,遇上一大夥人,正在向校门口行进。走在前面的是一夥大学生,彼此争论不休,而且嗓门很大;当然是在用时髦话语争吵,除了毛主席的教导,还经常提到“十六条”。所谓十六条,是中央颁布的展开文化革命的十六条规定,其中有一条叫作“要文斗、不要武斗”,制定出来就是供大家违反之用。在那些争论的人之中,有一个人居于中心地位。但他双唇紧闭,一声不吭,唇边似有血迹。在场的大学生有一半在追问他,要他开口说话,另一半则在维护他,不让他说话。 文化革命里到处都有两派之争,这是个具体的例子。至于队伍的后半部分,是一帮像我这么大的男孩子,一个个也是双唇紧闭,一声不吭,但唇边没有血迹,阴魂不散地跟在后面。有几个大学生想把他们拦住,但是不成功,你把正面拦住,他们就从侧面绕过去,但保持着一声不吭的态度。这件事相当古怪,因为我们院里的孩子相当的厉害,不但敢吵敢骂,而且动起手来,大学生还未必是个儿,那天真是令人意外的老实。我立刻投身其中,问他们出了什么事,怪的是这些孩子都不理我,继续双唇紧闭,两眼发直,显出一种坚忍的态度,继续向前行进──这情形好像他们发了一种集体性的癔症。 有关癔症,我们知道,有一种一声不吭,只顾扬尘舞蹈;另一种喋喋不休,就不大扬尘舞蹈。不管哪一种,心里想的和表现出来的完全不是一回事。我在北方插队时,村里有几个妇女有癔症,其中有一位,假如你信她的说法,她其实是个死去多年的狐狸,成天和丈夫(假定此说成立,这位丈夫就是个兽奸犯)吵吵闹闹,以狐狸的名义要求吃肉。但肉割来以后,她要求把肉煮熟,并以大蒜佐餐。很显然,这不合乎狐狸的饮食习惯。所以,实际上是她,而不是它要吃肉。至于文化革命,有几分像场集体性的癔症,大家闹的和心里想的也不是一回事。但是我说的那些大学里的男孩子其实没有犯癔症。后来,我揪住了一个和我很熟的孩子,问出了这件事的始末:原来,在大学生宿舍的盥洗室里,有两个学生在洗脸时相遇,为各自不同的观点争辩起来。争着争着,就打了起来。其中一位受了伤,已被送到医院。另一位没受伤,理所当然地成了打人凶手,就是走在队伍前列的那一位。这一大夥人在理论上是前往某个机构(叫作校革委还是筹委会,我已经不记得了)讲理,实际上是在校园里做无目标的布朗运动。 这个故事还有另一个线索:被打伤的学生血肉模糊,有一只耳朵(是左耳还是右耳已经记不得,但我肯定是两者之一)的一部份不见了,在现场也没有找到。根据一种安加莎·克里斯蒂式的推理,这块耳朵不会在别的地方,只能在打人的学生嘴里,假如他还没把它吃下去的话;因为此君不但脾气暴燥,急了的时候还会咬人,而且咬了不止一次了。我急于交待这件事的要点,忽略了一些细节,比方说,受伤的学生曾经惨叫了一声,别人就闻声而来,使打人者没有机会把耳朵吐出来藏起来,等等。总之,此君现在只有两个选择,或是在大庭广众之中把耳朵吐出来,证明自己的品行恶劣,或者把它吞下去。我听到这些话,马上就加入了尾随的行列,双唇紧闭,牙关紧咬,并且感觉到自己嘴里仿佛含了一块咸咸的东西。 现在我必须承认,我没有看到那件事的结局;因为天晚了,回家太晚会有麻烦。但我的确关心着这件事的进展,几乎失眠。这件事的结局是别人告诉我的:最后,那个咬人的学生把耳朵吐了出来,并且被人逮住了。不知你会怎么看,反正当时我觉得如释重负:不管怎么说,人性尚且存在。同类不会相食,也不会把别人的一部份吞下去。当然,这件事可能会说明一些别的东西:比方说,咬掉的耳朵块太大,咬人的学生嗓子眼太细,但这些可能性我都不愿意考虑。我说到这件事,是想说明我自己曾在沉默中学到了一点东西,而这些东西是好的。这是我选择沉默的主要原因之一:从话语中,你很少能学到人性,从沉默中却能。假如还想学得更多,那就要继续一声不吭。 有一件事大多数人都知道:我们可以在沉默和话语两种文化中选择。我个人经历过很多选择的机会,比方说,插队的时候,有些插友就选择了说点什么,到“积代会”上去“讲用”,然后就会有些好处。有些话年轻的朋友不熟悉,我只能简单地解释道:积代会是“活学活用毛主席著作积极分子代表大会”,讲用是指讲自己活学活用毛主席著作的心得体会。参加了积代会,就是积极分子。而积极分子是个好意思。 另一种机会是当学生时,假如在会上积极发言,再积极参加社会活动,就可能当学生干部,学生干部又是个好意思。这些机会我都自愿地放弃了。选择了说话的朋友可能不相信我是自愿放弃的,他们会认为,我不会说话或者不够档次,不配说话。因为话语即权力,权力又是个好意思,所以的确有不少人挖空心思要打进话语的圈子,甚至在争夺“话语权”。我说我是自愿放弃的,有人会不信──好在还有不少人会相信。主要的原因是进了那个圈子就要说那种话,甚至要以那种话来思索,我觉得不够有意思。据我所知,那个圈子里常常犯着贫乏症。 二十多年前,我在云南当知青。除了穿着比较乾净、皮肤比较白晰之外,当地人怎么看待我们,是个很费猜的问题。我觉得,他们以为我们都是台面上的人,必须用台面上的语言和我们交谈──最起码在我们刚去时,他们是这样想的。这当然是一个误会,但并不讨厌。还有个讨厌的误会是:他们以为我们很有钱,在集市上死命地朝我们要高价,以致我们买点东西,总要比当地人多花一两倍的钱。 后来我们就用一种独特的方法买东西:不还价,甩下一叠毛票让你慢慢数,同时把货物抱走。等你数清了毛票,连人带货都找不到了。起初我们给的是公道价,后来有人就越给越少,甚至在毛票里杂有些分票。假如我说自己洁身自好,没干过这种事,你一定不相信;所以我决定不争辩。终于有一天,有个学生在这样买东西时被老乡扯住了;但这个人决不是我。那位老乡决定要说该同学一顿,期期艾艾地憋了好半天,才说出:哇!不行啦!思想啦!斗私批修啦!后来我们回家去,为该老乡的话语笑得打滚。可想而知,在今天,那老乡就会说:哇!不行啦!五讲啦!四美啦!三热爱啦!同样也会使我们笑得要死。从当时的情形和该老乡的情绪来看,他想说的只是一句很简单的话,那一句话的头一个字发音和洗澡的澡有些相似。 我举这个例子,绝不是讨了便宜又要卖乖,只是想说明一下话语的贫乏。用它来说话都相当困难,更不要说用它来思想了。话语圈子里的朋友会说,我举了一个很恶劣的例子----我记住这种事,只是为了丑化生活;但我自己觉得不是的。还有一些人会说,我们这些熟练掌握了话语的人在嘲笑贫下中农,这是个卑劣的行为。说实在的,那些话我虽耳熟,但让我把它当众讲出口来,那情形不见得比该老乡好很多。我希望自己朴实无华,说起话来,不要这样绕嘴,这样古怪,这样让人害怕。这也是我保持沉默的原因之一。 中国人有句古话:敬惜字纸。这话有古今两种通俗变体:古代人们说,用印了字的纸擦屁股要瞎眼睛;现代有种近似科学的说法:用有油墨的纸擦屁股会生痔疮。其实,真正要敬惜的根本就不是纸,而是字。文字神圣。我没听到外国有类似的说法,他们那里神圣的东西都与上帝有关。人间的事物要想神圣,必须经过上帝或者上帝在人间代理机构的认可。听说,天主教的主教就需要教皇来祝圣。相比之下,中国人就不需要这个手续。只要读点书,识点字,就可以写文章。写来写去,自祝自圣。这件事有好处,也有不好处。好处是达到神圣的手续甚为简便,坏处是写什么都要带点“圣”气,就丧失了平常心。我现在在写字,写什么才能不亵渎我神圣的笔,真是个艰巨的问题。古代和近代有两种方法可以壮我的胆。古代的方法是,文章要从夫子曰开始。近代的方法是从“毛主席教导我们说”开始。这两种方法我都不拟采用。其结果必然是:这篇文字和我以往任何一篇文字一样,没有丝毫的神圣性。我们所知道、并且可以交流的信息有三级:一种心知肚明,但既不可说也不可写。 另一种可说不可写,我写小说,有时就写出些汉语拼音来。最后一种是可以写出来的。当然,说得出的必做得出,写得出的既做得出也说得出;此理甚明。人们对最后这类信息交流方式抱有崇敬之情。在这方面我有一个例子:我在云南插队时,有一阵是记工员。队里的人感觉不舒服不想上工,就给我写张假条。有一天,队里有个小伙子感觉屁股疼,不想上工。他可以用第一种方式通知我,到我屋里来,指指屁股,再苦苦脸,我就会明白。用第二种方法也甚简便。不幸他用了第三种方式。我收到那张条子,看到上面写着“龟xx疼”,就照记下来。后来这件事就传扬开来,队里的人还说,他得了杨梅大疮,否则不会疼在那个部位上。因此他找到我,还威胁说要杀掉我。经过核实原始凭据,发现他想按书面语言,写成臀部疼,不幸写成了“电布疼”,除此之外,还写得十分歪歪斜斜。以致我除了认做龟xx疼,别无他法。其实呢,假如他写屁股疼,我想他是能写出的;此人既不是龟xx疼,也不是屁股疼,而是得了痔疮;不过这一点已经无关紧要了。要紧的是人们对于书面话语的崇敬之情。假如这种话语不仅是写了出来,而且还印了出来,那它简直就是神圣的了。但不管怎么说罢,我希望人们在说话和写文章时,要有点平常心。屁股疼就说屁股疼,不要写电布疼。至于我自己,丝毫也不相信有任何一种话语是神圣的。缺少了这种虔诚,也就不配来说话。我所说的一切全都过去了。似乎没有必要保持沉默了。如前所述,我曾经是个沉默的人,这就是说,我不喜欢在各种会议上发言,也不喜欢写稿子。这一点最近已经发生了改变,参加会议时也会发言,有时也写点稿。对这种改变我有种强烈的感受,有如丧失了童贞。这就意味着我违背了多年以来的积习,不再属于沉默的大多数了。 我还不致为此感到痛苦,但也有一点轻微的失落感,我们的话语圈从五十年代起,就没说过正常的话:既鼓吹过亩产三十万吨钢,也炸过精神原子弹。说得不好听,它是座声名狼籍的疯人院。如今我投身其中,只能有两种可能:一是它正常了,二是我疯掉了,两者必居其一。我当然想要弄个明白,但我无法验证自己疯没疯。在这方面有个例子:当年里根先生以七十以上的高龄竞选总统,有人问他:假如你当总统以后老糊涂了怎么办?里根先生答道:没有问题。假如我老糊涂了,一定交权给副总统。然后人家又问:你老糊涂了以后,怎能知道自己老糊涂了?他就无言以对。这个例子对我也适用:假如我疯掉了,一定以为自己没有疯。我觉得话语圈子比我容易验证一些。 假如你相信我的说法,沉默的大多数比较谦虚、比较朴直、不那么假正经,而且有较健全的人性。如果反过来,说那少数说话的人有很多毛病,那也是不对的。不过他们的确有缺少平常心的毛病。 几年前,我参加了一些社会学研究,因此接触了一些“弱势群体”,其中最特别的就是同性恋者。做过了这些研究之后,我忽然猛省到:所谓弱势群体,就是有些话没有说出来的人。就是因为这些话没有说出来,所以很多人以为他们不存在或者很遥远。在中国,人们以为同性恋者不存在。在外国,人们知道同性恋者存在,但不知他们是谁。有两位人类学家给同性恋者写了一本书,题目就叫做《Wordisout》。然后我又猛省到自己也属于古往今来最大的一个弱势群体,就是沉默的大多数。这些人保持沉默的原因多种多样,有些人没能力、或者没有机会说话;还有人有些隐情不便说话;还有一些人,因为种种原因,对于话语的世界有某种厌恶之情。我就属于这最后一种。 对我来说,这是青少年时代养成的习惯,是一种难改的积习。小时候我贫嘴聊舌,到了一定的岁数之后就开始沉默寡言。当然,这不意味着我不会说话──在私下里我说的话比任何人都不少──这只意味着我放弃了权力。不说话的人不仅没有权力,而且会被人看做不存在,因为人们不会知道你。 我曾经是个沉默的人,这就是说,我不喜欢在各种会议上发言,也不喜欢写稿子。这一点最近已经发生了改变,参加会议时也会发言,有时也写点稿。对这种改变我有种强烈的感受,有如丧失了童贞。这就意味着我违背了多年以来的积习,不再属于沉默的大多数了。我还不至为此感到痛苦,但也有一点轻微的失落感。现在我负有双重任务,要向保持沉默的人说明,现在我为什么要进入话语的圈子;又要向在话语圈子里的人说明,我当初为什么要保持沉默,而且很可能在两面都不落好。照我看来,头一个问题比较容易回答。我发现在沉默的人中间,有些话永远说不出来。照我看,这件事是很不对的。因此我就很想要说些话。当然,话语的圈子里自然有它的逻辑,和我这种逻辑有些距离。虽然大家心知肚明,但我还要说一句,话语圈子里的人有作家、社会科学工作者,还有些别的人。出于对最后一些人的尊重,就不说他们是谁了──其实他们是这个圈子的主宰。我曾经是个社会科学工作者,那时我想,社会科学的任务之一,就是发掘沉默。就我所知,持我这种立场的人不会有好下场。不过,我还是想做这件事。 第二个问题是:我当初为什么要保持沉默。这个问题难回答,是因为它涉及到一系列复杂的感觉。一个人决定了不说话,他的理由在话语圈子里就是说不清的。但是,我当初面对的话语圈和现在的话语圈已经不是一个了──虽然它们有一脉相承之处。 在今天的话语圈里,也许我能说明当初保持沉默的理由。而在今后的话语圈里,人们又能说明今天保持沉默的理由。沉默的说明总是要滞后于沉默。倘若你问,我是不是依然部份地保持了沉默,就是明知故问──不管怎么说,我还是决定了要说说昨天的事。但是要慢慢地说。 七八年前,我在海外留学,遇上一位老一辈的华人教授。聊天的时候他问:你们把太太叫作“爱人”──那么,把lover叫做什么?我呆了一下说道:叫作“第三者”罢。他朝我哈哈大笑了一阵,使我感觉受到了暗算,很不是滋味。回去狠狠想了一下,想出了一大堆:情人、傍肩儿、拉边套的、乱搞男女关系的家伙、破鞋或者野汉子,越想越歪。人家问的是我们所爱的人应该称作什么,我竟答不上来。倘若说大陆上全体中国人就只爱老婆或老公,别人一概不爱,那又透着虚伪。最后我只能承认:这个称呼在话语里是没有的,我们只是心知肚明,除了老婆和老公,我们还爱过别人。以我自己为例,我老婆还没有和我结婚时,我就开始爱她。此时她只是我的女朋友。根据话语的逻辑,我该从领到了结婚证那一刻开始爱她,既不能迟,也不能早。不过我很怀疑谁控制自己感情的能力有这么老到。由此可以得到两个推论:其一,完全按照话语的逻辑来生存,实在是困难得很。其二:创造话语的人是一批假正经。沿着第一个推理前进,会遇上一堆老话。越是困难,越是要上;存天理灭人欲嘛──那些陈糠烂谷子太多了,不提也罢。让我们沿着第二条道路前进:“爱人”这个字眼让我们想到什么?做爱。这是个外来语,从makelove硬译而来。本土的词儿最常用有两个,一个太粗,根本不能写。另外一个叫作“敦伦”。这个词儿实在有意思。假如有人说,他总是以敦厚人伦的虔敬心情来干这件事,我倒想要认识他,因为他将是我所认识的最不要脸的假正经。为了捍卫这种神圣性,做爱才被叫作“敦伦”。 现在可以说说我当初保持沉默的原因。时至今日,哪怕你借我个胆子,我也不敢说自己厌恶神圣。我只敢说我厌恶自己说自己神圣,而且这也是实情。 在一个科幻故事里,有个科学家造了一个机器人,各方面都和人一样,甚至和人一样的聪明,但还不像人。因为缺少自豪感,或者说是缺少自命不凡的天性。这位科学家就给该机器人装上了一条男根。我很怀疑科学家的想法是正确的。照我看来,他只消给机器人装上一个程序,让他到处去对别人说:我们机器人是世界上最优越的物种,就和人是一样的了。 但是要把这种经历作为教学方法来推广是不合适的。特别是不能用咬耳朵的方法来教给大家人性的道理,因为要是咬人耳的话,被咬的人很疼,咬猪耳的话,效果又太差。所以,需要有文学和社会科学。我也要挤入那个话语圈,虽然这个时而激昂、时而消沉,时而狂吠不止、时而一声不吭的圈子,在过去几十年里从来就没教给人一点好的东西,但我还要挤进去。
Java
UTF-8
274
2.8125
3
[]
no_license
public class Zad6 { public static void main(String[] args) { for (int i = 0; i <= 100000; i++){ if (i%3==0 && i%5==0 && i%7==0){ System.out.println("i = " + i + " i jest podzielne przez 3, 5 i 7"); } } } }
Python
UTF-8
2,502
3.28125
3
[]
no_license
''' AUTHORS: Dinindu Thilakarathna [dininduwm@gmail.com] ''' from csv import writer from os import walk import json import datetime, pytz # path for the events event_path = 'events/' csv_file = 'data/data.csv' # event list event_list = [] # headers of the data headers = ["date","time","description","link","registration","additional_info","tags"] # format and validate data def formatAndValidateData(data): dtobj1=datetime.datetime.utcnow() #utcnow class method # print(dtobj1) dtobj3=dtobj1.replace(tzinfo=pytz.UTC) #replace method dtobj_sl=dtobj3.astimezone(pytz.timezone("Asia/Colombo")) #astimezone method if data[0] >= datetime.datetime.strftime(dtobj_sl, '%Y-%m-%d'): for index in range(len(data)): if (type(data[index]) == list): data[index] = ','.join(data[index]) data[index] = f'"{data[index]}"' # print(data[index]) return data return False # add to the data.csv fule def genarateCSVFile(file_name): # Open file in append mode with open(file_name, 'w', newline='') as write_obj: # Create a writer object from csv module csv_writer = writer(write_obj) # add the headers to the csv csv_writer.writerow(headers) # Add contents to the csv file for event in event_list: csv_writer.writerow(event) # get file list to read def genarateEventList(): filenames = next(walk(event_path), (None, None, []))[2] for file in filenames: # separating the json files if file.split('.')[-1] == 'json': file_path = event_path + file # opening the file f = open(file_path, "r") # try to pars json doc try: data = f.read() decodedData = json.loads(data) # print(decodedData) tmpList = [] for title in headers: if title in decodedData: tmpList.append(decodedData[title]) else: tmpList.append("") except Exception as e: print (e) # add to the event list validatedData = formatAndValidateData(tmpList) if (validatedData): event_list.append(validatedData) # Append a list as new line to an old csv file # append_list_as_row('data/data.csv', row_contents) genarateEventList() # print(event_list) genarateCSVFile(csv_file)
Java
UTF-8
528
1.898438
2
[]
no_license
package com.kaishengit.mapper; import com.kaishengit.pojo.User; import java.util.List; import java.util.Map; /** * Created by liu on 2017/3/17. */ public interface UserMapper { User findByUserName(String username); Long findAll(); Long findAllByQueryParam(Map<String, Object> queryParam); List<User> findUserByQueryParam(Map<String, Object> queryParam); void save(User user); User findUserById(Integer id); void update(User user); List<User> findByParam(Map<String, Object> param); }
Markdown
UTF-8
2,365
3.296875
3
[ "Apache-2.0", "MIT" ]
permissive
# Advanced Example There will be sections of the wiki to go into these in detail, but this is an example of a table with a custom row, filters, search, custom view: ```php <?php namespace App\Http\Livewire; use App\Models\User; use Illuminate\Container\Container; use Illuminate\Database\Eloquent\Builder; use Luckykenlin\LivewireTables\Components\BooleanFilter; use Luckykenlin\LivewireTables\LivewireTables; use Luckykenlin\LivewireTables\Views\Action; use Luckykenlin\LivewireTables\Views\Boolean; use Luckykenlin\LivewireTables\Views\Column; class UserTable extends LivewireTables { public function query(): Builder { return User::query(); } public function columns(): array { return [ Column::make('#', 'id')->sortable(), // custom view Column::make('Status')->render(fn(User $user) => view('users.status', ['user'=>$user])), Column::make('Avatar')->render(fn(User $user) => view('users.avatar', ['user'=>$user])), Column::make('Name')->sortable()->searchable(), // format value Column::make('Phone')->sortable() ->searchable() ->format(fn($v) => '(+1)'.$v), // add class to column Column::make('Address') ->addClass('text-red-700'), Column::make('Email') ->sortable() ->searchable() ->render(fn(User $user) => view('users.email', ['user' => $user])), // format value as html Boolean::make('Admin', 'is_admin') ->sortable() ->format(fn($v) => '<span class="text-green-300">' . $v . '</span>') ->asHtml(), Column::make('Created At') ->sortable() ->format(fn(Carbon $v) => $v->diffForHumans()), // sticky on right with default actions (show, edit, delete) Action::make()->sticky() ]; } public function filters(): array { return [ BooleanFilter::make('is_admin') ]; } /* * Table row click callback. */ public function rowOnClick(User $user) { return redirect(route('users.edit', $user->id)); } } ```
Go
UTF-8
824
2.65625
3
[]
no_license
package main import ( "context" "io" "log" "time" pb "github.com/wagaru/microservice/streaming-server/gen/pb-go/helloworld" "google.golang.org/grpc" ) const ( address = "localhost:50052" defaultName = "world" ) func main() { conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock()) if err != nil { log.Fatalf("did not connect: %v", err) } defer conn.Close() c := pb.NewGreeterClient(conn) ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) defer cancel() stream, err := c.SayHello(ctx, &pb.HelloRequest{Name: defaultName}) if err != nil { log.Fatalf("could not greet: %v", err) } for { reply, err := stream.Recv() if err == io.EOF { break } if err != nil { log.Fatalf("stream read failed: %v", err) } log.Println(reply.GetMessage()) } }
Java
UTF-8
2,754
3.859375
4
[]
no_license
package com.concurrent; import java.util.Arrays; /** * @author hujing * @date Create in 2020/9/23 * 大顶堆实现 **/ public class HeapDemo { public static void main(String[] args) { Heap heap = new Heap(10); heap.add(5); heap.add(3); heap.add(4); heap.add(7); heap.add(9); heap.add(1); heap.add(2); System.out.println(Arrays.toString(heap.data)); } static class Heap { private final int[] data; private int size; Heap(int capacity) { data = new int[capacity + 1]; size = 0; } Heap(int[] source) { build(source); data = source; size = source.length - 1; } //堆排序,将一个数组构建成堆 private void build(int[] source) { //从最后一个非叶子节点向上进行堆化即可 int size = source.length - 1; for (int i = size / 2; i >= 1; i--) { heapify(source, size, i); } } //堆排序 public void sort() { //依次取出堆顶元素放置到末尾 for (; ; ) { if (size == 0) return; int i = 1; swap(data, size--, 1); heapify(data, size, i); } } //添加,从下往上堆化 public void add(int val) { if (size >= data.length - 1) { System.out.println("元素满了"); return; } int i = ++size; data[i] = val; while (i / 2 >= 1 && data[i / 2] < val) { data[i] = data[i / 2]; i = i / 2; } data[i] = val; } //交换结尾,从上往下堆化 public int remove() { if (size == 0) { return -1; } int result = data[1]; swap(data, size, 1); data[size--] = 0; //从上往下堆化 heapify(data, size, 1); return result; } public void heapify(int[] data, int n, int i) { for (; ; ) { int maxPos = i; if (2 * i <= n && data[i] < data[i * 2]) maxPos = 2 * i; if (2 * i + 1 <= n && data[maxPos] < data[2 * i + 1]) maxPos = 2 * i + 1; if (maxPos == i) { break; } swap(data, i, maxPos); i = maxPos; } } public void swap(int[] a, int x, int y) { int tmp = a[x]; a[x] = a[y]; a[y] = tmp; } } }
Shell
UTF-8
549
3.453125
3
[ "MIT" ]
permissive
#!/bin/bash # Copyright (C) 2015 Jeffrey Meyers # This program is released under the "MIT License". # Please see the file COPYING in the source # distribution of this software for license terms. # ./add_user.sh <username> <password> db=$1 db_user=$2 username=$3 password=$4 pass_hash=$(echo -n ${password} | sha256sum | awk -F ' ' '{ print $1 }') insert="INSERT INTO users (username, password_hash) VALUES" insert="${insert} ('${username}', '${pass_hash}');" echo ${username} ${password} ${pass_hash} su -c "psql -c \"${insert}\" -d ${db}" ${db_user}
Python
UTF-8
3,071
2.5625
3
[]
no_license
import cv2 import numpy as np import tensorflow as tf import tensorflow.keras as keras import matplotlib.pyplot as plt model = keras.models.load_model('./models/face_net.h5') face_cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml') font = cv2.FONT_HERSHEY_SIMPLEX fontScale = 0.8 fontColor = (0,0,255) lineType = 1 eth_list = ['Asian', 'Black', 'Hispanic', 'Indian', 'White'] age_mapping = {0:'<10', 1:'11-15', 2:'16-20', 3:'21-25', 4:'26-30', 5:'31-35', 6:'36-42', 7:'43-50', 8:'51-60', 9:'>60'} def main(): gender_string, age_string, eth_string = 'Detecting..', 'Detecting..', 'Detecting..' cap = cv2.VideoCapture(0) while 1: ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) i = 0 for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2) # Get the face image & resize face = gray[y:y + h, x:x + w] face = cv2.resize(face, dsize=(48,48), interpolation=cv2.INTER_AREA) face = face/255.0 face = np.reshape(face, (1, 48,48)) # Output of from the odel output = model.predict(face) age, gender, eth = np.argmax(output[0]), round(output[1][0][0]), np.argmax(output[2]) gender_string = 'Male' if gender==0 else 'Female' age_string = f'Age: {age_mapping[age]}' eth_string = f'Ethnicity: {eth_list[eth]}' # The text needs to be put on every frame cv2.putText(img,gender_string, (x,y), font, fontScale, fontColor, lineType) cv2.putText(img, age_string, (x+w,y+h), font, fontScale, fontColor, lineType) cv2.putText(img, eth_string, (x+w,y+h+25), font, fontScale, fontColor, lineType) roi_gray = gray[y:y + h, x:x + w] roi_color = img[y:y + h, x:x + w] # Not more than 3 faces if i==3: break i+=1 cv2.imshow('img', img) if cv2.waitKey(1) & 0xFF==ord('q'): break cap.release() cv2.destroyAllWindows() if __name__=='__main__': main()
Python
UTF-8
453
2.625
3
[]
no_license
import os import glob # response = input("This will remove all log files.... Continue? y/n\n") # if response == 'y': # exp1 = glob.glob('../logs/exp1/*') # exp2 = glob.glob('../logs/exp2/*') # for f1 in exp1: # os.remove(f1) # for f2 in exp2: # os.remove(f2) # else: # quit() exp1 = glob.glob('../logs/exp1/*') exp2 = glob.glob('../logs/exp2/*') for f1 in exp1: os.remove(f1) for f2 in exp2: os.remove(f2)
Python
UTF-8
7,513
3.1875
3
[ "Apache-2.0" ]
permissive
""" CNN Model: Handles anything related to the Convolutional Neural Network """ import torch import numpy as np # import PyTorch Functionalities import torch.nn.functional as F import torch.nn as nn # import own modules import loghub ''' //////////////////////////////////////////////////////////////////////////////////// /// Transpose / Normalization Functions //// //////////////////////////////////////////////////////////////////////////////////// ''' # Creates a Tensor from the Numpy dataset, which is used by the GPU for processing class ToTensor(object): def __call__(self, sample): data, label = sample # swap color axis if needed : This function is not doing anything for now. data = data.transpose((0, 1, 2)) return torch.from_numpy(data), torch.from_numpy(label) # Code for Normalization of the data class Normalize(object): def __init__(self, mean, std): self.mean, self.std = mean, std def __call__(self, sample): data, label = sample data = (data - self.mean)/self.std return data, label ''' //////////////////////////////////////////////////////////////////////////////////// /// Convolution Neural Network Model Class //// //////////////////////////////////////////////////////////////////////////////////// ''' class BaselineASC(nn.Module): def __init__(self, in_channel): # the main CNN model -- this function initializes the layers. NOTE THAT we are not performing the conv/pooling operations in this function (this is just the definition) super(BaselineASC, self).__init__() # first conv layer, extracts 32 feature maps from 1 channel input self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=32, kernel_size=11, stride=1, padding=5) # batch normalization layer self.conv1_bn = nn.BatchNorm2d(32) # max pooling of 5x5 self.mp1 = nn.MaxPool2d((5,5)) # dropout layer, for regularization of the model (efficient learning) self.drop1 = nn.Dropout(0.3) self.conv2 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=5, stride=1, padding=2) self.conv2_bn = nn.BatchNorm2d(64) self.mp2 = nn.MaxPool2d((4,100)) self.drop2 = nn.Dropout(0.3) # a dense layer self.fc1 = nn.Linear(1*2*64, 100) self.drop3 = nn.Dropout(0.3) self.fc2 = nn.Linear(100, 10) def forward(self, x): # feed-forward propagation of the model. Here we have the input x, which is propagated through the layers # x has dimension (batch_size, channels, mel_bins, time_indices) - for this model (16, 1, 40, 500) # perfrom first convolution x = self.conv1(x) # batch normalization x = self.conv1_bn(x) # ReLU activation x = F.relu(x) # Max pooling, results in 32 8x100 feature maps [output -> (16, 32, 8, 100)] x = self.mp1(x) # apply dropout x = self.drop1(x) # next convolution layer (results in 64 feature maps) output: (16, 64, 4, 100) x = self.conv2(x) x = self.conv2_bn(x) x = F.relu(x) # max pooling of 4, 100. Results in 64 2x1 feature maps (16, 64, 2, 1) x = self.mp2(x) x = self.drop2(x) # Flatten the layer into 64x2x1 neurons, results in a 128D feature vector (16, 128) x = x.view(-1, 1*2*64) # add a dense layer, results in 100D feature vector (16, 100) x = self.fc1(x) x = F.relu(x) x = self.drop3(x) # add the final output layer, results in 10D feature vector (16, 10) x = self.fc2(x) # add log_softmax for the label return F.log_softmax(x, dim=1) def train(args, model, device, train_loader, optimizer, epoch): model.train() # training module for batch_idx, sample_batched in enumerate(train_loader): # for every batch, extract data (16, 1, 40, 500) and label (16, 1) data, label = sample_batched # Map the variables to the current device (CPU or GPU) data = data.to(device, dtype=torch.float) label = label.to(device, dtype=torch.long) # set initial gradients to zero : https://discuss.pytorch.org/t/why-do-we-need-to-set-the-gradients-manually-to-zero-in-pytorch/4903/9 optimizer.zero_grad() # pass the data into the model output = model(data) # get the loss using the predictions and the label loss = F.nll_loss(output, label) # backpropagate the losses loss.backward() # update the model parameters : https://discuss.pytorch.org/t/how-are-optimizer-step-and-loss-backward-related/7350 optimizer.step() # Printing the results if batch_idx % args.log_interval == 0: #print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( # epoch, batch_idx * len(data), len(train_loader.dataset), # 100. * batch_idx / len(train_loader), loss.item())) loghub.logMsg(msg="{}: Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}".format( __name__, epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item()), otherlogs=["test_acc"]) def test(args, model, device, test_loader, data_type): # evaluate the model model.eval() # init test loss test_loss = 0 correct = 0 pred_results = np.asarray([]) #print('Testing..') loghub.logMsg(msg="{}: Testing...".format(__name__), otherlogs=["test_acc"]) # Use no gradient backpropagations (as we are just testing) with torch.no_grad(): # for every testing batch for i_batch, sample_batched in enumerate(test_loader): # for every batch, extract data (16, 1, 40, 500) and label (16, 1) data, label = sample_batched # Map the variables to the current device (CPU or GPU) data = data.to(device, dtype=torch.float) label = label.to(device, dtype=torch.long) # get the predictions output = model(data) # accumulate the batchwise loss test_loss += F.nll_loss(output, label, reduction='sum').item() # get the predictions pred = output.argmax(dim=1, keepdim=True) # accumulate the correct predictions correct += pred.eq(label.view_as(pred)).sum().item() # collate the predicted results pred = np.squeeze(pred.cpu().numpy()) pred_results = np.concatenate((pred_results, pred)) # normalize the test loss with the number of test samples test_loss /= len(test_loader.dataset) # print the results #print('Model prediction on ' + data_type + ': Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format( # test_loss, correct, len(test_loader.dataset), # 100. * correct / len(test_loader.dataset))) loghub.logMsg(msg="{}: Model prediction on {}: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n".format( __name__, data_type, test_loss, correct, len(test_loader.dataset), 100. * correct / len(test_loader.dataset)), otherlogs=["test_acc"]) return pred_results def predict(model, device, test_loader): # evaluate the model model.eval() pred_results = np.asarray([]) #test_pred = torch.LongTensor() #print('Testing..') loghub.logMsg(msg="{}: Predicting...".format(__name__), otherlogs=["test_acc"]) # Use no gradient backpropagations (as we are just testing) with torch.no_grad(): # for every testing batch for i_batch, sample_batched in enumerate(test_loader): # for every batch, extract data (16, 1, 40, 500) and label (16, 1) data, invalid_label = sample_batched # Map the variables to the current device (CPU or GPU) data = data.to(device, dtype=torch.float) # get the predictions output = model(data) # get the predictions pred = output.argmax(dim=1, keepdim=True) # collate the predicted results pred = np.squeeze(pred.cpu().numpy()) pred_results = np.concatenate((pred_results, pred)) #test_pred = torch.cat((test_pred, pred), dim=0) return pred_results
Java
UTF-8
1,411
2.28125
2
[]
no_license
package ipstore.aspect.change; import ipstore.entity.*; /** * Here will be javadoc * * @author karlovsky * @since 2.5.0, 4/8/13 */ public enum ChangeType { NONE, // 0 ACCOUNTS(Account.class, AccountChangeField.class, "/accounts/"), // 1 EQUIPMENT(Equipment.class, EquipmentChangeField.class, "/equipment/"), // 2 COMMUNIGATE(CommunigateDomain.class, CommunigateChangeField.class, "/communigate/"), // 3 USERS(User.class, UsersChangeField.class, "/users/"); // 4 private Class<? extends IHasId> entityClazz; private Class<? extends IChangeField> fieldsClazz; private String viewPageURL; private ChangeType() { } private ChangeType(Class<? extends IHasId> entityClazz, Class<? extends IChangeField> fieldsClazz, String viewPageURL) { this.entityClazz = entityClazz; this.fieldsClazz = fieldsClazz; this.viewPageURL = viewPageURL; } public IChangeField[] getIChangeFields() { return fieldsClazz != null ? fieldsClazz.getEnumConstants() : null; } public Class<? extends IHasId> getEntityClazz() { return entityClazz; } public String getViewPageURL() { return viewPageURL; } }
Markdown
UTF-8
1,818
2.578125
3
[ "Apache-2.0" ]
permissive
[clikt](../index.md) / [com.github.ajalt.clikt.parameters.options](index.md) / [transformAll](./transform-all.md) # transformAll `fun <AllT, EachT : `[`Any`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/index.html)`, ValueT> `[`NullableOption`](-nullable-option.md)`<`[`EachT`](transform-all.md#EachT)`, `[`ValueT`](transform-all.md#ValueT)`>.transformAll(defaultForHelp: `[`String`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-string/index.html)`? = this.helpTags[HelpFormatter.Tags.DEFAULT], showAsRequired: `[`Boolean`](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-boolean/index.html)` = HelpFormatter.Tags.REQUIRED in this.helpTags, transform: `[`CallsTransformer`](-calls-transformer.md)`<`[`EachT`](transform-all.md#EachT)`, `[`AllT`](transform-all.md#AllT)`>): `[`OptionWithValues`](-option-with-values/index.md)`<`[`AllT`](transform-all.md#AllT)`, `[`EachT`](transform-all.md#EachT)`, `[`ValueT`](transform-all.md#ValueT)`>` Transform all calls to the option to the final option type. The input is a list of calls, one for each time the option appears on the command line. The values in the list are the output of calls to [transformValues](transform-values.md). If the option does not appear from any source (command line or envvar), this will be called with an empty list. Used to implement functions like [default](default.md) and [multiple](multiple.md). ### Parameters `defaultForHelp` - The help text for this option's default value if the help formatter is configured to show them, or null if this option has no default or the default value should not be shown.This does not affect behavior outside of help formatting. `showAsRequired` - Tell the help formatter that this option should be marked as required. This does not affect behavior outside of help formatting.
Java
UTF-8
10,442
2.328125
2
[]
no_license
package noppes.mpm.client.model.part.legs; import net.minecraft.client.model.ModelBase; import net.minecraft.client.model.ModelRenderer; import net.minecraft.entity.Entity; import net.minecraft.util.MathHelper; import noppes.mpm.client.model.ModelPlaneRenderer; import org.lwjgl.opengl.GL11; public class ModelNagaLegs extends ModelRenderer { public boolean isRiding = false; public boolean isSneaking = false; public boolean isSleeping = false; public boolean isCrawling = false; private ModelRenderer nagaPart1; private ModelRenderer nagaPart2; private ModelRenderer nagaPart3; private ModelRenderer nagaPart4; private ModelRenderer nagaPart5; public ModelNagaLegs(ModelBase base) { super(base); this.nagaPart1 = new ModelRenderer(base, 0, 0); ModelRenderer legPart = new ModelRenderer(base, 0, 16); legPart.addBox(0, -2, -2, 4, 4, 4); legPart.setRotationPoint(-4, 0, 0); this.nagaPart1.addChild(legPart); legPart = new ModelRenderer(base, 0, 16); legPart.mirror = true; legPart.addBox(0, -2, -2, 4, 4, 4); this.nagaPart1.addChild(legPart); { this.nagaPart2 = new ModelRenderer(base, 0, 0); final int wid = 4, hei = 4, dep = 4; final int xTx = 0, yTx = 24; // Front ModelPlaneRenderer plane = new ModelPlaneRenderer(base, xTx + dep, yTx); plane.addBackPlane(-4, -2, -2, wid, hei); this.nagaPart2.addChild(plane); plane = new ModelPlaneRenderer(base, xTx + dep, yTx); plane.mirror = true; plane.addBackPlane(0, -2, -2, wid, hei); this.nagaPart2.addChild(plane); // Back plane = new ModelPlaneRenderer(base, xTx + dep * 2 + wid, yTx); plane.addBackPlane(0, -2, 2, wid, hei); this.nagaPart2.addChild(plane); plane = new ModelPlaneRenderer(base, xTx + dep * 2 + wid, yTx); plane.mirror = true; plane.addBackPlane(-4, -2, 2, wid, hei); this.nagaPart2.addChild(plane); // Top plane = new ModelPlaneRenderer(base, 4, yTx); plane.addTopPlane(-4, -2, -2, wid, dep); plane.rotateAngleX = (float) Math.PI; // Flip back and front this.nagaPart2.addChild(plane); plane = new ModelPlaneRenderer(base, 4, yTx); plane.mirror = true; plane.addTopPlane(0, -2, -2, wid, dep); plane.rotateAngleX = (float) Math.PI; // Flip back and front this.nagaPart2.addChild(plane); // Bottom plane = new ModelPlaneRenderer(base, 8, yTx); plane.addTopPlane(-4, -2, -2, wid, dep); this.nagaPart2.addChild(plane); plane = new ModelPlaneRenderer(base, 8, 26); plane.mirror = true; plane.addTopPlane(0, -2, -2, wid, dep); this.nagaPart2.addChild(plane); // Right plane = new ModelPlaneRenderer(base, 0, yTx); plane.rotateAngleX = (float) (Math.PI / 2); plane.addSidePlane(-4, -2, -2, dep, hei); this.nagaPart2.addChild(plane); // Left plane = new ModelPlaneRenderer(base, 0, yTx); plane.rotateAngleX = (float) (Math.PI / 2); plane.addSidePlane(4, -2, -2, dep, hei); this.nagaPart2.addChild(plane); } { this.nagaPart3 = new ModelRenderer(base, 0, 0); ModelPlaneRenderer plane = new ModelPlaneRenderer(base, 4, 28); plane.addBackPlane(0, -2, 0, 4, 4); plane.setRotationPoint(-4, 0, 0); this.nagaPart3.addChild(plane); plane = new ModelPlaneRenderer(base, 4, 28); plane.mirror = true; plane.addBackPlane(0, -2, 0, 4, 4); this.nagaPart3.addChild(plane); plane = new ModelPlaneRenderer(base, 8, 28); plane.addBackPlane(0, -2, 6, 4, 4); plane.setRotationPoint(-4, 0, 0); this.nagaPart3.addChild(plane); plane = new ModelPlaneRenderer(base, 8, 28); plane.mirror = true; plane.addBackPlane(0, -2, 6, 4, 4); this.nagaPart3.addChild(plane); plane = new ModelPlaneRenderer(base, 4, 26); plane.addTopPlane(0, -2, -6, 4, 6); plane.setRotationPoint(-4, 0, 0); plane.rotateAngleX = 3.1415927F; this.nagaPart3.addChild(plane); plane = new ModelPlaneRenderer(base, 4, 26); plane.mirror = true; plane.addTopPlane(0, -2, -6, 4, 6); plane.rotateAngleX = 3.1415927F; this.nagaPart3.addChild(plane); plane = new ModelPlaneRenderer(base, 8, 26); plane.addTopPlane(0, -2, 0, 4, 6); plane.setRotationPoint(-4, 0, 0); this.nagaPart3.addChild(plane); plane = new ModelPlaneRenderer(base, 8, 26); plane.mirror = true; plane.addTopPlane(0, -2, 0, 4, 6); this.nagaPart3.addChild(plane); plane = new ModelPlaneRenderer(base, 0, 26); plane.rotateAngleX = 1.5707964F; plane.addSidePlane(0, 0, -2, 6, 4); plane.setRotationPoint(-4, 0, 0); this.nagaPart3.addChild(plane); plane = new ModelPlaneRenderer(base, 0, 26); plane.rotateAngleX = 1.5707964F; plane.addSidePlane(4, 0, -2, 6, 4); this.nagaPart3.addChild(plane); } this.nagaPart4 = new ModelRenderer(base, 0, 0); this.nagaPart4.childModels = this.nagaPart3.childModels; this.nagaPart5 = new ModelRenderer(base, 0, 0); legPart = new ModelRenderer(base, 0, 36); legPart.addBox(0, 0, -2, 2, 5, 2); legPart.setRotationPoint(-2, 0, 0); legPart.rotateAngleX = 1.5707964F; this.nagaPart5.addChild(legPart); legPart = new ModelRenderer(base, 0, 36); legPart.mirror = true; legPart.addBox(0, 0, -2, 2, 5, 2); legPart.rotateAngleX = 1.5707964F; this.nagaPart5.addChild(legPart); if (childModels != null) childModels.clear(); addChild(this.nagaPart1); addChild(this.nagaPart2); addChild(this.nagaPart3); addChild(this.nagaPart4); addChild(this.nagaPart5); this.nagaPart1.setRotationPoint(0, 14, 0); this.nagaPart2.setRotationPoint(0, 18, 0.6F); this.nagaPart3.setRotationPoint(0, 22, -0.3F); this.nagaPart4.setRotationPoint(0, 22, 5); this.nagaPart5.setRotationPoint(0, 22, 10); } public void setRotationAngles(float par1, float par2, float par3, float par4, float par5, float par6, Entity entity) { this.nagaPart1.rotateAngleY = (MathHelper.cos(par1 * 0.6662F) * 0.26F * par2); this.nagaPart2.rotateAngleY = (MathHelper.cos(par1 * 0.6662F) * 0.5F * par2); this.nagaPart3.rotateAngleY = (MathHelper.cos(par1 * 0.6662F) * 0.26F * par2); this.nagaPart4.rotateAngleY = (-MathHelper.cos(par1 * 0.6662F) * 0.16F * par2); this.nagaPart5.rotateAngleY = (-MathHelper.cos(par1 * 0.6662F) * 0.3F * par2); this.nagaPart1.setRotationPoint(0, 14, 0); this.nagaPart2.setRotationPoint(0, 18, 0.6F); this.nagaPart3.setRotationPoint(0, 22, -0.3F); this.nagaPart4.setRotationPoint(0, 22, 5); this.nagaPart5.setRotationPoint(0, 22, 10); this.nagaPart1.rotateAngleX = 0; this.nagaPart2.rotateAngleX = 0; this.nagaPart3.rotateAngleX = 0; this.nagaPart4.rotateAngleX = 0; this.nagaPart5.rotateAngleX = 0; if ((this.isSleeping) || (this.isCrawling)) { this.nagaPart3.rotateAngleX = -1.5707964F; this.nagaPart4.rotateAngleX = -1.5707964F; this.nagaPart5.rotateAngleX = -1.5707964F; this.nagaPart3.rotationPointY -= 2; this.nagaPart3.rotationPointZ = 0.9F; this.nagaPart4.rotationPointY += 4; this.nagaPart4.rotationPointZ = 0.9F; this.nagaPart5.rotationPointY += 7; this.nagaPart5.rotationPointZ = 2.9F; } if (this.isRiding) { this.nagaPart1.rotationPointY -= 1; this.nagaPart1.rotateAngleX = -0.19634955F; this.nagaPart1.rotationPointZ = -1; this.nagaPart2.rotationPointY -= 4; this.nagaPart2.rotationPointZ = -1; this.nagaPart3.rotationPointY -= 9; this.nagaPart3.rotationPointZ -= 1; this.nagaPart4.rotationPointY -= 13; this.nagaPart4.rotationPointZ -= 1; this.nagaPart5.rotationPointY -= 9; this.nagaPart5.rotationPointZ -= 1; if (this.isSneaking) { this.nagaPart1.rotationPointZ += 5; this.nagaPart3.rotationPointZ += 5; this.nagaPart4.rotationPointZ += 5; this.nagaPart5.rotationPointZ += 4; this.nagaPart1.rotationPointY -= 1; this.nagaPart2.rotationPointY -= 1; this.nagaPart3.rotationPointY -= 1; this.nagaPart4.rotationPointY -= 1; this.nagaPart5.rotationPointY -= 1; } } else if (this.isSneaking) { this.nagaPart1.rotationPointY -= 1; this.nagaPart2.rotationPointY -= 1; this.nagaPart3.rotationPointY -= 1; this.nagaPart4.rotationPointY -= 1; this.nagaPart5.rotationPointY -= 1; this.nagaPart1.rotationPointZ = 5; this.nagaPart2.rotationPointZ = 3; } } public void render(float par7) { if ((this.isHidden) || (!this.showModel)) { return; } this.nagaPart1.render(par7); this.nagaPart3.render(par7); if (!this.isRiding) { this.nagaPart2.render(par7); } GL11.glPushMatrix(); GL11.glScalef(0.74F, 0.7F, 0.85F); GL11.glTranslatef(this.nagaPart3.rotateAngleY, 0.66F, 0.06F); this.nagaPart4.render(par7); GL11.glPopMatrix(); GL11.glPushMatrix(); GL11.glTranslatef(this.nagaPart3.rotateAngleY + this.nagaPart4.rotateAngleY, 0, 0); this.nagaPart5.render(par7); GL11.glPopMatrix(); } }
Python
UTF-8
1,257
2.765625
3
[ "MIT" ]
permissive
import os import sys import os.path dir_path = os.path.dirname(os.path.realpath(__file__)) def write_file_ecg_len(filepath): l=0 fopen = open(filepath) print(fopen.name) for line in fopen: l+=1 print(l) fw = open(filepath+".len",'w+') fw.write(str(l)) fopen.close() fw.close() return l def write_folder_len(folder=dir_path): for path, subdirs, files in os.walk(folder): for filename in files: if filename[-4:] != ".ecg": continue write_file_ecg_len(path+"\\"+filename) def file_ecg_samples_len(file)->int: size = -1 lenfile = file+".len" if os.path.exists(lenfile): lenfileopen = open(lenfile,'r') for line in lenfileopen: size = int(line) break else: size = write_file_ecg_len(file) return size def file_ecg_freq(file)->int: freq = -1 freqfile = file+".freq" if os.path.exists(freqfile): freqfileopen = open(freqfile,'r') for line in freqfileopen: try: freq = int(line) except: freq = -1 break else: return -1 return freq
Python
UTF-8
2,479
3.5
4
[]
no_license
''' Author: Qiming Chen Date Apr 30 2017 Description: A CUDA version to calculate the Mandelbrot set Usage: 1. setup cuda environment 2. python mandelbrot_gpu.py ''' from numba import cuda import numpy as np from pylab import imshow, show @cuda.jit(device=True) def mandel(x, y, max_iters): ''' Given the real and imaginary parts of a complex number, determine if it is a candidate for membership in the Mandelbrot set given a fixed number of iterations. ''' c = complex(x, y) z = 0.0j for i in range(max_iters): z = z*z + c if (z.real*z.real + z.imag*z.imag) >= 4: return i return max_iters @cuda.jit def compute_mandel(min_x, max_x, min_y, max_y, image, iters): ''' A GPU version of calculating the mandel value for each element in the image array. The real and imag variables contain a value for each element of the complex space defined by the X and Y boundaries (min_x, max_x) and (min_y, max_y). Step 1: define the absolute thread id (y, x) in (1024, 1536) and Step 2: define task size (e.g (1,12)) of each thread such to assign (1024 1536) tasks into (1024, 128) threads Step 3: finish tasks in each thread ''' grid_y, grid_x = cuda.gridsize(2) #(1024, 128) y, x = cuda.grid(2) # (y, x) where y is in [0, 1023] and x is in [0, 127] height, width = image.shape # 1024, 1536 pixel_size_x = (max_x - min_x) / width pixel_size_y = (max_y - min_y) / height # get the partition index of the y and x block_y = height // grid_y # 1 block_x = width // grid_x # 12 # every thread in (1024, 128) should handle (1, 12) tasks such that the totally (1024, 1536) tasks are evenly assigned for i in range(block_x): thread_x = x * block_x + i real = min_x + thread_x * pixel_size_x for j in range(block_y): thread_y = y * block_y+ j imag = min_y + thread_y * pixel_size_y if thread_y < height and thread_x < width: image[thread_y, thread_x] = mandel(real, imag, iters) if __name__ == '__main__': image = np.zeros((1024, 1536), dtype = np.uint8) threadsperblock = (32, 8) blockspergrid = (32, 16) # (1024,128) ==> (1024, 128*12) image_global_mem = cuda.to_device(image) compute_mandel[blockspergrid, threadsperblock](-2.0, 1.0, -1.0, 1.0, image_global_mem, 20) image_global_mem.copy_to_host() imshow(image) show()
C++
UTF-8
513
2.71875
3
[]
no_license
#include <iostream> #include <string> #include <fstream> #include <vector> using namespace std; #include "school.h" int main() { ifstream ifs; string name, nick, yr_s; int yr; vector<School> schools; School sch; ifs.open("schoolinfo.csv"); char c = ifs.peek(); while(c != EOF) { getline(ifs, name , ','); getline(ifs, nick , ','); getline(ifs, yr_s , '\n'); yr = stoi(yr_s); sch = School(name, nick, yr); schools.push_back(sch); c = ifs.peek(); } return 0; }
Java
UTF-8
1,309
2.671875
3
[]
no_license
package com.csis3275.model; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name = "jobs_mavericks") public class Jobs_Mavericks { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) public int id; public String title; public double salaryPerDay; public int payPeriod; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public double getSalaryPerDay() { return salaryPerDay; } public void setSalaryPerDay(double salaryPerDay) { this.salaryPerDay = salaryPerDay; } public int getPayPeriod() { return payPeriod; } public void setPayPeriod(int payPeriod) { this.payPeriod = payPeriod; } @Override public String toString() { return "Jobs_Mavericks [id=" + id + ", title=" + title + ", salaryPerDay=" + salaryPerDay + ", payPeriod=" + payPeriod + "]"; } public Jobs_Mavericks() { //default constructor } public Jobs_Mavericks(String title, double salaryPerDay, int payPeriod) { this.title = title; this.salaryPerDay = salaryPerDay; this.payPeriod = payPeriod; } }
JavaScript
UTF-8
4,749
2.6875
3
[ "MIT" ]
permissive
import { statuses, types } from './constants'; import { getDefaults, resetDefaults, setDefaults } from './defaults'; import QueueItem from './QueueItem'; import { isObject } from './utils'; class Qonductor { constructor(options = {}) { const { autoStart: defaultAutoStart, keepHistory: defaultKeepHistory, maxConcurrency: defaultMaxConcurrency, type: defaultType } = getDefaults(); const { autoStart = defaultAutoStart, keepHistory = defaultKeepHistory, maxConcurrency = defaultMaxConcurrency, type = defaultType } = options; Object.assign(this, { autoStart, completed: {}, completedCount: 0, currentIndex: 0, keepHistory, isRunning: false, maxConcurrency, pending: {}, pendingCount: 0, queue: {}, running: {}, runningCount: 0, type: type.toLowerCase() }); } /** * add the cancel function to the queueItem * * @param {object} queueItem * @return {function(message): void} * @private */ _addQueueItemCancel(queueItem) { return (message) => { if (queueItem.status === statuses.PENDING || queueItem.status === statuses.RUNNING) { queueItem._publishCancellation(message); } }; } /** * remove the queueItem from the running / pending list and * move to completed * * @param {number} index * @param {object} queueItem * @private */ _complete(index, queueItem) { if (!this.completed[index]) { if (this.keepHistory) { this.completed[index] = queueItem; } this.completedCount++; } if (this.running[index]) { delete this.running[index]; this.runningCount--; } else if (this.pending[index]) { delete this.pending[index]; this.pendingCount--; } delete this.queue[index]; if (this.isRunning && this.pendingCount) { this._runQueue(); } else if (!this.runningCount && !this.pendingCount) { this.isRunning = false; } } /** * based on the type, return the next index to process * * @param {array<string>} keys * @param {string} type * @return {string} * @private */ _getNextIndex(keys, type) { if (!keys.length) { return -1; } switch (type) { case types.LIFO: return Math.max.apply(this, keys); case types.SIRO: return keys[Math.floor(Math.random() * keys.length)]; default: return Math.min.apply(this, keys); } } /** * run the items in the queue up to the maxConcurrency limit * * @private */ _runQueue() { let running = this.runningCount; while (++running <= this.maxConcurrency) { const index = this._getNextIndex(Object.keys(this.pending), this.type); if (index === -1) { break; } const queueItem = this.pending[index]; this.running[index] = queueItem; this.runningCount++; delete this.pending[index]; this.pendingCount--; queueItem.run(); } } /** * add the function to the queue * * @param {function} fn * @return {Promise} */ add(fn) { const index = this.currentIndex; const queueItem = new QueueItem(index, fn, this._complete.bind(this)); this.queue[index] = queueItem; this.currentIndex++; this.pending[index] = queueItem; this.pendingCount++; queueItem.promise.cancel = this._addQueueItemCancel(queueItem); if (this.autoStart && !this.isRunning) { this.start(); } return queueItem.promise; } /** * cancel all remaining promises in the queue */ clear() { Object.keys(this.queue).forEach((key) => { if (this.queue[key].status !== statuses.COMPLETED) { this.queue[key].promise.cancel(); } }); } /** * get the global defaults for Qonductor * * @returns {object} */ static getDefaults() { return getDefaults(); } /** * reset the global defaults for Qonductor * * @returns {object} */ static resetDefaults() { return resetDefaults(); } /** * set the global defaults for Qonductor * * @param {object} newDefaults={} * @returns {object} */ static setDefaults(newDefaults = {}) { if (!isObject(newDefaults)) { throw new SyntaxError('Defaults assignment must be passed an object.'); } return setDefaults(newDefaults); } /** * kick off the processing of the queue */ start() { if (this.isRunning) { return; } this.isRunning = true; this._runQueue(); } /** * stop processing pending queue items */ stop() { this.isRunning = false; } } export default Qonductor;
Java
UTF-8
789
2.03125
2
[]
no_license
package ssm.testService; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import ssm.dao.ContrcatDao; import ssm.domain.Contract; import ssm.domain.SelectInfo; import ssm.service.ContrcatService; import ssm.service.impl.ContrcatServiceImpl; import java.util.List; public class ContractServiceTest { @Test public void test() throws Exception { ContrcatService contrcatService =new ContrcatServiceImpl(); SelectInfo selectInfo = new SelectInfo(); selectInfo.setPagenum(1); selectInfo.setPagesize(2); selectInfo.setQuery("123"); List<Contract> contracts=contrcatService.findContractByInfo(selectInfo); for (Contract contract:contracts) System.out.println(contract); } }
Java
UHC
1,058
3.234375
3
[]
no_license
package jv_0910; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class eggMonster { public static void main(String[] args) { String morningEgg; String lunchEgg; String dinnerEgg; try { BufferedReader keybd = new BufferedReader(new InputStreamReader(System.in)); System.out.print("ħ : "); morningEgg = keybd.readLine(); System.out.println("ħ : "+morningEgg+""); System.out.println(); System.out.print("ɿ : "); lunchEgg = keybd.readLine(); System.out.println("ɿ : "+lunchEgg+""); System.out.println(); System.out.print("ῡ : "); dinnerEgg = keybd.readLine(); System.out.println("ῡ : "+dinnerEgg+""); }catch(IOException e) { e.printStackTrace(); System.exit(1); }/* finally { try { if(keybd != null) keybd.close(); }catch(IOException e1) { }*/ } }
PHP
UTF-8
4,406
3.25
3
[]
no_license
<?php abstract class AbsAPI { /** * Metodo para retornar o nome da API usado na requisição. * @return string nome da api para requisição. */ public abstract function getAPIName(); /** * Comando GET para listar os arquivos do banco de dados.<br> * Exemplo de uma requisição:<br> * /api/postAPI?listar<br> * * Exemplo de uma resposta:<br> * [ * {id=10,texto="Teste-Exemplo 1"}, * {id=11,texto="Teste-Exemplo 2"}, * {id=12,texto="Teste-Exemplo 3"}, * {id=13,texto="Teste-Exemplo 4"} * ] * * @return string JSON contendo a resposta da requisição. */ public abstract function listar(); /** * Comando GET para remover um id do banco de dados.<br> * Exemplo de uma requisição:<br> * /api/postAPI?remover&id=10<br> * * Exemplo de uma resposta 200:<br> * { * codigo=200, status="Post removido com sucesso!" * } * Exemplo de uma resposta 404:<br> * { * codigo=404, status="Post não encontrado!" * } * @return string JSON contendo a resposta da requisição. */ public abstract function remover(); /** * Comando POST para inserir os dados para um banco de dados.<br> * Exemplo de requisição GET:<br> * /api/postAPI?inserir<br> * Exemplo de dados POST:<br> * { * id=20, texto="Teste de POST" * } * Exemplo de resposta 200:<br> * { * codigo=200, status="Post inserido com sucesso!" * } * Exemplo de resposta 409:<br> * { * codigo=409, status="Post já existe no sistema!" * } * Exemplo de resposta 400:<br> * { * codigo=400, status="Post foi recusado por conter problemas!", problemas="Texto maior que o limite!;" * } * @return string JSON contendo a resposta da requisição. */ public abstract function inserir(); /** * Comando POST para atualizar um item no banco de dados.<br> * Exemplo de requisição:<br> * /api/postAPI?atualizar<br> * * Exemplo de dados POST:<br> * { * id=20, texto="Teste de POST" * } * * Exemplo de resposta 200:<br> * { * codigo=200, status="Post atualizado com sucesso!" * } * * Exemplo de resposta 404:<br> * { * codigo=404, status="Post recusado por conter problemas!", problemas="Texto maior que o limite!;" * } * * Exemplo de resposta 400:<br> * { * codigo=400, status="Post não atualizado por não existir!" * } * @return string JSON contendo a resposta da requisição. */ public abstract function atualizar(); /** * Metodo para fazer um parser de um array para um objeto * @template T * @param $arr array um Array com seus dados, ex: $_GET * @param {T} $obj um objeto já instanciado. * @return {T} O mesmo objeto instanciado porem com os atributos preenchidos. */ protected function tryParseArrayToObj($arr, $obj) { // var_dump(get_class_vars(get_class($obj))); foreach (get_class_vars(get_class($obj)) as $var => $value) { if (key_exists($var, $arr)) { $obj->{$var} = $arr[$var]; } } return $obj; } /** * Metodo para exibir uma mensagem em JSON. * @param $code int status http (tente ser o mais fiel possivel) * @param $status string mensagem basica de erro. * @param array $extra parametros extras para ser exibido. */ protected function reportar($code, $status, $extra = []) { $dados['code'] = $code; $dados['status'] = $status; foreach ($extra as $key => $value) { if (key_exists($key, $dados)) { $dados[$key] = $dados[$key] . ", " . $value; } else { $dados[$key] = $value; } } http_response_code($dados['code']); echo(json_encode($dados)); } /** * Metodo para checar se o parametro GET foi atendido. Caso sim, o script * executa normalmente, caso não ele reporta e sai. * @param $parametro String parametro para ser checado. */ protected function condicaoGet($parametro){ if (!isset($_GET[$parametro])){ $this->reportar(500, "Parametro obrigatorio : ".$parametro); exit(-1); } } }
PHP
UTF-8
320
2.609375
3
[]
no_license
<?php namespace app\core; /** * Class Controller * @package app\core */ class Controller { /** * @param $view * @param array $params * @return string|string[] */ public function render($view, $params = []) { return Application::$app->view->renderView($view, $params); } }
TypeScript
UTF-8
3,890
2.984375
3
[ "MIT" ]
permissive
import { Key } from '../interface'; /** * 获取有效的scrollTop值 * Safari的缓动效果会获得负值的scrollTop */ export function getValidScrollTop(scrollTop: number, scrollRange: number) { return scrollTop < 0 ? 0 : scrollTop > scrollRange ? scrollRange : scrollTop; } /** * 获取滚动比例 * 视口已滚动距离 / 总可滚动距离 */ export function getScrollPercentage({ scrollTop, scrollHeight, clientHeight, }: { scrollTop: number; scrollHeight: number; clientHeight: number; }) { const scrollLength = scrollHeight - clientHeight; return getValidScrollTop(scrollTop, scrollLength) / scrollLength; } /** * 根据滚动条当前的滚动百分比,计算出基准元素(滚动位置对应的元素) * 在基准元素的上方和下方渲染可见区域的其他元素 */ export function getLocationItem(scrollPtg: number, itemCount: number) { const itemIndex = Math.floor(scrollPtg * itemCount); const itemTopPtg = itemIndex / itemCount; // The ratio of the top edge of the datum element beyond the scroll position const offsetPtg = (scrollPtg - itemTopPtg) / (1 / itemCount); return { index: itemIndex, // scrollPtg >= itemTopPtg, the calculation result is the offset of the scroll distance that the element should add to its height offsetPtg: Number.isNaN(offsetPtg) ? 0 : offsetPtg, }; } /** * 计算需要渲染的元素的开始下标、结束下标和用于定位的元素下标 */ export function getRangeIndex( scrollPtg: number, itemCount: number, visibleCount: number ) { const { index, offsetPtg } = getLocationItem(scrollPtg, itemCount); const beforeCount = Math.ceil(scrollPtg * visibleCount); const afterCount = Math.ceil((1 - scrollPtg) * visibleCount); return { itemIndex: index, itemOffsetPtg: offsetPtg, startIndex: Math.max(0, index - beforeCount), endIndex: Math.min(itemCount - 1, index + afterCount), }; } interface ItemTopConfig { itemHeight: number; itemOffsetPtg: number; scrollTop: number; scrollPtg: number; clientHeight: number; } /** * 计算元素相对于视口顶部的偏移量 */ export function getItemRelativeTop({ itemHeight, itemOffsetPtg, scrollPtg, clientHeight, }: Omit<ItemTopConfig, 'scrollTop'>) { if (scrollPtg === 1) return clientHeight - itemHeight; return Math.floor(clientHeight * scrollPtg - itemHeight * itemOffsetPtg); } /** * 计算元素相对于整个滚动区域顶部的偏移量 */ export function getItemAbsoluteTop({ scrollTop, ...rest }: ItemTopConfig) { return scrollTop + getItemRelativeTop(rest); } interface CompareItemConfig { locatedItemRelativeTop: number; locatedItemIndex: number; compareItemIndex: number; getItemKeyByIndex: (index: number) => Key; startIndex: number; endIndex: number; getItemHeightOrDefault: (key: Key) => number; } /** * 计算某一指定下标的元素相对于视口顶部的偏移量 */ export function getCompareItemRelativeTop({ locatedItemRelativeTop, locatedItemIndex, compareItemIndex, startIndex, endIndex, getItemKeyByIndex, getItemHeightOrDefault, }: CompareItemConfig) { let compareItemTop = locatedItemRelativeTop; const compareItemKey = getItemKeyByIndex(compareItemIndex); if (compareItemIndex <= locatedItemIndex) { for (let index = locatedItemIndex; index >= startIndex; index -= 1) { const key = getItemKeyByIndex(index); if (key === compareItemKey) { break; } const prevItemKey = getItemKeyByIndex(index - 1); compareItemTop -= getItemHeightOrDefault(prevItemKey); } } else { for (let index = locatedItemIndex; index <= endIndex; index += 1) { const key = getItemKeyByIndex(index); if (key === compareItemKey) { break; } compareItemTop += getItemHeightOrDefault(key); } } return compareItemTop; }
Markdown
UTF-8
12,811
3.046875
3
[]
no_license
--- order_index: null title: Conditional Probabilities template_type: popup uid: efbff85df56391b7be2c39e44adee68d parent_uid: 9ca6b310dc93095c9ac0f0e5f95e6930 technical_location: >- https://ocw.mit.edu/resources/res-6-012-introduction-to-probability-spring-2018/part-i-the-fundamentals/conditional-probabilities short_url: conditional-probabilities inline_embed_id: 60888684conditionalprobabilities6862469 about_this_resource_text: '<p><strong>Instructor:</strong> John Tsitsiklis</p>' related_resources_text: '' transcript: >- <p><span m="2330">Conditional probabilities are probabilities associated with</span> <span m="6150">a revised model that takes into account some additional</span> <span m="9860">information about the outcome of a probabilistic experiment.</span></p><p><span m="13850">The question is how to carry out this</span> <span m="16730">revision of our model.</span></p><p><span m="18930">We will give a mathematical definition of conditional</span> <span m="21390">probabilities, but first let us motivate this definition by</span> <span m="25730">examining a simple concrete example.</span></p><p><span m="29480">Consider a probability model with 12 equally likely</span> <span m="33660">possible outcomes, and so each one of them has probability</span> <span m="38180">equal to 1/12.</span></p><p><span m="41900">We will focus on two particular events, event A and</span> <span m="45940">B, two subsets of the sample space.</span></p><p><span m="48750">Event A has five elements, so its probability is 5/12, and</span> <span m="54800">event B has six elements, so it has probability 6/12.</span></p><p><span m="61190">Suppose now that someone tells you that event B has occurred,</span> <span m="64800">but tells you nothing more about the outcome.</span></p><p><span m="67980">How should the model change?</span></p><p><span m="70770">First, those outcomes that are outside event B</span> <span m="76450">are no longer possible.</span></p><p><span m="79390">So we can either eliminate them, as was done in this</span> <span m="83190">picture, or we might keep them in the picture but assign them</span> <span m="88220">0 probability, so that they cannot occur.</span></p><p><span m="93130">How about the outcomes inside the event B?</span></p><p><span m="96570">So we're told that one of these has occurred.</span></p><p><span m="101460">Now these 6 outcomes inside the event B were equally</span> <span m="105979">likely in the original model, and there is no reason to</span> <span m="110280">change their relative probabilities.</span></p><p><span m="112500">So they should remain equally likely in revised model as</span> <span m="116479">well, so each one of them should have now probability</span> <span m="120530">1/6 since there's 6 of them.</span></p><p><span m="123710">And this is our revised model, the</span> <span m="125680">conditional probability law.</span></p><p><span m="127760">0 probability to outcomes outside B, and probability 1/6</span> <span m="132740">to each one of the outcomes that is inside the event B.</span></p><p><span m="138120">Let us write now this down mathematically.</span></p><p><span m="141790">We will use this notation to describe the conditional</span> <span m="146710">probability of an event A given that some other event B</span> <span m="152280">is known to have occurred.</span></p><p><span m="154500">We read this expression as probability of A given B. So</span> <span m="160540">what are these conditional probabilities in our example?</span></p><p><span m="164760">So in the new model, where these outcomes are equally</span> <span m="168829">likely, we know that event A can occur in</span> <span m="172610">two different ways.</span></p><p><span m="174240">Each one of them has probability 1/6.</span></p><p><span m="176829">So the probability of event A is 2/6 which</span> <span m="182320">is the same as 1/3.</span></p><p><span m="186060">How about event B. Well, B consists of 6 possible</span> <span m="191350">outcomes each with probability 1/6.</span></p><p><span m="193850">So event B in this revised model should have probability</span> <span m="198670">equal to 1.</span></p><p><span m="200030">Of course, this is just saying the obvious.</span></p><p><span m="202770">Given that we already know that B has occurred, the</span> <span m="206150">probability that B occurs in this new model</span> <span m="209310">should be equal to 1.</span></p><p><span m="211920">How about now, if the sample space does not consist of</span> <span m="215010">equally likely outcomes, but instead we're given the</span> <span m="218340">probabilities of different pieces of the sample space, as</span> <span m="222120">in this example.</span></p><p><span m="224210">Notice here that the probabilities are consistent</span> <span m="227800">with what was used in the original example.</span></p><p><span m="231350">So this part of A that lies outside B has probability</span> <span m="235329">3/12, but in this case I'm not telling you how that</span> <span m="240190">probability is made up.</span></p><p><span m="241780">I'm not telling you that it consists of 3</span> <span m="243780">equally likely outcomes.</span></p><p><span m="244990">So all I'm telling you is that the collective probability in</span> <span m="247390">this region is 3/12.</span></p><p><span m="250070">The total probability of A is, again, 5/12 as before.</span></p><p><span m="254820">The total probability of B is 2 plus 4 equals</span> <span m="257930">6/12, exactly as before.</span></p><p><span m="261940">So it's a sort of similar situation as before.</span></p><p><span m="265440">How should we revise our probabilities and create--</span> <span m="271160">construct--</span> <span m="272040">conditional probabilities once we are told</span> <span m="275800">that event B has occurred?</span></p><p><span m="279430">First, this relation should remain true.</span></p><p><span m="284430">Once we are told that B has occurred, then B is certain to</span> <span m="289780">occur, so it should have conditional</span> <span m="291340">probability equal to 1.</span></p><p><span m="293280">How about the conditional probability of A given that B</span> <span m="296600">has occurred?</span></p><p><span m="297760">Well, we can reason as follows.</span></p><p><span m="300140">In the original model, and if we just look inside event B,</span> <span m="306320">those outcomes that make event A happen had a collective</span> <span m="312050">probability which was 1/3 of the total probability assigned</span> <span m="317340">to B. So out of the overall probability assigned to B, 1/3</span> <span m="322230">of that probability corresponds to outcomes in</span> <span m="325210">which event A is happening.</span></p><p><span m="327840">So therefore, if I tell you that B has occurred, I should</span> <span m="333010">assign probability equal to 1/3 that event A is</span> <span m="337710">also going to happen.</span></p><p><span m="339159">So that, given that B happened, the conditional</span> <span m="341750">probability of A given B should be equal to 1/3.</span></p><p><span m="346440">By now, we should be satisfied that this approach is a</span> <span m="349290">reasonable way of constructing conditional probabilities.</span></p><p><span m="352210">But now let us translate our reasoning into a formula.</span></p><p><span m="360920">So we wish to come up with a formula that gives us the</span> <span m="365450">conditional probability of an event given another event.</span></p><p><span m="369890">The particular formula that captures our way of thinking,</span> <span m="374630">as motivated before, is the following.</span></p><p><span m="379540">Out of the total probability assigned to B--</span> <span m="382700">which is this--</span> <span m="385290">we ask the question, which fraction of that probability</span> <span m="392230">is assigned to outcomes under which event A also happens?</span></p><p><span m="400650">So we are living inside event B, but within that event, we</span> <span m="406890">look at those outcomes for which event A also happens.</span></p><p><span m="411290">So this is the intersection of A and B. And we ask, out of</span> <span m="415430">the total probability of B, what fraction of that</span> <span m="418040">probability is allocated to that intersection of A with B?</span></p><p><span m="423460">So this formula, this definition, captures our</span> <span m="426690">intuition of what we did before to construct</span> <span m="431370">conditional probabilities in our particular example.</span></p><p><span m="434530">Let us check that the definition indeed does what</span> <span m="437510">it's supposed to do.</span></p><p><span m="439310">In this example, the probability of the</span> <span m="441520">intersection was 2/12 and the total probability of B was</span> <span m="447750">6/12, which gives us 1/3, which is the answer that we</span> <span m="453010">had gotten intuitively a little earlier.</span></p><p><span m="458170">At this point, let me also make a comment that this</span> <span m="462430">definition of conditional probabilities makes sense only</span> <span m="467730">if we do not attempt to divide by zero.</span></p><p><span m="471230">That this, only if the event B on which we're conditioning,</span> <span m="475280">has positive probability.</span></p><p><span m="477900">If B, if an event B has 0 probability, then conditional</span> <span m="483470">probabilities given B will be left undefined.</span></p><p><span m="488350">And one final comment.</span></p><p><span m="491440">This is a definition.</span></p><p><span m="494880">It's not a theorem.</span></p><p><span m="498310">What does that mean?</span></p><p><span m="499690">It means that there is no question whether this equality</span> <span m="503770">is correct or not.</span></p><p><span m="505600">It's just a definition.</span></p><p><span m="507520">There's no issue of correctness.</span></p><p><span m="511010">The earlier argument that we gave was just a motivation of</span> <span m="516909">the definition.</span></p><p><span m="518110">We tried to figure out what the definition should be if we</span> <span m="522610">want to have a certain intuitive and meaningful</span> <span m="526160">interpretation of the conditional probabilities.</span></p><p><span m="532600">Let us now continue with a simple example.</span></p><p>&nbsp;</p> embedded_media: - uid: 54edbbdedc80b3abb60a66557a597170 parent_uid: efbff85df56391b7be2c39e44adee68d id: Video-YouTube-Stream title: Video-YouTube-Stream type: Video media_location: MPRKc4UPoJk - uid: 04f0345d53342d5c1c9e8d8d921ff875 parent_uid: efbff85df56391b7be2c39e44adee68d id: Thumbnail-YouTube-JPG title: Thumbnail-YouTube-JPG type: Thumbnail media_location: 'https://img.youtube.com/vi/MPRKc4UPoJk/default.jpg' - uid: 91b3f73f8e9b43052af0bb4c14e65f1f parent_uid: efbff85df56391b7be2c39e44adee68d id: 3Play-3PlayYouTubeid-MP4 title: 3Play-3Play YouTube id type: 3Play media_location: MPRKc4UPoJk - uid: c5b058611443eb92d99ba7e927127906 parent_uid: efbff85df56391b7be2c39e44adee68d id: MPRKc4UPoJk.srt title: 3play caption file type: null technical_location: >- /resources/res-6-012-introduction-to-probability-spring-2018/part-i-the-fundamentals/conditional-probabilities/MPRKc4UPoJk.srt - uid: 0c1ffb4da9a5e04b0277fab2032f8c2d parent_uid: efbff85df56391b7be2c39e44adee68d id: MPRKc4UPoJk.pdf title: 3play pdf file type: null technical_location: >- /resources/res-6-012-introduction-to-probability-spring-2018/part-i-the-fundamentals/conditional-probabilities/MPRKc4UPoJk.pdf - uid: 7010779a545ecad3a02127f67a7aa60b parent_uid: efbff85df56391b7be2c39e44adee68d id: Caption-3Play YouTube id-SRT title: Caption-3Play YouTube id-SRT-English - US type: Caption - uid: 53cdbf16e8375fc8dca633a08632e24e parent_uid: efbff85df56391b7be2c39e44adee68d id: Transcript-3Play YouTube id-PDF title: Transcript-3Play YouTube id-PDF-English - US type: Transcript - uid: b567cc3aeb6ce3c477fd4518d6c2e52d parent_uid: efbff85df56391b7be2c39e44adee68d id: Video-InternetArchive-MP4 title: Video-Internet Archive-MP4 type: Video media_location: >- https://archive.org/download/MITRES.6-012S18/MITRES6_012S18_L02-02_300k.mp4 course_id: res-6-012-introduction-to-probability-spring-2018 type: course layout: video ---