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
Markdown
UTF-8
1,449
2.890625
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: Los tipos protegidos sólo se pueden declarar dentro de una clase. ms.date: 07/20/2015 f1_keywords: - vbc31047 - bc31047 helpviewer_keywords: - BC31047 ms.assetid: b2d79254-8efd-4b8f-b691-dc168caed207 ms.openlocfilehash: f63f45efc96c3064d0f642fa65248aa3f324307e ms.sourcegitcommit: 22c3c8f74eaa138dbbbb02eb7d720fce87fc30a9 ms.translationtype: MT ms.contentlocale: es-ES ms.lasthandoff: 05/17/2018 ms.locfileid: "34234254" --- # <a name="protected-types-can-only-be-declared-inside-of-a-class"></a>Los tipos protegidos sólo se pueden declarar dentro de una clase. Un tipo dentro de un módulo se declaró como `Protected`. Normalmente, se produce este error del compilador cuando se aplica el `Protected` modificador de acceso a una clase no anidada. Por ejemplo: ```vb Public Class OuterClass ' Generates compiler error BC31047. End Class ``` Dado que `Protected` es un modificador de acceso a miembros, solo se puede aplicar a un miembro de clase, como una propiedad, un método o una clase anidada. **Identificador de error:** BC31047 ## <a name="to-correct-this-error"></a>Para corregir este error 1. Declare el tipo dentro de una clase. 2. Quite el modificador `Protected` . ## <a name="see-also"></a>Vea también [Class (instrucción)](../../visual-basic/language-reference/statements/class-statement.md) [Protected](../../visual-basic/language-reference/modifiers/protected.md)
Java
UTF-8
1,545
2.140625
2
[]
no_license
package org.zerock.test; import static org.junit.Assert.*; import javax.inject.Inject; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.zerock.domain.BoardVO; import org.zerock.service.BoardService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"file:src/main/webapp/WEB-INF/spring/**/*.xml"}) public class BoardServiceTest { public static final Logger logger = LoggerFactory.getLogger(BoardServiceTest.class); @Inject private BoardService service; @Test public void testDI() throws Exception { logger.info("test DI BoardService:{}", service); } @Test public void testRegist() throws Exception { BoardVO board = new BoardVO(); board.setTitle("테스트 제목"); board.setContent("테스트 본문"); board.setWriter("user02"); service.regist(board); } @Test public void testRead() throws Exception { logger.info("## testRead:{}", service.read(15)); } @Test public void testModify() throws Exception { BoardVO board = new BoardVO(); board.setBno(15); board.setTitle("수정된 제목"); board.setContent("수정된 본문"); service.modify(board); } @Test public void testRemove() throws Exception { service.remove(15); } @Test public void testListAll() throws Exception { logger.info("## testListAll():\n{}", service.listAll()); } }
Python
UTF-8
3,555
2.90625
3
[]
no_license
# Own python file from Melody import Melody # Python standard libs import time import random # Pygame import pygame class Queue: def __init__(self): self.lst = [] def __str__(self): return str(self.lst) def enQ(self, items): self.lst.append(items) def deQ(self): if not self.is_empty(): self.lst[0].clear_surface() self.lst.pop(0) def is_empty(self): return self.size() == 0 def size(self): return len(self.lst) def render(self,window,pos): for i in self.lst: i.render(window,pos) def peek(self): if not self.is_empty(): return self.lst[0] class MelodyGen: def __init__(self,pos_data,game_data): self.melodyQ1 = Queue() self.melodyQ2 = Queue() self.melodyQ3 = Queue() self.melodyQ4 = Queue() self.melodyQ5 = Queue() self.melodyQ = [self.melodyQ1,self.melodyQ2,self.melodyQ3,self.melodyQ4,self.melodyQ5] self.prev_time = 0 self.canCreated = True self.game_data = game_data self.start_pos_list = pos_data["start_pos_list"] self.end_pos_list = pos_data["end_pos_list"] self.bottom_y_pos = pos_data["bottom_y_pos"] self.resolution = game_data["resolution"] self.H,self.W = self.resolution[1],self.resolution[0] self.player = game_data["single_player_obj"] self.game_data = game_data full_screen = game_data["fullscreen"] if full_screen: self.melody_bg = pygame.Surface((0,0),pygame.FULLSCREEN) else: self.melody_bg = pygame.Surface(self.resolution) # print(game_data["random_seed"]) self.front_Q = [0,0,0,0,0] def get_front_Q(self): return self.front_Q def get_melody_Q(self): return self.melodyQ def update(self,time_delta): if pygame.time.get_ticks() - self.prev_time > random.randrange(8000,12000,500): self.canCreated = True self.prev_time = pygame.time.get_ticks() if self.canCreated: rand = random.randint(0,4) # print(rand) # random.seed(random.randint(0,9999)) self.melodyQ[rand].enQ( Melody(self.start_pos_list[rand],0, self.end_pos_list[rand],self.bottom_y_pos, random.randint(0,127),self.game_data ) ) self.canCreated = False # Front of melody queue for i in range(5): if not self.melodyQ[i].is_empty(): self.front_Q[i] = self.melodyQ[i].peek() #print(f"MelodyQ1 : {self.melodyQ1}") #print(f"MelodyQ2 : {self.melodyQ2}") #print(f"MelodyQ3 : {self.melodyQ3}") #print(f"MelodyQ4 : {self.melodyQ4}") #print(f"MelodyQ5 : {self.melodyQ5}") for meQ in self.melodyQ: for melody in meQ.lst: melody.update(time_delta) if melody.get_position()[1] >= self.bottom_y_pos: meQ.deQ() #self.player.set_score(self.player.get_score() + 10) #self.player.score_update() def render(self, window): self.melody_bg.set_colorkey((0,0,0)) window.blit(self.melody_bg,(0,0)) for meQ in self.melodyQ: for melody in meQ.lst: melody.render(self.melody_bg) melody.set_parent_window(self.melody_bg)
Python
UTF-8
7,471
3.109375
3
[]
no_license
import numpy as np import matplotlib.pyplot as plt import pandas as pd from matplotlib.patches import Rectangle def load_event_properties(experiment): """ Load event property file picks for a given experiment number and return that data as an array """ return np.loadtxt('../Slip_Property_Data/%s_event_properties.txt'%experiment,delimiter=',',skiprows=1) def load_blacklist(experiment): """ Load event numbers from the blacklist file for each experiment and return them as an array """ blacklist = np.loadtxt('../Slip_Property_Data/%s_blacklist.txt'%experiment) return blacklist def load_events(experiment): """ Loads all events from a given experiment that are not on the blacklist file for that experiment. Returns array of event properties. """ event_properties = load_event_properties(experiment) blacklist = load_blacklist(experiment) return np.delete(event_properties,blacklist,axis=0) def filter(data,col,low,high): """ Take array, filter out rows in which the element in the given column is not in the range low-high (inclusive) """ inds = np.where(data[:,col]>=low) data_trim = data[inds] inds = np.where(data_trim[:,col]<=high) data_trim = data_trim[inds] return data_trim # Tuple of experiments we'll consider for plotting even data from experiments_with_event_data = ('p4343','p4344','p4345','p4346', 'p4347','p4348','p4350','p4351') # Tuple of experiments we'll plot unload/reload stiffness from experiments_with_unload_reload = ('p4267','p4268','p4269','p4270','p4271', 'p4272','p4273','p4309','p4310','p4311', 'p4312','p4313','p4314','p4316','p4317', 'p4327','p4328','p4329','p4330') # Read those experiments into a dictionary of event data experiment_event_data = dict() for experiment in experiments_with_event_data: experiment_event_data[experiment] = load_events(experiment) # Make the plot # Setup figure and axes # Generally plots is ~1.33x width to height (10,7.5 or 12,9) fig = plt.figure(figsize=(12,5)) ax1 = plt.subplot(121) ax2 = plt.subplot(122) # Panel A # Set labels and tick sizes ax1.set_xlabel(r'$\kappa$',fontsize=24) ax1.set_ylabel(r'Peak Slip Velocity [$mm/s$]',fontsize=18) ax1.tick_params(axis='both', which='major', labelsize=16) # Turns off chart clutter # # Turn off top and right tick marks # ax1.get_xaxis().tick_bottom() # ax1.get_yaxis().tick_left() # # # Turn off top and right splines # ax1.spines["top"].set_visible(False) # ax1.spines["right"].set_visible(False) ax1.text(-0.2,0.95,'A',transform = ax1.transAxes,fontsize=24) filter_col = 9 low_val = 40000. high_val = 50000. y_col = 11 marker_alpha = 0.3 for key in experiment_event_data: event_data = experiment_event_data[key] event_data = filter(event_data,filter_col,low_val,high_val) ax1.scatter(event_data[:,5]/0.0007,event_data[:,y_col]/1000.,color='k',alpha=marker_alpha) ax1.errorbar(np.mean(event_data[:,5]/0.0007),np.mean(event_data[:,y_col]/1000.),fmt='ro',ecolor='w',elinewidth=2,xerr=np.std(event_data[:,5]/0.0007),yerr=np.std(event_data[:,y_col]/1000.)) ax1.errorbar(np.mean(event_data[:,5]/0.0007),np.mean(event_data[:,y_col]/1000.),fmt='ro',markeredgecolor='w',ecolor='k',elinewidth=1,xerr=np.std(event_data[:,5]/0.0007),yerr=np.std(event_data[:,y_col]/1000.)) # Add audible/non-audible annotation ax1.axvline(x=0.75,color='k',linestyle='--') ax1.axvline(x=1.1,color='k',linestyle='--') ax1.text(0.647,4.4,'Audible',fontsize=14) ax1.text(0.9,4.4,'Silent',fontsize=14) ax1.text(1.11,2.555,'Stable',fontsize=14,rotation=90) ax1.axvspan(1.1,1.15,color='k',alpha=0.2) ax1.annotate("", xy=(0.63, 4.35), xycoords='data', xytext=(0.75,4.35), textcoords='data', arrowprops=dict(arrowstyle="->", connectionstyle="arc3"), ) ax1.annotate("", xy=(0.75, 4.35), xycoords='data', xytext=(1.1,4.35), textcoords='data', arrowprops=dict(arrowstyle="<->", connectionstyle="arc3"), ) ax1.annotate("", xy=(1.1, 4.35), xycoords='data', xytext=(1.15,4.35), textcoords='data', arrowprops=dict(arrowstyle="<-", connectionstyle="arc3"), ) ax1.annotate("", xy=(1.1, 0.35), xycoords='data', xytext=(1.15,0.35), textcoords='data', arrowprops=dict(arrowstyle="<-", connectionstyle="arc3"), ) ax1.set_ylim(0,4.7) ax1.set_xlim(0.63,1.15) # Panel B # Set labels and tick sizes ax2.set_xlabel(r'$\kappa$',fontsize=24) ax2.set_ylabel(r'Slip Duration [$s$]',fontsize=18) ax2.tick_params(axis='both', which='major', labelsize=16) ax2.get_yaxis().set_ticks([0,0.2,0.4,0.6,0.8,1.0]) # Turns off chart clutter # # Turn off top and right tick marks # ax2.get_xaxis().tick_bottom() # ax2.get_yaxis().tick_left() # # # Turn off top and right splines # ax2.spines["top"].set_visible(False) # ax2.spines["right"].set_visible(False) ax2.text(-0.08,0.95,'B',transform = ax2.transAxes,fontsize=24) filter_col = 9 low_val = 40000. high_val = 50000. y_col = 4 marker_alpha = 0.3 for key in experiment_event_data: event_data = experiment_event_data[key] event_data = filter(event_data,filter_col,low_val,high_val) ax2.scatter(event_data[:,5]/0.0007,event_data[:,y_col],color='k',alpha=marker_alpha) ax2.errorbar(np.mean(event_data[:,5]/0.0007),np.mean(event_data[:,y_col]),fmt='ro',ecolor='w',elinewidth=2,xerr=np.std(event_data[:,5]/0.0007),yerr=np.std(event_data[:,y_col])) ax2.errorbar(np.mean(event_data[:,5]/0.0007),np.mean(event_data[:,y_col]),fmt='ro',markeredgecolor='w',ecolor='k',elinewidth=1,xerr=np.std(event_data[:,5]/0.0007),yerr=np.std(event_data[:,y_col])) #ax2.errorbar(np.mean(event_data[:,5]/0.0007),np.mean(event_data[:,y_col]),fmt='ro',ecolor='k',elinewidth=2,xerr=np.std(event_data[:,5]/0.0007),yerr=np.std(event_data[:,y_col])) # Add audible/non-audible annotation ax2.axvline(x=0.75,color='k',linestyle='--') ax2.axvline(x=1.1,color='k',linestyle='--') ax2.text(0.647,1.123,'Audible',fontsize=14) ax2.text(0.9,1.123,'Silent',fontsize=14) ax2.text(1.11,0.65,'Stable',fontsize=14,rotation=90) ax2.axvspan(1.1,1.15,color='k',alpha=0.2) ax2.annotate("", xy=(0.63, 1.11), xycoords='data', xytext=(0.75,1.11), textcoords='data', arrowprops=dict(arrowstyle="->", connectionstyle="arc3"), ) ax2.annotate("", xy=(0.75, 1.11), xycoords='data', xytext=(1.1,1.11), textcoords='data', arrowprops=dict(arrowstyle="<->", connectionstyle="arc3"), ) ax2.annotate("", xy=(1.1, 1.11), xycoords='data', xytext=(1.15,1.11), textcoords='data', arrowprops=dict(arrowstyle="<-", connectionstyle="arc3"), ) ax2.annotate("", xy=(1.1, 0.09), xycoords='data', xytext=(1.15,0.09), textcoords='data', arrowprops=dict(arrowstyle="<-", connectionstyle="arc3"), ) ax2.set_xlim(0.63,1.15) ax2.set_ylim(0,1.2) #ax2.set_xlim(4.5,8.5) plt.savefig('figure.png', bbox_inches="tight");
Ruby
UTF-8
749
3.71875
4
[]
no_license
# Algoritma # 1) Başla # 2) toplam = 0 olsun # 3) sayac = 1 olsun # 4) sayac > 999 ise 9. adıma git # 5) Eğer sayac mod 3 = 0 veya sayac mod 5 = 0 değil ise 7. adıma git. # 6) toplam = toplam + sayac olsun # 7) sayac = sayac + 1 olsun # 8) 4. adıma git # 9) toplamı ekrana yazdır # 10) Bitir # 2) toplam = 0 olsun toplam = 0 # 3) sayac = 1 olsun sayac = 1 # 4) sayac > 999 ise 9. adıma git until sayac > 999 # 5) Eğer sayac mod 3 = 0 veya sayac mod 5 = 0 değil ise 7. adıma git. if sayac % 3 == 0 || sayac % 5 == 0 # 6) toplam = toplam + sayac olsun toplam += sayac end # 7) sayac = sayac + 1 olsun sayac += 1 # 8) 4. adıma git end # 9) toplamı ekrana yazdır puts "İşemin sonucu = #{toplam}"
Java
UTF-8
2,350
1.929688
2
[]
no_license
package com.dxjr.portal.cms.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.dxjr.common.page.Page; import com.dxjr.portal.cms.mapper.CmsTagMapper; import com.dxjr.portal.cms.service.CmsTagService; import com.dxjr.portal.cms.vo.CmsArticle; import com.dxjr.portal.cms.vo.CmsTag; import com.dxjr.portal.cms.vo.SearchPageVo; @Service public class CmsTagServiceImpl implements CmsTagService { @Autowired CmsTagMapper cmsTagMapper; @Override public Page searchCmsTagPage(int pageNo, int pageSize) { Page page = new Page(pageNo, pageSize); page.setResult(cmsTagMapper.queryCmsTagListForPage(page)); page.setTotalCount(cmsTagMapper.getCountCmsTagListForPage()); return page; } @Override public void save(CmsTag cmsTag) { CmsTag cmsTagTemp = cmsTagMapper.getTagByName(cmsTag.getName()); if (cmsTagTemp != null) { cmsTag.setId(cmsTagTemp.getId()); } else { cmsTagMapper.insert(cmsTag); } } @Override public List<CmsTag> queryCmsTagList(Integer channelId, int start, int count) { return cmsTagMapper.queryCmsTagList(channelId, start, count); } @Override public List<CmsTag> queryTagsByName(String name, int start, int count) { return cmsTagMapper.queryTagsByName(name, start, count); } @Override public List<CmsTag> queryCmsTagListByTypeAndNum(Integer type, Integer num) { return cmsTagMapper.queryCmsTagListByTypeAndNum(type,num); } @Override public Page queryArticlePageByCnd(SearchPageVo seach, Page p) { Integer totalCount = cmsTagMapper.queryArticlePageByCndCount(seach); p.setTotalCount(totalCount); List<CmsArticle> list = cmsTagMapper.queryArticlePageByCndList(seach, p); p.setResult(list); return p; } @Override public List<CmsArticle> findHotArticlesByTagLimit(Integer id, int i, int j) { return cmsTagMapper.queryHotArticlesByTagLimit(id,i,j); } @Override public CmsTag getCmsTagById(Integer id) { return cmsTagMapper.selectByPrimaryKey(id); } @Override public List<CmsTag> queryCmsTagListByParentChannelId(int moneymanagement, int i, int j) { return cmsTagMapper.queryCmsTagListByParentChannelId(moneymanagement, i, j); } @Override public CmsTag getCmsTagByParam(String param) { return cmsTagMapper.queryCmsTagByParam(param); } }
Java
UTF-8
7,266
2.203125
2
[ "Apache-2.0" ]
permissive
package io.quarkus.it.hibernate.validator; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; import org.junit.jupiter.api.Test; import io.quarkus.test.common.QuarkusTestResource; import io.quarkus.test.h2.H2DatabaseTestResource; import io.quarkus.test.junit.QuarkusTest; import io.restassured.RestAssured; /** * Test various Bean Validation operations running in Quarkus */ @QuarkusTest @QuarkusTestResource(H2DatabaseTestResource.class) public class HibernateValidatorFunctionalityTest { @Test public void testBasicFeatures() throws Exception { StringBuilder expected = new StringBuilder(); expected.append("failed: additionalEmails[0].<list element> (must be a well-formed email address)").append(", ") .append("categorizedEmails<K>[a].<map key> (length must be between 3 and 2147483647)").append(", ") .append("categorizedEmails[a].<map value>[0].<list element> (must be a well-formed email address)").append(", ") .append("email (must be a well-formed email address)").append(", ") .append("score (must be greater than or equal to 0)").append("\n"); expected.append("passed"); RestAssured.when() .get("/hibernate-validator/test/basic-features") .then() .body(is(expected.toString())); } @Test public void testCustomClassLevelConstraint() throws Exception { StringBuilder expected = new StringBuilder(); expected.append("failed: (invalid MyOtherBean)").append("\n"); expected.append("passed"); RestAssured.when() .get("/hibernate-validator/test/custom-class-level-constraint") .then() .body(is(expected.toString())); } @Test public void testCDIBeanMethodValidation() { StringBuilder expected = new StringBuilder(); expected.append("passed").append("\n"); expected.append("failed: greeting.name (must not be null)"); RestAssured.when() .get("/hibernate-validator/test/cdi-bean-method-validation") .then() .body(is(expected.toString())); } @Test public void testRestEndPointValidation() { RestAssured.when() .get("/hibernate-validator/test/rest-end-point-validation/plop/") .then() .statusCode(400) .body(containsString("numeric value out of bounds")); RestAssured.when() .get("/hibernate-validator/test/rest-end-point-validation/42/") .then() .body(is("42")); } @Test public void testRestEndPointInterfaceValidation() { RestAssured.when() .get("/hibernate-validator/test/rest-end-point-interface-validation/plop/") .then() .statusCode(400) .body(containsString("numeric value out of bounds")); RestAssured.when() .get("/hibernate-validator/test/rest-end-point-interface-validation/42/") .then() .body(is("42")); } @Test public void testRestEndPointInterfaceValidationWithAnnotationOnImplMethod() { RestAssured.when() .get("/hibernate-validator/test/rest-end-point-interface-validation-annotation-on-impl-method/plop/") .then() .statusCode(400) .body(containsString("numeric value out of bounds")); RestAssured.when() .get("/hibernate-validator/test/rest-end-point-interface-validation-annotation-on-impl-method/42/") .then() .body(is("42")); } @Test public void testRestEndPointGenericMethodValidation() { RestAssured.when() .get("/hibernate-validator/test/rest-end-point-generic-method-validation/9999999/") .then() .statusCode(400) .body(containsString("numeric value out of bounds")); RestAssured.when() .get("/hibernate-validator/test/rest-end-point-generic-method-validation/42/") .then() .body(is("42")); } @Test public void testNoProduces() { RestAssured.when() .get("/hibernate-validator/test/no-produces/plop/") .then() .statusCode(400) .body(containsString("numeric value out of bounds")); } @Test public void testInjection() throws Exception { StringBuilder expected = new StringBuilder(); expected.append("passed").append("\n"); expected.append("failed: value (InjectedConstraintValidatorConstraint violation)"); RestAssured.when() .get("/hibernate-validator/test/injection") .then() .body(is(expected.toString())); } @Test public void testInheritedImplementsConstraints() { StringBuilder expected = new StringBuilder(); expected.append("passed").append("\n") .append("failed: echoZipCode.zipCode (size must be between 5 and 5)"); RestAssured.when() .get("/hibernate-validator/test/test-inherited-implements-constraints") .then() .body(is(expected.toString())); } @Test public void testInheritedExtendsConstraints() { StringBuilder expected = new StringBuilder(); expected.append("passed").append("\n"); expected.append("failed: greeting.name (must not be null)"); RestAssured.when() .get("/hibernate-validator/test/test-inherited-extends-constraints") .then() .body(is(expected.toString())); } @Test public void testValidationMessageLocale() { RestAssured.given() .header("Accept-Language", "en-US;q=0.25,hr-HR;q=1,fr-FR;q=0.5") .when() .get("/hibernate-validator/test/test-validation-message-locale/1") .then() .body(containsString("Vrijednost ne zadovoljava uzorak")); } @Test public void testValidationMessageDefaultLocale() { RestAssured.given() .when() .get("/hibernate-validator/test/test-validation-message-locale/1") .then() .body(containsString("Value is not in line with the pattern")); } @Test public void testManualValidationMessageLocale() { RestAssured.given() .header("Accept-Language", "en-US;q=0.25,hr-HR;q=1,fr-FR;q=0.5") .header("Content-Type", "application/json") .when() .body("{\"name\": \"b\"}") .post("/hibernate-validator/test/test-manual-validation-message-locale") .then() .body(containsString("Vrijednost ne zadovoljava uzorak")); } @Test public void testHibernateOrmIntegration() { RestAssured.when() .get("/hibernate-validator/test/test-hibernate-orm-integration") .then() .statusCode(500); } }
Java
UTF-8
4,689
3.21875
3
[]
no_license
package org.gnuhpc.interview.leetcode.solutions; import org.junit.Test; import java.util.HashMap; import java.util.Map; public class NumberToWords273 { Map<Integer, String> wordsMap = new HashMap<Integer, String>() {{ put(0, "Zero"); put(1, "One"); put(2, "Two"); put(3, "Three"); put(4, "Four"); put(5, "Five"); put(6, "Six"); put(7, "Seven"); put(8, "Eight"); put(9, "Nine"); put(10, "Ten"); put(11, "Eleven"); put(12, "Twelve"); put(13, "Thirteen"); put(14, "Fourteen"); put(15, "Fifteen"); put(16, "Sixteen"); put(17, "Seventeen"); put(18, "Eighteen"); put(19, "Nineteen"); put(20, "Twenty"); put(30, "Thirty"); put(40, "Forty"); put(50, "Fifty"); put(60, "Sixty"); put(70, "Seventy"); put(80, "Eighty"); put(90, "Ninety"); }}; Map<Integer, String> unitMap = new HashMap<Integer, String>() {{ put(3, "Hundred"); put(4, "Thousand"); put(7, "Million"); put(10, "Billion"); }}; public String numberToWords(int num) { if (wordsMap.containsKey(num)) { return wordsMap.get(num); } String n = String.valueOf(num); int len = n.length(); if (len < 3) { int key = (n.charAt(0) - '0') * 10; return wordsMap.get(key) + " " + numberToWords(num - key); } if (len == 3 || len == 4 || len == 7 || len == 10) { int key = n.charAt(0) - '0'; String unit = unitMap.get(len); int next = num - key * (int) Math.pow(10, len - 1); if (next == 0) { return wordsMap.get(key) + " " + unit; } else { return wordsMap.get(key) + " " + unit + " " + numberToWords(next); } } if (len >= 5 && len <= 6) { return parse(n, 3); } if (len >= 8 && len <= 9) { return parse(n, 6); } return ""; } private String parse(String n, int base) { int key = Integer.parseInt(n.substring(0, n.length() - base)); String unit = unitMap.get(base + 1); int next = Integer.parseInt(n) - key * (int) Math.pow(10, base); if (next == 0) { return numberToWords(key) + " " + unit; } else { return numberToWords(key) + " " + unit + " " + numberToWords(next); } } @Test public void test() { System.out.println(numberToWords(0)); System.out.println(numberToWords(5)); System.out.println(numberToWords(67)); System.out.println(numberToWords(100)); System.out.println(numberToWords(197)); System.out.println(numberToWords(2197)); System.out.println(numberToWords(10000)); System.out.println(numberToWords(16251)); System.out.println(numberToWords(316251)); System.out.println(numberToWords(1316251)); System.out.println(numberToWords(21316251)); System.out.println(numberToWords(1234567891)); } //add by tina //"" is kept for index simplicity. TENS: 1st 2nd never used, keep for index simplicity private final String[] LESS_THAN_20 = { "", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"}; private final String[] TENS = {"", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety"}; private final String[] THOUSANDS = {"", "Thousand", "Million", "Billion"}; public String numberToWords2(int num) { if (num == 0) return "Zero"; int i = 0;//ptr to thousands String words = ""; while (num > 0) { if (num % 1000 != 0) { //avoid special case 1,000,000 else return one million thousand words = helper(num % 1000) + THOUSANDS[i] + " " + words; } num /= 1000; i++; } return words.trim();//remove extra space in the end. } private String helper(int num) { if (num == 0) { return ""; } else if (num < 20) { return LESS_THAN_20[num] + " "; } else if (num < 100) { return TENS[num / 10] + " " + helper(num % 10);//avid extra space by recur call } else {//100-999 return LESS_THAN_20[num / 100] + " Hundred " + helper(num % 100); } } }
Markdown
UTF-8
444
2.671875
3
[]
no_license
--- layout: post title: TripLab has its first social event at Snakes and Lattes! date: 2019-07-22 excerpt: > TripLab has its first social event at Snakes and Lattes! --- The lab had our first lab social event at a boardgame themed coffeeshop, Snakes and Lattes. We played the game Codenames and had a ton of fun! ![The lab at Snakes and Lattes](/images/people/chutes_and_lattes_2019.jpg "The lab at Snakes and Lattes"){:height="400px"}
Python
UTF-8
12,281
2.875
3
[]
no_license
"""M3C 2018 Homework 3 Frederica Melbourne CID: 01068192 Contains five functions: plot_S: plots S matrix -- use if you like simulate2: Simulate tribal competition over m trials. Return: all s matrices at final time and fc at nt+1 times averaged across the m trials. performance: To be completed -- analyze and assess performance of python, fortran, and fortran+openmp simulation codes analyze: To be completed -- analyze influence of model parameter, g visualize: To be completed -- generate animation illustrating "interesting" tribal dynamics """ import numpy as np import matplotlib.pyplot as plt from y1 import tribes as tr #assumes that hw3_dev.f90 has been compiled with: f2py3 --f90flags='-fopenmp' -c hw3_dev.f90 -m f1 -lgomp #May also use scipy and time modules as needed import time import matplotlib.animation as animation def plot_S(S): """Simple function to create plot from input S matrix """ ind_s0 = np.where(S==0) #C locations ind_s1 = np.where(S==1) #M locations plt.plot(ind_s0[1],ind_s0[0],'rs') plt.plot(ind_s1[1],ind_s1[0],'bs') plt.show() return None #------------------ def simulate2(N,Nt,b,e,g,m): """Simulate m trials of C vs. M competition on N x N grid over Nt generations. b, e, and g are model parameters to be used in fitness calculations. Output: S: Status of each gridpoint at end of simulation, 0=M, 1=C fc_ave: fraction of villages which are C at all Nt+1 times averaged over the m trials """ #Set initial condition S = np.ones((N,N,m),dtype=int) #Status of each gridpoint: 0=M, 1=C j = int((N-1)/2) S[j,j,:] = 0 N2inv = 1./(N*N) fc_ave = np.zeros(Nt+1) #Fraction of points which are C fc_ave[0] = S.sum() #Initialize matrices NB = np.zeros((N,N,m),dtype=int) #Number of neighbors for each point NC = np.zeros((N,N,m),dtype=int) #Number of neighbors who are Cs S2 = np.zeros((N+2,N+2,m),dtype=int) #S + border of zeros F = np.zeros((N,N,m)) #Fitness matrix F2 = np.zeros((N+2,N+2,m)) #Fitness matrix + border of zeros A = np.ones((N,N,m)) #Fitness parameters, each of N^2 elements is 1 or b P = np.zeros((N,N,m)) #Probability matrix Pden = np.zeros((N,N,m)) #--------------------- #Calculate number of neighbors for each point NB[:,:,:] = 8 NB[0,1:-1,:],NB[-1,1:-1,:],NB[1:-1,0,:],NB[1:-1,-1,:] = 5,5,5,5 NB[0,0,:],NB[-1,-1,:],NB[0,-1,:],NB[-1,0,:] = 3,3,3,3 NBinv = 1.0/NB #------------- #----Time marching----- for t in range(Nt): R = np.random.rand(N,N,m) #Random numbers used to update S every time step #Set up coefficients for fitness calculation A = np.ones((N,N,m)) ind0 = np.where(S==0) A[ind0] = b #Add boundary of zeros to S S2[1:-1,1:-1,:] = S #Count number of C neighbors for each point NC = S2[:-2,:-2,:]+S2[:-2,1:-1,:]+S2[:-2,2:,:]+S2[1:-1,:-2,:] + S2[1:-1,2:,:] + S2[2:,:-2,:] + S2[2:,1:-1,:] + S2[2:,2:,:] #Calculate fitness matrix, F---- F = NC*A F[ind0] = F[ind0] + (NB[ind0]-NC[ind0])*e F = F*NBinv #----------- #Calculate probability matrix, P----- F2[1:-1,1:-1,:]=F F2S2 = F2*S2 #Total fitness of cooperators in community P = F2S2[:-2,:-2,:]+F2S2[:-2,1:-1,:]+F2S2[:-2,2:,:]+F2S2[1:-1,:-2,:] + F2S2[1:-1,1:-1,:] + F2S2[1:-1,2:,:] + F2S2[2:,:-2,:] + F2S2[2:,1:-1,:] + F2S2[2:,2:,:] #Total fitness of all members of community Pden = F2[:-2,:-2,:]+F2[:-2,1:-1,:]+F2[:-2,2:,:]+F2[1:-1,:-2,:] + F2[1:-1,1:-1,:] + F2[1:-1,2:,:] + F2[2:,:-2,:] + F2[2:,1:-1,:] + F2[2:,2:,:] P = (P/Pden)*g + 0.5*(1.0-g) #probability matrix #--------- #Set new affiliations based on probability matrix and random numbers stored in R S[:,:,:] = 0 S[R<=P] = 1 fc_ave[t+1] = S.sum() #----Finish time marching----- fc_ave = fc_ave*N2inv/m return S,fc_ave #------------------ def performance(input=(None),display=False): """Assess performance of simulate2, simulate2_f90, and simulate2_omp Modify the contents of the tuple, input, as needed When display is True, figures equivalent to those you are submitting should be displayed Comments: The first graph shows how the performance of the Fortran/OpenMP implementation varies with no. trials M and grid size N. It contrasts the performance when using one and two threads. We can see that, as you would expect, runtime increases linearly with M (as the number of loops is being increased) and seems to increase proportional to N^2 (because, for example, doubling N leads to four times as many grid points). We can also see that using one thread (equivalent to a non-parallelized version) is notably slower than using two thread- this shows that parallelisation is successful in improving performance. The second graph explicitly shows this speedup of the Fortran/OpenMP implementation; calculated by fixing N and Nt and varying the number of trials, M, and using speedup = runtime with one thread / runtime with two threads. We can see that there is an average speedup of around 1.92 for all sample sizes, which doesn't appear to be affected by the number of trials. Thus there is a great improvement in performance by parallelising the function. Finally, we can compare the performance of the Fortran/OpenMP implementation to the pure Fortran and Python implementations. I chose to compare this for increasing M due to the found linear relationship, which could make trends easier to observe. We see that the relative performance is quite consistent- for all values of M that were tested, the Fortran version was about two fifths the speed of the Fortran/OpenMP version, and the Python version was much worse, at around a twentieth of the speed. This is because vectorisation is much more important in Python, whereas when Fortran code is compiled the code can generally be optimized. Thus the loop over time results in a much worse performance for the Python implementationself. The parallelized version is faster than both of the others because the tasks are being split up and then carried out simultaneously. """ #set parameters tr.tr_b = 1.1 tr.tr_e = 0.01 tr.tr_g = 0.95 #initialise arrays onethreadtimeM=np.zeros(7) onethreadtimeN=np.zeros(7) twothreadtimeM=np.zeros(7) twothreadtimeN=np.zeros(7) timef=np.zeros(7) timep=np.zeros(7) #choose M/N values Msize=[31,81,101,151,201,271,351] Nsize=[31,81,101,151,201,271,351] #caluclate runtimes for one thread (Fortran/OpenMP) tr.numthreads=1 for i in range(7): t1=time.time() tr.simulate2_omp(51,50,Msize[i]) t2=time.time() onethreadtimeM[i]=t2-t1 t1=time.time() tr.simulate2_omp(Nsize[i],50,50) t2=time.time() onethreadtimeN[i]=t2-t1 #calculate runtimes for two threads (Fortran/OpenMP) & Fortran, Python tr.numthreads=2 for i in range(7): t1=time.time() tr.simulate2_omp(51,50,Msize[i]) t2=time.time() twothreadtimeM[i]=t2-t1 t1=time.time() tr.simulate2_omp(Nsize[i],50,50) t2=time.time() twothreadtimeN[i]=t2-t1 t1=time.time() tr.simulate2_f90(51,50,Msize[i]) t2=time.time() timef[i]=t2-t1 t1=time.time() simulate2(51,50,1.1,0.01,0.95,Msize[i]) t2=time.time() timep[i]=t2-t1 #calculate speedup of Fortran/OpenMP speedupM=np.divide(onethreadtimeM,twothreadtimeM) #calculate relative performance of F/OpenMP and Fortran, Python relfortran=np.divide(twothreadtimeM,timef) relpython=np.divide(twothreadtimeM,timep) #plot figures if display == True: plt.figure() plt.plot(Msize, speedupM, 'r') plt.xlabel('M') plt.ylabel('Speedup') plt.title('Speedup of simulate2_omp against M') plt.show() plt.figure() plt.plot(Msize, onethreadtimeM, 'b', label='1 thread (M)') plt.plot(Nsize, onethreadtimeN, 'b--', label='1 thread (N)') plt.plot(Msize, twothreadtimeM, 'g', label='2 threads (M)') plt.plot(Nsize, twothreadtimeN, 'g--', label='2 threads (N)') plt.xlabel('M/N') plt.ylabel('Runtime') plt.legend() plt.title('Performance of simulate2_omp using 1 or 2 threads') plt.show() plt.figure() plt.plot(Msize, relfortran, 'r', label='Fortran') plt.plot(Msize, relpython, 'r--', label='Python') plt.xlabel('M') plt.ylabel('Runtime of simulate2_omp/Runtime of other function') plt.title('Relative Performance of Fortran/Python Implementations') plt.legend() plt.show() return None #Modify as needed def analyze(input=(None),display=False): """Analyze influence of model parameter, g. Modify the contents of the tuple, input, as needed When display is True, figures equivalent to those you are submitting should be displayed Comments: The first graph shows that the new variable, gamma, affects both the value that the fc_ave tends to, as well as the number of days the fc_ave takes to converge. Taking b=1.3, we can see that as gamma increases from 0.8, the proportions of M/C villages takes more time to become stable, but tend to result in M winning more of the villages (shown by the lower fc_ave). This is true except for gamma = 1, when the fc_ave appears to be tending to around a half. The second graph is a contour plot of fc_ave for different values of b and g. The yellow vertical line at gamma =1 corresponds to what we found in the previous graph, and we see that this high proportion of C villages occurs for all values of b. Except for this, we can see that for all values of b, M fares better as gamma increases, and has the best chance for high values of b and g (except 1). """ #set parameters tr.tr_e = 0.01 N=51 tr.tr_b=1.3 #choose gamma/b values gammas = [0.8, 0.9, 0.95, 0.98, 0.995, 0.9995, 1] bs = [1.05, 1.1, 1.2, 1.3, 1.4, 1.5] #intialise array fcave80 = np.zeros((len(bs), len(gammas))) #plot figures if display == True: plt.figure() for i in range(len(gammas)): tr.tr_g=gammas[i] fcave = tr.simulate2_omp(N,100,100)[1] plt.plot(range(101),fcave, label='g ='+str(gammas[i])) plt.xlabel('Time') plt.ylabel('fc_ave') plt.title('fc_ave over time for different g values (b=1.3)') plt.legend() plt.show() plt.figure() X, Y = np.meshgrid(gammas, bs) for i in range(len(gammas)): tr.tr_g = gammas[i] for j in range(len(bs)): tr.tr_b=bs[j] fcave80[j,i]=tr.simulate2_omp(N,80,100)[1][40] plt.contourf(X,Y, fcave80, 15) plt.colorbar() plt.xlabel('g') plt.ylabel('b') plt.title('Contour plot of fc_ave after 80 days (e=0.01)') plt.show() return None #Modify as needed def visualize(): """Generate an animation illustrating the evolution of villages during C vs M competition """ #set parameters tr.tr_e=0.01 tr.tr_g=0.95 tr.tr_b=1.2 #get 3D array of one trial at each time step evolv= tr.simulate22_f90(21,100) def update_fig(x): im.set_array(evolv[:,:,x]) return im, #get animation fig=plt.figure() im=plt.imshow(evolv[:,:,0], animated=True) x =0 ani = animation.FuncAnimation(fig, update_fig, frames=100, blit=True, repeat=False) ani.save('hw3movie.mp4', writer='ffmpeg') #save animation return None #Modify as needed if __name__ == '__main__': #Modify the code here so that it calls performance analyze and # generates the figures that you are submitting with your code input_p = None output_p = performance(input_p) #modify as needed input_a = None output_a = analyze(input_a)
Swift
UTF-8
1,958
2.703125
3
[ "MIT" ]
permissive
// // AnimatedImageView.swift // AnimatedImage // // Created by Tigran Yesayan on 6/26/17. // Copyright © 2017 Tigran Yesayan. All rights reserved. // import UIKit private let kContentChangeAnimation = "__contentChangeAnimation" public class AnimatedImageView: UIImageView { public override class var layerClass: AnyClass { get { return AnimatedImageLayer.self } } private var animatedLayer: AnimatedImageLayer { return self.layer as! AnimatedImageLayer } public override init(frame: CGRect) { super.init(frame: frame) setup() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } // MARK - Setup private func setup() -> Void { animatedLayer.contentsGravity = kCAGravityResizeAspect } public var animatedImage: AnimatedImage? { set { animatedLayer.animatedImage = newValue animatedLayer.removeAnimation(forKey: kContentChangeAnimation) if let image = newValue { animatedLayer.add(contentChangeAnimation(frameCount: image.frameCount - 1, duration: image.duration), forKey: kContentChangeAnimation) } } get { return self.animatedLayer.animatedImage } } private func contentChangeAnimation(frameCount: Int, duration: CFTimeInterval) -> CABasicAnimation { let animation = CABasicAnimation(keyPath: "index") animation.fromValue = 0 animation.toValue = frameCount animation.fillMode = kCAFillModeForwards animation.repeatCount = Float.infinity animation.duration = duration return animation } public var paused: Bool { set { animatedLayer.speed = newValue ? 0 : 1 } get { return animatedLayer.speed == 0 } } }
PHP
UTF-8
2,678
2.734375
3
[]
no_license
<?php /** * POST createProperty * Summary: Create property * Notes: * Output-Formats: [application/json] */ $app->POST('/v2/property', function ($request, $response, $args) { try { $dataRequest = $request->getParsedBody(); $insertStatement = $this->db->insert(array_keys($dataRequest)) ->into('property') ->values(array_values($dataRequest)); $insertId = $insertStatement->execute(true); $dataRequest['id'] = $insertId; return $response->withJson(json_decode(json_encode(($dataRequest))), 201); } catch (Exception $e) { return $response->withJson(['message' => 'An error is occured'], 404); } }); /** * DELETE deleteProperty * Summary: Delete property * Notes: * Output-Formats: [application/json] */ $app->DELETE('/v2/property/{id}', function ($request, $response, $args) { //todo : delete property by id property, but don't forget to delete id_renter on property. (may be another routes in user). $deleteStatement = $this->db->delete() ->from('property') ->where('id', '=', $args['id']); $affectedRows = $deleteStatement->execute(); if ($affectedRows) return $response->withJson(['message' => 'User is delete'], 200); return $response->withJson(['message' => 'An error is occured'], 404); }); /** * GET getAllPropertyByUserId * Summary: Get all property by user id * Notes: * Output-Formats: [application/json] */ $app->GET('/v2/property/{userId}', function ($request, $response, $args) { $sth = $this->db->prepare(' SELECT p.* FROM `user` u JOIN `property` p ON u.id = p.id_owner WHERE p.id_owner = :userId'); $sth->bindParam(':userId', $args['userId'], PDO::PARAM_INT); $sth->execute(); $data = $sth->fetchAll(); $response = $response->withJson($data); if (empty($data)) return $response->withJson(['message' => 'User(s) not found'], 404); return $response; }); /** * PUT updatePropertyById * Summary: update property * Notes: * Output-Formats: [application/json] */ $app->PUT('/v2/property', function ($request, $response, $args) { $dataRequest = $request->getParsedBody(); if (!isset($dataRequest['id'])) return $response->withJson(['message' => 'Property\'s ID is required'], 404); $updateStatement = $this->db->update($dataRequest) ->table('property') ->where('id', '=', $dataRequest['id']); $affectedRows = $updateStatement->execute(); if ($affectedRows) return $response->withJson(['message' => 'Property is update'], 200); return $response->withJson(['message' => 'Property not found or no update data'], 404); });
C#
UTF-8
807
2.765625
3
[]
no_license
public void NewClass() { try { con.Open(); SqlCommand cmd = new SqlCommand("create database "+dbnm,con); cmd.ExecuteNonQuery(); cmd.Cancel();cmd.Dispose(); con.Close();con.Dispose(); con = new SqlConnection("Data Source=DESKTOP-0R1BJNQ\\HARDIKPATEL;Initial Catalog="+dbnm+";Integrated Security=True"); con.Open(); cmd = new SqlCommand("CREATE TABLE dbo.MyTable (ID int IDENTITY(1,1) PRIMARY KEY,MyProduct nvarchar(100) NOT NULL,MyDateTime datetime NOT NULL)", con); cmd.ExecuteNonQuery(); cmd.Cancel();cmd.Dispose(); con.Close();con.Dispose(); } catch(Exception err) { lblmsg.Text = err.ToString(); } }
Markdown
UTF-8
3,010
3.1875
3
[ "MIT" ]
permissive
# Căi Express permite mai multe modalități de formare a căilor necesare rutării. ## Căi explicite Introduci calea ca prim argument. ```javascript app.use('/abcd', function (req, res, next) { next(); }); ``` ## Căi după șabloane O cale care începe cu `ab`, este urmat de caracterul `c`, care poate exista sau nu, urmat de orice caracter, dacă este menționat vreunul, dar care se încheie cu `d`. ```javascript app.use('/abc?d', function (req, res, next) { next(); }); ``` Calea de mai jos trebuie să înceapă cu `ab`, poate continua cu orice, dar trebuie să se încheie cu `cd`. ```javascript app.use('/ab+cd', function (req, res, next) { next(); }); ``` În cazul de mai jos `\*` înseamnă absolut orice caracter ```javascript app.use('/ab\*cd', function (req, res, next) { next(); }); ``` Se pot grupa caractere pentru care se fac opțiuni. În exemplul de mai jos, grupul `(bc)` poate să apară sau nu. ```javascript app.use('/a(bc)?d', function (req, res, next) { next(); }); ``` ## Expresii regulate ```javascript app.use(/\/abc|\/xyz/, function (req, res, next) { next(); }); ``` ## Array-uri în orice combinație Ceea ce permite Express este combinarea de fragmente de text sau șabloane într-un singur array, care va fi folosit pentru a se face potrivirea pe rută. ```javascript app.use(['/abcd', '/xyza', /\/lmn|\/pqr/], function (req, res, next) { next(); }); ``` ## Parametrii în rute Parametrii din căi sunt segmente URL folosite pentru a captura valori în funcție de poziția lor din URL. Valorile care sunt extrase din URL sunt introduse în obiectul `req.params`. ```text Route path: /users/:userId/books/:bookId Request URL: http://localhost:3000/users/34/books/8989 /* req.params: { "userId": "34", "bookId": "8989"} */ ``` Numele parametrilor din rute pot fi caractere literale: ([A-Za-z0-9_]). ```javascript app.get('/users/:userId/books/:bookId', function (req, res) { res.send(req.params) }) ``` Liniuța (`-`) și punctul (`.`) sunt interpretate literal, ceea ce permite realizarea de astfel de parametri precum cei de mai jos. ```text Route path: /flights/:from-:to Request URL: http://localhost:3000/flights/LAX-SFO req.params: { "from": "LAX", "to": "SFO" } ``` Sunt permise și astfel de construcții cu punct. ```text Route path: /plantae/:genus.:species Request URL: http://localhost:3000/plantae/Prunus.persica req.params: { "genus": "Prunus", "species": "persica" } ``` Pentru a controla mai bine string-urile care se vor potrivi cu un anumit șablon, se poate folosi și o expresie regulată, care va fi menționată între paranteze. ```text Route path: /user/:userId(\d+) Request URL: http://localhost:3000/user/42 req.params: {"userId": "42"} ``` Referitor la expresii regulate, în Express caracterul `*` este interpretat diferit, recomandarea fiind evitarea folosirii acestuia. În locul lui `*` se poate folosi `{0,}`. ## Referințe - [Path examples](http://expressjs.com/en/4x/api.html#path-examples)
Java
WINDOWS-1252
945
2.0625
2
[]
no_license
package com.guyi.TestNG; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.annotations.Test; import org.testng.annotations.BeforeTest; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeSuite; import org.testng.annotations.AfterSuite; import com.guyi.Base.BasePage; public class TestNGBase { static WebDriver driver ; static BasePage basepage ; @Test public void createDriver() { if(TestNGBase.driver == null ){ driver = new FirefoxDriver(); System.err.println("test TestNGBase---------"+driver); } driver.manage().window().maximize(); } @BeforeTest public void beforeTest() { } @AfterTest public void afterTest() { } @BeforeSuite public void beforeSuite() { System.err.println("11111"); } @AfterSuite public void afterSuite() { System.err.println("رdriver"); driver.quit(); } }
C++
UTF-8
1,806
2.53125
3
[ "MIT" ]
permissive
#include "Polygon3DDataBS.h" #include "Polygon3DTopology.h" #include <data_structures/VectorOperations.h> Polygon3DDataBS::Polygon3DDataBS( const std::shared_ptr<Polygon3DTopology>& topology, const Vectors& positionsBS, const Vectors& outerVertexNormalsBS, const Vectors& outerFaceNormalsBS) : Polygon3DData (topology) , mPositionsBS(positionsBS) , mOuterVertexNormalsBS(outerVertexNormalsBS) , mOuterFaceNormalsBS(outerFaceNormalsBS) { } Polygon3DDataBS::~Polygon3DDataBS() { } Vectors& Polygon3DDataBS::getPositionsBS() { return mPositionsBS; } void Polygon3DDataBS::setPositionsBS(const Vectors& positionsBS) { mPositionsBS = positionsBS; } Vectors& Polygon3DDataBS::getOuterVertexNormalsBS() { return mOuterVertexNormalsBS; } void Polygon3DDataBS::setOuterVertexNormalsBS(const Vectors& outerVertexNormalsBS) { mOuterVertexNormalsBS = outerVertexNormalsBS; } Vectors& Polygon3DDataBS::getOuterFaceNormalsBS() { return mOuterFaceNormalsBS; } void Polygon3DDataBS::setOuterFaceNormalsBS(const Vectors& outerFaceNormalsBS) { mOuterFaceNormalsBS = outerFaceNormalsBS; } void Polygon3DDataBS::removeVector(ID index) { Polygon3DData::removeVector(index); VectorOperations::removeVector(mPositionsBS, index); VectorOperations::removeVector(mOuterVertexNormalsBS, index); VectorOperations::removeVector(mOuterFaceNormalsBS, index); } void Polygon3DDataBS::removeVectors(std::vector<ID>& indices) { Polygon3DData::removeVectors(indices); VectorOperations::removeVectors(mPositionsBS, indices.begin(), indices.end()); VectorOperations::removeVectors(mOuterVertexNormalsBS, indices.begin(), indices.end()); VectorOperations::removeVectors(mOuterFaceNormalsBS, indices.begin(), indices.end()); }
Shell
UTF-8
1,293
4.34375
4
[]
no_license
#!/bin/bash # # create a tree full of files that can be used to verify access # checking behavior. # # You will want to change TEST_DIR to be on the file system to be tested. # You might want to change TEST_PGM to be a fully qualified file name # # program that can be executed for testing purposes TEST_PGM=./check_access # directory under which all of this testing should take place TEST_DIR="/tmp/wherever" if [ -d $TEST_DIR ] then echo cleaning previous $TEST_DIR rm -rf $TEST_DIR/* else echo "creating $TEST_DIR" mkdir $TEST_DIR chmod 777 $TEST_DIR fi MANIFEST="$TEST_DIR/Manifest" echo $TEST_DIR > $MANIFEST # figure out who is going to own these files MY_UID=`id -u` MY_GID=`id -g` # create top level directories with a range of accesses for dirmode in 500 700 750 770 775 777 do dirname=$TEST_DIR/UID_"$MY_UID"_GID_"$MY_GID"_MODE_"$dirmode" mkdir $dirname echo $dirname >> $MANIFEST # create files with a range of accesses for filemode in 400 500 700 740 750 770 744 755 777 do filename=UID_"$MY_UID"_GID_"$MY_GID"_MODE_"$filemode" cp $TEST_PGM $dirname/$filename chmod $filemode $dirname/$filename echo $dirname/$filename >> $MANIFEST done # we chmod at the end, because some are not me-writeable chmod $dirmode $dirname done
JavaScript
UTF-8
2,109
3.03125
3
[]
no_license
"use strict"; exports.__esModule = true; var tuckShop_1 = require("../tuckshop/tuckShop"); var vendingMachine_1 = require("../vending/vendingMachine"); function main() { var t = []; t.push(new tuckShop_1.TuckShop("T1", 1, "b", new vendingMachine_1.VendingMachine("Coco-cola", 1, 2, 15))); t.push(new tuckShop_1.TuckShop("T2", 2, "e", new vendingMachine_1.VendingMachine("Pepsi", 2, 2, 15))); t.push(new tuckShop_1.TuckShop("T3", 3, "b", new vendingMachine_1.VendingMachine("Maza", 3, 1, 20))); t.push(new tuckShop_1.TuckShop("T4", 4, "e", new vendingMachine_1.VendingMachine("ButterMilk", 2, 1, 12))); var vendingMachine = new vendingMachine_1.VendingMachine("ThumsUp", 4, 2, 30); t.push(new tuckShop_1.TuckShop("T5", 5, "b", vendingMachine)); //Displaying details of TuckShop array console.table(t); t.forEach(function (e) { console.log("Machine Name = " + e.getMachineName() + " MachineId = " + e.getMachineId() + " PowerType = " + e.getPowerType()); }); // Searching function findElement(drinkName) { return t.filter(function (e) { return e.getVendingMachine().getDrinkName() === drinkName; }); } var element = findElement("Pepsi"); if (element) { console.log(element[0]); console.log(element[0].getVendingMachine().findBill()); } // sorting based of machine name t.sort(function (t1, t2) { if (t1.getMachineName() < t2.getMachineName()) { return 1; } }); console.table(t); // sorting based on cost of one cup in vending machine. t.sort(function (t1, t2) { return t1.getVendingMachine().getCostOfOneCup() - t2.getVendingMachine().getCostOfOneCup(); }); console.table(t); //searching based on costofonecup function findElementBasedOnCost(costofonecup) { return t.filter(function (e) { return e.getVendingMachine().getCostOfOneCup() === costofonecup; }); } element = findElementBasedOnCost(12); if (element) { console.log(element[0]); console.log(element[0].getVendingMachine().findBill()); } } main();
Swift
UTF-8
630
2.671875
3
[]
no_license
// // NetworkConstants.swift // CarMeets // // Created by Lennert Bontinck on 18/01/2019. // Copyright © 2019 Lennert Bontinck. All rights reserved. // import Foundation /** Base URL's voor communicatie met de backend. */ struct NetworkConstants { static let baseApiURL = URL(string: "https://carmeets-backend.herokuapp.com/API/")! static let baseApiMeetingsURL = URL(string: "https://carmeets-backend.herokuapp.com/API/meetings/")! static let baseApiUsersURL = URL(string: "https://carmeets-backend.herokuapp.com/API/users/")! static let baseImageURL = URL(string: "https://carmeets-backend.herokuapp.com/uploadImages/")! }
Ruby
UTF-8
631
2.65625
3
[]
no_license
module Kernel def Boolean(string) return true if string== true || string =~ (/(true|t|yes|y|1)$/i) return false if string== false || string.nil? || string =~ (/(false|f|no|n|0)$/i) raise ArgumentError.new("invalid value for Boolean: \"#{string}\"") end if RUBY_VERSION < "1.9" def ruby_18 yield end def ruby_19 false end else def ruby_18 false end def ruby_19 yield end end end module Kernel def suppress_warnings original_verbosity = $VERBOSE $VERBOSE = nil result = yield $VERBOSE = original_verbosity return result end end
C#
UTF-8
7,075
2.828125
3
[ "MIT" ]
permissive
using NAudio.Wave; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Zokma.Libs.Audio { /// <summary> /// Audio data. /// </summary> public class AudioData : IDisposable { /// <summary> /// Min volume. /// </summary> private const float MIN_VOLUME = AudioPlayer.MIN_VOLUME; /// <summary> /// Max volume. /// </summary> private const float MAX_VOLUME = AudioPlayer.MAX_VOLUME; /// <summary> /// Min resampling quality. /// </summary> private const int MIN_RESAMPLING_QUALITY = 1; /// <summary> /// Max resampling quality. /// </summary> private const int MAX_RESAMPLING_QUALITY = 60; private bool disposedValue; /// <summary> /// Audio file path. /// </summary> internal string FilePath { get; private set; } /// <summary> /// Cached audio data. /// </summary> internal float[] Data { get; private set; } /// <summary> /// Checks if the audio data is cached. /// </summary> public bool IsCached { get { return (this.Data != null); } } /// <summary> /// Audio wave format. /// </summary> public WaveFormat WaveFormat { get; private set; } /// <summary> /// Resampling Quality. /// </summary> internal int ResamplingQuality { get; private set; } /// <summary> /// Audio volume. /// </summary> public float Volume { get; private set; } /// <summary> /// Constructor is private. /// </summary> private AudioData() { } /// <summary> /// Creates resampler. /// </summary> /// <param name="reader">Audio file reader.</param> /// <param name="targetFormat">Target Wave format.</param> /// <param name="resamplingQuality">Resampling quality from min(1) to max(60).</param> /// <returns>Resampler.</returns> internal static MediaFoundationResampler CreateResampler(AudioFileReader reader, WaveFormat targetFormat, int resamplingQuality) { if(reader.WaveFormat.SampleRate != targetFormat.SampleRate) { var format = NAudio.Wave.WaveFormat.CreateIeeeFloatWaveFormat(targetFormat.SampleRate, targetFormat.Channels); var resampler = new MediaFoundationResampler(reader, format) { ResamplerQuality = resamplingQuality }; return resampler; } return null; } /// <summary> /// Loads audio file. /// </summary> /// <param name="filePath">Audio file path.</param> /// <param name="waveFormat">Target Wave format. The format will be resampled if needed.</param> /// <param name="isCached">true if the audio file is cached on the memory.</param> /// <param name="volume">Audio volume.</param> /// <param name="resamplingQuality">Resampling quality from min(1) to max(60).</param> /// <returns>Audio data.</returns> public static AudioData LoadAudio(string filePath, WaveFormat waveFormat = null, bool isCached = true, float volume = 1.0f, int resamplingQuality = 60) { // Instantiate once to check format even if the audio data will not be cached. using var reader = new AudioFileReader(filePath); var audioData = new AudioData() { FilePath = filePath, WaveFormat = ((waveFormat != null) ? (new WaveFormat(waveFormat.SampleRate, reader.WaveFormat.Channels)) : (new WaveFormat(reader.WaveFormat))), ResamplingQuality = Math.Min(Math.Max(resamplingQuality, MIN_RESAMPLING_QUALITY), MAX_RESAMPLING_QUALITY), Volume = Math.Min(Math.Max(volume, MIN_VOLUME), MAX_VOLUME), }; if (isCached) { var buffer = new List<float>((int)(reader.Length << 2)); var readBuffer = new float[audioData.WaveFormat.SampleRate * audioData.WaveFormat.Channels]; using var resampler = CreateResampler(reader, audioData.WaveFormat, audioData.ResamplingQuality); ISampleProvider stream; if(resampler != null) { //stream = WaveExtensionMethods.ToSampleProvider(resampler); stream = resampler.ToSampleProvider(); } else { stream = reader; } int samplesRead; while ((samplesRead = stream.Read(readBuffer, 0, readBuffer.Length)) > 0) { buffer.AddRange(readBuffer.Take(samplesRead)); } audioData.Data = buffer.ToArray(); } return audioData; } /// <summary> /// Loads audio file. /// </summary> /// <param name="filePath">Audio file path.</param> /// <param name="isCached">true if the audio file is cached on the memory.</param> /// <param name="volume">Audio volume.</param> /// <returns>Audio data.</returns> public static AudioData LoadAudio(string filePath, bool isCached = true, float volume = 1.0f) { return LoadAudio(filePath, null, isCached, volume); } /// <summary> /// Loads audio file. /// </summary> /// <param name="filePath">Audio file path.</param> /// <returns>Audio data.</returns> public static AudioData LoadAudio(string filePath) { return LoadAudio(filePath, null); } protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects) } // TODO: free unmanaged resources (unmanaged objects) and override finalizer // TODO: set large fields to null this.Data = null; this.FilePath = null; disposedValue = true; } } // // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources // ~AudioData() // { // // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method // Dispose(disposing: false); // } public void Dispose() { // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method Dispose(disposing: true); GC.SuppressFinalize(this); } } }
C++
UTF-8
956
3.078125
3
[]
no_license
#include <iostream> using namespace std; int main() { int n; cin>>n; int a[n]; for(int i=0;i<n;i++){ cin>>a[i]; } int smaller[n]; int greater[n]; smaller[0]=-1; int min=0; for(int i=1;i<n;i++) { if(a[i]<=a[min]) { min=i; smaller[i]=-1; } else { smaller[i]=min; } } greater[n-1]=-1; int max=n-1; for(int i=n-2;i>=0;i--) { if(a[i]>a[max]) { max=i; greater[i]=-1; } else { greater[i]=max; } } for(int i=0;i<n;i++){ if(smaller[i]!=-1&&greater[i]!=-1){ cout<<a[smaller[i]]<<" "<<a[i]<<" "<<a[greater[i]]<<endl; } } return 0; } /****************************************************************************** Input--> 7 12 11 10 5 6 2 30 Output--> 5 6 30 *******************************************************************************/
Markdown
UTF-8
1,300
2.578125
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- description: Gets a pointer to the pool of shared parameters. ms.assetid: 1e999fd5-76ef-43fa-8a77-ae6f2821f46d title: ID3DXEffect::GetPool method (D3DX9Effect.h) ms.topic: reference ms.date: 05/31/2018 topic_type: - APIRef - kbSyntax api_name: - ID3DXEffect.GetPool api_type: - COM api_location: - D3dx9.lib - D3dx9.dll --- # ID3DXEffect::GetPool method Gets a pointer to the pool of shared parameters. ## Syntax ```C++ HRESULT GetPool( [out] LPD3DXEFFECTPOOL *ppPool ); ``` ## Parameters <dl> <dt> *ppPool* \[out\] </dt> <dd> Type: **[**LPD3DXEFFECTPOOL**](id3dxeffectpool.md)\*** Pointer to a [**ID3DXEffectPool**](id3dxeffectpool.md) object. </dd> </dl> ## Return value Type: **[**HRESULT**](https://msdn.microsoft.com/library/Bb401631(v=MSDN.10).aspx)** This method always returns the value S\_OK. ## Remarks Pools contain shared parameters between effects. See [Cloning and Sharing (Direct3D 9)](cloning-and-sharing.md). ## Requirements | Requirement | Value | |--------------------|------------------------------------------------------------------------------------------| | Header<br/> | <dl> <dt>D3DX9Effect.h</dt> </dl> | | Library<br/> | <dl> <dt>D3dx9.lib</dt> </dl> | ## See also <dl> <dt> [ID3DXEffect](id3dxeffect.md) </dt> </dl>    
C#
UTF-8
443
3.125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication.Calculator { public class OperationAdd { public float Calculate(string inputA, string inputB) { inputA = inputA.Replace('.', ','); inputB = inputB.Replace('.', ','); return float.Parse(inputA) + float.Parse(inputB); } } }
Python
UTF-8
1,247
3.171875
3
[]
no_license
# coding:utf-8 ''' @Copyright:LintCode @Author: ultimate010 @Problem: http://www.lintcode.com/problem/regular-expression-matching @Language: Python @Datetime: 16-07-03 08:50 ''' class Solution: """ @param s: A string @param p: A string includes "." and "*" @return: A boolean """ def isMatch(self, s, p): # write your code here m = len(s) n = len(p) if m == 0 and n == 0: return True if n > 0 and p[0] == '*': return False dp = [[False] * (n + 1) for i in range(m + 1)] dp[0][0] = True for i in range(1, n + 1): if p[i - 1] == '*': dp[0][i] = dp[0][i - 2] for i in range(1, m + 1): for j in range(1, n + 1): if p[j - 1] == '*': dp[i][j] = dp[i][j - 2] # not use 'x*' if p[j - 2] == s[i - 1] or p[j - 2] == '.': # use 'x*' dp[i][j] |= dp[i - 1][j] else: if s[i - 1] == p[j - 1] or p[j - 1] == '.': dp[i][j] = dp[i - 1][j - 1] # print dp return dp[-1][-1]
Ruby
UTF-8
875
3.96875
4
[]
no_license
# puts "WEBCAMP".methods # puts "WEBCAMP".reverse # puts "WEBCAMPでプログラミング学習".include?("WEBCAMP") # tall = 180 # if tall >= 170 && tall <= 190 # puts "身長は170以上190以下です。" # end # puts 'キーボードで数字「2」と数字「3」を入力してください' # a = gets.to_i # b = gets.to_i # puts "a+b=#{a+b}" dice = 0 while dice != 6 do dice =rand(1..6) puts dice end # for i in 1..10 do # puts i # end # {"apple"=>130, "strawberry"=>180, "orange"=>100}.each do |fruit, price| #ハッシュの内容を順にキーをfruit、値をpriceに代入して繰り返す # puts "#{fruit}は#{price}円です。" #変数展開 # end # puts "計算を始めます" # "2つの値を入力してください" # a = gets.to_i # b = gets.to_i # puts"計算結果を出力します" # "a*b=#{a*b}"
Python
UTF-8
402
3.453125
3
[]
no_license
import time def sieve_eratosthenes(n): sieve = [1] * n sieve[0] = 0 for p in xrange(2, n + 1): if sieve[p - 1]: # print p for i in xrange(p ** 2, n + 1, p): sieve[i - 1] = 0 n = 100000000 average = 0 for _ in xrange(2): start = time.time() sieve_eratosthenes(n) end = time.time() average += end - start print average / 2.
Python
UTF-8
26,453
2.703125
3
[]
no_license
import random import copy from ks.commands import ECommandDirection, ChangeGhostDirection, ChangePacmanDirection from ks.models import ECell, EDirection ai = None CELL_EMPTY = ECell.Empty CELL_FOOD = ECell.Food CELL_SUPERFOOD = ECell.SuperFood CELL_WALL = ECell.Wall DIR_UP = EDirection.Up DIR_RIGHT = EDirection.Right DIR_DOWN = EDirection.Down DIR_LEFT = EDirection.Left food = [[]] super_food = [[]] super_food_for_ghosts = [[]] ghost_is_triggered = 0 distance_to_ghost_memory = [100, 100, 100] def initialize(width, height, my_score, other_score, board, pacman, ghosts, constants, my_side, other_side, current_cycle, cycle_duration): food.pop(0) super_food.pop(0) super_food_for_ghosts.pop(0) for x in range(width): for y in range(height): if board[y][x] == CELL_FOOD: food.append([y, x]) for x in range(width): for y in range(height): if board[y][x] == CELL_SUPERFOOD: super_food.append([y, x]) for x in range(width): for y in range(height): if board[y][x] == CELL_SUPERFOOD: super_food_for_ghosts.append([y, x]) pass def decide(width, height, my_score, other_score, board, pacman, ghosts, constants, my_side, other_side, current_cycle, cycle_duration): global ghost_is_triggered global food_map_copy food_map_copy = 0 food_board = copy.deepcopy(board) def nearest_ghost(): minimum_distance = 100000 for id in range(len(ghosts)): temp = len(FindPATH(pacman, ghosts[id].x, ghosts[id].y, 0, ghosts, board, width, height, 'nor', pacman)) if temp < minimum_distance: minimum_distance = temp return minimum_distance def nearest_ghost_id(): target_id = 0 minimum_distance = 100000 for id in range(len(ghosts)): temp = len(FindPATH(pacman, ghosts[id].x, ghosts[id].y, 0, ghosts, board, width, height, 'nor', pacman)) if temp < minimum_distance: minimum_distance = temp target_id = id return target_id def pacman_move(path): desiredY = path[0] - pacman.y desiredX = path[1] - pacman.x if is_there_any_ghost(desiredX,desiredY,board,width,height,ghosts): if pacman.direction == DIR_RIGHT: change_pacman_direction(DIR_LEFT) if pacman.direction == DIR_LEFT: change_pacman_direction(DIR_RIGHT) if pacman.direction == DIR_DOWN: change_pacman_direction(DIR_UP) if pacman.direction == DIR_UP: change_pacman_direction(DIR_DOWN) return if desiredX == 1: change_pacman_direction(DIR_RIGHT) if desiredX == -1: change_pacman_direction(DIR_LEFT) if desiredY == 1: change_pacman_direction(DIR_DOWN) if desiredY == -1: change_pacman_direction(DIR_UP) def pacman_eat_food(): print('pacman_eat_food') global food_map_copy if food_map_copy == 0: map_copy_food() path = find_path_to_nearst_food(pacman, CELL_FOOD, 1, ghosts, food_board, width, height)[1] pacman_move(path) def pacman_eat_super_food(): print('pacman_eat_super_food') if [pacman.x, pacman.y] in super_food: for counter in range(len(super_food)): if pacman.x == super_food[1] and pacman.y == super_food[0]: super_food.pop(counter) if len(super_food): path = find_path_to_nearst_food(pacman, CELL_SUPERFOOD, 1, ghosts, board, width, height)[1] pacman_move(path) else: pacman_eat_food() def map_copy_food(): for x in range(width): for y in range(height): if board[y][x] == CELL_SUPERFOOD: food_board[y][x] = CELL_WALL def pacman_attack(): global ghost_is_triggered ghost_is_triggered = 0 print('pacman_attack') id = nearest_ghost_id() path = pacman_attack_path(id, ghosts, board, width, height, pacman)[1] pacman_move(path) def distance_to_super_foods(): if len(super_food_for_ghosts) == 0: return 0 distance = 1000 for iterator in range(len(super_food_for_ghosts)): temp_super_food = super_food_for_ghosts[iterator] temp = len(FindPATH(pacman, temp_super_food[1], temp_super_food[0], 1, ghosts, board, width, height, 'nor', pacman)) if temp < distance: distance = temp if [pacman.x, pacman.y] in super_food_for_ghosts: for counter in range(len(super_food_for_ghosts)): if pacman.x == super_food_for_ghosts[1] and pacman.y == super_food_for_ghosts[0]: super_food_for_ghosts.pop(counter) print('in distance to super foods', distance) return distance def ghost_move(id, path): desiredY = path[0] - ghosts[id].y desiredX = path[1] - ghosts[id].x if desiredX == 1: change_ghost_direction(id, DIR_RIGHT) if ghosts[id].direction == DIR_LEFT: if board[ghosts[id].y][ghosts[id].x + 1] == CELL_WALL: change_ghost_direction(id, DIR_RIGHT) if board[ghosts[id].y+1][ghosts[id].x] == CELL_WALL: change_ghost_direction(id, DIR_UP) else: change_ghost_direction(id, DIR_DOWN) if desiredX == -1: change_ghost_direction(id, DIR_LEFT) if ghosts[id].direction == DIR_RIGHT: if board[ghosts[id].y][ghosts[id].x - 1] == CELL_WALL: change_ghost_direction(id, DIR_LEFT) if board[ghosts[id].y+1][ghosts[id].x] == CELL_WALL: change_ghost_direction(id, DIR_UP) else: change_ghost_direction(id, DIR_DOWN) if desiredY == 1: change_ghost_direction(id, DIR_DOWN) if ghosts[id].direction == DIR_UP: if board[ghosts[id].y - 1][ghosts[id].x] == CELL_WALL: change_ghost_direction(id, DIR_DOWN) if board[ghosts[id].y][ghosts[id].x+1] == CELL_WALL: change_ghost_direction(id, DIR_LEFT) else: change_ghost_direction(id, DIR_RIGHT) if desiredY == -1: change_ghost_direction(id, DIR_UP) if ghosts[id].direction == DIR_DOWN: if board[ghosts[id].y + 1][ghosts[id].x] == CELL_WALL: change_ghost_direction(id, DIR_UP) if board[ghosts[id].y][ghosts[id].x+1] == CELL_WALL: change_ghost_direction(id, DIR_LEFT) else: change_ghost_direction(id, DIR_RIGHT) def ghost_run_away(): ghost_run_away_board = copy.deepcopy(board) if pacman.direction == DIR_DOWN: ghost_run_away_board[pacman.y - 1][pacman.x] = CELL_WALL if pacman.direction == DIR_UP: ghost_run_away_board[pacman.y + 1][pacman.x] = CELL_WALL if pacman.direction == DIR_LEFT: ghost_run_away_board[pacman.y][pacman.x + 1] = CELL_WALL if pacman.direction == DIR_RIGHT: ghost_run_away_board[pacman.y][pacman.x - 1] = CELL_WALL if pacman.x < width / 2 and pacman.y < height / 2: for id in range(len(ghosts)): path = FindPATH(ghosts[id], width - 2, height - 2, 0, ghosts, ghost_run_away_board, width, height, 'em', pacman) if len(path) == 0: change_ghost_direction(id, random.choice([DIR_LEFT, DIR_RIGHT, DIR_UP, DIR_DOWN])) return ghost_move(id, path[1]) if pacman.x < width / 2 and pacman.y > height / 2: for id in range(len(ghosts)): path = FindPATH(ghosts[id], width - 2, 1, 0, ghosts, ghost_run_away_board, width, height, 'em', pacman) if len(path) == 0: change_ghost_direction(id, random.choice([DIR_LEFT, DIR_RIGHT, DIR_UP, DIR_DOWN])) return ghost_move(id, path[1]) if pacman.x > width / 2 and pacman.y < height / 2: for id in range(len(ghosts)): path = FindPATH(ghosts[id], 1, height - 2, 0, ghosts, ghost_run_away_board, width, height, 'em', pacman) if len(path) == 0: change_ghost_direction(id, random.choice([DIR_LEFT, DIR_RIGHT, DIR_UP, DIR_DOWN])) return ghost_move(id, path[1]) if pacman.x > width / 2 and pacman.y > height / 2: for id in range(len(ghosts)): path = FindPATH(ghosts[id], 1, 1, 0, ghosts, ghost_run_away_board, width, height, 'em', pacman) if len(path) == 0: change_ghost_direction(id, random.choice([DIR_LEFT, DIR_RIGHT, DIR_UP, DIR_DOWN])) return ghost_move(id, path[1]) def ghosts_attack(): path_for_ghost_three = 0 path_for_ghost_zero = FindPATH(ghosts[0], pacman.x, pacman.y, 0, ghosts, board, width, height, 'nor', pacman)[1] path_for_ghost_one = ghost_attack_path0(1, ghosts, board, width, height, pacman)[1] path_for_ghost_two = FindPATH(ghosts[2], pacman.x, pacman.y, 0, ghosts, board, width, height, 'nor', pacman)[1] if current_cycle % 50 == 0: if path_for_ghost_zero == FindPATH(ghosts[0], pacman.x, pacman.y, 0, ghosts, board, width, height, 'nor', pacman)[1]: path_for_ghost_zero = ghost_attack_path0(0, ghosts, board, width, height, pacman)[1] else: path_for_ghost_zero = FindPATH(ghosts[0], pacman.x, pacman.y, 0, ghosts, board, width, height, 'nor', pacman)[1] if len(ghosts) == 4: path_for_ghost_three = ghost_attack_path0(3, ghosts, board, width, height, pacman)[1] ghost_move(0, path_for_ghost_zero) ghost_move(1, path_for_ghost_one) ghost_move(2, path_for_ghost_two) if len(ghosts) == 4: ghost_move(3, path_for_ghost_three) if my_side == 'Pacman': min_dist_ghosts = nearest_ghost() distance_to_ghost_memory.append(min_dist_ghosts) if len(distance_to_ghost_memory) >= 3: distance_to_ghost_memory.pop(0) if distance_to_ghost_memory[2] < 6 and distance_to_ghost_memory[1] >= distance_to_ghost_memory[2] and \ distance_to_ghost_memory[0] >= distance_to_ghost_memory[1]: ghost_is_triggered = 1 if pacman.giant_form_remaining_time > 4: pacman_attack() else: if ghost_is_triggered: pacman_eat_super_food() else: pacman_eat_food() elif my_side == 'Ghost': should_run = False if pacman.giant_form_remaining_time > 4: should_run = True else: should_run = False nearest_super_food = distance_to_super_foods() if nearest_super_food < 8: should_run = True if should_run: ghost_run_away() else: ghosts_attack() def change_pacman_direction(dir): ai.send_command(ChangePacmanDirection(direction=dir)) def change_ghost_direction(id, dir): ai.send_command(ChangeGhostDirection(id=id, direction=dir)) def FindPATH(OBJECT, x2, y2, ghostscheck, ghosts, board, width, height, status, pacman): if status == 'nor': paths = [[[OBJECT.y, OBJECT.x]]] total_paths = len(paths) used = [] while total_paths > 0: newpaths = [] index = 0 while index < total_paths: path = paths[index] x = path[-1][1] y = path[-1][0] if x == x2 and y == y2: return path else: if x + 1 < width: if board[y][x + 1] != CELL_WALL and not [y, x + 1] in (path + used): if ghostscheck: if not is_there_any_ghost(x + 1, y, board, width, height, ghosts): newpaths.append(path + [[y, x + 1]]) used.append([y, x + 1]) else: newpaths.append(path + [[y, x + 1]]) used.append([y, x + 1]) if y + 1 < height: if board[y + 1][x] != CELL_WALL and not [y + 1, x] in (path + used): if ghostscheck: if not is_there_any_ghost(x, y + 1, board, width, height, ghosts): newpaths.append(path + [[y + 1, x]]) used.append([y + 1, x]) else: newpaths.append(path + [[y + 1, x]]) used.append([y + 1, x]) if x - 1 >= 0: if board[y][x - 1] != CELL_WALL and not [y, x - 1] in (path + used): if (ghostscheck): if not is_there_any_ghost(x - 1, y, board, width, height, ghosts): newpaths.append(path + [[y, x - 1]]) used.append([y, x - 1]) else: newpaths.append(path + [[y, x - 1]]) used.append([y, x - 1]) if y - 1 >= 0: if board[y - 1][x] != CELL_WALL and not [y - 1, x] in (path + used): if ghostscheck: if not is_there_any_ghost(x, y - 1, board, width, height, ghosts): newpaths.append(path + [[y - 1, x]]) used.append([y - 1, x]) else: newpaths.append(path + [[y - 1, x]]) used.append([y - 1, x]) index += 1 paths = copy.deepcopy(newpaths) total_paths = len(paths) return [] else: print("Escape") ghostscheck = 1 paths = [[[OBJECT.y, OBJECT.x]]] total_paths = len(paths) used = [] while total_paths > 0: newpaths = [] index = 0 while index < total_paths: path = paths[index] x = path[-1][1] y = path[-1][0] if x == x2 and y == y2: return path else: if x + 1 < width: if board[y][x + 1] != CELL_WALL and not [y, x + 1] in (path + used): if (1): if not is_there_pacman(x + 1, y, board, width, height, pacman): newpaths.append(path + [[y, x + 1]]) used.append([y, x + 1]) else: newpaths.append(path + [[y, x + 1]]) used.append([y, x + 1]) if y + 1 < height: if board[y + 1][x] != CELL_WALL and not [y + 1, x] in (path + used): if (1): if not is_there_pacman(x, y + 1, board, width, height, pacman): newpaths.append(path + [[y + 1, x]]) used.append([y + 1, x]) else: newpaths.append(path + [[y + 1, x]]) used.append([y + 1, x]) if x - 1 >= 0: if board[y][x - 1] != CELL_WALL and not [y, x - 1] in (path + used): if (1): if not is_there_pacman(x - 1, y, board, width, height, pacman): newpaths.append(path + [[y, x - 1]]) used.append([y, x - 1]) else: newpaths.append(path + [[y, x - 1]]) used.append([y, x - 1]) if y - 1 >= 0: if board[y - 1][x] != CELL_WALL and not [y - 1, x] in (path + used): if (1): if not is_there_pacman(x, y - 1, board, width, height, pacman): newpaths.append(path + [[y - 1, x]]) used.append([y - 1, x]) else: newpaths.append(path + [[y - 1, x]]) used.append([y - 1, x]) index += 1 paths = copy.deepcopy(newpaths) total_paths = len(paths) return [] def is_there_any_ghost(x, y, board, width, height, ghosts): st = 0 for ID in range(0, len(ghosts)): if ghosts[ID].x == x and ghosts[ID].y == y: st = st + 1 if st >= 1: return 1 else: return 0 def is_there_pacman(x, y, board, width, height, pacman): if pacman.x == x and pacman.y == y: return 1 else: return 0 def find_path_to_nearst_food(pacman, food_type, ghostscheck, ghosts, board, width, height): paths = [[[pacman.y, pacman.x]]] total_paths = len(paths) used = [] wboard = copy.deepcopy(board) while total_paths > 0: newpaths = [] index = 0 while index < total_paths: path = paths[index] x = path[-1][1] y = path[-1][0] if wboard[y][x] == food_type: return path else: if x + 1 < width: if board[y][x + 1] != CELL_WALL and not [y, x + 1] in (path + used): if ghostscheck: if not is_there_any_ghost(x + 1, y, board, width, height, ghosts): newpaths.append(path + [[y, x + 1]]) used.append([y, x + 1]) else: newpaths.append(path + [[y, x + 1]]) used.append([y, x + 1]) if y + 1 < height: if board[y + 1][x] != CELL_WALL and not [y + 1, x] in (path + used): if ghostscheck: if not is_there_any_ghost(x, y + 1, board, width, height, ghosts): newpaths.append(path + [[y + 1, x]]) used.append([y + 1, x]) else: newpaths.append(path + [[y + 1, x]]) used.append([y + 1, x]) if x - 1 >= 0: if board[y][x - 1] != CELL_WALL and not [y, x - 1] in (path + used): if ghostscheck: if not is_there_any_ghost(x - 1, y, board, width, height, ghosts): newpaths.append(path + [[y, x - 1]]) used.append([y, x - 1]) else: newpaths.append(path + [[y, x - 1]]) used.append([y, x - 1]) if y - 1 >= 0: if board[y - 1][x] != CELL_WALL and not [y - 1, x] in (path + used): if ghostscheck: if not is_there_any_ghost(x, y - 1, board, width, height, ghosts): newpaths.append(path + [[y - 1, x]]) used.append([y - 1, x]) else: newpaths.append(path + [[y - 1, x]]) used.append([y - 1, x]) index += 1 paths = copy.deepcopy(newpaths) total_paths = len(paths) return [] def pacman_attack_path(ID, ghosts, board, width, height, pacman): paths = [[[pacman.y, pacman.x]]] total_paths = len(paths) used = [] EditedBoard = copy.deepcopy(board) if ghosts[ID].direction == DIR_DOWN: EditedBoard[ghosts[ID].y - 1][ghosts[ID].x] = CELL_WALL if ghosts[ID].direction == DIR_UP: EditedBoard[ghosts[ID].y + 1][ghosts[ID].x] = CELL_WALL if ghosts[ID].direction == DIR_LEFT: EditedBoard[ghosts[ID].y][ghosts[ID].x + 1] = CELL_WALL if ghosts[ID].direction == DIR_RIGHT: EditedBoard[ghosts[ID].y][ghosts[ID].x - 1] = CELL_WALL while total_paths > 0: newpaths = [] index = 0 while index < total_paths: path = paths[index] x = path[-1][1] y = path[-1][0] if x == ghosts[ID].x and y == ghosts[ID].y: return path else: if x + 1 < width: if EditedBoard[y][x + 1] != CELL_WALL and not [y, x + 1] in (path + used): newpaths.append(path + [[y, x + 1]]) used.append([y, x + 1]) if y + 1 < height: if EditedBoard[y + 1][x] != CELL_WALL and not [y + 1, x] in (path + used): newpaths.append(path + [[y + 1, x]]) used.append([y + 1, x]) if x - 1 >= 0: if EditedBoard[y][x - 1] != CELL_WALL and not [y, x - 1] in (path + used): newpaths.append(path + [[y, x - 1]]) used.append([y, x - 1]) if y - 1 >= 0: if EditedBoard[y - 1][x] != CELL_WALL and not [y - 1, x] in (path + used): newpaths.append(path + [[y - 1, x]]) used.append([y - 1, x]) index += 1 paths = copy.deepcopy(newpaths) total_paths = len(paths) return [] def ghost_attack_path(id, ghosts, board, width, height, pacman): paths = [[[ghosts[id].y, ghosts[id].x]]] total_paths = len(paths) used = [] edited_board = copy.deepcopy(board) if pacman.direction == DIR_DOWN: edited_board[pacman.y - 1][pacman.x] = CELL_WALL if pacman.direction == DIR_UP: edited_board[pacman.y + 1][pacman.x] = CELL_WALL if pacman.direction == DIR_LEFT: edited_board[pacman.y][pacman.x + 1] = CELL_WALL if pacman.direction == DIR_RIGHT: edited_board[pacman.y][pacman.x - 1] = CELL_WALL while total_paths > 0: newpaths = [] index = 0 while index < total_paths: path = paths[index] x = path[-1][1] y = path[-1][0] if x == ghosts[id].x and y == ghosts[id].y: return path else: if x + 1 < width: if edited_board[y][x + 1] != CELL_WALL and not [y, x + 1] in (path + used): newpaths.append(path + [[y, x + 1]]) used.append([y, x + 1]) if y + 1 < height: if edited_board[y + 1][x] != CELL_WALL and not [y + 1, x] in (path + used): newpaths.append(path + [[y + 1, x]]) used.append([y + 1, x]) if x - 1 >= 0: if edited_board[y][x - 1] != CELL_WALL and not [y, x - 1] in (path + used): newpaths.append(path + [[y, x - 1]]) used.append([y, x - 1]) if y - 1 >= 0: if edited_board[y - 1][x] != CELL_WALL and not [y - 1, x] in (path + used): newpaths.append(path + [[y - 1, x]]) used.append([y - 1, x]) index += 1 paths = copy.deepcopy(newpaths) total_paths = len(paths) return [] def ghost_attack_path0(id, ghosts, board, width, height, pacman): paths = [[[ghosts[id].y, ghosts[id].x]]] total_paths = len(paths) used = [] EditedBoard = copy.deepcopy(board) if pacman.direction == DIR_DOWN: EditedBoard[pacman.y - 1][pacman.x] = CELL_WALL if pacman.direction == DIR_UP: EditedBoard[pacman.y + 1][pacman.x] = CELL_WALL if pacman.direction == DIR_LEFT: EditedBoard[pacman.y][pacman.x + 1] = CELL_WALL if pacman.direction == DIR_RIGHT: EditedBoard[pacman.y][pacman.x - 1] = CELL_WALL while total_paths > 0: newpaths = [] index = 0 while index < total_paths: path = paths[index] x = path[-1][1] y = path[-1][0] if x == pacman.x and y == pacman.y: return path else: if x + 1 < width: if EditedBoard[y][x + 1] != CELL_WALL and not [y, x + 1] in (path + used): newpaths.append(path + [[y, x + 1]]) used.append([y, x + 1]) if y + 1 < height: if EditedBoard[y + 1][x] != CELL_WALL and not [y + 1, x] in (path + used): newpaths.append(path + [[y + 1, x]]) used.append([y + 1, x]) if x - 1 >= 0: if EditedBoard[y][x - 1] != CELL_WALL and not [y, x - 1] in (path + used): newpaths.append(path + [[y, x - 1]]) used.append([y, x - 1]) if y - 1 >= 0: if EditedBoard[y - 1][x] != CELL_WALL and not [y - 1, x] in (path + used): newpaths.append(path + [[y - 1, x]]) used.append([y - 1, x]) index += 1 paths = copy.deepcopy(newpaths) total_paths = len(paths) return []
Java
UTF-8
3,996
2.625
3
[]
no_license
package backend.deductiveRules.segments.theorems; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import backend.ast.GroundedClause; import backend.ast.Descriptors.Intersection; import backend.ast.Descriptors.Relations.Congruences.GeometricCongruentAngles; import backend.ast.figure.components.angles.Angle; import backend.deductiveRules.Deduction; import backend.deductiveRules.RuleFactory; import backend.deductiveRules.generalRules.Theorem; import backend.hypergraph.Annotation; import backend.hypergraph.QueryableHypergraph; public class VerticalAnglesTheorem extends Theorem { private static final String NAME = "Vertical Angles Theorem"; public String getName() { return NAME; } public String getDescription() { return getName(); } private final static Annotation ANNOTATION = new Annotation(NAME, RuleFactory.JustificationSwitch.VERTICAL_ANGLES); @Override public Annotation getAnnotation() { return ANNOTATION; } public VerticalAnglesTheorem(QueryableHypergraph<GroundedClause, Annotation> qhg) { super(qhg); ANNOTATION.active = RuleFactory.JustificationSwitch.VERTICAL_ANGLES; } // // Intersect(X, Segment(A, B), Segment(C, D)) -> Congruent(Angle(A, X, C), Angle(B, X, D)), // Congruent(Angle(A, X, D), Angle(C, X, B)) // public Set<Deduction> deduce() { HashSet<Deduction> deductions = new HashSet<Deduction>(); // Acquire all Midpoint clauses from the hypergraph Set<Intersection> intersections = _qhg.getIntersections(); for (Intersection intersection : intersections) { deductions.addAll(deduceTheorem(intersection)); } return deductions; } public Set<Deduction> deduceTheorem(Intersection intersection) { HashSet<Deduction> deductions = new HashSet<Deduction>(); // // Verify that this intersection is composed of two overlapping segments // That is, we do not allow a segment to stand on another: // \ // \ // \ // ______\_______ // if (intersection.standsOn()) return deductions; // // Congruent(Angle(A, X, C), Angle(B, X, D)) // List<GroundedClause> antecedent1 = new ArrayList<GroundedClause>(); antecedent1.add(intersection); Angle ang1Set1 = new Angle(intersection.getlhs().getPoint1(), intersection.getIntersect(), intersection.getrhs().getPoint1()); Angle ang2Set1 = new Angle(intersection.getlhs().getPoint2(), intersection.getIntersect(), intersection.getrhs().getPoint2()); antecedent1.add(ang1Set1); antecedent1.add(ang2Set1); GeometricCongruentAngles cca1 = new GeometricCongruentAngles(ang1Set1, ang2Set1); //cca1.MakeIntrinsic(); // This is an 'obvious' notion so it should be intrinsic to any figure deductions.add(new Deduction(antecedent1, cca1, ANNOTATION)); // // Congruent(Angle(A, X, D), Angle(C, X, B)) // List<GroundedClause> antecedent2 = new ArrayList<GroundedClause>(); antecedent1.add(intersection); Angle ang1Set2 = new Angle(intersection.getlhs().getPoint1(), intersection.getIntersect(), intersection.getrhs().getPoint2()); Angle ang2Set2 = new Angle(intersection.getlhs().getPoint2(), intersection.getIntersect(), intersection.getrhs().getPoint1()); antecedent1.add(ang1Set2); antecedent1.add(ang2Set2); GeometricCongruentAngles cca2 = new GeometricCongruentAngles(ang1Set2, ang2Set2); //cca2.MakeIntrinsic(); // This is an 'obvious' notion so it should be intrinsic to any figure deductions.add(new Deduction(antecedent2, cca2, ANNOTATION)); return deductions; } }
Python
UTF-8
231
3.5
4
[]
no_license
#Oef 04 som van n getal = input("Geef een getal op: ") getal = getal getal1 = getal+getal getal2 = getal+getal+getal getal = int(getal) getal1 = int(getal1) getal2 = int(getal2) totaal = getal + getal1 + getal2 print(totaal)
C
UTF-8
823
3.515625
4
[]
no_license
#include <stdio.h> void tohex(unsigned char * in, size_t insz, char * out, size_t outsz) { unsigned char * pin = in; const char * hex = "0123456789ABCDEF"; char * pout = out; for(; pin < in+insz; pout +=3, pin++){ pout[0] = hex[(*pin>>4) & 0xF]; pout[1] = hex[ *pin & 0xF]; pout[2] = ':'; if (pout + 3 - out > outsz){ /* Better to truncate output string than overflow buffer */ /* it would be still better to either return a status */ /* or ensure the target buffer is large enough and it never happen */ break; } } pout[-1] = 0; } int main(){ enum {insz = 4, outsz = 3*insz}; unsigned char buf[] = {0, 1, 10, 11}; char str[outsz]; tohex(buf, insz, str, outsz); printf("%s\n", str); }
C++
UTF-8
314
2.578125
3
[]
no_license
#include <iostream> #include <my_math.h> using namespace std; int main(void){ Math my_math_library; cout << my_math_library.getSin(30) << endl; cout << my_math_library.getCos(30) << endl; cout << my_math_library.getCos(45) << endl; cout << my_math_library.getSin(45) << endl; return 0; }
PHP
UTF-8
1,645
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Console\Commands; use App\model\Penjualan; use Carbon\Carbon; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; class updateExpiredOrder extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'order:expired'; /** * The console command description. * * @var string */ protected $description = 'Order Expired'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { try{ DB::beginTransaction(); //------------------------------------------------------------------------- $date = Carbon::now()->subDays(3); \Log::info("Order Update: ".$date); $penjualan = Penjualan::whereDate('created_at',Carbon::now()->subDays(3)) ->orWhere('status',null)->get(); \Log::info("Order Update: ".$penjualan); foreach ($penjualan as $item){ $item->status = "Dibatalkan"; $item->update(['status'=>'Dibatalkan']); $item->save(); } //------------------------------------------------------------------------- DB::commit(); \Log::info("Order Update: ".$penjualan); }catch (\Exception $e){ DB::rollBack(); \Log::info("Order Update Failed: "); } } }
Java
UTF-8
3,583
2.390625
2
[]
no_license
package org.me.web.plugin.shiro.authentication; import java.util.Set; import javax.annotation.Resource; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.AuthenticationInfo; import org.apache.shiro.authc.AuthenticationToken; import org.apache.shiro.authc.LockedAccountException; import org.apache.shiro.authc.SimpleAuthenticationInfo; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.AuthorizationInfo; import org.apache.shiro.authz.SimpleAuthorizationInfo; import org.apache.shiro.realm.AuthorizingRealm; import org.apache.shiro.session.Session; import org.apache.shiro.subject.PrincipalCollection; import org.apache.shiro.subject.Subject; import org.me.core.common.Constant; import org.me.web.plugin.shiro.service.ISecurityService; import org.me.web.server.entity.SystemUser; import org.me.web.server.service.ISystemUserService; public class MyRealm extends AuthorizingRealm { @Resource private ISystemUserService loginUserService; @Resource private ISecurityService securityService; /** * 为当前登录的Subject授予角色和权限 */ @Override protected AuthorizationInfo doGetAuthorizationInfo( PrincipalCollection principals) { String strLoginId = (String)principals.getPrimaryPrincipal(); // 为当前用户设置角色和权限 SimpleAuthorizationInfo auth = new SimpleAuthorizationInfo(); Set<String> roles=securityService.getRoles(strLoginId); Set<String> perms=securityService.getPermissions(roles); auth.setStringPermissions(perms);//权限加入AuthorizationInfo认证对象 return auth; } /** * 验证当前登录的Subject */ @Override protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException { SystemUser loginUser=null; if(null == getSession(Constant.LOGINUSER)){ // 实际上这个authcToken是从UserController里面subject.login(token)传过来的 // 两个token的引用都是一样的 UsernamePasswordToken token = (UsernamePasswordToken) authcToken; loginUser=loginUserService.getByLoginName(token.getUsername()); if(loginUser == null){ throw new UnknownAccountException();//没找到帐号 } if(loginUser.getnState() != 1) { throw new LockedAccountException(loginUser.getnState()+""); //帐号锁定 } }else { loginUser=(SystemUser) getSession(Constant.LOGINUSER); } AuthenticationInfo authcInfo = new SimpleAuthenticationInfo( loginUser.getStrUserId(), loginUser.getStrPassword(),getName()); this.setSession(Constant.LOGINUSER, loginUser); return authcInfo; } /** * 将一些数据放到ShiroSession中,以便于其它地方使用 * 比如Controller,使用时直接用HttpSession.getAttribute(key)就可以取到 */ private void setSession(Object key, Object value){ Subject currentUser = SecurityUtils.getSubject(); if(null != currentUser){ Session session = currentUser.getSession(); if(null != session){ session.setAttribute(key, value); } } } private Object getSession(Object key){ Subject currentUser = SecurityUtils.getSubject(); if(null != currentUser){ Session session = currentUser.getSession(); if(null != session) return session.getAttribute(key); return null; } return null; } }
Go
UTF-8
5,894
2.640625
3
[ "MIT" ]
permissive
package canvas_test import ( "fmt" "github.com/ghthor/aodd/game/client/canvas" "github.com/ghthor/filu/rpg2d" "github.com/ghthor/filu/rpg2d/coord" "github.com/ghthor/filu/rpg2d/quad" "github.com/ghthor/filu/sim/stime" "github.com/ghthor/gospec" . "github.com/ghthor/gospec" ) type terrainContext struct { rpg2d.TerrainMap } func (t *terrainContext) Reset(slice rpg2d.TerrainMapStateSlice) { tm, err := rpg2d.NewTerrainMap(slice.Bounds, slice.Terrain) if err != nil { panic(err) } t.TerrainMap = tm } func (t *terrainContext) Shift(dir canvas.TerrainShift, mags canvas.TerrainShiftMagnitudes) { switch dir { case canvas.TS_NORTH: t.shiftNorth(mags[coord.North]) case canvas.TS_NORTHEAST: t.shiftNorth(mags[coord.North]) t.shiftEast(mags[coord.East]) case canvas.TS_EAST: t.shiftEast(mags[coord.East]) case canvas.TS_SOUTHEAST: t.shiftSouth(mags[coord.South]) t.shiftEast(mags[coord.East]) case canvas.TS_SOUTH: t.shiftSouth(mags[coord.South]) case canvas.TS_SOUTHWEST: t.shiftSouth(mags[coord.South]) t.shiftWest(mags[coord.West]) case canvas.TS_WEST: t.shiftWest(mags[coord.West]) case canvas.TS_NORTHWEST: t.shiftNorth(mags[coord.North]) t.shiftWest(mags[coord.West]) default: panic(fmt.Sprintf("unknown canvas shift direction %v", dir)) } } func joinWithEmptySpace(newBounds coord.Bounds, m rpg2d.TerrainMap, diffs []coord.Bounds) rpg2d.TerrainMap { maps := make([]rpg2d.TerrainMap, 0, len(diffs)+1) for _, d := range diffs { m, err := rpg2d.NewTerrainMap(d, string(' ')) if err != nil { panic(err) } maps = append(maps, m) } maps = append(maps, m.Slice(newBounds)) m, err := rpg2d.JoinTerrain(newBounds, maps...) if err != nil { panic(err) } return m } // Shifts the image drawn on the canvas to the north // freeing up space to the south to draw in the new // tiles. func (t *terrainContext) shiftNorth(mag int) { // move bounds to south newBounds := coord.Bounds{ t.Bounds.TopL.Add(0, -mag), t.Bounds.BotR.Add(0, -mag), } t.TerrainMap = joinWithEmptySpace(newBounds, t.TerrainMap, t.Bounds.DiffFrom(newBounds)) } func (t *terrainContext) shiftEast(mag int) { // move bounds to the west newBounds := coord.Bounds{ t.Bounds.TopL.Add(-mag, 0), t.Bounds.BotR.Add(-mag, 0), } t.TerrainMap = joinWithEmptySpace(newBounds, t.TerrainMap, t.Bounds.DiffFrom(newBounds)) } func (t *terrainContext) shiftSouth(mag int) { // move bounds to the north newBounds := coord.Bounds{ t.Bounds.TopL.Add(0, mag), t.Bounds.BotR.Add(0, mag), } t.TerrainMap = joinWithEmptySpace(newBounds, t.TerrainMap, t.Bounds.DiffFrom(newBounds)) } func (t *terrainContext) shiftWest(mag int) { // move bounds to the east newBounds := coord.Bounds{ t.Bounds.TopL.Add(mag, 0), t.Bounds.BotR.Add(mag, 0), } t.TerrainMap = joinWithEmptySpace(newBounds, t.TerrainMap, t.Bounds.DiffFrom(newBounds)) } func (t *terrainContext) DrawTile(terrainType rpg2d.TerrainType, cell coord.Cell) { t.SetType(terrainType, cell) } func DescribeTerrainCanvas(c gospec.Context) { c.Specify("a terrain canvas", func() { quadTree, err := quad.New(coord.Bounds{ coord.Cell{-4, 4}, coord.Cell{3, -3}, }, 20, nil) c.Assume(err, IsNil) terrain, err := rpg2d.NewTerrainMap(quadTree.Bounds(), ` DDDDDDDD DGGGGGGD DGGRRGGD DGRRRRGD DGRRRRGD DGGRRGGD DGGGGGGD DDDDDDDD `) c.Assume(err, IsNil) world := rpg2d.NewWorld(stime.Time(0), quadTree, terrain) worldState := world.ToState() north := coord.Bounds{ coord.Cell{-2, 4}, coord.Cell{1, 1}, } northEast := coord.Bounds{ coord.Cell{0, 4}, coord.Cell{3, 1}, } east := coord.Bounds{ coord.Cell{0, 2}, coord.Cell{3, -1}, } southEast := coord.Bounds{ coord.Cell{0, 0}, coord.Cell{3, -3}, } south := coord.Bounds{ coord.Cell{-2, 0}, coord.Cell{1, -3}, } southWest := coord.Bounds{ coord.Cell{-4, 0}, coord.Cell{-1, -3}, } west := coord.Bounds{ coord.Cell{-4, 2}, coord.Cell{-1, -1}, } northWest := coord.Bounds{ coord.Cell{-4, 4}, coord.Cell{-1, 1}, } center := coord.Bounds{ coord.Cell{-2, 2}, coord.Cell{1, -1}, } c.Specify("can be reset by a diff if there is no overlap", func() { initialState := worldState.Cull(northWest) context := &terrainContext{ TerrainMap: initialState.Clone().TerrainMap.TerrainMap, } nextState := worldState.Cull(northEast) canvas.ApplyTerrainDiff(context, initialState, initialState.Diff(nextState)) c.Expect(context.String(), Equals, nextState.TerrainMap.String()) }) c.Specify("can be shifted by a diff to the", func() { initialState := worldState.Cull(center) context := &terrainContext{ TerrainMap: initialState.Clone().TerrainMap.TerrainMap, } var nextState rpg2d.WorldState expectContextIsUpdated := func() { canvas.ApplyTerrainDiff(context, initialState, initialState.Diff(nextState)) c.Expect(context.String(), Equals, nextState.TerrainMap.String()) } c.Specify("north", func() { nextState = worldState.Cull(north) expectContextIsUpdated() }) c.Specify("north & east", func() { nextState = worldState.Cull(northEast) expectContextIsUpdated() }) c.Specify("east", func() { nextState = worldState.Cull(east) expectContextIsUpdated() }) c.Specify("south & east", func() { nextState = worldState.Cull(southEast) expectContextIsUpdated() }) c.Specify("south", func() { nextState = worldState.Cull(south) expectContextIsUpdated() }) c.Specify("south & west", func() { nextState = worldState.Cull(southWest) expectContextIsUpdated() }) c.Specify("west", func() { nextState = worldState.Cull(west) expectContextIsUpdated() }) c.Specify("north & west", func() { nextState = worldState.Cull(northWest) expectContextIsUpdated() }) }) }) }
PHP
UTF-8
9,550
2.53125
3
[]
no_license
<!DOCTYPE html> <html> <head> <title>Profile Page</title> <meta charset="UTF-8"> <?php include 'header.php' ?> </head> <body> <?php include 'config.php'; include 'db_connect.php'; include 'navbar.php'; ?> <?php function generateRandomString($length = 10) { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; } if(isset($_POST['submit'])){ $target_dir = "uploads/"; $target_file = $target_dir . basename($_FILES["file"]["name"]); $imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) { echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed."; $uploadOk = 0; } else { $pic_name = generateRandomString(); move_uploaded_file($_FILES['file']['tmp_name'],"uploads/".$pic_name); $query = "update users set grav_override = 1 where user_name = '".$_SESSION['username']."'"; mysqli_query($link, $query); $query = "update users set pic_name = '".$pic_name."' where user_name = '".$_SESSION['username']."'"; mysqli_query($link, $query); } } if(isset($_POST['del_prof'])){ $query = "select * from users where user_name = '".$_SESSION['username']."'"; $result = mysqli_query($link, $query); $row = mysqli_fetch_array($result); unlink("uploads/".$row['pic_name']); $query = "update users set grav_override = 0 where user_name = '".$_SESSION['username']."'"; mysqli_query($link, $query); } ?> <div class="container"> <div class="row"> <div class ='col-md-4'> <?php $query = "select * from users where user_name = '".$_GET['uname']."'"; $result = mysqli_query($link, $query); $row = mysqli_fetch_array($result); if($row['git_user'] == 0) { if($row['grav_override'] == 1) { ?> <img width='100' height='100' src='./uploads/<?php echo $row['pic_name']; ?>' alt='No Image Available' onerror= 'this.src="./uploads/defaultIcon.png";' /> <?php } else { $gravcheck = "http://www.gravatar.com/avatar/".md5( strtolower( trim( $row['email'] ) ) )."?d=404"; $response = get_headers($gravcheck); if ($response[0] != "HTTP/1.1 404 Not Found"){ ?> <img src="https://www.gravatar.com/avatar/<?php echo md5( strtolower( trim( $row['email'] ) ) ); ?>" /> <?php } else { ?> <img width='100' height='100' src='./uploads/<?php echo $row['pic_name']; ?>' alt='No Image Available' onerror= 'this.src="./uploads/defaultIcon.png";' /> <?php } } } else{ ?> <img width='100' height='100' src='https://github.com/<?php echo $row['user_name'].".png"; ?>' alt='No Image Available' /> <?php } ?> <br><br> <?php if (isset($_SESSION['username'])) { if($_SESSION['username'] == $_GET['uname'] && $_SESSION['gitvar'] == 0) {?> <form method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" name="submit"> <button type="delete" name="del_prof">Delete Picture</button> </form> <?php } } ?> </div> <div class ='col-md-8 prof_details'>Username - <?php echo $_GET['uname']; ?> <br><br> <?php $query = "SELECT sum(votes) from questions where qnd_user = '".mysqli_real_escape_string($link, $_GET['uname'])."'"; $result = mysqli_query($link, $query); $row = mysqli_fetch_array($result); ?> <span>Score : <?php echo $row[0] ?> </span> </div> </div> </div> <br> <div class="container"> <h3>My Questions</h3> <hr> <br><br> <?php $query = "SELECT * from questions where qnd_user = '".mysqli_real_escape_string($link, $_GET['uname'])."'"; if($result = mysqli_query($link, $query)) { while($row = mysqli_fetch_array($result)) { $query_answers = "SELECT count(*) from answers where qid = '".$row['qid']."'"; $result_answers = mysqli_query($link, $query_answers); $row_answers = mysqli_fetch_array($result_answers); ?> <div class='row'> <div class ='col-md-1'> <span style="background-color: #4682B4; color:white; text-align: center; border-radius: 3px; box-shadow: 0 0 6px #ccc;">Views</span><br> <span style="position:relative; left:10px;"> <?php echo $row['views']; ?></span> </div> <div class ='col-md-1'> <span style="background-color: #4682B4; color:white; text-align: center; border-radius: 3px; box-shadow: 0 0 6px #ccc;">Votes</span><br> <span style="position:relative; left:10px;"> <?php echo $row['votes']; ?></span> </div> <div class ='col-md-1'> <span style="background-color: #4682B4; color:white; text-align: center; border-radius: 3px; box-shadow: 0 0 6px #ccc;">Answers</span><br> <span style="position:relative; left:10px;"> <?php echo $row_answers[0]; ?></span> </div> <a href="display_question.php?qid=<?php echo $row['qid']; ?> " data-rel="tooltip" data-html="true" title = "" onmouseover="answer_tooltip(this.id)" class = "question_hyperlink col-md-9 red-tooltip" id = "<?php echo $row['qid']; ?>" > <?php echo htmlentities($row['question_title']); ?></a> </div> <br><br> <div class="row"> <div class='col-sm-3'></div> <div class='col-sm-5'>Tags : <?php $pieces = explode(" ", $row['tags']); foreach($pieces as $v){ ?> <a href='tags.php?tag=<?php echo $v ?>'> <?php echo $v." "; ?> </a> <?php } ?></div> <div class="col-sm-4"><span class="asked_by"><i class="fa fa-user" aria-hidden="true"></i> asked by </span><a href=""> <?php echo $row['qnd_user']; ?></a></div> </div> <div class="row"> <div class="col-sm-4 col-sm-offset-8 asked_by"><span class="asked_by"><i class="fa fa-clock-o" aria-hidden="true"></i> on </span> <?php echo $row['q_created']; ?> </div> </div> <hr> <?php } } ?> </div> <script> $(document).ready(function() { $('a[data-rel=tooltip]').tooltip(); }); function answer_tooltip(qid) { $.post('./answer_tooltip.php', {"qid": qid}, function(response){ $("#"+qid).attr('data-original-title', response); console.log(response) }) } </script> <div class="footer"></div> </body> </html>
Java
UTF-8
4,744
3.5
4
[]
no_license
package com.company; import java.util.ArrayList; /** * Created by mh6900 on 2/20/2019. */ public class Students { //Properties: private ArrayList<Assignments> Assignments;//Assignments (List) //create Assignments class private String firstName;//firstName (String) private String lastName;//lastName (String) private String username;//username (String) private long phoneNumber;//phoneNumber (long) private int daysAbsent;//daysAbsent (int) private int daysTardy;//daysTardy (int) //Constructors: public Students(String firstName, String lastName, String username, long phoneNumber) { this.firstName = firstName;//set firstName this.lastName = lastName;//set lastName this.username = username;//set username this.phoneNumber = phoneNumber;//set phoneNumber daysAbsent = 0;//set daysAbsent as 0 daysTardy = 0;//set daysTardy as 0 Assignments = new ArrayList<>();//create space for assignments to be added to } //Methods: //add assignment to student: public boolean addAssignmentToStudent(String assignmentName, int pointsPossible) { int assignmentIndex = getAssignmentIndexByAssignmentName(assignmentName); if (assignmentIndex != -1) {//if assignment exists... return false;//return false } else {//else... return Assignments.add(new Assignments(assignmentName, pointsPossible));//create new assignment and add to assignments list } } //set score: public int setScore(String assignmentName, int pointsEarned) { int assignmentIndex = getAssignmentIndexByAssignmentName(assignmentName); if (assignmentIndex != -1) {//if assignment exists... Assignments currAssignment = Assignments.get(assignmentIndex); return currAssignment.setScore(currAssignment, pointsEarned);//sets the score for the specified assignment } else {//else... return -2;//return -2 if false } } //mark tardy: public void markTardy() { daysTardy++;//marks a student tardy } //mark absent: public void markAbsent() { daysAbsent++;//marks a student absent } //get overall score: public double getOverallScore(Students currStudent) { double overallScore = 0; int assignmentIndex = 0; if (Assignments.size() == 0) { overallScore = 100; return overallScore; } else if (Assignments.size() == 1) { Assignments currAssignment = currStudent.Assignments.get(0); overallScore = (currAssignment.getAssignmentScorePercent(currAssignment)); return overallScore;//return overallScore } while (assignmentIndex < currStudent.Assignments.size()) { Assignments currAssignment = currStudent.Assignments.get(assignmentIndex); double currAssignmentPercent = currAssignment.getAssignmentScorePercent(currAssignment); overallScore = overallScore + currAssignmentPercent; assignmentIndex++; } overallScore = (overallScore / Assignments.size()); return overallScore;//return overallScore } //get assignment score: public double getAssignmentScorePercent(String assignmentName) { if (Assignments.size() == 0){ return -5;//return -5 if false } int assignmentIndex = getAssignmentIndexByAssignmentName(assignmentName); if (assignmentIndex != -1) {//if assignment exists... Assignments currAssignment = Assignments.get(assignmentIndex); return currAssignment.getAssignmentScorePercent(currAssignment);//sets the score for the specified assignment } else {//else... return -2;//return -2 if false } } //get tardy count: public int getDaysTardy() { return daysTardy;//gets a student's tardy count } //get absent count: public int getDaysAbsent() { return daysAbsent;//gets a student's absent count } //other methods: private int getAssignmentIndexByAssignmentName(String assignmentName) {//search if given assignmentName is used already int index = 0; while (index < Assignments.size()) { if (assignmentName.equalsIgnoreCase(Assignments.get(index).getAssignmentName())) {//if a assignment is found with the given assignmentName... return index;//return the found index } index++; } //if no assignment found with the given assignmentName... return -1;//return -1 if false } public String getUsername() { return username;//return username } }
C++
UTF-8
4,153
2.6875
3
[]
no_license
/* Copyright Kangaroo Magic 2011 Created Jonathan Jones Name RobotBuildingPuzzle.hpp Brief Includes all the objects that make up the robot building puzzle */ #ifndef ROBOT_BUILDING_PUZZLE_HPP #define ROBOT_BUILDING_PUZZLE_HPP // Includes #include <Vector> #include "Puzzle.hpp" // Forward decelarations class BuildPiece; class BuildPieceSilhouette; /* Name RobotBuildingPuzzle Brief Includes all the objects that make up the robot building puzzle */ class RobotBuildingPuzzle : public Puzzle // Inherits from puzzle { public: RobotBuildingPuzzle(); ~RobotBuildingPuzzle(); void initialise(); // Initialise objects in puzzle void deinitialise(); // Deinitialise objects in the puzzle void update(); // Update all the objects of the puzzle void touchUpdate(int touchX, int touchY); // Update that handles touch events void render(); // Renders all the robot parts bool movingABuildPiece(); // Returns true if buildPiece is being moved void noTouchEventsActive(); // Resets variables when no touch events are active void movePuzzle(int deltaX); // Move all parts of the puzzle by delta X int16 getCenterX(); // Return the centre X coord of a silhouette piece private: std::vector<BuildPiece*> robotParts_; // A vector which stores all the componenets that make up the robot std::vector<BuildPieceSilhouette*> robotSilhouette_; // A vector which stores all the robot parts silhouettes bool movingABuildPiece_; // Bool which describes if the player is moving a robot part BuildPiece* buildPieceBeingMoved_; // Pointer to build piece being moved const int START_X; const int ROBOT_HEAD_WIDTH; const int ROBOT_HEAD_HEIGHT; const int ROBOT_HEAD_X; const int ROBOT_HEAD_Y; const int ROBOT_HEAD_SILHOUETTE_WIDTH; const int ROBOT_HEAD_SILHOUETTE_HEIGHT; const int ROBOT_HEAD_SILHOUETTE_X; const int ROBOT_HEAD_SILHOUETTE_Y; const int ROBOT_TORSO_WIDTH; const int ROBOT_TORSO_HEIGHT; const int ROBOT_TORSO_X; const int ROBOT_TORSO_Y; const int ROBOT_TORSO_SILHOUETTE_WIDTH; const int ROBOT_TORSO_SILHOUETTE_HEIGHT; const int ROBOT_TORSO_SILHOUETTE_X; const int ROBOT_TORSO_SILHOUETTE_Y; const int ROBOT_LEGS_WIDTH; const int ROBOT_LEGS_HEIGHT; const int ROBOT_LEGS_X; const int ROBOT_LEGS_Y; const int ROBOT_LEGS_SILHOUETTE_WIDTH; const int ROBOT_LEGS_SILHOUETTE_HEIGHT; const int ROBOT_LEGS_SILHOUETTE_X; const int ROBOT_LEGS_SILHOUETTE_Y; const int ROBOT_POWER_CELL_WIDTH; const int ROBOT_POWER_CELL_HEIGHT; const int ROBOT_POWER_CELL_X; const int ROBOT_POWER_CELL_Y; const int ROBOT_POWER_CELL_SILHOUETTE_WIDTH; const int ROBOT_POWER_CELL_SILHOUETTE_HEIGHT; const int ROBOT_POWER_CELL_SILHOUETTE_X; const int ROBOT_POWER_CELL_SILHOUETTE_Y; const int ROBOT_LEFT_UPPER_ARM_WIDTH; const int ROBOT_LEFT_UPPER_ARM_HEIGHT; const int ROBOT_LEFT_UPPER_ARM_X; const int ROBOT_LEFT_UPPER_ARM_Y; const int ROBOT_LEFT_UPPER_ARM_SILHOUETTE_WIDTH; const int ROBOT_LEFT_UPPER_ARM_SILHOUETTE_HEIGHT; const int ROBOT_LEFT_UPPER_ARM_SILHOUETTE_X; const int ROBOT_LEFT_UPPER_ARM_SILHOUETTE_Y; const int ROBOT_RIGHT_UPPER_ARM_WIDTH; const int ROBOT_RIGHT_UPPER_ARM_HEIGHT; const int ROBOT_RIGHT_UPPER_ARM_X; const int ROBOT_RIGHT_UPPER_ARM_Y; const int ROBOT_RIGHT_UPPER_ARM_SILHOUETTE_WIDTH; const int ROBOT_RIGHT_UPPER_ARM_SILHOUETTE_HEIGHT; const int ROBOT_RIGHT_UPPER_ARM_SILHOUETTE_X; const int ROBOT_RIGHT_UPPER_ARM_SILHOUETTE_Y; const int ROBOT_LEFT_LOWER_ARM_WIDTH; const int ROBOT_LEFT_LOWER_ARM_HEIGHT; const int ROBOT_LEFT_LOWER_ARM_X; const int ROBOT_LEFT_LOWER_ARM_Y; const int ROBOT_LEFT_LOWER_ARM_SILHOUETTE_WIDTH; const int ROBOT_LEFT_LOWER_ARM_SILHOUETTE_HEIGHT; const int ROBOT_LEFT_LOWER_ARM_SILHOUETTE_X; const int ROBOT_LEFT_LOWER_ARM_SILHOUETTE_Y; const int ROBOT_RIGHT_LOWER_ARM_WIDTH; const int ROBOT_RIGHT_LOWER_ARM_HEIGHT; const int ROBOT_RIGHT_LOWER_ARM_X; const int ROBOT_RIGHT_LOWER_ARM_Y; const int ROBOT_RIGHT_LOWER_ARM_SILHOUETTE_WIDTH; const int ROBOT_RIGHT_LOWER_ARM_SILHOUETTE_HEIGHT; const int ROBOT_RIGHT_LOWER_ARM_SILHOUETTE_X; const int ROBOT_RIGHT_LOWER_ARM_SILHOUETTE_Y; }; #endif
Markdown
UTF-8
641
2.703125
3
[]
no_license
--- title: "Testing Hugo Markup" date: 2023-05-15T23:58:09-07:00 draft: false --- It's a particle! In a box! <canvas id="particlecanvas" width="300" height="100"></canvas> <script> const c = document.getElementById("particlecanvas"); const ctx = c.getContext("2d") let pos = 0; let v = 1; function step() { ctx.clearRect(0,0,300,100); ctx.strokeRect(0,0,300,100); ctx.fillRect(0+pos, 40, 10, 10); if (pos >= 290) { v *= -1; } if (pos <= 0 && v < 0) { v *= -1; } pos += v; } window.setInterval(step, 10); </script> Just testing out how to include little javascript snippets in Hugo markdown.
Python
UTF-8
5,119
2.53125
3
[]
no_license
from numpy import exp, median from scipy.sparse.csgraph import laplacian from sklearn.manifold.locally_linear import ( null_space, LocallyLinearEmbedding) from sklearn.metrics.pairwise import pairwise_distances, rbf_kernel from sklearn.neighbors import kneighbors_graph, NearestNeighbors from mpl_toolkits.mplot3d import Axes3D from optparse import OptionParser from sklearn.datasets import make_swiss_roll from sklearn.manifold import SpectralEmbedding import matplotlib.pyplot as plt def ler(X, Y, n_components=2, affinity='nearest_neighbors', n_neighbors=None, gamma=None, mu=1.0, y_gamma=None, eigen_solver='auto', tol=1e-6, max_iter=100, random_state=None): if eigen_solver not in ('auto', 'arpack', 'dense'): raise ValueError("unrecognized eigen_solver '%s'" % eigen_solver) nbrs = NearestNeighbors(n_neighbors=n_neighbors + 1) nbrs.fit(X) X = nbrs._fit_X Nx, d_in = X.shape Ny = Y.shape[0] if n_components > d_in: raise ValueError("output dimension must be less than or equal " "to input dimension") if Nx != Ny: raise ValueError("X and Y must have same number of points") if affinity == 'nearest_neighbors': if n_neighbors >= Nx: raise ValueError("n_neighbors must be less than number of points") if n_neighbors == None or n_neighbors <= 0: raise ValueError("n_neighbors must be positive") elif affinity == 'rbf': if gamma != None and gamma <= 0: raise ValueError("n_neighbors must be positive") else: raise ValueError("affinity must be 'nearest_neighbors' or 'rbf' must be positive") if Y.ndim == 1: Y = Y[:, None] if y_gamma is None: dists = pairwise_distances(Y) y_gamma = 1.0 / median(dists) if affinity == 'nearest_neighbors': affinity = kneighbors_graph(X, n_neighbors, include_self=True) else: if gamma == None: dists = pairwise_distances(X) gamma = 1.0 / median(dists) affinity = kneighbors_graph(X, n_neighbors, mode='distance', include_self=True) affinity.data = exp(-gamma * affinity.data ** 2) K = rbf_kernel(Y, gamma=y_gamma) lap = laplacian(affinity, normed=True) lapK = laplacian(K, normed=True) embedding, _ = null_space(lap + mu * lapK, n_components, k_skip=1, eigen_solver=eigen_solver, tol=tol, max_iter=max_iter, random_state=random_state) return embedding class LER(LocallyLinearEmbedding): def __init__(self, n_components=2, affinity='nearest_neighbors', n_neighbors=2, gamma=None, mu=1.0, y_gamma=None, eigen_solver='auto', tol=1E-6, max_iter=100, random_state=None, neighbors_algorithm='auto'): self.n_components = n_components self.affinity = affinity self.n_neighbors = n_neighbors self.gamma = gamma self.mu = mu self.y_gamma = y_gamma self.eigen_solver = eigen_solver self.tol = tol self.max_iter = max_iter self.random_state = random_state self.neighbors_algorithm = neighbors_algorithm def fit_transform(self, X, Y): self.fit(X, Y) return self.embedding_ def fit(self, X, Y): self.nbrs_ = NearestNeighbors(self.n_neighbors, algorithm=self.neighbors_algorithm) self.nbrs_.fit(X) self.embedding_ = ler( X, Y, n_components=self.n_components, affinity=self.affinity, n_neighbors=self.n_neighbors, gamma=self.gamma, mu=self.mu, y_gamma=self.y_gamma, eigen_solver=self.eigen_solver, tol=self.tol, max_iter=self.max_iter, random_state=self.random_state) return self def demo(k): X, t = make_swiss_roll(noise=1) #le = SpectralEmbedding(n_components=2, n_neighbors=k) #le_X = le.fit_transform(X) ler = LER(n_components=2, n_neighbors=k, affinity='rbf') ler_X = ler.fit_transform(X, t) """ _, axes = plt.subplots(nrows=1, ncols=3, figsize=plt.figaspect(0.33)) axes[0].set_axis_off() axes[0] = plt.subplot(131, projection='3d') axes[0].scatter(*X.T, c=t, s=50) axes[0].set_title('Swiss Roll') axes[1].scatter(*le_X.T, c=t, s=50) axes[1].set_title('LE Embedding') axes[2].scatter(*ler_X.T, c=t, s=50) axes[2].set_title('LER Embedding') plt.show() """ _, axes = plt.subplots(nrows=1, ncols=2, figsize=plt.figaspect(0.33)) axes[0].set_axis_off() axes[0] = plt.subplot(131, projection='3d') axes[0].scatter(*X.T, c=t, s=50) axes[0].set_title('Swiss Roll') axes[1].scatter(*ler_X.T, c=t, s=50) axes[1].set_title('LER Embedding') plt.show() if __name__ == "__main__": op = OptionParser() op.add_option('--n_neighbors', type=int, metavar='k', default=10, help='# of neighbors for LE & LER [7]') opts, args = op.parse_args() demo(opts.n_neighbors)
Java
UTF-8
913
3.265625
3
[]
no_license
package com.lfw.io.base; import java.io.*; /** * @email fuwei.liu@dmall.com * @author: fuwei.iu * @date: 2021/4/25 下午10:36 * @description: 写入字符流信息 */ public class WriterDemo { /** * 字节流(inputStream/outputStream)与字符流(reader/writer)的区别: * 字符流可以直接处理中文,但是字符流处理中文会出现乱码 * * @param args */ public static void main(String[] args) { Writer writer = null; try { writer = new FileWriter("writerForTest.text"); writer.write("123"); writer.write("中文才是他的优势"); writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } }
Go
UTF-8
1,642
2.703125
3
[]
no_license
package structs_test import ( "testing" "github.com/andrievsky/daretogo/structs" "github.com/stretchr/testify/assert" ) func TestHashSetInit(t *testing.T) { var set = structs.NewHashSet(10) assert.Equal(t, false, set.Contains(1)) assert.Equal(t, 0, set.Count()) } func TestHashSet(t *testing.T) { var set = structs.NewHashSet(10) assert.Equal(t, true, set.Add(1)) assert.Equal(t, true, set.Contains(1)) assert.Equal(t, 1, set.Count()) assert.Equal(t, false, set.Add(1)) assert.Equal(t, true, set.Contains(1)) assert.Equal(t, 1, set.Count()) } func TestGenericHashSet(t *testing.T) { var set = structs.NewGenericHashSet() assert.Equal(t, true, set.Add(1)) assert.Equal(t, true, set.Contains(1)) assert.Equal(t, 1, set.Count()) assert.Equal(t, false, set.Add(1)) assert.Equal(t, true, set.Contains(1)) assert.Equal(t, 1, set.Count()) } func TestGreedyHashSet(t *testing.T) { var set = structs.NewGreedyHashSet(10) assert.Equal(t, true, set.Add(1)) assert.Equal(t, true, set.Contains(1)) assert.Equal(t, 1, set.Count()) assert.Equal(t, false, set.Add(1)) assert.Equal(t, true, set.Contains(1)) assert.Equal(t, 1, set.Count()) } func BenchmarkHashSet(b *testing.B) { var set = structs.NewHashSet(b.N) for n := 0; n < b.N; n++ { set.Add(n) set.Contains(n) set.Count() } } func BenchmarkGenericHashSet(b *testing.B) { var set = structs.NewGenericHashSet() for n := 0; n < b.N; n++ { set.Add(n) set.Contains(n) set.Count() } } func BenchmarkGreedyHashSet(b *testing.B) { var set = structs.NewGreedyHashSet(b.N) for n := 0; n < b.N; n++ { set.Add(n) set.Contains(n) set.Count() } }
Markdown
UTF-8
4,754
2.59375
3
[]
no_license
--- title: 搭建WordPress个人站点 date: 2017/12/10 12:00:00 tags: - WordPress - 个人博客 - MySQL categories: 搭建博客 --- > WordPress 是一款常用的搭建个人博客网站软件,使用 PHP 语言和 MySQL 数据库开发。 ## 说在前面 近期我的女神希望建立自己的个人博客,明确表示不喜欢平时我写博客的方式——目前我使用hexo+github的方式。她希望有一种创建博客的感觉,能够所见即所得,而且不喜欢用markdown语法,就目前而言,我能想到的只有WordPress,恰好最近在腾讯云上买了一台服务器,于是立即着手。<br> 在构建WordPressd的时候,想起之前在腾讯云上买服务器的时候,看到类似的教程,于是搜索到了对应的[教程](https://cloud.tencent.com/document/product/213/8044),安装的时候也都是参照此文档。 <!-- more --> ## 创建并运行云服务器 服务器之前已经买过,连接服务器我还是更喜欢用XShell,大家看喜好。 ## 搭建 LNMP 环境 ### 使用 Yum 安装必要软件 #### 安装基础部分 ``` yum install php php-fpm php-mysql mysql-server -y ``` 注意: - nginx之前使用源码包已经安装过,在此不再重新安装。 但是安装完成之后,发现已安装的列表中,不包括mysql,这让我很是费解。在查看这个[链接](https://cloud.tencent.com/document/product/213/2046)的时候,发现如下这段话: ``` 从 CentOS 7 系统开始,MariaDB 成为 yum 源中默认的数据库安装包。在 CentOS 7 及以上的系统中使用 yum 安装 MySQL 包将无法使用 MySQL。您可以选择使用完全兼容的 MariaDB,或点击 参阅此处 进行较低版本的 MySQL 的安装。 ``` #### 安装MySQL(我的服务器是CentOS 7.2) 根据这个[链接](https://www.linode.com/docs/databases/mysql/how-to-install-mysql-on-centos-7/)进行安装。安装花费了很长时间,很多源码包下载的速度从几KB降到几B,重复换源下载,这个过程浪费了很多时间。 ### 软件配置 #### 配置Nginx 按照我的习惯,我在conf/vhost目录下,建立了对应的配置文件**xx.conf**,然后重启nginx #### 配置MySQL - 启动msyql ``` service mysqld start ``` - 设置密码 ``` /usr/bin/mysqladmin -u root password "123456" ``` #### 配置 PHP - 启动 PHP-FPM 服务 ``` service php-fpm start ``` - 配置 PHP Session 的存储路径 ``` vi /etc/php.ini 修改 session.save_path = "/var/lib/php/session" ``` #### 验证环境配置 在nginx配置的目录中,使用**index.php**验证,确认是否配置成功。 ## 安装和配置 WordPress ### 下载 WordPress - 先删除nginx配置目录中的**index.php** ### 依次下载 WordPress 并解压到当前目录 我使用的是**/usr/local/src**目录: ``` wget https://cn.wordpress.org/wordpress-4.7.4-zh_CN.tar.gz tar zxvf wordpress-4.7.4-zh_CN.tar.gz ``` ### 配置数据库 - 登录 MySQL 服务器 ``` mysql -u root -p ``` 输入之前设置的密码 - 为 WordPress 创建数据库并设置用户名和密码(可自定义) ``` CREATE DATABASE wordpress; CREATE USER user@localhost; SET PASSWORD FOR user@localhost=PASSWORD("wordpresspassword"); ``` - 为创建的用户开通数据库 “wordpress” 的完全访问权限 ``` GRANT ALL PRIVILEGES ON wordpress.* TO user@localhost IDENTIFIED BY 'wordpresspassword'; ``` - 使所有配置生效 ``` FLUSH PRIVILEGES; ``` - 退出MySQL ### 写入数据库信息 - 创建新配置文件 将wp-config-sample.php文件复制到名为wp-config.php的文件 ``` cd wordpress/ cp wp-config-sample.php wp-config.php ``` - 编辑新创建的配置文件 ``` vi wp-config.php ``` 配置如下: ``` // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', 'wordpress'); /** MySQL database username */ define('DB_USER', 'user'); /** MySQL database password */ define('DB_PASSWORD', 'wordpresspassword'); ``` ### 安装 WordPress - 移至nginx配置的目录 ``` mv * /xjm/run/wordpress/ ``` 访问即可,这个时候填入基本信息,点击**安装WordPress**,这个速度应该是很快的。 ## 其它 ### Navicat访问数据库 这个时候通过navicat访问数据库是无法访问的,我们在创建user时,是否还记得@后面的localhost,它表示只能在这台服务器进行登录。 ``` mysql -u root -p use mysql; update user set host = '%' where user = 'user'; ``` 再使用Navicat试试 ### Https 可以在腾讯云申请一个证书,按照文档进行配置即可。 ![](https://img.ryoma.top/WordPress/stella.blog.png) ### 自定义配置 如果不满足WordPress默认的内容,可以通过后台修改,或者直接修改源代码
Swift
UTF-8
3,946
3.0625
3
[ "AFL-3.0" ]
permissive
@testable import DiceKit import XCTest final class ChanceTests: XCTestCase { func testInitialization() { XCTAssertNil(try? Chance.oneOut(of: 0)) XCTAssertNotNil(try? Chance.oneOut(of: 1)) XCTAssertNil(try? Chance.oneOut(of: -1)) XCTAssertNotNil(try? Chance.oneOut(of: 5)) XCTAssertNil(try? Chance.oneOut(of: -5)) XCTAssertNil(try? Chance(oneOutOf: 0)) XCTAssertNotNil(try? Chance(oneOutOf: 1)) XCTAssertNil(try? Chance(oneOutOf: -1)) XCTAssertNotNil(try? Chance(oneOutOf: 5)) XCTAssertNil(try? Chance(oneOutOf: -5)) XCTAssertNotNil(try? Chance(1, outOf: 1)) XCTAssertNil(try? Chance(2, outOf: 1)) XCTAssertNotNil(try? Chance(1, outOf: 2)) XCTAssertNotNil(try? Chance(0, outOf: 1)) XCTAssertNil(try? Chance(1, outOf: 0)) XCTAssertNotNil(try? Chance(2, outOf: 3)) XCTAssertNil(try? Chance(3, outOf: 2)) XCTAssertNil(try? Chance(-1, outOf: 2)) XCTAssertNil(try? Chance(-2, outOf: 1)) XCTAssertNotNil(try? Chance(6, outOf: 6)) XCTAssertNotNil(try? Chance(0, outOf: 6)) XCTAssertNil(try? Chance(6, outOf: 0)) XCTAssertNotNil(try? Chance(approximating: 0)) XCTAssertNotNil(try? Chance(approximating: 1)) XCTAssertNil(try? Chance(approximating: 2)) XCTAssertNil(try? Chance(approximating: -1)) XCTAssertNil(try? Chance(approximating: Double.pi / 3)) XCTAssertNotNil(try? Chance(approximating: Double.pi / 4)) XCTAssertNotNil(try? Chance(approximating: 0.5)) XCTAssertNil(try? Chance(approximating: 1.5)) XCTAssertNotNil(try? Chance(approximating: 0.000_000_234)) } func testDoubleApproximation() { let c: Chance = 0.25 XCTAssertTrue(c.fraction == (1, 4)) let c2 = try! Chance(approximating: 1.0 / 3.0) XCTAssertTrue(c2.fraction == (1, 3)) // XCTAssertEqual(c.fraction, (1, 4)) This doesn't work because tuples can't conform to Equatable directly } func testProperties() { let c = try! Chance(1, outOf: 4) XCTAssertTrue((1, 4) == c.fraction) XCTAssertEqual(c.n, 1) XCTAssertEqual(c.d, 4) XCTAssertTrue((c.n, c.d) == c.fraction) } func testEquatable() { let c = try! Chance(oneOutOf: 10) let c2 = try! Chance(1, outOf: 10) let c3 = try! Chance(approximating: 0.1) let c4: Chance = 0.1 let c5 = try! Chance(2, outOf: 20) XCTAssertAllEqual(c, c2, c3, c4, c5) } func testAddition() { let oneSixth = try! Chance(1, outOf: 6) let oneThird = try! Chance(1, outOf: 3) let oneHalf = try! Chance(1, outOf: 2) XCTAssertEqual(oneSixth + oneThird, oneHalf) for c in [oneSixth, oneThird, oneHalf, try! .init(approximating: 0.5432), try! .init(3, outOf: 76)] { XCTAssertEqual(c, c + .zero) XCTAssertEqual(c, .zero + c) } } func testSubtraction() { let oneSixth = try! Chance(1, outOf: 6) let oneThird = try! Chance(1, outOf: 3) let oneHalf = try! Chance(1, outOf: 2) XCTAssertEqual(oneHalf - oneSixth, oneThird) for c in [oneSixth, oneThird, oneHalf, try! .init(approximating: 0.5432), try! .init(3, outOf: 76)] { XCTAssertEqual(c, c - .zero) } } func testMultiplication() { let oneSixth = try! Chance(1, outOf: 6) let oneThird = try! Chance(1, outOf: 3) let oneHalf = try! Chance(1, outOf: 2) XCTAssertEqual(oneHalf * oneThird, oneSixth) for c in [oneSixth, oneThird, oneHalf, try! .init(approximating: 0.5432), try! .init(3, outOf: 76)] { XCTAssertEqual(c, c * .one) XCTAssertEqual(c, .one * c) XCTAssertEqual(Chance.zero, c * .zero) XCTAssertEqual(Chance.zero, .zero * c) } } }
PHP
UTF-8
2,001
2.515625
3
[ "MIT", "BSD-3-Clause" ]
permissive
<?php namespace MissionBundle\Service; class Mission { protected $em; public function __construct(\Doctrine\ORM\EntityManager $em) { $this->em = $em; } public function organiseMissions($listMissionsAvailable, $listCurrentMissions) { foreach ($listMissionsAvailable as $mission) { foreach ($listCurrentMissions as $currentMission) { if ($mission->getId() == $currentMission->getId()) { unset($listMissionsAvailable[array_search($mission, $listMissionsAvailable)]); } } } return ($listMissionsAvailable); } public function sendDeleteMessageInView($request, $i, $j, $step, $translator) { if ($i > $step->getNbMaxUser() || $i == 0) { $request->getSession() ->getFlashBag() ->add('success', $translator->trans('mission.selection.minimum', array( '%limit%' => $step->getNbMaxUser()), 'MissionBundle' )); } elseif ($i > $step->getReallocUser())// If you want to delete more than you can { $request->getSession() ->getFlashBag() ->add('success', $translator->trans('mission.selection.limit', array("%limit%" => $step->getReallocUser()), 'MissionBundle')); } elseif ($j - $i <= 0)// If after the deletion there is no user left { $request->getSession() ->getFlashBag() ->add('success', $translator->trans('mission.selection.delete', array(), 'MissionBundle')); } elseif ($step->getReallocUser() == 0) // If you deleted the maximum of user that you can { $request->getSession() ->getFlashBag() ->add('success', $translator->trans('mission.selection.counter', array(), 'MissionBundle')); } } }
C++
ISO-8859-1
11,204
2.875
3
[]
no_license
#pragma once #include <vector> #include <time.h> #include <windows.h> #include <gl\gl.h> #include <gl\glu.h> #include <math.h> #include <stdlib.h> #include "Model.h" #include "Constant.h" #include "Vertex.h" class Asteroid { private: /*MEMBERS*/ //Variabile che fa da moltiplicatore per la velocit //di movimento dell'asteroide: andremo ad aumentarla //con il passare del tempo di gioco. float difficulty; //Velocit, intese in termini vettoriali, dell'asteroide //lungo i due assi. ///TO SEE PROBLEMA: se consideriamo il nostro spazio come /// nel disegno che ho messo in Data allora le velocit /// lungo x e y rispettivamente saranno e potranno essere /// negative. Dici che va bene? //ANSWER si lungo y positive e negstive mentre lungo x direi solo negative float speedX; float speedY; //Dimensioni dell'asteroide float length; float width; //Centro dell'asteroide nel nostro spazio Vertex center; //Lista di vertici che costituiscono la nostra //forma geometrica sottostante l'asteroide. std::vector<Vertex> shape; //Variabile che memorizza il tempo a cui il //Aanswer per cosa la vuoi usare io forse la terrei per far si che //l'esplosione sia visibile per qualche ciclo tipo 1 o 2 e poi eliminerei il tutto?? //che ne dici? int hittingTime; //Variabile che, qualora settata a true, indica //che l'oggetto non deve essere pi disegnato e //va eliminato quanto prima. ///TO SEE non so se lasciare che venga settata ///dall'interno della classe oppure dal modello. ///In particolare la setterei a true laddove si ///verifichi la condizione di outOfBoundaries. //Answer io come concordato con gratta non la userei perche distruggiamo togliendo direttamente dal array bool toDestroy; ///TO SEE: guarda queste due variabili, dobbiamo ///considerarle se vogliamo fare gli effetti di esplosione. //Variabile che, qualora settata a true, indica //che l'oggetto stato colpito e pertanto deve //essere disegnato in fase di esplosione. //Se tale variabile a true l'oggetto deve //smettere di muoversi (l'esplosione non si muove). bool hitten; //Variabile che contiene le nostre texture. ///TO SEE In teoria potrebbe servirci pi /// di una texture in modo da ciclare /// e rendere l'asteroide un po' pi /// bello, idem per l'esplosione. ///TO SEE a quanto ho visto le vere e proprie /// texture vengono memorizzate in model.h /// nella classe dell'oggetto memorizzi i /// riferimenti alle texture di model.h. // ANSWER penso sia una specifica da chiedere a grattarola domani int texture; int explosionTexture; public: /*METHODS*/ Asteroid(float x, float y, float z, float sX, float sY, float diff, float l, float w) { center = Vertex(x, y, z); difficulty = diff; //Computazione della velocit lungo le x: //Dal costruttore viene fornita la velocit di base lungo le x. //Ad essa si aggiunge una quantit randomica in uno span di valori //che varia al variare della difficulty. //La velocit cos ottenuta viene ulteriormente moltiplicata per la //difficulty. //Considerando come abbiamo definito il nostro spazio la velocit //lungo le x deve avere un valore negativo. speedX = difficulty * (sX + (rand() % int(AST_SPAN_SPEED_X * difficulty))) ; speedX = -speedX; //La velocit lungo y pu essere sia negativa che positiva: //dobbiamo randomizzare anche la scelta del segno. int sign; int auxRand = rand() % 2; if (auxRand) sign = 1; else sign = -1; speedY = sign * difficulty * (sY + (rand() % int(AST_SPAN_SPEED_Y * difficulty))); ///TO SEE Invece che il raggio ho messo length e width /// in modo da poter mettere asteroidi non quadrati. //ANSWER io direi che basta il raggio per il motivo che ti pecifico nell'audio numero 1 length = l; width = w; toDestroy = false; hitten = false; //Definiamo i vertici dell'asteroide utilizzando //larghezza e lunghezza shape.push_back(Vertex(x + length / 2, y + width / 2, z, 0, 0, 1, 1, 1)); shape.push_back(Vertex(x + length / 2, y - width / 2, z, 0, 0, 1, 1, 0)); shape.push_back(Vertex(x - length / 2, y - width / 2, z, 0, 0, 1, 0, 0)); shape.push_back(Vertex(x - length / 2, y + width / 2, z, 0, 0, 1, 0, 1)); //Scegliamo quale delle 4 texture usare randomicamente, //in modo da dare varianza all'aspetto degli asteroidi. texture = rand() % 4; explosionTexture = 0; } //Costruttore che genera un asteroide con dimensioni, posizione e velocit //randomiche. Asteroid(float diff) { difficulty = diff; length = AST_MIN_LENGTH + (rand() % (AST_MAX_LENGTH - AST_MIN_LENGTH)); width = AST_MIN_WIDTH + (rand() % (AST_MAX_WIDTH - AST_MIN_WIDTH)); float x, y, z; //Non randomizzo la posizione della coordinata x del centro in quanto //vogliamo che l'asteroide venga generato in fondo alla mappa fuori //dalla zona di visibilit. x = MAX_VIS_X - length / 2; //Il calcolo della coordinata y randomizzato in modo tale che l'asteroide //venga generato completamente all'interno della zona di visibilit della Y. y = (MIN_VIS_Y + width / 2) + (rand() % int(MAX_VIS_Y - MIN_VIS_Y - width)); z = AST_HEIGHT; center = Vertex(x, y, z); //Computazione della velocit lungo le x: //In questo caso non abbiamo una velocit di base fornita dall'esterno. => //=> Usiamo la velocit di base fornita come costante del modello. //Ad essa si aggiunge una quantit randomica in uno span di valori //che varia al variare della difficulty. //La velocit cos ottenuta viene ulteriormente moltiplicata per la //difficulty. //Considerando come abbiamo definito il nostro spazio la velocit //lungo le x deve avere un valore negativo. speedX = difficulty * (AST_BASE_SPEED_X + (rand() % int(AST_SPAN_SPEED_X * difficulty))); speedX = -speedX; //La velocit lungo y pu essere sia negativa che positiva: //dobbiamo randomizzare anche la scelta del segno. //Anche in questo caso usiamo la velocit base fornita come //costante al modello. int sign; int auxRand = rand() % 2; if (auxRand) sign = 1; else sign = -1; speedY = sign * difficulty * (AST_BASE_SPEED_Y + (rand() % int(AST_SPAN_SPEED_Y * difficulty))); toDestroy = false; hitten = false; //Definiamo i vertici dell'asteroide utilizzando //larghezza e lunghezza shape.push_back(Vertex(x + length / 2, y + width / 2, z, 0, 0, 1, 1, 1)); shape.push_back(Vertex(x + length / 2, y - width / 2, z, 0, 0, 1, 1, 0)); shape.push_back(Vertex(x - length / 2, y - width / 2, z, 0, 0, 1, 0, 0)); shape.push_back(Vertex(x - length / 2, y + width / 2, z, 0, 0, 1, 0, 1)); //Scegliamo quale delle 4 texture usare randomicamente, //in modo da dare varianza all'aspetto degli asteroidi. texture = rand() % 4; explosionTexture = 0; } //SET METHODS void setDifficulty(float difficulty) { this->difficulty = difficulty; } void setSpeedX(float speedX) { this->speedX = speedX; } void setSpeedY(float speedY) { this->speedY = speedY; } void setLength(float length) { this->length = length; } void setWidth(float width) { this->width = width; } void setCenter(Vertex center) { this->center = center; shape.clear(); shape.push_back(Vertex(center.getX() + length / 2, center.getY() + width / 2, center.getZ(), 0, 0, 1, 1, 1)); shape.push_back(Vertex(center.getX() + length / 2, center.getY() - width / 2, center.getZ(), 0, 0, 1, 1, 1)); shape.push_back(Vertex(center.getX() - length / 2, center.getY() - width / 2, center.getZ(), 0, 0, 1, 1, 1)); shape.push_back(Vertex(center.getX() - length / 2, center.getY() + width / 2, center.getZ(), 0, 0, 1, 1, 1)); } void setHitten(bool hitten) { this->hitten = hitten; } void setHittingTime(double hittingTime) { this->hittingTime = hittingTime; } void setToDestroy(bool toDestroy) { this->toDestroy = toDestroy; } void setTexture(int texture) { this->texture = texture; } void setExplosionTexture(int explosionTexture) { this->explosionTexture = explosionTexture; } //GET METHODS float getDifficulty() { return difficulty; } float getSpeedX() { return speedX; } float getSpeedY() { return speedY; } float getLength() { return length; } float getWidth() { return width; } Vertex getCenter() { return center; } std::vector<Vertex> getShape() { return shape; } bool getHitten() { return hitten; } double getHittingTime() { return hittingTime; } bool getToDestroy() { return toDestroy; } int getTexture() { return texture; } int getExplosionTexture() { return explosionTexture; } //Funzione per verificare se l'oggetto fuori dalla zona //di visibilit. ///TO SEE io personalmente non la userei per impedire all'oggetto /// di muoversi, pi che altro la userei per far scattare la /// "distruzione" dell'oggetto all'interno del modello. => /// => non consideriamo il movimento ma semplicemente la /// posizione (una volta che uscito possiamo anche bloccare /// il movimento. /// Secondo te la distruzione dell'oggetto va fatta a livello /// del modello o qui interna alla classe? Che non mi molto /// chiaro come possiamo fare. //ANSWER io con distruzione dell'asteroide semplicemente lo rimuoverei dalla lista di asteroidi del model.h bool outOfBoundaries() { //Bisogna aspettare che l'ultimo pezzo visibile di asteroide //sia uscito dalla zona di visibilit if (this->center.getX() - length / 2 > MAX_VIS_X) return true; else if (speedY < 0 && this->center.getY() + width / 2 < MIN_VIS_Y) return true; else if (speedY > 0 && this->center.getY() - width / 2 > MAX_VIS_Y) return true; else return false; } //Funzione che muove l'asteroide nello spazio bidimensionale. ///TO SEE Non sono sicuro che con il modo che utilizzi /// per modificare i vertici sia corretto: /// da quello che ho visto con quelle funizioni /// andresti a duplicare ogni volta i membri di shape. /// Io direi di spostare anche il centro, se non un /// problema concettuale. //ANSWER ci avevo pensato a spostare il centro anzi che i vertici, io spostavo entrambi se non ricordo male vedi audio2 bool move(double elapsed) { if (!this->outOfBoundaries()) { center.modifyP(speedX*elapsed, speedY*elapsed); for (int i = 0; i < shape.size(); i++) shape[i].modifyP(speedX*elapsed, speedY*elapsed); } return !this->outOfBoundaries(); } };
C#
UTF-8
896
2.875
3
[]
no_license
using System; using System.IO; using Data.Models; using Data.Repositories.Interfaces; using Newtonsoft.Json; namespace Data.Repositories { public class JsonRepository<T>: IRepository<T> { private readonly string _filePath; public JsonRepository() { _filePath = AppDomain.CurrentDomain.BaseDirectory; if (typeof(T) == typeof(LoanContract)) _filePath += @"/Resources/loanSettings.json"; else _filePath += @"/Resources/feeSettings.json"; } public T GetFirst() { return Read(); } public T Read() { return JsonConvert.DeserializeObject<T>(File.ReadAllText(_filePath)); } public void Write(T model) { File.WriteAllText(_filePath, JsonConvert.SerializeObject(model)); } } }
PHP
UTF-8
593
2.828125
3
[]
no_license
<?php namespace Bundle\DownloadBundle\Resources; /* * MORE TYPES: * http://www.iana.org/assignments/media-types/ * http://en.wikipedia.org/wiki/Internet_media_type * */ class MediaType { public static $mediaTypes = array( 'pdf' => 'application/pdf', 'mp3' => 'audio/mpeg', 'wav' => 'audio/vnd.wave', 'zip' => 'application/zip', ); static function getType($ext) { if (isset(self::$mediaTypes[$ext])) { return self::$mediaTypes[$ext]; } else { return 'application/octet-stream'; } } }
JavaScript
UTF-8
2,311
2.890625
3
[]
no_license
import fetchCountries from './fetchCountries.js'; import getRefs from './get-refs.js'; import { success, info, error } from './pnotify.js'; import singleRenderCountry from '../templates/singleCountryRender.hbs'; import multipleRenderCountry from '../templates/multipleCountryRender.hbs'; const _ = require('lodash'); const refs = getRefs(); refs.searchInput.value = ''; function fullRender(searchQuery) { if (searchQuery === '') { clearUl(); return; } fetchCountries(searchQuery) .then(data => data.filter(country => country.name .toLowerCase() .includes(refs.searchInput.value.toLowerCase()), ), ) .then(countriesArray => markupRender(countriesArray)) .catch(e => { // refs.searchInput.value = ''; clearUl(); error({ title: 'Sorry', text: e, }); }); } function clearUl() { if (refs.searchInput.value === '') { refs.cardContainer.innerHTML = ''; } } const debounced = _.debounce(() => { fullRender(refs.searchInput.value); }, 500); function markupRender(countriesArray) { if (countriesArray.length > 1 && countriesArray.length <= 10) { refs.cardContainer.innerHTML = ''; countriesArray.map(country => { multipleRender(country); }); success({ title: 'Success!', text: 'Look at the countries on your request', }); } else if (countriesArray.length === 1) { refs.cardContainer.innerHTML = ''; countriesArray.map(country => { singleRender(country); }); success({ title: 'Success!', text: 'Country info loaded', }); } else if (countriesArray.length > 10 || countriesArray.length === 0) { info({ text: 'Please enter a more specific query!', }); } } function multipleRender(country) { refs.cardContainer.insertAdjacentHTML( 'beforeend', multipleRenderCountry([...country]), ); } function singleRender(country) { refs.cardContainer.insertAdjacentHTML( 'beforeend', singleRenderCountry([...country]), ); } refs.searchInput.addEventListener('input', debounced); refs.searchContainer.addEventListener('submit', e => e.preventDefault());
Java
UTF-8
1,428
2.140625
2
[]
no_license
package com.hg.anDGS; import java.util.Locale; import android.app.Activity; import android.content.SharedPreferences; import android.content.res.Configuration; import android.content.res.Resources; import android.os.Bundle; public class DGSActivity extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SharedPreferences settings = getSharedPreferences("MainDGS", 0); Configuration config = getBaseContext().getResources().getConfiguration(); String defLanguage = Resources.getSystem().getConfiguration().locale.getLanguage(); String confLanguage = config.locale.getLanguage(); String myLanguage = settings.getString("com.hg.anDGS.Locale", ""); if (!confLanguage.contentEquals(myLanguage)) { if (myLanguage.contentEquals("")) { if (!defLanguage.startsWith(confLanguage)) { doit(config, defLanguage); } } else { doit(config, myLanguage); } } } private void doit(Configuration config, String myLanguage) { //Locale.setDefault(myLocale); config.locale = new Locale(myLanguage); //getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); getBaseContext().getResources().updateConfiguration(config, null); } }
C#
UTF-8
1,017
3.203125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace ByteBank.Modelos { class FileReader : IDisposable // Provides a mechanism for releasing unmanaged resources. { /*------------------------------ | Variables |-------------------------------- * */ public string Arquivo { get; } /*------------------------------ | MÉTODO CONSTRUTOR |-------------------------------- * * Realizar a leitura de um arquivo * */ public FileReader(string arquivo) { Arquivo = arquivo; } public string LerProximaLinha() { Console.WriteLine("Lendo linha..."); return "Linha do arquivo"; throw new IOException(); } public void Dispose() { Console.WriteLine("Fechando arquivo."); } } }
Python
UTF-8
4,457
2.828125
3
[ "BSD-2-Clause" ]
permissive
class KNNClassifier: def __init__(self, k=5, strategy='my_own', metric='euclidean', weights=False, test_block_size=1000): self.strategy = strategy self.weights = weights self.test_block_size = test_block_size self.metric = metric self.k = k if strategy != 'my_own': self.classifier = NearestNeighbors(k, algorithm=strategy, metric=metric) def fit(self, X, y): self.train_y = y if self.strategy == 'my_own': self.train_X = X else: self.classifier.fit(X, y) self.Nclass = np.unique(y) def euclid_dist(X, Y): return ((X ** 2).sum(axis=1)[:, np.newaxis] + (Y ** 2).sum(axis=1)[np.newaxis, :] - 2 * X.dot(Y.transpose())) ** (1 / 2) def cosine_dist(X, Y): return np.ones((X.shape[0], Y.shape[0])) - X.dot(Y.transpose()) / (((X ** 2).sum(axis=1)[:, np.newaxis] ** (1/2)) * ((Y ** 2).sum(axis=1)[np.newaxis, :] ** (1/2))) def find_kneighbors(self, X, return_distance=True): indexex = np.zeros((0, self.k)) distance = np.zeros((0, self.k)) tbl = self.test_block_size if self.strategy == 'my_own': if self.metric == 'euclidean': metric_func = KNNClassifier.euclid_dist else: metric_func = KNNClassifier.cosine_dist for i in range(X.shape[0] // tbl): P = metric_func(X[i * tbl:(i + 1) * tbl, :], self.train_X) ind = np.argpartition(P, range(self.k), axis=1)[:, 0:self.k] indexex = np.vstack((indexex, ind)) if return_distance is True: dist = np.partition(P, range(self.k), axis=1)[:, 0:self.k] distance = np.vstack((distance, dist)) P = metric_func(X[(X.shape[0] // tbl) * tbl:], self.train_X) ind = np.argpartition(P, range(self.k), axis=1)[:, 0:self.k] indexex = np.vstack((indexex, ind)) if return_distance is True: dist = np.partition(P, range(self.k), axis=1)[:, 0:self.k] distance = np.vstack((distance, dist)) else: for i in range(X.shape[0] // self.test_block_size): dist, ind = self.classifier.kneighbors(X[i * tbl:(i + 1) * tbl, :], n_neighbors=self.k, return_distance=True) distance = np.vstack((distance, dist)) indexex = np.vstack((indexex, ind)) if X.shape[0] % tbl != 0: dist, ind = self.classifier.kneighbors(X[(X.shape[0] // tbl) * tbl:, :], n_neighbors=self.k, return_distance=True) distance = np.vstack((distance, dist)) indexex = np.vstack((indexex, ind)) if return_distance is True: return (distance, indexex.astype(int)) else: return indexex.astype(int) def predict(self, X): answer = np.zeros(X.shape[0]) if self.weights is False: knn = self.find_kneighbors(X, return_distance=False) classes = self.train_y[knn] m = np.zeros(X.shape[0]) for i in self.Nclass: current = (classes == i).sum(axis=1) answer[(current > m)] = i m[(current - m) > 0] = current[(current - m) > 0] else: knn = self.find_kneighbors(X, return_distance=True) weights = (knn[0] + 10 ** (-5)) ** (-1) classes = self.train_y[knn[1]] m = np.zeros(X.shape[0]) for i in self.Nclass: current = ((classes == i) * weights).sum(axis=1) answer[(current > m)] = i m[(current - m) > 0] = current[(current - m) > 0] return answer def predict_k(self, classes, knn_dist=None): answer = np.ones(classes.shape[0]) if knn_dist is None: weights = np.ones(classes.shape) else: weights = (knn_dist + 10 ** (-5)) ** (-1) m = np.zeros(classes.shape[0]) for i in self.Nclass: current = ((classes == i) * weights).sum(axis=1) answer[(current > m)] = i m[(current - m) > 0] = current[(current - m) > 0] return answer
C#
UTF-8
1,321
2.5625
3
[]
no_license
using Coding.ShannonFano; using NUnit.Framework; namespace CodingUnitTests { [TestFixture] public class ShannonFano { [TestCase("aaabbcde", "000101011011101111")] [TestCase("a", "0")] [TestCase("aaaaaaaa", "00000000")] public void EncodeTesting(string input, string expected) { //arrange var coder = new Coder(); //act var actual = coder.Encode(input); //assert Assert.AreEqual(expected, actual); } [TestCase("aaabbcde", "000101011011101111", 7.11d)] [TestCase("a", "0", 16d)] [TestCase("aaaaaaaa", "00000000", 16d)] public void CompressCoefficient(string initial, string compressed, double expectedValue) { //arrange, act var actual = Compress.CompressGetter.GetCompress(initial, compressed); //assert Assert.AreEqual(expectedValue, actual); } [Test] public void DoublePenetration() { //arrange var coder = new Coder(); //act var actual = coder.Encode("aaabbcde"); actual = coder.Encode("aaabbcde"); //assert Assert.AreEqual("000101011011101111", actual); } } }
Python
UTF-8
6,498
2.59375
3
[]
no_license
# -*- coding: utf-8 -*- from sqlalchemy import create_engine from sqlalchemy import Table, Column, Integer, String, Text from sqlalchemy import Sequence from sqlalchemy import and_, or_ from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base SQLALCHEMY_DATABASE_URI = "mysql://%s:%s@%s/%s" % ('root', '', '127.0.0.1', 'db_demo') Base = declarative_base() engine = create_engine(SQLALCHEMY_DATABASE_URI, echo=True) # Create DB session Session = sessionmaker(bind=engine) class User(Base): """ User table scheme""" __tablename__ = 'users' id = Column(Integer, Sequence('user_id_seq'), primary_key=True) name = Column(String(50)) fullname = Column(String(50)) password = Column(String(50)) addresses = relationship('Address', back_populates='user', cascade="all, delete, delete-orphan") posts = relationship('BlogPost', back_populates='author', lazy='dynamic') def __repr__(self): return "<User name='%s'>" % self.name class Address(Base): __tablename__ = 'address' id = Column(Integer, primary_key=True) email_address = Column(String(255), nullable=False) user_id = Column(Integer, ForeignKey('users.id')) user = relationship('User', back_populates='addresses') def __repr__(self): return '<Address email_address="%s">' % self.email_address #===================================================================================== # Many to many #===================================================================================== # association table post_keywords = Table('post_keywords', Base.metadata, Column('post_id', ForeignKey('posts.id'), primary_key=True), Column('keyword_id', ForeignKey('keywords.id'), primary_key=True)) class BlogPost(Base): __tablename__ = 'posts' id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('users.id')) headline = Column(String(255), nullable=False) body = Column(Text) # many to many BlogPost <-> Keyword keywords = relationship('Keyword', secondary=post_keywords, back_populates='posts') author = relationship('User', back_populates='posts') def __init__(self, headline, body, author): self.author = author self.headline = headline self.body = body def __repr__(self): return "BlogPost(%s, %s, %s)" % (self.headline, self.body, self.author) class Keyword(Base): __tablename__ = 'keywords' id = Column(Integer, primary_key=True) keyword = Column(String(50), nullable=False, unique=True) posts = relationship('BlogPost', secondary=post_keywords, back_populates='keywords') def __init__(self, keyword): self.keyword = keyword # Init db , create all table Base.metadata.create_all(engine) # Get session session = Session() def addUser(name, fullname, password): user = User(name=name, fullname=fullname, password=password) session.add(user) session.commit() def add_all(): user1 = User(name='wendy', fullname='Wendy Williams', password='foobar') user2 = User(name='mary', fullname='Mary Contrary', password='xxg527') user3 = User(name='fred', fullname='Fred Flinstone', password='blah') session.add_all([user1, user2, user3]) session.commit() def query(): # user = session.query(User).filter_by(name='zhang').first() # print user query = session.query(User) # equals # print query.filter(User.name == 'mary').all() # not equals # print query.filter(User.name != 'mary').all() # like # print query.filter(User.name.like('%an%')).all() # ilike # print query.filter(User.name.ilike('%an%')).all() # in # print query.filter(User.name.in_(['wendy', 'jack'])).all() # and # print query.filter(and_(User.name == 'zhang', User.password == '123456')).first() # print query.filter(User.name == 'zhang', User.password == '123456').first() # print query.filter(User.name == 'zhang').filter(User.password == '123456').first() # or # print query.filter(or_(User.name == 'zhang', User.name == 'mary')).all() # match # print query.filter(User.name.match('zhang')) # count print query.filter(User.name.like('%li%')).count() def deleteUser(): user = session.query(User).filter_by(name='li').one() if user: session.delete(user) session.commit() def addAddress(): jack = User(name='jack', fullname='Jack Bean', password='123456') session.add(jack) session.commit() jack = session.query(User).filter_by(name='jack').first() print jack.addresses jack.addresses = [ Address(email_address='jack@google.com'), Address(email_address='j25@yahoo.com') ] session.add(jack) session.commit() def addBlogPost(): jack = session.query(User).filter_by(name='jack').one() post = BlogPost("Jack's Blog Post", "This is a test", jack) post.keywords.append(Keyword('Jack')) post.keywords.append(Keyword('firstpost')) session.add(post) session.commit() def queryBlogPost(): # result = session.query(BlogPost).filter(BlogPost.keywords.any(keyword='firstpost')).all() # print result jack = session.query(User).filter_by(name='jack').one() result = session.query(BlogPost).\ filter(BlogPost.author==jack).\ filter(BlogPost.keywords.any(keyword='firstpost')).\ all() print result def queryUserAndAddress(): for u, a in session.query(User, Address).\ filter(User.id == Address.user_id).\ filter(Address.email_address == 'jack@google.com').\ all(): print u print a result = session.query(User).join(Address).\ filter(Address.email_address=='jack@google.com').\ all() print result def queryJoin(): from sqlalchemy.orm import joinedload jack = session.query(User).options(joinedload(User.addresses)).filter_by(name='jack').one() print jack print jack.addresses if __name__ == '__main__': # addUser('zhang', 'zhangsan', '123456') # addUser('li', 'lisi', '123456') # addUser('ling', 'lingliu', '123456') # add_all() # query() # deleteUser() # addAddress() # addBlogPost() queryBlogPost()
PHP
UTF-8
743
2.625
3
[ "MIT" ]
permissive
<?php /** * PayuBundle for Symfony2 * * This Bundle is part of Symfony2 Payment Suite * */ namespace PaymentSuite\PayUBundle\Model\Abstracts; /** * Abstract Model class for report response models */ abstract class PayuReportResponse extends PayuResponse { /** * @var PayuResult * * result */ protected $result; /** * Sets Result * * @param PayuResult $result Result * * @return PayuReportResponse Self object */ public function setResult($result) { $this->result = $result; return $this; } /** * Get Result * * @return PayuResult Result */ public function getResult() { return $this->result; } }
PHP
UTF-8
1,674
3.46875
3
[]
no_license
<?php interface MyProduk{ public function getInfoProduk(); } abstract class Produk{ protected $nameProduk; protected $ketegory; protected $modelProduk; public function __construct($nameProduk="name Produk", $ketegory="ketegory", $modelProduk="model Produk") { $this->nameProduk = $nameProduk; $this->ketegory = $ketegory; $this->modelProduk = $modelProduk; } abstract public function setNameProduk($nameProduk); abstract public function setKetegory($ketegory); abstract public function setModelProduk($modelProduk); public function getInfo() { $str = "{$this->nameProduk} - {$this->ketegory} - {$this->modelProduk} <br>"; return $str; } } class Produk1 extends Produk implements MyProduk{ protected $nameProduk; protected $ketegory; protected $modelProduk; public function setNameProduk($nameProduk) { $this->nameProduk = $nameProduk; } public function setKetegory($ketegory) { $this->ketegory = $ketegory; } public function setModelProduk($modelProduk) { $this->modelProduk = $modelProduk; } public function getInfoProduk() { return $this->getInfo(); } } class CetakInfo{ public $produkInfo = []; public function cetakInfo( Produk $produk ) { $this->produkInfo[] = $produk; } public function cetak(){ $str = "DAFTAR PRODUK: <br>"; foreach ($this->produkInfo as $p) { $str .= $p->getInfo(); } return $str; } } $produk1 = new Produk1(); $produk2 = new Produk1(); $produk3 = new Produk1(); $produk4 = new Produk1(); $cetakP = new CetakInfo(); $cetakP->cetakInfo($produk1); $cetakP->cetakInfo($produk2); $cetakP->cetakInfo($produk3); $cetakP->cetakInfo($produk4); print($cetakP->cetak());
Go
UTF-8
1,753
2.6875
3
[ "Apache-2.0" ]
permissive
/* Copyright 2018 COMPANY Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package flags import ( "fmt" "reflect" "text/template" "github.com/pkg/errors" ) type TemplateFlag struct { rawTemplate string template *template.Template context interface{} } func (t *TemplateFlag) String() string { return t.rawTemplate } func (t *TemplateFlag) Usage() string { defaultUsage := "Format output with go-template." if t.context != nil { goType := reflect.TypeOf(t.context) url := fmt.Sprintf("https://godoc.org/%s#%s", goType.PkgPath(), goType.Name()) defaultUsage += fmt.Sprintf(" For full struct documentation, see %s", url) } return defaultUsage } func (t *TemplateFlag) Set(value string) error { tmpl, err := template.New("flagtemplate").Parse(value) if err != nil { return errors.Wrap(err, "setting template flag") } t.rawTemplate = value t.template = tmpl return nil } func (t *TemplateFlag) Type() string { return fmt.Sprintf("%T", t) } func (t *TemplateFlag) Template() *template.Template { return t.template } func NewTemplateFlag(value string, context interface{}) *TemplateFlag { return &TemplateFlag{ template: template.Must(template.New("flagtemplate").Parse(value)), rawTemplate: value, context: context, } }
Java
UTF-8
2,788
2.359375
2
[]
no_license
package com.bvd.android.carstobert.customer; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ArrayAdapter; import android.widget.ListView; import com.bvd.android.carstobert.R; import com.bvd.android.carstobert.controllers.CarController; import com.bvd.android.carstobert.model.Car; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class CustomerActivity extends AppCompatActivity { @BindView(R.id.customerCarList) public ListView carListView; private List<Car> cars; private Retrofit retrofit; private static final String API_BASE_URL = "http://10.0.2.2:4000/"; public static final String TAG = CustomerActivity.class.getName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_customer); ButterKnife.bind(this); cars = new ArrayList<>(); Car car = new Car("P100D", "Tesla", 1, "sold"); cars.add(car); createAdapter(); } private void createAdapter() { HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient.Builder httpClient = new OkHttpClient.Builder(); httpClient.addInterceptor(interceptor); Retrofit retrofit = new Retrofit.Builder() .client(httpClient.build()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(API_BASE_URL) .build(); CarController carController = retrofit.create(CarController.class); Call<List<Car>> getCarsCall = carController.getAvailableCars(); Log.v(TAG, "Calling api for getting all my cars"); getCarsCall.enqueue(new Callback<List<Car>>() { @Override public void onResponse(Call<List<Car>> call, Response<List<Car>> response) { Log.v(TAG, "getting the cars..."); //cars = response.body(); Log.v(TAG, response.body().toString()); } @Override public void onFailure(Call<List<Car>> call, Throwable t) { Log.v(TAG, "Failed call"); } }); ArrayAdapter<Car> carArrayAdapter = new ArrayAdapter<Car>(this, android.R.layout.simple_list_item_1, cars); carListView.setAdapter(carArrayAdapter); } }
Markdown
UTF-8
3,884
2.59375
3
[ "MIT" ]
permissive
![image preview](https://github.com/acecreamu/craquelure-graphs/blob/master/readme_imgs/img_preview.jpg) Supporting code to the publication [“The cracks that wanted to be a graph”: application of image processing and Graph Neural Networks to the description of craquelure patterns](https://arxiv.org) # Option 1. Extraction and characterization of craquelure patterns from an image Taking a skeletonized binary image as an input, given algorithm extracts non-directed graph from a cracks pattern, classifies nodes by topology onto X, Y, and O types, fits edges with polynomial, and exports comprehensive characteristic of a craquelure pattern. The latter can be used for forgery detection, origin examination, aging monitoring, and damage identification. ### Technical details We thank [alchemyst](https://github.com/alchemyst/ternplot) and [phi-max](https://github.com/phi-max/skel2graph3d-matlab) for their algorithms which we modify and apply in our code. All the rights to original implementations belong to the authors. The code is written under MatLab R2017b, other versions haven't be tested. Unlikely anything but the Image Processing Toolbox is required. If you find any surprising dependency - please notify us. Binarization of the crack images is very tricky and ungreatful process so we leave it for a user's responsibility. (Although we provide a helper code `prepare_bw.m` which was used in our experiments (parameters are in filenames of the images)). Run `main.m` for a fast start. </br> #### Output: ![image preview](https://github.com/acecreamu/craquelure-graphs/blob/master/readme_imgs/img_graph.jpg) ![image preview](https://github.com/acecreamu/craquelure-graphs/blob/master/readme_imgs/img_stats.jpg) </br></br> # Option 2. Extraction of graph features using GNN The algorithm takes a bunch of labeled graphs, uses them to train GNN, and then extracts a vector of hidden features from the GNN's layers for each graph. ### Technical details The implemention is based on [this algorithm by Xu *et al.*](https://github.com/weihua916/powerful-gnns) </br> Requirements: ``` pytorch tqdm numpy networkx scipy ``` ### Running the code As simple as: ``` cd GNN python main.py --dataset CRACKS --lr 0.001 --epochs 10 --fold_idx 0 ``` The output is a .mat file `graph-features.mat` containing only one variable of a size `[N_graphs x N_features]`. ### Custom dataset If you want to use custom dataset run `createTXT.m` and move the output to `/dataset/CRACKS/`. </br> The structure of the required .txt is following: - each graph is a block - first line of a block consist of *%number of nodes%* *%class label%* - each following line describes single node in a way: *%node label%* *%number of connected nodes%* *%connected node #1%* *%connected node #2%* *%connected node #3%*... - row number correspond to the node's index, starting from 0 - test/train partition is defined by cross-validation and doesn't appear in .txt For example: ``` 10 7 0 3 1 2 9 0 3 0 2 9 0 4 0 1 3 9 0 3 2 4 5 0 3 3 5 6 0 5 3 4 6 7 8 0 4 4 5 7 8 0 3 5 6 8 0 3 5 6 7 1 3 0 1 2 ``` The block corespond to a graph which consist of 10 nodes and belongs to class 7. First (0) node has label 0 and has 3 neighbours; these neighbours are nodes 1, 2, and 9. The same can be applied to the next nodes. </br></br></br> # Option 3. Merging the features and reproduction of the classification results from the paper The final part where extracted features are combined and used for the classification of patterns. ### Technical details 1. Use Option 2 to generate graph-features in advance or load proposed `stats.m` and `graph-features-263.m` 2. Follow `classification.m` </br> ![image preview](https://github.com/acecreamu/craquelure-graphs/blob/master/readme_imgs/img_GNN.jpg) </br> *Please cite the paper if you find our algorithm useful.* #### Good luck with your experiments.
JavaScript
UTF-8
3,894
2.59375
3
[ "CC-BY-3.0", "CC-BY-4.0" ]
permissive
customElements.define('fb-news-item', class extends HTMLElement { constructor() { super(); let menu = [ { 'label':'新增消息', 'event':'add-item' }, { 'label':'更改消息', 'event':'update-item' }, { 'label':'刪除消息', 'event':'remove-item' } ]; let that = this; let path = "https://d25k6mzsu7mq5l.cloudfront.net/template7.0/hkfb/_block/fb-news/html"; $.get(path, function(html){ console.log('HTML',html); const template= document.createElement('template'); template.innerHTML = html; const templateContent = template.content; // this.appendChild( that.attachShadow({mode: 'open'}).appendChild( templateContent.cloneNode(true) ); }); // Init Menu document.dispatchEvent(new CustomEvent('init-menu', { detail: {'component':'fb-news-item','element':that,'menu':menu} })); this.addEventListener('add-item',e=>{ const dom = e['detail']['element']; console.log(dom,dom.querySelector('[slot=ID]')); const table = dom.querySelector('[slot=ID]').getAttribute('data-table') || null; const dataId = dom.querySelector('[slot=ID]').getAttribute('data-id') || null; console.log('Detail',table,dataId); let title = prompt("請輸入資料標題 (注意: 重覆標題, 資料會遭覆寫", "標題"); if (title) { let json = { 'ID':title, 'title':title, 'updated': new Date().getTime(), 'link':title } document.dispatchEvent(new CustomEvent('save-data', { 'detail': { 'table':'news', 'id':json['ID'],'data':json }})); } // console.log('Add Item1'); }); this.addEventListener('remove-item',e=>{ const dom = e['detail']['element']; console.log(dom,dom.querySelector('[slot=ID]')); const table = dom.querySelector('[slot=ID]').getAttribute('data-table') || null; const dataId = dom.querySelector('[slot=ID]').getAttribute('data-id') || null; console.log('Detail',table,dataId); let isRemove = confirm("你是否確認資料要刪除?"); if (isRemove){ document.dispatchEvent(new CustomEvent('remove-data', { 'detail': { 'table':'news', 'id':dataId }})); } }); this.addEventListener('update-item',e=>{ const dom = e['detail']['element']; let table,dataId,msg; let record = {}; msg = "<h3>請輸入以下資料:</h3>"; console.log(dom,dom.querySelectorAll('[slot]')); dom.querySelectorAll('[slot]').forEach(item=>{ let slot = item.getAttribute('slot') || null; switch(slot){ case 'ID': table = item.getAttribute('data-table') || null; dataId = item.getAttribute('data-id') || null; record['ID'] = dataId; break; case 'updated': record['updated'] = new Date().getTime(); break; default: let value = prompt('請輸入'+slot); record[slot] = value; break; } }); document.dispatchEvent(new CustomEvent('save-data', { 'detail': { 'table':'news', 'id':dataId,'data':record }})); }); } } ); //const slottedSpan = document.querySelector('my-paragraph span'); //console.log(slottedSpan.assignedSlot); //console.log(slottedSpan.slot);
Markdown
UTF-8
1,076
2.6875
3
[ "MIT" ]
permissive
Site Lab ===== Site Lab aims to be an open-source replacement for website analysis tools such as BuiltWith, NerdyData, and DataNyze. Site Lab is a Ruby on Rails application. It uses PostgreSQL as its database and Redis + Sidekiq for background processing. How Does it Work? ----- Right now, it's fairly simple: - The [MetaInspector Gem](https://github.com/jaimeiniesta/metainspector) retrieves some basic info about the site/URL - There is a "Technology" model which stores regular expressions - Technologies are matched against the source of the sites/URLs More complex analysis is in the works. Installation ----- It's a Rails 4.1 app, so you'll need a dev environment that supports that (prolly RVM). - Clone the repo - Edit the database.yml file with your info - Run `bundle install` to install gems - Run `bundle exec rake db:create` to create the DB(s) - Run `bundle exec rake db:seed` to load the seed data - Run `rails s` to start the server locally Screenshot ----- ![Screenshot](https://raw.githubusercontent.com/callmeed/site-lab/master/screen.png)
JavaScript
UTF-8
668
2.59375
3
[]
no_license
let net = require("net"); let fs = require("fs"); function rert(remoteFileName) { if (remoteFileName!=undefined); console.log("no remote filename"); return send(remoteFileName); } function send(remoteFileName) { let commands = []; commands[0] = "PASV \n"; commands[1] = "RETR "+remoteFileName+"\n" return commands; } function getFile(port, ip, fileName) { let socket = new net.Socket(); socket.connect(port, ip); socket.on('data', (data) =>{ let write= fs.createWriteStream("./Downloads/"+fileName); write.write(data); write.end(); }); } module.exports = {send, getFile}
TypeScript
UTF-8
1,544
2.984375
3
[]
no_license
import faker = require('faker'); import { EventsMap, IEventDetails } from './EventsSourceToMap'; import { IEvent } from './iDBEvent'; function readEventsMap(): {key: string, item: IEventDetails} | undefined{ let i: number = 0; let max: number = EventsMap.size - 1; const index: number = (faker.random.number({'min': 0, 'max': max})) for (const [key, item] of EventsMap.entries()) { if ( i++ === index ) return ({key, item}); } return undefined; } const event_types = new Map([ ['i', 'info'], ['a', 'alarm'], ['w', 'warning'], ]); export function createEvent(): IEvent | undefined{ //случайное время (нужен формат "2020-09-26T16:18:36.036Z") const datetime: any = faker.date.recent(30); const date: string = DateTimeToDBStr(datetime); const utime: number = DateTimeToDBInt(datetime); //читаю случайное событие const mapData: {key: string, item: IEventDetails} | undefined = readEventsMap(); if (mapData === undefined) return undefined; const {key, item} = {... mapData} const event: IEvent = { utime, date, type:event_types.get(item.type), trig: faker.random.arrayElement(['FRONT','REAR','TOUGLE']), tag: `U1/RAM/${key}`, details: item } return event; } export function DateTimeToDBStr(date: Date): string { return date.toString().split(' ').slice(1, 6).join(' '); } export function DateTimeToDBInt(date: Date): number { return date.getTime() }
Java
UHC
1,083
3.75
4
[]
no_license
import java.util.Scanner; public class Exam04_3_1 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print(" Էϼ(1~12)>>"); int month = scanner.nextInt(); if (month <= 2) { System.out.println("ܿ"); } else if (month <= 5) { System.out.println(""); } else if (month <= 8) { System.out.println(""); } else if (month <= 11) { System.out.println(""); } else { System.out.println("ܿ"); } /* Է¹ month 3 ~ 5 ̸ */ /* Է¹ month 6 ~ 8 ̸ */ /* Է¹ month 9 ~ 11 ̸ */ /* * Է¹ * month * 12 * Ǵ 1 * Ǵ 2 * ̸ ܿ * */ scanner.close(); } }
Ruby
UTF-8
1,947
4.21875
4
[]
no_license
# Write a program called name.rb that asks the user to type in their name and then prints out a greeting message with their name included. puts "What's your name?" name = gets.chomp puts "Hello, #{name}. Have a nice day." # Write a program called age.rb that asks a user how old they are and then tells them how old they will be in 10, 20, 30 and 40 years. Below is the output for someone 20 years old. # # output of age.rb for someone 20 yrs old # How old are you? # In 10 years you will be: # 30 # In 20 years you will be: # 40 # In 30 years you will be: # 50 # In 40 years you will be: # 60 puts "How old are you?" age = gets.chomp.to_i puts "In 10 years you will be: #{age + 10}" puts "In 20 years you will be: #{age + 20}" puts "In 30 years you will be: #{age + 30}" puts "In 40 years you will be: #{age + 40}" # Add another section onto name.rb that prints the name of the user 10 times. You must do this without explicitly writing the puts method 10 times in a row. Hint: you can use the times method to do something repeatedly. 10.times do puts name end # Modify name.rb again so that it first asks the user for their first name, saves it into a variable, and then does the same for the last name. Then outputs their full name all at once. puts "What's your first name?" first_name = gets.chomp puts "What's your last name?" last_name = gets.chomp puts "#{first_name} #{last_name}" # Look at the following programs... # x = 0 # 3.times do # x += 1 # end # puts x # and... # y = 0 # 3.times do # y += 1 # x = y # end # puts x # What does x print to the screen in each case? Do they both give errors? Are the errors different? Why? # In the first case will print 3, in the second case will throw an error. # What does the following error message tell you? # NameError: undefined local variable or method `shoes' for main:Object # from (irb):3 # from /usr/local/rvm/rubies/ruby-2.0.0-rc2/bin/irb:16:in `<main>'
Java
UTF-8
905
2.5625
3
[ "MIT" ]
permissive
package id.or.k4x2.monopoly.entity.Cards; import id.or.k4x2.monopoly.entity.Player; import id.or.k4x2.monopoly.model.Context; import id.or.k4x2.monopoly.model.ContextEvents.MoneyEvent; import id.or.k4x2.monopoly.model.GameManager; /** * deduct money entity * @author Muhammad Yanza Hattari/18217043 */ public class DeductMoneyCard extends Card { private int dedmoney; public DeductMoneyCard(String name, String desc,int dedmoney){ super(name, desc); this.dedmoney = dedmoney; } public int getDedmoney() { return dedmoney; } public void setDedmoney(int dedmoney) { this.dedmoney = dedmoney; } public void doAction(Player player) { GameManager.getInstance().deductMoney(player,dedmoney); // Log event Context.getInstance().logEvent(new MoneyEvent(false, dedmoney, player.getName() + " mengeluarkan Rp " + dedmoney)); } }
Java
UTF-8
7,871
2.875
3
[]
no_license
package newcalculator; import java.awt.BorderLayout; import javax.swing.*; import java.sql.*; import java.awt.EventQueue; import javax.swing.border.EmptyBorder; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import java.awt.Font; import java.awt.Image; import com.toedter.calendar.JDateChooser; import java.util.Date; import java.text.SimpleDateFormat; public class frame2 extends JFrame { private JPanel contentPane; private JTextField textField14; private JDateChooser dateChooser;/*i have declred this as instance variable...bcoz this instance i can use anywhere in my class. i had to use that same instance datechooser as datechooser.getdata()in try block. .so i have to make it as instance variale ...similary i have done same thing for Jcombobox */ private JComboBox comboBox; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { frame2 frame = new frame2(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } public static int isNumber(String str2) { try { double v = Double.parseDouble(str2); return 1; } catch (NumberFormatException nfe) { } return 0; } Connection connection1 =null; private JTextField textField16; /** * Create the frame. */ public frame2() { connection1=sqliteConnection.dbConnector(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 842, 488); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblNewLabel = new JLabel("Amount"); lblNewLabel.setFont(new Font("Calisto MT", Font.PLAIN, 16)); lblNewLabel.setBounds(174, 214, 89, 14); contentPane.add(lblNewLabel); JLabel lblNewLabel_1 = new JLabel("Category"); lblNewLabel_1.setFont(new Font("Calisto MT", Font.PLAIN, 16)); lblNewLabel_1.setBounds(174, 277, 89, 18); contentPane.add(lblNewLabel_1); textField14 = new JTextField(); textField14.setBounds(273, 213, 86, 20); contentPane.add(textField14); textField14.setColumns(10); JButton Button5 = new JButton("OK"); Image img12=new ImageIcon(this.getClass().getResource("/60.png")).getImage(); Button5.setIcon(new ImageIcon(img12)); Button5.setFont(new Font("Calisto MT", Font.PLAIN, 16)); Button5.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { String str=textField14.getText(); int check=frame2.isNumber(str);//if amount is other than number then check will be 0 if(str.equals("")) { JOptionPane.showMessageDialog(null," Amount Can Not Be Empty"); } else if(check==0) { JOptionPane.showMessageDialog(null," Enter Proper Amount"); } else { SimpleDateFormat dateobj=new SimpleDateFormat("dd"); SimpleDateFormat monthobj=new SimpleDateFormat("MMMM"); SimpleDateFormat yearobj=new SimpleDateFormat("yyyy"); String query="insert into IncomeTable (Day,Month,Year,Amount,category,Description) values (?,?,?,?,?,?)"; PreparedStatement pst=connection1.prepareStatement(query); pst.setString(1,dateobj.format(dateChooser.getDate())); pst.setString(2,monthobj.format(dateChooser.getDate())); pst.setString(3,yearobj.format(dateChooser.getDate())); pst.setString(4,textField14.getText()); pst.setString(5,(String)comboBox.getSelectedItem()); pst.setString(6,textField16.getText()); pst.execute(); JOptionPane.showMessageDialog(null," DATA SAVED SUCCESSFULLY"); pst.close(); dispose(); Mainframe obj2=new Mainframe(); double value = Double.valueOf(textField14.getText()); Mainframe.Income=(Mainframe.Income)+value; obj2.frame.setVisible(true); obj2.textField1.setText(Double.toString(Mainframe.Income)+" "+"INR"); obj2.textField2.setText(Double.toString(Mainframe.Expense)+" "+"INR"); obj2.textField3.setText(Double.toString(Mainframe.Income-Mainframe.Expense)+" "+"INR"); }//else cloed }//try closed catch (Exception e3) { e3.printStackTrace(); } } }); Button5.setBounds(145, 399, 118, 23); contentPane.add(Button5); JLabel lblNewLabel_5 = new JLabel("Date"); lblNewLabel_5.setFont(new Font("Calisto MT", Font.PLAIN, 16)); lblNewLabel_5.setBounds(174, 155, 81, 20); contentPane.add(lblNewLabel_5); JLabel lblNewLabel_2 = new JLabel("Enter Income"); lblNewLabel_2.setFont(new Font("Calisto MT", Font.PLAIN, 20)); lblNewLabel_2.setBounds(205, 83, 123, 14); contentPane.add(lblNewLabel_2); JLabel lblNewLabel_6 = new JLabel(""); Image img6=new ImageIcon(this.getClass().getResource("/70.png")).getImage(); lblNewLabel_6.setIcon(new ImageIcon(img6)); lblNewLabel_6.setBounds(10, 108, 125, 287); contentPane.add(lblNewLabel_6); JButton btnNewButton = new JButton("BACK"); Image img16=new ImageIcon(this.getClass().getResource("/50.png")).getImage(); btnNewButton.setIcon(new ImageIcon(img16)); btnNewButton.setFont(new Font("Calisto MT", Font.PLAIN, 16)); btnNewButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { dispose(); Mainframe obj2=new Mainframe(); obj2.frame.setVisible(true); obj2.textField1.setText(Double.toString(Mainframe.Income)+" "+"INR"); obj2.textField2.setText(Double.toString(Mainframe.Expense)+" "+"INR"); obj2.textField3.setText(Double.toString(Mainframe.Income-Mainframe.Expense)+" "+"INR"); } }); btnNewButton.setBounds(274, 399, 134, 23); contentPane.add(btnNewButton); dateChooser = new JDateChooser(); dateChooser.getCalendarButton().setFont(new Font("Calisto MT", Font.PLAIN, 16));/*equvivaent to JDateChooser dateChooser = new JDateChooser();i have already declared JDateChooser dateChooser as instance variable; this 4 lines were already created by IDE hen we drag jdatechooser*/ dateChooser.setDateFormatString("dd MMMM yyyy"); dateChooser.setBounds(271, 155, 166, 20); contentPane.add(dateChooser); Date obj=new Date(); dateChooser.setDate(obj);//set current date JLabel lblNewLabel_3 = new JLabel(""); Image img110=new ImageIcon(this.getClass().getResource("/20.png")).getImage(); lblNewLabel_3.setIcon(new ImageIcon(img110)); lblNewLabel_3.setBounds(145, 77, 50, 31); contentPane.add(lblNewLabel_3); JLabel lblNewLabel_4 = new JLabel(""); Image img111=new ImageIcon(this.getClass().getResource("/20.png")).getImage(); lblNewLabel_4.setIcon(new ImageIcon(img111)); lblNewLabel_4.setBounds(326, 77, 95, 31); contentPane.add(lblNewLabel_4); comboBox = new JComboBox(); comboBox.setFont(new Font("Calisto MT", Font.BOLD, 13)); comboBox.addItem("Loan"); comboBox.addItem("Salary"); comboBox.addItem("Pocket Money"); comboBox.addItem("Gift"); comboBox.addItem("Other"); comboBox.setSelectedItem("Pocket Money"); comboBox.setBounds(270, 278, 151, 23); contentPane.add(comboBox); textField16 = new JTextField(); textField16.setFont(new Font("Calisto MT", Font.PLAIN, 14)); textField16.setBounds(270, 345, 123, 20); contentPane.add(textField16); textField16.setColumns(10); JLabel lblNewLabel_7 = new JLabel("Description"); lblNewLabel_7.setFont(new Font("Calisto MT", Font.PLAIN, 16)); lblNewLabel_7.setBounds(174, 343, 89, 23); contentPane.add(lblNewLabel_7); } }
Python
UTF-8
1,919
2.765625
3
[]
no_license
import requests from fake_useragent import UserAgent # # url = 'http://codingbat.com/java' # file_name = 'codingbat_exercises.txt' # # user_agent = UserAgent() # page = requests.get(url, headers ={'user-agent':user_agent.chrome}) # # with open(file_name,'w') as file: # file.write(page.content.decode('utf-8')) if type(page.content) == bytes else file.write(page.content) from bs4 import BeautifulSoup # # def read_file(): # file = open('codingbat_exercises.txt') # data = file.read() # file.close() # return data # # soup = BeautifulSoup(read_file(), 'lxml') # # all_divs = soup.find_all('div', attrs={'class':'summ'}) user_agent = UserAgent() main_url = 'http://codingbat.com/java' page = requests.get(main_url, headers={'user-agent':user_agent.chrome}) soup = BeautifulSoup(page.content, 'lxml') base_url = 'http://codingbat.com' all_divs = soup.find_all('div', class_ ='summ') all_links = [base_url + div.a['href'] for div in all_divs] for link in all_links: inner_page = requests.get(link,headers={'user-agent':user_agent.chrome}) inner_soup = BeautifulSoup(inner_page.content, 'lxml') div = inner_soup.find('div', class_='tabc') question_links = [base_url + td.a['href'] for td in div.table.find_all('td')] # for question_link in question_links: # print(question_link) # break for question_link in question_links: final_page = requests.get(question_link) final_soup = BeautifulSoup(final_page.content, 'lxml') indent_div = final_soup.find('div', attrs={'class':'indent'}) problem_statement = indent_div.table.div.string siblings_of_statement = indent_div.table.div.next_siblings examples = [sibling for sibling in siblings_of_statement if sibling.string is not None] for example in examples: print(example) #for sibling in siblings_of_statement: break break
Markdown
UTF-8
959
2.609375
3
[]
no_license
# CandyShop This is a candy store website. New user can sign up and log in. There are two roles: admin and user. Admin has an access to the admin panel. Admin can add new good, user, category; edit good, user, category and order status; delete good, user and category. User is able to search goods by category and name; add good to the cart; make order; browse his orders; ## Launch guide * Create PostgreSQL database * Provide database connection parameters in `db.properties` file in `resources` folder. * Connect database with Inteliji Idea and run `CandyShop.sql` script. Then run `insertionScript.sql` * In `web.xml` specify context param value of `upload.location` with your path, where images will be uploaded ## Recomendations * Tomcat ver 9 + * Internet connection * Test on the Google Chrome web browser * Images of goods will not be displayed until they are uploaded into folder specified in `web.xml`. You can add them in admin panel.
Go
UTF-8
1,792
3.0625
3
[]
no_license
package currencies import ( "gopkg.in/mgo.v2/bson" "klubox/infrastructure/db" "klubox/util" ) // CurrencyRepository is a Mongo DB implementation of the currency repository type CurrencyRepository struct { Db db.DbHandler } // Save is a method for adding a currency to the currency mongo repo. func (repo *CurrencyRepository) Save(curr *Currency) (*Currency, error) { collection := repo.Db.Query("currencies") query := bson.M{"name": curr.Name} count, err := collection.Find(query).Count() if err != nill { return nil, err } else if count > 0 { return nil, util.ErrCurrencyExists } curr.ID = db.NewID() if err := collection.Insert(curr); err != nil { return nil, err } return curr, nil } // FindAll - method for retrieving currencies func (repo *CurrencyRepository) FindAll() ([]*Currency, error) { var currencies []*Currency collection := repo.Db.Query("currencies") err := collection.Find(bson.M{}).All(&currencies) if err != nil { return nil, util.ErrDBError } return currencies, nil } // DeleteCurrency - method for deleting currency func (repo *CurrencyRepository) DeleteCurrency(id string) error { collection := repo.Db.Query("currencies") query := bson.M{"id", bson.ObjectIdHex(id)} count, err := collection.Find(query).Count() if err != nil { return err } if count < 1 { return util.ErrCurrencyDoesNotExist } err = collection.Remove(query) if err != nil { return err } return nil } // UpdateCurrency - updates the exchange rate of a currency func (repo *CurrencyRepository) UpdateCurrency(id string, curr *Currency) (*Currency, error) { collection := repo.Db.Query("currencies") id = bson.ObjectIdHex(id) err := collection.Update(bson.M{"id": id}, curr) if err != nil { return nil, err } return curr, nil }
Java
UTF-8
1,880
2.234375
2
[]
no_license
package mx.com.doe.dev.webbet.data.mysql; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import javax.annotation.Resource; import javax.ejb.Stateless; import javax.sql.DataSource; import mx.com.doe.dev.webbet.domain.Event; @Stateless public class EventDao { @Resource(name="jdbc/datasource") private DataSource dataSource; private SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm a"); public List<Event> findByCompetition(String competitionName) { List<Event> events = new ArrayList<Event>(0); String sql = "SELECT e.id, s.fnme, c.fnme, e.edtn, e.stge, e.dttm,l.snme,l.logo,l.stad,v.snme,v.logo " + "FROM tbldoebetwebevent e, tbldoebetwebcompetition c, tbldoebetwebsport s, tbldoebetwebteam l, tbldoebetwebteam v " + "WHERE e.cmpt = c.id AND c.spot = s.snme AND l.id = e.locl AND v.id = e.vstr " + "AND c.snme = ? AND e.stus = 1 ORDER BY dttm ASC;"; try { Connection conn = dataSource.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, competitionName); ResultSet rs = pstmt.executeQuery(); while(rs.next()) { Event e = new Event(); e.setEventId(rs.getInt(1)); e.setSportName(rs.getString(2)); e.setCompetitionName(rs.getString(3)); e.setEdition(rs.getString(4)); e.setStage(rs.getString(5)); e.setDateTime(sdf.format(rs.getTimestamp(6))); e.setLocalName(rs.getString(7)); e.setLocalLogo(rs.getString(8)); e.setLocalStadium(rs.getString(9)); e.setVisitorName(rs.getString(10)); e.setVisitorLogo(rs.getString(11)); events.add(e); } } catch(Exception e) { e.printStackTrace(); } return events; } }
C++
UTF-8
953
2.671875
3
[]
no_license
/* Define the traditional particle filter (PF) algorithm */ #ifndef PARTICLEFILTER #define PARTICLEFILTER #include <iostream> #include <Eigen/Dense> #include "Filter.h" namespace attitude_estimation{ class ParticleFilter: public ParticleFilterBase { double diffuse_kernel_; // Noise parameter to diffuse particles after resampling public: // Constructor ParticleFilter(const VectorXd &IC_mean, const VectorXd &IC_std, const int num_particles, const double diffuse_kernel) : ParticleFilterBase(IC_mean, IC_std, num_particles), diffuse_kernel_(diffuse_kernel) {} // Run particle filter algorithm for one step virtual void update(int TI, double dt, std::default_random_engine &generator) override; // Resampling procedure void resampling(VectorXd &weights, std::default_random_engine &generator); virtual std::ostream& message(std::ostream &out) const override; }; } // End of attitude_estimation namespace #endif
Python
UTF-8
19,282
4.84375
5
[]
no_license
""" In this lesson, you will build a simple to-do list program that lets you: Print your to-do list Add items to your to-do list Mark items as "complete" - removing them from the list """ "WHAT IS A SEQUENCE?" "In Python, a sequence is a data type that can store multiple, individual values. Examples of sequences include:" "List" programming_languages = ["bash", "Python", "HTML", "CSS", "JavaScript", "SQL"] #Lists are mutable (modifiable) in sequences - versatile, general-purpose collection. "Tuple" gps_coordinates = (33.848673, -84.373313) #Tuples are immutable sequences - best for representing something with a fixed size (e.g. GPS coordinations) "Range" numbers_from_zero_to_a_million = range(1000000) #Ranges are lists of numeric values """ HOW DO I CREATE A LIST? Lists can hold any other type (Strings, numbers, other Lists, etc.). The easiest way to create one is to assign a List literal to a variable: """ todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] """ A List literal is: • one or more values (or variables) • separated by commas , • enclosed in square brackets [] """ """ HOW DO I ACCESS ITEMS IN A SEQUENCE? You can access items in a sequence in groups or individually. #How do I access individual items in a Sequence? Here is how Python stores values in our todos List: index value 0 "pet the cat" 1 "go to work" 2 "feed the cat" Python uses an integer index to identify values within a single List. The first index is always 0. """ #You use the index to reer to a specific item in the list: todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] first_item = todos[0] second_item = todos[1] # It is not necessary to create a variable. You can index as part of an expression: todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] # first_item = todos[0] print("The first item is:", todos[0]) # second_item = todos[1] print("The second item is:", todos[1]) """ Why is a negative index valid? Python allows you to use a negative index, which tells it to start from the end instead of the beginning. """ todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] print("This is the last item:", todos[-1]) print("This is the next to last item:", todos[-2]) """ How do I access groups of items in a Sequence? You can access all of the items simply by using the variable name for the sequence itself: """ todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] print("Here are your todos:") print(todos) #Which prints Here are your todos: ['pet the cat', 'go to work', 'feed the cat'] "You can use the slicing syntax to access a subset of the items:" todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] print("Here are the second and third todos:") print(todos[1:3]) """ When you slice a List, you normally provide two number separated by a : The first number is the starting index. It is included in the result The second number is the ending index. It is not included in the result. If you omit the starting index, Python starts the slice at the beginning (index 0). If you omit the ending index, Python goes to the end (the last index). """ #Here is the output Slice from the third through the end: ['shop for groceries', 'go home', 'feed the cat'] Slice from the beginning up to, but not including the fourth: ['pet the cat', 'go to work', 'shop for groceries'] # You can use negative indexes with slices: todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] print("Two items up to, but not including the last:", todos[-3:-1]) print("These are the last 3 items:", todos[-3:]) # Which gives the following result: Two items up to, but not including the last: ['shop for groceries', 'go home'] These are the last 3 items: ['shop for groceries', 'go home', 'feed the cat'] #ITERATING THROUGH A SEQUENCE """ Now that you know how to access items manually, it is time to automate that with a loop. Using a loop to access a sequence's items one at a time is called iteration. In this portion of the lesson, we will print the items of the to-do list. Recall that a while loop should always move closer to some end condition so that it isn't an infinite loop. #How do I find the length of a Sequence? Python provides a len() function that will tell you how many items are in a Sequence. You give len() a Sequence; it returns an integer. We will use this as part of the condition for a while-loop. """ todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] index = 0 # Begin with index 0 while index < len(todos): todo = todos[index] print("%d: %s" % (index + 1, todo)) index += 1 """ These are the three parts of our while loop ^ : • An initial state: we start the index variable at 0 • A condition: only run the code block if index is less than len(todos) • A code block that moves us closer to the end condition: index += 1 This while-loop is exactly like the simple counter program from the previous lesson. The only difference is that on line 5, we create a todo variable to reference the item at todos[index]. Not only does incrementing move us closer to the end condition, but it lets us access the next item in the list each time the code block runs. When we run our program, we see the following: """ 1: pet the cat 2: go to work 3: shop for groceries 4: go home 5: feed the cat """ On line 6 of our program, we interpolate the value index + 1 so that it prints a "human readable" version of our index. """ """ What is a for-loop and why should I use it with a List? Often, you do not need to know the specific index of an item. You just want the items themselves. Python provides another kind of loop: the for-loop. Here is our to-do printer using this syntax, with the numerical index omitted: """ todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] for todo in todos: print(todo) """ It's so much shorter! For-loops are a shorthand for iterating and accessing an item at a time. """ pet the cat go to work shop for groceries go home feed the cat """ If you do want to show the index (or at least number the todos) you can add a variable that you display and increment: """ todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] count = 1 for todo in todos: print("%d: %s" % (count, todo)) count += 1 """ Other than looking nice next to each to-do, the count variable serves no other purpose in our for-loop. """ 1: pet the cat 2: go to work 3: shop for groceries 4: go home 5: feed the cat """ HOW DO I MODIFY A LIST? Lists are Python's mutable Sequence type, meaning that you can add, remove, and replace items. How do I add items to a List? • There are three ways to add items to a List: • You can .append() individual items • You can concatenate two lists together • You can .extend() a list using elements from another list • Each List has a .append() method that you can use like this: """ todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] todos.append("binge watch a show") todos.append("go to sleep") count = 1 for todo in todos: print("%d: %s" % (count, todo)) count += 1 "You can see that it adds on to our original todos:" 1: pet the cat 2: go to work 3: shop for groceries 4: go home 5: feed the cat 6: binge watch a show 7: go to sleep "Alternatively, you can use the concatenation operator + to combine two lists:" todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] todos = todos + ["binge watch a show", "go to sleep"] count = 1 for todo in todos: print("%d: %s" % (count, todo)) count += 1 "This is equivalent to using the .extend() method:" todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] todos.extend(["binge watch a show", "go to sleep"]) count = 1 for todo in todos: print("%d: %s" % (count, todo)) count += 1 """ *** Concatenation produces a new List. .append() and .extend() modify a List in-place. That is, these mutate a List instead of returning *** """ todos = [] # Prompt the user the first time new_todo = input("What do you need to do? ") while len(new_todo) > 0: todos.append(new_todo) # Print the current list of to-do items print("To do:") print("====================") count = 1 for todo in todos: print("%d: %s" % (count, todo)) count += 1 # Prompt the user again print("\n") new_todo = input("What do you need to do? ") print("Have a nice day!") """ How do I replace items in a List? You can use an index to refer to a specific place in a List. If you do this on the LHS of an assignment, you can replace an item: """ todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] todos[1] = "go to the grocery store" print(todos) "In this example, we have reassigned the value at index 1:" ['pet the cat', 'go to the grocery store', 'shop for groceries', 'go home', 'feed the cat'] todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] "If you need to replace multiple items, you can use a slice on the LHS and a List on the RHS:" todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] todos[1:4] = ["make cat food", "cook cat food"] print(todos) "Here, we replace the items from index 1 up to, but not including index 4:" ['pet the cat', 'make cat food', 'cook cat food', 'feed the cat'] "Notice that our slice on the LHS referred to 3 items, but the List on the RHS only contained 2 items. Python replaces that entire segment of the list with a new list; it is not replacing those items individually." todos = [] # Create a constant for our main menu. # This saves us from having to type it out twice. MAIN_MENU = """ Choose an action: P: Print your to-do list A: Add a to-do item R: Replace a to-do item (Or press Enter to exit the program.) """ choice = input(MAIN_MENU) choice = choice.upper() # Simplifies our if-conditions # As long as they type something, keep prompting while len(choice) > 0: if choice == "P": # Print the current list of to-do items print("\n\n\nTo do:") print("====================") count = 1 for todo in todos: print("%d: %s" % (count, todo)) count += 1 elif choice == "A": new_todo = input("What do you need to do? ") if len(new_todo) > 0: todos.append(new_todo) elif choice == "R": # Print the current list of to-do items print("\n\n\nTo do:") print("====================") count = 1 for todo in todos: print("%d: %s" % (count, todo)) count += 1 which_index = input("Which to-do number? ") try: which_index = int(which_index) which_index -= 1 # Convert from human-readable to 0-based index if which_index >= 0 and which_index < len(todos): new_todo = input("What do you need to do? ") todos[which_index] = new_todo except ValueError: print("\n\n***Please enter a number.***") else: print("\n\n***Please enter a valid menu option.***") choice = input(MAIN_MENU) choice = choice.upper() # Simplifies our if-conditions print("Have a nice day!") """ HOW DO I DELETE ITEMS FROM A LIST The syntax for removing an item from a List is different from what we've seen so far. Use the del keyword to tell Python to remove one or more items from a List: """ todos = ["pet the cat", "go to work", "shop for groceries", "go home", "feed the cat"] del todos[0] # Remove the first one print(todos) del todos[1:3] # Remove items at index 1 up but not including index 3 print(todos) "Here is the output from running the example:" ['go to work', 'shop for groceries', 'go home', 'feed the cat'] ['go to work', 'feed the cat'] todos = [] # Create a constant for our main menu. # This saves us from having to type it out twice. MAIN_MENU = """ Choose an action: P: Print your to-do list A: Add a to-do item R: Replace a to-do item C: Complete a to-do item (Or press Enter to exist the program.) """ choice = input(MAIN_MENU) choice = choice.upper() # Simplifies our if-conditions # As long as they type something, keep prompting while len(choice) > 0: if choice == "P": # Print the current list of to-do items print("\n\n\nTo do:") print("====================") count = 1 for todo in todos: print("%d: %s" % (count, todo)) count += 1 elif choice == "A": new_todo = input("What do you need to do? ") if len(new_todo) > 0: todos.append(new_todo) elif choice == "R": # Print the current list of to-do items print("\n\n\nTo do:") print("====================") count = 1 for todo in todos: print("%d: %s" % (count, todo)) count += 1 which_index = input("Which to-do number? ") try: which_index = int(which_index) which_index -= 1 # Convert from human-readable to 0-based index if which_index >= 0 and which_index < len(todos): new_todo = input("What do you need to do? ") todos[which_index] = new_todo except ValueError: print("\n\n***Please enter a number.***") elif choice == "C": # Print the current list of to-do items print("\n\n\nTo do:") print("====================") count = 1 for todo in todos: print("%d: %s" % (count, todo)) count += 1 which_index = input("Which to-do number? ") try: which_index = int(which_index) which_index -= 1 # Convert from human-readable to 0-based index if which_index >= 0 and which_index < len(todos): completed_todo = todos[which_index] del todos[which_index] print("%s has been marked complete!" % completed_todo) except ValueError: print("\n\n***Please enter a number.***") else: print("\n\n***Please enter a valid menu option.***") choice = input(MAIN_MENU) choice = choice.upper() # Simplifies our if-conditions print("Have a nice day!") """ WHEN SHOULD I USE NESTED LOOPS? Lists can hold any kind of value, including Lists. You can use nested loops to create nested Lists and to iterate over them. Let's create a tic-tac-toe board using nested loops. It will look like this: """ """ How do I use the range() function to generate numbers? To create our game board, we need to produce numbers that correspond to our List indexes. To do that, we'll use the range() function. You pass range() a number, and it returns the integers up to, but not including that number. First, let's see the nested loops in action, just printing the numbers generated by range(0): """ """ How do I use Strings as Sequences? Like Lists, you can index, slice, and get the length of Strings as if though they were Lists. """ alphabet = "abcdefghijklmnopqrstuvwxyz" print("The first letter is", alphabet[0]) print("The first three letters are", alphabet[:3]) print("Some letters in the middle are", alphabet[11:16]) print("There are %d letters in the alphabet" % len(alphabet)) """ How do I loop through the characters of a String? Because you can index and get the length of a String, you can also iterate through the individual characters: """ alphabet = "abcdefghijklmnopqrstuvwxyz" for letter in alphabet: print(letter) "And the results of running the code:" a b c d e f g h i j k l m n o p q r s t u v w x y z """ How do I convert a String into a List? One notable difference between Strings and Lists is that you cannot modify a String by reassigning to an index. You would first have to convert it to a List so that you could mutate the data: """ alphabet = "abcdefghijklmnopqrstuvwxyz" alphalist = list(alphabet) alphalist[0] = "4" print(alphalist) "This allows you to make whatever modifications you choose:" ['4', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] """ How do I convert a List into a String? There is a trick to converting your List back into a String, and it is a bit counter-intuitive at first. """ alphabet = "abcdefghijklmnopqrstuvwxyz" alphalist = list(alphabet) alphalist[0] = "4" print(alphalist) alphabet = "".join(alphalist) print(alphabet) # You use the String method .join() to reconnect the items of a List. # Because we used an empty String ('') to join the items, the resulting String has no spaces: ['4', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 4bcdefghijklmnopqrstuvwxyz "Note that we did not mutate our String, but did reassign the variable name alphabet to our newly .join()-ed String. But, we can use any String we want to insert between the joined List items:" alphabet = "abcdefghijklmnopqrstuvwxyz" alphalist = list(alphabet) alphalist[0] = "4" print(alphalist) alphabet = "!\n".join(alphalist) print(alphabet) "Now, our alphabet String has an ! and a line break between each letter:" ['4', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] 4! b! c! d! e! f! g! h! i! j! k! l! m! n! o! p! q! r! s! t! u! v! w! x! y! z "Note that .join() inserts a String between each List item. The z does not have a ! after it." """ What Sequence operations work with Tuples? Just as with Strings, you can index, slice, and get the length of a Tuple. But you cannot modify a Tuple. """ coordinates = (33.848673, -84.373313) latitude = coordinates[0] longitude = coordinates[1] print("The latitude is %f and the longitude is %f" % (latitude, longitude)) This program prints the following: The latitude is 33.848673 and the longitude is -84.373313 """ Tuples are immutable. Assigning to an index of a Tuple results in an error. But you can concatenate to produce a new Tuple: """ band_mates = ("John", "Paul", "George", "Pete") print(band_mates) band_mates = band_mates[:-1] # All but the last print(band_mates) band_mates = band_mates + ("Ringo", ) print(band_mates) "This works because you are doing reassignment, not mutation." ('John', 'Paul', 'George', 'Pete') ('John', 'Paul', 'George') ('John', 'Paul', 'George', 'Ringo')" "To create a Tuple with a single item, you must wrap it in parentheses and add a trailing comma as shown in the previous code sample." """ Summary In this lesson, you learned about the following Sequence types: Lists Strings Tuples ranges Sequences in Python share a number of qualities in common. They are all: index-able slice-able length-able Because of these qualities, they are also iterable (meaning you can use a for-loop with them.) """
Shell
UTF-8
709
3.875
4
[]
no_license
#! /usr/bin/env bash xbit=false gbit=false ro=false script="$0" fail() { local target="$1" if [ -f $target ]; then rm -f $target shift fi echo "$script: $@" 1>&2 exit 1 } args="" for arg in $@; do case "$arg" in -x) xbit=true ;; -g) gbit=true ;; -p) xbit=true gbit=true ;; -r) ro=true ;; *) args="$args $arg" ;; esac done for arg in $args; do mv -f $arg $arg.tmp$$ || fail $arg.tmp$$ Unable to rename $arg cp -f $arg.tmp$$ $arg status=$? if [ $status -ne 0 ]; then mv -f $arg.tmp$$ $arg fail '' Unable to copy back $arg fi $xbit && chmod ugo+x $arg $gbit && chmod ug+w $arg $ro && chmod ugo-w $arg done
Java
UTF-8
304
2
2
[ "Apache-2.0" ]
permissive
package com.hyphenate.easeui.game.iterface; /** * Reference: * Author: * Date:2016/9/9. */ public interface OnPlayListener { int FLAG_I_WIN=0; int FLAG_OPPO_WIN=1; int FLAG_DRAW=2; void onIPlayed(int[] data); void onOppoPlayed(int[] data); void onGameOver(int resultFlag); }
Java
UTF-8
2,208
2.4375
2
[]
no_license
package com.dodge.dodgedemoapp.restcontroller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.dodge.dodgedemoapp.entity.InfactRecord; import com.dodge.dodgedemoapp.service.InfactRecordServiceImpl; @RestController @RequestMapping(("/api")) public class InfactRecordRestController { @Autowired private InfactRecordServiceImpl infactRecordServiceImpl; @GetMapping("/index") public String welcome() { return "Welcome to Dodge"; } @GetMapping("/infact-record") private List<InfactRecord> list() { List<InfactRecord> infactRecords = infactRecordServiceImpl.list(); return infactRecords; } @GetMapping("/infact-record/{id}") private InfactRecord get(@PathVariable("id") Long id) { return infactRecordServiceImpl.get(id); } @PostMapping("/infact-record") private ResponseEntity<?> save(@RequestBody InfactRecord infactRecord) { infactRecordServiceImpl.save(infactRecord); return ResponseEntity.ok().body( "New InfactRecord has been saved with ID: " + infactRecord.getRecordId()); } /*---Update a infact-record by id---*/ @RequestMapping(value="/infact-record", method=RequestMethod.PUT) public ResponseEntity<?> update(@RequestBody InfactRecord infactRecord) { infactRecordServiceImpl.update(infactRecord); return ResponseEntity.ok().body( "infact-record has been updated successfully."); } /*---Delete a infact-record by id---*/ @DeleteMapping("/infact-record/{id}") public ResponseEntity<?> delete(@PathVariable("id") long id) { infactRecordServiceImpl.delete(id); return ResponseEntity.ok().body( "infact-record has been deleted successfully."); } }
Markdown
UTF-8
1,708
3.4375
3
[ "MIT" ]
permissive
--- title: Exercise 4.1-2 published: 2012-08-28 18:05 modified: 2021-01-19 10:30 keywords: "maximum subarray, python code" description: "[Python code] Write pseudocode for the brute-force method of solving the maximum-subarray problem. Your procedure should run in Θ(n²) time." --- > Write pseudocode for the brute-force method of solving the maximum-subarray problem. Your procedure should run in $$\Theta(n^2)$$ time. {% capture code %} left = low right = high sum = -∞ for i = low to high tempSum = 0 for j = i to high tempSum = tempSum + A[j] if tempSum > sum sum = tempSum left = i right = j return (left, right, sum) {% endcapture %} {% include clrs_code.html title="Find-Maximum-Subarray-BruteForce(A, low, high)" %} You can find Python implementation of this at the [bottom of the page](#code-editor). {% capture note %} Although this algorithm is able to find the correct sum, it will always find the longest sequence, in case there are multiple possible answers. For example, arrays with 0 as the beginning of maximum-subarray. For $$A = [0, 1, 2]$$, it'll always return $$[1 .. 3]$$ instead of another possible answer $$[2 .. 3]$$ For $$A = [1, -1, 2]$$, it'll always return $$[1 .. 3]$$ instead of another possible answer $$[3 .. 3]$$ Whereas recursive implementation will always return the second ones. You can play with such cases and compare with recursive implementation in the [next exercise]({% link _solutions/04/E04.01-03.md %}){:target='_blank'}. {% endcapture %} {% include aside.html title='Did you notice?' %} #### Python implementation {% include code/code.html file='code/04/code_E040102.py' %}
Shell
UTF-8
390
2.65625
3
[ "MIT" ]
permissive
#!/bin/bash # # Customized i3lock with https://github.com/Lixxia/i3lock set -euo pipefail source "$HOME/.colors" i3lock="$HOME/repos/i3lock/i3lock" wallpaper="$HOME/.local/share/wallpaper.png" "$i3lock" \ --image "$wallpaper" \ --24 \ --ignore-empty-password \ --idle-color "$B_BASE06" \ --verify-color "$EMPHASIZED_CONTENT_COLOR" \ --wrong-color "$ERROR_COLOR"
Markdown
UTF-8
744
3.015625
3
[ "MIT" ]
permissive
# Задание к занятию «Методы математической оптимизации» ## 1. Массивы Существует массив `Z = [1,2,3,4,5,6,7,8,9,10,11,12,13,14]`, как из него создать массив `R = [[1,2,3,4], [2,3,4,5], [3,4,5,6], ...,[11,12,13,14]]`? ## 2. Матрица Дана произвольная матрица `A`. Рассчитать ранг матрицы `A`. ## 3. Опимизация Найти лучший алгоритм для решения следующей задачи: ``` min(x1x4(x1+x2+x3)+x3) ``` Условия: ``` x1x2x3x4≥30 x1^2+x2^2+x3^2+x4^2=60 2≤x1,x2,x3,x4≤6 ``` Начальное приближение: ``` x=(1,5,5,1) ```
Java
UTF-8
1,019
2.078125
2
[ "Apache-2.0" ]
permissive
package com.sdl.web.spring.configuration; import com.sdl.dxa.DxaModelServiceApplication; import org.junit.Test; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ModelServiceContainerConfigurationTest { @Test public void shouldHaveServiceContainerConfiguration_InRightPackageByConvention() { //then assertEquals("com.sdl.web.spring.configuration", ModelServiceContainerConfiguration.class.getPackage().getName()); assertTrue(ModelServiceContainerConfiguration.class.isAnnotationPresent(Configuration.class)); } @Test public void serviceContainerConfiguration_ImportsModelServiceConfiguration() { //given Class<?> value = ModelServiceContainerConfiguration.class.getAnnotation(Import.class).value()[0]; //then assertEquals(DxaModelServiceApplication.class, value); } }
Markdown
UTF-8
4,974
2.640625
3
[]
no_license
# Security perspective The security perspective guides you as you consider the set of processes and technologies that allow the owners of resources in the system to reliably control who can perform what actions on particular resources. The ability of the system to reliably control, monitor, and audit who can perform what actions on these resources and the ability to detect and recover from failures in security mechanisms ## Authentication and Authorization ### Authentication ![Figure 1: High-level overview of the authentication flow](../img/Authentication.png) Figure 1: High-level overview of the authentication flow Figure 1 shows the general flow of authentication for customer/client access over the internet. This flow is **not** used for direct communication to AWS resources. ### Cognito AWS offers a service called Cognito which we use here to handle our authentication needs. The flow described here is known as the [Authorization Code Grant](https://aws.amazon.com/blogs/mobile/understanding-amazon-cognito-user-pool-oauth-2-0-grants/). > Some clients don't support redirect handling (302 handling) natively or by default. This is a common cause of error/misunderstandings in development. Cognito has all the necessary forms built-in to use in your login, logout, profile, etc. screens. Styling can be applied to brand all screens. #### Settings - Make sure to use the User Pool setting in Cognito! - Allow _with username_ for login - Allow _verified e-mail address_ for login - Add attributes to the identity data: phone number, email. - Allow _openid_ scope - Set the load balancer's _scheme_ to _internet facing_ ### Federation Federation allows for other authentication providers to be hooked up to our systems. A practical example of this is giving the user the option to log in to *your system* using their google, Facebook, or other social media site login. The use of federation will immediately generate trust in your system with a large portion of potential users. > Support non-federated authentication too. Some people may either trust *your* site less than the federated authentication provider's (ie. Google). This may make them skeptical. To further support the availability of your own authentication provider, you should consider that users may want to use different passwords for different online services from a security perspective. ### Loadbalancer The design offered here uses the load balancer directly to provide authentication. The HTTPS Listener is used with a set of rules that provide actions for checking the identity of the user requesting the resource. Once this is done we use the load balancers' rule to forward the traffic to the appropriate scaling group. [Infrastructure Scaling and Balancing](./infrastructure/InfrastructureScalingAndBalancing.md)) ### Pricing Though the pricing of Cognito can be found on the pricing list on the AWS website, we would like to clarify one thing. The pricing of Cognito is based on unique users per month. Billing **does not** go up if a user logs in multiple times per month nor when they perform multiple requests. If a user doesn't log in or register during a month you will not be billed for that user. Please check [AWS Cognito pricing](https://aws.amazon.com/cognito/pricing/) for up-to-date information. ## Applicability to Views | View | Aspects of applicability | |------|---------| | Functional | Reveals which functional elements need to be protected. Functional structure may be impacted by the need to implement your security policies. | | Information | Reveals what data needs to be protected. Information models are often modified as a result of security design (e.g., partitioning information by sensitivity). | | Concurrency | Security design may indicate the need to isolate different pieces of the system into different runtime elements, so affecting the system’s concurrency structure. | | Development | Captures security related development guidelines and constraints. | | Deployment | May need major changes to accommodate security-oriented hardware or software, or to address security risks. | | Operational | Needs to make the security assumptions and responsibilities clear, so that these aspects of the security implementation can be reflected in operational processes. | ## Risks ## Checklist for Architecture Definition and further work - Have you addressed each threat identified in the threat model to the extent required? - Have you used as much third-party security technology as possible? - Have you produced an integrated overall design for the security solution? - Have you considered all standard security principles when designing the infrastructure? - Is your security infrastructure as simple as possible? - Have you defined how to identify and recover from security breaches? - Have you applied the results of the Security perspective to all the affected views? - Have external experts reviewed your security design?
C++
UTF-8
6,871
2.953125
3
[]
no_license
#ifndef h_db_chit #define h_db_chit #include "DBChitFwd.h" class db_chit_exception_t : public std::exception { public: db_chit_exception_t(); db_chit_exception_t(const db_chit_exception_t &initializer); virtual ~db_chit_exception_t() throw(); db_chit_exception_t &operator=(const db_chit_exception_t &rhs); virtual const char *what() const; }; /* db_chit_exception_t */ class chit_not_found_exception_t : public db_chit_exception_t { public: chit_not_found_exception_t(const chit_name_t &name); chit_not_found_exception_t(const chit_key_t key); chit_not_found_exception_t(const chit_not_found_exception_t &initializer); ~chit_not_found_exception_t() throw(); chit_not_found_exception_t &operator=( const chit_not_found_exception_t &rhs); const char *what() const; const chit_name_t &name() const; const chit_key_t key() const; private: chit_name_t name_; chit_key_t key_; }; /* chit_not_found_exception_t */ class chit_option_not_found_exception_t : public db_chit_exception_t { public: chit_option_not_found_exception_t(const chit_option_name_t &name); chit_option_not_found_exception_t(const chit_option_key_t option_key); chit_option_not_found_exception_t( const chit_option_not_found_exception_t &initializer); ~chit_option_not_found_exception_t() throw(); chit_option_not_found_exception_t &operator=( const chit_option_not_found_exception_t &rhs); const char *what() const; const chit_option_name_t &name() const; const chit_key_t option_key() const; private: chit_option_name_t name_; chit_option_key_t option_key_; }; /* chit_option_not_found_exception_t */ class db_chit_t { public: /* Get a chit's key by name. */ static const chit_key_t key(const chit_name_t &name); /* Get a chit's name by key. */ static const chit_name_t name(const chit_key_t key); /* Exception-free variants. */ static bool key(const chit_name_t &name, chit_key_t &key); static bool name(const chit_key_t key, chit_name_t &name); /* Get a list of all of the chits keys. */ static std::auto_ptr<chit_key_vector_t> keys(); /* Finds the keys for the associated names. */ static std::auto_ptr<chit_key_vector_t> keys( const chit_name_vector_t &names); /* Get a list of all chit names. */ static std::auto_ptr<chit_name_vector_t> names(); /* Finds the names for the associated keys. */ static std::auto_ptr<chit_name_vector_t> names( const chit_key_vector_t &keys); /* Creates a list of chit names with their associated keys. */ static std::auto_ptr<chit_name_key_vector_t> names_and_keys(); /* Returns a list of a chit's options in name-key form. */ static std::auto_ptr<chit_option_key_vector_t> option_keys( const chit_key_t key); static std::auto_ptr<chit_option_name_vector_t> option_names( const chit_key_t key); static std::auto_ptr<chit_option_name_key_vector_t> option_names_and_keys( const chit_key_t key); /* Translates an option's key to a name, */ static const chit_option_name_t option_name(const chit_option_key_t key); /* Translates an option's name to a key. */ static const chit_option_key_t option_key(const chit_key_t key, const chit_option_name_t &name); /* Creates a new chit in the database and returns it's key. */ static const chit_key_t add_chit( const std::wstring &default_menu, const std::wstring &mask, const chit_name_t &name, const EChitFormatType format_type, const EChitPromptType prompt_type, const bool is_default, const bool isHoldAndSendDisabled, const bool isNonChargableChit, const bool isDisplayTablesDisabled, const bool IsCaptureCustomerNameAndPhone, const bool IsAutoSaveOnTab, const bool IsCaptureCustomerDetails, const bool promptForPickUpDeliveryTime, const int inAddMinutes, const bool savecustomername, const bool savemembername, const bool savememberaddress, const bool onlinepickuporder, const bool onlinedeliveryorder); /* The same as above except that it'll also create and link options. */ static const chit_key_t add_chit( const std::wstring &default_menu, const std::wstring &mask, const chit_name_t &name, const chit_option_name_set_t &option_names, const EChitFormatType format_type, const EChitPromptType prompt_type, const bool is_default, const bool isHoldAndSendDisabled, const bool isNonChargableChit, const bool isDisplayTablesDisabled, const bool IsCaptureCustomerNameAndPhone, const bool IsAutoSaveOnTab, const bool IsCaptureCustomerDetails, const bool promptForPickUpDeliveryTime, const int inAddMinutes, const bool savecustomername, const bool savemembername, const bool savememberaddress, const bool onlinepickuporder, const bool onlinedeliveryorder); static void update_chit( const chit_key_t key, const std::wstring &default_menu, const std::wstring &mask, const chit_name_t &name, const chit_option_name_set_t &options_to_be_added, const chit_option_name_set_t &options_to_be_deleted, const chit_option_rename_map_t &options_to_be_renamed, const EChitFormatType format_type, const EChitPromptType prompt_type, const bool is_default, const bool isHoldAndSendDisabled, const bool isNonChargableChit, const bool isDisplayTablesDisabled, const bool IsCaptureCustomerNameAndPhone, const bool IsAutoSaveOnTab, const bool IsCaptureCustomerDetails, const bool promptForPickUpDeliveryTime, const int inAddMinutes, const bool savecustomername, const bool savemembername, const bool savememberaddress, const bool onlinepickuporder, const bool onlinedeliveryorder); static void remove_chit(const chit_key_t key); /* Adds an option to a chit. */ static const chit_option_key_t add_option(const chit_key_t chit_key, const chit_option_name_t &name); /* The same but in bulk. */ static const chit_option_key_vector_t add_options( const chit_key_t chit_key, const chit_option_name_vector_t &names); /* Renames an existing option. */ static void rename_option(const chit_option_key_t option_key, const chit_option_name_t &new_option_name); /* Removes an option from a chit. */ static void remove_option(const chit_option_key_t option_key); private: static void ensure_chit_present(const chit_key_t key); static void ensure_option_present(const chit_option_key_t key); }; /* db_chit_t */ #endif /* h_db_chit */
TypeScript
UTF-8
1,547
3.09375
3
[]
no_license
import { expect } from "chai"; import { identity } from "../../src/identity"; import { mapBy } from "../../src/intermediates"; import { toArrayBy } from "../../src/consumables"; describe("intermediates::mapBy", () => { it("empty array returns empty array", () => { const items = []; const result = toArrayBy(mapBy(items, identity)(), identity); expect(result).to.be.deep.equals(items); }); it("should return a copied array", () => { const items = [3, 6, 5]; const result = toArrayBy(mapBy(items, identity)(), identity); expect(result).not.to.be.equals(items); }); it("identity reducer returns same element", () => { const items = [3, 6, 5]; const result = toArrayBy(mapBy(items, identity)(), identity); expect(result).to.be.deep.equals(items); }); it("transformation by index", () => { const items = [3, 6, 5]; const reducer = <T>(_: T, index: number) => index; const result = toArrayBy(mapBy(items, reducer)(), identity); expect(result).to.be.deep.equals([0, 1, 2]); }); it("linear transformation", () => { const items = [3, 6, 5]; const reducer = (item: number) => item * 3; const result = toArrayBy(mapBy(items, reducer)(), identity); expect(result).to.be.deep.equals([9, 18, 15]); }); it("transformation with index", () => { const items = [3, 6, 5]; const reducer = (item: number, index: number) => item * index; const result = toArrayBy(mapBy(items, reducer)(), identity); expect(result).to.be.deep.equals([0, 6, 10]); }); });
PHP
UTF-8
1,809
2.859375
3
[]
no_license
<?php class Pedido { private $codPedido; private $codCliente; private $tipo; private $dtEntrada; private $dtEmbarque; private $valorTotal; private $desconto; public function __construct($codPedido, $codCliente, $tipo, $dtEntrada, $dtEmbarque, $valorTotal, $desconto) { $this->codPedido = $codPedido; $this->codCliente = $codCliente; $this->tipo = $tipo; $this->dtEntrada = $dtEntrada; $this->dtEmbarque = $dtEmbarque; $this->valorTotal = $valorTotal; $this->desconto = $desconto; } public function getCodPedido() { return $this->codPedido; } public function setCodPedido($codPedido) { $this->codPedido = $codPedido; } public function getCodCliente() { return $this->codCliente; } public function setCodCliente($codCliente) { $this->codCliente = $codCliente; } public function getTipo() { return $this->tipo; } public function setTipo($tipo) { $this->tipo = $tipo; } public function getDtEntrada() { return $this->dtEntrada; } public function setDtEntrada($dtEntrada) { $this->dtEntrada = $dtEntrada; } public function getDtEmbarque() { return $this->dtEmbarque; } public function setDtEmbarque($dtEmbarque) { $this->dtEmbarque = $dtEmbarque; } public function getValorTotal() { return $this->valorTotal; } public function setValorTotal($valorTotal) { $this->valorTotal = $valorTotal; } public function getDesconto() { return $this->desconto; } public function setDesconto($desconto) { $this->desconto = $desconto; } }
JavaScript
UTF-8
646
2.796875
3
[ "MIT" ]
permissive
const slugify = require("slugify"); const { kebabCase, startCase, round } = require("lodash"); function toSlug(str) { return slugify(kebabCase(str)); } function toArray(param) { if (param && typeof param === "object") return Object.keys(param).map((key) => param[key]); return undefined; } function hasProperty(obj, prop) { return ( !!(obj && obj[prop]) || (obj instanceof Object && Object.prototype.hasOwnProperty.call(obj, prop)) ); } function hasMethod(obj, prop) { return hasProperty(obj, prop) && typeof obj[prop] === "function"; } module.exports = { round, startCase, toSlug, toArray, hasProperty, hasMethod };
JavaScript
UTF-8
650
2.859375
3
[ "MIT" ]
permissive
class Actor { constructor(x,y,radius) { this.preOffsetPosition = createVector(x,y); this.postOffsetPosition = createVector(x,y); this.radius = radius; this.radiusCopy = radius; this.isColliding = false; this.closestFood = null; this.closestFoodDist = Infinity; } checkCollision(object) { let distance = dist(this.postOffsetPosition.x,this.postOffsetPosition.y,object.postOffsetPosition.x,object.postOffsetPosition.y); this.closestFoodDist = min(distance,this.closestFoodDist); if(this.closestFoodDist==distance) this.closestFood = object; return distance < this.radius/2 + object.radius/2 } }
JavaScript
UTF-8
1,808
3.015625
3
[]
no_license
const handlebars = require('handlebars') handlebars.registerHelper('compare', function (lvalue, operator, rvalue, options) { if (arguments.length < 3) { throw new Error("Handlerbars Helper 'compare' needs 2 parameters"); } if (options === undefined) { options = rvalue; rvalue = operator; operator = "==="; } let operators = { '==': function (l, r) { return l == r; }, '===': function (l, r) { return l === r; }, '!=': function (l, r) { return l != r; }, '!==': function (l, r) { return l !== r; }, '<': function (l, r) { return l < r; }, '>': function (l, r) { return l > r; }, '<=': function (l, r) { return l <= r; }, '>=': function (l, r) { return l >= r; }, 'typeof': function (l, r) { return typeof l == r; } }; if (!operators[operator]) { throw new Error("Handlerbars Helper 'compare' doesn't know the operator " + operator); } const result = operators[operator](lvalue, rvalue); if (result) { return options.fn(this); } else { return options.inverse(this); } }); handlebars.registerHelper('inArray', function (val, arr, options) { arr = arr || []; var len = arr.length; var i; for (i = 0; i < len; i++) { if (arr[i] === val) { return options.fn(this); } } return options.inverse(this); }); handlebars.registerHelper('outArray', function (val, arr, options) { arr = arr || []; var len = arr.length; var i; for (i = 0; i < len; i++) { if (arr[i] === val) { return options.inverse(this); } } return options.fn(this); });
Python
UTF-8
5,146
2.625
3
[]
no_license
from myapp import app from myapp.decorators import login_required from myapp.library.models import Author, Book from myapp.library.forms import AuthorForm, BookForm from myapp.database import db_session from flask import render_template, redirect, request, url_for, flash @app.route('/') def index(): books_amount = Book.query.count() authors_amount = Author.query.count() return render_template('library/index.html', books_amount=books_amount, authors_amount=authors_amount) @app.route('/books/<id>/') @app.route('/books/') def view_book(id=None): error = None if id: book = Book.query.get(id) if not book: error = 'Sorry, we don\'t have the book with id {0}.'.format(id) return render_template('library/view_book.html', book=book, error=error) books = Book.query.all() return render_template('library/list_books.html', books=books) @app.route('/authors/<id>/') @app.route('/authors/') def view_author(id=None): error = None if id: author = Author.query.get(id) if not author: error = 'Sorry, we don\'t have the author with id {0}.'.format(id) return render_template('library/view_author.html', author=author, error=error) authors = sorted(Author.query.all(), key=lambda author: author.name.split()[-1]) return render_template('library/list_authors.html', authors=authors) @app.route('/authors/add/', methods=['GET', 'POST']) @login_required def add_author(): form = AuthorForm(request.form) if request.method == 'POST' and form.validate(): author = Author(form.name.data) db_session.add(author) db_session.commit() flash('The author was added to the Library.') return redirect(url_for('view_author', id=author.id)) return render_template('library/add_author.html', form=form) @app.route('/authors/<id>/edit/', methods=['GET', 'POST']) @login_required def edit_author(id): error = None author = Author.query.get(id) if not author: error = 'Sorry, we don\'t have the author with id {0}.'.format(id) form = AuthorForm(request.form, obj=author) if request.method == 'POST' and form.validate(): form.populate_obj(author) db_session.add(author) db_session.commit() return redirect(url_for('view_author', id=author.id)) return render_template('library/edit_author.html', form=form, author=author, error=error) @app.route('/authors/<id>/delete/', methods=['GET', 'POST']) @login_required def delete_author(id): error = None author = Author.query.get(id) if not author: error = 'Sorry, we don\'t have the author with id {0}.'.format(id) if request.method == 'POST': db_session.delete(author) db_session.commit() flash('The author and his books were deleted.') return redirect(url_for('view_author')) return render_template('library/delete_author.html', author=author, error=error) @app.route('/books/add/', methods=['GET', 'POST']) @login_required def add_book(): form = BookForm(request.form) form.authors.choices = sorted([(a.id, a.name) for a in Author.query.all()], key=lambda author: author[1].split()[-1]) if request.method == 'POST' and form.validate(): book = Book(form.name.data) for id in form.authors.data: book.authors.append(Author.query.get(id)) db_session.add(book) db_session.commit() flash('The book was added to the Library.') return redirect(url_for('view_book', id=book.id)) return render_template('library/add_book.html', form=form) @app.route('/books/<id>/edit/', methods=['GET', 'POST']) @login_required def edit_book(id): error = None book = Book.query.get(id) if not book: error = 'Sorry, we don\'t have the book with id {0}.'.format(id) form = BookForm(request.form, obj=book) form.authors.choices = sorted([(a.id, a.name) for a in Author.query.all()], key=lambda author: author[1].split()[-1]) if request.method == 'POST' and form.validate(): book.name = form.name.data book.authors = [] for id in form.authors.data: book.authors.append(Author.query.get(id)) db_session.add(book) db_session.commit() return redirect(url_for('view_book', id=book.id)) form.authors.data = [a.id for a in book.authors] return render_template('library/edit_book.html', form=form, book=book, error=error) @app.route('/books/<id>/delete/', methods=['GET', 'POST']) @login_required def delete_book(id): error = None book = Book.query.get(id) if not book: error = 'Sorry, we don\'t have the book with id {0}.'.format(id) if request.method == 'POST': db_session.delete(book) db_session.commit() flash('The book was deleted.') return redirect(url_for('view_book')) return render_template('library/delete_book.html', book=book, error=error)
C#
UTF-8
2,690
2.625
3
[]
no_license
using Social.Core.Entity; using Social.Core.Entity.Enums; using Social.Core.Service; using Social.Model.Context; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace Social.Service.Base { public class BaseService<T> : ICoreService<T> where T : CoreEntity { private readonly SocialContext _context; public BaseService(SocialContext context) { _context = context; } public bool Add(T model) { try { _context.Set<T>().Add(model); return Save() > 0; } catch (Exception) { return false; } } public bool Update(T model) { try { _context.Set<T>().Update(model); return Save() > 0; } catch (Exception) { return false; } } public bool Delete(T model) { try { _context.Set<T>().Remove(model); return Save() > 0; } catch (Exception) { return false; } } public bool Delete(int? id) { try { _context.Set<T>().Remove(_context.Set<T>().Find(id)); return Save() > 0; } catch (Exception) { return false; } } public bool Activate(int? id) { T model = GetById(id); model.Status = Status.Active; return Update(model); } public bool Passive(int? id) { T model = GetById(id); model.Status = Status.Passive; return Update(model); } public bool Any(Expression<Func<T, bool>> expression) => _context.Set<T>().Any(expression); public List<T> GetActive() => _context.Set<T>().Where(x => x.Status == Status.Active).ToList(); public List<T> GetPassive() => _context.Set<T>().Where(x => x.Status == Status.Passive).ToList(); public T GetByDefault(Expression<Func<T, bool>> exception) => _context.Set<T>().FirstOrDefault(exception); public T GetById(int? id) => _context.Set<T>().Find(id); public List<T> GetAll() => _context.Set<T>().ToList(); public List<T> GetDefaultList(Expression<Func<T, bool>> expression) => _context.Set<T>().Where(expression).ToList(); public int Save() => _context.SaveChanges(); } }
Python
UTF-8
6,584
3.21875
3
[]
no_license
class LinearRegression: @staticmethod def get_cofactor(arr, temp, p, q, n): i = 0 j = 0 for row in range(n): for col in range(n): if row != p and col != q: temp[i][j] = arr[row][col] j += 1 if j == n-1: j = 0 i += 1 def get_det(self, arr, n): D = 0 if n == 1: return arr[0][0] temp = [] for i in range(N): temp.append([]) for j in range(N): temp[i].append([]) sign = 1 for f in range(n): self.get_cofactor(arr, temp, 0, f, n) D += sign * arr[0][f] * self.get_det(temp, n-1) sign = -sign return D def get_adjoint(self, arr, adj): if N == 1: adj[0][0] = 1 return temp = [] for i in range(N): temp.append([]) for j in range(N): temp[i].append([]) for i in range(N): for j in range(N): self.get_cofactor(arr, temp, i, j, N) sign = 1 if ((i + j) % 2 == 0) else -1 # adj[p][q] = sign * get_matrix_determinant(tmp) adj[j][i] = sign * self.get_det(temp, N-1) def get_matrix_inverse(self, arr, inverse): # determinant = get_matrix_determinant(m) determinant = self.get_det(arr, N) # special case for 2x2 matrix: # if len(arr) == 2: # return [[arr[1][1]/determinant, -1*arr[0][1]/determinant], # [-1*arr[1][0]/determinant, arr[0][0]/determinant]] # find matrix of co-factors adj = [] for i in range(N): adj.append([]) for j in range(N): adj[i].append([]) self.get_adjoint(arr, adj) for i in range(N): for j in range(N): inverse[i][j] = adj[i][j] / float(determinant) linear = LinearRegression() # x = '0, 1, 2, 3, 4' # y = '1, 1.8, 3.3, 4.5, 6.3' # y = '-4, -1, 4, 11, 20' # x = '1, 2, 3, 4' # y = '6, 11, 18, 27' # x = '1, 2, 3, 4, 5, 6' # y = '1200, 900, 600, 200, 110, 50' # x = '71, 68, 73, 69, 67, 65, 66, 67' # y = '69, 72, 70, 70, 68, 67, 68, 64' # x = '-1, 0, 1, 2' # y = '2, 5, 3, 0' # x = '1, 2, 3, 4, 5, 6, 7, 8, 9' # y = '2, 6, 7, 8, 10, 11, 11, 10, 9' # x = '1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937' # y = '352, 356, 357, 358, 360, 361, 361, 360, 359' # y = '1, 1.8, 1.3, 2.5, 6.3' # x = '1, 2, 3, 4, 5, 6, 7, 8, 9, 10' # y = '7.5, 44.31, 60.8, 148.97, 222.5, 262.64, 289.06, 451.53, 439.62, 698.88' x = '1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, ' \ '31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, ' \ '59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, ' \ '87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, ' \ '112, 113, 114, 115, 116, 117, 118, 119, 120 ' y = '7.50, 44.31, 60.80, 148.97, 225.50, 262.64, 289.06, 451.53, 439.62, 698.88, 748.24, 896.46, 1038.78, 1214.04, '\ '1377.08, 1579.86, 1763.14, 1993.92, 2196.96, 2456.22, 2678.54, 2966.76, 3207.88, 3525.54, 3784.98, 4132.56, ' \ '4409.84, 4787.82, 5082.46, 5491.32, 5802.84, 6243.06, 6570.98, 7043.04, 7386.88, 7891.26, 8250.54, 8787.72, ' \ '9161.96, 9732.42, 10121.14, 10725.36, 11128.08, 11766.54, 12182.78, 12855.96, 13285.24, 13993.62, 14435.46, ' \ '15179.52, 15633.44, 16413.66, 16879.18, 17696.04, 18172.68, 19026.66, 19513.94 ,20405.52, 20902.96, 21832.62, ' \ '22339.74, 23307.96, 23824.28, 24831.54, 25356.58, 26403.36, 26936.64, 28023.42, 28564.46, 29691.72, 30240.04, ' \ '31408.26, 31963.38, 33173.04, 33734.48, 34986.06, 35553.34, 36847.32, 37419.96, 38756.82, 39334.34, 40714.56, ' \ '41296.48, 42720.54, 43306.38, 44774.76, 45364.04, 46877.22, 47469.46, 49027.92, 49622.64, 51226.86, 51823.58, ' \ '53474.04, 54072.28, 55769.46, 56368.74, 58113.12, 58712.96, 60505.02, 61104.94, 62945.16, 63544.68, 65433.54, ' \ '66032.18, 67970.16, 68567.44, 70555.02, 71150.46, 73188.12, 73781.24, 75869.46, 76459.78, 78599.04, 79186.08, ' \ '81376.86, 81960.14, 84202.92, 84781.96, 87077.22 ' degree_of_x: int = 2 independentInputArray = x.split(',') dependentInputArray = y.split(',') sigma_X = [] sigma_XY = [] x_count = 1 while x_count <= degree_of_x * 2: temp = 0 for x in independentInputArray: temp = temp + pow(float(x), x_count) sigma_X.append(temp) x_count += 1 y_count = 0 while y_count <= degree_of_x: temp = 0 number_of_x = 0 for y in dependentInputArray: temp = temp + float(y) * (pow(float(independentInputArray[number_of_x]), y_count)) number_of_x = number_of_x + 1 sigma_XY.append(temp) y_count += 1 arr = [] sigma_X.insert(0, float(len(independentInputArray))) for i in range(degree_of_x + 1): temp = [] for j in range(degree_of_x + 1): temp.append(sigma_X[j + i]) arr.append(temp) N = degree_of_x + 1 adj = [] inverse = [] for i in range(N): adj.append([]) inverse.append([]) for j in range(N): adj[i].append([]) inverse[i].append([]) sigma_XY_Transpose = [] for i in range(N): sigma_XY_Transpose.append([]) for j in range(1): sigma_XY_Transpose[i].append(0) for i in range(N): sigma_XY_Transpose[i][0] = sigma_XY[i] print('\n Transpose of different sigma xy \n') for transpose in sigma_XY_Transpose: print(transpose) print('\n') print('\n Array after finding and putting x and y values in equations \n') for a in arr: print(a) print('\n') linear.get_adjoint(arr, adj) print('\n Array Adjoint \n') for adjoint in adj: print(adjoint) print('\n') linear.get_matrix_inverse(arr, inverse) print('\n Inverse of Array after finding x and y values \n') for inv in inverse: print(inv) print('\n') result = [] for i in range(N): result.append([]) for j in range(1): result[i].append(0) for i in range(len(inverse)): for j in range(len(sigma_XY_Transpose[0])): for k in range(len(sigma_XY_Transpose)): result[i][j] += inverse[i][k] * sigma_XY_Transpose[k][j] variable_count = 0 for res in result: print('printing \u03B2', variable_count, ' = ', res) variable_count += 1
Java
UTF-8
2,240
2.0625
2
[]
no_license
package com.celik.gokhun.burgerfinder; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import android.Manifest; import android.content.DialogInterface; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { public final static int PERMISSION_REQUEST_CODE = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); requestLocationPermissions(); startLocation(); } public void startLocation(){ startService(new Intent(MainActivity.this, LocationService.class)); } public void jump(View view){ startActivity(new Intent(MainActivity.this, MapsActivity.class)); } private void requestLocationPermissions() { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) & ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) ) { new android.app.AlertDialog.Builder(this) .setTitle("Permission needed").setMessage("This permission needed because of this and that").setPositiveButton("ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_CODE); } }).setNegativeButton("cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int i) { dialog.dismiss(); } }) .create().show(); } else { ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_CODE); } } }
Markdown
UTF-8
3,040
3.140625
3
[ "MulanPSL-2.0", "LicenseRef-scancode-mulanpsl-2.0-en", "LicenseRef-scancode-unknown-license-reference" ]
permissive
--- --- --- title: 43 宇宙是怎么来的? --- 宇宙是如何诞生的?有很多理论试图去回答这个问题,但目前全世界范围内,接受度最高的一种理论是:宇宙大爆炸理论(the Big Bang theory)。 所谓的宇宙大爆炸理论,讲的是宇宙诞生于130多亿年前的一场大爆炸,在大爆炸还没有发生的时候,万事万物都不存在,宇宙只是一个致密的几何奇点。爆炸发生时,时间、空间诞生并开始扩散,整个宇宙就像一锅热汤,能量密度极高。随着继续扩大,宇宙开始冷却,并在万有引力的作用下,星系天体开始形成,听着是不是很耳熟?这样看来,好像盘古开天地和上帝创世这两个东西方神话都还挺有道理的。 单看宇宙大爆炸理论,感觉还是有点漫无边际,那为什么它会被广泛接受呢?因为它有几个佐证。第一个佐证是哈勃定律。1929年,美国天文学家哈勃通过天文观测,发现所有星系都在远离我们,并且离我们越远的星系,远离我们的速度越快。由此哈勃推测出,宇宙一直在膨胀,越变越大。既然宇宙越变越大,就说明它以前比现在小。如果运用极限思维,推理到极致,就能大胆地猜测,宇宙一开始应该是一个大小无限接近于零的奇点。也就是说,宇宙大爆炸理论的模型确实跟我们对宇宙变化规律的观测结果是吻合的。 第二个佐证是宇宙微波背景辐射。20世纪60年代有两个美国工程师,彭齐亚斯和威尔逊(Penzias & Wilson),他们通过射电天文望远镜接收到了一个奇怪信号。这个信号的特点是,不论你把望远镜指向哪个方向,这个信号的强度都差不多,没有显著的变化。这说明该信号应当是从宇宙最深处传来的,否则应当有一个位置的信号是最强的。这个信号就是宇宙微波背景辐射。它的频率在微波范围内,并且在四面八方都有,是宇宙背景深处传来的信号,所以叫宇宙微波背景辐射。 既然宇宙微波背景辐射是从宇宙深处传来的,就可以理解为它是宇宙早期的信息,因为宇宙大爆炸早期的信息应当已经随着膨胀来到了宇宙边缘。但不要忘了,由于宇宙在膨胀,微波背景辐射的信号源,也就是宇宙边缘,是在飞速远离我们的。因此我们接收到的,来自宇宙边缘的信号应当是存在“多普勒红移”的。我们接收到的信号频率应当是降低了的,通过计算去反向推算出宇宙边缘发出信号的原频率,我们就能知道宇宙大爆炸之初是怎样一番光景了。果不其然,根据计算,这些信号的原频率很高,反推出来,宇宙早期确实是处在能量密度很高的状态,如一锅热汤一般,这就与宇宙大爆炸理论的描述相吻合。 宇宙的膨胀和宇宙微波背景辐射,就是宇宙大爆炸理论在全球范围内拥有很高接受度的主要原因。
Markdown
UTF-8
2,061
2.78125
3
[]
no_license
#### 费拉 https://jikipedia.com/definition/7505 指在古埃及文明没落之后,依然在尼罗河领域耕作的农民。反民主政治作家斯宾格勒在西方的没落中借用该词描述所有伟大文明没落之后的民族(如罗马之后的意大利,日不落帝国之后的英吉利) #### 费 拉 https://www.sohu.com/a/306315574_99922744 费拉源自阿拉伯语,本义是种植者、佃农、自耕农。引申为丧失武德,失去公民特征,以苟活为目的的散沙化民众,是人尽可欺的社会最底层,却有些不着边际的生存智慧。 ![](http://5b0988e595225.cdn.sohucs.com/images/20190407/0bdf83fef1514d1daef13765655e98b9.jpeg) 五四以来,追求科学与敏感词。我现在很讨厌有人提及敏感词。 譬如三年困难时期,以甘肃、河南、安徽、四川灾情最重。这四个省份,除甘肃本来地瘠民贫以外,其它三个省份,都是主要的产粮区,按地理气候的科学分析,悲剧不应该发生在这三个省份。就好像乌克兰本是大粮仓,本与灾荒无缘,却被斯大林饿死了四分之一的人口。古今中外,只要失去武德,奉好死不如赖活为人生最高智慧,从来都是任人宰割的羔羊。 马克思说东方人就像一个大麻袋里的土豆,忍气吞声,慈眉善目,彼此分散,无法组织,从而形成合力。 费拉和土豆都是来自西方的社会学理论,相对而言,中土有更为丰富的称谓:如孔子深恶痛绝的乡愿,李斯奉为圭臬的老鼠哲学,孙中山所说的一盘散沙,柏扬描绘的酱缸,乃至如今岁月静好的佛系。 按照雅斯贝尔斯的轴心理论,孔子是决定华族文明路径的思想巨人,他生活的春秋时代百花齐放、百家争鸣,是华族文明的发展最高峰。两千五百年以后,孔门子弟,虽西北边陲,也文胜于质,丧失武德。人口净流出的地方,它的结局是被一种组织能力更强的信仰收割,至于是否和平,那要看造化了。
Java
UTF-8
571
1.914063
2
[]
no_license
package com.arz.pmp.base.framework.commons; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Data; import javax.validation.Valid; import javax.validation.constraints.NotNull; /** * description 请求体信息 * * @author chen wei * @date 2019/11/11 */ @Data @ApiModel public class RestRequest<T> { private RestRequest() { } @ApiModelProperty("消息头部") @NotNull @Valid private RequestHeader header; @ApiModelProperty("内容") @Valid @NotNull private T body; }
Python
UTF-8
348
3.34375
3
[]
no_license
#coding: utf-8 # # criada uma classe # class Juros(): pass # # instancia da classe 'Juros' # juros = Juros() # # deinido uma funcao para o metodo atraves do lambda # juros.simples = lambda obj: obj.capital * obj.taxa * obj.periodo # # teste # juros.capital = 16000 juros.taxa = 0.04 juros.periodo = 4 assert 2560 == juros.simples(juros)
Java
UTF-8
1,606
2.140625
2
[ "MIT" ]
permissive
package org.innovateuk.ifs.publiccontent.service; import org.innovateuk.ifs.commons.rest.RestResult; import org.innovateuk.ifs.commons.service.BaseRestService; import org.innovateuk.ifs.competition.publiccontent.resource.PublicContentResource; import org.innovateuk.ifs.competition.publiccontent.resource.PublicContentSectionType; import org.springframework.stereotype.Service; /** * Implementation for public content rest calls. */ @Service public class PublicContentRestServiceImpl extends BaseRestService implements PublicContentRestService { private static final String PUBLIC_CONTENT_REST_URL = "/public-content/"; @Override public RestResult<PublicContentResource> getByCompetitionId(Long id) { return getWithRestResult(PUBLIC_CONTENT_REST_URL + "find-by-competition-id/" + id, PublicContentResource.class); } @Override public RestResult<Void> publishByCompetitionId(Long id) { return postWithRestResult(PUBLIC_CONTENT_REST_URL + "publish-by-competition-id/" + id, Void.class); } @Override public RestResult<Void> updateSection(PublicContentResource resource, PublicContentSectionType section) { return postWithRestResult(PUBLIC_CONTENT_REST_URL + "update-section/" + section.name() + "/" + resource.getId(), resource, Void.class); } @Override public RestResult<Void> markSectionAsComplete(PublicContentResource resource, PublicContentSectionType section) { return postWithRestResult(PUBLIC_CONTENT_REST_URL + "mark-section-as-complete/" + section.name() + "/" + resource.getId(), resource, Void.class); } }
Markdown
UTF-8
1,969
2.90625
3
[ "MIT" ]
permissive
# Settings ### `cozy.client.settings.diskUsage()` `cozy.client.settings.diskUsage` is used to known informations about the total used space on the cozy disk. It returns a promise of the document of the disk-usage of id `io.cozy.settings.disk-usage`, with attributes containing a `used` field a string of how many *bytes* are used on the disk. The `used` field is a string since the underlying data is an `int64` which may not be properly represented in javascript. ```javascript const usage = await cozy.client.settings.diskUsage() console.log(usage.attributes.used) ``` ### `cozy.client.settings.changePassphrase(oldPassphrase, newPassphrase)` `cozy.client.settings.changePassphrase` is used to change the passphrase of the current user. You must supply the currently used passphrase, as well as the new one. It simply returns a promise that will resolve if the change was successful. ### `cozy.client.settings.getInstance()` `cozy.client.settings.getInstance` returns a promise with informations about the current Cozy instance, such as the locale or the public name. See cozy-stack [documentation](https://docs.cozy.io/en/cozy-stack/settings/#response-3) for more details. ### `cozy.client.settings.updateInstance(instance)` `cozy.client.settings.updateInstance` is used to update informations about the current instance. `instance` is an object that should be based on to the one you receive from `cozy.settings.getInstance()`. It returns a promise with the updated instance information. ### `cozy.client.settings.getClients()` `cozy.client.settings.getClients` returns a promise for an array of registered clients. See the [cozy-stack documentation](https://docs.cozy.io/en/cozy-stack/settings/#response-5) for more details. ### `cozy.client.settings.deleteClientById('123')` `cozy.client.settings.deleteClientById` revokes the specified client from the instance. This method returns a promise that simply resolves if the revokation was successful.
Markdown
UTF-8
1,212
2.578125
3
[]
no_license
# Rent WebApi em C# que realiza um CRUD de endereços no SQLServer consumindo recursos da API do ViaCEP # Banco de Dados: SQLServer # Como executar o projeto: * Clone o repositório https://github.com/joaogbsilva/rent.git localmente * Abra o projeto e vá até o arquivo "appsettings.json" e ajuste o conteúdo da "ConnectionStrings" * Altere os parâmetros "Server" e se necessário altere também os parâmetros de conexão, como "User ID" e "Password" * Em seguida, verifique se a porta 44319 está disponível pois nossa aplicação web irá utilizá-la * Verifique se o serviço do SQLServer está ativo * Com o projeto aberto no VisualStudio, abra o terminal e execute o comando a seguir para criar o banco de dados: dotnet ef --startup-project ../RentWebMvc database update * Execute o comando: dotnet run * Execute o comando: npm install * Execute o comando: ng serve # Acessando a aplicação web * Acesse: http://localhost:44319 * Clique no botão "Novo Imóvel" * No campo CEP, basta digitar o CEP desejado que ao trocar de campo, automaticamente os outros campos serão preenchidos com os dados retornados da API ViaCep * Após o endereço inserido, será possível Editar, Visualizar e Excluir
Java
UTF-8
852
2.578125
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package editor.common; import Polyhedron.Vector3; import java.util.List; /** * Docasny model implementujici zakladni funkce * @author ggrrin_ */ public class TempModel implements IModel{ List<Integer> i; List<Vector3> v; /** * Inicializuje docasny model indexbufferem i a vertexBuferem v * @param i indexBuffer * @param v vertexByffer */ public TempModel(List<Integer> i, List<Vector3> v) { this.i = i; this.v = v; } @Override public List<Vector3> getVertexBuffer() { return v; } @Override public List<Integer> getIndexBuffer() { return i; } }
Java
UTF-8
540
3.15625
3
[]
no_license
package array; public class MyClass { int y; double x; @Override public String toString() { return "y: "+y+"\nx: "+x; } public static void main(String[] args) { // int x = 10; // String xx = String.valueOf(10); // System.out.println(xx); MyClass obj = new MyClass(); obj.y = 15; obj.x = 12.0; String c = "35"; System.out.println(Integer.getInteger(c)); // String objdata = obj.toString(); // System.out.println(obj.toString()); } }