language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
2,099
2.140625
2
[]
no_license
package be.kevinbaes.bap.webfluxr2dbc.persistence.config; import io.r2dbc.spi.ConnectionFactories; import io.r2dbc.spi.ConnectionFactory; import io.r2dbc.spi.ConnectionFactoryOptions; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.r2dbc.config.AbstractR2dbcConfiguration; import org.springframework.data.r2dbc.connectionfactory.R2dbcTransactionManager; import org.springframework.data.r2dbc.repository.config.EnableR2dbcRepositories; import org.springframework.transaction.ReactiveTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; import static io.r2dbc.spi.ConnectionFactoryOptions.*; @Configuration @EnableR2dbcRepositories(basePackages = {"be.kevinbaes.bap.webfluxr2dbc.persistence"}) @EnableTransactionManagement public class R2dbcConfiguration extends AbstractR2dbcConfiguration { private ConnectionFactoryProperties dataSourceProperties; public R2dbcConfiguration(ConnectionFactoryProperties dataSourceProperties) { this.dataSourceProperties = dataSourceProperties; } /** * The reactive equivalent of PlatformTransactionManager */ @Bean ReactiveTransactionManager transactionManager(ConnectionFactory connectionFactory) { return new R2dbcTransactionManager(connectionFactory); } /** * Uses the R2DBC ConnectionFactory discovery and passes all possible configuration properties * @return a driver specific connectionfactory */ @Override @Bean public ConnectionFactory connectionFactory() { return ConnectionFactories.get(ConnectionFactoryOptions.builder() .option(DRIVER, dataSourceProperties.getDriver()) .option(PROTOCOL, dataSourceProperties.getProtocol()) .option(HOST, dataSourceProperties.getHost()) .option(PORT, dataSourceProperties.getPort()) .option(USER, dataSourceProperties.getUsername()) .option(PASSWORD, dataSourceProperties.getPassword()) .option(DATABASE, dataSourceProperties.getDatabase()) .build()); } }
Python
UTF-8
14,995
2.65625
3
[]
no_license
from selenium import webdriver #pip install selenium import random import time import fire #pip install fire import colorama #pip install colorama from colorama import Fore, Back, Style colorama.init() start_time = time.time() driver = webdriver.Firefox() # Firefox, Chrome count_s = 0; count_f = 0; count_b = 0; driver.get("http://www.sharelane.com/cgi-bin/main.py") print(driver.title) # ---------- REGISTRATION ---------- def registration(debug = ''): global count_s, count_f driver.get("http://www.sharelane.com/cgi-bin/main.py") driver.get("http://www.sharelane.com/cgi-bin/register.py") driver.find_element_by_xpath("//input[@name='zip_code']").send_keys("12345") driver.find_element_by_xpath("//input[@value='Continue']").click() driver.find_element_by_xpath("//input[@name='first_name']").send_keys("qwerty") randint = str(random.randint(1, 999999) + random.randint(1, 999999)) driver.find_element_by_xpath("//input[@name='email']").send_keys("qwerty" + randint +"@gmail.com") password = '123456'; driver.find_element_by_xpath("//input[@name='password1']").send_keys(password) driver.find_element_by_xpath("//input[@name='password2']").send_keys(password) driver.find_element_by_xpath("//input[@value='Register']").click() confirmation_message = driver.find_element_by_css_selector(".confirmation_message"); if(confirmation_message.text == 'Account is created!'): if(debug == ''): count_s += 1 print('') print('Registration: Successful') else: if(debug == ''): count_f += 1 print('') print('Registration: Failed') # ---------- END REGISTRATION ---------- # ---------- LOGIN ---------- def login(debug = ''): global count_s, count_f reg_email = driver.find_element_by_css_selector(".form_all_underline > tbody:nth-child(1) > tr:nth-child(6) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(4) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(2) > b:nth-child(1)") reg_pass = driver.find_element_by_css_selector(".form_all_underline > tbody:nth-child(1) > tr:nth-child(6) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(4) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2)") list = [reg_email.text, reg_pass.text]; driver.get("http://www.sharelane.com/cgi-bin/main.py") driver.find_element_by_xpath("//input[@name='email']").send_keys(list[0]) driver.find_element_by_xpath("//input[@name='password']").send_keys(list[1]) driver.find_element_by_xpath("//input[@value='Login']").click() #------get cookie------ cookies_list = driver.get_cookies() cookies_dict = {} for cookie in cookies_list: cookies_dict[cookie['name']] = cookie['value'] #---------------------- if(cookies_dict['email'] == '"' + list[0] + '"'): if(debug == ''): count_s += 1 print('') print('Login: Successful') else: if(debug == ''): count_f += 1 print('') print('Login: Failed') # ---------- END LOGIN ---------- # ---------- SEARCHING BY AUTHOR ---------- def searching_by_author(num, debug = ''): global count_s, count_f print('') print('searching by author testing...') driver.get("http://www.sharelane.com/cgi-bin/main.py") count_books = 0 i = 1; while(i <= num): name_author = driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(1) > p:nth-child(1) > b:nth-child(1)').text driver.find_element_by_css_selector(".form_all_underline > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(1) > form:nth-child(1) > input:nth-child(1)").send_keys(name_author) driver.find_element_by_xpath("//input[@value='Search']").click() try: name_author1 = driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1) > table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(2) > p:nth-child(1) > b:nth-child(1)').text print(name_author + ' - ' + name_author1) if(name_author == name_author1): count_books = count_books + 1 else: print('Error') except: print(Fore.RED + "Match wasn't found" + Style.RESET_ALL) i += 1 driver.get("http://www.sharelane.com/cgi-bin/main.py") print('---' + str(count_books) + ' matches of ' + str(num) + '---') #checkout if(count_books == (i - 1)): if(debug == ''): count_s += 1 print('Searching by author: Successful') else: if(debug == ''): count_f += 1 print('Searching by author: Failed') # ---------- END SEARCHING BY AUTHOR ---------- # ---------- SEARCHING BY TITLE ---------- def searching_by_title(num, debug = ''): global count_s, count_f print('') print('searching by title testing...') driver.get("http://www.sharelane.com/cgi-bin/main.py") count_books = 0 i = 1; while(i <= num): name_book = driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(1) > a:nth-child(1)').text driver.find_element_by_css_selector(".form_all_underline > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(1) > form:nth-child(1) > input:nth-child(1)").send_keys(name_book) driver.find_element_by_xpath("//input[@value='Search']").click() name_book1 = driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1) > table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(2) > p:nth-child(2)').text if(name_book == name_book1): count_books = count_books + 1 print(name_book + ' - ' + name_book1) else: print(Fore.RED + (name_book + ' - ' + name_book1) + Style.RESET_ALL) i += 1 driver.get("http://www.sharelane.com/cgi-bin/main.py") print('---' + str(count_books) + ' matches of ' + str(num) + '---') #checkout if(count_books == (i - 1)): if(debug == ''): count_s += 1 print('Searching by title: Successful') else: if(debug == ''): count_f += 1 print('Searching by title: Failed') # ---------- END SEARCHING BY TITLE ---------- # ---------- ADDING TO CART ---------- def adding_one_book_to_cart(debug = ''): global count_s, count_f def _add_one_book(): global name_book1, name_book2 driver.get("http://www.sharelane.com/cgi-bin/main.py") driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(1) > a:nth-child(1)').click() name_book1 = driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(2) > p:nth-child(1) > b:nth-child(1)').text driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(2) > p:nth-child(2) > a:nth-child(1)').click() driver.get("http://www.sharelane.com/cgi-bin/shopping_cart.py") name_book2 = driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(1)').text driver.get("http://www.sharelane.com/cgi-bin/main.py") cookies = driver.get_cookies() # returns list of dicts login_status = False if cookies: login_status = True if login_status: _add_one_book() else: registration() login() _add_one_book() if(name_book1 == name_book2): if(debug == ''): count_s += 1 print('') print('Adding to cart one book: Successful') else: if(debug == ''): count_f += 1 print('') print('Adding to cart one book: Failed') # ---------- END ADDING TO CART ---------- # ---------- ADDING TO CART SEVERAL BOOKS ---------- def adding_multiple_items_to_cart(): global count_b count_b += 1 print('') print('Adding multiple items to cart: Blocked') # ---------- END ADDING TO CART ---------- # ---------- UPDATE CART ---------- def update_cart(amount, debug = ''): global count_s, count_f driver.get("http://www.sharelane.com/cgi-bin/shopping_cart.py") am = driver.find_element_by_xpath("//input[@name='q']") am.clear() am.send_keys(amount) driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(4) > td:nth-child(1) > input:nth-child(1)').click() amount1 = driver.find_element_by_xpath("//input[@name='q']").get_attribute("value") if(int(amount1) == int(amount)): if(debug == ''): count_s += 1 print('') print('Update cart: Successful') else: if(debug == ''): count_f += 1 print('') print('Update cart: Failed') # ---------- END ADDING TO CART ---------- # ---------- CLEAR CART ---------- def clear_cart(): global count_s, count_f, count_b driver.get("http://www.sharelane.com/cgi-bin/shopping_cart.py") count_b += 1 print('') print('Clear cart: Blocked') # ---------- END CLEAR CART ---------- # ---------- CHECKOUT ---------- def checkout(debug = ''): global count_s, count_f driver.get("https://www.sharelane.com/cgi-bin/get_credit_card.py?type=1") credit_card_number = driver.find_element_by_css_selector('body > center:nth-child(1) > table:nth-child(6) > tbody:nth-child(1) > tr:nth-child(1) > td:nth-child(1) > center:nth-child(1) > table:nth-child(2) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2) > span:nth-child(1) > b:nth-child(1)').text #print(credit_card_number) driver.get("http://www.sharelane.com/cgi-bin/shopping_cart.py") driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1) > form:nth-child(1) > input:nth-child(1)').click() driver.find_element_by_name("card_number").send_keys(credit_card_number) driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(3) > td:nth-child(2) > table:nth-child(4) > tbody:nth-child(2) > tr:nth-child(10) > td:nth-child(2) > input:nth-child(1)').click() msg = driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(1) > p:nth-child(1) > font:nth-child(1) > b:nth-child(1)') if(msg): if(debug == ''): count_s += 1 print('') print('Checkout: Successful') else: if(debug == ''): count_f += 1 print('') print('Checkout: Failed') # ---------- END CHECKOUT ---------- # ---------- LOGOUT ---------- def logout(debug = ''): global count_s, count_f driver.get("http://www.sharelane.com/cgi-bin/main.py") cookies = driver.get_cookies() # returns list of dicts if cookies: driver.find_element_by_css_selector('tr.grey_bg:nth-child(3) > td:nth-child(1) > a:nth-child(1)').click() count_s += 1 if(debug == ''): print('') print('Logout: Successful') else: count_f += 1 if(debug == ''): print('') print('Logout: Failed') # ---------- END LOGOUT ---------- # ---------- DISCOUNT TEST ---------- def discount(num1, num2): registration('n') login('n') adding_one_book_to_cart('n') am = driver.find_element_by_xpath("//input[@name='q']") am.clear() print('') print('Scanning for bugs in discount...') #i = num1 while(num1 <= num2): driver.get("http://www.sharelane.com/cgi-bin/shopping_cart.py") am = driver.find_element_by_xpath("//input[@name='q']") am.clear() am.send_keys(num1) driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(5) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(4) > td:nth-child(1) > input:nth-child(1)').click() quantity = driver.find_element_by_xpath("//input[@name='q']").get_attribute("value") discount = driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(6) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(5) > p:nth-child(1) > b:nth-child(1)').text c = driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(6) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(7)').text price = driver.find_element_by_css_selector('.form_all_underline > tbody:nth-child(1) > tr:nth-child(6) > td:nth-child(1) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(4)').text first = (int(quantity) * float(price)) second = (int(quantity) * (float(price) * int(discount))/100) exp_total = str( first - second ) #print(str(quantity) + ' - ' + str(discount) + ' % --- ' + str( first - second ) + ' - ' + str(c)) if(int(quantity) == 1): print('quantity '+ str(quantity) + ' -- ' + 'discount ' + str(discount) + ' % --- ' + 'expected total ' + exp_total + ' --- ' +'actual total ' + str(c)) elif(int(quantity) > 1 and int(quantity) < 10): print('quantity '+ str(quantity) + ' -- ' + 'discount ' + str(discount) + ' % --- ' + 'expected total ' + exp_total + ' -- ' +'actual total ' + str(c)) elif(int(quantity) == 10 and float(exp_total) < 100): print('quantity '+ str(quantity) + ' - ' + 'discount ' + str(discount) + ' % --- ' + 'expected total ' + exp_total + ' -- ' +'actual total ' + str(c)) else: print('quantity '+ str(quantity) + ' - ' + 'discount ' + str(discount) + ' % --- ' + 'expected total ' + exp_total + ' - ' +'actual total ' + str(c)) num1 += 1 #------------END DISCOUNT TEST----------- #------------PRINT TOTAL----------- def print_total(): print('') print('-------------------------------------------') print('TOTAL: Successful ' + str(count_s) + ', Failed ' + str(count_f) + ', Blocked ' + str(count_b)) print('-------------------------------------------') #print('') #print("--- %s seconds ---" % (time.time() - start_time)) t = time.time() - start_time print("-------------- "+ str(round(t, 1)) +" seconds --------------") print('-------------------------------------------') #------------END PRINT TOTAL----------- # ---------- FULL TEST ---------- def full_test(): registration() login() searching_by_author(5) searching_by_title(20) adding_one_book_to_cart() adding_multiple_items_to_cart() update_cart(5) checkout() clear_cart() logout() print_total() #-------------------------------- if __name__ == '__main__': fire.Fire()
JavaScript
UTF-8
2,803
2.546875
3
[]
no_license
//hackerrank.js code converted into async await let puppeteer = require("puppeteer"); let mail = "sehox56004@mtlcz.com"; let password="789456123"; let {answers} = require("./ans"); let browserObj = puppeteer.launch({ defaultViewport: null, headless: false, args : [ '--start-maximized'] }); let page, browser; (async function fn(){ try{ browser = await browserObj; page = await browser.newPage(); await page.goto("https://www.hackerrank.com/auth/login"); await page.waitForSelector('.ui-tooltip-wrapper input[id="input-1"]', {visible:true}); await page.type('.ui-tooltip-wrapper input[id="input-1"]', mail); await page.type('.ui-tooltip-wrapper input[id="input-2"]', password); await page.click('button.ui-btn.ui-btn-large.ui-btn-primary.auth-button.ui-btn-styled'); await page.waitForSelector('.topic-card a[data-attr1="algorithms"]', {visible:true}); await page.click('.topic-card a[data-attr1="algorithms"]'); await page.waitForSelector('.checkbox-wrap input[value="warmup"]', {visible:true}); await page.click('.checkbox-wrap input[value="warmup"]'); await page.waitForSelector(".ui-btn.ui-btn-normal.primary-cta.ui-btn-line-primary.ui-btn-styled", {visible:true}); let quesArr = await page.$$(".ui-btn.ui-btn-normal.primary-cta.ui-btn-line-primary.ui-btn-styled", {delay:100}); // console.log(quesArr.length); // for(let i=0; i<answers.length; i++){ console.log("29"+quesArr[1]); await solveQues(page, quesArr[0], answers[0]); // } } catch(err){ console.log(err); } })(); (async function solveQues(page, quesSelector, answer){ try{ console.log("41"+quesSelector); await page.waitForSelector(quesSelector, {visible:true}); await quesSelector.click(); await page.waitForSelector(".monaco-editor.no-user-select.vs", {visible:true}); await page.click(".monaco-editor.no-user-select.vs"); await page.waitForSelector(".checkbox-input", {visible:true}); await page.click(".checkbox-input"); await page.waitForSelector("textarea.custominput", {visible:true}); await page.type("textarea.custominput", answer, { delay: 10 }); await page.keyboard.down("Control"); await page.keyboard.press("A",{ delay: 100 }); await page.keyboard.press("X",{ delay: 100 }); await page.keyboard.up("Control"); await page.waitForSelector(".monaco-editor.no-user-select.vs", {visible:true}); await page.click(".monaco-editor.no-user-select.vs"); await page.keyboard.down("Control"); await page.keyboard.press("A",{ delay: 100 }); await page.keyboard.press("V",{ delay: 100 }); await page.keyboard.up("Control"); page.click(".hr-monaco__run-code", { delay: 50 }); } catch(err){ console.log(err); } })();
Java
UTF-8
3,183
2.078125
2
[ "Apache-2.0" ]
permissive
/* * JBoss, Home of Professional Open Source * Copyright 2012, Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * 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 org.jboss.weld.bootstrap.events; import java.lang.reflect.Type; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.jboss.weld.event.ObserverNotifier; import org.jboss.weld.executor.DaemonThreadFactory; import org.jboss.weld.util.reflection.ParameterizedTypeImpl; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; /** * Allows observer methods for container lifecycle events to be resolved upfront while the deployment is waiting for classloader * or reflection API. * * @author Jozef Hartinger * */ public class ContainerLifecycleEventPreloader { private class PreloadingTask implements Callable<Void> { private final Type type; public PreloadingTask(Type type) { this.type = type; } @Override public Void call() throws Exception { notifier.resolveObserverMethods(type); return null; } } private final ExecutorService executor; private final ObserverNotifier notifier; public ContainerLifecycleEventPreloader(int threadPoolSize, ObserverNotifier notifier) { this.executor = Executors.newFixedThreadPool(threadPoolSize, new DaemonThreadFactory(new ThreadGroup("weld-preloaders"), "weld-preloader-")); this.notifier = notifier; } /** * In multi-threaded environment we often cannot leverage multiple core fully in bootstrap because the deployer * threads are often blocked by the reflection API or waiting to get a classloader lock. While waiting for classes to be loaded or * reflection metadata to be obtained, we can make use of the idle CPU cores and start resolving container lifecycle event observers * (extensions) upfront for those types of events we know we will be firing. Since these resolutions are cached, firing of the * lifecycle events will then be very fast. * */ @SuppressFBWarnings(value = "RV_RETURN_VALUE_IGNORED_BAD_PRACTICE", justification = "We never need to synchronize with the preloader.") void preloadContainerLifecycleEvent(Class<?> eventRawType, Type... typeParameters) { executor.submit(new PreloadingTask(new ParameterizedTypeImpl(eventRawType, typeParameters, null))); } void shutdown() { if (!executor.isShutdown()) { executor.shutdownNow(); } } }
Java
UTF-8
7,746
1.6875
2
[ "BSD-3-Clause" ]
permissive
/* * [New BSD License] * Copyright (c) 2011-2022, Brackit Project Team <info@brackit.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Brackit Project Team nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.brackit.query.function; import io.brackit.query.ErrorCode; import io.brackit.query.QueryContext; import io.brackit.query.Tuple; import io.brackit.query.atomic.Atomic; import io.brackit.query.atomic.IntNumeric; import io.brackit.query.atomic.QNm; import io.brackit.query.jdm.*; import io.brackit.query.jdm.json.Array; import io.brackit.query.jdm.json.Object; import io.brackit.query.jdm.type.Cardinality; import io.brackit.query.jdm.type.ItemType; import io.brackit.query.jdm.type.SequenceType; import io.brackit.query.module.StaticContext; import io.brackit.query.sequence.FunctionConversionSequence; import io.brackit.query.sequence.ItemSequence; import io.brackit.query.util.ExprUtil; import io.brackit.query.QueryException; import io.brackit.query.compiler.Bits; import org.magicwerk.brownies.collections.GapList; /** * @author Johannes Lichtenberger */ public class DynamicFunctionExpr implements Expr { private final StaticContext sctx; private final Expr functionExpr; private final Expr[] arguments; public DynamicFunctionExpr(StaticContext sctx, Expr function, Expr... exprs) { this.sctx = sctx; this.functionExpr = function; this.arguments = exprs; } @Override public Sequence evaluate(QueryContext ctx, Tuple tuple) { final var functionItem = functionExpr.evaluateToItem(ctx, tuple); final var argumentsSize = arguments.length; if (functionItem instanceof Array array) { if (argumentsSize == 0) { final var it = array.iterate(); final var buffer = new GapList<Item>(array.len()); Item item; while ((item = it.next()) != null) { buffer.add(item); } return new ItemSequence(buffer.toArray(new Item[0])); } if (argumentsSize == 1) { final var indexItem = arguments[0].evaluateToItem(ctx, tuple); if (!(indexItem instanceof IntNumeric)) { throw new QueryException(ErrorCode.ERR_TYPE_INAPPROPRIATE_TYPE, "Illegal operand type '%s' where '%s' is expected", indexItem.itemType(), Type.INR); } final int index = ((IntNumeric) indexItem).intValue(); return array.at(index); } // TODO / FIXME throw new QueryException(new QNm("")); } if (functionItem instanceof Object object) { if (argumentsSize == 0) { final var names = object.names(); final var buffer = new GapList<Item>(names.len()); for (int i = 0; i < names.len(); i++) { buffer.add(names.at(i).evaluateToItem(ctx, tuple)); } return new ItemSequence(buffer.toArray(new Item[0])); } if (argumentsSize == 1) { final var fieldItem = arguments[0].evaluateToItem(ctx, tuple); return getSequenceByObjectField(object, fieldItem); } // TODO / FIXME throw new QueryException(new QNm("")); } if (functionItem instanceof Function function) { int pos = 0; for (Sequence sequence : tuple.array()) { if (sequence == functionItem) { break; } pos++; } final ItemType dftCtxItemType = function.getSignature().defaultCtxItemType(); final SequenceType dftCtxType; if (dftCtxItemType != null) { dftCtxType = new SequenceType(dftCtxItemType, Cardinality.One); } else { dftCtxType = null; } Sequence res; Sequence[] args; if (dftCtxType != null) { Item ctxItem = arguments[0].evaluateToItem(ctx, tuple); FunctionConversionSequence.asTypedSequence(dftCtxType, ctxItem, false); args = new Sequence[] { ctxItem }; } else { SequenceType[] params = function.getSignature().getParams(); args = new Sequence[arguments.length + pos]; for (int i = 0; i < pos; i++) { args[i] = tuple.get(i); } for (int i = 0; i < arguments.length; i++) { SequenceType sType = i < params.length ? params[i] : params[params.length - 1]; if (sType.getCardinality().many()) { args[pos + i] = arguments[i].evaluate(ctx, tuple); if (!sType.getItemType().isAnyItem()) { args[pos + i] = FunctionConversionSequence.asTypedSequence(sType, args[i], false); } } else { args[pos + i] = arguments[i].evaluateToItem(ctx, tuple); args[pos + i] = FunctionConversionSequence.asTypedSequence(sType, args[i], false); } } } try { res = function.execute(sctx, ctx, args); } catch (StackOverflowError e) { throw new QueryException(e, ErrorCode.BIT_DYN_RT_STACK_OVERFLOW, "Execution of function '%s' was aborted because of too deep recursion.", function.getName()); } if (function.isBuiltIn()) { return res; } res = FunctionConversionSequence.asTypedSequence(function.getSignature().getResultType(), res, false); return ExprUtil.materialize(res); } // TODO / FIXME throw new QueryException(new QNm("")); } private Sequence getSequenceByObjectField(Object object, Item itemField) { if (itemField instanceof QNm qNmField) { return object.get(qNmField); } else if (itemField instanceof IntNumeric intNumericField) { return object.value(intNumericField); } else if (itemField instanceof Atomic atomicField) { return object.get(new QNm(atomicField.stringValue())); } else { throw new QueryException(Bits.BIT_ILLEGAL_OBJECT_FIELD, "Illegal object itemField reference: %s", itemField); } } @Override public Item evaluateToItem(QueryContext ctx, Tuple tuple) { return ExprUtil.asItem(evaluate(ctx, tuple)); } @Override public boolean isUpdating() { return functionExpr.isUpdating(); } @Override public boolean isVacuous() { return false; } public String toString() { return functionExpr.toString(); } }
Java
UTF-8
349
3.359375
3
[]
no_license
public class Linear_String { public static void main(String[]args) { String[] list1 = {"mona","sona","hina","ritu","mahi","rohini"}; String result = "mahi"; for (int index=0;index<list1.length; index++) { if (list1[index].equals(result)){ System.out.println("result is found at" + index + " " + " " +"index position"); } } } }
Python
UTF-8
303
2.78125
3
[]
no_license
class PlaylistInfo: def __init__(self, id, title, duration): self.id = id self.title = title self.duration = duration def getId(self): return self.id def getTitle(self): return self.title def getDuration(self): return self.duration
Markdown
UTF-8
8,711
3.5625
4
[]
no_license
--- title: Tags Organized by Count (Size) category: Coding tags: Jekyll Liquid author: Josh --- Jekyll is blog-aware and it runs on Liquid (plus Markdown, HTML, CSS, etc.). Liquid is a templating language, not a fully-fledged programming language. Jekyll+Liquid can make a great website/blog, but sometimes things to a little haywire. Making a complex array, that is, an array with an array in it or (an array where elements have attributes) simply isn't possible in Liquid. Liquid can *handle* such arrays (use all the YAML and JSON files you want in yout \_data files), and it can even make those kinds of arrays *on its own* (we'll get to that), but **you** can't make those arrays with Liquid. And this stands in the way of organizing tags on your blog by post count. ## Categories Versus Tags Jekyll is automatically aware of categories and tags, things most blogs have. You can label all of your posts from the get-go, and Jekyll will know what to do with them. By design, categories are similar to folders in which posts are filed, and tags are sticky-notes you can attach to the posts, noting the more-specific topic or, importantly, topic***s***. Other people who use Jekyll have wanted multiple categories or to only use tags instead, and by all means, you do you, but the default setup is already a problem. ## Posts Served by Tags or Categories With a few quick lines of code, you can pull together groups of posts that are connected by category or tag, which, obviously you should be able to. It's one of the first things people do when they start a blog, and [they even tell you exactly how to do this on the Jekyll website](https://jekyllrb.com/docs/posts/#tags-and-categories): {% highlight liquid %}{% raw %}{% for tag in site.tags %} <h3>{{ tag[0] }}</h3> <ul> {% for post in tag[1] %} <li><a href="{{ post.url }}">{{ post.title }}</a></li> {% endfor %} </ul> {% endfor %}{% endraw %}{% endhighlight %} The same code works for categories if you just replace `tags` with `categories` above. It works because the built-in functionality of Jekyll creates a complex array out of the `site.tags` or `site.categories` variable. That is, each element in the array is an array where the first element is the tag (or category) name and the second is another array filled with the posts marked with that tag. Mathematically (not actually) this looks like: ``` { {"Bananas", {#, #, #} }, {"Zuchinis", {#, #, #, #} } } ``` You have four posts about zuchinis and only three about bananas. It's okay, we overplanted zuchinis in our pandemic apocalypse garden, too. In Liquid, you can even run this through a sort filter and it will sort by elements in the outermost array (or the first element in the arrays, one layer in), the tag/category. This alphabetizes the arrays by the tag/category. So Liquid is basically fine *dealing with* complex arrays, but you cannot create one. You can't `assign` an array to an array index position. Why is this important? ## Categories Organized by Count (Size) There may come a time when you want to indicate to your audience what you're into. Rather than simply telling them what you're into, you could demonstrate it by showing off what you like to write about. And you'd do that by creating a list of categories of your posts organized in descending order by which categories have the most posts. You're clearly into the things you write about most! Ahh, but how!? We literally just created a complex array that had all of the posts in an array right next to the category label (`site.categories`). You can find out the size of the post array by calling `site.categories[Zuchinis].size`, and you'd be forgiven for thinking that because you can get that information, you'd be set! If only you could organize that complex array by the *size* of the *second* element! Well, you can't. Luckily, you've limited yourself to only one category per post (very important), so there's an easy way around this: {% highlight liquid %}{% raw %}{% assign categoriesBySize = site.posts | group_by: "category" | sort: "size" | reverse %} {% for category in categoriesBySize limit:5 %} <span class="smaller">{{ category.size }} Posts</span><br /> <a href="{{ site.baseurl }}/blog/category/{{ category.name | slugify }}">{{ category.name }}</a><br /><br /> {% endfor %}{% endraw %}{% endhighlight %} Using another nifty filter that comes built in (`group_by`), you can create a complex array of your posts, categorized by their category **and** it even gives you the size of the post array *as an element* in the complex array. Mercifully, it also associates each position in the array with a name, so you can refer to it in a sort filter. Again, mathematically (not actually), this looks like: ``` { {name="Bananas", items={#, #, #}, size=3}, {name="Zuchinis", items={#, #, #, #}, size=4} } ``` If you sorted by `name` instead of `size`, you could use this as an alternative method for generating the list of posts by category in a more intuitive way (in my opinion, anyway). ## The Point It was very important, though, in the last section that you only had one category per post. The why is explained by tags. Say you had tagged the above posts variously as "breakfast", "dinner", "snack", and "baby". Those tags would pile up on a post about breakfast baby food, and instead of neatly separated `name` elements from the above array, your `name`s would also be arrays, like `name={"breakfast", "baby"}`. You would not be getting a list of posts with neatly separated tags, you'd be getting posts separated by all the *sets* of tags you used. It works as intended, it's just annoying. And you can't build your own complex array because, as discussed, Liquid can't do that. That's okay, though, really. The language wasn't *designed* to do this, so the fact that it can't shouldn't be shocking, even if it does make you waste a lot of time, late late into the night, coding and re-coding *BECAUSE IT JUST SHOULD WORK!* Because of that, people have created plugins to accomplish the task. One of which, [jekyll-archives](https://jekyllrb.com/docs/plugins/your-first-plugin/), is right at the top of the page about plugins. But you don't need a plugin (and I hate needlessly complicating the internet). ## The Solution There is a way to solve this without a plugin. It was [posted to Stack Overflow](https://stackoverflow.com/questions/24700749/how-do-you-sort-site-tags-by-post-count-in-jekyll#answer-24744306) by [Christian Specht](https://stackoverflow.com/users/6884/christian-specht) in response to someone asking about a plugin to solve this same problem. It's been described as "slick" (by someone else) and "hacky" (by me), but it works without a ton of code. A commenter, [Mincong Huang](https://stackoverflow.com/users/4381330/mincong-huang), made it even better with a seemingly small note. First, the code, modified to work on this site: {% highlight liquid %}{% raw %}{% capture tags %} {% for tag in site.tags %} {{ tag[1].size | minus: 10000 }}#{{ tag[0] }}#{{ tag[1].size }} {% endfor %} {% endcapture %} {% assign tagsBySize = tags | split: " " | sort %} {% for tag in tagsBySize limit:5 %} {% assign tagArray = tag | split: "#" %} <span class="smaller">{{ tagArray[2] }} Posts</span><br /> <a href="{{ site.baseurl }}/blog/tag/{{ tagArray[1] | slugify }}">{{ tagArray[1] }}</a><br /><br /> {% endfor %}{% endraw %}{% endhighlight %} Essentially, you create a string that concatenates the number of posts in a tag formatted in a sortable way, the tag name, and the number of posts in a readable way, each separated by hashes. You sort while all that is one string, and then you break it into pieces to use the parts of the string as you need. The sortable format is the slick part. If you use the post count in a string and sort, "10\#Baby\#10" will come before "2\#Breakfast2\#2". The original poster solved this by adding 1000 to create leading zeroes, just like we do with filenames to keep them in order (e.g. image002 &gt; image010 not image10 &gt; image2). In that way, 1002\#Breakfast\#2 will come before 1010\#Baby\#10. The OP then just reversed the order so that the highest number came first (that is, so that 1010 was higher than 1002). This creates a small problem, though. If two tags have the same number of posts, then reversing the sort will reverse-alphabetize the names: 1010\#Baby\#10 &gt; 1002\#Dinner\#2 &gt; 1002\#Breakfast\#2. If you *subtract* 1000 (or in my case, 10000, to give myself more leeway), you get the correct order without having to reverse, so the alphabetizing is preserved: 9990\#Baby\#10 &gt; 9998\#Breakfast\#2 &gt; 9998\#Dinner\#2. *Et voil&#0224;!* That only took all night.
C#
UTF-8
865
3.390625
3
[]
no_license
using System; namespace HealtyLifestyle { public static class Calculator { public static double CalorieCalculation(int weight,int grow,int old,double k,goal goal) { const double const1 = 9.99; const double const2 = 6.25; const double const3 = 4.92; const int const4 = 161; double result = const1 * weight + const2 * grow - const3 * old - const4; result *= k; switch (goal) { case goal.sliming: return result - (result * 20) / 100; case goal.keeping: return result; case goal.setting: return result + (result * 15) / 100; default: throw new ArgumentException("kek"); } } } }
JavaScript
UTF-8
3,241
2.78125
3
[]
no_license
import React from 'react'; import fire from '../../firebase.js'; import 'semantic-ui-css/semantic.min.css'; import './Apprating.css'; class AppRating extends React.Component { maxStars = 5; state = { rating: this.props.rating, ratingOnHover: null } // if voted, stores the id internally so it can be changed ratingDbKey = null; render() { var stars = []; var clear = []; for (let i = 1; i <= this.maxStars; i++) { // hover overwrites the state of the stored rating from the database const currentRating = (this.state.ratingOnHover !== null ? this.state.ratingOnHover : this.state.rating); const starShine = (i <= currentRating); stars.push( <Star key={i} rating={i} shine={starShine} setRating={(rating) => this._setRating(rating)} changeRatingOnHover={(rating) => this._changeRatingOnHover(rating)} /> ); } // add a button to clear the rating completely if (this.state.rating !== 0) { clear.push( <i key={this.state.rating} className='remove circle icon' onClick={(rating) => this._setRating(0)}> </i> ) } return ( <div> {clear} <div className='ui star rating' onMouseLeave={() => this._clearRatingOnHover()}> {stars} </div> </div> ) } _setRating = (rating) => { this.setState({ rating }); this._updateRating(rating); } _changeRatingOnHover = (rating) => { this.setState({ ratingOnHover: rating }); } _clearRatingOnHover = () => { this.setState({ ratingOnHover: null }); } // updates the rating in the database _updateRating = (rating) => { const ratingsPath = `/accounts/${this.props.accountId}/apps/${this.props.appId}/ratings/`; if (this.ratingDbKey === null) { // add a new key each time a user votes within the current lifespan of the app // This gives them the ability to change their mind this.ratingDbKey = fire.database().ref(ratingsPath).push({ rating }).key; } else { // set the value in the firebase database fire.database().ref(ratingsPath + this.ratingDbKey).set({ rating }); } } } const Star = (props) => { const _handleHover = (event) => { event.stopPropagation(); props.changeRatingOnHover(props.rating); } const _handleClick = (event) => { event.stopPropagation(); props.setRating(props.rating); } const stateClassSuffix = (props.shine === true ? ' active' : ''); return ( <i rating={props.rating} onClick={_handleClick} onMouseEnter={_handleHover} className={'icon' + stateClassSuffix}> </i> ) } export default AppRating;
SQL
UTF-8
1,943
3.625
4
[]
no_license
CREATE TABLE `escola.administrador` ( `id` INT(11) NOT NULL, `nome` varchar(50) NOT NULL, `login` varchar(50) NOT NULL UNIQUE, `senha` varchar(255) NOT NULL, PRIMARY KEY (`id`) ); CREATE TABLE `escola.alunos` ( `id` INT(11) NOT NULL, `cpf` varchar(11) NOT NULL UNIQUE, `nome` varchar(50) NOT NULL, `email` varchar(50) NOT NULL UNIQUE, `celular` varchar(14) NOT NULL UNIQUE, `login` varchar(20) NOT NULL UNIQUE, `senha` varchar(255) NOT NULL, `endereco` varchar(50), `cidade` varchar(30), `bairro` varchar(30), `cep` varchar(9), PRIMARY KEY (`id`) ); CREATE TABLE `escola.instrutores` ( `id` INT(11) NOT NULL, `nome` varchar(50) NOT NULL, `email` varchar(50) NOT NULL UNIQUE, `valor_hora` INT(10), `login` varchar(20) NOT NULL UNIQUE, `senha` varchar(255) NOT NULL, PRIMARY KEY (`id`) ); CREATE TABLE `escola.cursos` ( `id` INT(10) NOT NULL, `nome` varchar(50) NOT NULL, `requisito` varchar(255), `ementa` varchar(255), `carga_horaria` INT(5), `preco` DECIMAL, PRIMARY KEY (`id`) ); CREATE TABLE `escola.turmas` ( `id` INT(10) NOT NULL, `instrutores_id` INT(11) NOT NULL, `cursos_id` INT(10) NOT NULL, `data_inicio` DATE, `data_fim` DATE, `carga_horaria` INT(5), PRIMARY KEY (`id`) ); CREATE TABLE `escola.matriculas` ( `id` INT(10) NOT NULL, `turmas_id` INT(10) NOT NULL, `alunos_id` INT(11) NOT NULL, `data_matricula` DATE, `nota` DECIMAL((11,0)), PRIMARY KEY (`id`) ); ALTER TABLE `escola.turmas` ADD CONSTRAINT `escola.turmas_fk0` FOREIGN KEY (`instrutores_id`) REFERENCES `escola.instrutores`(`id`); ALTER TABLE `escola.turmas` ADD CONSTRAINT `escola.turmas_fk1` FOREIGN KEY (`cursos_id`) REFERENCES `escola.cursos`(`id`); ALTER TABLE `escola.matriculas` ADD CONSTRAINT `escola.matriculas_fk0` FOREIGN KEY (`turmas_id`) REFERENCES `escola.turmas`(`id`); ALTER TABLE `escola.matriculas` ADD CONSTRAINT `escola.matriculas_fk1` FOREIGN KEY (`alunos_id`) REFERENCES `escola.alunos`(`id`);
Python
UTF-8
1,594
2.515625
3
[]
no_license
from django import forms from .models import User class RegisterForm(forms.Form): class Meta: model = User fields = ['userName', 'password', 'email'] username = forms.CharField(label='Username', max_length=30, widget=forms.TextInput(attrs={'class' : 'form-control'})) email = forms.EmailField(label='Email', widget=forms.TextInput(attrs={'class' : 'form-control'})) Password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class' : 'form-control'})) Password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class' : 'form-control'})) def clean(self): pass1 = self.cleaned_data.get('Password1') pass2 = self.cleaned_data.get('Password2') if pass1 and pass1 != pass2: raise forms.ValidationError("Passwords do not match.") return self.cleaned_data class SignUpForm(forms.Form): class Meta: model = User fields = ['userName', 'email', 'password'] def clean_userName(self): userName = self.cleaned_data.get('userName') # write validation code return userName def clean_email(self): email = self.cleaned_data.get('email') email_base, provider = email.split("@") # domain, extension = provider.split(".") # # if not domain == "USC": # # raise forms.ValidationError("Please make sure you use your USC email.") # if not extension == "edu": # raise forms.ValidationError("Please use a valid .edu email address") return email
JavaScript
UTF-8
734
2.609375
3
[]
no_license
import React from "react"; import { getRecipe } from "../recipesService"; function RecipePage(props) { const recipeId = props.match.params.recipeId; const [recipe, setRecipe] = React.useState(null); React.useEffect(() => { getRecipe(recipeId) .then((response) => { const recipe = response.data; setRecipe(recipe); }) .catch((error) => { alert(`No recipe with ID of '${recipeId}' exists`); }); }, [recipeId]); return ( <div className="recipe-page"> {recipe ? ( <> <h1>{recipe.name}</h1> <h3>{recipe.ingredients}</h3> <h5>{recipe.instructions}</h5> </> ) : null} </div> ); } export default RecipePage;
Java
UTF-8
854
2.140625
2
[]
no_license
package com.zhongyang.java.vo; /** * Created by Matthew on 2016/1/25. */ public class RetuenUMPVO { private String user_id; private String ret_code; private String ret_msg; public String getUser_id() { return user_id; } public void setUser_id(String user_id) { this.user_id = user_id; } public String getRet_code() { return ret_code; } public void setRet_code(String ret_code) { this.ret_code = ret_code; } public String getRet_msg() { return ret_msg; } public void setRet_msg(String ret_msg) { this.ret_msg = ret_msg; } public RetuenUMPVO(String user_id, String ret_code, String ret_msg) { this.user_id = user_id; this.ret_code = ret_code; this.ret_msg = ret_msg; } public RetuenUMPVO() { } }
JavaScript
UTF-8
1,494
2.84375
3
[]
no_license
// depends on jquery, and showdown.js // not all browsers support navigator.languages - if not just use the browser render language if (typeof navigator !== 'undefined' && navigator.languages === undefined) { navigator.languages = [navigator.language]; } // when browser language changes, reload the faq $(window).bind("languagechange", function() { loadFaq(); }); loadFaq(); function loadFaq() { var locale = Cookies.get("locale") || getBrowserLocale(); // first look for a translated faq if(locale == 'en') { $.get('faq.md', function(md) { $('.doc').html(new showdown.Converter().makeHtml(md)); }); } else { $.get('./locales/faq.' + locale + '.md', function(md) { $('.doc').html(new showdown.Converter().makeHtml(md)); }).fail(function() { // if no translation - fail back $.get('faq.md', function(md) { $('.doc').html(new showdown.Converter().makeHtml(md)); }); }); } } function getBrowserLocale() { if (typeof navigator !== 'undefined' && navigator.languages !== undefined) { // the first lanaguage in the list is the user's preference var userLang = navigator.languages[0]; // if(userLang == undefined) return "en"; var lang; try { lang = userLang.split('-')[0]; } catch (error) { lang = 'en'; } return lang; } return "en"; }
Java
UTF-8
556
3.546875
4
[]
no_license
package i_TextProcessingAndRegularExpressions; public class demo7Replacing { public static void main(String[] args) { //replace(match, replacement) – replaces all occurrences //The result is a new string (strings are immutable) String text = "Hello, john@softuni.bg, you have been using john@softuni.bg in your registration."; String replacedText = text .replace("john@softuni.bg", "john@softuni.com"); System.out.println(replacedText); // Hello, john@softuni.com, you have been using john@softuni.com in your registration. } }
Java
UTF-8
120
1.664063
2
[]
no_license
package com.mydesign.modes.design_modes.mvp; public interface BasePresenter { void start(); void detach(); }
C++
UTF-8
248
2.890625
3
[]
no_license
#include <iostream> using namespace std; int main() { cout<<"Fibonacci Program\n"; int a=8,f=0,s=1,t; cout<<f<<" "<<s<<" "; while(a){ t=f+s; cout<<t<<" "; f=s; s=t; a--; } return 0; }
C++
UTF-8
3,999
2.65625
3
[]
no_license
#include "channels.h" #include "IoDriver.h" //#include "io.h" #include "io.h" #include <assert.h> #include <stdlib.h> // Number of signals and lamps on a per-floor basis (excl sensor) static const int lamp_channel_matrix[FLOORCOUNT][BUTTONCOUNT] = { {LIGHT_UP1, LIGHT_DOWN1, LIGHT_COMMAND1}, {LIGHT_UP2, LIGHT_DOWN2, LIGHT_COMMAND2}, {LIGHT_UP3, LIGHT_DOWN3, LIGHT_COMMAND3}, {LIGHT_UP4, LIGHT_DOWN4, LIGHT_COMMAND4}, }; static const int button_channel_matrix[FLOORCOUNT][BUTTONCOUNT] = { {BUTTON_UP1, BUTTON_DOWN1, BUTTON_COMMAND1}, {BUTTON_UP2, BUTTON_DOWN2, BUTTON_COMMAND2}, {BUTTON_UP3, BUTTON_DOWN3, BUTTON_COMMAND3}, {BUTTON_UP4, BUTTON_DOWN4, BUTTON_COMMAND4}, }; bool IoDriver_initialize(void) { int i; // Init hardware if (!io_init(ET_comedi)) return false; for (i = 0; i < FLOORCOUNT; ++i) { if (i != 0) ioDriver_clearOrderButtonLamp(BUTTON_CALL_DOWN, i); if (i != FLOORCOUNT - 1) ioDriver_clearOrderButtonLamp(BUTTON_CALL_UP, i); ioDriver_clearOrderButtonLamp(BUTTON_COMMAND, i); } // Clear stop lamp, door open lamp, and set floor indicator to ground floor. ioDriver_clearStopLamp(); ioDriver_clearDoorOpenLamp(); ioDriver_setFloorIndicator(0); // Return success. return true; } void ioDriver_setMotorDirection(motor_direction_t direction) { switch (direction) { case DIRECTION_DOWN: io_set_bit(MOTORDIR); io_write_analog(MOTOR, 2800); break; case DIRECTION_STOP: io_write_analog(MOTOR, 0); break; case DIRECTION_UP: io_clear_bit(MOTORDIR); io_write_analog(MOTOR, 2800); break; } } void ioDriver_setDoorOpenLamp(void) { io_set_bit(LIGHT_DOOR_OPEN); } void ioDriver_clearDoorOpenLamp(void){ io_clear_bit(LIGHT_DOOR_OPEN); } bool ioDriver_isElevatorObstructed(void) { return io_read_bit(OBSTRUCTION); } bool ioDriver_isStopButtonPressed(void) { return io_read_bit(STOP); } void ioDriver_setStopLamp(void) { io_set_bit(LIGHT_STOP); } void ioDriver_clearStopLamp(void){ io_clear_bit(LIGHT_STOP); } int ioDriver_getFloorSensorValue(void) { if (io_read_bit(SENSOR_FLOOR1)) return 0; else if (io_read_bit(SENSOR_FLOOR2)) return 1; else if (io_read_bit(SENSOR_FLOOR3)) return 2; else if (io_read_bit(SENSOR_FLOOR4)) return 3; else return -1; } void ioDriver_setFloorIndicator(int floor) { assert(floor >= 0); assert(floor < FLOORCOUNT); // Binary encoding. One light must always be on. if (floor & 0x02) io_set_bit(LIGHT_FLOOR_IND1); else io_clear_bit(LIGHT_FLOOR_IND1); if (floor & 0x01) io_set_bit(LIGHT_FLOOR_IND2); else io_clear_bit(LIGHT_FLOOR_IND2); } bool ioDriver_isOrderButtonPressed(button_type_t type, int floor) { assert(floor >= 0); assert(floor < FLOORCOUNT); assert(!(type == BUTTON_CALL_UP && floor == FLOORCOUNT - 1)); assert(!(type == BUTTON_CALL_DOWN && floor == 0)); assert(type == BUTTON_CALL_UP || type == BUTTON_CALL_DOWN || type == BUTTON_COMMAND); if (io_read_bit(button_channel_matrix[floor][type])) return 1; else return 0; } void ioDriver_setOrderButtonLamp(button_type_t type, int floor){ assert(floor >= 0); assert(floor < FLOORCOUNT); assert(!(type == BUTTON_CALL_UP && floor == FLOORCOUNT - 1)); assert(!(type == BUTTON_CALL_DOWN && floor == 0)); assert(type == BUTTON_CALL_UP || type == BUTTON_CALL_DOWN || type == BUTTON_COMMAND); io_set_bit(lamp_channel_matrix[floor][type]); } void ioDriver_clearOrderButtonLamp(button_type_t type, int floor){ assert(floor >= 0); assert(floor < FLOORCOUNT); assert(!(type == BUTTON_CALL_UP && floor == FLOORCOUNT - 1)); assert(!(type == BUTTON_CALL_DOWN && floor == 0)); assert(type == BUTTON_CALL_UP || type == BUTTON_CALL_DOWN || type == BUTTON_COMMAND); io_clear_bit(lamp_channel_matrix[floor][type]); }
Python
UTF-8
547
4.15625
4
[]
no_license
#Program to demostrate the two ways of creating threads in Python #First thread displays Hello World and Second thread displays Welcome to Python import threading def HelloWorld(): i=0 while i<10: print("HelloWorld") i+=1 class WelcomeToPython(threading.Thread): def __init__(self): super().__init__() def run(self): i=0 while i<10: print("Welcome to Python") i+=1 if __name__=="__main__": #First thread t1=threading.Thread(target=HelloWorld,args=()) #Second thread t2=WelcomeToPython() t1.start() t2.start()
Java
UTF-8
641
2.15625
2
[]
no_license
package au.com.westernpower.ci; import au.com.westernpower.ci.model.SuperBean; import au.com.westernpower.ci.repository.SuperBeanRepository; import au.com.westernpower.ci.repository.SuperBeanRepositoryImpl; import org.junit.Assert; import org.junit.Test; /** * Created by N038603 on 8/02/2016. */ public class MySuperRepositoryTest { SuperBeanRepository repository = new SuperBeanRepositoryImpl(); @Test public void testSave(){ SuperBean superBean = new SuperBean(); repository.save(superBean); Assert.assertNotNull("Bean ID must not be null",superBean.getId()); } }
SQL
UTF-8
6,801
2.953125
3
[]
no_license
CREATE TABLE AVION ( AV_NII VARCHAR2(50 BYTE) PRIMARY KEY , AV_TYPE VARCHAR2(20 BYTE) NOT NULL, AV_DATE_SERVICE DATE NOT NULL, AV_NB_HEURE FLOAT(126) NOT NULL, AV_CAPACITE NUMBER NOT NULL ) ; CREATE TABLE ELEMENT ( ELEM_ID NUMBER PRIMARY KEY, ELEM_NOM VARCHAR2(50 BYTE) ) ; CREATE TABLE ELEMENT_REVISION ( ELEM_ID NUMBER, REV_ID NUMBER NOT NULL, CONSTRAINT ELEMENT_REVISION_pk PRIMARY KEY(ELEM_ID,REV_ID) ); CREATE TABLE EMPLOYEE ( EMP_ID VARCHAR2(5) PRIMARY KEY, EMP_NOM VARCHAR2(100 BYTE) NOT NULL, EMP_PRENOM VARCHAR2(100 BYTE) NOT NULL, EMP_SEXE VARCHAR2(10 BYTE) NOT NULL, EMP_DATE_NAISSANCE DATE NOT NULL, EMP_ADRESSE VARCHAR2(200 BYTE) NOT NULL, EMP_DATE_EMBAUCHE DATE NOT NULL, EMP_CATEGORIE VARCHAR2(100 BYTE) NOT NULL, EMP_SALAIRE NUMBER NOT NULL, EMP_TEL NUMBER NOT NULL ); /* CREATE TABLE EQUIPE ( EQUIPE_ID NUMBER PRIMARY KEY, PILOTE_ID VARCHAR2(5) NOT NULL, STEWARD_ID VARCHAR2(5) NOT NULL, AVION_NII VARCHAR2(50 BYTE) NOT NULL ); */ CREATE TABLE ESCALE ( ESC_MIS_ID NUMBER, ESC_VILLE_ID NUMBER NOT NULL, ESC_HEURE VARCHAR2(5) NOT NULL, CONSTRAINT ESCALE_pk PRIMARY KEY(ESC_MIS_ID,ESC_VILLE_ID) ); CREATE TABLE MISSION ( MIS_ID NUMBER PRIMARY KEY, MIS_VILLE_DEPART NUMBER NOT NULL, MIS_VILLE_ARRIVE NUMBER NOT NULL, MIS_HEURE_DEPART VARCHAR2 (5) NOT NULL, MIS_HEURE_ARRIVE VARCHAR2 (5) NOT NULL ); CREATE TABLE VOL ( VOL_ID NUMBER , MIS_ID NUMBER NOT NULL, VOL_DATE DATE NOT NULL, PILOTE_ID VARCHAR2(5) , STEWARD_ID VARCHAR2(5), AVION_NII VARCHAR2(50 BYTE), CONSTRAINT VOL_PK PRIMARY KEY(VOL_ID,MIS_ID,VOL_DATE) ); CREATE TABLE NAVIGANT ( NAV_EMP_ID VARCHAR2(5) PRIMARY KEY, NAV_HEURE_VOL FLOAT(126) NOT NULL ); CREATE TABLE REVISION ( REV_ID NUMBER PRIMARY KEY, REV_DATE DATE NOT NULL, REV_MECA_ID VARCHAR2(5) NOT NULL, REV_AVION_NII VARCHAR2(50) NOT NULL, REV_HEURE_VOL VARCHAR2 (20) NOT NULL ); CREATE TABLE VILLE ( VILLE_ID NUMBER PRIMARY KEY, VILLE_NOM VARCHAR2(50 BYTE) NOT NULL, VILLE_PAYS VARCHAR2(20 BYTE) NOT NULL, VILLE_POSTAL NUMBER NOT NULL ); CREATE TABLE PASSAGER ( P_ID NUMBER PRIMARY KEY, P_NOM VARCHAR2(100) NOT NULL, P_PRENOM VARCHAR2(100) NOT NULL, P_DATE_NAISSANCE DATE NOT NULL, P_TEL NUMBER NOT NULL, P_EMAIL VARCHAR2(100) NOT NULL, P_ADRESSE VARCHAR2(200) NOT NULL, P_PASSEPORT VARCHAR2(50) NOT NULL, P_SEXE VARCHAR2(5) NOT NULL ) ; CREATE TABLE RESERVATION ( RES_ID NUMBER PRIMARY KEY, RES_VOL_ID NUMBER NOT NULL, RES_P_ID NUMBER NOT NULL ); ------------------------------------------------------- -- Ref Constraints for Table ELEMENT_REVISION -------------------------------------------------------- ALTER TABLE ELEMENT_REVISION ADD CONSTRAINT ELEM_FK FOREIGN KEY ( ELEM_ID ) REFERENCES ELEMENT ( ELEM_ID ); ALTER TABLE ELEMENT_REVISION ADD CONSTRAINT REV_FK FOREIGN KEY ( REV_ID ) REFERENCES REVISION ( REV_ID ) ; -------------------------------------------------------- -- Ref Constraints for Table EMPLOYEE -------------------------------------------------------- ALTER TABLE EMPLOYEE ADD CONSTRAINT categorie_check CHECK(emp_categorie IN('admin','pilote','steward','mecanicien')); ALTER TABLE EMPLOYEE ADD CONSTRAINT sexe_check CHECK(emp_sexe IN('F','M')); --xym -------------------------------------------------------- -- Ref Constraints for Table EQUIPE -------------------------------------------------------- /* ALTER TABLE EQUIPE ADD CONSTRAINT AVION_NII_FK FOREIGN KEY ( AVION_NII ) REFERENCES AVION ( AV_NII ) ; ALTER TABLE EQUIPE ADD CONSTRAINT PILOTE_ID_FK FOREIGN KEY ( PILOTE_ID ) REFERENCES EMPLOYEE ( EMP_ID ) ; ALTER TABLE EQUIPE ADD CONSTRAINT STEWARD_ID_FK FOREIGN KEY ( STEWARD_ID ) REFERENCES EMPLOYEE ( EMP_ID ) ;*/ -------------------------------------------------------- -- Ref Constraints for Table ESCALE -------------------------------------------------------- ALTER TABLE ESCALE ADD CONSTRAINT MIS_ID_FK FOREIGN KEY ( ESC_MIS_ID ) REFERENCES MISSION ( MIS_ID ) ; ALTER TABLE ESCALE ADD CONSTRAINT VILLE_ID_FK FOREIGN KEY ( ESC_VILLE_ID ) REFERENCES VILLE ( VILLE_ID ) ; -------------------------------------------------------- -- Ref Constraints for Table MISSION -------------------------------------------------------- ALTER TABLE MISSION ADD CONSTRAINT VILLE_ARRIVE_FK FOREIGN KEY ( MIS_VILLE_ARRIVE ) REFERENCES VILLE ( VILLE_ID ) ; ALTER TABLE MISSION ADD CONSTRAINT VILLE_DEPART_FK FOREIGN KEY ( MIS_VILLE_DEPART ) REFERENCES VILLE ( VILLE_ID ) ; -------------------------------------------------------- -- Ref Constraints for Table VOL -------------------------------------------------------- /*ALTER TABLE VOL ADD CONSTRAINT EQUIPE_FK FOREIGN KEY ( EQUIPE_ID ) REFERENCES EQUIPE ( EQUIPE_ID ) ;*/ ALTER TABLE VOL ADD CONSTRAINT MIS_FK FOREIGN KEY ( MIS_ID ) REFERENCES MISSION ( MIS_ID ) ; ALTER TABLE VOL ADD CONSTRAINT AVION_NII_FK FOREIGN KEY ( AVION_NII ) REFERENCES AVION ( AV_NII ) ; ALTER TABLE VOL ADD CONSTRAINT PILOTE_ID_FK FOREIGN KEY ( PILOTE_ID ) REFERENCES EMPLOYEE ( EMP_ID ) ; ALTER TABLE VOL ADD CONSTRAINT STEWARD_ID_FK FOREIGN KEY ( STEWARD_ID ) REFERENCES EMPLOYEE ( EMP_ID ) ; -------------------------------------------------------- -- Ref Constraints for Table NAVIGANT -------------------------------------------------------- ALTER TABLE NAVIGANT ADD CONSTRAINT EMP_ID_PK FOREIGN KEY ( NAV_EMP_ID ) REFERENCES EMPLOYEE ( EMP_ID ) ; -------------------------------------------------------- -- Ref Constraints for Table REVISION -------------------------------------------------------- ALTER TABLE REVISION ADD CONSTRAINT REV_AVION_FK FOREIGN KEY ( REV_AVION_NII ) REFERENCES AVION ( AV_NII ) ; ALTER TABLE REVISION ADD CONSTRAINT REV_MECA_FK FOREIGN KEY ( REV_MECA_ID ) REFERENCES EMPLOYEE ( EMP_ID ) ; -------------------------------------------------------- -- Ref Constraints for Table RESERVATION -------------------------------------------------------- ALTER TABLE RESERVATION ADD CONSTRAINT RES_VOL_ID_PK FOREIGN KEY ( RES_VOL_ID ) REFERENCES VOL ( VOL_ID ) ; ALTER TABLE RESERVATION ADD CONSTRAINT RES_P_ID_PK FOREIGN KEY ( RES_P_ID ) REFERENCES PASSAGER ( P_ID ) ; -------------------------------------------------------- -- Ref Constraints for Table passager -------------------------------------------------------- ALTER TABLE PASSAGER ADD CONSTRAINT p_sexe_check CHECK(p_sexe IN('F','M')); --xym
JavaScript
UTF-8
2,935
2.515625
3
[]
no_license
import React, { Component } from 'react' import PropTypes from 'prop-types' import Messages from '../Messages/Messages.jsx' import Header from '../Header/Header.jsx' import ChatList from '../ChatList/ChatList.jsx' import './style.css' let user = 'You' export default class Layout extends Component { static propTypes = { chatId: PropTypes.number, } static defaultProps = { chatId: 1, } state = { chats: { 1: { title: 'Чат 1', messagesList: [1] }, 2: { title: 'Чат 2', messagesList: [2] }, 3: { title: 'Чат 3', messagesList: [] } }, messages: { 1: { text: 'Hello', sender: 'bot' }, 2: { text: 'What is up?', sender: 'bot' } }, inputText: '', } componentDidUpdate (prevProps, prevState) { const { messages } = this.state; if (Object.keys(prevState.messages).length < Object.keys(messages).length && Object.values(messages)[Object.values(messages).length - 1].sender === 'You') { setTimeout(() => this.sendMessage('Не приставай ко мне, я робот!', 'bot'), 1000); } } sendMessage = (message, sender) => { let { messages, chats} = this.state; let { chatId } = this.props; let messageId = Object.keys (messages).length + 1 this.setState ({ messages: { ...messages, [messageId]: {text: message, sender: sender} }, chats: { ...chats, [chatId]: { ...chats[chatId], messageList: [...chats[chatId]['messageList'], messageId] } } }) }; addChat = (title) => { let { chats } = this.state; let chatId = Object.keys(chats).lenght + 1; this.setState({ chats: {...chats, [chatId]: {title: title, messageList: []} }, }) } render () { return ( <div className = "d-flex justify-content-center w-100 layout"> <Header chatId = { this.props.chatId } /> <div className = "d-flex justify-content-center w-100 layout-left-side"> <div className = "pr-5 w-30"> <ChatList chats = { this.state.chats } addChat = { this.addChat } /> </div> <div className = "d-flex justify-content-center w-100 layout-right-side"> <Messages chatId = { this.props.chatId } chats = { this.state.chats } messages = { this.state.messages } sendMessage = { this.sendMessage } /> </div> </div> </div> ) } }
Python
UTF-8
3,710
2.546875
3
[]
no_license
#!/usr/bin/env python # coding=utf-8 # usage: # 早期Pinnacle3 TPS的压缩包,没有添加Institution头文件,Restore时,TPS无法直接识别 # 此程序的功能是:批量的将就压缩包,转换成TPS可以识别的新压缩包;1,增加Institution头文件,2,删除病例中无用的临时文件 # import os import re import time import shutil from Pinnutil.untar_old_pinnacle_backup_file import untar_old_pinnacle_backup_file from Pinnutil.tar_one_pinn_patient import tar_one_pinn_patient DEBUG = 0 # 删除Pinnacle 3 TPS native file,匹配的规则如下(删除),同时检测link文件(删除) # 输入参数,rootpath,和logobject文件指针 def CleaningPatientPool(poolpath, logfile): MatchRegList = ['^.auto.plan*', '.ErrorLog$', '.Transcript$', '.defaults$', '.pinnbackup$', '^Institution.\d+', '^Patient.\d+', '\s*~\s*'] for dirpath, dirname, filenames in os.walk(poolpath): for file in filenames: filepath = os.path.join(dirpath, file) if os.path.islink(filepath): os.remove(filepath) continue for currentReg in MatchRegList: if re.findall(currentReg, file): os.remove(filepath) print('del:%s\n' % filepath) # logfile.write('del:%s\n'%filepath) if __name__ == "__main__": # 工作路径 work_path = "/home/peter/PinnWork" # 头文件模板 inst_template = os.path.join(work_path, 'institution_template') # 源文件夹,旧病例存储 old_Pinn_pool = '/media/peter/BACKUP/PinnX86/PinnV80/' #old_Pinn_pool = '/media/peter/BACKUP/PinnX86/test/' # 新生成压缩包的归档文件夹 new_Pinn_pool = '/media/peter/BACKUP/PinnX86/NewPinn/' # log filename = time.asctime() + '.log' listfile = os.path.join(work_path, filename) logobj = open(listfile, 'w+') i = 1 for tar_file in os.listdir(old_Pinn_pool): print i i = i + 1 current_tar_file = os.path.join(old_Pinn_pool, tar_file) if os.path.isfile(current_tar_file): # Step1:解压就压缩包,得到病例数据文件夹绝对路径 data_dir = untar_old_pinnacle_backup_file( work_path, current_tar_file).untar_gzip_file() if data_dir: # 删除旧压缩包 os.remove(current_tar_file) # Step2:删除病例数据中的临时文件 CleaningPatientPool(data_dir, logobj) # Step3: 生成新的文件压缩包,targzip打包压缩,返回压缩包的绝对路径 new_tar_file = tar_one_pinn_patient( inst_template, data_dir).get_tar_gzip_file() if new_tar_file: print ' Get New TarFile:', os.path.basename(new_tar_file) logobj.write("convert:%s to %s\n" % (tar_file, new_tar_file)) # 删除临时临时病例文件夹 shutil.rmtree(data_dir) if not os.path.isfile(os.path.join(new_Pinn_pool, os.path.basename(new_tar_file))): # Step4:移动到归档文件夹中 try: shutil.move(new_tar_file, new_Pinn_pool) except IOError, OSError: print "move fail!" else: print "file already exists" logobj.close() print "finish"
Java
UTF-8
468
1.703125
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package probando; /** * * @author Walter */ public class Probando { /** * @param args the command line arguments */ public static void main(String[] args) { new NewJFrame().setVisible(true); new Forma().setVisible(true); // TODO codenew application logic here new ClaseHilo("mayo").start(); } }
C#
UTF-8
538
2.96875
3
[]
no_license
using App.Enums; using App.Interfaces; namespace App.Entities { public class Student : User { public int Course { get; set; } public Group Group { get; set; } public Student(){} public Student(string name, int age, Sex sex, int salary, int course, Group group) : base(name, age, sex, salary) { Course = course; Group = group; } public override bool IsEqualRole(IUser other) { return other is Student; } } }
C++
UTF-8
550
3.0625
3
[]
no_license
#include "p1.h" #include "basic_functions.h" #include <iostream> bool XOR(bool a, bool b){ return Or(And(a,Not(b)),And(Not(a),b)); } bool Mux(bool operation, bool output_if_true, bool output_if_false){ return Or(And(operation, output_if_true), And(Not(operation), output_if_false)); } bool Sum(bool a, bool b){ return XOR(a,b); } bool Sum(bool a, bool b, bool c){ return XOR(XOR(a,b),c); } bool CarryOut(bool a, bool b, bool c){ bool x = XOR(a,b); return Or(And(c,x),And(a,b)); } bool Equal(bool a, bool b){ return !XOR(a,b); }
Java
UTF-8
11,764
2.0625
2
[]
no_license
package org.jcrm.web.rest; import org.jcrm.JCrmApp; import org.jcrm.domain.Client; import org.jcrm.repository.ClientRepository; import org.jcrm.service.ClientService; import org.jcrm.web.rest.errors.ExceptionTranslator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.web.PageableHandlerMethodArgumentResolver; import org.springframework.http.MediaType; import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import javax.persistence.EntityManager; import java.time.LocalDate; import java.time.ZoneId; import java.util.List; import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.Matchers.hasItem; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; /** * Test class for the ClientResource REST controller. * * @see ClientResource */ @RunWith(SpringRunner.class) @SpringBootTest(classes = JCrmApp.class) public class ClientResourceIntTest { private static final String DEFAULT_NAME = "AAAAAAAAAA"; private static final String UPDATED_NAME = "BBBBBBBBBB"; private static final LocalDate DEFAULT_BIRTHDATE = LocalDate.ofEpochDay(0L); private static final LocalDate UPDATED_BIRTHDATE = LocalDate.now(ZoneId.systemDefault()); private static final String DEFAULT_LAST_NAME = "AAAAAAAAAA"; private static final String UPDATED_LAST_NAME = "BBBBBBBBBB"; private static final String DEFAULT_NIP = "AAAAAAAAAA"; private static final String UPDATED_NIP = "BBBBBBBBBB"; private static final String DEFAULT_PESEL = "AAAAAAAAAA"; private static final String UPDATED_PESEL = "BBBBBBBBBB"; private static final String DEFAULT_PHONE_HOME = "AAAAAAAAAA"; private static final String UPDATED_PHONE_HOME = "BBBBBBBBBB"; private static final String DEFAULT_PHONE_WORK = "AAAAAAAAAA"; private static final String UPDATED_PHONE_WORK = "BBBBBBBBBB"; @Autowired private ClientRepository clientRepository; @Autowired private ClientService clientService; @Autowired private MappingJackson2HttpMessageConverter jacksonMessageConverter; @Autowired private PageableHandlerMethodArgumentResolver pageableArgumentResolver; @Autowired private ExceptionTranslator exceptionTranslator; @Autowired private EntityManager em; private MockMvc restClientMockMvc; private Client client; @Before public void setup() { MockitoAnnotations.initMocks(this); final ClientResource clientResource = new ClientResource(clientService); this.restClientMockMvc = MockMvcBuilders.standaloneSetup(clientResource) .setCustomArgumentResolvers(pageableArgumentResolver) .setControllerAdvice(exceptionTranslator) .setMessageConverters(jacksonMessageConverter).build(); } /** * Create an entity for this test. * * This is a static method, as tests for other entities might also need it, * if they test an entity which requires the current entity. */ public static Client createEntity(EntityManager em) { Client client = new Client() .name(DEFAULT_NAME) .birthdate(DEFAULT_BIRTHDATE) .last_name(DEFAULT_LAST_NAME) .NIP(DEFAULT_NIP) .PESEL(DEFAULT_PESEL) .phone_home(DEFAULT_PHONE_HOME) .phone_work(DEFAULT_PHONE_WORK); return client; } @Before public void initTest() { client = createEntity(em); } @Test @Transactional public void createClient() throws Exception { int databaseSizeBeforeCreate = clientRepository.findAll().size(); // Create the Client restClientMockMvc.perform(post("/api/clients") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(client))) .andExpect(status().isCreated()); // Validate the Client in the database List<Client> clientList = clientRepository.findAll(); assertThat(clientList).hasSize(databaseSizeBeforeCreate + 1); Client testClient = clientList.get(clientList.size() - 1); assertThat(testClient.getName()).isEqualTo(DEFAULT_NAME); assertThat(testClient.getBirthdate()).isEqualTo(DEFAULT_BIRTHDATE); assertThat(testClient.getLast_name()).isEqualTo(DEFAULT_LAST_NAME); assertThat(testClient.getNIP()).isEqualTo(DEFAULT_NIP); assertThat(testClient.getPESEL()).isEqualTo(DEFAULT_PESEL); assertThat(testClient.getPhone_home()).isEqualTo(DEFAULT_PHONE_HOME); assertThat(testClient.getPhone_work()).isEqualTo(DEFAULT_PHONE_WORK); } @Test @Transactional public void createClientWithExistingId() throws Exception { int databaseSizeBeforeCreate = clientRepository.findAll().size(); // Create the Client with an existing ID client.setId(1L); // An entity with an existing ID cannot be created, so this API call must fail restClientMockMvc.perform(post("/api/clients") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(client))) .andExpect(status().isBadRequest()); // Validate the Client in the database List<Client> clientList = clientRepository.findAll(); assertThat(clientList).hasSize(databaseSizeBeforeCreate); } @Test @Transactional public void getAllClients() throws Exception { // Initialize the database clientRepository.saveAndFlush(client); // Get all the clientList restClientMockMvc.perform(get("/api/clients?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(client.getId().intValue()))) .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString()))) .andExpect(jsonPath("$.[*].birthdate").value(hasItem(DEFAULT_BIRTHDATE.toString()))) .andExpect(jsonPath("$.[*].last_name").value(hasItem(DEFAULT_LAST_NAME.toString()))) .andExpect(jsonPath("$.[*].NIP").value(hasItem(DEFAULT_NIP.toString()))) .andExpect(jsonPath("$.[*].PESEL").value(hasItem(DEFAULT_PESEL.toString()))) .andExpect(jsonPath("$.[*].phone_home").value(hasItem(DEFAULT_PHONE_HOME.toString()))) .andExpect(jsonPath("$.[*].phone_work").value(hasItem(DEFAULT_PHONE_WORK.toString()))); } @Test @Transactional public void getClient() throws Exception { // Initialize the database clientRepository.saveAndFlush(client); // Get the client restClientMockMvc.perform(get("/api/clients/{id}", client.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(client.getId().intValue())) .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString())) .andExpect(jsonPath("$.birthdate").value(DEFAULT_BIRTHDATE.toString())) .andExpect(jsonPath("$.last_name").value(DEFAULT_LAST_NAME.toString())) .andExpect(jsonPath("$.NIP").value(DEFAULT_NIP.toString())) .andExpect(jsonPath("$.PESEL").value(DEFAULT_PESEL.toString())) .andExpect(jsonPath("$.phone_home").value(DEFAULT_PHONE_HOME.toString())) .andExpect(jsonPath("$.phone_work").value(DEFAULT_PHONE_WORK.toString())); } @Test @Transactional public void getNonExistingClient() throws Exception { // Get the client restClientMockMvc.perform(get("/api/clients/{id}", Long.MAX_VALUE)) .andExpect(status().isNotFound()); } @Test @Transactional public void updateClient() throws Exception { // Initialize the database clientService.save(client); int databaseSizeBeforeUpdate = clientRepository.findAll().size(); // Update the client Client updatedClient = clientRepository.findOne(client.getId()); updatedClient .name(UPDATED_NAME) .birthdate(UPDATED_BIRTHDATE) .last_name(UPDATED_LAST_NAME) .NIP(UPDATED_NIP) .PESEL(UPDATED_PESEL) .phone_home(UPDATED_PHONE_HOME) .phone_work(UPDATED_PHONE_WORK); restClientMockMvc.perform(put("/api/clients") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(updatedClient))) .andExpect(status().isOk()); // Validate the Client in the database List<Client> clientList = clientRepository.findAll(); assertThat(clientList).hasSize(databaseSizeBeforeUpdate); Client testClient = clientList.get(clientList.size() - 1); assertThat(testClient.getName()).isEqualTo(UPDATED_NAME); assertThat(testClient.getBirthdate()).isEqualTo(UPDATED_BIRTHDATE); assertThat(testClient.getLast_name()).isEqualTo(UPDATED_LAST_NAME); assertThat(testClient.getNIP()).isEqualTo(UPDATED_NIP); assertThat(testClient.getPESEL()).isEqualTo(UPDATED_PESEL); assertThat(testClient.getPhone_home()).isEqualTo(UPDATED_PHONE_HOME); assertThat(testClient.getPhone_work()).isEqualTo(UPDATED_PHONE_WORK); } @Test @Transactional public void updateNonExistingClient() throws Exception { int databaseSizeBeforeUpdate = clientRepository.findAll().size(); // Create the Client // If the entity doesn't have an ID, it will be created instead of just being updated restClientMockMvc.perform(put("/api/clients") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(client))) .andExpect(status().isCreated()); // Validate the Client in the database List<Client> clientList = clientRepository.findAll(); assertThat(clientList).hasSize(databaseSizeBeforeUpdate + 1); } @Test @Transactional public void deleteClient() throws Exception { // Initialize the database clientService.save(client); int databaseSizeBeforeDelete = clientRepository.findAll().size(); // Get the client restClientMockMvc.perform(delete("/api/clients/{id}", client.getId()) .accept(TestUtil.APPLICATION_JSON_UTF8)) .andExpect(status().isOk()); // Validate the database is empty List<Client> clientList = clientRepository.findAll(); assertThat(clientList).hasSize(databaseSizeBeforeDelete - 1); } @Test @Transactional public void equalsVerifier() throws Exception { TestUtil.equalsVerifier(Client.class); Client client1 = new Client(); client1.setId(1L); Client client2 = new Client(); client2.setId(client1.getId()); assertThat(client1).isEqualTo(client2); client2.setId(2L); assertThat(client1).isNotEqualTo(client2); client1.setId(null); assertThat(client1).isNotEqualTo(client2); } }
C#
UTF-8
639
3.625
4
[]
no_license
using System; class PrimeChecker { static void Main() { long num = long.Parse(Console.ReadLine()); bool isPrime = IsPrime(num); Console.WriteLine(isPrime); } static bool IsPrime(long num) { if (num == 0 || num == 1) { return false; } if (num == 2) { return true; } var maxNum = Math.Sqrt(num); for (int currentNum = 2; currentNum <= maxNum; currentNum++) { if (num % currentNum == 0) { return false; } } return true; } }
JavaScript
UTF-8
4,950
2.625
3
[]
no_license
'use strict'; // Test via a getter in the options object to see if the passive property is accessed var supportsPassive = false; try { var opts = Object.defineProperty({}, 'passive', { get: function() { supportsPassive = true; } }); window.addEventListener("testPassive", null, opts); window.removeEventListener("testPassive", null, opts); } catch (e) {} // Use our detect's results. passive applied if supported, capture will be false either way. // elem.addEventListener('touchstart', fn, supportsPassive ? { passive: true } : false); // ---------------------------------------- TOP BAR FIXED START -------------------------------------------------- // const menu = document.querySelector(".top_bar"); window.addEventListener("scroll", ()=>{ if(window.scrollY > 50){ menu.classList.add("top_bar-fixed"); } else { menu.classList.remove("top_bar-fixed"); } }); // ---------------------------------------- MODAL START -------------------------------------------------- // const modal = document.querySelector(".modal"); const regBtns = document.querySelectorAll(".free_reg_button"), closeModal = document.querySelector(".close_modal"), modalContainer = document.querySelector(".modal-container"), body = document.querySelector("body"); function openCloseToggle() { modal.classList.toggle("show"); modal.classList.remove("hide-modal"); body.classList.toggle("ovhide"); modal.setAttribute("aria-hidden", "true") } closeModal.addEventListener("click", ()=>{ openCloseToggle(); }); modal.addEventListener("click", (e)=>{ if (!modalContainer.contains(e.target)) { openCloseToggle(); } }); regBtns.forEach((el, index)=>{ el.addEventListener("click", ()=>{ openCloseToggle(); modal.querySelector("input[name=login]").focus(); }) }); // ---------------------------------------- SECTION 04 - CAROUSEL START -------------------------------------------------- // const btnL = document.querySelector(".carousel_navigation-left"), btnR = document.querySelector(".carousel_navigation-right"), allEls = document.querySelectorAll(".carousel_element"), qCont = document.querySelectorAll(".q-container"); let index = 0; btnR.addEventListener("click", ()=>{ index--; index = (index < 0 ? (allEls.length-1) : index); spin(index); }); btnL.addEventListener("click", ()=>{ index++; index = (index > (allEls.length-1) ? 0 : index); spin(index); }); function spin(to){ // Testimonials text visiblity qCont.forEach((q)=>{ q.classList.remove("visible"); q.classList.add("hidden"); q.setAttribute("aria-hidden", "true"); }); qCont[to].classList.add("visible"); qCont[to].classList.remove("hidden"); qCont[to].setAttribute("aria-hidden", "false"); // Testimonials images visiblity allEls.forEach((a)=>{ a.classList.remove("active", "el_left", "el_right", "el_center"); a.classList.add("not-active"); a.setAttribute("aria-hidden", "true"); }); let left = (to <= 0 ? 2 : (to-1)); let right = (to >= 2 ? 0 : (to+1)); allEls[left].classList.add("el_left"); allEls[right].classList.add("el_right"); allEls[to].classList.remove("not-active"); allEls[to].classList.add("active", "el_center"); allEls[to].setAttribute("aria-hidden", "false"); }; // ----------------------------- AUTO HIDE MENU BAR -------------------------------- const html = document.querySelector('html'); html.addEventListener('wheel', findScrollDirectionOtherBrowsers, supportsPassive ? { passive: true } : false); let delta; function findScrollDirectionOtherBrowsers(event){ if (event.wheelDelta){ delta = event.wheelDelta; }else{ delta = -1 * event.deltaY; } if (delta < 0){ menu.style.marginTop = -100+"px"; }else if (delta > 0){ menu.style.marginTop = 0; } } // ------------------------------------- BTN TOGGLE MENU ----------------------------- const toggleBtn = document.querySelector(".toggle-btn"), menuItem = document.querySelectorAll(".menu_item"), headerMenu = document.querySelector(".header_menu"), menuLi = document.querySelector(".menu"); toggleBtn.addEventListener("click", ()=>{ if(toggleBtn.innerHTML !== "<i class=\"fas fa-times\"></i>"){ open(); } else { close(); } }); if(window.innerWidth < 760){ menuItem.forEach((item)=>{ item.addEventListener("click", ()=>{ close(); }); }); }; function close(){ menuItem.forEach((item, i)=>{ item.style.left = -4000+"px"; item.style.transitionDelay = "0s"; }); toggleBtn.innerHTML = "<i class=\"fas fa-bars\"></i>"; toggleBtn.setAttribute('aria-expanded', 'false'); menu.style.height = 55+"px"; menuLi.style.height = 0; }; function open(){ menu.style.height = 100+"%"; menuLi.style.height = "auto"; menuItem.forEach((item, i)=>{ item.style.left = 0+"px"; item.style.transitionDelay = "0."+i+"s"; }); toggleBtn.innerHTML = "<i class=\"fas fa-times\"></i>"; toggleBtn.setAttribute('aria-expanded', 'true'); };
PHP
UTF-8
1,173
2.59375
3
[ "MIT" ]
permissive
<?php namespace Nuwave\Lighthouse\Schema\Directives; use Nuwave\Lighthouse\Support\Contracts\ArgBuilderDirective; class SearchDirective extends BaseDirective implements ArgBuilderDirective { public static function definition(): string { return /** @lang GraphQL */ <<<'GRAPHQL' """ Perform a full-text search by the given input value. """ directive @search( """ Specify a custom index to use for search. """ within: String ) on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION GRAPHQL; } /** * Apply a scout search to the builder. * * @param \Illuminate\Database\Eloquent\Builder $builder * @return \Laravel\Scout\Builder */ public function handleBuilder($builder, $value): object { /** * TODO make class-string once PHPStan can handle it. * @var \Illuminate\Database\Eloquent\Model&\Laravel\Scout\Searchable $modelClass */ $modelClass = get_class($builder->getModel()); $builder = $modelClass::search($value); if ($within = $this->directiveArgValue('within')) { $builder->within($within); } return $builder; } }
Markdown
UTF-8
1,651
3.015625
3
[ "MIT" ]
permissive
# Annotated Notes plugin for Craft CMS 3.x Field for multiple notes with automatic annotation ## Requirements This plugin requires Craft CMS 3.0.0-beta.23 or later. ## Annotated Notes Overview Annotated Notes is a varient of the [Table](https://docs.craftcms.com/v3/table-fields.html#settings) fieldtype, where the table has two columns: - **Note**, a text field (handle: `note`) - **Annotation** a non-editable text field whose content is generated by twig (handle: `annotation`) ## Configuring Annotated Notes When you create an Annotated Notes field, you specify the twig code which will be parsed after the element is saved to generate the content for the annotations. You can also (under Advanced) specify the user visible labels for the `note` and `annotation` columns (the handles are not changed). ## Using Annotated Notes An Annotated Notes field behaves like a [Table](https://docs.craftcms.com/v3/table-fields.html#settings) field. It has two columns, `Note` and `Annotation`. When you save an Element with an `Annotated Notes` field, any rows which have a `Note` but no `Annotation`, will have the `Annotation` set to the value of the parsed twig. When you edit an Element with an `Annotated Notes` field, the `Notes` can be modified, but the `Annotation`s are not editable. On the front end, the field behaves like any other [Table](https://docs.craftcms.com/v3/table-fields.html#settings) field. The handles for the columns are `note` and `annotation`. Brought to you by [Marion Newlevant](http://marion.newlevant.com) Many thanks to André Elvan, whose [Preparse Field](https://plugins.craftcms.com/preparse-field) was a major influence.
Java
UTF-8
570
1.953125
2
[]
no_license
package com.agency04.sbss.pizza.service; import com.agency04.sbss.pizza.dto.CustomerDTO; import com.agency04.sbss.pizza.model.Customer; import com.agency04.sbss.pizza.model.CustomerForm; import java.util.Optional; public interface CustomerService { Optional<CustomerDTO> findCustomerByUsername(String username); Optional<Customer> findConvertedCustomer(String username); Optional<CustomerDTO> saveCustomer(CustomerForm customerForm); Optional<CustomerDTO> updateCustomer(CustomerForm updatedCustomerForm); void deleteCustomer(String username); }
Java
UTF-8
398
2.71875
3
[]
no_license
import javax.swing.table.DefaultTableModel; class MyTableModel extends DefaultTableModel{ private Object[][] data; MyTableModel(Object[][] data){ this.data = data; } public Object getValueAt(int row, int column) { return data[row][column]; } public int getColumnCount() { return 2; } public int getRowCount() { return 4; } }
Shell
UTF-8
706
3.046875
3
[ "MIT" ]
permissive
#!/bin/sh # # Sample Begin Script for profiled install on x86 # # "@(#)x86-begin 1.5 93/10/13" # #PATH=$PATH:/sbin:/usr/sbin #export PATH # #INSTALL_LOG=/tmp/install_log #ROOT_DEV=c0t0d0p0 # #echo 'Executing profile begin script...' >> $INSTALL_LOG 2>&1 # ## ## Copy all conf files from the directory with the same name as the begin ## script (+ .conf) into the tempfs which will be copied onto the installed ## disk. ## ## SI_BEGIN and SI_CONFIG_DIR come from the caller's environment ## #mkdir -p /tmp/root/kernel/drv >> $INSTALL_LOG 2>&1 #cp -r ${SI_CONFIG_DIR}/${SI_BEGIN}.conf/*.conf /tmp/root/kernel/drv >> $INSTALL_LOG 2>&1 # #echo 'Completed profile begin script.' >> $INSTALL_LOG 2>&1 # #exit 0
PHP
UTF-8
522
2.53125
3
[]
no_license
<?php require_once('../Class_Library/class_post_like.php'); if(!empty($_POST)) { $obj = new Like(); $pid = $_POST['post_id']; $val = $obj->like_display($pid); $val1 = json_decode($val, true); echo $val; } else { ?> <form name="form1" method="post" action="" enctype="multipart/form-data"> <p>Post_id: <label for="textfield"></label> <input type="text" name="post_id" id="textfield"> </p> <p> <input type="submit" name="submit" id="button" value="Click to Display Post Details"> </p> </form> <?php } ?>
JavaScript
UTF-8
516
2.609375
3
[]
no_license
"use strict"; //строгий режим, который запускает "современный код" и исключает ошибки с прошлых версий // use strict в случаях,когда используются классы и модули включать необязательно, //т.к. современный JS автоматически включает его alert( 'Ya est` grut');// вывод диалогового окна с сообщением
Python
UTF-8
487
3.671875
4
[]
no_license
class IsMultiple: def __init__(self,x): self.x = x def __call__(self,func): def wrapper(a,b): r = func(a,b) if r % self.x == 0: print(f'{func.__name__}의 반환값은 {self.x}의 배수가 맞습니다') else: print(f'{func.__name__}의 반환값은 {self.x}의 배수가 아닙니다') return r return wrapper @IsMultiple(5) def add(a,b): return a+b print(add(10,20))
Java
UTF-8
2,853
3.828125
4
[]
no_license
package com.my.java.suanfa.dui; public class MinHeap { // 堆的存储结构 - 数组 private int[] data; //将一个数组传入构造函数, 并转换成一个最小堆,最小的那个元素在堆头 public MinHeap(int[] data) { this.data = data; buildHeap(); } /** * 完全二叉树只有数组下标小于或等于 (data.length) / 2 - 1 的元素有孩子结点,遍历这些结点。 * 比如上面的图中,数组有10个元素, (data.length) / 2 - 1的值为4,a[4]有孩子结点,但a[5]没有 */ private void buildHeap() { for (int i = (data.length / 2) - 1; i >= 0; i--) { heapify(i); } } private void heapify(int i) { int right = (i + 1) << 1; //获取右节点数组下标,<< 1相当于乘以2 int left = ((i + 1) << 1) - 1; //获取左节点数组下标 int smallest = i; // 存在左结点,且左结点的值小于根结点的值 if (left < data.length && data[left] < data[i]) { smallest = left; } // 存在右结点,且右结点的值小于以上比较的较小值 if (right < data.length && data[right] < data[smallest]) { smallest = right; } if (i == smallest) { return; } // 交换根节点和左右结点中最小的那个值,把根节点的值替换下去 int tmp = data[i]; data[i] = data[smallest]; data[smallest] = tmp; // 由于替换后左右子树会被影响,所以要对受影响的子树再进行heapify heapify(smallest); } /** * 获取堆中最小的元素, 根元素 */ private int getRoot() { if (data.length != 0) { return data[0]; } return -1; } /** * 替换根元素并重新heapify */ private void setRoot(int root) { data[0] = root; heapify(0); } public static void main(String[] args) { //<< 1相当于乘以2 System.out.println((13 +1) << 1); int[] data = new int[]{12, 23, 4, 2, 3, 32, 42, 1, 33, 55, 2, 88, 18, 5, 12}; int[] topK = topK(data, 8); for (int tmp : topK) { System.out.println(tmp); } } // 当数据大于堆中最小的数(根节点)时,替换堆中的根节点,再转换成堆 private static int[] topK(int[] data, int k) { int[] topK = new int[k]; //取前K个元素放到tok 数组中 System.arraycopy(data, 0, topK, 0, k); MinHeap heap = new MinHeap(topK); for (int i = k; i < data.length; i++) { int root = heap.getRoot(); if (data[i] > root) { heap.setRoot(data[i]); } } return topK; } }
C#
UTF-8
1,667
2.890625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ElvenTools.Utils; namespace Day17 { public class ConwayEvaluator { public static long Evaluate(Dictionary<string, bool> coordinates) { for (var i = 0; i < 6; i++) { coordinates.Keys.ToList().ForEach(c => { LinqExtension.DimensionalNeighbors(c.Split(',').Select(int.Parse)) .Select(t => string.Join(',', t)) .Where(t => !coordinates.ContainsKey(t)) .ToList() .ForEach(t => coordinates[t] = false); }); var coordinatesCopy = new Dictionary<string, bool>(); coordinates.Keys.ToList().ForEach(c => { var activeNeighbors = LinqExtension.DimensionalNeighbors(c.Split(',').Select(int.Parse)) .Select(t => string.Join(',', t)) .Where(t => coordinates.ContainsKey(t)) .Select(t => coordinates[t]) .Count(v => v); coordinatesCopy[c] = coordinates[c] switch { true when (activeNeighbors < 2 || activeNeighbors > 3) => false, false when activeNeighbors == 3 => true, _ => coordinates[c] }; }); coordinates = coordinatesCopy; } return coordinates.Values.Count(v => v); } } }
Java
ISO-8859-7
200
1.882813
2
[]
no_license
package p2; import java.util.*; public class n_18108 { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n=sc.nextInt(); System.out.println(n-543); } }
Python
UTF-8
960
2.90625
3
[]
no_license
from cierreJornada import * class Empleado: def __init__(self, nombre = "test"): self.nombre = nombre self.porcentajeGanancias = 0 self.horasTrabajadasJornada = 0 def setNombre(self, nombre): self.nombre = nombre def getNombre(self): return self.nombre def setHorasTrabajadasJornada(self, horasTrabajadasJornada): self.horasTrabajadasJornada = horasTrabajadasJornada def getHorasTrabajadasJornada(self): return self.horasTrabajadasJornada def setPorcentajeGanancias(self, porcentajeGanancias): self.porcentajeGanancias = porcentajeGanancias def getPorcentajeGanancias(self): return self.porcentajeGanancias if __name__ == '__main__': # Configuración de la aplicación jornada = CierreJornada() jornada.setTotalPropinas(200) jornada.setTotalHorasCamareros(15) plantillaPersonal = [] # Los casos test de esta clase requieren conocimientos de diccionarios... y no habéis querido leerlos... # En breve los escribo.
Python
UTF-8
328
2.625
3
[]
no_license
N = int(input()) dp = [[0 for _ in range(10)] for _ in range(1001)] for i in range(0, 10): dp[1][i] = 1 for i in range(2, N + 1): for j in range(10): if j == 9: dp[i][j] = dp[i - 1][9] else: for k in range(j, 10): dp[i][j] += dp[i - 1][k] print(sum(dp[N]) % 10007)
Shell
UTF-8
373
3.671875
4
[]
no_license
#!/usr/bin/env bash LESS_FILES="bootstrap.less style.less email.less" LESS_DIR=$(dirname $0)/public/css CSS_DIR=$LESS_DIR if [ "$1" = "wait" ] ; then # Wait a few moment for file to be written (if network mounted) sleep 1 fi for less in $LESS_FILES ; do css=$(echo $less | sed 's/\.less$/.css'/) echo "$less => $css..." lessc "$LESS_DIR/$less" "$CSS_DIR/$css" done
Java
UTF-8
1,504
3.15625
3
[ "MIT" ]
permissive
package examples.classes; import helpers.Description; import static helpers.Difficulty.*; import static helpers.Topic.*; public class Classes { /** * You can access private variables of inner class */ @Description(topics = {INNER_CLASSES, ACCESS_MODIFIERS}, difficulty = EASY) private static class Inner { private static final Object CONST_1 = new Object(); private Object notConst = new Object(); } private void intruder() { Object o1 = Inner.CONST_1; Object o2 = new Inner().notConst; } /** * Cyclic dependencies are forbidden * it's compilation time error */ @Description(topics = {INHERITANCE}, difficulty = EASY) public static void cyclicDependency() {} // static class XXX extends YYY{} // static class YYY extends XXX {} // static interface AAA extends BBB {} // static interface BBB extends AAA {} // static class A1 extends A3 {} // static class A2 extends A1 {} // static class A3 extends A2 {} /** * This class name is String, so it hides java.lang.String, so * assigning string literal to non-string reference is compilation time error */ @Description(topics = {WEIRD_SYNTAX}, difficulty = MEDIUM) public static void stringHidding() { class String { // String x = "value"; // not ok java.lang.String y = "value"; // ok } } public static void main(String... args) { } }
Java
UTF-8
2,007
2.71875
3
[]
no_license
package com.project.entities.infrastructure.building; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.SequenceGenerator; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.project.entities.infrastructure.floor.Floor; @Entity public class Building { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "bulding_generator") @SequenceGenerator(name = "building_generator", sequenceName = "building_sequence", initialValue = 1, allocationSize = 1) @Column(name = "id", updatable = false, nullable = false) private Long id; @Column(name = "name", nullable = false) private String name; @Column(name = "address", nullable = false) private String address; @JsonIgnoreProperties(value = "building") @OneToMany(mappedBy = "building", cascade = CascadeType.ALL, orphanRemoval = true) private Set<Floor> floors; /* ----- CONSTRUCTORS ----- */ public Building() { super(); } public Building(String name, String address) { super(); this.name = name; this.address = address; this.floors = new HashSet<Floor>(); } /* ----- GETTERS & SETTERS ----- */ public Long getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Set<Floor> getFloors() { return floors; } public void setFloors(Set<Floor> floors) { this.floors = floors; } /* ----- METHODS ----- */ public void addFloor(Floor floor) { this.floors.add(floor); floor.setBuilding(this); } public void removeFloor(Floor floor) { this.floors.remove(floor); floor.setBuilding(null); } }
Python
UTF-8
7,675
2.53125
3
[]
no_license
#!/usr/bin/env python import sys def usage(): if len(sys.argv) < 5: print("Usage: <program> <inputFile> <annFile> <syncFile> <outFile>") sys.exit(0) def make_NSdict(): NSd = {} with open("/home/mrood/WH-BH/data/enrichmentGuide2.txt", 'r') as infile: next(infile) for line in infile: line = line.strip().split('\t') NSd[line[1]] = int(line[5]) print("There are {0} samples.".format(len(NSd))) return NSd def gen_outliers(inputFile, NSd): outliers = [] patA = set() patB = set() patC = set() patD = set() patE = set() for samp in NSd: column = int(NSd[samp]) with open(inputFile, 'r') as infile: next(infile) for line in infile: line = line.strip().split('\t') value = line[column] if value != 'DQ' and value != 'Inf' and value != 'NaN' and value != '-': NS = float(line[column]) if NS > 1.0: outliers.append((samp, line[0], value)) if samp[0] == 'A': patA.add(line[0]) elif samp[0] == 'B': patB.add(line[0]) elif samp[0] == 'C': patC.add(line[0]) elif samp[0] == 'D': patD.add(line[0]) elif samp[0] == 'E': patE.add(line[0]) print("There are {0} outliers.".format(len(outliers))) return outliers, patA, patB, patC, patD, patE def summary_dict(inputFile): d = {} with open(inputFile, 'r') as infile: next(infile) for line in infile: line = line.strip().split('\t') if int(line[1]) in d: d[int(line[1])].append((line[0],float(line[2]),float(line[3]),float(line[4]))) else: d[int(line[1])] = [(line[0],float(line[2]),float(line[3]),float(line[4]))] print('There are {0} snps in the dictionary'.format(len(d))) return d def simp_dict(d): d2 = {} for pos in d: fstVals = [] for tup in d[pos]: fst = tup[1] fstVals.append(fst) #print('for {pos} there are {l} entries'.format(pos=pos, l=len(fstVals))) rInd = fstVals.index(max(fstVals)) d2[pos] = [d[pos][rInd]] return d2 def make_geneDict(): geneDict = {} with open("/home/mrood/scripts/importantFiles/PerGeneSummary.txt", 'r') as dat: for line in dat: line = line.strip().split('\t') start = int(line[4]) stop = int(line[5]) gene = line[0] geneDict[gene] = [start,stop,line[1],line[7]] return geneDict def annotate_snp(d2, geneDict): for snp in d2: geneList = [] commonList = [] desList = [] for gene in geneDict: if snp >= geneDict[gene][0] and snp <= geneDict[gene][1]: geneList.append(gene) commonList.append(geneDict[gene][2]) desList.append(geneDict[gene][3]) d2[snp].append(geneList) d2[snp].append(commonList) d2[snp].append(desList) return d2 def find_freq(syncFile, d2): freqDict = {} with open(syncFile, 'r') as sync: for line in sync: line = line.strip().split('\t') pos = int(line[1]) ref = line[2] freqs = [] samps = line[3:] if pos in d2: cS1 = samps[0].split(":") cS1 = [int(i) for i in cS1] maa = cS1.index(max(cS1)) for samp in samps: counts = samp.split(":") counts = [int(x) for x in counts] cov = sum(counts) if cov < 10: af = "NA" else: #if ref == "A": if maa == 0: ma = "A" af = 1 - float(counts[0])/cov #elif ref == "T": elif maa == 1: ma = "T" af = 1 - float(counts[1])/cov #elif ref == "C": elif maa == 2: ma = "C" af = 1 - float(counts[2])/cov #elif ref == "G": elif maa == 3: ma = "G" af = 1 - float(counts[3])/cov af2 = "{0:.2f}".format(af) if float(af2) == 1.00: af2 = "1.0" freqs.append(af2) freqDict[pos] = freqs d2[pos].append(ma) d2[pos].append(freqs) return d2 def make_snpDict(annFile, d2): snpDict = {} with open(annFile, 'r') as ann: for line in ann: line = line.strip().split() snpDict[int(line[0])] = line[1:] for snp in d2: try: d2[snp].append(snpDict[snp]) except KeyError: d2[snp].append(["NA","NA","NA","NA","NA","NA"]) return d2 def make_catDict(d2): catDict = {} with open("/home/mrood/scripts/importantFiles/NumberedGeneSet.txt", 'r') as catFile: for line in catFile: line = line.strip().split('\t') cat = line[0] catDict[cat] = [i.replace("c","") for i in line[2].split()] for snp in d2: if len(d2[snp][1]) > 0: gene = d2[snp][1][0].replace("c","") catList = [] for cat in catDict: if gene in catDict[cat]: catList.append(cat) catList = [int(i) for i in catList] d2[snp].append(sorted(catList)) return d2 def make_catDict2(): catDict = {} with open("/home/mrood/scripts/importantFiles/NumberedGeneSet.txt", 'r') as catFile: for line in catFile: line = line.strip().split('\t') cat = line[0] catDict[cat] = [i.replace("c","") for i in line[2].split()] return catDict def write_outfile2(inFileName,outFileName,catDict,geneDict): with open(inFileName, 'r') as inFile, open(outFileName, 'w') as outFile: for line in inFile: line = line.strip() gene = line.replace("c", "") geneCatList = [] for cat in catDict: if gene in catDict[cat]: geneCatList.append(cat) outFile.write('%s\t%s\t%s\n' % (line, "\t".join(geneDict[line][2:]), ",".join(geneCatList))) def write_outfile(d2,outFile): with open(outFile, 'w') as outfile: for snp in d2: outfile.write('%s\t%i\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' % ("\t".join([str(i) for i in d2[snp][0]]), snp, ", ".join(d2[snp][1]), ", ".join(d2[snp][2]), ", ".join(d2[snp][3]), d2[snp][4], ", ".join([str(i) for i in d2[snp][5]]), "\t".join(d2[snp][6]), ", ".join([str(i) for i in d2[snp][7]])) ) #usage() #inputFile, annFile, syncFile, outFile = sys.argv[1:] #d = summary_dict(inputFile) #d2 = simp_dict(d) #geneDict = make_geneDict() #d2 = annotate_snp(d2,geneDict) #d2 = find_freq(syncFile,d2) #d2 = make_snpDict(annFile,d2) #d2 = make_catDict(d2) #write_outfile(d2,outFile)
JavaScript
UTF-8
527
2.984375
3
[]
no_license
// Bind the event handler to the "submit" JavaScript event $('form').submit(function () { var inputs = [ "#inputName", "#inputEmail", "#inputPhone", "#inputStates", "#inputPassword", "#inputTerms" ]; var error = false; inputs.forEach(function(e) { // Get the Login Name value and trim it var name = $.trim($(e).val()); // Check if empty of not if (name === '') { alert(e + ' is empty.'); error = true; } }); if (error) { return false; } });
Java
UTF-8
4,145
1.914063
2
[]
no_license
import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import java.util.List; import java.util.concurrent.TimeUnit; import static java.lang.Thread.sleep; public class Cinema { public WebDriver driver; @Before public void setup() { System.setProperty("webdriver.chrome.driver", "C:\\Users\\OUT-Akopyan-SR\\driver\\ChromeDriver 72.0.3626.69.exe"); driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.get("https://afisha.mail.ru/"); driver.manage().window().maximize(); } @Test public void Cinema () throws InterruptedException { WebElement Cino = driver.findElement(By.xpath("//span[text()='В кино']")); Cino.click(); WebDriverWait wait = new WebDriverWait(driver, 5); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@class='input-group__item']//div[@class='dropdown__text js-dates__title' and text()='Сегодня']"))); WebElement Tomorrow = driver.findElement(By.xpath("//div[@class='input-group__item']//div[@class='dropdown__text js-dates__title' and text()='Сегодня']")); Tomorrow.click(); wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//div[@data-module='CustomScroll']//input[@data-title='Завтра']/.."))); WebElement ChooseDay = driver.findElement(By.xpath("//div[@data-module='CustomScroll']//input[@data-title='Завтра']/..")); ChooseDay.click(); WebElement Metro = driver.findElement(By.xpath("//div[@class='input-group__item']//input[@class='input__field js-suggest__input' and @placeholder=\"Станции метро\"]")); Metro.click(); Metro.sendKeys("Курская"); WebElement ChooseMetro = driver.findElement(By.xpath("//div[@data-id='68']")); ChooseMetro.click(); WebElement ChooseJaners = driver.findElement(By.xpath("//form[@data-action='/ajax/kinoafisha/']//input[@class='input__field padding_right_40 js-select__filter']")); ChooseJaners.click(); List<WebElement> listJaners = driver.findElements(By.xpath("//div[@class='suggest suggest_active dropdown__suggest']//div[@data-optidx]")); for (WebElement element : listJaners) { String text = element.findElement(By.xpath("./div/span")).getText(); if(text.equals("драма") || text.equals("комедия")) { element.click(); } } WebElement Seans = driver.findElement(By.xpath("//div[@class='checkbox checkbox_colored margin_right_20']")); Seans.click(); WebElement Podborka = driver.findElement(By.xpath("//button[@class='button button_color_project']")); Podborka.click(); WebElement headerIcon = driver.findElement(By.xpath("//h1[@class='title__title']")); Assert.assertTrue("Страница не загрузилась https://kino.mail.ru/", headerIcon.isDisplayed()); WebElement Proverka1 = driver.findElement(By.xpath("//div[@class='dropdown__text js-dates__title' and text()='Завтра']")); Assert.assertTrue("Страница не загрузилась https://kino.mail.ru/", Proverka1.isDisplayed()); WebElement Proverka2 = driver.findElement(By.xpath("//span[@class='tag__text' and text()='комедия']")); Assert.assertTrue("Страница не загрузилась https://kino.mail.ru/", Proverka2.isDisplayed()); WebElement Proverka3 = driver.findElement(By.xpath("//div[@class='checkbox checkbox_colored margin_right_20']")); Assert.assertTrue("Страница не загрузилась https://kino.mail.ru/", Proverka3.isDisplayed()); } @After public void tearDown() { driver.quit(); } }
Swift
UTF-8
3,042
3.296875
3
[]
no_license
// // Connections.swift // MeteorologySwift5 // // Created by Carlos on 03/05/2020. // Copyright © 2020 TestCompany. All rights reserved. // import UIKit protocol getWeatherDelegate { func getWeatherDidFinish(weatherInfo : Weather) func getWeatherDidFailWithError(error : NSError) } class Connections { // Example -> "https://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=myAPIKey" fileprivate let baseURL : String = "https://api.openweathermap.org/data/2.5/weather" #warning("WARNING: PUT YOUR OWN APIKEY: api.openweathermap.org") fileprivate let openWeatherMapKey : String = "1234567890" fileprivate var delegate : getWeatherDelegate init(delegate: getWeatherDelegate) { self.delegate = delegate if openWeatherMapKey == "1234567890" { print(""" ============================== == == Do you have your own APIkey? == ============================== """) } } // Request by city func requestWeatherByCity(_ city: String) { let weatherRequestURL = URL(string: "\(baseURL)?q=\(city)&APPID=\(openWeatherMapKey)&lang=es")! getWeather(weatherRequestURL) } // Request by place func requestWeatherByLocation(latitude: Double, longitude: Double) { let weatherRequestURL = URL(string: "\(baseURL)?APPID=\(openWeatherMapKey)&lat=\(latitude)&lon=\(longitude)&lang=es")! getWeather(weatherRequestURL) } } extension Connections { func getWeather(_ weatherRequestURL: URL) { let session = URLSession.shared session.configuration.timeoutIntervalForRequest = 5 // Seconds let urlRequest : NSMutableURLRequest = NSMutableURLRequest(url: weatherRequestURL) let task = session.dataTask(with: urlRequest as URLRequest) { (data, response, error) -> Void in let httpResponse = response as! HTTPURLResponse let statusCode = httpResponse.statusCode if (statusCode == 200) { do { let parsedData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : Any] let weather = Weather(datosTiempo: parsedData as [String : AnyObject]) self.delegate.getWeatherDidFinish(weatherInfo: weather) print("El tiempo tiene: \(weather)") } catch let jsonError as NSError { self.delegate.getWeatherDidFailWithError(error: jsonError) print("Error: \(jsonError)") } } } task.resume() } }
JavaScript
UTF-8
4,141
3.34375
3
[ "MIT" ]
permissive
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var is = exports.is = function is(type, value) { if (type && type.isValid instanceof Function) { return type.isValid(value); } else if (type === String && (value instanceof String || typeof value === 'string') || type === Number && (value instanceof Number || typeof value === 'number') || type === Boolean && (value instanceof Boolean || typeof value === 'boolean') || type === Function && (value instanceof Function || typeof value === 'function') || type === Object && (value instanceof Object || (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') || type === undefined) { return true; } return false; }; var check = function check(types, required, data) { Object.keys(types).forEach(function (key) { var t = types[key], value = data[key]; if (required[key] || value !== undefined) { if (!(t instanceof Array)) t = [t]; var i = t.reduce(function (a, _type) { return a || is(_type, value); }, false); if (!i) { throw '{' + key + ': ' + JSON.stringify(value) + '} is not one of ' + t.map(function (x) { return '\n - ' + x; }); } } }); return true; }; var Model = exports.Model = function Model() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var types = void 0, required = void 0, logic = void 0; args.map(function (x) { if (x instanceof Function && !logic) { logic = x; } else if ((typeof x === 'undefined' ? 'undefined' : _typeof(x)) === 'object') { if (!types) { types = x; } else if (!required) { required = x; } } }); var isValid = function isValid(data) { var pipe = logic ? [check, logic] : [check]; return pipe.reduce(function (a, v) { return a && v(types || {}, required || {}, data); }, true); }; var whenValid = function whenValid(data) { return new Promise(function (res, rej) { return isValid(data) && res(data); }); }; return { isValid: isValid, whenValid: whenValid }; }; var ArrayOf = exports.ArrayOf = function ArrayOf(M) { return Model(function (t, r, data) { if (!(data instanceof Array)) throw data + ' not an Array'; data.map(function (x) { if (!is(M, x)) throw x + ' is not a model instance'; }); return true; }); }; /** Use it // create a Name model with required first/last, // but optional middle let Name = Model({ first: String, middle: String, last: String }, {first:true, last:true}) // create a Tags model with extra checks let Tags = Model((types,required,data) => { if(!(data instanceof Array)) throw `${data} not an Array` data.map(x => { if(!is(String, x)) throw `[${data}] contains non-String` }) return true }) // create a Price model that just has a business logic fn let Price = Model((t,r,d) => { return (d instanceof Number || typeof d === 'number') && d !== 0 }) // create an Activity model with a required type and name, // all others optional let Activity = Model({ type: [String, Function, Number], latlng: Array,//LatLng, title: String, tags: Tags, name: Name, price: Price }, {name:true, price: true}) // create a new Activity instance, throwing errors if there are // any invalid fields. let a = { tags: ['1','2'], type: 1, name: {first:'matt',last:'keas'}, price: 100.43, url: 'http://www.google.com' } Activity.whenValid(a).then(log).catch(e => log(e+'')) **/
Java
UTF-8
6,224
2.09375
2
[]
no_license
package com.xin.webservice; import java.net.URLEncoder; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Properties; import com.qcloud.cos.COSClient; import com.qcloud.cos.ClientConfig; import com.qcloud.cos.exception.AbstractCosException; import com.qcloud.cos.request.CreateFolderRequest; import com.qcloud.cos.request.UploadFileRequest; import com.qcloud.cos.sign.Sign; import com.xin.system.dao.FileUploadDao; import com.zhenhr.tools.Base64; import com.zhenhr.tools.JsonUtil; import com.zhenhr.tools.PropertiesUtils; import com.zhenhr.tools.RandomUtils; import org.json.JSONObject; /** * @author guoyongshi */ public class COSClientService { /** * 创建签名 * * @param fileType * @return */ public static FileUploadDao createFileSign(String fileType) { String path = "/default"; String fileName = createFileName(fileType); fileName = path + "/" + fileName; FileUploadDao dao = new FileUploadDao(); dao.setKey(fileName); CosAccount account = new CosAccount(); long expired = System.currentTimeMillis() / 1000 + 600; try { String bucketName = account.getFileBucketName(); String signStr = Sign.getPeriodEffectiveSign(bucketName, fileName, account.getCredentials(), expired); dao.setSign(signStr); dao.setUrl(account.getFileHost() + fileName); dao.setUploadUrl(account.getUploadFileHost(bucketName, fileName)); return dao; } catch (AbstractCosException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * 创建企业上传文件 * * @param companyId * @param folder * @param fileName * @param fileType * @return */ public static FileUploadDao createFileSign(Long companyId, String folder, String fileName, String fileType) { // 创建目录 if (folder != null) { if (!folder.startsWith("/")) { folder = "/" + folder; } if (!folder.endsWith("/")) { folder += "/"; } if (companyId != null) { folder += companyId + "/"; } String result = COSClientService.createFolder(folder + companyId); } // 获取文件名称 if (fileName == null) { fileName = createFileName(fileType); } else { if (!fileName.endsWith(fileType)) { if (fileType.startsWith(".")) { fileName += fileType; } else { fileName += "." + fileType; } } } if (folder != null) { fileName = folder + fileName; } else { fileName = "/default/" + fileName; } FileUploadDao dao = new FileUploadDao(); dao.setKey(fileName); CosAccount account = new CosAccount(); long expired = System.currentTimeMillis() / 1000 + 600; try { String bucketName = account.getFileBucketName(); String signStr = Sign.getPeriodEffectiveSign(bucketName, fileName, account.getCredentials(), expired); dao.setSign(signStr); dao.setUrl(account.getFileHost() + fileName); dao.setUploadUrl(account.getUploadFileHost(bucketName, fileName)); return dao; } catch (AbstractCosException e) { e.printStackTrace(); return null; } } public static void deleFile(String path) { } /** * 创建path * * @return */ public static String createFolder(String folder) { CosAccount account = new CosAccount(); COSClient cosClient = getClient(); if (!folder.endsWith("/")) { folder += "/"; } CreateFolderRequest request = new CreateFolderRequest(account.getFileBucketName(), folder); String result = cosClient.createFolder(request); return result; } private static COSClient getClient() { CosAccount account = new CosAccount(); ClientConfig clientConfig = new ClientConfig(); clientConfig.setRegion(account.getRegion()); COSClient cosClient = new COSClient(clientConfig, account.getCredentials()); return cosClient; } private static String createFileName(String fileType) { String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); fileName = fileName + RandomUtils.generateNumber(5); if (fileType.startsWith(".")) { fileName += fileType; } else { fileName += "." + fileType; } return fileName; } public static void testUpload() { Properties prop = PropertiesUtils.getProperties("qcos.properties"); int appId = Integer.valueOf(prop.getProperty("appId")); String secretId = prop.getProperty("secretId"); String secretKey = prop.getProperty("secretKey"); String bucketName = prop.getProperty("file_bucketName"); String filehost = prop.getProperty("filehost"); filehost = filehost.replaceAll("#bucketName#", bucketName); COSClient cosClient = new COSClient(appId, secretId, secretKey); String cosFilePath = "/sample_file.txt"; String localFilePath1 = "/Volumes/work/deploy.sh"; UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, cosFilePath, localFilePath1); String uploadFileRet = cosClient.uploadFile(uploadFileRequest); JSONObject uploadFileJson = new JSONObject(uploadFileRet); } public static void main(String[] args) { // Integer a = 10; // Integer b = 10; // Long l = 20L; // Integer c = 200; // Integer d = 200; // System.out.println(a == b); // // System.out.println(c.equals(d)); // // System.out.println(l == a+b); // System.out.println(l.equals( a+b)); } }
Java
UTF-8
2,262
2.4375
2
[]
no_license
package com.example.person.service; import com.example.person.core.PersonNotFoundException; import com.example.person.domain.Person; import com.example.person.domain.PersonMapper; import com.example.person.domain.dto.MensageDTO; import com.example.person.domain.dto.PersonDTO; import com.example.person.repository.PersonRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import lombok.AllArgsConstructor; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @AllArgsConstructor(onConstructor = @__(@Autowired)) @Service public class PersonService { private final PersonRepository personRepository; private final PersonMapper personMapper = PersonMapper.INSTANCE; private MensageDTO createMessageResponse(Long id, String message) { return MensageDTO .builder() .mensage(message + id) .build(); } private Person converterDTOToPerson(PersonDTO personDTO) { Person personToSave = personMapper.toModel(personDTO); return personRepository.save(personToSave); } public MensageDTO insert(PersonDTO personDTO) { Person salved = converterDTOToPerson(personDTO); return createMessageResponse(salved.getId(), "Created person with ID :"); } public PersonDTO findById(Long id) throws PersonNotFoundException { Person person = personRepository .findById(id) .orElseThrow(() -> new PersonNotFoundException(id)); return personMapper.toDTO(person); } public List<PersonDTO> findByAll() { return personRepository .findAll() .stream() .map(personMapper::toDTO) .collect(Collectors.toList()); } public void deleteById(Long id) throws PersonNotFoundException { findById(id); personRepository.deleteById(id); } public MensageDTO update(Long id, PersonDTO personDTO) throws PersonNotFoundException { findById(id); Person personToUpdate = converterDTOToPerson(personDTO); return createMessageResponse(personToUpdate.getId(), "Update person with ID :"); } }
Java
UTF-8
785
2.34375
2
[]
no_license
/** * */ package com.mu.muls.util; import java.util.Date; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; import org.springframework.format.annotation.DateTimeFormat; /** * @author bolinluo * */ public class ApDemoUtil { /** * @param args */ public static void main(String[] args) { String bankStr = " "; String str1 = " aabc dwa dxyrt "; System.out.println("bankStr="+StringUtils.isNotBlank(bankStr)); System.out.println("Str1="+StringUtils.remove(str1, "ad")); System.out.println("Str1 remove="+StringUtils.remove(str1, "a")); System.out.println("Str1 strip="+StringUtils.strip(str1)); System.out.println(" ToStringBuilder="+ToStringBuilder.reflectionToString(new String())); } }
Python
UTF-8
555
4.0625
4
[]
no_license
""" PROBLEM 1 #If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. #The sum of these multiples is 23. #Find the sum of all the multiples of 3 or 5 below 1000. """ response = input("Input Number: ") sum = 0 counter = 0 print "Numbers Divisible by 3 or 5" print "---------------------------" for i in range(0,response): if (i % 3 == 0 or i % 5 == 0): print i, counter += 1 if (counter == 5): print counter = 0 sum += i print "\n\nSum: ", sum
C
UTF-8
434
3.421875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> int main() { int x; int y; printf("Please enter coordinate x y : "); scanf("%d %d",&x,&y); if(x>0&&y>0) printf("(%d,%d) = Q1",x,y); else if(x<0,y>0) printf("(%d,%d) = Q2",x,y); else if(x<0,y<0) printf("(%d,%d) = Q3",x,y); else if(x>0,y<0) printf("(%d,%d) = Q4",x,y); else(x=0&&y=0) printf("(%d,%d)",x,y); return 0; }
JavaScript
UTF-8
763
2.765625
3
[]
no_license
const express = require('express'); const app = express(); app.use(express.json()); /* cuando entre o visite la aplicacion, llevar a cabo una funcion la cual va despues de la coma (,)*/ app.get('/user', (req, res) => { res.json({ username:'Cameron', lastmane:'Howe' }); }); app.post('/user:id', (req, res) => { console.log(req.body); console.log(req.params); res.send('Post Request Received'); }) app.put('/contact', (req, res) => { res.send('update r R'); }) app.delete('/test', (req, res) => { res.send('<h1>delete rescuet RR</h1>'); }) //se le indica al server que muestre el mensaje en el localhost:5000 app.listen(5000, ()=> { console.log('Server en puerto 5000'); })
Python
UTF-8
304
2.84375
3
[]
no_license
# First way: import packages.Pack1.Module1 packages.Pack1.Module1.f1() # function f1 in module1 # Second way: Much easier from packages.Pack1.Module1 import f1 f1() # function f1 in module1 # subpackages from packages.Pack1.Module1 import f1 from packages.Pack1.Pack2.Module2 import f2 f1() f2()
Java
UTF-8
2,065
3.359375
3
[]
no_license
package mules.moscow.dungeonsanddragons5echaractersheet; import java.util.ArrayList; public class AbilityScore { private int score; private int modifier; private ArrayList<Integer> RaceModifiers = new ArrayList<>(); private ArrayList<Integer> ClassModifiers = new ArrayList<>(); /** * AbilityScore constructor. Adds all race modifiers to the ability score. * @param base The base score rolled for the player * @param RaceList List containing races and their modifiers(?) */ AbilityScore(int base, ArrayList<Integer> RaceList){ RaceModifiers.addAll(RaceList); } /** * Sets the modifier for the player's ability score * @param num The base score rolled for the player * @param raceIndex The modifier for the score given the player's race * @param classIndex The modifier for the score given the player's class(?) */ public void setScore(int num, int raceIndex, int classIndex) { this.score = num + RaceModifiers.get(raceIndex) + ClassModifiers.get(classIndex); if(score >= 19) { this.modifier = 5; } else if(score >= 17 && score <19) { this.modifier = 4; } else if(score >= 15 && score <17) { this.modifier = 3; } else if(score >= 13 && score <15) { this.modifier = 2; } else if(score >= 11 && score <13) { this.modifier = 1; } else if(score == 10) { this.modifier = 0; } else if(score >= 8 && score <10) { this.modifier = -1; } else if(score >= 6 && score <8) { this.modifier = -2; } else if(score >= 4 && score <6) { this.modifier = -3; } else if(score >= 2 && score <4) { this.modifier = -4; } else if(score <2){ this.modifier= -5; } } /** * returns the player's ability score * @return the player's ability score */ public int getScore() { return this.score; } /** * returns the player's ability score modifier * @return the player's ability score modifier */ public int getModifier() { return this.modifier; } }
Java
UTF-8
5,434
2.65625
3
[]
no_license
package com.example.rafael.popularmovies.Utilities; import android.content.ContentValues; import android.database.Cursor; import android.graphics.Movie; import com.example.rafael.popularmovies.data.MovieContract; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by Rafael on 17/02/2018. */ public class Parsing { public static List<Movies> parseFromJsonMovies(String jsonMovieData) { try { List<Movies> moviesList = new ArrayList<>(); JSONObject jsonObjectMovieData = new JSONObject(jsonMovieData); JSONArray jsonArrayMovies = jsonObjectMovieData.getJSONArray("results"); for(int i = 0; i < jsonArrayMovies.length(); i++){ JSONObject movieIterator = jsonArrayMovies.getJSONObject(i); String original_title = movieIterator.getString("original_title"); String poster_path = movieIterator.getString("poster_path"); String overview = movieIterator.getString("overview"); String vote_average = movieIterator.getString("vote_average"); String release_date = movieIterator.getString("release_date"); String id = movieIterator.getString("id"); Movies movie = new Movies(original_title,poster_path,overview,vote_average,release_date, id); moviesList.add(movie); } return moviesList; } catch (JSONException e) { e.printStackTrace(); } return null; } public static List<Review> parseFromJsonReviews(String jsonReviewData) { try { List<Review> reviewsList = new ArrayList<>(); JSONObject jsonObjectReviewData = new JSONObject(jsonReviewData); JSONArray jsonArrayReviews = jsonObjectReviewData.getJSONArray("results"); for(int i = 0; i < jsonArrayReviews.length(); i++){ JSONObject movieIterator = jsonArrayReviews.getJSONObject(i); String author = movieIterator.getString("author"); String content = movieIterator.getString("content"); Review review = new Review(author,content); reviewsList.add(review); } return reviewsList; } catch (JSONException e) { e.printStackTrace(); } return null; } public static List<Trailer> parseFromJsonTrailers(String jsonTrailerData) { try { List<Trailer> trailersList = new ArrayList<>(); JSONObject jsonObjectTrailerData = new JSONObject(jsonTrailerData); JSONArray jsonArrayTrailers = jsonObjectTrailerData.getJSONArray("results"); for(int i = 0; i < jsonArrayTrailers.length(); i++){ JSONObject movieIterator = jsonArrayTrailers.getJSONObject(i); String key = movieIterator.getString("key"); String name = movieIterator.getString("name"); Trailer trailer = new Trailer(key,name); trailersList.add(trailer); } return trailersList; } catch (JSONException e) { e.printStackTrace(); } return null; } public static ContentValues parseMovieToContentValues(Movies mCurrentMovie) { ContentValues resultContentValues = new ContentValues(); resultContentValues.put(MovieContract.MovieEntry.COLUMN_MOVIE_ID, mCurrentMovie.getMovie_id()); resultContentValues.put(MovieContract.MovieEntry.COLUMN_OVERVIEW, mCurrentMovie.getOverview()); resultContentValues.put(MovieContract.MovieEntry.COLUMN_POSTER_PATH, mCurrentMovie.getPoster_path()); resultContentValues.put(MovieContract.MovieEntry.COLUMN_RELEASE_DATE, mCurrentMovie.getRelease_date()); resultContentValues.put(MovieContract.MovieEntry.COLUMN_TITLE, mCurrentMovie.getOriginal_title()); resultContentValues.put(MovieContract.MovieEntry.COLUMN_VOTE_AVERAGE, mCurrentMovie.getVote_average()); return resultContentValues; } public static List<Movies> parseFromCursorToMovieList(Cursor dataMovies) { //Based on https://stackoverflow.com/questions/10723770/whats-the-best-way-to-iterate-an-android-cursor List<Movies> moviesList = new ArrayList<>(); for (dataMovies.moveToFirst(); !dataMovies.isAfterLast(); dataMovies.moveToNext()) { String movieId = dataMovies.getString(dataMovies.getColumnIndex(MovieContract.MovieEntry.COLUMN_MOVIE_ID)); String overview = dataMovies.getString(dataMovies.getColumnIndex(MovieContract.MovieEntry.COLUMN_OVERVIEW)); String posterPath = dataMovies.getString(dataMovies.getColumnIndex(MovieContract.MovieEntry.COLUMN_POSTER_PATH)); String releaseDate = dataMovies.getString(dataMovies.getColumnIndex(MovieContract.MovieEntry.COLUMN_RELEASE_DATE)); String title = dataMovies.getString(dataMovies.getColumnIndex(MovieContract.MovieEntry.COLUMN_TITLE)); String voteAverage = dataMovies.getString(dataMovies.getColumnIndex(MovieContract.MovieEntry.COLUMN_VOTE_AVERAGE)); Movies movie = new Movies(title,posterPath,overview,voteAverage,releaseDate, movieId); moviesList.add(movie); } return moviesList; } }
Markdown
UTF-8
15,109
3.328125
3
[ "Apache-2.0" ]
permissive
# Kubernetes Building Blocks In this chapter, we will explore the [Kubernetes object model](https://kubernetes.io/docs/concepts/overview/working-with-objects/kubernetes-objects/) and describe some of its fundamental building blocks, such as **Pods**, **ReplicaSets**, **Deployments**, **Namespaces**, etc. We will also discuss the essential role of **Labels** and **Selectors** in a microservices driven architecture as they logically group decoupled objects together. --- There are an [API Convention](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-architecture/api-conventions.md), which describes technically each of the Kubernetes terms. The Kubernetes object model is very rich and can represent several **persistent entities** in the Kubernetes cluster. Those entities describe the containerized applications we are running, the nodes that are deploying, the application resources and a lot of another configurations. Kubernetes uses these entities to represent the state of your cluster. In the **spec** section we can describe the ***desired state*** of the object and Kubernetes manages the **status** section for objects, where the **current state** of the object is. Then, the Control Plane continually tries to match the desired status (`spec`) to current state (`status`). For example, a Deployment was configured to execute three replicas (desired state -- `spec`), but in a moment one replica falls down, the current state (`status`) is different from the desired state and the control plane tries to fix it. The next is an example of an Deployment object's configuration manifest: ```yml apiVersion: apps/v1 kind: Deployment metadata: name: nginx-deployment labels: app: nginx spec: replicas: 3 selector: matchLabels: app: nginx template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.15.11 ports: - containerPort: 80 ``` - `apiVersion`: the first required field and specifies which API endpoint in the API Server we want to connect to. - `kind`: the second required field and specifies the object type. - `metadata`: the third required field, metadata holds the object's basic information, such as name, namespaces, labels, etc. - `spec`: the fourth required field describes the desired object state. All pods from this object model manifest are created using the Pod Template defined in **spec.template**. When a Pod inherits from this object model manifest, the Pod retains its **metadata** and **spec**, but the **apiVersion** and **kind** are replaced by **template**. - `spec.template.spec`: this field defines the desired state **of the Pod**. The previous manifest doesn't have any **state** field because this field is created by the Kubernetes system. ### Pod A [Pod](https://kubernetes.io/docs/concepts/workloads/pods/) is the smallest, simplest and the widely known Kubernetes object. It represents an instance of the application **when it is deployed**, so, a Deploy object can create a Pod. A Pod contains one or more containers, which ones share the network namespaces, the IP address, that is, all the containers inside a Pod share the same IP address, and all the containers have access to mount the same external storage. Usually, a Pod contains only a single container, which one is the application.![pods-containers](https://courses.edx.org/assets/courseware/v1/ccc5ba54a8a06ac2a87fe447bb53dcf1/asset-v1:LinuxFoundationX+LFS158x+3T2020+type@asset+block/pods-1-2-3-4.svg) Pods are extremely ephemeral, that is, they may have short life-cycle and they may be easily created, deleted and recreated, but they do not have the capability to self-heal themselves. This is the reason they are always related with a controller, such as a Deployments, ReplicaSets, etc, and these controller handle Pod's replication, fault tolerance, self-healing, etc. The Pod's metadata is inherited from the controller that creates the Pod, using the Pod Template in `spec.template`. The code below is an example of a Pod's manifest: ```yaml apiVersion: v1 kind: Pod metadata: name: nginx-pod labels: app: nginx spec: containers: - name: nginx image: nginx:1.15.11 ports: - containerPort: 80 ``` **Important:** Pods should never be created directly using a manifest file of kind Pod. Pods are not self-healing and, hence, a Pod cannot recreate an instance of itself it there may be an error. The reliable way to create Pods is using a Deployment which configures a [ReplicaSet](https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/) controller to manage the [Pod's lifecycle](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/). ### Labels [Labels](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/) are simply a **key-value pairs** attached to Kubernetes object to create a concise management. They are just used as a easily way to organize and select objects. Controllers use Labels to logically group together decoupled objects, rather than using object's name or ID. <img src="https://courses.edx.org/assets/courseware/v1/6669997d43534cbd2f251a57ebe0587c/asset-v1:LinuxFoundationX+LFS158x+3T2020+type@asset+block/Labels.png" alt="labels" style="zoom: 33%;" /> Labels do not provide uniqueness by Pods, but we can set a bunch with the same label, instead. Labels is the Kubernetes way to group Pods. We can insert one or several labels in the `spec.template.labels.[*]` and then, we can search Pods by those labels (#1). We can even set the same label on Pods in different namespaces, and get them with `--all-namespaces` option (#2): ```bash kubectl get pods -l env=qa #1 kubectl get pods --all-namespaces -l heritage=Helm #2 kubectl get pods --all-namespaces -l heritage!=Helm # get all that aren't Heml ``` However, we must pay attention that the **labels in `metadata.labels.[*]` will not be inherited by Pods**, just the ones in `spec.template.labels.[*]`. There is also the [Label Selectors](https://kubernetes.io/docs/concepts/overview/working-with-objects/labels/#label-selectors) way to select Pods based on their labels. It allows us to search in a great way than the early way. There is the **equality-based selectors**, that works as before using the operators **=**, **==**, and **!=**. There is also the **set-based selectors**, that provides a way to search using a bunch of tags using **in**, **notin**, **exist/does not exist** operators. ### ReplicationController Although no longer a recommended controller, a [ReplicationController](https://kubernetes.io/docs/concepts/workloads/controllers/replicationcontroller/) ensures a specified number of Pods running at same time. A ReplicationController constantly verifies the desired state of managed application and ensures the current state will match. If the number of desired Pods is smaller than the actual number, the ReplicationController instances new Pods; If greater, the ReplicationController terminates them. The default way to manage Pods is using a [Deployment](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/), which configures a [ReplicaSet](https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/) controller to manage [Pod's lifecycle](https://kubernetes.io/docs/concepts/workloads/pods/pod-lifecycle/). ### ReplicaSets A [ReplicaSet](https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/) is the next-generation of the legacy ReplicationController as well there are some advantages in the ReplicaSet use against the ReplicationController such as the ReplicaSet supports both equality/set-based selectors whereas ReplicationController supports only equality-based selectors. A ReplicaSet aims to keep a set of replica Pods running in a given time as the desired state. For a specific number of replicas described in the `spec.replicas`, the ReplicaSet creates as much replicas as specified. Both Pods are identically and they run the same container image once they are cloned from the Pod template -- `spec.template`. The information about the ReplicaSet that created a Pod is in `metadata.ownerReferences`. <img src="https://courses.edx.org/assets/courseware/v1/bdb9c27c39d027fc22133456a2882fa6/asset-v1:LinuxFoundationX+LFS158x+3T2020+type@asset+block/Replica_Set1.png" alt="replica-set-working" style="zoom:33%;" /> There is a very interesting thing about the ReplicaSet and labels. ```yaml apiVersion: v1 kind: Pod metadata: name: to-fill-unique-pod namespace: default labels: delete: once app: to-fill env: production # arch: x86 # with label commented, ReplicaSet will not match this pod spec: containers: - name: to-fill-unique-pod image: danielventurini/to-fill:1.0 ports: - containerPort: 8080 --- apiVersion: apps/v1 kind: ReplicaSet metadata: name: to-fill-metadata namespace: default labels: delete: once app: to-fill spec: replicas: 2 selector: matchLabels: delete: once app: to-fill env: production arch: x86 template: metadata: labels: delete: once app: to-fill env: production arch: x86 spec: containers: - name: to-fill-unique-pod image: danielventurini/to-fill:1.0 ports: - containerPort: 8080 ``` In the first part of the manifest above, we create a Pod. This Pod has specific labels in `metadata` field. Then, in the second part of the manifest above, we create a ReplicaSet that instances two Pod's replicas. All the Pods that this ReplicaSet manages is labeled as `spec.selector.matchLabels[*]`. The Pod in the first part of the manifest has three of four labels managed by the ReplicaSet. When we apply this file, Kubernetes creates a Pod and a ReplicaSet with two Pod's instance, hence, we have three Pods. If we add the label `arch: x86` to the Pod in the first part of the manifest, the ReplicaSet would acquire this Pod and manage it. So, ReplicaSet would notice that there are three Pod's instance in the current state whereas the desire state (`spec.replicas`) specifies only two instances. Finally, the ReplicaSet would delete the first Pod and keep only two replicas as well. It happens because the Pod's template in ReplicaSet (`spec.template`) will be the same as `metadata` in Pod, so, both Pods are the same Kubernetes object. We can also delete a ReplicaSet and leave all of the Pods unchanged, that is, orphan. The Deployment is the high-level concept that manages a ReplicaSet. A Deployment provides a set of complementary features to orchestrate Pods. When a Deployment creates Pods, it also creates a ReplicaSet to manage these Pods. **It is not recommended to create and manage a ReplicaSet or a Pod directly**, unless there may be some custom orchestration resources/updates or do not require updates at all. ### Deployments A [Deployment](https://kubernetes.io/docs/concepts/workloads/controllers/deployment/) is a Kubernetes object that aims to create and manage Pods and ReplicaSets. The DeploymentController is part of the master's node controller managers and it ensures the current state matches the desired state. A Deployment allows for seamless applications **updates and rollbacks** through **rollouts** and **rollbacks**. In the following image, a Deployment creates three ReplicaSets, which ones create two Pods. Each ReplicaSet reads the Deployment's template in field `spec.template` and they manage the Pods according the template. <img src="https://courses.edx.org/assets/courseware/v1/5b2c8cbd6bed63c68f6a7d2566615d7f/asset-v1:LinuxFoundationX+LFS158x+3T2020+type@asset+block/Deployment_Updated.png" style="zoom: 25%;" /> The Deployment allows the application to easily receive push updates. When a update is pushed to container, the Deployment **triggers a new ReplicaSet** for the new container and it creates a new **Revision**, as in the following image, and this transition from the previous ReplicaSet to the new ReplicaSet is a Deployment **rolling update**. The new ReplicaSet is scaled to the required number of Pods wheres the previous ReplicaSet is scaled down to 0 Pods and **this ReplicaSet is "stored" for further rollbacks**. All updates in specifics properties of the Pod's template in Deployment metadata triggers a rolling update and, hence, a new revision. <img src="https://courses.edx.org/assets/courseware/v1/979a990d505485a3ad502836ca5f1078/asset-v1:LinuxFoundationX+LFS158x+3T2020+type@asset+block/ReplikaSet_B.png" alt="deployment-rolling-update" style="zoom:25%;" /> In the above image, the previous state used the container image **nginx:1.7.9**, but when there was an update in the Pod's template in Deployment metadata to image **nginx:1.9.1**, the Deployment saved the **Revision 1** and created the **Revision 2**. If there is something wrong with the update, the Deployment can be safety rolled back to Revision 1. In this case, the Revision 1 becomes the Revision 3, and there is no more Revision available, just Revision 2 and 3. Kubernetes stores up to 10 Revision set. When there is a deploy, a new ReplicaSet is scaled up and the previous ReplicaSet is scaled down. This previous ReplicaSet's Pod Template is saved with the desired state as 0 replicas. Then, it creates a new Revision, that we can see using through the `rollout` command. Also, the previous ReplicaSet's Pod Templates can be seen yet (#1,#2). We then can see the amount of Revisions that can be rolled back (#3). We also can see detailed the ReplicaSet's Pod Template for a specific revision number (#4). Finally, we can restore a previous ReplicaSet's Pod Template (#5), then, **the Revision 3 become the latest Revision**. ```bash kubectl -n mynamespace get replicasets # 1 kubectl -n mynamespace describe replicasets replset-name # 2 kubectl -n mynamespace rollout history deployment deplname # 3 kubectl -n mynamespace rollout history deployment deplname --revision=3 # 4 kubectl -n mynamespace rollout undo deployment deplname --to-revision=3 # 5 ``` Revisions are not a Deployment exclusive, but we can rollback DaemonSets and StatefulSets. ### Namespaces A [Namespace](https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/) is a logical cluster separator that allow multiple users and teams to work on the same Kubernetes cluster. The names of the resources/objects created in a Namespace **is unique in that Namespace**, but across the Namespace in the cluster. There are some pre-built namespaces, such as `kube-system`, `kube-public` and the basic one, the `default` namespace. The namespace `kube-public` is really public, it means this namespace provides insecurity access and anyone can read it. Other important namespace is the `kube-node-lease`, which holds **node lease objects** used for node heartbeat data. --- You should now be able to: - Describe the Kubernetes object model. - Discuss Kubernetes building blocks, e.g. Pods, ReplicaSets, Deployments, Namespaces. - Discuss Labels and Selectors.
PHP
UTF-8
1,678
2.546875
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Slider; use \Illuminate\Support\Facades\Storage; use Intervention\Image\Facades\Image; class SliderController extends Controller { public function index() { //Get all Sliders $sliders = Slider::all(); return view('admin.content.slider.index', compact('sliders')); } public function show(Slider $slider) { return view('admin.content.slider.show', compact('slider')); } public function update(Request $request, Slider $slider) { //Validating Inputs from Request $validated = $request->validate([ 'title' => 'required|', 'content' => 'required|', 'btntext' => 'required', 'btnlink' => 'required', 'image' => 'nullable|image' ]); //Checking if request has image to update if ($request->has('image')) { //Deleting Current Image from Storage $slider->deleteImg(); //Storing New Image $imagePath = $request->file('image')->store('slider'); //Resizing Image with Image Intervention $image = Image::make(public_path("storage/{$imagePath}"))->fit(1920, 999); $image->save(); //Updating the Image_Path $slider->update(['image_path' => $imagePath]); } //Update Slider's Credentials $slider->update([ 'title' => $request->input('title'), 'content' => $request->input('content'), 'btntext' => $request->input('btntext'), 'btnlink' => $request->input('btnlink'), ]); return redirect('/admin/homu/content/slider'); } }
Java
UTF-8
1,024
2.3125
2
[]
no_license
package gbq.com.myaccount.base; import android.support.v7.app.AppCompatActivity; import android.widget.Toast; import gbq.com.myaccount.base.util.CustomProgressDialog; /** * 基本的Activity,主要包含一些Activity的公共方法 * Created by gbq on 2016-11-15. */ public class BaseActivity extends AppCompatActivity implements IBaseCtrl{ private CustomProgressDialog progressDialog; @Override public void showAlert(String msg) { } @Override public void showProcess() { if (progressDialog == null){ progressDialog = CustomProgressDialog.createDialog(this); progressDialog.setMessage("玩命加载中..."); } progressDialog.show(); } @Override public void closeProcess() { if (progressDialog != null){ progressDialog.dismiss(); progressDialog = null; } } @Override public void showToast(String msg) { Toast.makeText(this, msg, Toast.LENGTH_SHORT).show(); } }
Java
UTF-8
1,005
2.796875
3
[]
no_license
package tracker; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.logging.Logger; import java.util.List; import tracker.TrackerThread; import common.Common; public class Tracker { private static HashMap<String, List<String>> swarmHashMap; static ServerSocket tracker = null; Socket client = null; TrackerThread tt; Thread t; Logger logger = Logger.getLogger(String.valueOf(this.getClass())); private Tracker() { try { tracker = new ServerSocket(Common.TrackerPort); swarmHashMap = new HashMap<String, List<String>>(); // key:InfoHash value:swram(peer list) while (true) { client = tracker.accept(); if (client != null) { tt = new TrackerThread(client, swarmHashMap); t = new Thread(tt); t.start(); } } } catch (Exception e) { logger.info(this.getClass().getName() + ".Tracker() =>" + "\n 발생원인 :" + e.getMessage()); } } public static void main(String[] args) { new Tracker(); } }
Markdown
UTF-8
1,444
2.59375
3
[]
no_license
# NucleusApi.DocumentSentimentModel ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **dataset** | **String** | Dataset name | **doc_title** | **String** | The title of the document to be analyzed. | [optional] **query** | **String** | Dataset-language-specific fulltext query, using SQL MATCH boolean query format. Example: \&quot;(word1 OR word2) AND (word3 OR word4)\&quot; | [optional] **num_topics** | **Number** | Number of topics to be extracted from the document to estimate the document&#39; sentiment. | [optional] **num_keywords** | **Number** | Number of keywords per topic that is extracted from the document. | [optional] **custom_stop_words** | **[String]** | List of dataset-language-specific stopwords that should be excluded from the analysis. Example: [\&quot;word1\&quot;, \&quot;word2\&quot;, ..., \&quot;wordN\&quot;] | [optional] **custom_dict_file** | **Object** | JSON with custom sentiment dictionary: {\&quot;word1\&quot;: value1, \&quot;word2\&quot;: value2, ..., \&quot;wordN\&quot;: valueN} | [optional] **cache_sentiment** | **Boolean** | If true, computes the sentiment for all docs in the dataset and saves it in a new \&quot;sentiment_category\&quot; metadata column. | [optional] [default to false] **overwrite** | **Boolean** | If true, overwrites cached sentiment values for all documents in the dataset | [optional] [default to false]
PHP
UTF-8
9,489
2.515625
3
[]
no_license
<?php class Cliente extends Application { private $Permissao; public function __construct() { parent::__construct(); } public function init() { $usuario = Session::read('LOGIN'); $mppUser = new MapperUsuarios(); $cnpj = $mppUser->getCNPJ('junior'); $this->Permissao = $mppUser->permissao($usuario, $cnpj); if(!$this->ChecarPermisao($usuario, "G") && !$this->ChecarPermisao($usuario, "S")) { Session::delete("LOGIN"); header( "Location: " . HTML_HOST ); die(); } if(!$this->CheckLogado()) header( "Location: " . HTML_HOST ); $this->smarty->assign('userHeader', $mppUser->getDados()); $this->smarty->assign('Permissao', $this->Permissao); } public function ativarUsuario() { $usuario = Session::read('LOGIN'); $mppUser = new MapperUsuarios(); $cnpj = $mppUser->getCNPJ($usuario); if($mppUser->atvUsuario($_GET['usuario'], $cnpj, 0)) { Message::display('Usuário ativado.', '?controller=cliente&action=atualizar-dados'); Log::write("Ativar-usuario.log", "Cliente", "Usuario ativou o usuário: {$_GET['usuario']}"); } } public function desativarUsuario() { $usuario = Session::read('LOGIN'); $mppUser = new MapperUsuarios(); $cnpj = $mppUser->getCNPJ($usuario); $Check = $mppUser->select($_GET['usuario'], $cnpj); if($Check->tipo == "G" or $Check->tipo == "A") Message::display('Você não pode desativar gestores ou administradores do sistema.', '?controller=cliente&action=atualizar-dados'); else if($usuario == $_GET['usuario']) Message::display('Você não pode desativar sua propria conta.', '?controller=cliente&action=atualizar-dados'); else if($mppUser->atvUsuario($_GET['usuario'], $cnpj, 1)) { Message::display('Usuário desativado.', '?controller=cliente&action=atualizar-dados'); Log::write("Desativar-usuario.log", "Cliente", "Usuario desativou o usuário: {$_GET['usuario']}"); } } public function index() { $this->smarty->display( "cliente/index.tpl" ); } public function verConsultas() { $mppFaturas = new MapperFaturas(); $id = (int)$_GET['id']; $this->smarty->assign( "Consultas", $mppFaturas->fetchConsultas($id)); $this->smarty->display( "cliente/ver-consultas.tpl" ); } public function editarUsuario() { $mppUsuarios = new MapperUsuarios(); $usuario = Session::read('LOGIN'); $cnpj = $mppUsuarios->getCNPJ($usuario); if($_POST && isset($_POST)) { $usuario = $_POST['usuario']; $nome = $_POST['nome']; $email = $_POST['email']; $limite = $_POST['limite']; $error = NULL; $sucesso = NULL; if($this->Permissao != "G") $error .= "Sem permissão de edição<br>"; if( empty($usuario) ) $error .= "Usuário em branco <br>"; if( empty($nome) ) $error .= "Nome em branco <br>"; if(!empty($_POST['senha']) && !empty($_POST['resenha'])) { $senha = $_POST['senha']; $resenha = $_POST['resenha']; if($senha == $resenha) { if($mppUsuarios->alterarSenha($senha, $usuario, $cnpj)) $sucesso = "Senha alterada com sucesso!<br>"; Log::write("Editar-usuario.log", "Cliente", "Usuario alterou a senha da conta: {$usuario}"); } else $error .= "Senhas não conferem."; } if($error == NULL) { $Usuarios = new Usuarios; $Usuarios->nome = $nome; $Usuarios->email = $email; $Usuarios->usuario = $usuario; $Usuarios->limite = $limite; if( $mppUsuarios->update(0, $Usuarios, $cnpj) ) { $this->smarty->assign( "Cadastrado", $sucesso."Usuário editado com sucesso"); Log::write("Editar-usuario.log", "Cliente", "Usuario editou a conta: {$usuario}"); } } $this->smarty->assign( "Error", $error); } $this->smarty->assign( "Usuario", $mppUsuarios->select($_GET['usuario'], $cnpj)); $this->smarty->display( "cliente/editar-usuario.tpl" ); } public function atualizarDados() { $mppEmpresas = new MapperEmpresas(); $mppUsuarios = new MapperUsuarios(); $usuario = Session::read('LOGIN'); if($_POST && isset($_POST["prosseguir"])) { $usuarios = $_POST['iptUsuarios']; $acao = $_POST['acao'] == 0 ? 0 : 1; $logado = Session::read('LOGIN'); $mppUser = new MapperUsuarios(); $cnpj = $mppUser->getCNPJ($logado); if(count($usuarios) > 0) { foreach($usuarios as $usuario) { $Check = $mppUser->select($usuario, $cnpj); if($Check->tipo == "G" or $Check->tipo == "A") { Message::display("Usuário: $usuario é gestor ou administrador do sistema.", '?controller=cliente&action=atualizar-dados'); break; } else if($usuario == $logado) { Message::display('Você não pode desativar sua propria conta.', '?controller=cliente&action=atualizar-dados'); break; } $mppUser->atvUsuario($usuario, $cnpj, $acao); } } Message::display('Operação realizada com sucesso!', '?controller=cliente&action=atualizar-dados'); Log::write("Desativar-usuario.log", "Cliente", "Usuario desativou usuários em massa."); } if($_POST && isset($_POST["Atualizar"])) { $razao = $_POST['razao']; $cnpj = Util::unmask($_POST['cnpj']); $endereco = $_POST['endereco']; $complemento = $_POST['complemento']; $numero = $_POST['numero']; $bairro = $_POST['bairro']; $cidade = $_POST['cidade']; $estado = $_POST['estado']; $cep = Util::unmask($_POST['cep']); $telefone = Util::unmask($_POST['telefone']); $email = $_POST['email']; $responsavel = $_POST['responsavel']; $error = NULL; if($this->Permissao != "G") $error .= "Sem permissão de edição<br>"; if( empty($endereco) ) $error .= "Endereco em branco <br>"; if( empty($numero) ) $error .= "Numero em branco <br>"; if( empty($bairro) ) $error .= "Bairro em branco <br>"; if( empty($cidade) ) $error .= "Cidade em branco <br>"; if( empty($estado) ) $error .= "Estado em branco <br>"; if( empty($cep) ) $error .= "CEP em branco <br>"; if( empty($razao) ) $error .= "Razão em branco <br>"; if( empty($telefone) ) $error .= "Telefone em branco <br>"; if( empty($email) ) $error .= "Email em branco <br>"; if( empty($responsavel) ) $error .= "Responsável em branco <br>"; if( strlen($telefone) < 10 ) $error .= "Telefone inválido <br>"; if( strlen($cep) < 8 ) $error .= "CEP inválido <br>"; if($error == NULL) { $Empresas = new Empresas; $Empresas->endereco = $endereco; $Empresas->numero = $numero; $Empresas->bairro = $bairro; $Empresas->cidade = $cidade; $Empresas->estado = $estado; $Empresas->cep = $cep; $Empresas->razao = $razao; $Empresas->telefone = $telefone; $Empresas->email = $email; $Empresas->responsavel = $responsavel; $Empresas->complemento = $complemento; $MapperEmpresas = new MapperEmpresas(); if( $MapperEmpresas->update($Empresas, $cnpj, $usuario) ) { $this->smarty->assign( "Cadastrado", "Empresa editada com sucesso!"); Log::write("Editar-empresa.log", "Cliente", "Usuario editou a empresa: {$razao} / {$cnpj}"); } } $this->smarty->assign( "Error", $error); } $Empresa = $mppEmpresas->select( $usuario ); $cnpj = $mppUsuarios->getCNPJ($usuario); $usuariosAtivos = $mppUsuarios->find('where empresa = ? AND ativo=0', $cnpj); $usuariosInativos = $mppUsuarios->find('where empresa = ? AND ativo=1', $cnpj); $this->smarty->assign( "Empresa", $Empresa); $this->smarty->assign( "usuariosAtivos", $usuariosAtivos); $this->smarty->assign( "usuariosInativos", $usuariosInativos); $this->smarty->display( "cliente/atualizar-dados.tpl" ); } public function relatorios() { $mppFaturas = new MapperFaturas(); $mppUsuarios = new MapperUsuarios(); $usuario = Session::read('LOGIN'); $cnpj = $mppUsuarios->getCNPJ($usuario); $Relatorios = $mppFaturas->ultimasConsultas($cnpj); $h2_title = "Últimas consultas"; if($_POST && isset($_POST)) { $Where = array(); $inicio = date('Y-m-d', strtotime(str_replace("/", "-", $_POST['inicio']))); $final = date('Y-m-d 23:59', strtotime(str_replace("/", "-", $_POST['final']))); $Where = array($inicio, $final); $Relatorios = $mppFaturas->ultimasConsultas($cnpj, $Where); } $this->smarty->assign( "Relatorios", $Relatorios); $this->smarty->assign( "h2_title", $h2_title); $this->smarty->display( "cliente/relatorios.tpl" ); } public function faturas() { $mppFaturas = new MapperFaturas(); $mppUsuarios = new MapperUsuarios(); $usuario = Session::read('LOGIN'); $cnpj = $mppUsuarios->getCNPJ($usuario); $Faturas = $mppFaturas->fetchAll('A', $cnpj); $FaturasF = $mppFaturas->fetchAll('F', $cnpj); $this->checkPermissao(); if(isset($_POST) && $_POST) { $inicio = $_POST['inicio']; $final = $_POST['final']; $order = isset($_POST['order']) ? $_POST['order'] : 2; $Faturas = $mppFaturas->find($inicio, $final, "", $order, 'A', $cnpj); $FaturasF = $mppFaturas->find($inicio, $final, "", $order, 'F', $cnpj); } $this->smarty->assign( "Faturas", $Faturas); $this->smarty->assign( "FaturasF", $FaturasF); $this->smarty->display( "cliente/faturas.tpl" ); } public function checkPermissao() { if($this->Permissao != "G") { header("Location: ?controller=cliente"); die(); } } } ?>
C++
UTF-8
1,527
3.4375
3
[]
no_license
#include <iostream> #include <map> #include <set> #include <string> using namespace std; struct str_compare { bool operator() (const string& lhs, const string& rhs) { if( (lhs.length() < rhs.length()) || (lhs.length()==rhs.length() && lhs < rhs) ) return true; return false; } }; void words_generator(set<string, str_compare>& words, int cur_letter, string& cur_word) { if(cur_word.length() == 5 || cur_letter > 122) { if(cur_word == "") return; bool valid = true; for(int i = 1; i < cur_word.length() && valid; i++) { if(cur_word[i] <= cur_word[i-1]) valid = false; } if(valid) { words.insert(cur_word); } return; } words_generator(words, cur_letter+1, cur_word); cur_word += cur_letter; words_generator(words, cur_letter+1, cur_word); cur_word.erase(cur_word.length()-1, 1); } int main() { set<string, str_compare> words; map<string, int> indexed_words; string cur = ""; words_generator(words, 'a', cur); int cur_index = 1; for(auto w: words) { indexed_words[w] = cur_index; cur_index++; } while(cin >> cur) { auto p = indexed_words.find(cur); if(p == indexed_words.end()) cout << 0 << endl; else cout << p->second << endl; } return 0; }
C#
UTF-8
1,427
2.859375
3
[]
no_license
using System; using System.IO; using System.Diagnostics; namespace TrabajosExpres.PresentationLogicLayer.Utils { class LogException { /// <summary> /// Method that receives the player's email /// </summary> /// <param name="obj">The telegram data</param> /// <param name="exception">The exception to log</param> public static void Log(object obj, Exception exception) { string date = DateTime.Now.ToString("yyyy-MM-dd"); string time = DateTime.Now.ToString("HH:mm:ss"); string path = "Log/log-" + date + ".txt"; string pathDirectory = "Log"; try { if (!Directory.Exists(pathDirectory)) { Directory.CreateDirectory(pathDirectory); } StreamWriter streamWriter = new StreamWriter(path, true); StackTrace stacktrace = new StackTrace(); streamWriter.WriteLine(obj.GetType().FullName + " " + time); streamWriter.WriteLine(stacktrace.GetFrame(1).GetMethod().Name + " - " + exception.ToString()); streamWriter.WriteLine(""); streamWriter.Flush(); streamWriter.Close(); } catch (IOException exceptionLog) { TelegramBot.SendToTelegram(exceptionLog); } } } }
Markdown
UTF-8
13,604
2.75
3
[]
no_license
--- title: Elevación de los privilegios de acceso de un administrador global en Azure Active Directory | Microsoft Docs description: Describe cómo elevar los privilegios de acceso de un administrador global en Azure Active Directory mediante Azure Portal o la API de REST. services: active-directory documentationcenter: '' author: rolyon manager: mtillman editor: bagovind ms.assetid: b547c5a5-2da2-4372-9938-481cb962d2d6 ms.service: role-based-access-control ms.devlang: na ms.topic: conceptual ms.tgt_pltfrm: na ms.workload: identity ms.date: 10/15/2018 ms.author: rolyon ms.reviewer: bagovind ms.openlocfilehash: a2f66078a817f5e6ad7296df11634a1a6130a055 ms.sourcegitcommit: 74941e0d60dbfd5ab44395e1867b2171c4944dbe ms.translationtype: HT ms.contentlocale: es-ES ms.lasthandoff: 10/15/2018 ms.locfileid: "49321672" --- # <a name="elevate-access-for-a-global-administrator-in-azure-active-directory"></a>Elevación de los privilegios de acceso de un administrador global en Azure Active Directory Si es un [administrador global](../active-directory/users-groups-roles/directory-assign-admin-roles.md#company-administrator) en Azure Active Directory (Azure AD), es posible que haya momentos en los que quiera hacer lo siguiente: - Recuperar el acceso a una suscripción de Azure cuando un usuario ha perdido el acceso - Conceder acceso a otro usuario o usted mismo a una suscripción a Azure - Ver todas las suscripciones a Azure de una organización - Permitir que una aplicación de automatización (por ejemplo, una aplicación de facturación o auditoría) tenga acceso a todas las suscripciones de Azure En este artículo se describen las distintas maneras en que puede elevar los derechos de acceso en Azure AD. [!INCLUDE [gdpr-dsr-and-stp-note](../../includes/gdpr-dsr-and-stp-note.md)] ## <a name="overview"></a>Información general Azure AD y los recursos de Azure están protegidos de forma independiente entre sí. Es decir, las asignaciones de roles de Azure AD no otorgan acceso a recursos de Azure, y las asignaciones de roles de Azure no conceden acceso a Azure AD. Sin embargo, si es administrador global de Azure AD, puede asignarse a sí mismo los privilegios de acceso para todas las suscripciones a Azure y los grupos de administración de su directorio. Use esta funcionalidad si no tiene acceso a recursos de suscripción a Azure, como máquinas virtuales o cuentas de almacenamiento, y quiere usar su privilegio de administrador global para obtener acceso a esos recursos. Al elevar los privilegios de acceso, se le asignará el rol [Administrador de acceso de usuario](built-in-roles.md#user-access-administrator) en Azure en el ámbito raíz (`/`). Esto le permite ver todos los recursos y asignar acceso en cualquier suscripción o grupo de administración en el directorio. Se pueden quitar las asignaciones de roles de administrador de acceso de usuario mediante PowerShell. Debe quitar este acceso con privilegios elevados una vez que haya hecho los cambios necesarios en el ámbito raíz. ![Elevación de los privilegios de acceso](./media/elevate-access-global-admin/elevate-access.png) ## <a name="azure-portal"></a>Azure Portal Siga estos pasos para elevar los privilegios de acceso de un administrador global mediante Azure Portal. 1. Inicie sesión en el [Azure Portal](https://portal.azure.com) o en el [Centro de administración de Azure Active Directory](https://aad.portal.azure.com) como administrador global. 1. En la lista de navegación, haga clic en **Azure Active Directory** y, luego, haga clic en **Propiedades**. ![Propiedades de Azure AD, captura de pantalla](./media/elevate-access-global-admin/aad-properties.png) 1. En **Access management for Azure resources** (Administración de acceso a recursos de Azure), establezca el modificador en **Sí**. ![Captura de pantalla de administración de acceso a recursos de Azure](./media/elevate-access-global-admin/aad-properties-global-admin-setting.png) Al establecer el modificador en **Sí**, se le asigna el rol de administrador de acceso de usuario en Azure RBAC en el ámbito raíz (/). Esto le concede permiso para asignar roles en todas las suscripciones de Azure y los grupos de administración asociados a este directorio de Azure AD. Este modificador solo está disponible para los usuarios que tienen asignado el rol de administrador global de Azure AD. Al establecer el modificador en **No**, se quita el rol de administrador de acceso de usuario en Azure RBAC de su cuenta de usuario. Ya no puede asignar roles en todas las suscripciones de Azure y los grupos de administración asociados a este directorio de Azure AD. Puede ver y administrar solo las suscripciones de Azure y los grupos de administración a los que se le ha concedido acceso. 1. Haga clic en **Guardar** para guardar la configuración. Esta configuración no es una propiedad global y se aplica solo al usuario que tiene la sesión iniciada. 1. Realice las tareas que debe realizar al tener privilegios elevados de acceso. Cuando haya terminado, seleccione **No**. ## <a name="azure-powershell"></a>Azure PowerShell ### <a name="list-role-assignment-at-the-root-scope-"></a>Mostrar la asignación de roles en el ámbito raíz (/) Para mostrar la asignación de roles de administrador de accesos de usuario de un usuario en el ámbito raíz (`/`), use el comando [Get-AzureRmRoleAssignment](/powershell/module/azurerm.resources/get-azurermroleassignment). ```azurepowershell Get-AzureRmRoleAssignment | where {$_.RoleDefinitionName -eq "User Access Administrator" ` -and $_.SignInName -eq "<username@example.com>" -and $_.Scope -eq "/"} ``` ```Example RoleAssignmentId : /providers/Microsoft.Authorization/roleAssignments/098d572e-c1e5-43ee-84ce-8dc459c7e1f0 Scope : / DisplayName : username SignInName : username@example.com RoleDefinitionName : User Access Administrator RoleDefinitionId : 18d7d88d-d35e-4fb5-a5c3-7773c20a72d9 ObjectId : d65fd0e9-c185-472c-8f26-1dafa01f72cc ObjectType : User ``` ### <a name="remove-a-role-assignment-at-the-root-scope-"></a>Eliminación de la asignación de roles en el ámbito raíz (/) Para quitar la asignación de roles de administrador de acceso de usuario de un usuario en el ámbito raíz (`/`), use el comando [Remove-AzureRmRoleAssignment](/powershell/module/azurerm.resources/remove-azurermroleassignment). ```azurepowershell Remove-AzureRmRoleAssignment -SignInName <username@example.com> ` -RoleDefinitionName "User Access Administrator" -Scope "/" ``` ## <a name="rest-api"></a>API DE REST ### <a name="elevate-access-for-a-global-administrator"></a>Elevación de los privilegios de acceso de un administrador global Utilice los siguientes pasos básicos para elevar los privilegios de acceso de un administrador global mediante la API de REST. 1. Mediante REST, llame a `elevateAccess`. Entonces, se le concede el rol de administrador de accesos de usuario en el ámbito raíz (`/`). ```http POST https://management.azure.com/providers/Microsoft.Authorization/elevateAccess?api-version=2016-07-01 ``` 1. Cree una [asignación de roles](/rest/api/authorization/roleassignments) para asignar cualquier rol en cualquier ámbito. En el ejemplo siguiente, se muestran las propiedades para asignar el rol {roleDefinitionID} en el ámbito (`/`): ```json { "properties": { "roleDefinitionId": "providers/Microsoft.Authorization/roleDefinitions/{roleDefinitionID}", "principalId": "{objectID}", "scope": "/" }, "id": "providers/Microsoft.Authorization/roleAssignments/64736CA0-56D7-4A94-A551-973C2FE7888B", "type": "Microsoft.Authorization/roleAssignments", "name": "64736CA0-56D7-4A94-A551-973C2FE7888B" } ``` 1. Mientras sea administrador de acceso de usuario, también podrá quitar asignaciones de roles en el ámbito raíz (`/`). 1. Quite los privilegios de administrador de acceso de usuario hasta que los vuelva a necesitar. ### <a name="list-role-assignments-at-the-root-scope-"></a>Enumeración de las asignaciones de roles en el ámbito raíz (/) Puede enumerar todas las asignaciones de roles para un usuario en el ámbito raíz (`/`). - Llamar a [GET roleAssignments](/rest/api/authorization/roleassignments/listforscope) donde `{objectIdOfUser}` es el id. de objeto del usuario cuyas asignaciones de roles quiere recuperar. ```http GET https://management.azure.com/providers/Microsoft.Authorization/roleAssignments?api-version=2015-07-01&$filter=principalId+eq+'{objectIdOfUser}' ``` ### <a name="list-deny-assignments-at-the-root-scope-"></a>Enumeración de las asignaciones de denegación en el ámbito raíz (/) Puede enumerar todas las asignaciones de denegación de un usuario en el ámbito raíz (`/`). - Llame a GET denyAssignments, donde `{objectIdOfUser}` es el id. de objeto del usuario cuyas asignaciones de denegación desea recuperar. ```http GET https://management.azure.com/providers/Microsoft.Authorization/denyAssignments?api-version=2018-07-01-preview&$filter=gdprExportPrincipalId+eq+'{objectIdOfUser}' ``` ### <a name="remove-elevated-access"></a>Eliminación de privilegios de acceso elevados Cuando llama a `elevateAccess`, crea una asignación de roles para sí mismo, por lo que, para revocar esos privilegios, debe quitar la asignación. 1. Llame al comando [GET-roleDefinitions](/rest/api/authorization/roledefinitions/get), donde `roleName` es el administrador de accesos de usuario, para determinar el id. del nombre del rol de administrador de accesos de usuario. ```http GET https://management.azure.com/providers/Microsoft.Authorization/roleDefinitions?api-version=2015-07-01&$filter=roleName+eq+'User Access Administrator' ``` ```json { "value": [ { "properties": { "roleName": "User Access Administrator", "type": "BuiltInRole", "description": "Lets you manage user access to Azure resources.", "assignableScopes": [ "/" ], "permissions": [ { "actions": [ "*/read", "Microsoft.Authorization/*", "Microsoft.Support/*" ], "notActions": [] } ], "createdOn": "0001-01-01T08:00:00.0000000Z", "updatedOn": "2016-05-31T23:14:04.6964687Z", "createdBy": null, "updatedBy": null }, "id": "/providers/Microsoft.Authorization/roleDefinitions/18d7d88d-d35e-4fb5-a5c3-7773c20a72d9", "type": "Microsoft.Authorization/roleDefinitions", "name": "18d7d88d-d35e-4fb5-a5c3-7773c20a72d9" } ], "nextLink": null } ``` Guarde el id. del parámetro `name`; en este caso: `18d7d88d-d35e-4fb5-a5c3-7773c20a72d9`. 2. También tiene que mostrar la asignación de roles del administrador de directorios en el ámbito del directorio. Muestre todas las asignaciones en el ámbito del directorio para `principalId` del administrador de directorios que hizo la llamada de elevación de privilegios de acceso. Esto mostrará todas las asignaciones en el directorio para objectid. ```http GET https://management.azure.com/providers/Microsoft.Authorization/roleAssignments?api-version=2015-07-01&$filter=principalId+eq+'{objectid}' ``` >[!NOTE] >Un administrador de directorios no debe tener muchas asignaciones; si la consulta anterior devuelve demasiadas asignaciones, puede consultar también todas las asignaciones en el nivel de ámbito de directorio y, después, filtrar los resultados: `GET https://management.azure.com/providers/Microsoft.Authorization/roleAssignments?api-version=2015-07-01&$filter=atScope()` 2. Las llamadas anteriores devuelven una lista de asignaciones de roles. Busque la asignación de roles en la que el ámbito sea `"/"`, `roleDefinitionId` termine con el id. del nombre de rol que se encuentra en el paso 1, y `principalId` coincida con el valor de ObjectId del administrador de directorios. Ejemplo de asignación de rol: ```json { "value": [ { "properties": { "roleDefinitionId": "/providers/Microsoft.Authorization/roleDefinitions/18d7d88d-d35e-4fb5-a5c3-7773c20a72d9", "principalId": "{objectID}", "scope": "/", "createdOn": "2016-08-17T19:21:16.3422480Z", "updatedOn": "2016-08-17T19:21:16.3422480Z", "createdBy": "93ce6722-3638-4222-b582-78b75c5c6d65", "updatedBy": "93ce6722-3638-4222-b582-78b75c5c6d65" }, "id": "/providers/Microsoft.Authorization/roleAssignments/e7dd75bc-06f6-4e71-9014-ee96a929d099", "type": "Microsoft.Authorization/roleAssignments", "name": "e7dd75bc-06f6-4e71-9014-ee96a929d099" } ], "nextLink": null } ``` Una vez más, guarde el id. del parámetro `name`; en este caso: e7dd75bc-06f6-4e71-9014-ee96a929d099. 3. Por último, utilice el id. de asignación de roles para quitar la asignación agregada por `elevateAccess`: ```http DELETE https://management.azure.com/providers/Microsoft.Authorization/roleAssignments/e7dd75bc-06f6-4e71-9014-ee96a929d099?api-version=2015-07-01 ``` ## <a name="next-steps"></a>Pasos siguientes - [Descripción de los distintos roles](rbac-and-directory-admin-roles.md) - [Control de acceso basado en roles con REST](role-assignments-rest.md)
C++
UTF-8
462
2.84375
3
[]
no_license
/** *@file barreronde.h *@brief Définition de la classe BarreRonde *@version 1.1 * @author Antoine CHEVREL * @date 20 septembre 2019 */ #ifndef BARRERONDE_H #define BARRERONDE_H #include "barre.h" class BarreRonde: public Barre { public: BarreRonde(string _ref, int _longueur,int _diametre, float _densite, string _nom); double CalculerSection(); float CalculerMasse(); ~BarreRonde(); private: int diametre; }; #endif // BARRERONDE_H
Java
UTF-8
4,562
2.359375
2
[]
no_license
package com.jiaying.mediatablet.net.utils; import com.jiaying.mediatablet.net.signal.RecSignal; import java.util.HashMap; /** * Created by hipil on 2016/4/3. */ public class FilterSignal { //true表示该状态信号可以被响应 //false表示该状态信号不可以被响应 private HashMap<String, Boolean> signalMap; public FilterSignal() { this.signalMap = new HashMap<String, Boolean>(); this.signalMap.put("CONFIRM", true); this.signalMap.put("COMPRESSION", false); this.signalMap.put("PUNCTURE", false); this.signalMap.put("STARTPUNTUREVIDEO", false); this.signalMap.put("START", false); this.signalMap.put("STARTCOLLECTIONVIDEO", false); this.signalMap.put("pipeLow", false); this.signalMap.put("pipeNormal", false); this.signalMap.put("PAUSED", false); this.signalMap.put("END", false); } public synchronized void recConfirm() { this.signalMap.put("CONFIRM", false); this.signalMap.put("COMPRESSION", true); this.signalMap.put("PUNCTURE", true); this.signalMap.put("STARTPUNTUREVIDEO", false); this.signalMap.put("START", true); this.signalMap.put("STARTCOLLECTIONVIDEO", false); this.signalMap.put("pipeLow", false); this.signalMap.put("pipeNormal", false); this.signalMap.put("PAUSED", false); this.signalMap.put("END", false); } public synchronized void recCompression() { this.signalMap.put("CONFIRM", false); this.signalMap.put("COMPRESSION", false); this.signalMap.put("PUNCTURE", true); this.signalMap.put("STARTPUNTUREVIDEO", false); this.signalMap.put("START", true); this.signalMap.put("STARTCOLLECTIONVIDEO", false); this.signalMap.put("pipeLow", false); this.signalMap.put("pipeNormal", false); this.signalMap.put("PAUSED", false); this.signalMap.put("END", false); } public synchronized void recPuncture() { this.signalMap.put("CONFIRM", false); this.signalMap.put("COMPRESSION", false); this.signalMap.put("PUNCTURE", false); this.signalMap.put("STARTPUNTUREVIDEO", true); this.signalMap.put("START", true); this.signalMap.put("STARTCOLLECTIONVIDEO", false); this.signalMap.put("pipeLow", false); this.signalMap.put("pipeNormal", false); this.signalMap.put("PAUSED", false); this.signalMap.put("END", false); } public synchronized void recStart() { this.signalMap.put("CONFIRM", false); this.signalMap.put("COMPRESSION", false); this.signalMap.put("PUNCTURE", false); this.signalMap.put("STARTPUNTUREVIDEO", false); this.signalMap.put("START", false); this.signalMap.put("STARTCOLLECTIONVIDEO", true); this.signalMap.put("pipeLow", true); this.signalMap.put("pipeNormal", true); this.signalMap.put("PAUSED", true); this.signalMap.put("END", true); } public synchronized void recEnd() { this.signalMap.put("CONFIRM", true); this.signalMap.put("COMPRESSION", false); this.signalMap.put("PUNCTURE", false); this.signalMap.put("STARTPUNTUREVIDEO", false); this.signalMap.put("START", false); this.signalMap.put("STARTCOLLECTIONVIDEO", false); this.signalMap.put("pipeLow", false); this.signalMap.put("pipeNormal", false); this.signalMap.put("PAUSED", false); this.signalMap.put("END", false); } public synchronized boolean checkSignal(RecSignal recSignal) { switch (recSignal) { case CONFIRM: return this.signalMap.get("CONFIRM"); case COMPRESSINON: return this.signalMap.get("COMPRESSION"); case PUNCTURE: return this.signalMap.get("PUNCTURE"); case STARTPUNTUREVIDEO: return this.signalMap.get("STARTPUNTUREVIDEO"); case START: return this.signalMap.get("START"); case STARTCOLLECTIONVIDEO: return this.signalMap.get("STARTCOLLECTIONVIDEO"); case pipeLow: return this.signalMap.get("pipeLow"); case pipeNormal: return this.signalMap.get("pipeNormal"); case PAUSED: return this.signalMap.get("PAUSED"); case END: return this.signalMap.get("END"); } return false; } }
C++
UTF-8
443
2.75
3
[]
no_license
/**http://codeforces.com/problemset/problem/798/B*/ #include <iostream> #include <string> using namespace std; int cnt=0,ans=0x3f3f3f3f; int main(){ int n; string a[55],temp; cin>>n; for(int i=0;i<n;i++) cin>>a[i]; for(int i=0;i<n;i++){ cnt=0; for(int j=0;j<n;j++){ temp=a[j]+a[j]; if(temp.find(a[i])==string::npos) {cout<<-1<<endl;return 0;} cnt+=temp.find(a[i]); } ans=min(ans,cnt); } cout<<ans<<endl; return 0; }
Python
UTF-8
1,165
3.265625
3
[]
no_license
from lox.expr import BaseExpr, Expr, ExprVisitor from lox.token import Token, TokenType class AstPrinter(ExprVisitor): def print(self, expr: BaseExpr): return expr.accept(self) def visit_unary(self, expr: Expr.Unary): return self.parenthesize(expr.operator.lexeme, expr.right) def visit_literal(self, expr: 'Expr.Literal'): return expr.value if expr.value is not None else 'nil' def visit_grouping(self, expr: 'Expr.Grouping'): return self.parenthesize('group', expr.expression) def visit_binary(self, expr: 'Expr.Binary'): return self.parenthesize(expr.operator.lexeme, expr.left, expr.right) def visit_ternary(self, expr: 'Expr.Ternary'): return self.parenthesize('?', expr.condition, expr.left, expr.right) def parenthesize(self, name, *exprs): return f'({name} {" ".join([str(x.accept(self)) for x in exprs])})' def test_ast_printer(): expr = Expr.Binary( Expr.Unary(Token(TokenType.PLUS, '+', None, 1), Expr.Literal(123)), Token(TokenType.STAR, '*', None, 1), Expr.Grouping(Expr.Literal(3.14)), ) print(AstPrinter().print(expr))
C++
UTF-8
3,414
2.796875
3
[]
no_license
/// File: Source\Nexus\Graphics\Base\GLRenderer.cpp. /// /// Summary: Implements the gl renderer class. #include <GLAD\GL.h> #include <Nexus\Graphics\Base\GLRenderer.hpp> #include <Nexus\DebugWriter.hpp> namespace Nexus::Graphics::Base { GLRenderer::GLRenderer() { DebugWriter().Write("GLRenderer created.\n"); } GLRenderer::~GLRenderer() noexcept { DebugWriter().Write("GLRenderer destroyed.\n"); } void GLRenderer::DrawArrays(const GLDrawMode& mode, const int& first, const int& count) noexcept { glDrawArrays(static_cast<GLenum>(mode), first, count); } void GLRenderer::DrawArraysIndirect(const GLDrawMode& mode, const GLDrawArraysIndirectCommand& cmd) noexcept { glDrawArraysIndirect(static_cast<GLenum>(mode), &cmd); } void GLRenderer::DrawArraysInstanced(const GLDrawMode& mode, const int& first, const int& count, const int& instanceCount) noexcept { glDrawArraysInstanced(static_cast<GLenum>(mode), first, count, instanceCount); } void GLRenderer::DrawArraysInstancedBaseInstance(const GLDrawMode& mode, const int& first, const int& count, const int& instanceCount, const unsigned int& baseInstance) noexcept { glDrawArraysInstancedBaseInstance(static_cast<GLenum>(mode), first, count, instanceCount, baseInstance); } void GLRenderer::DrawElements(const GLDrawMode& mode, const int& count, const void* indices) noexcept { glDrawElements(static_cast<GLenum>(mode), count, GL_UNSIGNED_INT, indices); } void GLRenderer::DrawElementsBaseVertex(const GLDrawMode& mode, const int& count, const void* indices, const int& baseVertex) noexcept { glDrawElementsBaseVertex(static_cast<GLenum>(mode), count, GL_UNSIGNED_INT, indices, baseVertex); } void GLRenderer::DrawElementsIndirect(const GLDrawMode& mode, const GLDrawElementsIndirectCommand& cmd) noexcept { glDrawElementsIndirect(static_cast<GLenum>(mode), GL_UNSIGNED_INT, &cmd); } void GLRenderer::DrawElementsInstanced(const GLDrawMode& mode, const int& count, const void* indices, const int& instanceCount) noexcept { glDrawElementsInstanced(static_cast<GLenum>(mode), count, GL_UNSIGNED_INT, indices, instanceCount); } void GLRenderer::DrawElementsInstancedBaseInstance(const GLDrawMode& mode, const int& count, const void* indices, const int& instanceCount, const unsigned int baseInstance) noexcept { glDrawElementsInstancedBaseInstance(static_cast<GLenum>(mode), count, GL_UNSIGNED_INT, indices, instanceCount, baseInstance); } void GLRenderer::DrawElementsInstancedBaseVertex(const GLDrawMode& mode, const int& count, const void* indices, const int& instanceCount, const int& baseVertex) noexcept { glDrawElementsInstancedBaseVertex(static_cast<GLenum>(mode), count, GL_UNSIGNED_INT, indices, instanceCount, baseVertex); } void GLRenderer::DrawElementsInstancedBaseVertexBaseInstance(const GLDrawMode& mode, const int& count, const void* indices, const int& instanceCount, const int& baseVertex, const int& baseInstance) noexcept { glDrawElementsInstancedBaseVertexBaseInstance(static_cast<GLenum>(mode), count, GL_UNSIGNED_INT, indices, instanceCount, baseVertex, baseInstance); } } // End of Source\Nexus\Graphics\Base\GLRenderer.cpp
Java
UTF-8
578
2.34375
2
[]
no_license
package org.esupportail.activbo.domain.beans.channels; import org.esupportail.commons.services.ldap.LdapUser; /** * @author aanli * Canal permettant l'envoi du code d'activation pour un utilisateur donné */ public interface Channel{ /** * @param id login de l'utilisateur concerné par le code * @throws ChannelException */ public void send(String id) throws ChannelException; /** * @param name nom du canal */ public void setName(String name); /** * @return name */ public String getName(); public boolean isPossible(LdapUser ldapUser); }
Markdown
UTF-8
10,688
2.953125
3
[ "MIT" ]
permissive
--- layout: post permalink: Ещe-раз-о-Диабeтe title: Ещe раз о Диабeтe image: assets/images/wordcloud.jpg --- **Если у вас или у ваших близких есть сахарный диабет 2 типа, значит эта статья для вас.** Работая много лет с больными сахарным диабетом, я обратил внимание на то, что большинство пациентов относятся к этому заболеванию недостаточно серьёзно. Однако, мало кто знает, что продолжительность жизни больных у которых диабет не находится под хорошим контролем, в среднем на 10 лет меньше, чем у людей с хорошо контролируемым диабетом. Диабет является ведущей причиной слепоты, почечной недoстаточности и ампутаций нижних конечностей в Cеверной Aмерике. И ещё немного тревожной статистики от Канадской Диабетической Ассоциации: в 2015 году в Канаде было зарегистрировано 3.4 миллиона больных сахарным диабетом, что составляет 9.3% всего населения Канады. К 2025 году ожидается рост до 5 миллионов, что составит 12.1% канадского населения. Каждая десятая смерть среди взрослых канадцев связана с сахарным диабетом. Для того чтобы жить дольше и при этом чувствовать себя хорошо, нужно быть достаточно информированным и следовать рекомендациям специалистов. Я планирую предоставить несколько своих статеи, которые я надеюсь немножко раcшиpят ваши знания о диабете. Статьи будут основаны на информации и рекомендациях от Канадскои Диабетической Аcсоциации и на моём многолетнем опыте работы с больными сахарным диабетом. Пожалуйста, обратите внимание на то, что в основном вся инфомация будет представлена о сахарном диабете 2-го типа. Как вы знаете, основные типы диабета-это диабет 1-го и 2-го типа. Главное их отличие заключается в том, что у людей с первым типом диабета поджелудочная железа практически не вырабатывает инсулин, и эти больные должны ежедневно делать иньекции. У больных сахарным диабетом 2 го типа поджелудочная железа вырабатывает инсулин, однако производит его недостаточно, чтобы покрыть все потребности организма. Существуют и другие, второстепенные отличия, например диабетом первого типа, как правило, заболевают в раннем возрасте, тогда как для 2- го типа более характерно начало заболевания в зрелом возрасте. Больные 2-м типом диабета в отличии от больных 1-м типом, как правило, имеют избыточный вес. Среди общего количества больных диабетом, на второй тип приходится 90% и только около 10% болеют 1-м типом. В этой статье я бы хотел поговорить о риск факторах или о причинах сахарного диабета 2 типа. Часто мне приходится слышать различные мифы о причинах диабета. Например, "мой знакомый заболел сахарным диабетом, наверно много ел сладкого" или "я заболел диабетом, потому что у меня было много стреcсов". К этим предположениям мы еще вернeмся, а сейчас я бы хотел привести список риск факторов для 2 го типа диабета, который даёт Канадская Диабетическая Ассоциация. <br />• **Возраст старше 40 лет** <br />• **Наследственность** (Наличие близких родственников с сахарным диабетом) <br />• **Принадлежность к определенным этническим группам** (Аборигены, латино-американцы, жители Азии и Африки чаще болеют дибетом, чем другие этнические группы) <br />• **Предиабет** (Состояние когда сахар крови слегка повышен, но ненастолько высок, чтобы можно было поставить диагноз диабет) <br />• **Диабет беременных** (Повышение сахара крови только в период беременности) <br />• **Рождение ребенка весом более 4 кг** (причем это риск фактор для обоих и матери и ребенка) <br />• **Избыточный вес** <br />• **Высокое кровяное давление** <br />• **Высокий холестерин** <br />• **Проблемы сердечно-сосудистой системы** <br />• **Синдром поликистоза яичников у женщин** <br />• **Приём некоторых медикаментов** (например, глюкокортикоидов или приём некоторых препаратов для лечения психических расстройств) <br />• **Некоторые психические растройства** (шизофрения, депрессия, маниакально-депрессивный психоз) Как мы видим, прием пищи с большим содержанием сахара и стреcс не находятся в этом списке. Они не являются прямыми причинами диабета. Однако, неумеренное употребление сладкого может быть одной из причин избыточного веса, а избыточный вес и есть серьёзный риск фактор. Аналогичная ситуация и со стреcсом. Очень часто люди, что бы уменьшить неприятные эмоции, связанные со стрессом переедают, стараясь "заесть стресс" , что опять же ведет к избыточному весу. Чем больше риск факторов, тем больше вероятнoсть заболеть диабетом 2-го типа. Как мы видим, имеются риск факторы, с которыми мы, к сожалению, ничего не можем поделать, такие как, например, наследственность или возраст. Однако снизить вес или привести в порядок давление и холестерин крови вполне нам по силам. Также я бы хотел хотел поговорить еще об одном мифе, а именно об излечении сахарного диабета, о котором иногда слышишь от недобросовестных целителей или от плохо информированных граждан. Хочу сразу сказать, что в настоящее время диабет является неизлечимым хроническим заболеванием. Мы знаем как добиться того что-бы держать диабет под хорошим контролем и даже снизить уровень сахара до нормальных цифр. Но мы не можем сказать пациенту-всё, мы тебя вылечили, забудь о диабете, кушай что хочешь, делай что хочешь. Представте, например, что наш пациент строго следует всем рекомендациям, следит за своей диетой, значительно повысил свою физическу активность, сбросил лишние килограммы, и как результат его сахар вернулся к нормальному уровню. Можем ли мы сказать, что он вылечился? Что будет с его его сахаром в крови, если он все забросит, начнет кушать сладкое и набирать прежний вес ? Разумеется, сахар опять повысится до исходных цифр. Конечно, нужно быть оптимистами, наука идет вперед очень быстро. Будем надеятся, что в ближайшем будущем диабет будет полностью излечим. А пока нужно полагаться на хорошо проверенные и надежные традиционные методы, о которых, как и о многом другом мы поговорим в моих следующих статьях. <br /> Николай Мазур <br /> Врач-эндокринолог (Россия) <br /> Сертифицированный консультант по диабету (CDE, Canada) Опубликовано в журнале "Канадский Лекарь", февраль 2016 стр. 44-45
Java
UTF-8
855
2.171875
2
[]
no_license
package com.onlineshop.business.adress.domain; import com.onlineshop.business.order.domain.Order; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; import java.util.UUID; @Data @Entity @Table @NoArgsConstructor @AllArgsConstructor @Builder public class Address { @Id @GeneratedValue private UUID id; @Column private String firstName; @Column private String lastName; @Column private String firstLineAddress; @Column private String secondLineAddress; @Column private String postcode; @Column private String city; @Column private Integer phoneNumber; @Column private String email; @Column private String additionalInformation; @OneToOne() private Order order; }
C++
UTF-8
2,610
2.5625
3
[ "Apache-2.0" ]
permissive
/** * @file FullyConnectedLayer.h * @date 2016/5/10 * @author jhkim * @brief * @details */ #ifndef LAYER_FULLYCONNECTEDLAYER_H_ #define LAYER_FULLYCONNECTEDLAYER_H_ #include "common.h" #include "BaseLayer.h" #include "LearnableLayer.h" #include "LayerConfig.h" #include "LayerFunc.h" /** * @brief Fully Connected (Inner Product) 레이어 * @details 이전 레이어와 현재 레이어의 모든 노드들에 대해 연결성이 있고 * 연결성을 통해 weighted sum, activation을 수행 출력값을 계산하는 레이어이다. * 입력 레이어가 다차원인 경우(이미지의 경우 height x width x channel의 3차원) * 1차원으로 flatten((height*width*channel) x 1 x 1)된다. * 출력 역시 1차원 flatten 결과이며 필요에 따라서 입력받는 레이어에서 다시 차원을 * 복구해야 한다. */ template <typename Dtype> class FullyConnectedLayer : public LearnableLayer<Dtype> { public: FullyConnectedLayer(); virtual ~FullyConnectedLayer(); virtual void backpropagation(); virtual void reshape(); virtual void feedforward(); virtual void update(); void applyChanges(LearnableLayer<Dtype> *targetLayer); void syncParams(LearnableLayer<Dtype> *targetLayer); virtual void saveParams(std::ofstream& ofs); protected: void _computeWeightedData(); void _computeWeightBiasedData(); void _computeWeightGrad(); void _computeBiasGrad(); void _computeInputGrad(); enum ParamType { Weight = 0, Bias = 1 }; protected: //Dtype* d_onevec; ///< batch 사이즈의 1 벡터, bias를 weighted sum에 더해 줄 때 사용 SyncMem<Dtype> _onevec; SyncMem<Dtype> _mask; public: uint32_t batches; uint32_t in_rows; uint32_t out_rows; public: /**************************************************************************** * layer callback functions ****************************************************************************/ static void* initLayer(); static void destroyLayer(void* instancePtr); static void setInOutTensor(void* instancePtr, void* tensorPtr, bool isInput, int index); static bool allocLayerTensors(void* instancePtr); static void forwardTensor(void* instancePtr, int miniBatchIndex); static void backwardTensor(void* instancePtr); static void learnTensor(void* instancePtr); static bool checkShape(std::vector<TensorShape> inputShape, std::vector<TensorShape> &outputShape); static uint64_t calcGPUSize(std::vector<TensorShape> inputShape); }; #endif /* LAYER_FULLYCONNECTEDLAYER_H_ */
Java
UTF-8
1,685
2.046875
2
[]
no_license
package com.avroreader; import org.apache.spark.SparkConf; import org.apache.spark.api.java.JavaSparkContext; import org.apache.spark.sql.DataFrameReader; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.SQLContext; public class ReadUtil { public static void main(String[] args) { SparkConf conf = new SparkConf(); conf.setAppName("SparkReadAvroTest"); conf.setMaster("local"); JavaSparkContext sc = new JavaSparkContext(conf); SQLContext sqlCon = new SQLContext(sc); sqlCon.sparkContext().hadoopConfiguration().set("avro.mapred.ignore.inputs.without.extension", "false"); ///Users/cuiwenxu/Documents/restore/icebergfiles/testupsert/metadata/snap-7348347678694955289-1-4329c3ed-a11c-4538-aae7-662fffff7919.avro // Dataset dataset = sqlCon.read().format("com.databricks.spark.avro").load("/Users/cuiwenxu/Documents/restore/icebergfiles/testupsert/metadata/snap-7348347678694955289-1-4329c3ed-a11c-4538-aae7-662fffff7919.avro"); Dataset dataset = sqlCon.read().format("com.databricks.spark.avro").load("/Users/cuiwenxu/Documents/restore/icebergfiles/testupsert/metadata/4329c3ed-a11c-4538-aae7-662fffff7919-m1.avro"); // Dataset dataset = sqlCon.read().format("com.databricks.spark.avro").load("/Users/cuiwenxu/Documents/restore/icebergfiles/testupsert/metadata/4329c3ed-a11c-4538-aae7-662fffff7919-m1.avro"); // Dataset dataset = sqlCon.read().format("com.databricks.spark.avro").load("/Users/cuiwenxu/Documents/restore/icebergfiles/testupsert/metadata/snap-7348347678694955289-1-4329c3ed-a11c-4538-aae7-662fffff7919.avro"); dataset.toDF().show(1000,false); } }
C++
UTF-8
3,063
3.875
4
[]
no_license
/* * File: main.cpp * Author: Anh Le * Created on October 2, 2015, 1:58 PM */ //Libraries #include <iomanip> #include <iostream> using namespace std; // Function prototypes void arrSelectSort(int [], int); void showArray(const int [], int); void showArrPtr(int [], int); int main() { int NUM_DONATIONS; // Number of donations //Prompt for user's input of the size of the array cout << "Enter the number of donations: \n"; cin >> NUM_DONATIONS; //Setting the pointers of arrays to 0 int* donations = NULL; // An array containing the donation amounts. int* arrPtr = NULL; // An array of pointers to int. //Allocate memories for the arrays donations = new int[NUM_DONATIONS]; arrPtr = new int[NUM_DONATIONS]; //Initialize elements to 0; for(int count = 0; count < NUM_DONATIONS; count++) { donations[count] = 0; } //OUTPUT for donation amount cout << "Enter the donation amounts: \n"; for(int count = 0; count < NUM_DONATIONS; count++) { cin >> donations[count]; //INPUT donations in different orders } // Each element of arrPtr is a pointer to int. Make each // element point to an element in the donations array. for (int count = 0; count < NUM_DONATIONS; count++) { arrPtr[count] = donations[count]; } // Sort the elements of the array of pointers. arrSelectSort(arrPtr, NUM_DONATIONS); // Display the donations using the array of pointers. This // will display them in sorted order. cout << "The donations, sorted in descending order are: \n"; showArrPtr(arrPtr, NUM_DONATIONS); // Display the donations in their original order. cout << "The donations, in their original order are: \n"; showArray(donations, NUM_DONATIONS); //Free the dynamic allocation delete [] donations; delete [] arrPtr; //Set the arrays back to 0 donations = NULL; arrPtr = NULL; return 0; } //Initialize selectionSort void arrSelectSort(int arr[], int size) { int startScan, minIndex; int minElem; for (startScan = 0; startScan < (size - 1); startScan++) { minIndex = startScan; minElem = arr[startScan]; for(int index = startScan + 1; index < size; index++) { if ((arr[index]) > minElem) { minElem = arr[index]; minIndex = index; } } arr[minIndex] = arr[startScan]; arr[startScan] = minElem; } } //*********************************************************** // Definition of function showArray. * // This function displays the contents of arr. size is the * // number of elements. * //*********************************************************** void showArray(const int arr[], int size) { for (int count = 0; count < size; count++) cout << arr[count] << " "; cout << endl; } //*********************************************************** // Definition of function showArrayPtr. * // This function displays the contents of arr. size is the * // number of elements. * //*********************************************************** void showArrPtr(int arr[], int size) { for (int count = 0; count < size; count++) cout << (arr[count]) << " "; cout << endl; }
Python
UTF-8
566
3.296875
3
[]
no_license
from p5 import * from math import cos, sin time = 0 wave = [] def setup(): size(1200, 400) title("Test") color_mode('RGB') background(0) def draw(): global time, wave background(0,0,0) translate(200,200) rad = 100 stroke(255) no_fill() circle((0,0), 2*rad) x = rad*cos(time) y = rad*sin(time) wave.insert(0, y) fill(255) circle((x, y), 8) line((0,0), (x,y)) no_fill() begin_shape() for i in range(0, len(wave)): vertex(i, wave[i]) end_shape() time += 0.05 run()
Java
UTF-8
473
1.773438
2
[]
no_license
package alex.swaggerhidden; import io.swagger.v3.oas.models.ExternalDocumentation; import io.swagger.v3.oas.models.OpenAPI; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class OpenApiConfig { @Bean public OpenAPI config() { return new OpenAPI() .externalDocs(new ExternalDocumentation().url("https://google.com").description("cool desc")); } }
Python
UTF-8
428
3.765625
4
[]
no_license
'''var_1 = "this is a text:" var_2 = " Hello bro! whats up!" var_3 = var_1 + var_2 print(var_3) print(type(var_3))''' manager_name = "Alex Ferguson" #print(len(manager_name)) '''print(manager_name[0]) print(manager_name[len(manager_name)-1]) print(len(manager_name)-1)''' #print(manager_name[5:]) #print(manager_name.index("e", 3)) manager_replaced_name = manager_name.replace("Ferguson", "Giggs") print(manager_replaced_name)
Java
UTF-8
1,309
3.375
3
[]
no_license
class hw19{ public static void main (String[]arg){ int x1 = Integer.parseInt(arg[0]); int y1 = Integer.parseInt(arg[1]); int x2 = Integer.parseInt(arg[2]); int y2 = Integer.parseInt(arg[3]); int B=0; // Check if both in range [1..8] if ((x1>0 && x1<9 && y1>0 && y1<9 && x2>0 && x2<9 && y2>0 && y2<9)){ // print the field START System.out.println(".........."); for (int ix=1;ix<=8;ix++){ System.out.print("."); for (int iy=1;iy<=8;iy++){ if (x1==x2 && y1==y2) { B=1; } if (ix==x1 && iy==y1){ if (B==1) { System.out.print("B"); }else { System.out.print("1"); } } else if (ix==x2 && iy==y2){ if (B==1) { System.out.print("B"); }else { System.out.print("2"); } } else if ((ix+iy)%2==0) { System.out.print("#"); } else { System.out.print(" "); } } System.out.println("."); } System.out.println("..........\n"); // print the field FINISH // Solution itself 8-) if (B==1) { System.out.println("No movement"); }else if (x1==x2 || y1==y2){ System.out.println("+ Rook friendly"); } else { System.out.println("- unRookAble "); } } else { System.out.println("One of the coordinates is out of [1..8] range!"); } } }
Markdown
UTF-8
6,684
2.78125
3
[]
no_license
--- description: Свойство clip-path создает ограниченную область, которая определяет какая часть элемента должна быть видимой --- # clip-path Свойство **`clip-path`** создает ограниченную область, которая определяет какая часть элемента должна быть видимой. Те части, которые находятся внутри области, видимы, в то время как части вне области, скрыты. Обрезанная область — это траектория, определяемая либо как внутренняя ссылка, либо как внешний SVG, либо как фигура, такая как круг (`circle()`). Свойство `clip-path` заменило устаревшее свойство [`clip`](clip.md). ??? info "Маски и Фигуры" <div class="col3" markdown="1"> - **clip-path** - [mask](mask.md) - [mask-border](mask-border.md) - [mask-border-mode](mask-border-mode.md) - [mask-border-outset](mask-border-outset.md) - [mask-border-repeat](mask-border-repeat.md) - [mask-border-slice](mask-border-slice.md) - [mask-border-source](mask-border-source.md) - [mask-border-width](mask-border-width.md) - [mask-clip](mask-clip.md) - [mask-composite](mask-composite.md) - [mask-image](mask-image.md) - [mask-mode](mask-mode.md) - [mask-origin](mask-origin.md) - [mask-position](mask-position.md) - [mask-repeat](mask-repeat.md) - [mask-size](mask-size.md) - [mask-type](mask-type.md) </div> <div class="col3" markdown="1"> - [shape-image-threshold](shape-image-threshold.md) - [shape-margin](shape-margin.md) - [shape-outside](shape-outside.md) </div> ## Синтаксис ```css /* Keyword values */ clip-path: none; /* Image values */ clip-path: url('resources.svg#c1'); /* Box values */ clip-path: fill-box; clip-path: stroke-box; clip-path: view-box; clip-path: margin-box; clip-path: border-box; clip-path: padding-box; clip-path: content-box; /* Geometry values */ clip-path: inset(100px 50px); clip-path: circle(50px at 0 100px); clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%); /* Box and geometry values combined */ clip-path: padding-box circle(50px at 0 100px); /* Global values */ clip-path: inherit; clip-path: initial; clip-path: unset; ``` ## Значения Свойство `clip-path` определяется как одно или комбинация значений перечисленных ниже. **`none`** : Обрезанная область не создается. `url()` : Представляет URL ссылку на траекторию, ограничивающую элемент. `inset()`, `circle()`, `ellipse()`, `polygon()` : Функция `<basic-shape>`. Размер и положение области определяется значением `<geometry-box>`. Если геометрия не определена, `border-box` будет использоваться в качестве блока. `<geometry-box>` : Если определен в комбинации с `<basic-shape>`, это значение определяет блок для базовой области. Если задан самостоятельно, определяет границы блока, включая формирование углов (такое как [`border-radius`](border-radius.md)). Геометрия может быть определена с помощью одного из следующих значений: `fill-box` : Использует границы объекта в качестве базовой области. `stroke-box` : Использует stroke bounding box в качестве базовой области. `view-box` : Использует ближайший SVG `viewport` в качестве базового блока. Если отриут `viewBox` определен для элемента, создающего SVG `viewport`, базовый блок позиционируется в оригинальной системе координат, установленной атрибутом `viewBox` и ширина и высота базового блока устанавливаются равными значениям атрибута `viewBox`. `margin-box` : Использует margin box в качестве базового блока. `border-box` : Использует border box в качестве базового блока. `padding-box` : Использует padding box в качестве базового блока. `content-box` : Использует content box в качестве базового блока. **Значение по-умолчанию:** ```css clip-path: none; ``` Применяется ко всем элементам; в SVG, это применяется к контейнерам, исключая элемент `defs` и все графические элементы ## Спецификации - [CSS Masking Module Level 1](https://drafts.fxtf.org/css-masking-1/#the-clip-path) - [Scalable Vector Graphics (SVG) 1.1 (Second Edition)](http://www.w3.org/TR/SVG11/masking.html#ClipPathProperty) ## Поддержка браузерами <p class="ciu_embed" data-feature="css-clip-path" data-periods="future_1,current,past_1,past_2"> <a href="http://caniuse.com/#feat=css-clip-path">Can I Use css-clip-path?</a> Data on support for the css-clip-path feature across the major browsers from caniuse.com. </p> ## Описание и примеры === "HTML" ```html <img id="clipped" src="https://mdn.mozillademos.org/files/12668/MDN.svg" alt="MDN logo" /> <svg height="0" width="0"> <defs> <clipPath id="cross"> <rect y="110" x="137" width="90" height="90" /> <rect x="0" y="110" width="90" height="90" /> <rect x="137" y="0" width="90" height="90" /> <rect x="0" y="0" width="90" height="90" /> </clipPath> </defs> </svg> <select id="clipPath"> <option value="none">none</option> <option value="circle(100px at 110px 100px)">circle</option> <option value="url(#cross)" selected>cross</option> <option value="inset(20px round 20px)">inset</option> </select> ``` === "CSS" ```css #clipped { margin-bottom: 20px; clip-path: url(#cross); } ```
C++
UTF-8
302
3.015625
3
[]
no_license
#include <commission.h> Commission::Commission(double comRate): Payment("commission"), commissionRate(comRate), totalSales(0.0){ } void Commission::addSales(double sales){ totalSales = totalSales + sales; } double Commission::pay() const{ return commissionRate / 100 * totalSales; }
C++
UTF-8
1,278
3.125
3
[]
no_license
#include <cstdlib> #include <iostream> #include <stack> #include <string> using namespace std; std :: stack <int> stak; string a; int n; int main(int argc, char *argv[]) { while(true){ cin >> a; if(a.compare("push") == 0){ cin >> n; stak.push(n); cout << "ok" << endl; } else if(a.compare("pop") == 0){ if(stak.empty()) cout << "error" << endl; else{ cout << stak.top() << endl; stak.pop(); } } else if(a.compare("back") == 0){ if(stak.empty()) cout << "error" << endl; else cout << stak.top() << endl; } else if(a.compare("clear") == 0){ while(!stak.empty()) stak.pop(); cout << "ok" << endl; } else if(a.compare("size") == 0){ cout << stak.size() << endl; } else if(a.compare("exit") == 0){ cout << "bye" << endl; break; } } return EXIT_SUCCESS; }
Ruby
UTF-8
2,314
4.03125
4
[]
no_license
require "pry" INITIAL_MARKER = ' ' PLAYER_MARKER = 'X' COMPUTER_MARKER = 'O' WINNING_LINES = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] + [[1, 4, 7], [2, 5, 8], [3, 6, 9]] + [[1, 5, 9], [3, 5, 7]] def prompt(msg) puts "=> #{msg}" end def initialize_board new_board = {} (1..9).each { |num| new_board[num] = INITIAL_MARKER } new_board end # rubocop:disable Metrics/AbcSize def display_board(board) puts " | | " puts " #{board[1]} | #{board[2]} | #{board[3]} " puts " | | " puts "-----------------------" puts " | | " puts " #{board[4]} | #{board[5]} | #{board[6]} " puts " | | " puts "-----------------------" puts " | | " puts " #{board[7]} | #{board[8]} | #{board[9]} " puts " | | " end # rubocop:enable Metrics/AbcSize def empty_squares(board) board.keys.select { |num| board[num] == INITIAL_MARKER } end def player_turn!(board) square = '' loop do prompt("Choose an empty square: #{empty_squares(board).join(' ')}") square = gets.chomp.to_i break if empty_squares(board).include?(square) prompt "Sorry, that's not a valid choice" end board[square] = PLAYER_MARKER end def computer_turn(board) square = empty_squares(board).sample board[square] = COMPUTER_MARKER end def winner?(board) WINNING_LINES.each do |line| slots = [board[line[0]], board[line[1]], board[line[2]]] if slots.all?(PLAYER_MARKER) || slots.all?(COMPUTER_MARKER) return slots[0] == PLAYER_MARKER ? PLAYER_MARKER : COMPUTER_MARKER end end false end def full?(board) empty_squares(board).empty? end def replay? prompt("Would you like to play again? y/n") replay = '' loop do replay = gets.chomp break if %(y n).include?(replay) prompt("I'm sorry, that's not a valid response.") end replay == 'y' end # Main Game Loop loop do board = initialize_board display_board(board) loop do player_turn!(board) break if winner?(board) || full?(board) computer_turn(board) break if winner?(board) || full?(board) display_board(board) end winner?(board) ? prompt("#{winner?(board)} won!") : prompt("It's a tie!") break unless replay? end
C++
UTF-8
1,106
3.0625
3
[]
no_license
class Solution { public: int calculate(string s) { stack<int> S; long long int temp = 0; char sign = '+'; for(int i = 0; i < s.size(); i++) { if(isdigit(s[i])) { temp = temp * 10 + (s[i] - '0'); } if((s[i] != ' ' && !isdigit(s[i])) || i == s.size() - 1) { if(sign == '+') { S.push(temp); } else if(sign == '-') { S.push(-temp); } else { if(sign == '*') { long long int num = S.top() * temp; S.pop(); S.push(num); } else { long long int num = S.top() / temp; S.pop(); S.push(num); } } sign = s[i]; temp = 0; } } long long int sum = 0; while(!S.empty()) { sum += S.top(); S.pop(); } return sum; } };
C
UTF-8
20,116
2.546875
3
[ "MIT" ]
permissive
#define __MIPSVM_C__ #include <string.h> #include <stdint.h> #include <stdbool.h> #include "mipsvm.h" static void schedule_abs_branch(mipsvm_t *ctx, uint32_t dst) { ctx->branch_pc = dst; ctx->branch_is_pending = 1; } static void schedule_rel_branch(mipsvm_t *ctx, int32_t offset) { ctx->branch_pc = ctx->pc + offset; ctx->branch_is_pending = 1; } static uint8_t readb(mipsvm_t *ctx, uint32_t addr) { return ctx->iface.readb(addr); } static uint16_t readh(mipsvm_t *ctx, uint32_t addr) { if (addr % 2) { ctx->exception = MIPSVM_RC_READ_ADDRESS_ERROR; return 0; } return ctx->iface.readh(addr); } static uint32_t readw(mipsvm_t *ctx, uint32_t addr) { if (addr % 4) { ctx->exception = MIPSVM_RC_READ_ADDRESS_ERROR; return 0; } return ctx->iface.readw(addr); } static void writeb(mipsvm_t *ctx, uint32_t addr, uint8_t data) { ctx->iface.writeb(addr, data); } static void writeh(mipsvm_t *ctx, uint32_t addr, uint16_t data) { if (addr % 2) { ctx->exception = MIPSVM_RC_WRITE_ADDRESS_ERROR; return; } ctx->iface.writeh(addr, data); } static void writew(mipsvm_t *ctx, uint32_t addr, uint32_t data) { if (addr % 4) { ctx->exception = MIPSVM_RC_WRITE_ADDRESS_ERROR; return; } ctx->iface.writew(addr, data); } static bool exec_special(mipsvm_t *ctx, uint32_t instr) { const int func = instr & 0x3F; const int rs = (instr >> 21) & 0x1F; const int rt = (instr >> 16) & 0x1F; const int rd = (instr >> 11) & 0x1F; const int aux = (instr >> 6) & 0x1F; if (rs == 0 && rt == 0 && aux == 0) // rs, rt, aux unused { switch (func) { case 0x10: // mfhi ctx->gpr[rd] = ctx->hi; return 1; case 0x12: // mflo ctx->gpr[rd] = ctx->lo; return 1; } } if (rt == 0 && rd == 0 && aux == 0) // aux, rd, rt unused { switch (func) { case 0x11: // mthi ctx->hi = ctx->gpr[rs]; return 1; case 0x13: // mtlo ctx->lo = ctx->gpr[rs]; return 1; } } if (rt == 0 && rd == 0) // rt, rd are unused { switch (func) { case 0x08: // jr schedule_abs_branch(ctx, ctx->gpr[rs]); return 1; } } if (rd == 0 && aux == 0) // rd, aux unused { switch (func) { case 0x1A: // div ctx->lo = (int32_t) ctx->gpr[rs] / (int32_t) ctx->gpr[rt]; ctx->hi = (int32_t) ctx->gpr[rs] % (int32_t) ctx->gpr[rt]; return 1; case 0x1B: // divu ctx->lo = ctx->gpr[rs] / ctx->gpr[rt]; ctx->hi = ctx->gpr[rs] % ctx->gpr[rt]; return 1; case 0x18: // mult ctx->acc = ((int64_t) (int32_t) ctx->gpr[rs]) * (int32_t) ctx->gpr[rt]; return 1; case 0x19: // multu ctx->acc = (uint64_t) ctx->gpr[rs] * ctx->gpr[rt]; return 1; } } if (aux == 0) // aux unused { switch (func) { case 0x0A: // movz if (ctx->gpr[rt] == 0) ctx->gpr[rd] = ctx->gpr[rs]; return 1; case 0x0B: // movn if (ctx->gpr[rt] != 0) ctx->gpr[rd] = ctx->gpr[rs]; return 1; case 0x2A: // slt ctx->gpr[rd] = (int32_t)ctx->gpr[rs] < (int32_t)ctx->gpr[rt]; return 1; case 0x2B: // sltu ctx->gpr[rd] = ctx->gpr[rs] < ctx->gpr[rt]; return 1; case 0x20: // add (w overflow) { uint32_t tmp = ctx->gpr[rs] + ctx->gpr[rt]; if (((tmp ^ ctx->gpr[rs]) & (tmp ^ ctx->gpr[rt])) >> 31) ctx->exception = MIPSVM_RC_INTEGER_OVERFLOW; else ctx->gpr[rd] = tmp; } return 1; case 0x21: // addu (wo overflow) ctx->gpr[rd] = ctx->gpr[rs] + ctx->gpr[rt]; return 1; case 0x24: // and ctx->gpr[rd] = ctx->gpr[rs] & ctx->gpr[rt]; return 1; case 0x27: // nor ctx->gpr[rd] = ~(ctx->gpr[rs] | ctx->gpr[rt]); return 1; case 0x25: // or ctx->gpr[rd] = ctx->gpr[rs] | ctx->gpr[rt]; return 1; case 0x04: // sllv ctx->gpr[rd] = ctx->gpr[rt] << (ctx->gpr[rs] & 0x1F); return 1; case 0x07: // srav ctx->gpr[rd] = (int32_t) ctx->gpr[rt] >> (ctx->gpr[rs] & 0x1F); return 1; case 0x06: // srlv ctx->gpr[rd] = ctx->gpr[rt] >> (ctx->gpr[rs] & 0x1F); return 1; case 0x22: // sub (w overflow) { uint32_t tmp = ctx->gpr[rs] - ctx->gpr[rt]; if (((ctx->gpr[rs] ^ ctx->gpr[rt]) & (tmp ^ ctx->gpr[rs])) >> 31) ctx->exception = MIPSVM_RC_INTEGER_OVERFLOW; else ctx->gpr[rd] = tmp; } return 1; case 0x23: // subu (w/o overflow) ctx->gpr[rd] = ctx->gpr[rs] - ctx->gpr[rt]; return 1; case 0x26: // xor ctx->gpr[rd] = ctx->gpr[rs] ^ ctx->gpr[rt]; return 1; } } if (rs == 0) // rs unused { switch (func) { case 0x00: // sll ctx->gpr[rd] = ctx->gpr[rt] << aux; return 1; case 0x02: // srl ctx->gpr[rd] = ctx->gpr[rt] >> aux; return 1; case 0x03: // sra ctx->gpr[rd] = (int32_t) ctx->gpr[rt] >> aux; return 1; } } if (rt == 0) // rt unused { switch (func) { case 0x09: // jalr ctx->gpr[rd] = ctx->pc + 4; schedule_abs_branch(ctx, rs ? ctx->gpr[rs] : 0); // XXX: r0 should be always 0 return 1; } } switch (func) { case 0x0D: // break ctx->code = (instr << 6) >> 12; ctx->exception = MIPSVM_RC_BREAK; return 1; case 0x02: if (rs == 1) // rotr { ctx->gpr[rd] = (ctx->gpr[rt] >> aux) | (ctx->gpr[rt] << (32 - aux)); return 1; } break; case 0x06: if (aux == 1) // rotrv { int s = ctx->gpr[rs] & 0x1F; ctx->gpr[rd] = (ctx->gpr[rt] >> s) | (ctx->gpr[rt] << (32 - s)); return 1; } break; case 0x0C: // syscall ctx->code = (instr << 6) >> 12; ctx->exception = MIPSVM_RC_SYSCALL; return 1; case 0x34: // teq if (ctx->gpr[rs] == ctx->gpr[rt]) { ctx->code = (instr >> 6) & 0x3FF; ctx->exception = MIPSVM_RC_TRAP; } return 1; case 0x30: // tge if ((int32_t)ctx->gpr[rs] >= (int32_t)ctx->gpr[rt]) { ctx->code = (instr >> 6) & 0x3FF; ctx->exception = MIPSVM_RC_TRAP; } return 1; case 0x31: // tgeu if (ctx->gpr[rs] >= ctx->gpr[rt]) { ctx->code = (instr >> 6) & 0x3FF; ctx->exception = MIPSVM_RC_TRAP; } return 1; case 0x32: // tlt if ((int32_t)ctx->gpr[rs] < (int32_t)ctx->gpr[rt]) { ctx->code = (instr >> 6) & 0x3FF; ctx->exception = MIPSVM_RC_TRAP; } return 1; case 0x33: // tltu if (ctx->gpr[rs] < ctx->gpr[rt]) { ctx->code = (instr >> 6) & 0x3FF; ctx->exception = MIPSVM_RC_TRAP; } return 1; case 0x36: // tltu if (ctx->gpr[rs] != ctx->gpr[rt]) { ctx->code = (instr >> 6) & 0x3FF; ctx->exception = MIPSVM_RC_TRAP; } return 1; } return 0; } static bool exec_special2(mipsvm_t *ctx, uint32_t instr) { const int func = instr & 0x3F; const int rs = (instr >> 21) & 0x1F; const int rt = (instr >> 16) & 0x1F; const int rd = (instr >> 11) & 0x1F; const int aux = (instr >> 6) & 0x1F; if (rd == 0 && aux == 0) { switch (instr) { case 0x00: // madd ctx->acc += ((int64_t) (int32_t) ctx->gpr[rs]) * (int32_t) ctx->gpr[rt]; return 1; case 0x01: // maddu ctx->acc += (uint64_t) ctx->gpr[rs] * ctx->gpr[rt]; return 1; case 0x04: // msub ctx->acc -= ((int64_t) (int32_t) ctx->gpr[rs]) * (int32_t) ctx->gpr[rt]; return 1; case 0x05: // msubu ctx->acc -= (uint64_t) ctx->gpr[rs] * ctx->gpr[rt]; return 1; } } if (aux == 0) { switch (func) { case 0x02: // mul ctx->gpr[rd] = (int32_t)ctx->gpr[rs] * (int32_t)ctx->gpr[rt]; return 1; // NOTE: no reason to call native hardware clz, we are VM and slow anyway case 0x20: // clz if (! ctx->gpr[rs]) ctx->gpr[rd] = 32; else { int i = 0; for (uint32_t tmp = ctx->gpr[rs]; ! (tmp & 0x80000000); tmp <<= 1, i++); ctx->gpr[rd] = i; } return 1; case 0x21: // clo if (ctx->gpr[rs] == 0xFFFFFFFF) ctx->gpr[rd] = 32; else { int i = 0; for (uint32_t tmp = ctx->gpr[rs]; tmp & 0x80000000; tmp <<= 1, i++); ctx->gpr[rd] = i; } return 1; } } return 0; } static bool exec_special3(mipsvm_t *ctx, uint32_t instr) { const int rs = (instr >> 21) & 0x1F; const int rt = (instr >> 16) & 0x1F; const int rd = (instr >> 11) & 0x1F; const int aux = (instr >> 6) & 0x1F; const int func = instr & 0x3F; if (rs == 0 && (func == 0x20)) // bshfl ? wtf name { switch (aux) { case 0x10: // seb ctx->gpr[rd] = (int32_t)(int8_t) ctx->gpr[rt]; return 1; case 0x18: // seh ctx->gpr[rd] = (int32_t)(int16_t) ctx->gpr[rt]; return 1; case 0x02: // wsbh { uint32_t tmp = ctx->gpr[rt]; tmp = ((tmp & 0x00FF0000) << 8) | ((tmp & 0xFF000000) >> 8 ) | ((tmp & 0x000000FF) << 8) | ((tmp & 0x0000FF00) >> 8); ctx->gpr[rd] = tmp; } return 1; } } if (func == 0x00) //ext { uint32_t src = ctx->gpr[rs]; src <<= 32 - aux - rd - 1; // remove msbits src >>= 32 - rd - 1; // remove lsbits and right-align ctx->gpr[rt] = src; return 1; } if (func == 0x04) // ins { int lsb = aux; int msb = rd; uint32_t src = ctx->gpr[rs]; src <<= 32 - (msb - lsb + 1); // clear src msbits src >>= 32 - (msb + 1); // align uint32_t mask = 0xFFFFFFFF; mask <<= 32 - (msb - lsb + 1); // clear mask msbits mask >>= 32 - (msb + 1); // align ctx->gpr[rt] = (ctx->gpr[rt] & ~mask) | src; return 1; } return 0; } static bool exec_jtype(mipsvm_t *ctx, uint32_t instr) { uint32_t targ = (instr << 8) >> 6; switch (instr >> 26) { case 0x02: // j schedule_abs_branch(ctx, (ctx->pc & 0xF0000000) | targ); return 1; case 0x03: // jal ctx->gpr[31] = ctx->pc + 4; schedule_abs_branch(ctx, (ctx->pc & 0xF0000000) | targ); return 1; } return 0; } static bool exec_itype(mipsvm_t *ctx, uint32_t instr) { const int opcode = instr >> 26; const int rs = (instr >> 21) & 0x1F; const int rt = (instr >> 16) & 0x1F; const uint32_t imm_ze = (instr & 0xFFFF); const int32_t imm_se = (int16_t)(instr & 0xFFFF); if (opcode == 1) // regimm { switch (rt) { case 0x0: // bltz if ((int32_t)ctx->gpr[rs] < 0) schedule_rel_branch(ctx, imm_se << 2); return 1; case 0x01: // bgez if ((int32_t)ctx->gpr[rs] >= 0) schedule_rel_branch(ctx, imm_se << 2); return 1; case 0x10: // bltzal if ((int32_t)ctx->gpr[rs] < 0) { ctx->gpr[31] = ctx->pc + 4; schedule_rel_branch(ctx, imm_se << 2); } return 1; case 0x11: // bgezal if ((int32_t)ctx->gpr[rs] >= 0) { ctx->gpr[31] = ctx->pc + 4; schedule_rel_branch(ctx, imm_se << 2); } return 1; case 0x0C: // teqi if (ctx->gpr[rs] == (uint32_t)imm_se) ctx->exception = MIPSVM_RC_TRAP; return 1; case 0x08: // tgei if ((int32_t)ctx->gpr[rs] >= imm_se) ctx->exception = MIPSVM_RC_TRAP; return 1; case 0x09: // tgeiu if (ctx->gpr[rs] >= (uint32_t)imm_se) ctx->exception = MIPSVM_RC_TRAP; return 1; case 0x0A: // tlti if ((int32_t)ctx->gpr[rs] < imm_se) ctx->exception = MIPSVM_RC_TRAP; return 1; case 0x0B: // tltiu if (ctx->gpr[rs] < (uint32_t)imm_se) ctx->exception = MIPSVM_RC_TRAP; return 1; case 0x0E: // tnei if (ctx->gpr[rs] != (uint32_t)imm_se) ctx->exception = MIPSVM_RC_TRAP; return 1; } } if (rt == 0) { switch (opcode) { case 0x07: // bgtz if ((int32_t)ctx->gpr[rs] > 0) schedule_rel_branch(ctx, imm_se << 2); return 1; case 0x06: // blez if ((int32_t)ctx->gpr[rs] <= 0) schedule_rel_branch(ctx, imm_se << 2); return 1; } } switch (opcode) { case 0x08: // addi (w ovf) { uint32_t tmp = ctx->gpr[rs] + imm_se; if (((tmp ^ ctx->gpr[rs]) & (tmp ^ imm_se)) >> 31) ctx->exception = MIPSVM_RC_INTEGER_OVERFLOW; else ctx->gpr[rt] = tmp; } return 1; case 0x09: // addiu (wo ovf) ctx->gpr[rt] = ctx->gpr[rs] + imm_se; return 1; case 0x0C: // andi ctx->gpr[rt] = ctx->gpr[rs] & imm_ze; return 1; case 0x04: // beq if (ctx->gpr[rs] == ctx->gpr[rt]) schedule_rel_branch(ctx, imm_se << 2); return 1; case 0x05: // bne if (ctx->gpr[rs] != ctx->gpr[rt]) schedule_rel_branch(ctx, imm_se << 2); return 1; case 0x20: // lb ctx->gpr[rt] = (int32_t)(int8_t)readb(ctx, ctx->gpr[rs] + imm_se); return 1; case 0x24: // lbu ctx->gpr[rt] = readb(ctx, ctx->gpr[rs] + imm_se); return 1; case 0x21: // lh ctx->gpr[rt] = (int32_t)(int16_t)readh(ctx, ctx->gpr[rs] + imm_se); return 1; case 0x25: // lhu ctx->gpr[rt] = readh(ctx, ctx->gpr[rs] + imm_se); return 1; case 0x0F: if (rs == 0) // lui { ctx->gpr[rt] = imm_ze << 16; return 1; } break; case 0x23: // lw ctx->gpr[rt] = readw(ctx, ctx->gpr[rs] + imm_se); return 1; case 0x22: // lwl { // little-endian mode uint32_t addr = ctx->gpr[rs] + imm_se; uint32_t offset = addr & 0x03; uint32_t word = readw(ctx, addr & -4U); uint32_t reg = ctx->gpr[rt]; reg &= 0x00FFFFFF >> (offset * 8); // 0x00FFFFFF, 0x0000FFFF, 0x000000FF, 0x00000000 word <<= 24 - (offset * 8); // 24, 16, 8, 0 ctx->gpr[rt] = reg | word; } return 1; case 0x26: // lwr { // little-endian mode uint32_t addr = ctx->gpr[rs] + imm_se; uint32_t offset = addr & 0x03; uint32_t word = readw(ctx, addr & -4U); uint32_t reg = ctx->gpr[rt]; reg &= ~(0xFFFFFFFF >> (offset * 8)); // ~0xFFFFFFFF, ~0x00FFFFFF, ~0x0000FFFF, ~0x000000FF word >>= offset * 8; // 0, 8, 16, 24 ctx->gpr[rt] = reg | word; } return 1; case 0x0D: //ori ctx->gpr[rt] = ctx->gpr[rs] | imm_ze; return 1; case 0x28: // sb writeb(ctx, ctx->gpr[rs] + imm_se, ctx->gpr[rt]); return 1; case 0x0A: // slti ctx->gpr[rt] = (int32_t) ctx->gpr[rs] < imm_se; return 1; case 0x0B: // sltiu ctx->gpr[rt] = ctx->gpr[rs] < (uint32_t)imm_se; return 1; case 0x29: // sh writeh(ctx, ctx->gpr[rs] + imm_se, ctx->gpr[rt]); return 1; case 0x2B: // sw writew(ctx, ctx->gpr[rs] + imm_se, ctx->gpr[rt]); return 1; case 0x2A: // swl { // little-endian mode uint32_t addr = ctx->gpr[rs] + imm_se; uint32_t base = addr & -4U; uint32_t offset = addr & 0x03; uint32_t reg = ctx->gpr[rt]; if (offset == 0) { writeb(ctx, base, reg >> 24); } else if (offset == 1) { writeh(ctx, base, reg >> 16); } else if (offset == 2) { writeh(ctx, base, reg >> 8); writeb(ctx, base + 2, reg >> 24); } else { writew(ctx, base, reg); } } return 1; case 0x2E: // swr { // little-endian mode uint32_t addr = ctx->gpr[rs] + imm_se; uint32_t base = addr & -4U; uint32_t offset = addr & 0x03; uint32_t reg = ctx->gpr[rt]; if (offset == 0) { writew(ctx, base, reg); // hgfe } else if (offset == 1) { writeb(ctx, base + 1, reg); // h writeh(ctx, base + 2, reg >> 8); // gf } else if (offset == 2) { writeh(ctx, base + 2, reg); // hg } else { writeb(ctx, base + 3, reg); // h } } return 1; case 0x0E: // xori ctx->gpr[rt] = ctx->gpr[rs] ^ imm_ze; return 1; case 0x30: // ll break; case 0x38: // sc break; } return 0; } mipsvm_rc_t mipsvm_exec(mipsvm_t *ctx) { // initial state before each instruction ctx->gpr[0] = 0; // r0 always == 0 ctx->exception = 0; // clean previous exception if any uint32_t instr = readw(ctx, ctx->pc); if (! ctx->branch_is_pending) { ctx->pc += 4; } else { ctx->branch_is_pending = 0; ctx->pc = ctx->branch_pc; } uint32_t opcode = instr >> 26; // 6 top bits is the opcode bool was_decoded = 0; if (opcode == 0x00) was_decoded = exec_special(ctx, instr); else if (opcode == 0x1C) was_decoded = exec_special2(ctx, instr); else if (opcode == 0x1F) was_decoded = exec_special3(ctx, instr); else if ((opcode & 0x3E) == 0x02) was_decoded = exec_jtype(ctx, instr); else if ((opcode & 0x3C) != 0x10) was_decoded = exec_itype(ctx, instr); if (ctx->exception) return ctx->exception; return was_decoded ? MIPSVM_RC_OK : MIPSVM_RC_RESERVED_INSTR; } void mipsvm_init(mipsvm_t *ctx, const mipsvm_iface_t *iface, uint32_t reset_pc) { memset(ctx, 0, sizeof(ctx)); ctx->iface = *iface; ctx->pc = reset_pc; } uint32_t mipsvm_get_callcode(const mipsvm_t *ctx) { return ctx->code; }
JavaScript
UTF-8
1,346
2.59375
3
[]
no_license
const express = require('express'); const router = express.Router(); const db = require('../database'); const bcrypt = require('bcryptjs'); router.post('/', function(request, response) { if(request.body.username && request.body.password){ var username = request.body.username; var password = request.body.password; db.query('SELECT password FROM user_table WHERE username = ?',[username], function(dbError, dbResults) { if(dbError){ response.json(dbError); } else { if (dbResults.length > 0) { bcrypt.compare(password,dbResults[0].password, function(err,compareResult) { if(compareResult) { console.log("success"); response.send(true); } else { console.log("wrong password"); response.send(false); } response.end(); } ); } else{ console.log("user does not exists"); response.send(false); } } } ); } else{ console.log("Give the username and password"); response.send(false); } } ); module.exports = router;
Markdown
UTF-8
671
2.890625
3
[ "Apache-2.0" ]
permissive
# async-http-client-usage Usage demo of [Async Http Client](https://github.com/AsyncHttpClient/async-http-client) with continuations (through Java 8 [CompletableFuture&lt;T>](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CompletableFuture.html)) Simple use: ```java try(AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient()) { asyncHttpClient .prepareGet("http://www.example.com/") .execute() .toCompletableFuture() .thenApply(Response::getResponseBody) .thenAccept(System.out::println) .join(); } ```
Python
UTF-8
7,729
2.921875
3
[]
no_license
#!/usr/bin/env python2.7 """ Columbia's COMS W4111.001 Introduction to Databases Example Webserver To run locally: python server.py Go to http://localhost:8111 in your browser. A debugger such as "pdb" may be helpful for debugging. Read about it online. """ import os from sqlalchemy import * from sqlalchemy.pool import NullPool from flask import Flask, request, render_template, g, redirect, Response tmpl_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates') app = Flask(__name__, template_folder=tmpl_dir) # # The following is a dummy URI that does not connect to a valid database. You will need to modify it to connect to your Part 2 database in order to use the data. # # XXX: The URI should be in the format of: # # postgresql://USER:PASSWORD@104.196.18.7/w4111 # # For example, if you had username biliris and password foobar, then the following line would be: # # DATABASEURI = "postgresql://biliris:foobar@104.196.18.7/w4111" # DATABASEURI = "postgresql://aja2173:6944@35.196.90.148/proj1part2" # # This line creates a database engine that knows how to connect to the URI above. # engine = create_engine(DATABASEURI) # # Example of running queries in your database # Note that this will probably not work if you already have a table named 'test' in your database, containing meaningful data. This is only an example showing you how to run queries in your database using SQLAlchemy. # @app.before_request def before_request(): """ This function is run at the beginning of every web request (every time you enter an address in the web browser). We use it to setup a database connection that can be used throughout the request. The variable g is globally accessible. """ try: print "done!!!" g.conn = engine.connect() except: print "uh oh, problem connecting to database" import traceback; traceback.print_exc() g.conn = None @app.teardown_request def teardown_request(exception): """ At the end of the web request, this makes sure to close the database connection. If you don't, the database could run out of memory! """ try: g.conn.close() except Exception as e: pass @app.route('/') def index(): print type(g.conn) return render_template("index.html") @app.route('/first') def first(): command = "select * from album where album.year>2014 order by album.year ;" c = g.conn.execute(command) a = [] for row in c : local = [] local.append(str(row['artist_id'])) local.append(row['year']) local.append(str(row['album_id'])) a.append(local) c.close() context = dict(data = a) return render_template("another.html", **context) @app.route('/second') def second(): command = "SELECT A1.artist_id Artist, COUNT(A2.award_id) The_number_of_winning_the_album_of_year FROM album A1, awarded_album A2 WHERE A1.album_id=A2.album_id GROUP BY A1.artist_id ORDER BY the_number_of_winning_the_album_of_year DESC;" c = g.conn.execute(command) a = [] for row in c : local = [] local.append(str(row['artist'])) local.append(str(row['the_number_of_winning_the_album_of_year'])) a.append(local) c.close() context = dict(data = a) return render_template("second.html", **context) @app.route('/third') def third(): command = "SELECT C1.artist_id artist, C1.country Country, COUNT(C2.album_id) total_album FROM artist C1, album C2 WHERE C1.artist_id = C2.artist_id GROUP BY C1.artist_id ORDER BY total_album DESC;" c = g.conn.execute(command) a = [] for row in c : local = [] local.append(str(row['artist'])) local.append(str(row['country'])) local.append(str(row['total_album'])) a.append(local) c.close() context = dict(data = a) return render_template("third.html", **context) @app.route('/fourth') def fourth(): command = "SELECT B1.artist_id1 Origin, B2.artist_id AS Similar, B2.album_id AS Similar_album, B2.rating AS Rating FROM similar_artists B1 INNER JOIN album B2 ON B1.artist_id2 = B2.artist_id ORDER BY Rating ASC LIMIT 1;" c = g.conn.execute(command) a = [] tmp = ['origin', 'similar', 'album', 'rating'] a.append(tmp) for row in c : local = [] local.append(str(row['origin'])) local.append(str(row['similar'])) local.append(str(row['similar_album'])) local.append(str(row['rating'])) a.append(local) c.close() context = dict(data = a) return render_template("fourth.html", **context) @app.route('/sixth') def sixth(): command = "select artist_id artist, album_id album, name song from song where artist_id = 'Swift'and album_id = 'Fearless';" c = g.conn.execute(command) a = [] tmp = ['artist', 'album', 'song'] a.append(tmp) for row in c : local = [] local.append(str(row['artist'])) local.append(str(row['album'])) local.append(str(row['song'])) a.append(local) c.close() context = dict(data = a) return render_template("sixth.html", **context) @app.route('/seventh') def seventh(): command = "select country, genre_id Genre, artist_id artist from artist where country = 'USA' and genre_id='country' group by artist_id;" c = g.conn.execute(command) a = [] tmp = ['country', 'genre', 'artist'] a.append(tmp) for row in c : local = [] local.append(str(row['country'])) local.append(str(row['genre'])) local.append(str(row['artist'])) a.append(local) c.close() context = dict(data = a) return render_template("seventh.html", **context) @app.route('/fifth') def fifth(): a = [] context = dict(data = a) return render_template("fifth.html", **context) def RepresentsInt(s): try: int(s) return True except ValueError: return False @app.route('/do_select', methods=['POST']) def do_select(): year = request.form['year'] if RepresentsInt(year)==False: a = ['Invalid Input'] context = dict(data = a) return render_template("fifth.html", **context) if int(year)>2017 or int(year)<2010: a = ['No avaiable year'] context = dict(data = a) return render_template("fifth.html", **context) command = "select * from album where year = "+year c = g.conn.execute(command) tmp = ['Artist', 'album', 'year', 'rating'] a = [] a.append(tmp) for row in c : local = [] local.append(str(row['artist_id'])) local.append(str(row['album_id'])) local.append(str(row['year'])) local.append(str(row['rating'])) a.append(local) c.close() context = dict(data = a) return render_template("fifth.html", **context) # Example of adding new data to the database @app.route('/add', methods=['POST']) def add(): print 'Hi' name = request.form['name'] g.conn.execute('INSERT INTO test VALUES (NULL, ?)', name) return redirect('/') @app.route('/login') def login(): abort(401) this_is_never_executed() if __name__ == "__main__": import click @click.command() @click.option('--debug', is_flag=True) @click.option('--threaded', is_flag=True) @click.argument('HOST', default='0.0.0.0') @click.argument('PORT', default=8111, type=int) def run(debug, threaded, host, port): """ This function handles command line parameters. Run the server using: python server.py Show the help text using: python server.py --help """ HOST, PORT = host, port print "running on %s:%d" % (HOST, PORT) app.run(host=HOST, port=PORT, debug=true, threaded=threaded) run()
Java
UTF-8
3,810
2.03125
2
[ "Apache-2.0" ]
permissive
package multidiffplus.jsanalysis.initstate; import java.util.HashMap; import java.util.Map; import java.util.Stack; import org.mozilla.javascript.ast.Name; import multidiffplus.cfg.CfgMap; import multidiffplus.jsanalysis.abstractdomain.Address; import multidiffplus.jsanalysis.abstractdomain.BValue; import multidiffplus.jsanalysis.abstractdomain.Change; import multidiffplus.jsanalysis.abstractdomain.Closure; import multidiffplus.jsanalysis.abstractdomain.Control; import multidiffplus.jsanalysis.abstractdomain.Dependencies; import multidiffplus.jsanalysis.abstractdomain.InternalFunctionProperties; import multidiffplus.jsanalysis.abstractdomain.InternalObjectProperties; import multidiffplus.jsanalysis.abstractdomain.JSClass; import multidiffplus.jsanalysis.abstractdomain.NativeClosure; import multidiffplus.jsanalysis.abstractdomain.Num; import multidiffplus.jsanalysis.abstractdomain.Obj; import multidiffplus.jsanalysis.abstractdomain.Property; import multidiffplus.jsanalysis.abstractdomain.Scratchpad; import multidiffplus.jsanalysis.abstractdomain.State; import multidiffplus.jsanalysis.abstractdomain.Store; import multidiffplus.jsanalysis.abstractdomain.Str; import multidiffplus.jsanalysis.flow.JavaScriptAnalysisState; import multidiffplus.jsanalysis.trace.Trace; /** * A factory which initializes the function object prototype in the abstract * store. */ public class FunctionFactory { public Store store; public FunctionFactory(Store store) { this.store = store; } public Obj Function_proto_Obj() { Map<String, Property> ext = new HashMap<String, Property>(); store = Utilities.addProp("external", -41, Num.inject(Num.top(), Change.u(), Dependencies.bot()), ext, store, new Name()); store = Utilities.addProp("apply", -42, Address .inject(StoreFactory.Function_proto_apply_Addr, Change.u(), Dependencies.bot()), ext, store, new Name()); store = Utilities.addProp("call", -43, Address.inject(StoreFactory.Function_proto_call_Addr, Change.u(), Dependencies.bot()), ext, store, new Name()); store = Utilities.addProp("toString", -44, Address .inject(StoreFactory.Function_proto_toString_Addr, Change.u(), Dependencies.bot()), ext, store, new Name()); InternalObjectProperties internal = new InternalObjectProperties( Address.inject(StoreFactory.Function_proto_Addr, Change.u(), Dependencies.bot()), JSClass.CFunction_prototype_Obj); return new Obj(ext, internal); } // TODO: apply and call need native closures because their behaviour // affects the analysis. public Obj Function_proto_toString_Obj() { return constFunctionObj(Str.inject(Str.top(), Change.u(), Dependencies.bot())); } public Obj Function_proto_apply_Obj() { return constFunctionObj(BValue.top(Change.u(), Dependencies.bot())); } public Obj Function_proto_call_Obj() { return constFunctionObj(BValue.top(Change.u(), Dependencies.bot())); } /** * Approximate a function which is not modeled. * * @return A function which has no side effects that that returns the BValue * lattice element top. */ public Obj constFunctionObj(BValue retVal) { Map<String, Property> external = new HashMap<String, Property>(); Closure closure = new NativeClosure() { @Override public FunctionOrSummary initializeOrRun(State preTransferState, Address selfAddr, Store store, Scratchpad scratchpad, Trace trace, Control control, CfgMap cfgs) { return new FunctionOrSummary(JavaScriptAnalysisState .initializeFunctionState(preTransferState.clone(), cfgs)); } }; Stack<Closure> closures = new Stack<Closure>(); closures.push(closure); InternalObjectProperties internal = new InternalFunctionProperties(closures, JSClass.CFunction); return new Obj(external, internal); } }
Java
UTF-8
18,451
2.09375
2
[]
no_license
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.io.Console; import java.io.File; import java.io.FileWriter; import java.io.FilenameFilter; //import gov.llnl.lc.infiniband.opensm.plugin.data.OSM_SysInfo; //import gov.llnl.lc.infiniband.opensm.plugin.net.OsmClientApi; //import gov.llnl.lc.infiniband.opensm.plugin.net.OsmServiceManager; //import gov.llnl.lc.infiniband.opensm.plugin.net.OsmSession; import gov.llnl.lc.infiniband.core.IB_Link; import gov.llnl.lc.infiniband.opensm.plugin.data.*; import net.minidev.json.JSONObject; public class OSMHBase { private static BufferedWriter countersBW, linksBW, routesBW, hbaseDumpBW; private static boolean writingHeaders = false; private static FilenameFilter fnameFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.startsWith("cab") && name.endsWith(".his"); } }; private static File hisDir; private static File outDir = new File("."); private static enum outFormat {json, delimited}; public static void main(String[] args) throws Exception { if (args.length > 0){ if (args[0].equals("help")){ showUsage(); } if (args[0].equals("parseHis")){ processOMSHistory(args); } } else{ System.out.println("No arguments found."); showUsage(); System.exit(1); } } private static void showUsage(){ System.out.println("-- ibperfp : IB Performance Processor --"); System.out.println(" ibperfp <operation> [<args>...] [json/del]"); System.out.println(""); System.out.println("Usage:"); System.out.println("# ibperfp help - Shows this help/usage message."); System.out.println("# ibperfp parseHis /path/to/his/dir - Extract data from OMS '.his' files located in a given path."); System.out.println("# ibperfp parseHis /path/to/hisFile - Extract data from a single '.his'"); System.out.println("# ibperfp parseHis <path> json - Writes data in JSON format."); System.out.println("# ibperfp parseHis <path> del - Writes data in delimited format."); } private static void processOMSHistory(String[] args){ File path; File[] hisFiles = null; outFormat outType = null; if (args.length > 1){ path = new File(args[1]); if(path.exists()){ if(path.isDirectory()){ hisDir = path; } else if(path.isFile()){ hisFiles = new File[1]; hisFiles[0] = path; } else{ System.err.println("ERROR: Cannot find path to history file(s) at: " + args[1]); showUsage(); System.exit(1); } } outType = outFormat.json; } else{ System.err.println("ERROR: No path argument given."); showUsage(); System.exit(1); } if (args.length > 2){ if (args[2].equals("del")){ outType = outFormat.delimited; } else if(! args[2].equals("json")){ System.err.println("ERROR: Invalid file format '" + args[2] + "' given. Using JSON."); } } OMS_Collection omsHistory = null; OpenSmMonitorService oms = null; OSM_Fabric fabric = null; long currentTime = System.currentTimeMillis() / 1000; long timestamp = 0; int i; try{ if (outType == outFormat.delimited){ File counterFile = new File(outDir, "/counters." + currentTime + ".txt"); File routesFile = new File(outDir, "/routes." + currentTime + ".txt"); File linksFile = new File(outDir, "/links." + currentTime + ".txt"); if (!counterFile.exists()) { counterFile.createNewFile(); } if (!routesFile.exists()) { routesFile.createNewFile(); } if (!linksFile.exists()) { linksFile.createNewFile(); } countersBW = new BufferedWriter(new FileWriter(counterFile)); routesBW = new BufferedWriter(new FileWriter(routesFile)); linksBW = new BufferedWriter(new FileWriter(linksFile)); } else{ File hbaseDumpFile = new File(outDir, "/hbaseDump." + currentTime + ".txt"); if (!hbaseDumpFile.exists()) { hbaseDumpFile.createNewFile(); } hbaseDumpBW = new BufferedWriter(new FileWriter(hbaseDumpFile)); } if (hisFiles == null){ hisFiles = hisDir.listFiles(fnameFilter); } for (File hisFile : hisFiles){ System.out.println("Processing history file: " + hisFile.getPath()); omsHistory = OMS_Collection.readOMS_Collection(hisFile.getPath()); for (i = 0; i < omsHistory.getSize(); i++){ oms = omsHistory.getOMS(i); fabric = oms.getFabric(); timestamp = oms.getTimeStamp().getTimeInSeconds(); System.out.println(".snapshot: " + oms.getTimeStamp().toString() + "."); if (outType == outFormat.json){ writeLinksJSON(fabric, timestamp); writePortCountersJSON(fabric.getOSM_Ports(), timestamp); writePortForwardingTableJSON(RT_Table.buildRT_Table(fabric), timestamp); } else{ writeLinksDelimited(fabric.getIB_Links(), timestamp); writePortCountersDelimited(fabric.getOSM_Ports(), timestamp); writePortForwardingTableDelimited(RT_Table.buildRT_Table(fabric), timestamp); } } } if (outType == outFormat.delimited){ countersBW.flush(); countersBW.close(); routesBW.flush(); routesBW.close(); linksBW.flush(); linksBW.close(); } if (outType == outFormat.json){ hbaseDumpBW.flush(); hbaseDumpBW.close(); } } catch (Exception e) { System.err.println("Couldn't open the file"); e.printStackTrace(); } System.out.println("- Complete"); } private static void writePortCountersDelimited(LinkedHashMap<String, OSM_Port> ports, long timestamp){ OSM_Port port; String portId; String nguid; int portNum; long recvData, xmitDrop, xmitWait, recvErr, recvSwRE, recvRPhE, xmitData, xmitConE; if(writingHeaders){ try { countersBW.write("# Record format: \"<timestamp>:<nguid>:<pn>:<xmitData>:<recvData>\""); countersBW.newLine(); countersBW.write("# ----Port Counters BEGIN----"); countersBW.newLine(); } catch (Exception e) { System.out.println("ERROR: could not write port counter header."); e.printStackTrace(); System.exit(1); } } for (Map.Entry<String, OSM_Port> entry: ports.entrySet()){ portId = entry.getKey(); port = entry.getValue(); nguid = portId.substring(0, 19).replace(":", ""); portNum = Integer.parseInt(portId.substring(20)); if (port.getPfmPort() == null){ continue; } timestamp = port.pfmPort.counter_ts; recvData = port.pfmPort.getCounter(PFM_Port.PortCounterName.rcv_data) * 4; recvErr = port.pfmPort.getCounter(PFM_Port.PortCounterName.rcv_err); recvSwRE = port.pfmPort.getCounter(PFM_Port.PortCounterName.rcv_switch_relay_err); recvRPhE = port.pfmPort.getCounter(PFM_Port.PortCounterName.rcv_rem_phys_err); xmitData = port.pfmPort.getCounter(PFM_Port.PortCounterName.xmit_data) * 4; xmitDrop = port.pfmPort.getCounter(PFM_Port.PortCounterName.xmit_discards); xmitWait = port.pfmPort.getCounter(PFM_Port.PortCounterName.xmit_wait); xmitConE = port.pfmPort.getCounter(PFM_Port.PortCounterName.xmit_constraint_err); try { countersBW.write(timestamp + ":" + nguid + ":" + portNum + ":" + xmitData + ":" + recvData); countersBW.newLine(); //if (i == 2) break; } catch (Exception e) { // TODO Auto-generated catch block System.out.println("ERROR: could not write port counters. "); e.printStackTrace(); System.exit(1); } } System.out.println("- Wrote port counters."); } private static void writePortCountersJSON(LinkedHashMap<String, OSM_Port> ports, long timestamp){ int i; OSM_Port port; String portId; String nguid; int portNum; long recvData, xmitDrop, xmitWait, recvErr, recvSwRE, recvRPhE, xmitData, xmitConE; JSONObject jsonPort = null; i = 0; for (Map.Entry<String, OSM_Port> entry: ports.entrySet()){ portId = entry.getKey(); port = entry.getValue(); nguid = portId.substring(0, 19).replace(":", ""); portNum = Integer.parseInt(portId.substring(20)); if (port.getPfmPort() == null){ continue; } //timestamp = port.pfmPort.counter_ts; recvData = port.pfmPort.getCounter(PFM_Port.PortCounterName.rcv_data) * 4; recvErr = port.pfmPort.getCounter(PFM_Port.PortCounterName.rcv_err); recvSwRE = port.pfmPort.getCounter(PFM_Port.PortCounterName.rcv_switch_relay_err); recvRPhE = port.pfmPort.getCounter(PFM_Port.PortCounterName.rcv_rem_phys_err); xmitData = port.pfmPort.getCounter(PFM_Port.PortCounterName.xmit_data) * 4; xmitDrop = port.pfmPort.getCounter(PFM_Port.PortCounterName.xmit_discards); xmitWait = port.pfmPort.getCounter(PFM_Port.PortCounterName.xmit_wait); xmitConE = port.pfmPort.getCounter(PFM_Port.PortCounterName.xmit_constraint_err); jsonPort = new JSONObject(); try { jsonPort.put("recordType", "counter"); jsonPort.put("ts", timestamp); jsonPort.put("nguid", nguid); jsonPort.put("portNum", portNum); jsonPort.put("r_data", port.pfmPort.getCounter(PFM_Port.PortCounterName.rcv_data) * 4); jsonPort.put("r_err", port.pfmPort.getCounter(PFM_Port.PortCounterName.rcv_err)); jsonPort.put("r_sr_err", port.pfmPort.getCounter(PFM_Port.PortCounterName.rcv_rem_phys_err)); jsonPort.put("r_phys_err", port.pfmPort.getCounter(PFM_Port.PortCounterName.rcv_rem_phys_err)); jsonPort.put("r_con_err", port.pfmPort.getCounter(PFM_Port.PortCounterName.rcv_constraint_err)); jsonPort.put("xmit_data", port.pfmPort.getCounter(PFM_Port.PortCounterName.xmit_data) * 4); jsonPort.put("xmit_discards", port.pfmPort.getCounter(PFM_Port.PortCounterName.xmit_discards)); jsonPort.put("xmit_wait", port.pfmPort.getCounter(PFM_Port.PortCounterName.xmit_wait)); jsonPort.put("xmit_con_err", port.pfmPort.getCounter(PFM_Port.PortCounterName.xmit_constraint_err)); jsonPort.put("mul_r_pkts", port.pfmPort.getCounter(PFM_Port.PortCounterName.multicast_rcv_pkts)); jsonPort.put("mul_xmit_pkts", port.pfmPort.getCounter(PFM_Port.PortCounterName.multicast_xmit_pkts)); jsonPort.put("uni_recv_pkts", port.pfmPort.getCounter(PFM_Port.PortCounterName.unicast_rcv_pkts)); jsonPort.put("uni_xmit_pkts", port.pfmPort.getCounter(PFM_Port.PortCounterName.unicast_xmit_pkts)); jsonPort.put("sym_err_cnt", port.pfmPort.getCounter(PFM_Port.PortCounterName.symbol_err_cnt)); jsonPort.put("vl15_drop", port.pfmPort.getCounter(PFM_Port.PortCounterName.vl15_dropped)); jsonPort.put("buff_overun", port.pfmPort.getCounter(PFM_Port.PortCounterName.buffer_overrun)); jsonPort.put("l_down", port.pfmPort.getCounter(PFM_Port.PortCounterName.link_downed)); jsonPort.put("l_err_recov", port.pfmPort.getCounter(PFM_Port.PortCounterName.link_err_recover)); jsonPort.put("l_integrity", port.pfmPort.getCounter(PFM_Port.PortCounterName.link_integrity)); hbaseDumpBW.write(jsonPort.toString()); hbaseDumpBW.newLine(); //if (i == 2) break; } catch (Exception e) { // TODO Auto-generated catch block System.out.println("ERROR: could not write port counters. "); e.printStackTrace(); System.exit(1); } i++; } System.out.println("- Wrote counters file."); } private static void writePortForwardingTableDelimited(RT_Table RoutingTable, long timestamp){ RT_Node node; String nguid; RT_Port port; int portNum; int routeLid; if(writingHeaders){ try { routesBW.write("# Record format: \"<ExitPort>:<LID>\""); routesBW.newLine(); routesBW.write("#----Forwarding Table BEGIN----"); routesBW.newLine(); } catch (Exception e) { System.out.println("ERROR: could not write port counter header."); e.printStackTrace(); System.exit(1); } } try{ for (Map.Entry<String, RT_Node> nEntry: RoutingTable.getSwitchGuidMap().entrySet()){ node = nEntry.getValue(); nguid = node.getGuid().toColonString().replace(":", ""); routesBW.newLine(); routesBW.write("Switch: 0x" + nguid); routesBW.newLine(); for (Map.Entry<String,RT_Port> pEntry: node.getPortRouteMap().entrySet()){ port = pEntry.getValue(); portNum = port.getPortNumber(); for (Map.Entry<String,Integer> item: port.getLidGuidMap().entrySet()){ routeLid = item.getValue(); routesBW.write(portNum + ":" + routeLid); routesBW.newLine(); } } } }catch (Exception e){ System.out.println("ERROR: Unable to write routes to file."); } System.out.println("- Wrote routes file."); } private static void writePortForwardingTableJSON(RT_Table RoutingTable, long timestamp){ RT_Node node; String nguid; RT_Port port; int portNum; int routeLid; JSONObject jsonPort = null; StringBuffer routes; try{ for (Map.Entry<String, RT_Node> nEntry: RoutingTable.getSwitchGuidMap().entrySet()){ node = nEntry.getValue(); nguid = node.getGuid().toColonString().replace(":", ""); for (Map.Entry<String,RT_Port> pEntry: node.getPortRouteMap().entrySet()){ port = pEntry.getValue(); portNum = port.getPortNumber(); jsonPort = new JSONObject(); jsonPort.put("recordType", "route"); jsonPort.put("ts", timestamp); jsonPort.put("nguid", nguid); jsonPort.put("portNum", portNum); routes = new StringBuffer(); for (Map.Entry<String,Integer> item: port.getLidGuidMap().entrySet()){ routeLid = item.getValue(); routes.append(routeLid + ":"); } jsonPort.put("routes", routes.toString()); hbaseDumpBW.write(jsonPort.toString()); hbaseDumpBW.newLine(); } } }catch (Exception e){ System.out.println("ERROR: Unable to write routes to file."); } System.out.println("- Wrote routes to file."); } private static void writeLinksDelimited(LinkedHashMap<String, IB_Link> ibLinks, long timestamp){ OSM_Port port1, port2; String nguid1, nguid2; Integer portNum1, portNum2; String nodeType1, nodeType2; Integer lid1, lid2; if(writingHeaders){ try { linksBW.write("# Record format: \"nguid1:nguid2:pn1:pn2:ntype1:ntype2:lid1:lid2\""); linksBW.newLine(); linksBW.write("#----Links BEGIN----"); linksBW.newLine(); } catch (Exception e) { System.out.println("ERROR: could not write port counter header."); e.printStackTrace(); System.exit(1); } } for(Map.Entry<String, IB_Link> entry: ibLinks.entrySet()){ IB_Link ln = entry.getValue(); port1 = ln.getEndpoint1(); port2 = ln.getEndpoint2(); nguid1 = port1.getNodeGuid().toColonString().replace(":", ""); nguid2 = port2.getNodeGuid().toColonString().replace(":", ""); portNum1 = port1.getPortNumber(); portNum2 = port2.getPortNumber(); nodeType1 = port1.getNodeType().getAbrevName(); nodeType2 = port2.getNodeType().getAbrevName(); lid1 = port1.getAddress().getLocalId(); lid2 = port2.getAddress().getLocalId(); try{ linksBW.write(nguid1 + ":" + nguid2 + ":" + portNum1 + ":" + portNum2 + ":" + nodeType1 + ":" + nodeType2 + ":" + lid1 + ":" + lid2); linksBW.newLine(); }catch (Exception e){ System.out.println("ERROR: Unable to write links to file."); } } System.out.println("- Wrote links file."); } private static void writeLinksJSON(OSM_Fabric fabric, long timestamp){ OSM_Port port1, port2; String nguid1, nguid2; Integer portNum1, portNum2; String nodeType1, nodeType2, desc1, desc2, conn1, conn2; int lid1, lid2; JSONObject jsonPort1 = null, jsonPort2 = null; LinkedHashMap<String, IB_Link> ibLinks; for(Map.Entry<String, IB_Link> entry: fabric.getIB_Links().entrySet()){ IB_Link ln = entry.getValue(); port1 = ln.getEndpoint1(); port2 = ln.getEndpoint2(); nguid1 = port1.getNodeGuid().toColonString().replace(":", ""); nguid2 = port2.getNodeGuid().toColonString().replace(":", ""); desc1 = fabric.getOSM_Node(port1.getNodeGuid()).sbnNode.description; desc2 = fabric.getOSM_Node(port2.getNodeGuid()).sbnNode.description; portNum1 = port1.getPortNumber(); portNum2 = port2.getPortNumber(); nodeType1 = port1.getNodeType().getAbrevName(); nodeType2 = port2.getNodeType().getAbrevName(); lid1 = port1.getAddress().getLocalId(); lid2 = port2.getAddress().getLocalId(); conn1 = nguid2 + ":" + portNum2; conn2 = nguid1 + ":" + portNum1; try{ jsonPort1 = new JSONObject(); jsonPort1.put("recordType", "link"); jsonPort1.put("ts", timestamp); jsonPort1.put("nguid", nguid1); jsonPort1.put("ndesc", desc1); jsonPort1.put("portNum", portNum1); jsonPort1.put("type", nodeType1); jsonPort1.put("lid", lid1); jsonPort1.put("conn", conn1); jsonPort1.put("speed", port1.getSpeedString()); jsonPort1.put("state", port1.getStateString()); jsonPort1.put("width", port1.getWidthString()); jsonPort1.put("rate", port1.getRateString()); jsonPort1.put("pguid", port1.sbnPort.port_guid); jsonPort2 = new JSONObject(); jsonPort2.put("recordType", "link"); jsonPort2.put("ts", timestamp); jsonPort2.put("nguid", nguid2); jsonPort2.put("ndesc", desc2); jsonPort2.put("portNum", portNum2); jsonPort2.put("type", nodeType2); jsonPort2.put("lid", lid2); jsonPort2.put("conn", conn2); jsonPort2.put("speed", port2.getSpeedString()); jsonPort2.put("state", port2.getStateString()); jsonPort2.put("width", port2.getWidthString()); jsonPort2.put("rate", port2.getRateString()); jsonPort2.put("pguid", port2.sbnPort.port_guid); hbaseDumpBW.write(jsonPort1.toString()); hbaseDumpBW.newLine(); hbaseDumpBW.write(jsonPort2.toString()); hbaseDumpBW.newLine(); }catch (Exception e){ System.out.println("ERROR: Unable to write links to file."); } } System.out.println("- Wrote links file."); } }
Python
UTF-8
1,801
2.875
3
[]
no_license
LINES_FOR_EACH_INPUT = 2 INPUT_FILE_NAME = 'C-small-attempt0.in' OUTPUT_FILE_NAME = 'C-small-attempt0.out' def do_case(input): circ=[0 for i in input] for i in range(len(circ)): circL=1 temp=input[i] while temp-1!=i and circL<len(circ)+1: circL+=1 temp=input[temp-1] circ[i]=circL if circ[i]==len(circ)+1: circ[i]=0 seg=[0 for i in input] for i in range(len(circ)): if circ[i]==2: seg[i]=max(seg[i],1) if circ[i]==0: Seg=1 temp=input[i] while circ[temp-1]==0: Seg+=1 temp=input[temp-1] if circ[temp-1]==2: seg[temp-1]=max(seg[temp-1],Seg+1) return str(max(max(circ),sum(seg))) def do_parse(input): return [int(num) for num in input[1].rstrip().split(" ")] def main(): input_f = open(INPUT_FILE_NAME, 'r') output = [] num_of_test_cases = int(input_f.readline(), 10) input_lines = input_f.readlines() for test_case in range(num_of_test_cases): parsed_input = do_parse(input_lines[test_case*LINES_FOR_EACH_INPUT : (test_case + 1) * LINES_FOR_EACH_INPUT]) output.append('Case #' + str(test_case + 1) + ': ' + do_case(parsed_input)) output_f = open(OUTPUT_FILE_NAME, 'w') output_f.write('\n'.join(output)) input_f.close() output_f.close() if __name__ == '__main__': main()
Python
UTF-8
1,845
3
3
[]
no_license
import logging import json import azure.functions as func def compute_ingredients(weight): return { "Salt": {"unit": "cups", "quantity": 0.05 * weight}, "Water": {"unit": "gallons", "quantity": 0.66 * weight}, "Brown sugar": {"unit": "cups", "quantity": 0.13 * weight}, "Shallots": {"unit": "cups", "quantity": 0.2 * weight}, "Garlic": {"unit": "cloves", "quantity": 0.4 * weight}, "Whole peppercorns": {"unit": "tablespoons", "quantity": 0.13 * weight}, "Dried juniper berries": {"unit": "tablespoons", "quantity": 0.13 * weight}, "Fresh rosemary": {"unit": "tablespoons", "quantity": 0.13 * weight}, "Thyme": {"unit": "tablespoons", "quantity": 0.06 * weight} } def compute_cooking_duration(weight): return { "Brine time (hours)": 2.4 * weight, "Roast time (minutes)": 15 * weight } def compute_recipe(turkey_weight): return { "Ingredients": compute_ingredients(turkey_weight), "Cooking duration": compute_cooking_duration(turkey_weight) } def prettify_recipe(recipe): for ingredient, details in recipe["Ingredients"].items(): details["quantity"] = round(details["quantity"], 2) return recipe def handler(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') weight: int = int(req.params.get('turkeyWeight')) if weight: return func.HttpResponse( json.dumps(prettify_recipe(compute_recipe(weight))), mimetype="application/json") else: return func.HttpResponse( "Please pass the turkey weight on the query string as 'turkeyWeight'", status_code=400 ) if __name__ == "__main__": print(json.dumps(prettify_recipe(compute_recipe(10))))
Java
UTF-8
1,052
2.953125
3
[]
no_license
package com.imooc.io.ch03; import java.io.File; import java.io.IOException; /** * @author luoc * @version V0.0.1 * @package com.imooc.io.ch03 * @description: TODO * @date 2017/11/11 15:50 */ public class IoUtilsTest2 { public static void main(String[] args) { try { long start = System.currentTimeMillis(); // IOUtils.copyFile(new File("F:\\Java\\java面试宝典.pdf"), new File("F:\\Java\\1.pdf"));//运行时间:15ms // IOUtils.copyFileByBuffer(new File("F:\\Java\\java面试宝典.pdf"), new File("F:\\Java\\2.pdf"));//运行时间:2776ms // IOUtils.copyFileByBufferAndP(new File("F:\\Java\\java面试宝典.pdf"), new File("F:\\Java\\3.pdf"));//运行时间:16ms IoUtils.copyFileByByte(new File("F:\\Java\\java面试宝典.pdf"), new File("F:\\Java\\4.pdf"));//运行时间:4181ms long end = System.currentTimeMillis(); System.out.print("运行时间:" + (end - start) + "ms"); } catch (IOException e) { e.printStackTrace(); } } }
Python
UTF-8
9,147
2.671875
3
[]
no_license
from os import system import os.path argPremisses=[] opPremisses=[] valPremisses=[] argFaits=[] valFaits=[] conclusions=[] premisses=[] faits=[] regles=[] f='' def creatListPremissesConclusions (conclusions,premisses,fichier): #Création de la liste des premisses, règles et conclusions filepath = r"regles\{}.txt".format(fichier) del premisses[:] del regles[:] del conclusions[:] premisse=[] with open(filepath) as fp: line = fp.readline() i = 0 while line: if line != "\n": regles.append(line) conclusions.append(line.split(" alors ")[1].split("\n")[0]) premisse.append(line.split(" alors ")[0].split("si ")[1]) premisses.append(premisse[i].split(" et ")) i += 1 line = fp.readline() def splitPremisses (premisses): #Création des listes contenant les arguments, les opérateurs et les valeurs des prémisses l='' temp=[] tempop=[] tempval=[] del argPremisses[:] del opPremisses[:] del tempval[:] del valPremisses[:] for l in premisses: for k in l: temp.append(k.split()[0]) tempop.append(k.split()[1]) tempval.append(k.split()[2]) argPremisses.append(temp) opPremisses.append(tempop) valPremisses.append(tempval) temp=[] tempop=[] tempval=[] def cretListFaits(faits,fichier): #création de la liste des faits filepath = r"faits\{}.txt".format(fichier) del faits[:] with open(filepath) as fp: line = fp.readline() i = 0 while line: faits.append(line.split("\n")[0]) line = fp.readline() i += 1 def splitFaits(faits): #création des liste contenants les arguments et les valeurs des faits l='' del argFaits[:] del valFaits[:] for l in faits: argFaits.append(l.split()[0]) valFaits.append(l.split()[2]) def ecrire(f,chaine): #fonction d'écriture dans le fichier trace f = open(r"trace.txt",'a') f.write(str(chaine)) f.close() def chainageAvant(argPremisses,opPremisses,argFaits,valFaits,conclusions): #chainage avant f = open(r"trace.txt",'w') ecrire(f,"************************\n****Règles utilisées****\n************************\n\n\n") temp=[] tempreg=[] for l in faits: temp.append(l) i=0 truth=False for l in argPremisses: j=0 for k in l: if not (k in argFaits): break truth=False index=argFaits.index(k) if (valFaits[index].isnumeric() and valPremisses[i][j].isnumeric()): if opPremisses[i][j]==">": truth=float(valFaits[index]) > float(valPremisses[i][j]) elif opPremisses[i][j]==">=": truth=float(valFaits[index]) >= float(valPremisses[i][j]) elif opPremisses[i][j]=="<": truth=float(valFaits[index]) < float(valPremisses[i][j]) elif opPremisses[i][j]=="<=": truth=float(valFaits[index]) <= float(valPremisses[i][j]) elif opPremisses[i][j]=="=": truth=float(valFaits[index]) == float(valPremisses[i][j]) elif opPremisses[i][j]=="!=": truth=float(valFaits[index]) != float(valPremisses[i][j]) else: truth=valFaits[index]==valPremisses[i][j] if not (truth): break j+=1 if truth: argFaits.append(conclusions[i].split()[0]) valFaits.append(conclusions[i].split()[2]) if not (conclusions[i] in faits): temp.append(conclusions[i]) if not (regles[i] in tempreg): tempreg.append(regles[i]) i+=1 for l in tempreg: ecrire(f,l) ecrire(f,"\n\n\n**********************\n****Base des faits****\n**********************\n\n\n") ecrire(f,str(temp)) ecrire(f,"\nchainage avant fini") def chainageAvantAvecBut(argPremisses,opPremisses,argFaits,valFaits,conclusions,but): #chainage avant avec but f = open(r"trace.txt",'w') ecrire(f,"************************\n****Règles utilisées****\n************************\n\n\n") trouve=False changement=True while not trouve and changement: changement=False if but in faits: trouve=True break truth=False i=0 for l in argPremisses: j=0 for k in l: if not (k in argFaits): break truth=False index=argFaits.index(k) if (valFaits[index].isnumeric() and valPremisses[i][j].isnumeric()): if opPremisses[i][j]==">": truth=float(valFaits[index]) > float(valPremisses[i][j]) elif opPremisses[i][j]==">=": truth=float(valFaits[index]) >= float(valPremisses[i][j]) elif opPremisses[i][j]=="<": truth=float(valFaits[index]) < float(valPremisses[i][j]) elif opPremisses[i][j]=="<=": truth=float(valFaits[index]) <= float(valPremisses[i][j]) elif opPremisses[i][j]=="=": truth=float(valFaits[index]) == float(valPremisses[i][j]) elif opPremisses[i][j]=="!=": truth=float(valFaits[index]) != float(valPremisses[i][j]) else: truth=valFaits[index]==valPremisses[i][j] if not (truth): break j+=1 if truth and not (conclusions[i] in faits): argFaits.append(conclusions[i].split()[0]) valFaits.append(conclusions[i].split()[2]) faits.append(conclusions[i]) ecrire(f,regles[i]) changement=True i+=1 ecrire(f,"\n\n\n**********************\n****Base des faits****\n**********************\n\n\n") ecrire(f,str(faits)) if trouve: ecrire(f,"\n{} est trouvé".format(but)) else: ecrire(f,"\n\n{} n'est pas trouvé".format(but)) def saturation(argPremisses,opPremisses,argFaits,valFaits,conclusions): #Saturation f = open(r"trace.txt",'w') ecrire(f,"************************\n****Règles utilisées****\n************************\n\n\n") changement=True while changement: truth=False i=0 changement=False for l in argPremisses: j=0 for k in l: if not (k in argFaits): break truth=False index=argFaits.index(k) if (valFaits[index].isnumeric() and valPremisses[i][j].isnumeric()): if opPremisses[i][j]==">": truth=float(valFaits[index]) > float(valPremisses[i][j]) elif opPremisses[i][j]==">=": truth=float(valFaits[index]) >= float(valPremisses[i][j]) elif opPremisses[i][j]=="<": truth=float(valFaits[index]) < float(valPremisses[i][j]) elif opPremisses[i][j]=="<=": truth=float(valFaits[index]) <= float(valPremisses[i][j]) elif opPremisses[i][j]=="=": truth=float(valFaits[index]) == float(valPremisses[i][j]) elif opPremisses[i][j]=="!=": truth=float(valFaits[index]) != float(valPremisses[i][j]) else: truth=valFaits[index]==valPremisses[i][j] if not (truth): break j+=1 if truth and not (conclusions[i] in faits): argFaits.append(conclusions[i].split()[0]) valFaits.append(conclusions[i].split()[2]) faits.append(conclusions[i]) ecrire(f,regles[i]) changement=True i+=1 ecrire(f,"\n\n\n**********************\n****Base des faits****\n**********************\n\n\n") ecrire(f,str(faits)) ecrire(f,"\n\nSaturation finie") #fichier="meteorologies" #creatListPremissesConclusions (conclusions,premisses,fichier) #splitPremisses(premisses) #cretListFaits(faits,fichier) #splitFaits(faits) #print(len(argPremisses),len(opPremisses),len(argFaits),len(valFaits),len(conclusions)) #chainageAvant(argPremisses,opPremisses,argFaits,valFaits,conclusions) #saturation(argPremisses,opPremisses,argFaits,valFaits,conclusions) #but="hdj" #chainageAvantAvecBut(argPremisses,opPremisses,argFaits,valFaits,conclusions,but)
Python
UTF-8
2,105
2.65625
3
[]
no_license
""" ============================ Author:古一 Time:2020/10/28 E-mail:369799130@qq.com ============================ """ import os import allure import requests from jsonpath import jsonpath from loguru import logger from common.handle_path import CONF_DIR from common.utils import Utils class BaseApi: conf_path = os.path.join(CONF_DIR, 'config.yaml') print(conf_path) conf_data = Utils().handle_yaml(conf_path) host = conf_data['env']['host'] headers = conf_data['request_headers']['headers'] account = conf_data['account'] investor_account = conf_data['investor_account'] mysql_conf = conf_data['mysql'] @staticmethod def send_http(data): try: response = requests.request(**data) except Exception as e: logger.error(f'发送请求失败,请求参数为:{data}') logger.exception(f'发生的错误为:{e}') raise e else: return response @staticmethod def get_yaml(file_name): """ 读取yaml文件 :param file_name: 文件路径名称 :return: dict """ return Utils.handle_yaml(file_name) @staticmethod def get_token(response): """ 处理并提取token :param response: :return: """ return Utils.handle_token(response) @staticmethod @allure.step('step:数据替换') def template(source_data: str, data: dict): """ 替换数据 :param source_data: 源数据 :param data: 替换内容,如{data:new_data} :return: """ return Utils.handle_template(source_data, data) @staticmethod def to_two_decimal(data): """ 将整数或浮点数转化为两位数decimal :param data: :return: """ return Utils.handle_decimal(data) @staticmethod def random_phone(): """ 生成随机手机号 :return: """ return Utils.handle_random_phone() if __name__ == '__main__': a = BaseApi() a.template()