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
Go
UTF-8
391
3.34375
3
[ "MIT" ]
permissive
package mathutil import "sort" // Copy copies an array of float64s. func Copy(input []float64) []float64 { output := make([]float64, len(input)) copy(output, input) return output } // SortCopy copies and sorts an array of floats. func SortCopy(input []float64) []float64 { inputCopy := make([]float64, len(input)) copy(inputCopy, input) sort.Float64s(inputCopy) return inputCopy }
Java
UTF-8
3,761
1.773438
2
[ "Apache-2.0", "GPL-1.0-or-later", "CDDL-1.0", "MIT", "LGPL-2.1-or-later" ]
permissive
/* * Copyright (c) 2014 Evolveum * * 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 com.evolveum.midpoint.prism.lex; import static com.evolveum.midpoint.prism.PrismInternalTestUtil.USER_JACK_FILE_BASENAME; import static com.evolveum.midpoint.prism.PrismInternalTestUtil.displayTestTitle; import static org.testng.AssertJUnit.assertEquals; import java.io.IOException; import com.evolveum.midpoint.prism.ParsingContext; import com.evolveum.midpoint.prism.lex.dom.DomLexicalProcessor; import org.testng.annotations.Test; import org.xml.sax.SAXException; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.foo.UserType; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.prism.xnode.ListXNode; import com.evolveum.midpoint.prism.xnode.MapXNode; import com.evolveum.midpoint.prism.xnode.PrimitiveXNode; import com.evolveum.midpoint.prism.xnode.RootXNode; import com.evolveum.midpoint.prism.xnode.XNode; /** * @author semancik * */ public class TestDomParser extends AbstractLexicalProcessorTest { @Override protected String getSubdirName() { return "xml"; } @Override protected String getFilenameSuffix() { return "xml"; } @Override protected DomLexicalProcessor createParser() { return new DomLexicalProcessor(PrismTestUtil.getSchemaRegistry()); } @Test public void testParseUserToXNode() throws Exception { final String TEST_NAME = "testParseUserToXNode"; displayTestTitle(TEST_NAME); // GIVEN DomLexicalProcessor parser = createParser(); // WHEN XNode xnode = parser.read(getFile(USER_JACK_FILE_BASENAME), ParsingContext.createDefault()); // THEN System.out.println("Parsed XNode:"); System.out.println(xnode.debugDump()); RootXNode root = getAssertXNode("root node", xnode, RootXNode.class); MapXNode rootMap = getAssertXNode("root subnode", root.getSubnode(), MapXNode.class); PrimitiveXNode<String> xname = getAssertXMapSubnode("root map", rootMap, UserType.F_NAME, PrimitiveXNode.class); // TODO: assert value ListXNode xass = getAssertXMapSubnode("root map", rootMap, UserType.F_ASSIGNMENT, ListXNode.class); assertEquals("assignment size", 2, xass.size()); // TODO: asserts MapXNode xextension = getAssertXMapSubnode("root map", rootMap, UserType.F_EXTENSION, MapXNode.class); } private void validateSchemaCompliance(String xmlString, PrismContext prismContext) throws SAXException, IOException { // Document xmlDocument = DOMUtil.parseDocument(xmlString); // Schema javaxSchema = prismContext.getSchemaRegistry().getJavaxSchema(); // Validator validator = javaxSchema.newValidator(); // validator.setResourceResolver(prismContext.getEntityResolver()); // validator.validate(new DOMSource(xmlDocument)); } @Override protected void validateUserSchema(String xmlString, PrismContext prismContext) throws SAXException, IOException { validateSchemaCompliance(xmlString, prismContext); } @Override protected void validateResourceSchema(String xmlString, PrismContext prismContext) throws SAXException, IOException { validateSchemaCompliance(xmlString, prismContext); } @Override protected String getWhenItemSerialized() { return "<when>2012-02-24T10:48:52.000Z</when>"; } }
C#
UTF-8
5,017
2.75
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Text; using System.Xml; using Newtonsoft.Json.Linq; namespace WindowsFormsCalculation { class FtpManager { int count = 1; public FtpWebResponse connectServer(string ip, string id, string pw, string method, Action<FtpWebRequest> action = null) { var request = WebRequest.Create(ip) as FtpWebRequest; request.UseBinary = true; request.Method = method; request.Credentials = new NetworkCredential(id, pw); if (action != null) { action(request); } return request.GetResponse() as FtpWebResponse; } public void calculateAutomation(string ip, string id, string pw) { var list = new List<string>(); var result = new List<string>(); using (var res = connectServer(ip + "/raw", id, pw, WebRequestMethods.Ftp.ListDirectory)) { using (var stream = res.GetResponseStream()) { using (var rd = new StreamReader(stream)) { while (true) { string buf = rd.ReadLine(); if (string.IsNullOrWhiteSpace(buf)) { break; } list.Add(buf); } } } } foreach (var fileName in list) { try { string filePath = ip + "/raw/" + fileName; string extension = Path.GetExtension(fileName); string expression = string.Empty; WebClient wc = new WebClient(); wc.Credentials = new NetworkCredential(id, pw); byte[] newFileData = wc.DownloadData(filePath); string fileString = Encoding.UTF8.GetString(newFileData); switch (extension) { case ".txt": { expression = fileString; break; } case ".json": { JObject json = JObject.Parse(fileString); expression = json["expression"].ToString(); break; } case ".xml": { var xml = new XmlDocument() as XmlDocument; xml.LoadXml(fileString); XmlNodeList xmlList = xml.SelectNodes("/expressions/expression"); foreach (XmlNode i in xmlList) { expression = i["exp"].InnerText; } break; } default: { Console.WriteLine("지원하지 않는 형식입니다."); break; } } if (expression == string.Empty || expression == "0") { Console.WriteLine("올바르지 않은 수식입니다."); } else { var cal = new CalManager() as CalManager; string res = cal.start(expression).ToString(); string value = expression + "=" + res; result.Add(value); } } catch (WebException) { Console.WriteLine("접속 오류"); } } foreach (var inputValue in result) { WebClient wc = new WebClient(); wc.Credentials = new NetworkCredential(id, pw); byte[] fileContents = Encoding.UTF8.GetBytes(inputValue); string filePath = ip + "/" + DateTime.Now.ToString("yyMMddhhmmss-") + count.ToString() + ".txt"; string fileName = DateTime.Now.ToString("yyMMddhhmmss-") + count.ToString() + ".txt"; Stream stream = wc.OpenWrite(filePath); stream.Write(fileContents, 0, fileContents.Length); stream.Close(); DBManager dm = new DBManager(); dm.dbConncetor(fileName, inputValue); count++; } Console.WriteLine("complete..."); } } }
Python
UTF-8
3,009
3.0625
3
[ "MIT", "NCSA", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
"""! @brief Pytorch abstract dataset class for inheritance. @author Efthymios Tzinis {etzinis2@illinois.edu} @copyright University of illinois at Urbana Champaign """ from abc import abstractmethod import inspect class Dataset: @abstractmethod def get_arg_and_check_validness(self, key, choices=None, dict_check=None, known_type=None, extra_lambda_checks=None): try: value = self.kwargs[key] except Exception as e: print(e) raise KeyError("Argument: <{}> does not exist in pytorch " "dataloader keyword arguments".format(key)) if dict_check is not None: try: for k, v in value.items(): assert isinstance(v, dict_check[k]), ( 'Value: {} is not an instance of: {}'.format( v, dict_check[k])) except Exception as e: print(e) raise ValueError('Expected to find a dict of format: {}' ' but got: {}'.format(dict_check, value)) return value if known_type is not None: if not isinstance(value, known_type): raise TypeError("Value: <{}> for key: <{}> is not an " "instance of " "the known selected type: <{}>" "".format(value, key, known_type)) if choices is not None: if isinstance(value, list): if not all([v in choices for v in value]): raise ValueError("Values: <{}> for key: <{}> " "contain elements in a" "regime of non appropriate " "choices instead of: <{}>" "".format(value, key, choices)) else: if value not in choices: raise ValueError("Value: <{}> for key: <{}> is " "not in the " "regime of the appropriate " "choices: <{}>" "".format(value, key, choices)) if extra_lambda_checks is not None: all_checks_passed = all([f(value) for f in extra_lambda_checks]) if not all_checks_passed: raise ValueError( "Value(s): <{}> for key: <{}> " "does/do not fulfill the predefined checks: " "<{}>".format(value, key, [inspect.getsourcelines(c)[0][0].strip() for c in extra_lambda_checks if not c(value)])) return value
TypeScript
UTF-8
1,524
2.5625
3
[]
no_license
import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { HeroModel } from '../models/hero.model'; import { map } from 'rxjs/operators'; @Injectable({ providedIn: 'root' }) export class HeroesService { private mainURL = 'https://roco-8b1a4.firebaseio.com'; constructor(private http: HttpClient) { } createHero(hero: HeroModel) { return this.http.post(`${this.mainURL}/heroes.json`, hero) .pipe( map((resp: any) => { console.log(resp); hero.id = resp.name; return hero; }) ); } updateHero(hero: HeroModel) { const tempHero = { ...hero }; delete tempHero.id; return this.http.put(`${this.mainURL}/heroes/${hero.id}.json`, tempHero); } getHeroes() { return this.http.get(`${this.mainURL}/heroes.json`) .pipe( map(this.createHeroArray) // esto envia el resultado del map como el primer argumento para el metodo createHeroArray. ); } deleteHero(id: string) { return this.http.delete(`${this.mainURL}/heroes/${id}.json`); } getHeroById(id: string) { return this.http.get(`${this.mainURL}/heroes/${id}.json`); } private createHeroArray(heroeObj: object) { const heroes: HeroModel[] = []; if (heroeObj === null) { return []; } Object.keys(heroeObj).forEach(key => { const hero: HeroModel = heroeObj[key]; hero.id = key; // este key es el id que crea firebase. heroes.push(hero); }); return heroes; } }
C#
UTF-8
847
3.265625
3
[]
no_license
using System; namespace TrialConsoleAppWithGit { class Program { static void Main(string[] args) { Console.WriteLine("Hi My Name is Shanice"); Console.WriteLine("I am here to help"); Console.WriteLine("What is your name?"); var usersName = Console.ReadLine(); Console.WriteLine($"Hi {usersName}, how may i help today."); Console.WriteLine($"Today is a sunny day and todays date is {DateTime.Now}"); Console.WriteLine("Do you like ice cream, i can search for where to get the best ice cream around you"); Console.WriteLine("Do you like swimming, i can search for places around you"); Console.WriteLine("cornwall is a nice place"); Console.WriteLine("cornwall is a nice place"); } } }
Java
UTF-8
1,618
1.921875
2
[ "MIT" ]
permissive
package net.minecraft.util.datafix.fixes; import com.mojang.datafixers.DSL; import com.mojang.datafixers.DataFix; import com.mojang.datafixers.TypeRewriteRule; import com.mojang.datafixers.schemas.Schema; import com.mojang.datafixers.util.Pair; import java.util.stream.Collectors; import net.minecraft.util.datafix.TypeReferences; public class KeyOptionsTranslation extends DataFix { public KeyOptionsTranslation(Schema outputSchema, boolean changesType) { super(outputSchema, changesType); } public TypeRewriteRule makeRule() { return this.fixTypeEverywhereTyped("OptionsKeyTranslationFix", this.getInputSchema().getType(TypeReferences.OPTIONS), (p_209667_0_) -> { return p_209667_0_.update(DSL.remainderFinder(), (p_209668_0_) -> { return p_209668_0_.getMapValues().<com.mojang.serialization.Dynamic<?>>map((p_209669_1_) -> { return p_209668_0_.createMap(p_209669_1_.entrySet().stream().map((p_209666_1_) -> { if (p_209666_1_.getKey().asString("").startsWith("key_")) { String s = p_209666_1_.getValue().asString(""); if (!s.startsWith("key.mouse") && !s.startsWith("scancode.")) { return Pair.of(p_209666_1_.getKey(), p_209668_0_.createString("key.keyboard." + s.substring("key.".length()))); } } return Pair.of(p_209666_1_.getKey(), p_209666_1_.getValue()); }).collect(Collectors.toMap(Pair::getFirst, Pair::getSecond))); }).result().orElse(p_209668_0_); }); }); } }
Java
UTF-8
360
2.140625
2
[]
no_license
package schmoller.unifier.mods.mekanism; import mekanism.common.RecipeHandler.Recipe; import schmoller.unifier.Mappings; public class CombinerProcessor extends MekanismBaseProcessor { @Override public String getName() { return "Combiner"; } @Override public int applyMappings( Mappings mappings ) { return apply(mappings, Recipe.COMBINER); } }
SQL
UTF-8
1,500
2.921875
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.8.4 -- https://www.phpmyadmin.net/ -- -- Host: 127.0.0.1:3306 -- Generation Time: Mar 17, 2019 at 08:18 AM -- Server version: 5.7.24 -- PHP Version: 7.2.14 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `empportal` -- CREATE DATABASE IF NOT EXISTS `empportal` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci; USE `empportal`; -- -------------------------------------------------------- -- -- Table structure for table `stdreg` -- DROP TABLE IF EXISTS `stdreg`; CREATE TABLE IF NOT EXISTS `stdreg` ( `sno` int(11) NOT NULL AUTO_INCREMENT, `emailid` varchar(100) NOT NULL, `name` varchar(50) NOT NULL, `pswd` varchar(20) NOT NULL, PRIMARY KEY (`sno`) USING BTREE ) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; -- -- Dumping data for table `stdreg` -- INSERT INTO `stdreg` (`sno`, `emailid`, `name`, `pswd`) VALUES (1, 'abc', 'sad@gmail.com', '1234'), (2, 'sad', '52', 'asd'), (3, 'sad', 'ani', 'asd'), (5, 'sad', 'ani', 'asd'); COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Markdown
UTF-8
908
2.5625
3
[ "MIT" ]
permissive
## Example Application ## This is a simple example application demonstration how ASP.NET Core, Angular 2, TypeScript and WebPack (to name just these four) work together. ### Before the first launch ### Before launching the application for the first time after cloning the repository make sure to rebuild the vendor scripts and install the typings. If you have not installed WebPack yet make sure to install it by opening a command prompt and running npm install -g webpack If you have not installed typings yet make sure to install it by opening a command prompt and running npm install -g typings After you have done this run webpack --config webpack.config.vendor.js in a command prompt located at the Zuehlke.ExpenseReporting folder. You need to repeat this step if you want to add another third party library to the project. See [bit.ly/aspnetcoretp](http://bit.ly/aspnetcoretp) for details.
Markdown
UTF-8
3,072
2.765625
3
[ "MIT" ]
permissive
# Convergence Input Element Bindings [![Build](https://github.com/convergencelabs/input-element-bindings/actions/workflows/build.yml/badge.svg)](https://github.com/convergencelabs/input-element-bindings/actions/workflows/build.yml) This module provides a set of utilities to bind plain HTML Input / Form Elements to a Convergence model. The module provides simple two way data binding between the HTML input element and a particular field in the Convergence data model. The module currently supports the following input elements: * **Text Input Fields** * &lt;input type="text" /&gt; * &lt;input type="password" /&gt; * &lt;input type="email" /&gt; * &lt;input type="url" /&gt; * &lt;input type="search" /&gt; * &lt;textarea /&gt; - **Radio Buttons** - &lt;input type="radio" /&gt; - **Select Elements** - &lt;select /&gt; - &lt;select multiple /&gt; - **Color Selector** - &lt;input type="color" /&gt; - **Number Fields** - &lt;input type="number" /&gt; - &lt;input type="range" /&gt; You can [see it in action here](https://examples.convergence.io/input-elements/index.html). ## Installation ```npm install @convergence/input-element-bindings``` ## Example Usage ```html <html> <head> <script src="https://cdn.jsdelivr.net/npm/rxjs@6.6.2/bundles/rxjs.umd.js"></script> <script src="https://cdn.jsdelivr.net/npm/@convergence/convergence/convergence.global.js"></script> <script src="https://cdn.jsdelivr.net/npm/@convergence/string-change-detector/browser/string-change-detector.js"></script> <script src="https://cdn.jsdelivr.net/npm/@convergence/input-element-bindings@0.5.0/dist/umd/convergence-input-element-bindings.min.js"></script> </head> <body> <input type="text" id="textInput" disabled="disabled"/> <script> const DOMAIN_URL = "http://localhost:8000/realtime/domain/convergence/default"; Convergence.connectAnonymously(DOMAIN_URL) .then((domain) => { return domain.models().openAutoCreate({ collection: "input-binder", id: "example", data: () => { return {textInput: "Text to collaborate on"}; } }); }) .then((model) => { const textInput = document.getElementById("textInput"); textInput.disabled = false; const realTimeString = model.elementAt("textInput"); ConvergenceInputElementBinder.bindTextInput(textInput, realTimeString); }) .catch((error) => { console.error(error); }); </script> </body> </html> ``` You can find a working example in the [example](example) directory. ## API ```javascript function bindTextInput(textInput, stringElement) function bindNumberInput(numberInput, numberElement) function bindCheckboxInput(checkboxInput, booleanElement) function bindRangeInput(rangeInput, numberElement) function bindColorInput(colorInput, stringElement) function bindSingleSelect(selectInput, stringElement) function bindMultiSelect(selectInput, arrayElement) function bindRadioInputs(radioInputs, stringElement) ```
Java
UTF-8
10,344
1.976563
2
[]
no_license
package com.bw.movie.model; import com.bawei.mymovie.R; import com.bw.movie.api.DetailsApiServise; import com.bw.movie.api.MyApiServise; import com.bw.movie.contract.MyContract; import com.bw.movie.model.entity.UserFollowCinemaEntity; import com.bw.movie.model.entity.UserFollowMovieEntity; import com.bw.movie.model.entity.dengluEntity.RegEntity; import com.bw.movie.model.entity.myEntity.AllSysMshEntity; import com.bw.movie.model.entity.myEntity.MyCinemaCommentEntity; import com.bw.movie.model.entity.myEntity.MyMovieCommentEntity; import com.bw.movie.model.entity.myEntity.MyxinxiEntity; import com.bw.movie.model.entity.myEntity.UserReserveEntity; import com.bw.movie.util.NetUtils; import io.reactivex.Observer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; /** * data:2020/4/10 * author:王江伟(DJ慢羊羊) * function: */ public class MyModel implements MyContract.IModel { @Override public void getUserFollowMovieData(int userId, String sessionId, int page, int count, MyModelCallback myModelCallback) { NetUtils.getInstance().getClear(DetailsApiServise.class) .userfollowMovie(userId,sessionId,page,count) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<UserFollowMovieEntity>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(UserFollowMovieEntity userFollowMovieEntity) { myModelCallback.userfollowMovieSuccess(userFollowMovieEntity); } @Override public void onError(Throwable e) { myModelCallback.userfollowMovieError(e); } @Override public void onComplete() { } }); } @Override public void getUserFollowCinemaData(int userId, String sessionId, int page, int count, MyModelCallback myModelCallback) { NetUtils.getInstance().getClear(DetailsApiServise.class) .userfollowCinema(userId,sessionId,page,count) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<UserFollowCinemaEntity>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(UserFollowCinemaEntity userFollowCinemaEntity) { myModelCallback.userfollowCinemaSuccess(userFollowCinemaEntity); } @Override public void onError(Throwable e) { myModelCallback.userfollowCinemaError(e); } @Override public void onComplete() { } }); } @Override public void getUserReserveData(int userId, String sessionId, MyModelCallback myModelCallback) { NetUtils.getInstance().getClear(MyApiServise.class) .UserReserve(userId,sessionId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<UserReserveEntity>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(UserReserveEntity userReserveEntity) { myModelCallback.UserReserveSuccess(userReserveEntity); } @Override public void onError(Throwable e) { myModelCallback.UserReserveError(e); } @Override public void onComplete() { } }); } @Override public void getMyMovieCommentData(int userId, String sessionId, int page, int count, MyModelCallback myModelCallback) { NetUtils.getInstance().getClear(MyApiServise.class) .MyMovieComment(userId,sessionId,page,count) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<MyMovieCommentEntity>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(MyMovieCommentEntity myMovieCommentEntity) { myModelCallback.MyMovieCommentSuccess(myMovieCommentEntity); } @Override public void onError(Throwable e) { myModelCallback.MyMovieCommentError(e); } @Override public void onComplete() { } }); } @Override public void getMyCinemaCommentData(int userId, String sessionId, String longitude, String latitude, int page, int count, MyModelCallback myModelCallback) { NetUtils.getInstance().getClear(MyApiServise.class) .MyCinemaComment(userId,sessionId,longitude,latitude,page,count) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<MyCinemaCommentEntity>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(MyCinemaCommentEntity myCinemaCommentEntity) { myModelCallback.MyCinemaCommentSuccess(myCinemaCommentEntity); } @Override public void onError(Throwable e) { myModelCallback.MyCinemaCommentError(e); } @Override public void onComplete() { } }); } @Override public void getfeedBackData(int userId, String sessionId, String content, MyModelCallback myModelCallback) { NetUtils.getInstance().getClear(MyApiServise.class) .feedBack(userId,sessionId,content) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<RegEntity>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(RegEntity regEntity) { myModelCallback.feedBackSuccess(regEntity); } @Override public void onError(Throwable e) { myModelCallback.feedBackError(e); } @Override public void onComplete() { } }); } @Override public void getallSysMsgData(int userId, String sessionId, int page, int count, MyModelCallback myModelCallback) { NetUtils.getInstance().getClear(MyApiServise.class) .allSysMsg(userId,sessionId,page,count) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<AllSysMshEntity>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(AllSysMshEntity allSysMshEntity) { myModelCallback.allSysMsgSuccess(allSysMshEntity); } @Override public void onError(Throwable e) { myModelCallback.allSysMsgError(e); } @Override public void onComplete() { } }); } @Override public void getchangeSysMsgData(int userId, String sessionId, int id, MyModelCallback myModelCallback) { NetUtils.getInstance().getClear(MyApiServise.class) .changeSysMsg(userId,sessionId,id) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<RegEntity>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(RegEntity regEntity) { myModelCallback.changeSysMsgSuccess(regEntity); } @Override public void onError(Throwable e) { myModelCallback.changeSysMsgError(e); } @Override public void onComplete() { } }); } @Override public void getUserInfoData(int userId, String sessionId, MyModelCallback myModelCallback) { NetUtils.getInstance().getClear(MyApiServise.class) .UserInfo(userId,sessionId) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<MyxinxiEntity>() { @Override public void onSubscribe(Disposable d) { } @Override public void onNext(MyxinxiEntity myxinxiEntity) { myModelCallback.UserInfoSuccess(myxinxiEntity); } @Override public void onError(Throwable e) { myModelCallback.UserInfoError(e); } @Override public void onComplete() { } }); } }
C
GB18030
1,678
2.96875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <libxml/parser.h> #include <libxml/tree.h> int main (int argc , char **argv) { xmlDocPtr pdoc = NULL; xmlNodePtr proot = NULL, pcur = NULL; /*****************xmlĵ********************/ xmlKeepBlanksDefault(0);//ϣֹԪǰĿհıŵһnode pdoc = xmlReadFile ("test.xml", "UTF-8", XML_PARSE_RECOVER);//libxmlֻܽUTF-8ʽ if (pdoc == NULL) { printf ("error:can't open file!\n"); exit (1); } /*****************ȡxmlĵĸڶ********************/ proot = xmlDocGetRootElement (pdoc); if (proot == NULL) { printf("error: file is empty!\n"); exit (1); } /*****************鼮********************/ pcur = proot->xmlChildrenNode; while (pcur != NULL) { //ͬ׼CеcharһxmlCharҲж̬ڴ䣬ַ غxmlMallocǶ̬ڴĺxmlFree׵ͷڴ溯xmlStrcmpַȽϺȡ //char* ch="book", xmlChar* xch=BAD_CAST(ch)xmlChar* xch=(const xmlChar *)(ch) //xmlChar* xch=BAD_CAST("book")char* ch=(char *)(xch) if (!xmlStrcmp(pcur->name, BAD_CAST("book"))) { xmlNodePtr nptr=pcur->xmlChildrenNode; while (pcur != NULL) { if (!xmlStrcmp(nptr->name, BAD_CAST("title"))) { printf("title: %s\n",((char*)XML_GET_CONTENT(nptr->xmlChildrenNode))); break; } } } pcur = pcur->next; } /*****************ͷԴ********************/ xmlFreeDoc (pdoc); xmlCleanupParser (); xmlMemoryDump (); return 0; }
C++
UHC
676
3.109375
3
[]
no_license
/* 2016.8.22 BaekJoon Online Judge Problem Solving Seong Joon Seo (ID: jjunCoder) Problem #1065 Ѽ ( X ڸ ̷ٸ Ѽ Ѵ.) */ #include <iostream> using namespace std; bool isHanSu(int n) { if (n < 100) return true; if (n == 1000) return false; int n1, n2, n3; n1 = n % 10; n /= 10; n2 = n % 10; n /= 10; n3 = n % 10; n /= 10; if (n1 - n2 != n2 - n3) return false; else return true; } void theNumofHanSu(int n) { int count = 0; for (int i = 1; i <= n; i++) { if (isHanSu(i)) count++; } cout << count; } int main() { int n; cin >> n; theNumofHanSu(n); return 0; }
Java
UTF-8
1,619
2.65625
3
[]
no_license
package bombercraft.game.entity.wall; import java.awt.Graphics2D; import bombercraft.game.GameAble; import bombercraft.game.entity.Entity; import bombercraft.game.level.Block; import utils.math.GVector2f; public abstract class Wall extends Entity{ public Wall(GVector2f position, GameAble parent) { super(position, parent); } public abstract void renderWalls(Graphics2D g2); protected int getType(){ boolean[] n = new boolean[]{ getParent().hasWall(getPosition().getXi(), getPosition().getYi() - Block.SIZE.getY()), getParent().hasWall(getPosition().getXi() + Block.SIZE.getX(), getPosition().getYi()), getParent().hasWall(getPosition().getXi(), getPosition().getYi() + Block.SIZE.getY()), getParent().hasWall(getPosition().getXi() - Block.SIZE.getX(), getPosition().getYi()) }; //0 int i = 0; //4 if(n[0] && n[1] && n[2] && n[3]) i = 15; //1 if(n[0] && !n[1] && !n[2] && !n[3]) i = 1; if(!n[0] && !n[1] && !n[2] && n[3]) i = 2; if(!n[0] && !n[1] && n[2] && !n[3]) i = 3; if(!n[0] && n[1] && !n[2] && !n[3]) i = 4; //2 if(n[0] && !n[1] && !n[2] && n[3]) i = 5; if(n[0] && n[1] && !n[2] && !n[3]) i = 6; if(!n[0] && n[1] && n[2] && !n[3]) i = 7; if(!n[0] && !n[1] && n[2] && n[3]) i = 8; if(n[0] && !n[1] && n[2] && !n[3]) i = 13; if(!n[0] && n[1] && !n[2] && n[3]) i = 14; //3 if(!n[0] && n[1] && n[2] && n[3]) i = 10; if(n[0] && n[1] && n[2] && !n[3]) i = 12; if(n[0] && n[1] && !n[2] && n[3]) i = 9; if(n[0] && !n[1] && n[2] && n[3]) i = 11; return i; } }
Python
UTF-8
765
2.703125
3
[]
no_license
import PySimpleGUI as sg from PIL import Image, ImageTk, ImageSequence from PySimpleGUI.PySimpleGUI import TITLEBAR_MINIMIZE_KEY, Titlebar, popup_animated sg.theme('DarkAmber') gif_filename = r'shapeB.gif' layout = [[ [sg.Image(filename=gif_filename, enable_events=True, key="-IMAGE-")], ]] # Create the Window window = sg.Window('STELLA', layout, finalize=True) # Event Loop to process "events" and get the "values" of the inputs while True: for frame in ImageSequence.Iterator(Image.open(gif_filename)): event, values = window.read(timeout=65) window['-IMAGE-'].update(data=ImageTk.PhotoImage(frame) ) if event == sg.WIN_CLOSED : # if user closes window or clicks cancel break window.close()
Markdown
UTF-8
1,540
3.21875
3
[]
no_license
# How to start a process from a JavaScript action var processInstanceId = **startActivitiProcess** (processId, obj); * processId: process id This value can be retrieved from the list of the processes or from the Web Modeler. Example: in the "Execution process list" you can see all the processes. To be more precise, all the versions for all the processes, where a specific process version is expressed as:\ SIN\<YOUR_COMPANY\_ID>\_YOUR\_COMPANY\_ID>_\<YOUR_PROCESS\_ID>:\<VERSION>:\<INTERNAL\_ID>_\ _The processId to specify must NOT include version and internal id, so it must be something like:_\ _SIN\<YOUR\_COMPANY\_ID>\_YOUR\_COMPANY\_ID>_\<YOUR\_PROCESS\_ID> * obj: Javascript object containing variables declared in the start event and required in order to start the process. More precisely, if you have defined variables like MY\_EMAIL\_ADDRESS and MY\_NAME, then the javascript object should contain something like:\ { myEmailAddress: “…”, myName: “…” }\ that is to say, variable names must be expressed in "camel-case". Note: the **start** variable is a boolean value representing the outcome of the process start. ## Example ```javascript var obj = { requestDate: new Date(), docId: vo.documentId, requestId: vo.requestId, initiator: vo.requestUserId }; var processInstanceId = null; try { processInstanceId = startActivitiProcess("PROCESS_ID",obj); } catch(e) { // in case of failure when attempting to start a process, an exception is fired here: e.toString() contains the error message } ```
Java
UTF-8
1,917
4.0625
4
[]
no_license
package leetcode; import java.util.HashMap; import java.util.HashSet; import java.util.Set; /** * 给定一个字符串,找到最长不含有重复字符的子字符串 */ class LongestSubstring { public static void main(String[] args) { // String str = "abc"; // String str = "abcabcbb"; // String str = "cdd"; String str = "abba"; System.out.println(test(str)); } /** * 解题分析: * 1、滑动窗口。 * 其实就是一个队列,比如abcbcba,进入这个队列(窗口)为 abc 满足题目要求,当再进入 b,队列变成了 abcb,这时不满足要求。所以,我们要移动这个队列。 * 移动队列方法:将队列中第一次出现b及b之前的所有元素移除 */ public static int test(String str) { Set<Character> set = new HashSet<>(); int len = str.length(); if (len <= 1) { return len; } int max = 0; int left = 0; for (int i = 0; i < len; i++) { char c = str.charAt(i); while (set.contains(c)) { // 记录最近出现的重复元素的下标+1。并删除当前重复元素及之前的所有元素 set.remove(str.charAt(left++)); } set.add(c); max = Math.max(max, set.size()); } return max; } /** * 解题分析: */ public static int test2(String str) { HashMap<Character, Integer> map = new HashMap<>(); int len = str.length(); if (len <= 1) { return len; } int max = 0; int left = 0; for (int i = 0; i < len; i++) { char c = str.charAt(i); if (map.containsKey(c)) { // 记录最近出现的重复元素的下标+1 // 这里使用Math.max,是为了防止当前重复元素的下标比现有重复元素小的情况。比如abba left = Math.max(left, map.get(c) + 1); } map.put(c, i); // 计算两个下标间子字符串长度时,是没有算边界的,所以这里的+1 max = Math.max(max, i - left + 1); } return max; } }
PHP
UTF-8
831
2.796875
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Trevor * Date: 2019/5/30 * Time: 19:13 */ namespace lib; /** * Class App * @package lib */ class App { /** * 应用运行入口 */ static public function run() { $version='v1'; $action='Index'; if (isset($_SERVER['REQUEST_URI'])){ $uri=preg_split('/\//',$_SERVER['REQUEST_URI']); if($_SERVER['REQUEST_URI']!='/' && count($uri)>=3){ $version=$uri[1]; $arr=preg_split('/\?/',$uri[2]); $action=ucfirst($arr[0]); } } try{ $class="\\api\\".$version."\\".$action; $object=new $class(); $object->exe(); }catch (\Exception $e){ print_r($e->getMessage(),$e->getCode()); } } }
Swift
UTF-8
3,897
2.640625
3
[]
no_license
// // APIYahoo.swift // hiragana // // Created by Pongrapee Attasaranya on 2020/02/11. // Copyright © 2020 Majorl3oat. All rights reserved. // import Foundation class APIYahoo: NSObject, XMLParserDelegate { // MARK: - Declaration struct API { private init() {} static let baseURL = "https://jlp.yahooapis.jp/FuriganaService/V1/furigana" static let method = "POST" static let contentType = "application/x-www-form-urlencoded" static let userAgent = "Yahoo AppID: " + kAPIYahooAppID } var elementName: String = String() var responseStr: String = String() var shouldParse: Bool = true var isError: Bool = false let exceptions: [String] = ["。", "、", "*", "?", "!", "(", ")", "「", "」", "…"] static let shared = APIYahoo() var delegate: HttpRequestDelegate? // MARK: - Main Functions private override init() {} func sendRequest(sentence: String?, delegate: HttpRequestDelegate?) { // Config let url = URL(string: API.baseURL) guard let requestUrl = url else { print("Invalid URL") return } self.delegate = delegate // Prepare Request Object var request = URLRequest(url: requestUrl) request.httpMethod = API.method request.setValue(API.contentType, forHTTPHeaderField: "Content-Type") request.setValue(API.userAgent, forHTTPHeaderField: "User-Agent") // Set request body guard let query = sentence else { return } let param = "sentence=\(query)" request.httpBody = param.data(using: String.Encoding.utf8) // Send request let task = URLSession.shared.dataTask(with: request) { (data, response, error) in if let error = error { print("URLSession Error: \(error)") return } guard let data = data else { return } // Parse XML Response let parser = XMLParser(data: data) parser.delegate = self parser.parse() } task.resume() } // MARK: - XMLParserDelegate func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { self.elementName = elementName if (elementName == "Word") { self.shouldParse = true } else if (elementName == "SubWordList") { // To skip <SubWordList> self.shouldParse = false } else if (elementName == "Error") { self.isError = true } } func parser(_ parser: XMLParser, foundCharacters string: String) { let str = string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) if (!self.shouldParse) { return } if (self.elementName == "Furigana") { responseStr += str } else if (self.elementName == "Surface") { let pattern = "[a-zA-Z0-9]+" if (self.exceptions.contains(str) || (str.range(of: pattern, options:.regularExpression) != nil)) { responseStr += str } } else if (self.elementName == "Message") { responseStr += str } } func parser(_ parser: XMLParser, foundCDATA CDATABlock: Data) { guard let str = String(data: CDATABlock, encoding: .utf8) else { return } responseStr += str } func parserDidEndDocument(_ parser: XMLParser) { if (isError) { self.delegate?.didFailConvert(error: responseStr) } else { self.delegate?.didFinishConvert(output: responseStr) } responseStr = "" } }
Markdown
UTF-8
1,500
2.8125
3
[]
no_license
3613点威力尽显 ==== **今天的走势极端技术化,前面已经明确说了,只要站不住3613点,就要再次探底。今天低开后,在60分钟刚好跌破顶分型的下边,早上那标准的回抽,极端显然地上不了3613点,因此确认这对顶分型下边的跌破是有效的,因此后面的下跌就顺理成章了,为什么?因为向下要形成笔。** ** ** **现在的走势很显然了,向上的笔后形成向下笔的调整,也就力度最大那种调整,因此,后面在向下笔结束前,都不适宜再度介入。但一旦向下笔结束,就又有一次美妙的短差机会。** ** ** **各位,看到没有,就用一个简单的60分钟分型结构是否延伸为笔,我们就能完全把握这样的走势与相应的退出,现在,我们只需要等待新的买点出现,如此简单而已。** ** ** **个股方面,昨天已经明确说了,只要地产不能重新启动,就有问题,今天万科等的走势,一个标准的短线多头陷阱,因此,引发回跌再正常不过了。** ** ** **当然,就算有真行情,也需要大的洗盘,但是否洗盘还是继续下跌,其实根本不重要,我们只关心下一个买点,把走势支解了进行操作,我们不废那个脑子。** ** ** **让脑子有水的人继续争论是否有真的行情,他们负责争论,我们负责挣钱,还有精力的,今晚继续加班看球。** ** ** **先下,再见。**
Java
UTF-8
4,835
2.15625
2
[ "Apache-2.0" ]
permissive
package github.hemandroid.checkifscreenlocked; import android.app.KeyguardManager; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.media.Ringtone; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button btn_check; private KeyguardManager mKeyguardManager; private Uri mUri; private Ringtone mRingtone; private Intent mIntent; private String str_action; private static final String LOGTAG = "CheckIfScreenLocked"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); // mUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); // mRingtone = RingtoneManager.getRingtone(getApplicationContext(), mUri); // // mIntent = new Intent(); // if( mKeyguardManager.inKeyguardRestrictedInputMode()) { // try { // mUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); // mRingtone = RingtoneManager.getRingtone(getApplicationContext(), mUri); // mRingtone.play(); // } catch (Exception e) { // e.printStackTrace(); // } // } else { // mUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); // mRingtone = RingtoneManager.getRingtone(getApplicationContext(), mUri); // if (mRingtone.isPlaying()){ // mRingtone.stop(); // } // } checkScreenLockState(); // btn_check = findViewById(R.id.btn_check); // btn_check.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View v) { // try { // Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); // Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification); // r.play(); // } catch (Exception e) { // e.printStackTrace(); // } // } // }); } private void checkScreenLockState() { final IntentFilter i_filter = new IntentFilter(); /** System Defined Broadcast Actions */ i_filter.addAction(Intent.ACTION_SCREEN_ON); i_filter.addAction(Intent.ACTION_SCREEN_OFF); i_filter.addAction(Intent.ACTION_USER_PRESENT); BroadcastReceiver screenStateReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String strAction = intent.getAction(); KeyguardManager kgMgr = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); if (strAction.equals(Intent.ACTION_SCREEN_OFF)) { Log.d(LOGTAG, "Screen Off"); } else if (strAction.equals(Intent.ACTION_SCREEN_ON)) { Log.d(LOGTAG, "Screen On"); } if (strAction.equals(Intent.ACTION_USER_PRESENT) && !kgMgr.inKeyguardRestrictedInputMode()) { Log.d(LOGTAG, "Device UNLOCKED"); } else { Log.d(LOGTAG, "Device LOCKED"); } } }; getApplicationContext().registerReceiver(screenStateReceiver, i_filter); } // @Override // protected void onResume() { // super.onResume(); // mKeyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); // str_action = mIntent.getAction(); // if (str_action.equals(Intent.ACTION_SCREEN_ON)){ // mUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); // mRingtone = RingtoneManager.getRingtone(getApplicationContext(), mUri); // if (mRingtone.isPlaying()){ // mRingtone.stop(); // } // } // } // // @Override // protected void onStop() { // super.onStop(); // str_action = mIntent.getAction(); // if (str_action.equals(Intent.ACTION_SCREEN_OFF)){ // try { // mUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM); // mRingtone = RingtoneManager.getRingtone(getApplicationContext(), mUri); // mRingtone.play(); // } catch (Exception e) { // e.printStackTrace(); // } // } // } }
JavaScript
UTF-8
1,434
2.59375
3
[]
no_license
const jsdom = require("jsdom"); const { JSDOM } = jsdom; const dom = new JSDOM(`<!DOCTYPE html><p>Hello world</p>`); window = dom.window; document = window.document; XMLHttpRequest = window.XMLHttpRequest; var _0x5490 = ["length", " ", "offsecphun1.gif", "offsecphun2.png", "getSeconds", "floor", "<img src=\'", "\'>", "write", "offsecphun5.bmp", "d6467e109c1606ed29", "-", "1f2e73705207bd", "21213/"]; var sillydate = 0; var sillyvar = 0; function StringArray(_0x5b7ex4) { this[_0x5490[0]] = _0x5b7ex4; for (var _0x5b7ex5 = 1; _0x5b7ex5 <= _0x5b7ex4; _0x5b7ex5++) { this[_0x5b7ex5] = _0x5490[1]; }; }; image = new StringArray(10); image[0] = _0x5490[2]; image[1] = _0x5490[3]; image[2] = _0x5490[2]; image[3] = _0x5490[3]; image[4] = _0x5490[2]; image[5] = _0x5490[3]; image[6] = _0x5490[2]; image[7] = _0x5490[3]; image[8] = _0x5490[3]; image[9] = _0x5490[3]; var ran = 60 / image[_0x5490[0]]; function _0x5491() { sillydate = new Date(); sillyvar = sillydate[_0x5490[4]](); sillyvar = Math[_0x5490[5]](sillyvar / ran); return (image[sillyvar]); }; function _0x5499(_0x4499) { var hmmmm = document.createElement("img"); hmmmm.src = "/" + _0x4499; document.body.appendChild(hmmmm); } //_0x5499(_0x5490[12]+_0x5490[10]+_0x5490[11]+_0x5490[13]+_0x5491()); document[_0x5490[8]](_0x5490[6] + _0x5491() + _0x5490[7]); console.log(_0x5490[12]+_0x5490[10]+_0x5490[11]+_0x5490[13]+_0x5491())
C++
UTF-8
3,044
3.296875
3
[]
no_license
// // main.cpp // rank_simple // // Created by Sean Yang on 2019/2/27. // Copyright © 2019 Sean Yang. All rights reserved. // #include <iostream> #include <ctime> #include <cstdlib> using namespace std; #define LENGTH 20 int *getMergeArray(int arr1[],int arr2[],int max_length_array_a,int max_length_array_b); int main(int argc, const char * argv[]) { srand((unsigned)time(NULL)); int num[LENGTH]; int rand_num; //生成随机数 for(int i=0;i<LENGTH;i++){ rand_num=rand()%100+1; num[i]=rand_num; } cout<<"排序前:"<<endl; // for(int i=0;i<LENGTH;i++){ // cout<<num[i]<<endl; // } cout<<"排序后:"<<endl; //MERGE SORT // for(int i;i<LENGTH;i++){ // // } int a[]={1,50,90}; int max_length_array_a=sizeof(a)/4; int b[]={2,10,20}; int max_length_array_b=sizeof(b)/4; int *c; c=getMergeArray(a,b,max_length_array_a,max_length_array_b); // cout<<*c<<endl; for(int i=0;i<max_length_array_a+max_length_array_b;i++){ cout<<*(c+i)<<endl; } //插入排序 for双嵌套 // for(int i=1;i<LENGTH;i++){ // int num1; // num1=num[i]; // for(int j=i-1;j>=0;j--){ // if(num1<num[j]){ // num[j+1]=num[j]; // num[j]=num1; // } // } // } //插入排序,for-while嵌套 // for(int i=1;i<LENGTH;i++){ // int num1; // num1=num[i]; // int j=i-1; // while(num1<num[j]&&j>=0){ // num[j+1]=num[j]; // num[j]=num1; // j--; // } // } // for(int i=0;i<LENGTH;i++){ // cout<<num[i]<<endl; // } return 0; } // 要生成和返回随机数的函数 int * getMergeArray(int arr1[],int arr2[],int max_length_array_a,int max_length_array_b) { int index_of_a=0,index_of_b=0; int merge_length=max_length_array_a+max_length_array_b; int array_merge[merge_length]; int array_merge_index=0; //进行数组合并 for(array_merge_index=0;array_merge_index<merge_length;array_merge_index++){ if(index_of_a<max_length_array_a&&index_of_b<max_length_array_b){ if(*(arr1+index_of_a)<*(arr2+index_of_b)){ array_merge[array_merge_index]=*(arr1+index_of_a); index_of_a++; }else{ array_merge[array_merge_index]=*(arr2+index_of_b); index_of_b++; } }else{ if(index_of_a==max_length_array_a){ array_merge[array_merge_index]=*(arr2+index_of_b); index_of_b++; }else{ array_merge[array_merge_index]=*(arr1+index_of_a); index_of_a++; } } } for(array_merge_index=0;array_merge_index<merge_length;array_merge_index++){ cout<< array_merge[array_merge_index] <<endl; } // cout<<sizeof*arr1+1<<endl; // int size1=sizeof(*arr1); // int size2=sizeof(*arr2); return array_merge; }
Java
UTF-8
2,280
2.34375
2
[]
no_license
package routes; import core.IO.Reader; import core.PlagiarismDetection.Assignment; import core.PlagiarismDetection.Submission; import core.PlagiarizerFactory.Factory; import com.fasterxml.jackson.databind.ObjectMapper; import core.configuration.ApplicationConfig; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @CrossOrigin(origins = { ApplicationConfig.testFrontEnd, ApplicationConfig.local, ApplicationConfig.herokuNoHttps, ApplicationConfig.heroku}) public class Submissions { Factory factory = new Factory(); Assignment a = factory.createAssignment(); Reader reader = factory.Reader(); ObjectMapper om = new ObjectMapper(); /** * @param id is the unique ID given to each Student * @param name is the name of the file * @return error if there is no file with the given name, else return the contents of the file */ @RequestMapping("submission") public ResponseEntity<?> findSubmission(@RequestParam(value = "studentID") String id, @RequestParam(value = "fileName") String name) { Submission submission; // to temporarily hold a submission String program; try { int studentID = Integer.parseInt(id); submission = (a.findSubmission(studentID)); // if no submission is present, return error if (submission == null) { return ApplicationConfig.ErrorResponse(); } else { // if no file is present, return error String absolutePathtoFile = submission.getAbsolutePath(name); if (absolutePathtoFile == null) return ApplicationConfig.ErrorResponse(); else program = om.writeValueAsString(reader.getFile(absolutePathtoFile)); } } catch (Exception e) { return ApplicationConfig.ErrorResponse(); } return ResponseEntity.ok(program); } }
Python
UTF-8
1,274
3.1875
3
[]
no_license
#!/usr/bin/python # https://wiki.wxpython.org/AnotherTutorial import wx class MyMenu(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(200, 100)) # menubar menubar = wx.MenuBar() # menus file = wx.Menu() edit = wx.Menu() help = wx.Menu() # add some item to the menu file.Append(101, 'Open', 'Open a new document') file.Append(102, 'Save', 'Save the document') file.AppendSeparator() # make a quit item and add to file menu quit = wx.MenuItem(file, 105, 'Quit', 'Quit the Application') quit.SetBitmap(wx.Image('stock_exit_24.png', wx.BITMAP_TYPE_PNG).ConvertToBitmap()) file.AppendItem(quit) # add menus to the menubar menubar.Append(file, 'File') menubar.Append(edit, 'Edit') menubar.Append(help, 'Help') # set the menubar to the frame self.SetMenuBar(menubar) class MyApp(wx.App): def OnInit(self): frame = MyMenu(None, wx.ID_ANY, "menu1.py") frame.SetIcon(wx.Icon('icon.ico', wx.BITMAP_TYPE_ICON)) frame.Center() frame.Show(True) return True app = MyApp(False) app.MainLoop()
C++
UTF-8
438
2.875
3
[]
no_license
#include <stdint.h> #include<stdio.h> #include<stdlib.h> //strlen int main(int argc, char** argv) { if (argc != 3) { printf("Wrong number of argumens, expected 2 arguments."); return -1; } uint8_t x1 = (uint8_t) atoi(argv[1]); uint8_t x2 = (uint8_t) atoi(argv[2]); int16_t value_int_rec = (int16_t) (((x1 & 0x00FF) << 8) | (x2 & 0x00FF)); printf("%d", value_int_rec); }
Go
UTF-8
226
2.828125
3
[ "Apache-2.0" ]
permissive
package singleton import ( "log" "sync" ) var a *Alone var once sync.Once func GetInstance() *Alone { once.Do(func() { a = &Alone{} }) return a } type Alone struct{} func (a Alone) Alone() { log.Println("a...") }
C
UTF-8
909
3.75
4
[]
no_license
#include <stdio.h> #include <math.h> float a, b, c,delta, x1, x2; int main() { /* printf("Entrez la valeur de a : "); scanf("%f\n",&a); printf("Entrez la valeur de a : %f\n", a); printf("Entrez la valeur de a : %f\n", c); */ a=0; b=0; c=0; x1=0; x2=0; printf("\n*** Programme Pour calculer la sol du second degré ***\n\n"); printf("\nEntrez la valeur de a :"); scanf("%f",&a); printf("\nEntrez la valeur de b :"); scanf("%f",&b); printf("\nEntrez la valeur de c :"); scanf("%f",&c); printf("\nMerci, calcul en cours\n"); delta=b*b-(4*a*c); if (delta == 0) { x1 = -b/(2*a); printf("\nx = %f\n",x1); } else if (delta<0) { printf("\nNO WAY -> impossible\n"); } else if (delta > 0) { x1= (-b-sqrt(delta))/(2*a) ; x2= (-b+sqrt(delta))/(2*a); printf("\nx1 = %f\n",x1); printf("x2 = %f\n",x2); } return 0; }
Java
UTF-8
499
1.976563
2
[]
no_license
package com.event_manager.eventservice.repositories; import com.event_manager.eventservice.models.Goody; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import java.util.List; public interface GoodyRepository extends JpaRepository<Goody, Long> { @Query("SELECT g FROM Goody g WHERE g.event.event_id = :id ") List<Goody> findByEventId(@Param("id") Long id); }
C++
UTF-8
1,067
3.390625
3
[ "MIT" ]
permissive
#include <bits/stdc++.h> #define read() freopen("input.txt", "r", stdin) #define write() freopen("output.txt", "w", stdout) using namespace std; bool balance(string s); bool check(char a, char b); int main(void) { int T; cin >> T; cin.ignore(); for(int i = 1; i <= T; i++){ string s; getline(cin, s); if(balance(s)) cout << "Yes" << endl; else cout << "No" << endl; } return 0; } bool balance(string s) { int len = s.length(); if(len == 0) return true; stack<char> S; for(int i = 0; i < len; i++){ if(s[i] == '(' || s[i] == '{' || s[i] == '[') S.push(s[i]); else{ if(S.empty() || !check(S.top(), s[i])) return false; else S.pop(); } } return S.empty()? true : false; } bool check(char a, char b) { if(a == '(' && b == ')') return true; else if(a == '{' && b == '}') return true; else if(a == '[' && b == ']') return true; return false; }
C#
UTF-8
343
2.75
3
[]
no_license
void Main() { var dt = new MyData(); FillTracking(dt); } public void FillTracking(TrackableObject obj) { obj.LastUpate = DateTime.Now; } public class TrackableObject { public DateTime LastUpate { get; set; } } public class MyData : TrackableObject { }
Python
UTF-8
5,629
3.375
3
[]
no_license
#! /usr/bin/env python # def cpv ( f, a, b, n ): #*****************************************************************************80 # ## CPV estimates the Cauchy Principal Value of an integral. # # Location: # # http://people.sc.fsu.edu/~jburkardt/f_src/cauchy_principal_value/cpv.f90 # # Discussion: # # This function can be used to estimate the Cauchy Principal Value of # a singular integral of the form # Integral f(t)/(t-x) dt # over an interval which includes the singularity point t=x. # # Isolate the singularity at x in a symmetric interval of finite size delta: # # CPV ( Integral ( a <= t <= b ) p(t) / ( t - x ) dt ) # = Integral ( a <= t <= x - delta ) p(t) / ( t - x ) dt # + CPV ( Integral ( x - delta <= t <= x + delta ) p(t) / ( t - x ) dt ) # + Integral ( x + delta <= t <= b ) p(t) / ( t - x ) dt. # # We assume the first and third integrals can be handled in the usual way. # The second integral can be rewritten as # Integral ( -1 <= s <= +1 ) ( p(s*delta+x) - p(x) ) / s ds # and approximated by # Sum ( 1 <= i <= N ) w(i) * ( p(xi*delta+x) - p(x) ) / xi(i) # = Sum ( 1 <= i <= N ) w(i) * ( p(xi*delta+x) ) / xi(i) # if we assume that N is even, so that coefficients of p(x) sum to zero. # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 01 April 2015 # # Author: # # John Burkardt # # Reference: # # Julian Noble, # Gauss-Legendre Principal Value Integration, # Computing in Science and Engineering, # Volume 2, Number 1, January-February 2000, pages 92-95. # # Parameters: # # Input, real F ( X ), the function that evaluates the # integrand. # # Input, real A, B, the endpoints of the symmetric interval, # which contains a singularity of the form 1/(X-(A+B)/2). # # Input, integer N, the number of Gauss points to use. # N must be even. # # Output, real VALUE, the estimate for the Cauchy Principal Value. # from legendre_set import legendre_set from sys import exit # # N must be even. # if ( ( n % 2 ) != 0 ): print '' print 'CPV - Fatal error!' print ' N must be even.' exit ( 'CPV - Fatal error.' ) # # Get the Gauss-Legendre rule. # [ x, w ] = legendre_set ( n ); # # Estimate the integral. # value = 0.0; for i in range ( 0, n ): x2 = ( ( 1.0 - x[i] ) * a \ + ( 1.0 + x[i] ) * b ) \ / 2.0 value = value + w[i] * ( f ( x2 ) ) / x[i] return value def cpv_test01 ( ): #*****************************************************************************80 # ## CPV_TEST01 seeks the CPV of Integral ( -1 <= t <= 1 ) exp(t) / t dt # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 02 April 2015 # # Author: # # John Burkardt # print '' print 'CPV_TEST01:' print ' CPV of Integral ( -1 <= t <= 1 ) exp(t) / t dt' print '' print ' N Estimate Error' print '' exact = 2.11450175075 a = -1.0 b = +1.0 for n in range ( 2, 10, 2 ): value = cpv ( f01, a, b, n ) print ' %2d %24.16g %14.6g' % ( n, value, abs ( value - exact ) ) return def f01 ( t ): #*****************************************************************************80 # ## F01 evaluates the integrand of Integral ( -1 <= t <= 1 ) exp(t) / t dt # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 01 April 2015 # # Author: # # John Burkardt # # Parameters: # # Input, real T, the argument. # # Output, real VALUE, the value of the integrand. # import numpy as np value = np.exp ( t ) return value def cpv_test02 ( ): #*****************************************************************************80 # ## CPV_TEST02 is another test. # # Discussion: # # We seek # CPV ( Integral ( 1-delta <= t <= 1+delta ) 1/(1-t)^3 dt ) # which we must rewrite as # CPV ( Integral ( 1-delta <= t <= 1+delta ) 1/(1+t+t^2) 1/(1-t) dt ) # so that our "integrand" is 1/(1+t+t^2). # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 01 April 2015 # # Author: # # John Burkardt # import numpy as np print '' print 'CPV_TEST02:' print ' Compute CPV ( Integral ( 1-delta <= t <= 1+delta ) 1/(1-t)^3 dt )' print ' Try this for delta = 1, 1/2, 1/4.' print '' print ' N Estimate Exact Error' delta = 1.0 for k in range ( 0, 3 ): print '' r1 = ( delta + 1.5 ) ** 2 + 0.75 r2 = ( - delta + 1.5 ) ** 2 + 0.75 r3 = np.arctan ( np.sqrt ( 0.75 ) / ( delta + 1.5 ) ) r4 = np.arctan ( np.sqrt ( 0.75 ) / ( - delta + 1.5 ) ) exact = - np.log ( r1 / r2 ) / 6.0 + ( r3 - r4 ) / np.sqrt ( 3.0 ) for n in range ( 2, 10, 2 ): a = 1.0 - delta b = 1.0 + delta value = cpv ( f02, a, b, n ) print ' %2d %24.16g %24.16g %14.6g' \ % ( n, value, exact, abs ( value - exact ) ) delta = delta / 2.0 return def f02 ( t ): #*****************************************************************************80 # ## F02: integrand of Integral ( 1-delta <= t <= 1+delta ) 1/(1-t^3) dt # # Discussion: # # 1/(1-t^3) = 1/(1+t+t^2) * 1/(1-t) # # Licensing: # # This code is distributed under the GNU LGPL license. # # Modified: # # 01 April 2015 # # Author: # # John Burkardt # # Parameters: # value = 1.0 / ( 1.0 + t + t * t ) return value if ( __name__ == '__main__' ): from timestamp import timestamp timestamp ( ) cpv_test01 ( ) cpv_test02 ( ) timestamp ( )
C++
UTF-8
137
2.5625
3
[]
no_license
#include<iostream> #include<cstdlib> int main(){ int null=0, *p=&null; double * p2=NULL; std::cout << *p << std::endl; return 0; }
Markdown
UTF-8
8,533
3.390625
3
[]
no_license
# JVM相关 ## 目录 1. 介绍一下Class文件 2. Java虚拟机运行时的数据区 3. 双亲委派模型 4. 判断Java中对象存活的算法 5. JVM垃圾回收算法 * 介绍一下Class文件 Java诞生之初,Java的规范就拆分为Java语言规范和Java虚拟机规范,为了实现Java语言的平台无关性,各种不同平台的虚拟机都统一使用的程序存储格式,也就是字节码。使用Java编译器可以把Java代码编译成为存储字节码的Class文件。Class文件是一组以8个字节为基础单位的二进制流,每一个Class文件都对应着唯一一个类或接口的定义信息。 * Java虚拟机运行时的数据区 分为 **程序计数器**,**Java虚拟机栈**,**本地方法栈**,**Java堆**,**方法区** **程序计数器**是线程私有的一块较小的内存空间,可以看作是当前线程所执行的字节码的行号指示器。如果线程正在执行的是一个Java方法,那么计数器记录的是正在执行的虚拟机字节码指令的地址。如果正在执行的是Natvie方法,这个计数器值为空。 **Java虚拟机栈**线程私有,生命周期与线程相同。虚拟机栈描述的是Java方法执行的内存模型。每个方法执行的同时都会创建一个栈帧,用于存储局部变量表,操作数栈,动态链接,方法出口等信息。方法的调用和执行完成,就对应着栈帧的入栈和岀栈过程。其中局部变量表存放的是编译器可知的各种基本数据类型,对象引用和returnAddress类型。这里规定了两种异常情况,如果线程请求的栈深度大于虚拟机所允许的深度,抛出StackOverFlow异常;如果虚拟机栈可以动态扩展,并且扩展时无法申请到足够的内存,会抛出OutOfMemoryError。 **本地方法栈**与Java虚拟机栈类似,区别就是这里执行的是native方法。 **Java堆** 是Java虚拟机所管理的内存中最大的一块。Java堆是被所有线程共享的一块内存区域。此内存区域的唯一目的就是存放对象实例,几乎所有的对象是你都在这里分配内存。这里也是垃圾收集器管理的主要区域,也成做GC堆。由于现代收集器基本都采用分代算法,所以Java堆还可以细分为:新生代和老年代。Java堆可以是物理上不连续的内存空间,只要逻辑连续即可。如果Java堆中没有内存完成实例分配,并且堆也无法拓展时,将抛出OutOfMemiryError。 **方法区** 也是各个线程共享的内存区域,用于存储已被虚拟机加载的类信息,常量,静态变量,即时编译器编译后的代码等。其中**运行时常量池**是方法区的一部分,用于存放编译器生成的各种字面量和符号引用。当方法区无法满足内存分配需求时,将会抛出OutOfMemiryError。 * 双亲委派模型 双亲委派模型指的是Java虚拟机执行类加载的时候,设计的一套类加载器的加载模型。 Java虚拟机把描述类的class文件加载到内存,并对数据进行校验,转换解析和初始化,最终形成被虚拟机直接使用的Java类型,就是虚拟机的类加载机制。 从Java虚拟机的角度,存在两种不同的类加载器,一种是启动类加载器,由C++语言实现,是虚拟机的一部分。另一类是其他类加载器,由Java语言实现,独立于虚拟机外部,继承自ClassLoader抽象类。 类加载器存在层次关系,最高层是启动类加载器,然后由上到下是扩展类加载器,应用程序类加载器以及各种自定义的类加载器。双亲委派模型的工作流程是,如果一个类加载器收到了类加载的请求,它首先不会自动去尝试加载这个类,而是把这个请求委派给父类加载器去完成。只有当父类加载器反馈自己无法完成这个加载请求时,子类加载器才会尝试自己去加载。 * 判断Java中对象存活的算法 1. 引用计数器算法: 引用计数器算法是给每个对象设置一个计数器,当有地方引用这个对象的时候,计数器+1,当引用失效的时候,计数器-1,当计数器为0的时候,JVM就认为对象不再被使用,是“垃圾”了。 引用计数器实现简单,效率高;但是不能解决循环引用问问题(A对象引用B对象,B对象又引用A对象,但是A,B对象已不被任何其他对象引用),同时每次计数器的增加和减少都带来了很多额外的开销,所以在JDK1.1之后,这个算法已经不再使用了。 2. 根搜索方法: 根搜索方法是通过一些“GCRoots”对象作为起点,从这些节点开始往下搜索,搜索通过的路径成为引用链(ReferenceChain),当一个对象没有被GCRoots的引用链连接的时候,说明这个对象是不可用的。 * JVM垃圾回收算法 1. 标记-清除算法 标记-清除(Mark-Sweep)算法是现代垃圾回收算法的思想基础。标记-清除算法将垃圾回收分为两个阶段:标记阶段和清除阶段。一种可行的实现是,在标记阶段,首先通过根节点,标记所有从根节点开始的可达对象。因此,未被标记的对象就是未被引用的要回收的对象。然后.在清除阶段,清除所有未被标记的对象。 缺点: 1、效率问题,标记和清除两个过程的效率都不高; 2、空间问题,标记清除之后会产生大量不连续的内存碎片,空间碎片太多可能会导致以后在程序运行过程中需要分配较大的对象时,无法找到足够的连续内存而不得不提前触发另一次垃圾收集动作。 2. 标记整理算法 标记整理算法类似与标记清除算法,不过它标记完对象后,不是直接对可回收对象进行清理,而是让所有存活的对象都向一端移动,然后直接清理掉边界以外的内存。 缺点: 1、效率问题,(同标记清除算法)标记和整理两个过程的效率都不高; 优点: 1、相对标记清除算法,解决了内存碎片问题。 2、没有内存碎片后,对象创建内存分配也更快速了(可以使用TLAB进行分配)。 3. 复制算法 复制算法可以解决效率问题,它将可用内存按容量划分为大小相等的两块,每次只使用其中的一块,当这一块内存用完了,就将还存活着的对象复制到另一块上面,然后再把已经使用过的内存空间一次清理掉,这样使得每次都是对整个半区进行内存回收,内存分配时也就不用考虑内存碎片等复杂情况,只要移动堆顶指针,按顺序分配内存即可 优点 效率高,没有内存碎片 缺点: 1、浪费一半的内存空间 2、复制收集算法在对象存活率较高时就要进行较多的复制操作,效率将会变低。 4. 分代收集算法 当前商业虚拟机都是采用分代收集算法,它根据对象存活周期的不同将内存划分为几块,一般是把Java堆分为新生代和老年代,然后根据各个年代的特点采用最适当的收集算法,在新生代中,每次垃圾收集都发现有大批对象死去,只有少量存活,就选用复制算法,而老年代因为对象存活率高,没有额外空间对它进行分配担保,就必须使用“标记清除”或者“标记整理”算法来进行回收。 对象分配策略: 对象优先在Eden区域分配,如果对象过大直接分配到Old区域。 长时间存活的对象进入到Old区域。 改进复制算法: 现在的商业虚拟机都采用这种收集算法来回收新生代,IBM公司的专门研究表明,新生代中的对象98%是“朝生夕死”的,所以并不需要按照1:1的比例来划分内存空间,而是将内存分为一块较大的Eden空间和两块较小的Survivor空间,每次使用Eden和其中一块Survivor 。当回收时,将Eden和Survivor中还存活着的对象一次性地复制到另外一块Survivor空间上,最后清理掉Eden和刚才用过的Survivor空间。 HotSpot虚拟机默认Eden和Survivor的大小比例是8:1,也就是每次新生代中可用内存空间为整个新生代容量的90%(80%+10%),只有10%的内存会被“浪费”。当然,98%的对象可回收只是一般场景下的数据,我们没有办法保证每次回收都只有不多于10%的对象存活,当Survivor空间不够用时,需要依赖其他内存(这里指老年代)进行分配担保(Handle Promotion)。
Java
UTF-8
234
2.40625
2
[]
no_license
package com.codingame.game.exception; @SuppressWarnings("serial") public class CellNotValidException extends GameException { public CellNotValidException(int id) { super("You can't plant a seed on cell " + id); } }
TypeScript
UTF-8
1,308
2.84375
3
[]
no_license
import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import { Product } from "../Products/products.slice"; import { RootState } from "../store"; // interface CartProduct extends Product { // amount: number // } type CartProduct = Product & { amount: number } const CartSlice = createSlice({ name: 'Cart', initialState: [] as CartProduct[], reducers: { addToCart: (state, action: PayloadAction<Product>) => { const productIndex = state.findIndex(product => product.id === action.payload.id) if(productIndex === -1){ state.push({...action.payload, amount: 1}) }else{ state[productIndex].amount += 1 } }, removeFromCart: (state, action: PayloadAction<string>) => { const productIndex = state.findIndex(product => product.id === action.payload) if(state[productIndex].amount > 1){ state[productIndex].amount -= 1 }else{ return state.filter(product => product.id !== action.payload) } } } }) export const { addToCart, removeFromCart } = CartSlice.actions export const getCartProductsSelector = (state: RootState) => state.Cart export const getTotalPriceSelector = (state: RootState) => state.Cart.reduce((acc, next) => acc += (next.amount * next.price), 0) export default CartSlice.reducer
Python
UTF-8
946
4.0625
4
[]
no_license
''' Created on 24-May-2020 @author: sasidharl Tuple - examples ''' if __name__ == '__main__': pass # declare tuple a = ("apple", "banana", "watermelon") # print("a length : ",len(a)) # print all values from tuple print(a) # print value by index print(a[1]) #print value by negative index # -1 refers the last item in the index print(a[-1]) # -2 refers the second last item print(a[-2]) #declare 2 tuples at a time in single line. # we can create tuple with the combination of integer and string types. tuple1, tuple2 = (123, 'xyz', 'zara'), (456, 'abc') print ("First tuple length : ", len(tuple1)) print ("Second tuple length : ", len(tuple2)) print(tuple1[0]) #convert tuple to list x = ("apple", "banana", "cherry") print(x) y = list(x) #change the value by index in the list y[1] = "kiwi" x = tuple(y) print(x) # You cannot add items to a tuple: # remove item in tuple #join two tuples # tuple constructor #count # index
Markdown
UTF-8
1,809
3.265625
3
[]
no_license
## Data Structure and Algorithms in Python 1. Stack - Determine if brackets are balanced - Reverse string - Convert decimal integer to binary 2. Singly Linked Lists - Insertion - Deletion by value - Deletion by position - Length - Node swap - Reverse - Merge two sorted linked lists - Remove duplicates - Nth-to-last node - Count occurrences - Rotate - Is palindrome - Move tail to head - Sum two linked lists 3. Circular Linked Lists - Insertion - Remove node - Split linked lists into two halves - Josephus problem - Is circular linked lists 4. Doubly Linked Lists - Append and prepend - Add node before/after - Delete node - Reverse - Remove duplicates - Pairs with sums 5. Arrays - Array advance game - Arbitrary precision increment - Two sum problem - Optimal task assignment - Intersection of two sorted arrays - Buy and sell stock 6. Binary Trees - Traversal algorithm - Level-order traversal - Reverse level-order traversal - Calculate binary tree height - Calculate tree size 7. Binary Search Trees - Insertion and search - Check BST property 8. Binary Search - Find the closest number - Find fixed point - Find bitonic peak - Find first entry in list with duplicates - Bisect method - Integer square root - Cyclically shifted array 9. Recursion - Find uppercase letter in string - Calculate string length - Count consonants in string - Product of two positive integers 10. String Processing - Look-and-say sequence - Spreadsheet encoding - Is palindrome - Is anagram - Is palindrome permutation - Check permutation - Is unique - String to integer
Markdown
UTF-8
1,900
2.71875
3
[]
no_license
仿MIUI计算器 =========== 基本功能: 1,完成了基本的加减乘除运算。 2,表达式出错(例如除以0)会返回错误。 3,点击等号后会有运算小动画(视图动画)。 4,点击等号运算结束后,再点击运算符和数字会有不同的效果,即点击运算符会把上一次的结果当做第一个数参与运算,而点击数字会清空重新输入。 5,完成科学计算界面 6,完成简易计算器与科学计算器之间的动画变换。 7,待完善科学计算的计算程序........囧,还没写完 重点: * 键盘界面仿的小米计算器,使用TableLayout,由于TableLayout不支持合并行,因而采用了嵌套的方式来显示跨行的等号。 * 最上面的表达式和结果显示的两个EditText使用右对齐,注意在每次输入的时候都要setSelection,即:`text2.setSelection(expression.length());`来确保始终会显示最新输入的字符。 * 为了使简易计算器和科学计算器之间变换效果接近小米原来的效果,这里使用了FrameLayout,键盘在第一层,占据下面2/3的用户区域,其他在第二层占据上面1/3的用户区域。这样,在键盘进行缩放动画的时候就不会影响到第二层的显示。(**键盘的动画始终显示在下面2/3的范围内!!!!**) 另外,注意三种高度的不同: * 屏幕区域,高度为整个屏幕的高度 * 应用区域,高度为去除状态栏的屏幕的高度 * 用户区域,高度为去除状态栏和标题栏的高度 <img src="./screenshot/simple1.png" width = "240" height = "430" alt="simple"/> <img src="./screenshot/simple2.png" width = "240" height = "430" alt="simple2" /> <img src="./screenshot/simple3.png" width = "240" height = "430" alt="simple2" /> <img src="./screenshot/anime.gif" height="430" alt="simple2" />
Java
UTF-8
6,234
1.984375
2
[]
no_license
/** * Copyright 2010-present Facebook. * * 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 com.foodango; import java.util.HashMap; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.facebook.LoggingBehavior; import com.facebook.Session; import com.facebook.SessionState; import com.facebook.Settings; import com.foodango.R; import com.foodango.constant.APIConstants; import com.foodango.constant.ApplicationConstants; import com.foodango.model.LoginResponseSuccessResponse; import com.foodango.net.GetJSONListener; import com.foodango.net.JSONClient; import com.google.gson.Gson; public class LoginActivity extends Activity implements GetJSONListener { private static final String URL_PREFIX_FRIENDS = "https://graph.facebook.com/me/friends?access_token="; EditText mLoginEditText; Button btn_login; Button btn_fblogin; String userName = null; private Session.StatusCallback statusCallback = new SessionStatusCallback(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.login_screen); mLoginEditText = (EditText) findViewById(R.id.txt_username); btn_login = (Button) findViewById(R.id.btn_login); btn_fblogin = (Button) findViewById(R.id.btn_fblogin); btn_login.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { login(userName); // check login is valid or not // TODO Auto-generated method stub // Intent intent = new Intent(LoginActivity.this, QRActivity.class); // startActivity(intent); } }); userName = mLoginEditText.getText().toString(); Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS); Session session = Session.getActiveSession(); if (session == null) { if (savedInstanceState != null) { session = Session.restoreSession(this, null, statusCallback, savedInstanceState); } if (session == null) { session = new Session(this); } Session.setActiveSession(session); if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) { session.openForRead(new Session.OpenRequest(this) .setCallback(statusCallback)); } } updateView(); } private void login(String userName) { if (userName != null) { JSONObject holder = new JSONObject(); try { holder.put(ApplicationConstants.LOGIN_USER_VALUE, userName); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } JSONClient client = new JSONClient(this, this, holder, APIConstants.LOGIN_URL, true, null, ApplicationConstants.LOGIN_CODE, true); client.execute(); } else { Toast.makeText(this, " PLEASE ENTER SOME VALUE ", Toast.LENGTH_SHORT); } } @Override public void onStart() { super.onStart(); Session.getActiveSession().addCallback(statusCallback); } @Override public void onStop() { super.onStop(); Session.getActiveSession().removeCallback(statusCallback); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); Session session = Session.getActiveSession(); Session.saveSession(session, outState); } private void updateView() { Session session = Session.getActiveSession(); if (session.isOpened()) { // textInstructionsOrLink.setText(URL_PREFIX_FRIENDS + // session.getAccessToken()); // buttonLoginLogout.setText(R.string.logout); // buttonLoginLogout.setOnClickListener(new OnClickListener() { // public void onClick(View view) { onClickLogout(); } // }); System.out.println("*****login****"); } else { btn_fblogin.setOnClickListener(new OnClickListener() { public void onClick(View view) { onClickLogin(); } }); System.out.println("*****login failed****"); } } private void onClickLogin() { Session session = Session.getActiveSession(); if (!session.isOpened() && !session.isClosed()) { session.openForRead(new Session.OpenRequest(this) .setCallback(statusCallback)); } else { Session.openActiveSession(this, true, statusCallback); } } private void onClickLogout() { Session session = Session.getActiveSession(); if (!session.isClosed()) { session.closeAndClearTokenInformation(); } } private class SessionStatusCallback implements Session.StatusCallback { @Override public void call(Session session, SessionState state, Exception exception) { updateView(); } } @Override public void onRemoteCallComplete(String json, int code) { Log.d("LoginActivity"," ******* JSON Response ********* : "+json); // try { // Gson gson = new Gson(); // LoginResponseSuccessResponse response = gson.fromJson(json, // LoginResponseSuccessResponse.class); // if (code == ApplicationConstants.LOGIN_CODE) { Log.d("LoginActivity"," ******* JSON Response Success ********* "); Intent intent = new Intent(LoginActivity.this, DashboardActivity.class); startActivity(intent); // } else { // Log.d("LoginActivity"," ******* JSON Response Else ********* "); // } // } catch (Exception e) { // Util.toast("", ""); // } } }
Markdown
UTF-8
5,537
2.59375
3
[]
no_license
Local reply modification {#config_http_conn_man_local_reply} ======================== The `HTTP connection manager <arch_overview_http_conn_man>`{.interpreted-text role="ref"} supports modification of local reply which is response returned by Envoy itself. Features: - `Local reply content modification<config_http_conn_man_local_reply_modification>`{.interpreted-text role="ref"}. - `Local reply format modification<config_http_conn_man_local_reply_format>`{.interpreted-text role="ref"}. Local reply content modification {#config_http_conn_man_local_reply_modification} -------------------------------- The local response content returned by Envoy can be customized. A list of `mappers <envoy_v3_api_field_extensions.filters.network.http_connection_manager.v3.LocalReplyConfig.mappers>`{.interpreted-text role="ref"} can be specified. Each mapper must have a `filter <envoy_v3_api_field_config.accesslog.v3.AccessLog.filter>`{.interpreted-text role="ref"}. It may have following rewrite rules; a `status_code <envoy_v3_api_field_extensions.filters.network.http_connection_manager.v3.ResponseMapper.status_code>`{.interpreted-text role="ref"} rule to rewrite response code, a `headers_to_add <envoy_v3_api_field_extensions.filters.network.http_connection_manager.v3.ResponseMapper.headers_to_add>`{.interpreted-text role="ref"} rule to add/override/append response HTTP headers, a `body <envoy_v3_api_field_extensions.filters.network.http_connection_manager.v3.ResponseMapper.body>`{.interpreted-text role="ref"} rule to rewrite the local reply body and a `body_format_override <envoy_v3_api_field_extensions.filters.network.http_connection_manager.v3.ResponseMapper.body_format_override>`{.interpreted-text role="ref"} to specify the response body format. Envoy checks each [mapper]{.title-ref} according to the specified order until the first one is matched. If a [mapper]{.title-ref} is matched, all its rewrite rules will apply. Example of a LocalReplyConfig ``` {.} mappers: - filter: status_code_filter: comparison: op: EQ value: default_value: 400 runtime_key: key_b headers_to_add: - header: key: "foo" value: "bar" append: false status_code: 401 body: inline_string: "not allowed" ``` In above example, if the status_code is 400, it will be rewritten to 401, the response body will be rewritten to as \"not allowed\". Local reply format modification {#config_http_conn_man_local_reply_format} ------------------------------- The response body content type can be customized. If not specified, the content type is plain/text. There are two [body_format]{.title-ref} fields; one is the `body_format <envoy_v3_api_field_extensions.filters.network.http_connection_manager.v3.LocalReplyConfig.body_format>`{.interpreted-text role="ref"} field in the `LocalReplyConfig <envoy_v3_api_msg_extensions.filters.network.http_connection_manager.v3.LocalReplyConfig>`{.interpreted-text role="ref"} message and the other `body_format_override <envoy_v3_api_field_extensions.filters.network.http_connection_manager.v3.ResponseMapper.body_format_override>`{.interpreted-text role="ref"} field in the [mapper]{.title-ref}. The latter is only used when its mapper is matched. The former is used if there is no any matched mappers, or the matched mapper doesn\'t have the [body_format]{.title-ref} specified. Local reply format can be specified as `SubstitutionFormatString <envoy_v3_api_msg_config.core.v3.SubstitutionFormatString>`{.interpreted-text role="ref"}. It supports `text_format <envoy_v3_api_field_config.core.v3.SubstitutionFormatString.text_format>`{.interpreted-text role="ref"} and `json_format <envoy_v3_api_field_config.core.v3.SubstitutionFormatString.json_format>`{.interpreted-text role="ref"}. Optionally, content-type can be modified further via `content_type <envoy_v3_api_field_config.core.v3.SubstitutionFormatString.content_type>`{.interpreted-text role="ref"} field. If not specified, default content-type is [text/plain]{.title-ref} for `text_format <envoy_v3_api_field_config.core.v3.SubstitutionFormatString.text_format>`{.interpreted-text role="ref"} and [application/json]{.title-ref} for `json_format <envoy_v3_api_field_config.core.v3.SubstitutionFormatString.json_format>`{.interpreted-text role="ref"}. Example of a LocalReplyConfig with [body_format]{.title-ref} field. ``` {.} mappers: - filter: status_code_filter: comparison: op: EQ value: default_value: 400 runtime_key: key_b status_code: 401 body_format_override: text_format: "<h1>%LOCAL_REPLY_BODY% %REQ(:path)%</h1>" content_type: "text/html; charset=UTF-8" - filter: status_code_filter: comparison: op: EQ value: default_value: 500 runtime_key: key_b status_code: 501 body_format: text_format: "%LOCAL_REPLY_BODY% %RESPONSE_CODE%" ``` In above example, there is a [body_format_override]{.title-ref} inside the first [mapper]{.title-ref} with a filter matching [status_code == 400]{.title-ref}. It generates the response body in plain text format by concatenating %LOCAL_REPLY_BODY% with the [:path]{.title-ref} request header. It is only used when the first mapper is matched. There is a [body_format]{.title-ref} at the bottom of the config and at the same level as field [mappers]{.title-ref}. It is used when non of the mappers is matched or the matched mapper doesn\'t have its own [body_format_override]{.title-ref} specified.
Java
UTF-8
1,000
2.609375
3
[]
no_license
import java.util.*; import java.sql.*; import java.sql.Date; import java.io.*; import java.math.*; public class Fines { private int Loan_id; private Double Fine_amt = 0.00; private boolean Paid = false; public Fines(int Loan_id) { super(); this.Loan_id= Loan_id; } public Fines(int Loan_id, Double Fine_amt, boolean Paid) { super(); this.Loan_id= Loan_id; this.Paid= Paid; this.Fine_amt= Fine_amt; } public int getLoan_id() { return Loan_id; } public void setLoan_id(int Loan_id) { this.Loan_id = Loan_id; } public Double getFine_amt() { return Fine_amt; } public void setFine_amt(double Fine_amt) { this.Fine_amt = Fine_amt; } public boolean getPaid() { return Paid; } public void setPaid(boolean Paid) { this.Paid = Paid; } @Override public String toString() { return String .format("Loan_id=%s, Fine_amt=%s, Paid =%s \n", Loan_id, Fine_amt, Paid); } }
Java
UTF-8
642
3.09375
3
[]
no_license
package hongbao67; import java.util.ArrayList; import java.util.Random; public class Memeber extends User { public Memeber(String name, int money) { super(name, money); } public void receive(ArrayList<Integer> list ){ //创建receive方法 接收空集合 Random random=new Random(); //生成随机索引 int index = random.nextInt(list.size()); //将产生的随机数定义为 集合长度 int money=list.remove(index); //将获取的金额从集合中移除 super.setMoney(getMoney()+money); // 重新设置获得的钱 } }
Markdown
UTF-8
5,775
2.828125
3
[]
no_license
--- nid: '1961' title: 'The Knights of Free Software' authors: 'Matt Barton' published: '2006-12-20 21:52:23' tags: 'ethics,philosophy,religion' license: verbatim_only section: opinions listed: 'true' --- Lately, I've been thinking about what the free software movement is really about. Is it really just a bunch of guys who work with code, releasing it under a particular type of license? We seem to talk a great deal about "freedom" and insist that what separates free software from open source or proprietary is this philosophical, ethical, and legal insistence on total freedom for the user. All right; but is this all there is to it? Or should free software programmers and devotees start thinking about bigger issues, and making more serious contributions to society than just improving its code base? Should we "focus on coding" and just hope that society improves by osmosis? Personally, I find this outlook is becoming increasingly unsatisfying. I think this movement needs to expand its horizon and start exploring more direct ways to change the world we live in. I think the Free Software Movement must be about a life choice, not merely a software licensing choice. What I'd like to do here is offer some possible steps towards a more total free software movement. What I have in mind specifically is some ethical standards and practices free software hackers could possibly set for themselves that set them radically apart from the rest of society. Many can say that the free software movement should be about more than the code of computers; it should be about a code of honor, akin to the chivalric code of Medieval knights, perhaps, but probably more similar to the code lived under by Franciscan monks. My contention is that by logically extending the principles of free software to other aspects of life, we end up with a much stronger movement. Keep in mind that what I am proposing is definitely not for everyone. However, some hackers out there could in fact get some inspiration. I will refer to a hackers who want to follow this path "Knights of Free Software." What would such a life look like from the outside? First off, it would be important to undertake a "vow of non-ownership." What I mean is that knights would not only refuse to own any proprietary software, but also to own any property whatsoever. He or she should accept only as much in the form of donations as absolutely necessary to survive and continue programming or enlightening others. Once these bare minimums of subsistence are reached, a knight should kindly refuse additional donations. All luxuries, such as fancy cars, expensive clothes, and the like should be avoided as well. Any "luxury" or "commodity" acquired out of some desire rather than merely to fulfill a necessity is a dangerous trap--a lure back into the closed, greedy society that true knights are committed to changing. Furthermore, many people will donate to such a worthy order if they are convinced of the sincerity of its followers. Besides a vow of poverty and subsequent lifestyle, knights should also practice selflessness. What I mean by this is that these knights should not be concerned about pride and winning admiration, but rather about acting in all ways selflessly, with humility. A knight should act in such a way as to always benefit others, whether that be in the form of coding or informing others about the movement. This will be best achieved if they come together to elect experienced people to direct their activities. Many folks new to FS are confused about a number of important tenants of the movement, and may resist. For example, an apprentice knight (i.e., a "squire") might still find it "necessary" to use Internet Explorer or to continue to buy and own frivolous items. This behavior would conflict with the code, and these squires would need to understand that even though they still think such things are acceptable, for the sake of the movement, they will cease them as long as they wish to retain their knight status. The idea here is that once they realize they really don't "need" such things, it won't be a problem to continue avoiding them. The final vow is to make every effort, whenever possible, to inform and challenge others who do not live in accordance to these principles. This should never be done in a violent or insulting way, but only in a helpful, informative and dialectical manner. For instance, if someone is seen using Internet Explorer, the knight should ask, "Why are you using that program?" and from there, very patiently, attempt to lead the person to the better way. This same tendency can be applied to other situations. For instance, if a person owns a gas-guzzling SUV, or is contemplating buying one, or is simply interested in acquiring wealth, the knight should engage in another round of questioning and debates (with an eye towards helping the person discover the truth). "Why do you desire to buy a vehicle that will drain your resources and destroy the environment you live in?" "Why do you desire more money than you need to survive?" With enough effort, the person can be shown that they are merely enslaved to their own foolish desire for wealth and envy, and if they really want to be free, they will learn to control these irrational impulses. My contention is that if there were a movement that really embraced these principles, it would have a much greater impact on the world and society. People would eventually become impressed by the lifestyle of these Knights of Free Software and likely become much more sympathetic to the movement. Of course, these knights might also be exposed to much ridicule and hatred, but their cool reserve and compassion for even those who hate them will only boost them in the eyes of others.
Python
UTF-8
472
3.703125
4
[]
no_license
def binary_search(number_list, number): first = 0 last = len(number_list) - 1 number_found = False while first <= last and not number_found: middle = (first + last) / 2 if number_list[middle] == number: number_found = True else: if number < number_list[middle]: last = middle-1 else: first = middle+1 return number_found binary_search([0, 1, 2, 3, 4, 5, 6, 8, 9, 10], 3)
Go
UTF-8
1,248
2.8125
3
[]
no_license
package cache import ( "gopkg.in/redis.v4" "testing" ) const ( largeSize = 4234987444 ) func TestSet(t *testing.T) { redisClient := redis.NewClient(&redis.Options{Addr: "localhost:6379", Password: "", DB: 13}) subject := RedisMetadataStore{redisClient} if err := subject.Set("key", &Metadata{"text/html", largeSize}); err != nil { t.Error("Cannot set Redis key") } metadata, err := subject.Get("key") if err != nil { t.Fatal("Cannot retrieve Redis key") } t.Log("Metadata retrieved:", metadata, err) if metadata.Size != largeSize || metadata.ContentType != "text/html" { t.Error("Wrong Metadata retrieved:", metadata) } redisClient.FlushDb() } func TestSetNonNumericSize(t *testing.T) { redisClient := redis.NewClient(&redis.Options{Addr: "localhost:6379", Password: "", DB: 13}) subject := RedisMetadataStore{redisClient} redisClient.HMSet("key", map[string]string{ "ContentType": "text/html", "Size": "notanumber", }) metadata, err := subject.Get("key") if err != nil { t.Fatal("Cannot retrieve Redis key") } t.Log("Metadata retrieved:", metadata, err) if metadata.Size != largeSize || metadata.ContentType != "text/html" { t.Error("Wrong Metadata retrieved:", metadata) } redisClient.FlushDb() }
Python
UTF-8
7,569
3.546875
4
[]
no_license
from classes.Piece import Piece from classes.Queen import Queen class Pawn(Piece): def create(self, id, color, position): self.id = id self.type = "Pawn" self.color = color self.position = position self.isCaptured = False #print("Creating " + self.color + " " + self.type) def getID(self): return self.id def giveMoveList(self, board): moveList = [] possible_column = self.position[1] # The column in which the pawn can move if(self.getColor() == "white"): # The white pawn has moved all the way to the last row and cannot move any more if(self.position[0] == 7): print("Update white pawn to queen") return moveList # The white pawn has moved before and can only move forward one position elif(self.position[0] <= 6 and self.position[0] > 1): possible_row_1 = self.position[0] + 1 if (board.getPiece(possible_row_1,possible_column) is None): # If one space in front of the pawn is empty is can move there moveList.append([possible_row_1, possible_column]) return moveList # The white pawn has not moved before and can move forward one or two spaces if they are empty elif(self.position[0] == 1): possible_row_1 = self.position[0] + 1 possible_row_2 = self.position[0] + 2 if (board.getPiece(possible_row_1,possible_column) is None): # If one space in front of the pawn is empty is can move there moveList.append([possible_row_1, possible_column]) if (board.getPiece(possible_row_2,possible_column) is None): # If one space in front of the pawn is empty and the second one is empty as well it can move there moveList.append([possible_row_2, possible_column]) return moveList elif(self.getColor() == "black"): # The black pawn has moved all the way to the first row and cannot move any more if (self.position[0] == 0): print("Update black pawn to queen") return moveList # The black pawn has moved before and can only move forward one position elif (self.position[0] >= 1 and self.position[0] < 6): possible_row_1 = self.position[0] - 1 if (board.getPiece(possible_row_1,possible_column) is None): # If one space in front of the pawn is empty is can move there moveList.append([possible_row_1, possible_column]) return moveList # The black pawn has not moved before and can move forward one or two spaces if they are empty elif (self.position[0] == 6): possible_row_1 = self.position[0] - 1 possible_row_2 = self.position[0] - 2 if (board.getPiece(possible_row_1,possible_column) is None): # If one space in front of the pawn is empty is can move there moveList.append([possible_row_1, possible_column]) if (board.getPiece(possible_row_2,possible_column) is None): # If one space in front of the pawn is empty and the second one is empty as well it can move there moveList.append([possible_row_2, possible_column]) return moveList def giveCaptureList(self,board): captureList = [] if (self.getColor() == "white"): if (self.position[0] == 7): return captureList possible_row = self.position[0] + 1 # The white pawn is in the first column and can only capture pieces that are in the column to its right if(self.position[1] == 0): possible_column_1 = 1 if(board.getPiece(possible_row,possible_column_1) is not None and board.getPiece(possible_row,possible_column_1).getColor() == "black"): captureList.append([possible_row, possible_column_1]) return captureList # The white pawn is in the last column and can only capture pieces that are in the column to its left elif(self.position[1] == 7): possible_column_1 = 6 if (board.getPiece(possible_row, possible_column_1) is not None and board.getPiece(possible_row, possible_column_1).getColor() == "black"): captureList.append([possible_row, possible_column_1]) return captureList else: possible_column_1 = self.position[1] - 1 possible_column_2 = self.position[1] + 1 if (board.getPiece(possible_row, possible_column_1) != None and board.getPiece(possible_row, possible_column_1).getColor() == "black"): captureList.append([possible_row, possible_column_1]) if (board.getPiece(possible_row, possible_column_2) != None and board.getPiece(possible_row, possible_column_2).getColor() == "black"): captureList.append([possible_row, possible_column_2]) return captureList elif(self.getColor() == "black"): if (self.position[0] == 0): return captureList possible_row = self.position[0] - 1 # The black pawn is in the first column and can only capture pieces that are in the column to its right if (self.position[1] == 0): possible_column_1 = 1 if (board.getPiece(possible_row, possible_column_1) != None and board.getPiece(possible_row, possible_column_1).getColor() == "white"): captureList.append([possible_row, possible_column_1]) return captureList # The black pawn is in the last column and can only capture pieces that are in the column to its left elif (self.position[1] == 7): possible_column_1 = 6 if (board.getPiece(possible_row, possible_column_1) != None and board.getPiece(possible_row, possible_column_1).getColor() == "white"): captureList.append([possible_row, possible_column_1]) return captureList else: possible_column_1 = self.position[1] - 1 possible_column_2 = self.position[1] + 1 if (board.getPiece(possible_row, possible_column_1) != None and board.getPiece(possible_row, possible_column_1).getColor() == "white"): captureList.append([possible_row, possible_column_1]) if (board.getPiece(possible_row, possible_column_2) != None and board.getPiece(possible_row, possible_column_2).getColor() == "white"): captureList.append([possible_row, possible_column_2]) return captureList #check whether a black or white piece is on the opposite side of the board, enabling it to be promoted def able_to_promote(self): if(self.getColor() == "white" and self.position[0] == 7): return True if(self.getColor() == "black" and self.position[0] == 0): return True return False #promotes the pawn to a Queen, with all of the same properties, except with a "Q" added to the end ID to indicate a promoted pawn def promotion(self): queen_to_return = Queen() queen_to_return.create(self.getID() + "Q", self.getColor(), self.position) return queen_to_return
C++
UTF-8
7,845
2.5625
3
[ "MIT" ]
permissive
#include "GameEngineMain.h" #include <assert.h> #include <thread> #include <chrono> #include <iostream> #include <SFML/Graphics.hpp> #include "Util/TextureManager.h" #include "Util/AnimationManager.h" #include "Util/ButtonManager.h" #include "Util/CameraManager.h" using namespace GameEngine; float GameEngineMain::WINDOW_HEIGHT = 500; float GameEngineMain::WINDOW_WIDTH = 500; //Nullptr init for singleton class GameEngineMain* GameEngineMain::sm_instance = nullptr; sf::Clock GameEngineMain::sm_deltaTimeClock; sf::Clock GameEngineMain::sm_gameClock; std::vector<Entity*> GameEngineMain::s_emptyEntityTagList; GameEngineMain::GameEngineMain() : m_renderTarget(nullptr) , m_gameBoard(nullptr) , m_windowInitialised(false) { CreateAndSetUpWindow(); //Load predefined textures TextureManager::GetInstance()->LoadTextures(); //Create predefined animation definition vector AnimationManager::GetInstance()->InitStaticGameAnimations(); CameraManager::GetInstance()->GetCameraView().setCenter(sf::Vector2f(WINDOW_WIDTH / 2.f, WINDOW_HEIGHT / 2.f)); CameraManager::GetInstance()->GetCameraView().setSize(sf::Vector2f(WINDOW_WIDTH, WINDOW_HEIGHT)); } GameEngineMain::~GameEngineMain() { delete m_renderTarget; } void GameEngineMain::OnInitialised() { //Engine is initialised, this spot should be used for game object and clocks initialisation m_gameBoard = new Game::GameBoard(); sm_deltaTimeClock.restart(); sm_gameClock.restart(); } void GameEngineMain::CreateAndSetUpWindow() { m_renderWindow = new sf::RenderWindow(sf::VideoMode((unsigned int)WINDOW_WIDTH, (unsigned int)WINDOW_HEIGHT), "Hack The North"); m_renderTarget = m_renderWindow; } void GameEngineMain::AddEntity(Entity* entity) { auto found = std::find(m_entities.begin(), m_entities.end(), entity); assert(found == m_entities.end()); //Drop an assert if we add duplicate; if (found == m_entities.end()) { m_entitiesToAdd.push_back(entity); } } void GameEngineMain::RemoveEntity(Entity* entity) { { auto found = std::find(m_entitiesToAdd.begin(), m_entitiesToAdd.end(), entity); if (found != m_entitiesToAdd.end()) { m_entitiesToAdd.erase(found); return; } } auto found = std::find(m_entities.begin(), m_entities.end(), entity); if (found == m_entities.end()) { found = std::find(m_entitiesToRemove.begin(), m_entitiesToRemove.end(), entity); assert(found != m_entitiesToRemove.end()); //Drop an assert if we remove a non existing entity (neither on entity list and on entity to remove list); } if (found != m_entities.end()) { m_entitiesToRemove.push_back(entity); entity->OnRemoveFromWorld(); } } void GameEngineMain::RefreshEntityTag(Entity* entity) { if (entity != nullptr && entity->HasEntityTag()) { const std::string& entityTag = entity->GetEntityTag(); std::vector<Entity*>& tagList = m_entityTagMap[entityTag]; tagList.push_back(entity); } } void GameEngineMain::RemoveEntityTagFromMap(Entity* entity, std::string tag) { bool hasFoundEntity = false; if (entity != nullptr) { auto tagListIt = m_entityTagMap.find(tag); if (tagListIt != m_entityTagMap.end()) { std::vector<Entity*>& tagList = (*tagListIt).second; auto tagEntityIt = std::find(tagList.begin(), tagList.end(), entity); if (tagEntityIt != tagList.end()) { tagList.erase(tagEntityIt); if (tagList.empty()) { m_entityTagMap.erase(tagListIt); } hasFoundEntity = true; } } } assert(hasFoundEntity); //Trying to remove an entity tag from the map that doesn't exist! Call Entity::ClearEntityTag instead! } std::vector<Entity*> GameEngineMain::GetEntitiesByTag(std::string tag) { auto it = m_entityTagMap.find(tag); if (it == m_entityTagMap.end()) { std::vector<Entity*> emptyVec; return emptyVec; } return it->second; } void GameEngineMain::Update() { //First update will happen after init for the time being (we will add loading later) if (!m_windowInitialised) { m_windowInitialised = true; OnInitialised(); } RemovePendingEntities(); UpdateWindowEvents(); if (m_gameBoard) m_gameBoard->Update(); UpdateEntities(); RenderEntities(); AddPendingEntities(); //We pool last delta and will pass it as GetTimeDelta - from game perspective it's more important that DT stays the same the whole frame, rather than be updated halfway through the frame m_lastDT = sm_deltaTimeClock.getElapsedTime().asSeconds(); sm_deltaTimeClock.restart(); } void GameEngineMain::AddPendingEntities() { for (int a = 0; a < m_entitiesToAdd.size(); ++a) { m_entities.push_back(m_entitiesToAdd[a]); m_entitiesToAdd[a]->OnAddToWorld(); } m_entitiesToAdd.clear(); } void GameEngineMain::RemovePendingEntities() { for (int a = 0; a < m_entitiesToRemove.size(); ++a) { Entity* entity = m_entitiesToRemove[a]; auto found = std::find(m_entities.begin(), m_entities.end(), entity); assert(found != m_entities.end()); if (found != m_entities.end()) { m_entities.erase(found); delete entity; } } m_entitiesToRemove.clear(); } void GameEngineMain::UpdateWindowEvents() { if (!m_renderWindow) return; sf::Event event; while (m_renderWindow->pollEvent(event)) { if (event.type == sf::Event::Closed) { m_renderWindow->close(); m_renderTarget = nullptr; break; } if (event.type == sf::Event::MouseButtonPressed) { ButtonManager::GetInstance()->OnMouseButtonPressedEvent(event.mouseButton.x, event.mouseButton.y); } } } void GameEngineMain::UpdateEntities() { //Update que for (auto entity : m_entities) { entity->Update(); } } void GameEngineMain::RenderEntities() { if (!m_renderTarget) return; //Here we use a windowRender target - it's more than enough for provided example, but in more complex versions this could end up flickering on the screen //If that is the case - one could try to implement doubleBuffer functionality, where the render target is a TEXTURE in memory and objects render there //And only at the last bit we render the prepared texture on the window. m_renderTarget->clear(); //The VIEW is the way to control what renders in the window in a very convenient way - view does not modify the local coordinates, but rather than that it defines the rectangle that the window //Is supposed to render - by default our camera manager is not doing anything, as it was not needed in bird implementation, but it can be set to follow the player (by modifying the IsFollow enabled static return) //If that setting is on, PlayerCamera component will update the camera position to player position - making our camera center on player entity //With that test setting on, our bird implementation changes a bunch of rules, just so we can test it easilly m_renderTarget->setView(CameraManager::GetInstance()->GetCameraView()); //Render que std::vector<RenderComponent*> renderers; //Every entity that has RenderComponent, or a component that extends RenderComponent - should end up in a render que for (auto entity : m_entities) { std::vector<RenderComponent*> renderComponents = entity->GetAllComponents< RenderComponent >(); if (!renderComponents.empty()) { renderers.insert(renderers.end(), renderComponents.begin(), renderComponents.end()); } } // sort using a lambda expression // We sort entities according to their Z level, meaning that the ones with that value lower will be draw FIRST (background), and higher LAST (player) std::sort(renderers.begin(), renderers.end(), [](RenderComponent* a, RenderComponent* b) { return a->GetZLevel() < b->GetZLevel(); }); for (auto renderer : renderers) { renderer->Render(m_renderTarget); } if (m_renderWindow && m_renderWindow->isOpen()) { m_renderWindow->display(); } }
Python
UTF-8
1,309
2.53125
3
[ "MIT" ]
permissive
import matplotlib matplotlib.use('TKAgg') import matplotlib.pyplot as plt import sys sys.path.append('..') import eccentricPre as SN import pandas as pd import numpy as np import astropy.units as units inputs = 50 Mcomp = 20 #np.random.choice(a=range(3,21), size=50, replace=false) Mhe = 5 #np.random.choice(a=range(3,10), size=50, replace=false) ap = np.linspace(20, 70, inputs) ep = np.linspace(0.0, 0.5, inputs) apx, epy = np.meshgrid(ap, ep) Apre = apx.flatten() epre = epy.flatten() nk = 100 data = [] df = pd.DataFrame() for i in range(inputs**2): sys = SN.System(Mcomp, Mhe, Apre[i], epre[i], nk) sys.SN() for n in range(nk): data.append({'Apre': sys.Apre[n], 'Apost': sys.Apost[n], 'epre': sys.epre[n], 'oldSNflag1': sys.oldSNflag1[n], 'SNflag1': sys.SNflag1[n], 'SNflag2': sys.SNflag2[n], 'SNflag3': sys.SNflag3[n], 'SNflag4': sys.SNflag4[n], 'SNflag5': sys.SNflag5[n], 'SNflag6': sys.SNflag6[n], 'SNflag7': sys.SNflag7[n], 'SNflags': np.all([item[n] for item in sys.SNflags])}) df = pd.DataFrame(data) pdf = df #[df['SNflag4'] == 1] print pdf['Apre'] print df['Apre'] plt.hist2d(pdf['Apre']*units.m.to(units.R_sun)/pdf['Apost']*units.m.to(units.R_sun), pdf['epre'], bins=(50,50), cmap='viridis') plt.colorbar() plt.xlabel('ApreSN/ApostSN') plt.ylabel('EpreSN') plt.show()
Python
UTF-8
236
2.78125
3
[]
no_license
from AOC import read_input from string import ascii_letters inp = read_input() c = 0 for i in inp.strip().split('\n'): l = len(i) c1, c2 = set(i[:l//2]), set(i[l//2:]) c += ascii_letters.index(list(c1 & c2)[0])+1 print(c)
Python
UTF-8
388
3.578125
4
[]
no_license
#import a memory_profiler module from memory_profiler import profile #Using a for loop @profile def my_func(): a = range(1000) b = [] for i in a: b.append(i * 2) return b #using list to illustrate the memory usage @profile def my_second(): a = range(1000) b = [i * 2 for i in a] return b if __name__ == '__main__': my_func() my_second()
Markdown
UTF-8
1,734
2.578125
3
[]
no_license
# Course project Neobis course project was created as part of our study plan, using django and django rest framework. ## Getting Started These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system. ### Prerequisites Pipenv package manager is required for creating virtual environment ``` pip install pipenv ``` ### Installing Install all the requirements ``` pipenv install -r requirements.txt ``` Run your virtual environment ``` pipenv shell ``` ### Documentation Documentation was made by swagger and OpenAPI 2.0 and available locally on localhost:8000/ ## Running the tests To run tests use ``` $python manage.py test ``` ### Coverage You also can use coverage to run tests and get report of how much of your code has been covered with tests To run tests with coverage ``` $python coverage run manage.py test -v 2 ``` Get results in terminal ``` $python coverage report ``` Get results in a html format. Later you can see your results in browser and get more detailed information about test coverage ``` $python coverage html ``` ## Deployment Project do not have any web server and proxy server configuration,so you can choose what ever option you want. (recomended gunicorn as web server and nginx as reverse proxy because of ease and speed of configuration) ## Built With * [Django](https://www.djangoproject.com/) - The web framework used * [Django REST framework](https://www.django-rest-framework.org/) - The REST framework for django ## Authors * **Daniiar Mukash uulu** - [Daniiarz](https://github.com/Daniiarz) ## License There is no license for this project :(
JavaScript
UTF-8
4,681
3
3
[]
no_license
// // BOTER, KAAS EN EIEREN RULESET // exports.gameMove = function(globalGameState, room, move) { var player = globalGameState[room]["init"][globalGameState[room]["users"][globalGameState[room]["active"]]]; var gamestate = JSON.parse(globalGameState[room]["gamestate"]); if (ruleSet(move, gamestate)) { gamestate[move[0]][move[1]] = player; } else { globalGameState[room]["count"]-- } globalGameState[room]["result"] = winCon(gamestate, globalGameState[room]["active"]); gamestate = JSON.stringify(gamestate); globalGameState[room]["gamestate"] = gamestate; } exports.gameInit = function(globalGameState, room) { var users = {} users[globalGameState[room]["users"][globalGameState[room]["active"]]] = "X" if (globalGameState[room]["active"] == 0) { var active = [globalGameState[room]["active"]]; active++; users[globalGameState[room]["users"][active]] = "O"; } else { var active = [globalGameState[room]["active"]]; active--; users[globalGameState[room]["users"][active]] = "O"; } return users; } exports.gameEnd = function(socket, room, globalGameState, server) { globalGameState[room]["winner"] = socket.username; if(globalGameState[room]["active"] === -1) { server.in(room).emit('game result', globalGameState[room]["result"][2]); server.in(room).emit('game result', globalGameState[room]["result"][3]); server.in(room).emit('game result', globalGameState[room]["result"][4]); } else { socket.to(room).emit('game loss', globalGameState[room]["result"][2]); socket.to(room).emit('game loss', globalGameState[room]["result"][3]); socket.to(room).emit('game loss', globalGameState[room]["result"][4]); socket.emit('game win', globalGameState[room]["result"][2]); socket.emit('game win', globalGameState[room]["result"][3]); socket.emit('game win', globalGameState[room]["result"][4]); } } function ruleSet(move, gamestate) { // RULE: Can't overwrite used space if (gamestate[move[0]][move[1]] === 0) { return 1 } else { return 0 } } function winCon(gamestate, user) { var breaches = []; // Win condition if (gamestate[0][0] == gamestate[0][1] && gamestate[0][1] == gamestate[0][2] && gamestate[0][0] != 0) { breaches.push("gameEnd"); breaches.push("winner = " + user) breaches.push("00") breaches.push("01") breaches.push("02") } else if (gamestate[1][0] == gamestate[1][1] && gamestate[1][1] == gamestate[1][2] && gamestate[1][0] != 0) { breaches.push("gameEnd"); breaches.push("winner = " + user) breaches.push("10") breaches.push("11") breaches.push("12") } else if (gamestate[2][0] == gamestate[2][1] && gamestate[2][1] == gamestate[2][2] && gamestate[2][0] != 0) { breaches.push("gameEnd"); breaches.push("winner = " + user) breaches.push("20") breaches.push("21") breaches.push("22") } else if (gamestate[0][0] == gamestate[1][0] && gamestate[1][0] == gamestate[2][0] && gamestate[2][0] != 0) { breaches.push("gameEnd"); breaches.push("winner = " + user) breaches.push("00") breaches.push("10") breaches.push("20") } else if (gamestate[0][1] == gamestate[1][1] && gamestate[1][1] == gamestate[2][1] && gamestate[0][1] != 0) { breaches.push("gameEnd"); breaches.push("winner = " + user) breaches.push("01") breaches.push("11") breaches.push("21") } else if (gamestate[0][2] == gamestate[1][2] && gamestate[1][2] == gamestate[2][2] && gamestate[2][2] != 0) { breaches.push("gameEnd"); breaches.push("winner = " + user) breaches.push("02") breaches.push("12") breaches.push("22") } else if (gamestate[0][0] == gamestate[1][1] && gamestate[1][1] == gamestate[2][2] && gamestate[0][0] != 0) { breaches.push("gameEnd"); breaches.push("winner = " + user) breaches.push("00") breaches.push("11") breaches.push("22") } else if (gamestate[0][2] == gamestate[1][1] && gamestate[1][1] == gamestate[2][0] && gamestate[2][0] != 0) { breaches.push("gameEnd"); breaches.push("winner = " + user) breaches.push("02") breaches.push("11") breaches.push("20") } // Game full: End condition if (gamestate[0].indexOf(0) >= 0 || gamestate[1].indexOf(0) >= 0 || gamestate[2].indexOf(0) >= 0) { } else { breaches.push("gameFull"); } return breaches; }
Ruby
UTF-8
1,465
3.265625
3
[ "Ruby" ]
permissive
# Author:: Michael J. Bruderer # Copyright:: March 2009 # License:: Ruby License # Email: ojos@gmx.ch begin require 'rubygems' require 'chronic' require 'date' $CHRONIC_INSTALLED=true rescue LoadError $CHRONIC_INSTALLED=false end class Newtodos @todo_string = '' def initialize s='' $stderr.print "Warning: chronic gem not installed - you can not add new todos\n" msg = self.extract_msg(s) tags = self.extract_tags(s) date = extract_date(s) @todo_string = "\n#{date} #{tags} #{msg}" end def extract_msg(s) reg = /"(.*)"/ res = s.scan(reg) res.to_s end def extract_date(s) s.sub!(/"(.*)"/, '') s.sub!(/\[(.*)\]/, '') s.tr!('.','/') split = s.split(/\//) # splits string on / if split.length == 0 s elsif split.length == 2 s = [split[1], split[0]].join("/") # US format date elsif split.length == 3 s = [split[1], split[0], split[2]].join("/") # US format date end european_date = '%d/%m/%Y' date = Chronic.parse(s).strftime(european_date) end def extract_tags(s) reg = /\[.*\]/ res = s.scan(reg) if res.length == 0 res = "[soon]" end res end def to_s @todo_string end def add_to_file(todofile) if todofile.class == 'Array' infile = todofile[0] else infile = todofile end f = File.open(infile, 'a') f.write(@todo_string) f.close puts "Added: "+@todo_string end end
Python
UTF-8
938
3.484375
3
[ "Apache-2.0" ]
permissive
class Solution: # @param A: An integers list. # @return: return any of peek positions. def findPeak(self, A): if not A: return -1 l, r = 0, len(A) - 1 while l + 1 < r: # 取中点位置 mid = l + int((r - l) / 2) # 判断中点位置左右情况 # 左>中,峰在左 if A[mid] < A[mid - 1]: r = mid elif A[mid] < A[mid + 1]: # 右>中,峰在右 l = mid else: # 此时的mid比左右元素均大 return mid # 单峰,谁大谁返回 mid = l if A[l] > A[r] else r return mid print('<iframe src="//player.bilibili.com/player.html?aid=796280508&bvid=BV1MC4y1h7BR&cid=209622032&page=1" scrolling="no" border="0" frameborder="no" framespacing="0" allowfullscreen="true"> </iframe>') s = Solution() print(s.findPeak([4, 5, 3,2,1]))
Java
UTF-8
3,679
3.203125
3
[]
no_license
/* Provides an abstracted version of a client. This class handles anything related */ package client; //Socket Class import java.net.Socket; import java.awt.image.BufferedImage; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.PrintWriter; import java.net.UnknownHostException; import java.util.Scanner; import javax.imageio.ImageIO; import shared.StatusCode; public class Client { //Private variables private String host; private int port; private Socket sock; private PrintWriter out; private BufferedReader in; /** * Creates a socket to h on port p * @param h (String) Hostname or IP Address of server * @param p (int) Port number to connect on * @throws UnknownHostException * @throws IOException */ public Client(String h, int p) throws UnknownHostException, IOException { host = h; port = p; sock = new Socket(host, port); out = new PrintWriter(sock.getOutputStream()); in = new BufferedReader(new InputStreamReader(sock.getInputStream())); //Specify a timeout of one minute sock.setSoTimeout(3600 * 1000); //Check for connection (through SOCK_CONNECT) String s = read(); StatusCode r = StatusCode.valueOf(s); if (r.statusCode == StatusCode.SOCK_CONNECT.statusCode) { System.out.println("Connected to server!"); } } /** * Close the current connection to a client * @throws IOException */ public void closeConnection() throws IOException { sock.close(); } /** * * @param cmd (String) Command to send to server * @return (StatusCode) representing the response from server. Defaults to StatusCode.NO_OPERATION * @throws IOException * @throws ClassNotFoundException */ public StatusCode sendCommand(String cmd) throws IOException, ClassNotFoundException { StatusCode s = StatusCode.NO_OPERATION; ObjectInputStream ois = null; if (sock.isConnected() && cmd.length() > 0) { //Client wants a screenshot if (cmd.substring(0, 3).equalsIgnoreCase("REQ")) { //Now prepare the object stream ois = new ObjectInputStream(sock.getInputStream()); //Send the regular command } out.println(cmd); out.flush(); if (ois != null) { Scanner reader = new Scanner(System.in); System.out.println("What is the name of the file to save the screenshot to (w/o extension)?"); String fileName = reader.nextLine(); fileName += ".png"; Object obj = ois.readObject(); if (obj instanceof BufferedImage) { BufferedImage ico = (BufferedImage) obj; ImageIO.write(ico, "png", new File(fileName)); } } } System.out.println("Sent command. Waiting for response"); String returnStatus = read(); System.out.println(returnStatus); if (returnStatus == null) { System.err.println("There was a problem reading the response. Closing connection."); } else { s = StatusCode.valueOf(returnStatus); if (s.statusCode == StatusCode.SOCK_DISCONNECT.statusCode) { sock.close(); } } return s; } /** * Returns the hostname/IP address of the remote host * @return (String) hostname/IP address of the remote host */ public String getHost() { return host; } /** * Gets the status of the connection * @return (boolean) True if connected, false if not */ public boolean isConnected() { return sock.isConnected(); } public String read() throws IOException { String s = in.readLine(); return s; } }
JavaScript
UTF-8
2,992
3.5
4
[]
no_license
class TypeWriter { constructor(txtElement, words, wait = 3000) { this.txtElement = txtElement; this.words = words; this.txt = ""; this.wordIndex = 0; this.wait = parseInt(wait, 10); this.type(); this.isDeleting = false; } type() { // Current index of word const current = this.wordIndex % this.words.length; // Get full text of current word const fullTxt = this.words[current]; // Check if deleting if (this.isDeleting) { // Remove char this.txt = fullTxt.substring(0, this.txt.length - 1); } else { // Add char this.txt = fullTxt.substring(0, this.txt.length + 1); } // Insert txt into element this.txtElement.innerHTML = `<span class="txt">${this.txt}</span>`; // Initial Type Speed let typeSpeed = 300; if (this.isDeleting) { typeSpeed /= 2; } // If word is complete if (!this.isDeleting && this.txt === fullTxt) { // Make pause at end typeSpeed = this.wait; // Set delete to true this.isDeleting = true; } else if (this.isDeleting && this.txt === "") { this.isDeleting = false; // Move to next word this.wordIndex++; // Pause before start typing typeSpeed = 500; } setTimeout(() => this.type(), typeSpeed); } } // Init On DOM Load document.addEventListener("DOMContentLoaded", init); // document.addEventListener("DOMContentLoaded", startCounting); window.addEventListener("scroll", checkCountdown); // Init App function init() { const txtElement = document.querySelector(".txt-type"); const words = JSON.parse(txtElement.getAttribute("data-words")); const wait = txtElement.getAttribute("data-wait"); // Init TypeWriter new TypeWriter(txtElement, words, wait); } const counters = document.querySelectorAll(".counter"); let wasCounted = false; function checkCountdown() { if (!wasCounted) { const triggerBottom = (window.innerHeight / 5) * 4; counters.forEach((counter) => { const boxTop = counter.getBoundingClientRect().top; if (boxTop < triggerBottom) { startCounting(); wasCounted = true; } }); } } function startCounting() { counters.forEach((counter) => { counter.innerText = "0"; const updateCounter = () => { const target = +counter.getAttribute("data-target"); const c = +counter.innerText; const increment = target / 1000; if (c < target) { counter.innerText = `${Math.ceil(c + increment)}`; setTimeout(updateCounter, 1); } else { counter.innerText = target; } }; updateCounter(); }); }
Java
UTF-8
3,691
2.078125
2
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * IzPack - Copyright 2001-2020 The IzPack project team. * All Rights Reserved. * * http://izpack.org/ * * 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 com.izforge.izpack.core.rules.process; import com.izforge.izpack.api.adaptator.IXMLElement; import com.izforge.izpack.api.adaptator.IXMLParser; import com.izforge.izpack.api.adaptator.impl.XMLParser; import com.izforge.izpack.api.data.AutomatedInstallData; import com.izforge.izpack.api.data.InstallData; import com.izforge.izpack.api.rules.RulesEngine; import com.izforge.izpack.core.container.DefaultContainer; import com.izforge.izpack.core.data.DefaultVariables; import com.izforge.izpack.core.rules.ConditionContainer; import com.izforge.izpack.core.rules.RulesEngineImpl; import com.izforge.izpack.util.Platforms; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class JavaConditionTest { public static final boolean CONSTANT_VALUE = true; public static final Boolean CONSTANT_OBJECT_VALUE = Boolean.TRUE; public static void conditionMethodWithArgument(String someArgument) { } public static String conditionMethodWithNonBooleanResult() { return "true"; } public static boolean conditionMethodFailing() { throw new RuntimeException(); } public static boolean conditionMethodPrimitiveResult() { return true; } public static Boolean conditionMethod() { return Boolean.TRUE; } @Test public void testJavaConditions() { RulesEngine rules = createRulesEngine(new AutomatedInstallData(new DefaultVariables(), Platforms.UNIX)); IXMLParser parser = new XMLParser(); IXMLElement conditions = parser.parse(getClass().getResourceAsStream("javaconditions.xml")); rules.analyzeXml(conditions); assertFalse(rules.isConditionTrue("java0")); // class does not exist assertFalse(rules.isConditionTrue("java1")); // field does not exist assertTrue(rules.isConditionTrue("java2")); // access to simple boolean field assertTrue(rules.isConditionTrue("java3")); // access to boolean object field assertFalse(rules.isConditionTrue("java4")); // method does not exist assertFalse(rules.isConditionTrue("java5")); // method has arguments assertFalse(rules.isConditionTrue("java6")); // method has non boolean return type assertFalse(rules.isConditionTrue("java7")); // method invocation fails assertTrue(rules.isConditionTrue("java8")); // simple boolean return value assertTrue(rules.isConditionTrue("java9")); // boolean object return value } /** * Creates a new {@link RulesEngine}. * * @param installData the installation data * @return a new rules engine */ private RulesEngine createRulesEngine(InstallData installData) { DefaultContainer parent = new DefaultContainer(); RulesEngine rules = new RulesEngineImpl(installData, new ConditionContainer(parent), installData.getPlatform()); parent.addComponent(RulesEngine.class, rules); return rules; } }
C#
UTF-8
854
2.609375
3
[]
no_license
using UnityEngine; using System.Collections; using System; [Serializable] public class Stat { [SerializeField] private Bar bar; [SerializeField] private int maxVal; [SerializeField] private int currentVal; public void LinkBarToObject(GameObject card) { bar = card.GetComponent<Bar>(); } public int CurrentVal { get { return currentVal; } set { this.currentVal = value; bar.Value = currentVal; } } public int MaxVal { get { return maxVal; } set { this.maxVal = value; bar.MaxValue = maxVal; } } public void Initialize(int health) { this.MaxVal = health; this.CurrentVal = health; } }
Python
UTF-8
1,458
3.65625
4
[]
no_license
# 18.03.2019 # br = value/weight # Bir hirsizin cantasinin kapasitesi 40 br class item(object): def __init__(self, n, v, w): self.name = n self.value = v self.weight = w item_1 = item('computer', 200, 20) item_2 = item('clock', 175, 10) item_3 = item('painting', 90, 9) item_4 = item('radio', 20, 4) item_5 = item('vase', 50, 2) item_6 = item('book', 10, 1) item = [item_6, item_5, item_4, item_3, item_2, item_1] max_para = 0 max_agirlik = 20 for k in range(len(item) - 1, -1, -1): # Sondan başlayarak her elemanı dener. agirlik_test = item[k].weight toplam_para = item[k].value i = k while ( max_agirlik >= agirlik_test and i >= 0): # Ağırlığı aşana kadar "k" indisindeki eleman ile kaç para kazanabileceğini hesaplasın. b = i - 1 if (b == 0): break if (agirlik_test == max_agirlik): if (max_para < toplam_para): max_para = toplam_para break elif (agirlik_test < max_agirlik): for dene in range(b, -1, -1): if (agirlik_test + item[dene].weight > 20): continue elif (agirlik_test + item[dene].weight <= 20): agirlik_test += item[dene].weight toplam_para += item[dene].value if (max_para < toplam_para): max_para = toplam_para i -= 1 print(max_para)
Shell
UTF-8
4,298
3.75
4
[ "MIT" ]
permissive
#!/usr/bin/env bash set -e INTERACTIVE=${INTERACTIVE:-"yes"} BUILD_IMAGE=${BUILD_IMAGE:-"no"} COM=$@ PORTS=${PORTS:-"8002-8010"} export PORTS=${PORTS:-"8002-8010"} CONTAINER_PORTS=${PORTS} export CONTAINER_PORTS=${PORTS} FOLDER_NAME=${PWD##*/} PROJECT_NAME=${FOLDER_NAME} export FOLDER_NAME=${PWD##*/} if [ "${INTERACTIVE}" = "yes" ]; then INTERACTIVE="i" else INTERACTIVE="" fi if [ "${COM}" != "b" ]; then PORTS="8002-8010" export PORTS="8002-8010" CONTAINER_PORTS="8001" export CONTAINER_PORTS="8001" fi VOLUME_OPTIONS="" case "$(uname)" in Darwin) VOLUME_OPTIONS=":delegated" ;; esac command -v docker >/dev/null 2>&1 || { echo >&2 "I require docker but it's not installed. Aborting."; exit 1; } command -v docker-compose >/dev/null 2>&1 || { echo >&2 "I require docker-compose but it's not installed. Aborting."; exit 1; } WS_CWD=$PWD export WS_CWD=$PWD PGID=$(id -g) PUID=$(id -u) export PGID=$(id -g) export PUID=$(id -u) #printf "Running in ${WS_CWD}\n" #printf "Use PUID ${PUID} and PGID ${PGID}\n" function finish { if [ "${COM}" = "b" ] || [ "${COM}" = "bb" ]; then WS_PWD=${WS_PWD:-"${HOME}/.docker-workspace/src/docker-workspace"} cd ${WS_PWD}-${PROJECT_NAME} echo $WS_PWD > ~/.docker-workspace/debug.log docker-compose -f .docker-compose-${PROJECT_NAME}.yml -f .docker-compose-dev-${PROJECT_NAME}.yml down -v >> ~/.docker-workspace/debug.log docker-sync clean -c .docker-sync-${PROJECT_NAME}.yml >> ~/.docker-workspace/debug.log rm -rf .docker-sync-${PROJECT_NAME}.yml .docker-compose-${PROJECT_NAME}.yml .docker-compose-dev-${PROJECT_NAME}.yml cd ${WS_PWD} rm -rf ${WS_PWD}-${PROJECT_NAME} else docker rm -f ${PROJECT_NAME} fi } trap finish 1 2 3 6 15 docker_sock_volume="" # Check if we have docker on host if [ -S "/var/run/docker.sock" ]; then docker_sock_volume="--volume=/var/run/docker.sock:/var/run/docker.sock" fi # Prepare ssh keys if [ ! -d "$HOME/.ssh" ]; then printf ${red}"You need to setup your ssh keys first."${neutral}"\n" exit 1 fi if [ "$1" = "update" ]; then docker pull phusion/baseimage:0.11 bash -c "$(curl https://raw.githubusercontent.com/travis-south/docker-workspace/master/install?no_cache=$RANDOM)" exit 0 fi #CTR_COMMAND=${COM} #export CTR_COMMAND=${COM} if [ "${BUILD_IMAGE}" = "yes" ] then docker-compose build docker-sync-stack clean fi if [ "${COM}" = "b" ] || [ "${COM}" = "bb" ]; then WS_PWD=${WS_PWD:-"${HOME}/.docker-workspace/src/docker-workspace"} cp -pR ${WS_PWD} ${WS_PWD}-${PROJECT_NAME} cd ${WS_PWD}-${PROJECT_NAME} sed "s/native-osx/native-osx-${PROJECT_NAME}/g" docker-sync.yml > .docker-sync-${PROJECT_NAME}.yml sed "s/native-osx/native-osx-${PROJECT_NAME}/g" docker-compose.yml > .docker-compose-${PROJECT_NAME}.yml sed "s/native-osx/native-osx-${PROJECT_NAME}/g" docker-compose-dev.yml > .docker-compose-dev-${PROJECT_NAME}.yml docker-sync start -c .docker-sync-${PROJECT_NAME}.yml printf "Waiting for volume..." until docker volume ls | grep appcode-native-osx-${PROJECT_NAME}-sync do printf "." sleep 1 done docker-compose -f .docker-compose-${PROJECT_NAME}.yml -f .docker-compose-dev-${PROJECT_NAME}.yml up -d printf "Processing..." until docker-compose -f .docker-compose-${PROJECT_NAME}.yml -f .docker-compose-dev-${PROJECT_NAME}.yml exec app-native-osx-${PROJECT_NAME} /sbin/setuser daker zsh -l 2>/dev/null do printf "." sleep 5 done docker-compose -f .docker-compose-${PROJECT_NAME}.yml -f .docker-compose-dev-${PROJECT_NAME}.yml down -v docker-sync clean -c .docker-sync-${PROJECT_NAME}.yml rm -rf .docker-sync-${PROJECT_NAME}.yml .docker-compose-${PROJECT_NAME}.yml .docker-compose-dev-${PROJECT_NAME}.yml cd ${WS_PWD} rm -rf ${WS_PWD}-${PROJECT_NAME} else docker run --rm -t${INTERACTIVE} \ -v $HOME/.ssh:/home/daker/.ssh \ -v $HOME/.docker-workspace:/home/daker/.docker-workspace \ -v $HOME/.oh-my-zsh:/home/daker/.oh-my-zsh \ -v $HOME/.zshrc:/home/daker/.zshrc \ -v $HOME/.gitconfig:/home/daker/.gitconfig \ -v $(pwd):$(pwd)${VOLUME_OPTIONS} \ -w $(pwd) \ $docker_sock_volume \ --env PGID=$(id -g) --env PUID=$(id -u) \ -p 0.0.0.0:${PORTS}:8001 \ --name ${PROJECT_NAME} \ travissouth/workspace:$(id -u) ${COM} fi
C++
UTF-8
4,488
3.046875
3
[]
no_license
#include "LineSeries.hpp" #include <fstream> #include <random> #include <tuple> #undef min LineSeries::LineSeries(const std::vector<vec2>& line_points, vec4 color) : mLinePoints(line_points), mColor(color) { } void LineSeries::push(const vec2& point) { mLinePoints.push_back(point); } void LineSeries::pop() { assert(mLinePoints.empty() == false); mLinePoints.pop_back(); } auto LineSeries::line(size_t index) -> std::pair<vec2, vec2> { assert(mLinePoints.size() >= 2); return std::make_pair(mLinePoints[index], mLinePoints[index + 1]); } auto LineSeries::line_transform(size_t index, real width) const -> mat4 { auto matrix = mat4(1); const auto end = mLinePoints[index + 1]; const auto start = mLinePoints[index]; const auto vector = end - start; matrix = glm::translate(matrix, vec3(start.x, start.y, 0)); matrix = glm::rotate(matrix, glm::atan(vector.y, vector.x), vec3(0, 0, 1)); matrix = glm::translate(matrix, vec3(0, -width * 0.5f, 0)); matrix = glm::scale(matrix, vec3(glm::length(vector), width, 1)); return matrix; } auto LineSeries::line_transform_with_scale(size_t index, vec2 scale, real width) const -> mat4 { auto matrix = mat4(1); const auto end = mLinePoints[index + 1] * scale; const auto start = mLinePoints[index] * scale; const auto vector = end - start; matrix = glm::translate(matrix, vec3(start.x, start.y, 0)); matrix = glm::rotate(matrix, glm::atan(vector.y, vector.x), vec3(0, 0, 1)); matrix = glm::translate(matrix, vec3(0, -width * 0.5f, 0)); matrix = glm::scale(matrix, vec3(glm::length(vector), width, 1)); return matrix; } auto LineSeries::size() const -> size_t { return mLinePoints.size() - 1; } auto LineSeries::color() const -> vec4 { return mColor; } auto LineSeries::data() -> vec2* { return mLinePoints.data(); } auto LineSeries::random_make(size_t size, real width_limit, real height_limit) -> LineSeries { static std::random_device device; static std::mt19937 engine(0); std::vector<vec2> lines; const auto space = width_limit / static_cast<real>(size); auto height = 0.0f; for (size_t i = 0; i <= size; i++) { lines.push_back({ i * space, height = Utility::clamp( height + std::uniform_real_distribution<real>(-0.5f, 0.5f)(engine) * height_limit * 0.1f, 1.0f, height_limit - 1.0f) }); } const std::uniform_real_distribution<real> gen_color(0.0f, 1.0f); return { lines, vec4(gen_color(engine), gen_color(engine), gen_color(engine), 1.0f) }; } auto LineSeries::read_from_file(const std::string& fileName) -> std::tuple<std::vector<LineSeries>, size_t, size_t> { //1th line: (n) number of line series width height //2nd -> (1 + n) th : ni(number of lines) px0 py0 px1 py1 ... px(n + 1) py(n + 1) red green blue alpha std::ifstream file; size_t nLineSeries = 0; size_t width = 0; size_t height = 0; file.open(fileName); assert(file.is_open() == true); file >> nLineSeries >> width >> height; std::vector<LineSeries> lineSeries(nLineSeries); for (size_t index = 0; index < nLineSeries; index++) file >> lineSeries[index]; file.close(); return std::make_tuple(lineSeries, width, height); } void LineSeries::save_to_file(const std::string& fileName, std::tuple<const std::vector<LineSeries>&, size_t, size_t> data) { std::ofstream file; file.open(fileName); assert(file.is_open() == true); auto& lineSeries = std::get<0>(data); file << lineSeries.size() << " " << std::get<1>(data) << " " << std::get<2>(data) << std::endl; for (auto& lines : lineSeries) file << lines << std::endl; file.close(); } std::istream& operator>>(std::istream& in, LineSeries& lineSeries) { size_t nLines = 0; //first, read the number of lines in >> nLines; //second, read the position of lines lineSeries.mLinePoints.resize(nLines + 1); for (size_t index = 0; index <= nLines; index++) in >> lineSeries.mLinePoints[index].x >> lineSeries.mLinePoints[index].y; //third, read the color of line series return in >> lineSeries.mColor.r >> lineSeries.mColor.g >> lineSeries.mColor.b >> lineSeries.mColor.a; } std::ostream& operator<<(std::ostream& out, const LineSeries& lineSeries) { //first, write the number of lines out << lineSeries.size() << " "; //second, write the position of lines for (auto& point : lineSeries.mLinePoints) out << point.x << " " << point.y << " "; //third, write the color of line series return out << lineSeries.mColor.r << " " << lineSeries.mColor.g << " " << lineSeries.mColor.b << " " << lineSeries.mColor.a; }
Python
UTF-8
133
4
4
[]
no_license
c = input('Enter any alphabet:') vowel = 'aeiouAEIOU' if c in vowel: print(f'{c} is vowel') else: print(f'{c} is consonant')
JavaScript
UTF-8
935
3
3
[]
no_license
function is_object(mixedVar) { return mixedVar instanceof Object; } function isset(obj) { if((typeof obj == 'undefined') || (obj === null) || (obj === "")) { return false; } else { return true; } } var apiJs = { typeRequest: '', urlRequest: '', typeResponse: '', stringParam: '', } apiJs.paramArray = function (param) { if(is_object(param)) { var symb = false; for(var key in param) { if(!symb) { this.stringParam += key + '=' + param[key]; symb = true; } else this.stringParam += '&' + key + '=' + param[key]; }; } } apiJs.ajaxStart = function (callback) { if(isset(this.typeRequest) && isset(this.urlRequest) && isset(this.typeResponse)) { $.ajax ({ type: this.typeRequest, url: this.urlRequest, dataType: this.typeResponse, data: this.stringParam, success: function(response) { eval(callback)(response); } }); } }
SQL
UTF-8
3,040
4.3125
4
[]
no_license
-- # 12-1 객체를 생성, 변경, 삭제하는 데이터 정의어 /* 데이터 정의어(DDL : Data Definition Language)는 데이터베이스 데이터를 보관하고 관리하기 위해 제공되는 여러 객체의 생성, 변경, 삭제 관련 기능을 수행하는 언어이다. 주의사항 사용자 정의어 실행은 COMMIT 효과를 낸다 */ -- # 12-2 테이블을 생성하는 CREATE -- 모든 열의 각 자료형을 정의해서 테이블 생성하기 CREATE TABLE EMP_DDL( EMPNO NUMBER(4), ENAME VARCHAR2(10), JOB VARCHAR2(9), MGR NUMBER(4), HIREDATE DATE, SAL NUMBER(7, 2), COMM NUMBER(7, 2), DEPTNO NUMBER(2) ); DESC EMP_DDL; -- 다른 테이블을 복사하여 테이블 생성하기 CREATE TABLE DEPT_DDL AS SELECT * FROM DEPT; SELECT * FROM DEPT_DDL; -- 다른 테이블의 일부를 복사하여 테이블 생성하기 CREATE TABLE EMP_DDL_30 AS SELECT * FROM EMP WHERE DEPTNO = 30; SELECT * FROM EMP_DDL_30; -- 다른 테이블을 복사하여 테이블 생성하기 CREATE TABLE EMPDEPT_DDL AS SELECT E.EMPNO, E.ENAME, E.JOB, E.MGR, E.HIREDATE, E.SAL, E.COMM, E.DEPTNO, D.DNAME, D.LOC FROM EMP E, DEPT D WHERE 1<>1; SELECT * FROM EMPDEPT_DDL; -- # 12-3 테이블을 변경하는 ALTER -- EMP 테이블 복사하여 EMP_ALTER 테이블 생성하기 CREATE TABLE EMP_ALTER AS SELECT * FROM EMP; -- ALTER 명령어로 HP 열 추가하기 ALTER TABLE EMP_ALTER ADD HP VARCHAR2(20); -- ALTER 명령어로 HP 열 이름을 TEL로 변경하기 ALTER TABLE EMP_ALTER RENAME COLUMN HP TO TEL; -- ALTER 명령어로 EMPNO 열 길이 변경하기 ALTER TABLE EMP_ALTER MODIFY EMPNO NUMBER(5); -- ALTER 명령어로 TEL열 삭제하기 ALTER TABLE EMP_ALTER DROP COLUMN TEL; SELECT * FROM EMP_ALTER; -- # 12-4 테이블 이름을 변경하는 RENAME -- 테이블 이름 변경하기 RENAME EMP_ALTER TO EMP_RENAME; SELECT * FROM EMP_RENAME; -- # 12-5 테이블의 데이터를 삭제하는 TRUNCATE -- EMP_RENAME 테이블의 전체 데이터 삭제하기 TRUNCATE TABLE EMP_RENAME; /* TRUNCATE는 구조만 남겨 놓고 데이터를 전부 삭제하는 것은, DML(Data Manipulation language)의 DELECT 명령어에서 where절을 삭제한 결과가 같다 하지만 TRUNCATE는 데이터 정의어에 포함되므로 자동 커밋이 되는 반면 DELECT는 데이터 조작어에 해당하므로 커밋이나 롤백이 가능하다. */ SELECT * FROM EMP_RENAME; -- # 12-6 테이블을 삭제하는 DROP DROP TABLE EMP_RENAME; -- Q1 CREATE TABLE EMP_HW ( EMPNO NUMBER(4), ENAME VARCHAR2(10), JOB VARCHAR2(9), MGR NUMBER(4), HIREDATE DATE, SAL NUMBER(7,2), COMM NUMBER(7,2), DEPTNO NUMBER(2) ); -- Q2 ALTER TABLE EMP_HW ADD BIGO VARCHAR2(20); -- Q3 ALTER TABLE EMP_HW MODIFY BIGO VARCHAR2(30); -- Q4 ALTER TABLE EMP_HW RENAME COLUMN BIGO TO REMARK; -- Q5 INSERT INTO EMP_HW SELECT EMPNO, ENAME, JOB, MGR, HIREDATE, SAL, COMM, DEPTNO, NULL FROM EMP; -- Q6 DROP TABLE EMP_HW; SELECT * FROM EMP_HW; SELECT sysdate FROM DUAL;
Java
UTF-8
805
2.09375
2
[]
no_license
package blog.vo; public class Likey { private int lokeyNo; private int postNo; private String memberId; private int likeyCk; private String likeyDate; public int getLokeyNo() { return lokeyNo; } public void setLokeyNo(int lokeyNo) { this.lokeyNo = lokeyNo; } public int getPostNo() { return postNo; } public void setPostNo(int postNo) { this.postNo = postNo; } public String getMemberId() { return memberId; } public void setMemberId(String memberId) { this.memberId = memberId; } public int getLikeyCk() { return likeyCk; } public void setLikeyCk(int likeyCk) { this.likeyCk = likeyCk; } public String getLikeyDate() { return likeyDate; } public void setLikeyDate(String likeyDate) { this.likeyDate = likeyDate; } }
C#
UTF-8
44,628
3
3
[ "Apache-2.0" ]
permissive
// Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to You 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. namespace Math3.linear { /// <summary> /// Interface defining field-valued matrix with basic algebraic operations. /// <para> /// Matrix element indexing is 0-based -- e.g., <c>getEntry(0, 0)</c> /// returns the element in the first row, first column of the matrix.</para> /// </summary> /// <typeparam name="T">the type of the field elements</typeparam> public interface FieldMatrix<T> : AnyMatrix where T : FieldElement<T> { /// <summary> /// Get the type of field elements of the matrix. /// </summary> /// <returns>the type of field elements of the matrix.</returns> Field<T> getField(); /// <summary> /// Create a new FieldMatrix(T) of the same type as the instance with /// the supplied row and column dimensions. /// </summary> /// <param name="rowDimension">the number of rows in the new matrix</param> /// <param name="columnDimension">the number of columns in the new matrix</param> /// <returns>a new matrix of the same type as the instance</returns> /// <exception cref="NotStrictlyPositiveException"> if row or column dimension /// is not positive.</exception> FieldMatrix<T> createMatrix(int rowDimension, int columnDimension); /// <summary> /// Make a (deep) copy of this. /// </summary> /// <returns>a copy of this matrix.</returns> FieldMatrix<T> copy(); /// <summary> /// Compute the sum of this and m. /// </summary> /// <param name="m">Matrix to be added.</param> /// <returns><c>this</c> + <c>m</c>.</returns> /// <exception cref="MatrixDimensionMismatchException"> if <c>m</c> is not /// the same size as <c>this</c> matrix.</exception> FieldMatrix<T> add(FieldMatrix<T> m); /// <summary> /// Subtract <c>m</c> from this matrix. /// </summary> /// <param name="m">Matrix to be subtracted.</param> /// <returns><c>this</c> - <c>m</c>.</returns> /// <exception cref="MatrixDimensionMismatchException"> if <c>m</c> is not /// the same size as <c>this</c> matrix.</exception> FieldMatrix<T> subtract(FieldMatrix<T> m); /// <summary> /// Increment each entry of this matrix. /// </summary> /// <param name="d">Value to be added to each entry.</param> /// <returns><c>d</c> + <c>this</c>.</returns> FieldMatrix<T> scalarAdd(T d); /// <summary> /// Multiply each entry by <c>d</c>. /// </summary> /// <param name="d">Value to multiply all entries by.</param> /// <returns><c>d</c> * <c>this</c>.</returns> FieldMatrix<T> scalarMultiply(T d); /// <summary> /// Postmultiply this matrix by <c>m</c>. /// </summary> /// <param name="m">Matrix to postmultiply by.</param> /// <returns><c>this</c> * <c>m</c>.</returns> /// <exception cref="DimensionMismatchException"> if the number of columns of /// <c>this</c> matrix is not equal to the number of rows of matrix /// <c>m</c>.</exception> FieldMatrix<T> multiply(FieldMatrix<T> m); /// <summary> /// Premultiply this matrix by <c>m</c>. /// </summary> /// <param name="m">Matrix to premultiply by.</param> /// <returns><c>m</c> * <c>this</c>.</returns> /// <exception cref="DimensionMismatchException"> if the number of columns of <c>m</c> /// differs from the number of rows of <c>this</c> matrix.</exception> FieldMatrix<T> preMultiply(FieldMatrix<T> m); /// <summary> /// Returns the result multiplying this with itself <c>p</c> times. /// Depending on the type of the field elements, T, instability for high /// powers might occur. /// </summary> /// <param name="p">raise this to power p</param> /// <returns>this^p</returns> /// <exception cref="NotPositiveException"> if <c>p < 0</c></exception> /// <exception cref="NonSquareMatrixException"> if <c>this matrix</c> is not square</exception> FieldMatrix<T> power(int p); /// <summary> /// Returns matrix entries as a two-dimensional array. /// </summary> /// <returns>a 2-dimensional array of entries.</returns> T[][] getData(); /// <summary> /// Get a submatrix. Rows and columns are indicated /// counting from 0 to n - 1. /// </summary> /// <param name="startRow">Initial row index</param> /// <param name="endRow">row index (inclusive)</param> /// <param name="startColumn">Initial column index</param> /// <param name="endColumn">column index (inclusive)</param> /// <returns>the matrix containing the data of the specified rows and columns.</returns> /// <exception cref="NumberIsTooSmallException"> is <c>endRow < startRow</c> of /// <c>endColumn < startColumn</c>.</exception> /// <exception cref="OutOfRangeException"> if the indices are not valid.</exception> FieldMatrix<T> getSubMatrix(int startRow, int endRow, int startColumn, int endColumn); /// <summary> /// Get a submatrix. Rows and columns are indicated /// counting from 0 to n - 1. /// </summary> /// <param name="selectedRows">Array of row indices.</param> /// <param name="selectedColumns">Array of column indices.</param> /// <returns>the matrix containing the data in the /// rows and columns.</returns> /// <exception cref="NoDataException"> if <c>selectedRows</c> or /// <c>selectedColumns</c> is empty</exception> /// <exception cref="NullArgumentException"> if <c>selectedRows</c> or /// <c>selectedColumns</c> is <c>null</c>.</exception> /// <exception cref="OutOfRangeException"> if row or column selections are not valid.</exception> FieldMatrix<T> getSubMatrix(int[] selectedRows, int[] selectedColumns); /// <summary> /// Copy a submatrix. Rows and columns are indicated /// counting from 0 to n-1. /// </summary> /// <param name="startRow">Initial row index.</param> /// <param name="endRow">row index (inclusive).</param> /// <param name="startColumn">Initial column index.</param> /// <param name="endColumn">column index (inclusive).</param> /// <param name="destination">The arrays where the submatrix data should be copied /// (if larger than rows/columns counts, only the upper-left part will be used).</param> /// <exception cref="">MatrixDimensionMismatchException if the dimensions of /// <c>destination</c> do not match those of <c>this</c>.</exception> /// <exception cref="NumberIsTooSmallException"> is <c>endRow < startRow</c> of /// <c>endColumn < startColumn</c>.</exception> /// <exception cref="OutOfRangeException"> if the indices are not valid.</exception> /// <exception cref="IllegalArgumentException"> if the destination array is too small.</exception> void copySubMatrix(int startRow, int endRow, int startColumn, int endColumn, T[][] destination); /// <summary> /// Copy a submatrix. Rows and columns are indicated /// counting from 0 to n - 1. /// </summary> /// <param name="selectedRows">Array of row indices.</param> /// <param name="selectedColumns">Array of column indices.</param> /// <param name="destination">Arrays where the submatrix data should be copied /// (if larger than rows/columns counts, only the upper-left part will be used)</param> /// <exception cref="MatrixDimensionMismatchException"> if the dimensions of /// <c>destination</c> do not match those of <c>this</c>.</exception> /// <exception cref="NoDataException"> if <c>selectedRows</c> or /// <c>selectedColumns</c> is empty</exception> /// <exception cref="NullArgumentException"> if <c>selectedRows</c> or /// <c>selectedColumns</c> is <c>null</c>.</exception> /// <exception cref="OutOfRangeException"> if the indices are not valid.</exception> void copySubMatrix(int[] selectedRows, int[] selectedColumns, T[][] destination); /// <summary> /// Replace the submatrix starting at <c>(row, column)</c> using data in the /// input <c>subMatrix</c> array. Indexes are 0-based. /// <para> /// Example:<para/> /// Starting with /// <code> /// 1 2 3 4 /// 5 6 7 8 /// 9 0 1 2 /// </code> /// and <c>subMatrix = {{3, 4} {5,6}}</c>, invoking /// <c>setSubMatrix(subMatrix,1,1))</c> will result in /// <code> /// 1 2 3 4 /// 5 3 4 8 /// 9 5 6 2 /// </code> /// </para> /// </summary> /// <param name="subMatrix">Array containing the submatrix replacement data.</param> /// <param name="row">Row coordinate of the top-left element to be replaced.</param> /// <param name="column">Column coordinate of the top-left element to be replaced.</param> /// <exception cref="OutOfRangeException"> if <c>subMatrix</c> does not fit into this /// matrix from element in <c>(row, column)</c>.</exception> /// <exception cref="NoDataException"> if a row or column of <c>subMatrix</c> is empty. /// </exception> /// <exception cref="DimensionMismatchException"> if <c>subMatrix</c> is not /// rectangular (not all rows have the same length).</exception> /// <exception cref="NullArgumentException"> if <c>subMatrix</c> is <c>null</c>. /// </exception> void setSubMatrix(T[][] subMatrix, int row, int column); /// <summary> /// Get the entries in row number <c>row</c> /// as a row matrix. /// </summary> /// <param name="row">Row to be fetched.</param> /// <returns>a row matrix.</returns> /// <exception cref="OutOfRangeException"> if the specified row index is invalid. /// </exception> FieldMatrix<T> getRowMatrix(int row); /// <summary> /// Set the entries in row number <c>row</c> as a row matrix. /// </summary> /// <param name="row">Row to be set.</param> /// <param name="matrix">Row matrix (must have one row and the same number /// of columns as the instance).</param> /// <exception cref="OutOfRangeException"> if the specified row index is invalid.</exception> /// <exception cref="MatrixDimensionMismatchException"> /// if the matrix dimensions do not match one instance row.</exception> void setRowMatrix(int row, FieldMatrix<T> matrix); /// <summary> /// Get the entries in column number <c>column</c> /// as a column matrix. /// </summary> /// <param name="column">Column to be fetched.</param> /// <returns>a column matrix.</returns> /// <exception cref="OutOfRangeException"> if the specified column index is invalid.</exception> FieldMatrix<T> getColumnMatrix(int column); /// <summary> /// Set the entries in column number <c>column</c> /// as a column matrix. /// </summary> /// <param name="column">Column to be set.</param> /// <param name="matrix">column matrix (must have one column and the same /// number of rows as the instance).</param> /// <exception cref="OutOfRangeException"> if the specified column index is invalid.</exception> /// <exception cref="MatrixDimensionMismatchException"> if the matrix dimensions do /// not match one instance column.</exception> void setColumnMatrix(int column, FieldMatrix<T> matrix); /// <summary> /// Get the entries in row number <c>row</c> /// as a vector. /// </summary> /// <param name="row">Row to be fetched</param> /// <returns>a row vector.</returns> /// <exception cref="OutOfRangeException"> if the specified row index is invalid.</exception> FieldVector<T> getRowVector(int row); /// <summary> /// Set the entries in row number <c>row</c> /// as a vector. /// </summary> /// <param name="row">Row to be set.</param> /// <param name="vector">row vector (must have the same number of columns /// as the instance).</param> /// <exception cref="OutOfRangeException"> if the specified row index is invalid.</exception> /// <exception cref="MatrixDimensionMismatchException"> /// if the vector dimensions do not match one instance row.</exception> void setRowVector(int row, FieldVector<T> vector); /// <summary> /// Returns the entries in column number <c>column</c> /// as a vector. /// </summary> /// <param name="column">Column to be fetched.</param> /// <returns>a column vector.</returns> /// <exception cref="OutOfRangeException"> if the specified column index is invalid. /// </exception> FieldVector<T> getColumnVector(int column); /// <summary> /// Set the entries in column number <c>column</c> /// as a vector. /// </summary> /// <param name="column">Column to be set.</param> /// <param name="vector">Column vector (must have the same number of rows /// as the instance).</param> /// <exception cref="OutOfRangeException"> if the specified column index is invalid. /// </exception> /// <exception cref="MatrixDimensionMismatchException"> if the vector dimension does not /// match one instance column.</exception> void setColumnVector(int column, FieldVector<T> vector); /// <summary> /// Get the entries in row number <c>row</c> as an array. /// </summary> /// <param name="row">Row to be fetched.</param> /// <returns>array of entries in the row.</returns> /// <exception cref="OutOfRangeException"> if the specified row index is not valid. /// </exception> T[] getRow(int row); /// <summary> /// Set the entries in row number <c>row</c> /// as a row matrix. /// </summary> /// <param name="row">Row to be set.</param> /// <param name="array">Row matrix (must have the same number of columns as /// the instance).</param> /// <exception cref="OutOfRangeException"> if the specified row index is invalid. /// </exception> /// <exception cref="MatrixDimensionMismatchException"> if the array size does not match /// one instance row.</exception> void setRow(int row, T[] array); /// <summary> /// Get the entries in column number <c>col</c> as an array. /// </summary> /// <param name="column">the column to be fetched</param> /// <returns>array of entries in the column</returns> /// <exception cref="OutOfRangeException"> if the specified column index is not valid. /// </exception> T[] getColumn(int column); /// <summary> /// Set the entries in column number <c>column</c> /// as a column matrix. /// </summary> /// <param name="column">the column to be set</param> /// <param name="array">column array (must have the same number of rows as the instance) /// </param> /// <exception cref="OutOfRangeException"> if the specified column index is invalid. /// </exception> /// <exception cref="MatrixDimensionMismatchException"> if the array size does not match /// one instance column.</exception> void setColumn(int column, T[] array); /// <summary> /// Returns the entry in the specified row and column. /// </summary> /// <param name="row">row location of entry to be fetched</param> /// <param name="column">column location of entry to be fetched</param> /// <returns>matrix entry in row,column</returns> /// <exception cref="OutOfRangeException"> if the row or column index is not valid. /// </exception> T getEntry(int row, int column); /// <summary> /// Set the entry in the specified row and column. /// </summary> /// <param name="row">row location of entry to be set</param> /// <param name="column">column location of entry to be set</param> /// <param name="value">matrix entry to be set in row,column</param> /// <exception cref="OutOfRangeException"> if the row or column index is not valid. /// </exception> void setEntry(int row, int column, T value); /// <summary> /// Change an entry in the specified row and column. /// </summary> /// <param name="row">Row location of entry to be set.</param> /// <param name="column">Column location of entry to be set.</param> /// <param name="increment">Value to add to the current matrix entry in /// <c>(row, column)</c>.</param> /// <exception cref="OutOfRangeException"> if the row or column index is not valid.</exception> void addToEntry(int row, int column, T increment); /// <summary> /// Change an entry in the specified row and column. /// </summary> /// <param name="row">Row location of entry to be set.</param> /// <param name="column">Column location of entry to be set.</param> /// <param name="factor">Multiplication factor for the current matrix entry /// in <c>(row,column)</c></param> /// <exception cref="OutOfRangeException"> if the row or column index is not valid.</exception> void multiplyEntry(int row, int column, T factor); /// <summary> /// Returns the transpose of this matrix. /// </summary> /// <returns>transpose matrix</returns> FieldMatrix<T> transpose(); /// <summary> /// Returns the <a href="http://mathworld.wolfram.com/MatrixTrace.html"> /// trace</a> of the matrix (the sum of the elements on the main diagonal). /// </summary> /// <returns>trace</returns> /// <exception cref="NonSquareMatrixException"> if the matrix is not square.</exception> T getTrace(); /// <summary> /// Returns the result of multiplying this by the vector <c>v</c>. /// </summary> /// <param name="v">the vector to operate on</param> /// <returns><c>this * v</c></returns> /// <exception cref="DimensionMismatchException"> if the number of columns of /// <c>this</c> matrix is not equal to the size of the vector <c>v</c>.</exception> T[] operate(T[] v); /// <summary> /// Returns the result of multiplying this by the vector <c>v</c>. /// </summary> /// <param name="v">the vector to operate on</param> /// <returns><c>this * v</c></returns> /// <exception cref="DimensionMismatchException"> if the number of columns of /// <c>this</c> matrix is not equal to the size of the vector <c>v</c>.</exception> FieldVector<T> operate(FieldVector<T> v); /// <summary> /// Returns the (row) vector result of premultiplying this by the vector /// <c>v</c>. /// </summary> /// <param name="v">the row vector to premultiply by</param> /// <returns><c>v * this</c></returns> /// <exception cref="DimensionMismatchException"> if the number of rows of <c>this</c> /// matrix is not equal to the size of the vector <c>v</c></exception> T[] preMultiply(T[] v); /// <summary> /// Returns the (row) vector result of premultiplying this by the vector /// <c>v</c>. /// </summary> /// <param name="v">the row vector to premultiply by</param> /// <returns><c>v * this</c></returns> /// <exception cref="DimensionMismatchException"> if the number of rows of <c>this</c> /// matrix is not equal to the size of the vector <c>v</c></exception> FieldVector<T> preMultiply(FieldVector<T> v); /// <summary> /// Visit (and possibly change) all matrix entries in row order. /// <para>Row order starts at upper left and iterating through all elements /// of a row from left to right before going to the leftmost element /// of the next row.</para> /// </summary> /// <param name="visitor">visitor visitor used to process all matrix entries /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor)"/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor)"/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor)"/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor)"/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor)"/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/></param> /// <returns>the value returned by <see cref="FieldMatrixChangingVisitor.end()"/> /// at the end of the walk</returns> T walkInRowOrder(FieldMatrixChangingVisitor<T> visitor); /// <summary> /// Visit (but don't change) all matrix entries in row order. /// <para>Row order starts at upper left and iterating through all elements /// of a row from left to right before going to the leftmost element /// of the next row.</para> /// </summary> /// <param name="visitor">visitor used to process all matrix entries /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor)"/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor)"/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor)"/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor)"/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor)"/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/></param> /// <returns>the value returned by <see cref="FieldMatrixPreservingVisitor.end()"/> /// at the end of the walk</returns> T walkInRowOrder(FieldMatrixPreservingVisitor<T> visitor); /// <summary> /// Visit (and possibly change) some matrix entries in row order. /// <para>Row order starts at upper left and iterating through all elements /// of a row from left to right before going to the leftmost element /// of the next row.</para> /// </summary> /// <param name="visitor">visitor used to process all matrix entries<para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor)"/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor)"/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor)"/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor)"/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor)"/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor)"/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// </param> /// <param name="startRow">Initial row index</param> /// <param name="endRow">row index (inclusive)</param> /// <param name="startColumn">Initial column index</param> /// <param name="endColumn">column index</param> /// <returns>the value returned by <see cref="FieldMatrixChangingVisitor.end()"/> /// at the end of the walk</returns> /// <exception cref="OutOfRangeException"> if the indices are not valid.</exception> /// <exception cref="NumberIsTooSmallException"> if <c>endRow < startRow</c> or /// <c>endColumn < startColumn</c>.</exception> T walkInRowOrder(FieldMatrixChangingVisitor<T> visitor, int startRow, int endRow, int startColumn, int endColumn); /// <summary> /// Visit (but don't change) some matrix entries in row order. /// <para>Row order starts at upper left and iterating through all elements /// of a row from left to right before going to the leftmost element /// of the next row.</para> /// </summary> /// <param name="visitor">visitor used to process all matrix entries<para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// </param> /// <param name="startRow">Initial row index</param> /// <param name="endRow">row index (inclusive)</param> /// <param name="startColumn">Initial column index</param> /// <param name="endColumn">column index</param> /// <returns>the value returned by <see cref="FieldMatrixPreservingVisitor.end()"/> /// at the end of the walk</returns> /// <exception cref="OutOfRangeException"> if the indices are not valid.</exception> /// <exception cref="NumberIsTooSmallException"> if <c>endRow < startRow</c> or /// <c>endColumn < startColumn</c>.</exception> T walkInRowOrder(FieldMatrixPreservingVisitor<T> visitor, int startRow, int endRow, int startColumn, int endColumn); /// <summary> /// Visit (and possibly change) all matrix entries in column order. /// <para>Column order starts at upper left and iterating through all elements /// of a column from top to bottom before going to the topmost element /// of the next column.</para> /// </summary> /// <param name="visitor">visitor visitor used to process all matrix entries<para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// </param> /// <returns>the value returned by <see cref="FieldMatrixChangingVisitor.end()"/> at /// the end of the walk</returns> T walkInColumnOrder(FieldMatrixChangingVisitor<T> visitor); /// <summary> /// Visit (but don't change) all matrix entries in column order. /// <para>Column order starts at upper left and iterating through all elements /// of a column from top to bottom before going to the topmost element /// of the next column.</para> /// </summary> /// <param name="visitor">visitor used to process all matrix entries<para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// </param> /// <returns>the value returned by <see cref="FieldMatrixPreservingVisitor.end()"/> at /// the end of the walk</returns> T walkInColumnOrder(FieldMatrixPreservingVisitor<T> visitor); /// <summary> /// Visit (and possibly change) some matrix entries in column order. /// <para>Column order starts at upper left and iterating through all elements /// of a column from top to bottom before going to the topmost element /// of the next column.</para> /// </summary> /// <param name="visitor">visitor used to process all matrix entries<para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// </param> /// <param name="startRow">Initial row index</param> /// <param name="endRow">row index (inclusive)</param> /// <param name="startColumn">Initial column index</param> /// <param name="endColumn">column index</param> /// <returns>the value returned by <see cref="FieldMatrixChangingVisitor.end()"/> at /// the end of the walk</returns> /// <exception cref="NumberIsTooSmallException"> if <c>endRow < startRow</c> or /// <c>endColumn < startColumn</c>.</exception> /// <exception cref="OutOfRangeException"> if the indices are not valid.</exception> T walkInColumnOrder(FieldMatrixChangingVisitor<T> visitor, int startRow, int endRow, int startColumn, int endColumn); /// <summary> /// Visit (but don't change) some matrix entries in column order. /// <para>Column order starts at upper left and iterating through all elements /// of a column from top to bottom before going to the topmost element /// of the next column.</para> /// </summary> /// <param name="visitor">visitor used to process all matrix entries<para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// </param> /// <param name="startRow">Initial row index</param> /// <param name="endRow">row index (inclusive)</param> /// <param name="startColumn">Initial column index</param> /// <param name="endColumn">column index</param> /// <returns>the value returned by <see cref="FieldMatrixPreservingVisitor.end()"/> at /// the end of the walk</returns> /// <exception cref="NumberIsTooSmallException"> if <c>endRow < startRow</c> or /// <c>endColumn < startColumn</c>.</exception> /// <exception cref="OutOfRangeException"> if the indices are not valid.</exception> T walkInColumnOrder(FieldMatrixPreservingVisitor<T> visitor, int startRow, int endRow, int startColumn, int endColumn); /// <summary> /// Visit (and possibly change) all matrix entries using the fastest possible order. /// <para>The fastest walking order depends on the exact matrix class. It may be /// different from traditional row or column orders.</para> /// </summary> /// <param name="visitor">visitor used to process all matrix entries<para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// </param> /// <returns>the value returned by <see cref="FieldMatrixChangingVisitor.end()"/> at /// the end of the walk</returns> T walkInOptimizedOrder(FieldMatrixChangingVisitor<T> visitor); /// <summary> /// Visit (but don't change) all matrix entries using the fastest possible order. /// <para>The fastest walking order depends on the exact matrix class. It may be /// different from traditional row or column orders.</para> /// </summary> /// <param name="visitor">visitor used to process all matrix entries<para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// </param> /// <returns>the value returned by <see cref="FieldMatrixPreservingVisitor.end()"/> at /// the end of the walk</returns> T walkInOptimizedOrder(FieldMatrixPreservingVisitor<T> visitor); /// <summary> /// Visit (and possibly change) some matrix entries using the fastest possible order. /// <para>The fastest walking order depends on the exact matrix class. It may be /// different from traditional row or column orders.</para> /// </summary> /// <param name="visitor">visitor used to process all matrix entries<para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// </param> /// <param name="startRow">Initial row index</param> /// <param name="endRow">row index (inclusive)</param> /// <param name="startColumn">Initial column index</param> /// <param name="endColumn">column index (inclusive)</param> /// <returns>the value returned by <see cref="FieldMatrixChangingVisitor.end()"/> at /// the end of the walk</returns> /// <exception cref="NumberIsTooSmallException"> if <c>endRow < startRow</c> or /// <c>endColumn < startColumn</c>.</exception> /// <exception cref="OutOfRangeException"> if the indices are not valid.</exception> T walkInOptimizedOrder(FieldMatrixChangingVisitor<T> visitor, int startRow, int endRow, int startColumn, int endColumn); /// <summary> /// Visit (but don't change) some matrix entries using the fastest possible order. /// <para>The fastest walking order depends on the exact matrix class. It may be /// different from traditional row or column orders.</para> /// </summary> /// <param name="visitor">visitor used to process all matrix entries<para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInRowOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInRowOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInColumnOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInColumnOrder(FieldMatrixPreservingVisitor, int, int, int, int)"/> /// <para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixPreservingVisitor)"/><para/> /// See <see cref="walkInOptimizedOrder(FieldMatrixChangingVisitor, int, int, int, int)"/> /// </param> /// <param name="startRow">Initial row index</param> /// <param name="endRow">row index (inclusive)</param> /// <param name="startColumn">Initial column index</param> /// <param name="endColumn">column index (inclusive)</param> /// <returns>the value returned by <see cref="FieldMatrixPreservingVisitor.end()"/> at /// the end of the walk</returns> /// <exception cref="NumberIsTooSmallException"> if <c>endRow < startRow</c> or /// <c>endColumn < startColumn</c>.</exception> /// <exception cref="OutOfRangeException"> if the indices are not valid.</exception> T walkInOptimizedOrder(FieldMatrixPreservingVisitor<T> visitor, int startRow, int endRow, int startColumn, int endColumn); } }
Markdown
UTF-8
2,551
2.796875
3
[]
no_license
Being a blogger myself, I realise how much quality content is written on the internet every day; content that gets lost in an endless stream of online information. I know how much you want to be able to share your content with an audience, but it's so difficult to do. Twitter is very momentarily; Reddit suffers from spam and angry people; and Facebook is, well, Facebook. I want a platform where I don't have to feel guilty about sharing my content, and where readers can easily discover new things to read. So I took one of the oldest blogging concepts and made a community driven platform out of it: RSS. ## Community driven? I realise that starting a project on my own, won't get me far. We live in a day and age where every possible app has been invented at least twice. Trying to do this myself won't get me far. That's why I decided on two things. The code is **open source**. I want to encourage people to contribute, help build the platform they want it to be. The **content** is provided by the community, and the platform will always redirect to the source of origin. It will never try to host your content, it's merely a portal. ## How does it work? Content creators can add their RSS feed to the platform. Their posts are synced and tagged according to the content and RSS meta data. Readers can explore new content daily in their feed. I've decided to not try and do anything fancy while building this feed. Platforms like Facebook and Twitter try to be smart and build a feed based on "your interests". They never succeed. So the feed is a simple chronological list, which you can filter on tags. That's it. There are no votes, no comments. You're encouraged to go the blogs themselves, and share your thoughts over there. The goal of the platform is simple: help readers discover new content, and get them to that original content as fast as possible. Meanwhile, content creators get a platform where they are allowed to share their own stuff, and an audience hungry for more. ## Get in touch Even though the basic concept is stable and up and running, there's still lots of things to do. There's improvements to be made to the tagging system, there are some convenience features that need to be added and more. If you're a web programmer yourself who's interested in open source, feel free to take a look around the [project board](*https://github.com/brendt/aggregate.stitcher.io/projects/1). Oh and, of course, here's a link to the platform: [aggregate.stitcher.io](*https://aggregate.stitcher.io/).
JavaScript
UTF-8
846
3.203125
3
[]
no_license
function splitText(parent_div_class, wrapper_class_name, class_name) { let parent_array = document.getElementsByClassName(parent_div_class); for(var j=0; j<parent_array.length; j++) { let text = parent_array[j].innerText; parent_array[j].innerText = ""; let word = text.split(" "); for(var i=0; i<word.length; i++) { let word_div = document.createElement('div'); word_div.className = wrapper_class_name + " " + wrapper_class_name + "-" + (i+1); word[i].split("").forEach(function(c) { let char_div = document.createElement('div'); char_div.className = class_name; char_div.append(c); word_div.append(char_div); }); parent_array[j].append(word_div); let space = document.createElement('div'); space.className = 'space-char'; space.append(" "); parent_array[j].append(space); }; }; };
Java
UTF-8
1,273
4.09375
4
[]
no_license
package jb02.part02; /* 1. while (조건) 2. do.. while (조건) 활용 및 차이점을 확인. */ public class WhileTest { public static void main(String[] args) { //while 문 int i = 0; // #1. 순환문의 조건을 주기위한 int i 초기화 while (i < 10) // #2. 조건 ( boolean data type ) // while ( 0 ) { // ==> compile error (error를 확인하면... ) { System.out.println("여기는 while문 내부안임 i = "+i); i++; // #3. 증감식 } //do-while 문 int j = 0; // #1. 순환문의 조건을 주기 위한 int j 초기화 do { System.out.println("\n\t 여기는 do문 내부임 j = "+j); j++; // #2. 증감식 } while (j < 1); // #3. 조건 ( boolean data type ) System.out.println("\n==========================\n"); //while 문을 이용하여 5단을 출력하는 프로그램 int k = 1; while (k < 10) { System.out.println("5 * "+k+" = "+5*k); k++; } //==> 무한루프 와 무한루프후단의 실행문에서 compile error 이해 while (true) { System.out.println("여기는 반복문 내부의 무한 루프"); } //==> 아래의 주석을 풀면 compile error 가 발생한다. 이유는... //System.out.println("error 가 발생한다. 이유는..."); } }
Markdown
UTF-8
1,155
2.546875
3
[]
no_license
# Article 2 Le ministre chargé de l'éducation attribue chaque année aux recteurs d'académie une dotation d'indemnités de sujétions spéciales pour chaque degré d'enseignement. Pour le second degré, les recteurs répartissent la dotation correspondante entre les collèges et les lycées de l'académie et établissent annuellement la liste des lycées ouvrant droit au versement de l'indemnité de sujétions spéciales, après avis des comités techniques académiques. Pour le premier degré, les collèges et les établissements d'éducation spéciale, les recteurs répartissent les dotations correspondantes entre les départements, après avis des comités techniques académiques. Dans la limite des contingents résultant de la répartition des dotations prévues à l'alinéa ci-dessus, les directeurs académiques des services de l'éducation nationale agissant sur délégation du recteur d'académie établissent annuellement, après avis des comités techniques départementaux, la liste des écoles, des collèges et des établissements d'éducation spéciale ouvrant droit au versement de l'indemnité de sujétions spéciales.
Java
UTF-8
3,044
2.234375
2
[]
no_license
package org.stepdefinition; import java.util.List; import java.util.Map; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import cucumber.api.java.en.Given; import cucumber.api.java.en.When; public class AddingTarifff { static WebDriver driver; @Given("user should be telecom homepage") public void user_should_be_telecom_homepage() { System.setProperty("webdriver.chrome.driver", "C:\\Users\\RESHMA\\parcts\\Practise\\driver\\chromedriver.exe"); driver=new ChromeDriver(); driver.get("http://demo.guru99.com/telecom/"); } @Given("user should navigate to Addtariffplan page") public void user_should_navigate_to_Addtariffplan_page() { driver.findElement(By.xpath("//a[text()='Add Tariff Plan']")).click(); } @When("user should enter plan details") public void user_should_enter_plan_details() { driver.findElement(By.id("rental1")).sendKeys("399"); driver.findElement(By.xpath("//input[@name='local_minutes']")).sendKeys("2000"); driver.findElement(By.xpath("//input[@name= 'inter_minutes']")).sendKeys("1000"); driver.findElement(By.xpath("//input[@id='sms_pack']")).sendKeys("400"); driver.findElement(By.xpath("//input[@id='minutes_charges']")).sendKeys("256"); driver.findElement(By.xpath("(//div[@style='font-weight:300']/input)[6]")).sendKeys("452"); driver.findElement(By.xpath("//input[@id='sms_charges']")).sendKeys("1"); } @When("user should enter plan details.") public void user_should_enter_plan_details(io.cucumber.datatable.DataTable dataTable) { List<List<String>> data = dataTable.asLists(String.class); driver.findElement(By.id("rental1")).sendKeys(data.get(1).get(0)); driver.findElement(By.xpath("//input[@name='local_minutes']")).sendKeys(data.get(3).get(1)); driver.findElement(By.xpath("//input[@name= 'inter_minutes']")).sendKeys(data.get(3).get(1)); driver.findElement(By.xpath("//input[@id='sms_pack']")).sendKeys(data.get(3).get(2)); driver.findElement(By.xpath("//input[@id='minutes_charges']")).sendKeys(data.get(3).get(5)); driver.findElement(By.xpath("(//div[@style='font-weight:300']/input)[6]")).sendKeys(data.get(3).get(4)); driver.findElement(By.xpath("//input[@id='sms_charges']")).sendKeys(data.get(3).get(6)); } @When("user should enter plan detail") public void user_should_enter_plan_detail(io.cucumber.datatable.DataTable dataTable) { List<Map<String, String>> data = dataTable.asMaps(String.class,String.class); driver.findElement(By.id("rental1")).sendKeys(data.get(1).get("MR")); driver.findElement(By.xpath("//input[@name='local_minutes']")).sendKeys(data.get(3).get("IM")); driver.findElement(By.xpath("//input[@name= 'inter_minutes']")).sendKeys(data.get(3).get("LM")); driver.findElement(By.xpath("//input[@id='sms_pack']")).sendKeys(data.get(3).get("SMS")); } @When("user should submit the plan details") public void user_should_submit_the_plan_details() { driver.findElement(By.xpath("//ul[@class='actions']/li/input")).click(); } }
Python
UTF-8
780
3.5625
4
[]
no_license
def get_data(): f = open("inputs/input2.txt", "r") lines = f.read().splitlines() f.close() return lines def day2(items): x = 0 y = 0 for i in items: first = int(i.split("-")[0]) second = int(i.split("-")[1].split(" ")[0]) character = i.split(" ")[1].split(":")[0] password = i.split(" ")[2] if first <= password.count(character) <= second: x += 1 if password[first - 1] == character or password[second - 1] == character: if not (password[first - 1] == character and password[second - 1] == character): y += 1 return x, y if __name__ == '__main__': answer_1, answer_2 = day2(get_data()) print("answer 1:", answer_1) print("answer 2:", answer_2)
Java
UTF-8
357
3.015625
3
[]
no_license
class Lab298{ public static void main(String[] arg) { Hello h=new Hello(); String a= h.add(10,"jlc"); System.out.println(a); String b= h.add("jlc",30); System.out.println(b); } } class Hello{ String add(int a,String b){ System.out.println("add(int,string)"); return a+b; } String add(String a,int b){ System.out.println("add(String,int)"); return a+b; } }
C++
UTF-8
1,339
3.109375
3
[]
no_license
class Solution { public: //the role of multi void helper(string num, int pos, int target, long curr, long multi, string path, vector<string> & res) { if (pos == num.length()) { if (curr == (long)target) { cout << curr << " " << target << endl; res.push_back(path); } return; } if (pos > num.length()) return; for (int i = pos; i < num.length(); i ++) { string tmp = num.substr(pos, i-pos+1); if (tmp.length()>1 && tmp.front() == '0') break;//no longer a valid number, for example "00" or "0123" long t = stol(tmp); if (pos == 0) { helper(num, i+1, target, t, t, tmp, res); } else { //think about "1+2*3" "1-2*3" "1+2*3*4" helper(num, i+1, target, curr+t, t, path+"+"+tmp, res); helper(num, i+1, target, curr-t, -t, path+"-"+tmp, res); helper(num, i+1, target, curr-multi+multi*t, multi*t, path+"*"+tmp, res); } } } vector<string> addOperators(string num, int target) { vector<string> res; if (num.empty()) return res; helper(num, 0, target, 0, 0, "", res); return res; } };
C
UTF-8
1,887
2.8125
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_color.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: llahti <llahti@student.hive.fi> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/23 16:02:15 by llahti #+# #+# */ /* Updated: 2020/02/12 10:35:04 by llahti ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" static int ft_get_rgb(char *input, int len, int minlen) { int temp; int res; if (len < minlen) return (0); res = ft_hexa_to_int(input[len - minlen + 1]); temp = ft_hexa_to_int(input[len - minlen]); return (res + temp * 16); } void ft_get_default_color(t_point *point) { point->b = DEFAULT_BLUE; point->g = DEFAULT_GREEN; point->r = DEFAULT_RED; } int ft_get_color(t_point *point, char *input, int k, int theme) { int colorlen; if (!(ft_strnequ(&input[k], ",0x", 3) || ft_strnequ(&input[k], ",0X", 3))) ft_error("Error at ft_get_color, no color after comma", 1); k += 3; colorlen = ft_hexa_len(&input[k]); if (theme) { point->tb = ft_get_rgb(&input[k], colorlen, 2); point->tg = ft_get_rgb(&input[k], colorlen, 4); point->tr = ft_get_rgb(&input[k], colorlen, 6); return (1); } point->b = ft_get_rgb(&input[k], colorlen, 2); point->g = ft_get_rgb(&input[k], colorlen, 4); point->r = ft_get_rgb(&input[k], colorlen, 6); k += colorlen; return (k); }
PHP
UTF-8
4,638
2.609375
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Database\Eloquent\Model; use App\DiscountType; use App\Bookingfact; use DateTime; use Validator; use App\Lib\Calculator; class Reservation extends Model { private $field; private $price; private $errorsMessages; public function bookingfacts() { return $this->belongsTo('App\Bookingfact'); } public function discounttype() { return $this->hasOne('App\DiscountType'); } public function validate($reservations) { $discountTypes = DiscountType::orderBy('id', 'asc')->get(); $discountTypesCount = count($discountTypes); foreach($reservations as $reservation) { $validatorReservations = Validator::make($reservation, [ 'name' => 'required|max:255', 'discount' => 'required|numeric|max:' . $discountTypesCount . '|min:1', 'fromdate' => 'required|date', 'fromtime' => ['required', 'regex:^(([0-1][0-9]|2[0-3]):[0-5][0-9]?)$^'], 'todate' => 'required|date', 'totime' => ['required', 'regex:^(([0-1][0-9]|2[0-3]):[0-5][0-9]?)$^'] ]); if($validatorReservations->fails()){ $messages[]=$validatorReservations->getMessageBag()->keys(); $this->errorsMessages = $validatorReservations ->getMessageBag()->all(); } else{ $messages[]=[]; } } $this->field=$messages; if ($validatorReservations->fails()) { return false; } return true; } public static function andSave($reservations) { // dd($reservations); foreach($reservations as $reservation) { $count = Reservation::where('guid', $reservation['guid'])->count(); // if ($count == 0) { $bookingFactId = Bookingfact::max('id'); $newReservation = new Reservation; $newReservation->name = $reservation['name']; $newReservation->datetime_from = DateTime::createFromFormat('d.m.Y H:i', $reservation['fromdate'] . " " . $reservation['fromtime'])->format('Y-m-d H:i'); $newReservation->datetime_to = DateTime::createFromFormat('d.m.Y H:i', $reservation['todate'] . " " . $reservation['totime'])->format('Y-m-d H:i'); $newReservation->discount_type_id = $reservation['discount']; // dd($reservation['prices']); //162.0 // $newReservation->price = $reservation['prices']; $newReservation->price = 1; // dd($newReservation->price); $newReservation->bookingfacts_id = $bookingFactId; $newReservation->guid = $reservation['guid']; $newReservation->save(); } // } } public function calculatePrices($reservations) { foreach ($reservations as &$reservation) { $price[]=$calkulate=Calculator::calculate($reservation); $reservation['prices']=$calkulate; $this->price=$price; // } unset($reservation); // // dd('s'); // dd($this->price); return $reservations; } public function getGuid($reservation) { $dataString = ''; $dataString .= url()->full() . $reservation['name'] . $reservation['discount'] . $reservation['fromdate'] . $reservation['fromtime'] . $reservation['todate'] . $reservation['totime']; // . $reservation['prices']; $hash = strtoupper(md5($this->getRandomString($dataString))); $hyphen = chr(45); $openBracket = chr(123); $closeBracket = chr(125); $uuid = $openBracket . substr($hash, 0, 8) . $hyphen . substr($hash, 8, 4) . $hyphen . substr($hash, 12, 4) . $hyphen . substr($hash, 16, 4) . $hyphen . substr($hash, 20, 12) . $closeBracket; return $uuid; } private function getRandomString($dataString) { $randomString = ''; for ($i = 0; $i < strlen($dataString) - 1; $i++) { $randomString .= $dataString[rand(0, strlen($dataString) - 1)]; } return $randomString; } public function getPrice(){ return $this->price; } public function getField(){ return $this->field; } public function getErrorsMessages(){ return $this->errorsMesages; } }
Java
UTF-8
3,073
3
3
[]
no_license
import java.io.*; import java.util.*; public class Main { public static void main(String[] args) throws IOException{ //BufferedReader f = new BufferedReader(new FileReader("uva.in")); BufferedReader f = new BufferedReader(new InputStreamReader(System.in)); //PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("cowjump.out"))); PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out))); int T = Integer.parseInt(f.readLine()); while(T-- > 0) { char[] t = f.readLine().toCharArray(); Character[] order = new Character[26]; for(int i = 0; i < 26; i++) { order[i] = (char) ('a'+i); } int[] occ = new int[26]; int[] last = new int[26]; for(int i = 0; i < t.length; i++) { last[t[i]-'a'] = i; occ[t[i]-'a']++; } Arrays.sort(order, new Comparator<Character>() { @Override public int compare(Character character, Character t1) { return last[character-'a']-last[t1-'a']; } }); StringBuilder sb = new StringBuilder(); for(char i: order) { if(occ[i-'a'] > 0) { sb.append(i); } } HashMap<Character, Integer> map = new HashMap<>(); boolean flag = false; for(int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); if(occ[c-'a']%(i+1) != 0) { flag = true; break; } map.put(c, occ[c-'a']/(i+1)); } if(flag) { out.println(-1); } else { StringBuilder res = new StringBuilder(); int i = 0; while(i < t.length && !map.isEmpty()) { if(!map.containsKey(t[i])) { flag = true; break; } res.append(t[i]); map.put(t[i], map.get(t[i])-1); if(map.get(t[i]) == 0) { map.remove(t[i]); } i++; } if(flag || !map.isEmpty()) { out.println(-1); } else { String cur = res.toString(); StringBuilder temp = new StringBuilder(); for(char j: sb.toString().toCharArray()) { temp.append(cur); cur = cur.replaceAll(""+j, ""); } if(!Arrays.equals(temp.toString().toCharArray(), t)) { out.println(-1); } else { out.println(res + " " + sb); } } } } f.close(); out.close(); } }
Markdown
UTF-8
2,256
3.296875
3
[]
no_license
# MacOS-like diacritical mark input for Windows This is an AutoHotKey script that emulates the MacOS diacritical mark input mechanism under Windows. As a developer, I find the US keyboard layout superior for coding. As a spanish speaker, I need to be able to easily add diacritical marks to characters when typing, but the US keyboard layout does not include any of the the necessary keys. Changing keyboard layouts constantly is impractical, and memorizing AltGr codes is clunky and doesn't work without a numeric keypad. Unfortunately, Windows does not offer any native solutions. MacOS has historically solved this problem nicely by allowing the use of Alt+Character combos to "prime" a diacritical mark for the next keystroke. For example, pressing Alt+E will prime a tilde, so that the next typed character will carry one. This script attempts to replicate this functionality for some of the possible diacritical marks. Adding other ones should be fairly easy, as the mechanism used is generic. It also emulates some basic media key functionality, because this script is meant for personal use and I find it convenient to keep all keyboard emulation in one place. The script automatically disables itself when running fullscreen apps, as AHK keystroke capture tends to conflict with games. ## How to use 1. Download and install AutoHotKey for Windows from https://www.autohotkey.com/ 2. Once AHK is installed, double-clicking the script should launch it. The script will run in the background and can be controlled from the tray. 3. It's convenient to have the script automatically launch at startup. This can be done by using Win+R to run the "shell:startup" command to open the current user's Startup folder, and then creating a shortcut to the script there. ## Supported keys * Alt+E -> acute (á, Á) * Alt+I -> circumflex (â, Â) * Alt+N -> tilde (ñ, Ñ) * Alt+U -> umlaut (ü, Ü) * Alt+Ctrl+Down -> Media pause * Alt+Ctrl+Right -> Media next * Alt+Ctrl+Left -> Media previous ## Credits This script is really just a simplified version of a script found on this blogpost by Aaron Gustafson: https://www.aaron-gustafson.com/notebook/mac-like-special-characters-in-windows/ He based his code in turn on a post by Veil on the AHK user forums.
Ruby
UTF-8
338
2.75
3
[ "MIT" ]
permissive
module Mlc module Abstract class Block def initialize @children = [] end def <<(child) @children << child end def to_lua(indent, options, state) i = ' ' * indent i + @children.map {|el| el.to_lua(indent + 1, options, state)}.join("\n#{i}") end end end end
Python
UTF-8
1,506
3.03125
3
[]
no_license
#!/usr/bin/env python # coding: utf-8 import requests import json from urllib.parse import urlencode from haversine import haversine import sys from tabulate import tabulate API_URL = "https://maps.googleapis.com/maps/api/geocode/json" API_VELOV_URL = "https://download.data.grandlyon.com/ws/rdata/jcd_jcdecaux.jcdvelov/all.json" def getPostion(address): param = { 'address':address} res = json.loads(requests.get("{}?{}".format(API_URL,urlencode(param))).text) location = res['results'][0]["geometry"]["location"] return float(location['lat']),float(location['lng']) def get_stations(): return json.loads(requests.get(API_VELOV_URL).text)["values"] def add_distance(stations, pos): for s in stations: pos_station = (float(s["lat"]),float(s["lng"])) s["distance"] = haversine(pos, pos_station) def sort_stations(stations): return sorted(stations, key=lambda x: x["distance"]) def get_closest_stations(address): stations = get_stations() add_distance(stations, getPostion(address)) return sort_stations(stations)[:10] def main(): address = sys.argv[1] stations = get_closest_stations(address) res = [] for s in stations: res.append([s["address"],s["available_bikes"],s["available_bike_stands"]]) #print("{} - {} - {}".format(s["address"],s["available_bikes"],s["available_bike_stands"])) print(tabulate(res, headers=("Adresse","Vélos libres","Places restantes"))) if __name__=="__main__": main()
C
UTF-8
13,846
3.96875
4
[]
no_license
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <time.h> /* CURRENT IDEA: numbers are stored using a singly linked list where the orders of magnitude are backwards ex. 1024 would be stored as [ 4, 2, 0, 1 ] it should be stored backwards because in order for a recursive function to carry a remainder to the next, higher order of magnitude place, it needs to traverse up the int, and since it's singly linked it would be best to store it in reverse order. */ //list to store numbers struct list { int digit; struct list *next; }; //datatype to hold numbers struct num { struct list *head; struct list *tail; }; //functions bool isEmpty(struct list *); //passed : head int length(struct list *, struct list *); //passed : head, tail void insertFront(struct list **, struct list **, int); //passed : head, tail, digit void insertBack(struct list **, struct list **, int); //passed : head, tail, digit struct list * deleteFront(struct list **); //passed : head void printList(struct list **, struct list **); //passed : head, tail void free_list(struct list **, struct list **); //passed : head, tail struct num * my_add(struct list **, struct list **, struct list **, struct list **); //passed : head,tail for num1, and head,tail for num2 struct num * my_sub(struct list **, struct list **, struct list **, struct list **); //passed : head,tail for num1, and head,tail for num2 bool isLargerThan(struct list **, struct list **, struct list **, struct list **); //passed : old head,head,tail for num1, and old head,head,tail for num2 struct num * dup_num(struct list **, struct list **); //passed : head, tail int main(int argc, char * argv[]) { struct num *x, *y; x = (struct num*) malloc(sizeof(struct num)); y = (struct num*) malloc(sizeof(struct num)); x->head = x->tail = y->head = y->tail = NULL; //change count to change size of numbers int i = 0, count = 10; srand(time(NULL)); //so we get random digits each iteration for (i; i < count; i++) { insertFront(&x->head, &x->tail, (rand() % 10)); insertBack(&y->head, &y->tail, (rand() % 10)); } printf("\nOriginal Lists: "); //prints list printList(&x->head, &x->tail); printf("x Length: %d", length(x->head, x->tail)); printList(&y->head, &y->tail); printf("y Length: %d", length(x->head, x->tail)); //tests isLargerThan printf("\n\nis x larger than y?: "); printf("%s", isLargerThan(&x->head, &x->tail, &y->head, &y->tail) ? "true" : "false"); printf("\n\nis y larger than x?: "); printf("%s", isLargerThan(&y->head, &y->tail, &x->head, &x->tail) ? "true" : "false"); //tests dup struct num* resultDup; resultDup = dup_num(&x->head, &x->tail); printf("\n\nduplicate x ="); printList(&resultDup->head, &resultDup->tail); //adds lists struct num *resultAdd; resultAdd = my_add(&x->head,&x->tail,&y->head,&y->tail); printf("\n\nx + y ="); printList(&resultAdd->head, &resultAdd->tail); printf("result Length: %d", length(resultAdd->head, resultAdd->tail)); //subtracts lists struct num *resultSub; resultSub = my_sub(&x->head, &x->tail, &y->head, &y->tail); printf("\n\nx - y ="); printList(&resultSub->head, &resultSub->tail); printf("result Length: %d", length(resultSub->head, resultSub->tail)); printf("\n"); //clears list free_list(&x->head, &x->tail); free_list(&y->head, &y->tail); free_list(&resultAdd->head, &resultAdd->tail); free_list(&resultSub->head, &resultSub->tail); free_list(&resultDup->head, &resultDup->tail); printf("\nLists after deleting all items:\nx: "); printList(&x->head, &x->tail); printf("y:"); printList(&y->head, &y->tail); printf("\nresultAdd:"); printList(&resultAdd->head, &resultAdd->tail); printf("\nresultSub:"); printList(&resultSub->head, &resultSub->tail); free(x); free(y); free(resultAdd); free(resultSub); free(resultDup); return 0; } bool isEmpty(struct list *ptr) { return ptr == NULL; } int length(struct list *start, struct list *end) { int length = 0; //if list is empty if(isEmpty(start)) { return 0; } struct list *current = start; while(current != end) { length++; current = current->next; } length++; return length; } //insert link at the first location void insertFront(struct list **head, struct list **tail, int digit) { //creates a link struct list *node = (struct list*) malloc(sizeof(struct list)); node -> digit = digit; if (isEmpty(*head)) { *head = *tail = node; (*head) -> next = (*tail) -> next = NULL; } else { //point it to old first list node -> next = *head; //point first to new first list *head = node; } } void insertBack(struct list **head, struct list **tail, int digit) { struct list *node = (struct list*) malloc(sizeof(struct list)); node -> digit = digit; if (isEmpty(*head)) { *head = *tail = node; (*head) -> next = (*tail) -> next = NULL; } else { //point it to NULL node -> next = NULL; //update old tail (*tail) -> next = node; *tail = node; } } //delete first item struct list * deleteFront(struct list **head) { if(isEmpty((*head)->next)) { printf("\nDeleted value:(%d)", (*head) -> digit); free(head); *head = NULL; return NULL; } //save reference to first link struct list *old_head = *head; //mark next to first link as first *head = (*head) -> next; printf("\nDeleted value:(%d)", old_head -> digit); free(old_head); //return the new head return *head; } //display the list void printList(struct list **head, struct list **tail) { printf("\n[ "); //start from the beginning if(!isEmpty(*head)) { struct list *ptr = *head; while(ptr != *tail) { if(ptr->digit != -1) { printf("%d ", ptr -> digit); } else { printf("- "); //for subtraction method } ptr = ptr -> next; } if(ptr->digit != -1) { printf("%d ", ptr -> digit); } else { printf("- "); } } printf(" ]\n"); } // destructor void free_list(struct list **head, struct list **tail) { while(!isEmpty(*head)) { struct list *temp = deleteFront(head); } printf("\n"); } //note carry can only ever be one struct num * my_add(struct list **head1, struct list **tail1, struct list **head2, struct list **tail2){ int val; int carry = 0; struct list *ptr1 = *head1; //just creating like a temp ptr to 1st number's head struct list *ptr2 = *head2; //same for above but for 2nd number struct list *first_tail = *tail1; //wouldnt work unless i created a temp ptr to the tail, wouldnt let me use original struct list *second_tail = *tail2; //same for above but for 2nd number int num1,num2; //values for the digit's used to calculate the value struct num *result; //where we will store our answer result = (struct num*) malloc(sizeof(struct num)); result->head = result->tail = NULL; //initialized //this loop makes sure we still have elements while(ptr1 != first_tail && ptr2 != second_tail){ //for the case where num2 has more digits than num1 if(ptr1 == first_tail && ptr2 != second_tail){ num1 = 0; num2 = ptr2->digit; ptr2 = ptr2->next; } //for the case where num1 has more digits than num2 else if(ptr2 == second_tail && ptr1 != first_tail){ num2 = 0; num1 = ptr1->digit; ptr1 = ptr1->next; } else{ num1 = ptr1 -> digit; num2 = ptr2 -> digit; ptr1 = ptr1->next; ptr2 = ptr2->next; } val = num1 + num2 + carry; //calculating val if(val > 9){ //if val is greater than 9 we will have a carry of 1, and we need to mod val to get carry = 1; //the least sig bit ex. say we have 5+7==12, 12 mod 10 = 2 which we would insert val = val % 10; insertBack(&result->head, &result->tail, val); }else{ //case where we can just insert and not have a carry carry = 0; insertBack(&result->head, &result->tail, val); } } val = ptr1->digit + ptr2->digit + carry; if(val > 9){ carry = 1; val = val % 10; insertBack(&result->head, &result->tail, val); insertBack(&result->head, &result->tail, carry); }else{ carry = 0; insertBack(&result->head, & result->tail, val); } //printList(&result->head, &result->tail); return result; } struct num * my_sub(struct list **head1, struct list **tail1, struct list **head2, struct list **tail2){ bool swap = false; //needed for if 2nd number is greater than 1st number int carry = 0; //basically just a suedo remainder struct num *result; result = (struct num*) malloc(sizeof(struct num)); result->head = result->tail = NULL; struct list *ptr1, *ptr2, *first_tail, *second_tail; if(isLargerThan(head1, tail1, head2, tail2)) { ptr1 = *head1; first_tail = *tail1; ptr2 = *head2; second_tail = *tail2; } else //if the 2nd number is larger, set the temp pointers the opposite of normal note that in swap variable { ptr2 = *head1; second_tail = *tail1; ptr1 = *head2; first_tail = *tail2; swap = true; } //traverses through the list while(ptr1 != first_tail && ptr2 != second_tail) { //if 2nd number is larger if(ptr1 != first_tail && ptr2 == second_tail) { insertBack(&result->head, &result->tail, ptr1->digit + carry); carry = 0; ptr1 = ptr1->next; } //if 1st number is larger else if(ptr1 == first_tail && ptr2 != second_tail) { insertBack(&result->head, &result->tail, ptr2->digit + carry); carry = 0; ptr2 = ptr2->next; } //if the 1st number is greater than 2nd number, subtract else if(ptr1->digit >= ptr2->digit) { //mainly just an edge case if(carry == -1 && ptr1->digit == ptr2->digit) { insertBack(&result->head, &result->tail, (ptr1->digit - ptr2->digit + carry + 10)); ptr1 = ptr1->next; ptr2 = ptr2->next; } else { insertBack(&result->head, &result->tail, (ptr1->digit - ptr2->digit + carry)); carry = 0; ptr1 = ptr1->next; ptr2 = ptr2->next; } } //if 2nd number is greater than 1st number, +10 then subtract, note that in carry variable else { insertBack(&result->head, &result->tail, (ptr1->digit + 10 - ptr2->digit + carry)); carry = -1; ptr1 = ptr1->next; ptr2 = ptr2->next; } } //same steps as while loop just done for tail if(ptr1->digit >= ptr2->digit) { insertBack(&result->head, &result->tail, (ptr1->digit - ptr2->digit + carry)); } else { insertBack(&result->head, &result->tail, (ptr1->digit + 10 - ptr2->digit + carry)); } if(swap) { insertBack(&result->head, &result->tail, -1); } return result; } //needed for subtraction bool isLargerThan(struct list **head1, struct list **tail1, struct list **head2, struct list **tail2) { struct list *ptr1, *ptr2, *first_tail, *second_tail; ptr1 = *head1; ptr2 = *head2; first_tail = *tail1; second_tail = *tail2; while(ptr1->next != first_tail && ptr2->next != second_tail) { //if statements in while loop check for equality amoung the last digits (since they're singly linked i had to choose how many to back-check; decide 3 digits is enough) if( (ptr1->next->next == first_tail && ptr2->next->next == second_tail) && ptr1->next->next->digit == ptr2->next->next->digit ) { if(ptr1->next->digit == ptr2->next->digit) { if(ptr1->digit >= ptr2->digit) { return true; } return false; } else if(ptr1->next->digit > ptr2->next->digit) { return true; } return false; } ptr1 = ptr1->next; ptr2 = ptr2->next; } ptr1 = ptr1->next; ptr2 = ptr2->next; if(ptr1 == first_tail && ptr2 == second_tail) { if(ptr1->digit > ptr2-> digit) { return true; } return false; } else if(ptr1 == first_tail) { return false; } return true; } struct num * dup_num(struct list **head1, struct list **tail1) { struct num * res = (struct num*) malloc(sizeof(struct num)); res->head = res->tail = NULL; struct list *ptr1, *ptr2; ptr1 = *head1; ptr2 = *tail1; while(ptr1 != ptr2) { insertBack(&res->head, &res->tail, ptr1->digit); ptr1 = ptr1->next; } insertBack(&res->head, &res->tail, ptr1->digit); return res; }
C++
UTF-8
556
2.578125
3
[]
no_license
#ifndef INFORMATIONOBJECT_H #define INFORMATIONOBJECT_H #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> using namespace cv; class InformationObject { public: InformationObject(); void setContours(vector<vector<Point>>); void setCenter(Point2f); void setRadius(float); vector<vector<Point>> getContours(); Point2f getCenter(); float getRadius(); private: vector<vector<Point>> contours; Point2f center; float radius; }; #endif // INFORMATIONOBJECT_H
Java
UTF-8
867
3.46875
3
[]
no_license
import java.util.Scanner; public class PopularVotes { public static void main (String[] args) { Scanner sc = new Scanner(System.in); int T = Integer.parseInt(sc.nextLine()); for (int i = 0; i < T; i++) { int N = Integer.parseInt(sc.nextLine()); int total = 0; int highest = -1; int winner = -1; int count = 0; for (int j = 0; j < N; j++) { int candidate = Integer.parseInt(sc.nextLine()); total += candidate; if (candidate > highest) { highest = candidate; winner = j + 1; count = 0; } else if (candidate == highest) { count++; } } if (count > 0) { System.out.println("no winner"); } else { if (highest > (total / 2)) { System.out.println("majority winner " + winner); } else { System.out.println("minority winner " + winner); } } } } }
Python
UTF-8
6,967
3.296875
3
[]
no_license
""" coordinates -- Manipulate and convert coordinates of different types Notes: - Currently, UTM calculations do not handle nonstandard zones. Sources: - http://www.uwgb.edu/dutchs/usefuldata/utmformulas.htm - https://en.wikipedia.org/wiki/ Universal_Transverse_Mercator_coordinate_system - https://en.wikipedia.org/wiki/Public_Land_Survey_System """ from math import (degrees, radians, sin, cos, tan, asin, acos, atan2, sinh, cosh, tanh, asinh, acosh, atanh, sqrt, hypot, ceil, floor) __all__ = [ 'from_utm', 'to_utm', 'from_dms', 'to_dms', 'great_circle', 'bounding_box' ] # Constants a, f = 6378.137, 1/298.257223563 # Equatorial radius (km) and flattening k0, easting_ = 0.9996, 500 # Point scale factor and false easting # Derived values n = f/(2 - f) A = a/(1 + n)*(1 + pow(n, 2)/4 + pow(n, 4)/64) alpha = ( n/2 - 2/3*pow(n, 2) + 5/16*pow(n, 3), 13/48*pow(n, 2) - 3/5*pow(n, 3), 61/240*pow(n, 3) ) beta = ( n/2 - 2/3*pow(n, 2) + 37/96*pow(n, 3), pow(n, 2)/48 + pow(n, 3)/15, 17/480*pow(n, 3) ) delta = ( 2*n - 2/3*pow(n, 2) - 2*pow(n, 3), 7/3*pow(n, 2) - 8/5*pow(n, 3), 56/15*pow(n, 3) ) def from_utm(easting: float, northing: float, zone: int, hemisphere: int =1) -> (float, float): """ Convert UTM coordinates to decimal latitude and longitude coordinates. Keyword Arguments: easting: The easting in m. northing: The northing in m. zone: The zone, an integer between 1 and 60, inclusive. hemisphere: A signed number, where a negative number indicates the coordinates are located in the southern hemisphere. Returns: latitude: The latitude in decimal degrees. longitude: The longitude in deciaml degrees. Raises: OverflowError: The coordinate does not exist. """ easting, northing = easting/1000, northing/1000 northing_ = 10000 if hemisphere < 0 else 0 xi_ = xi = (northing - northing_)/(k0*A) eta_ = eta = (easting - easting_)/(k0*A) for j in range(1, 4): p, q = 2*j*xi, 2*j*eta xi_ -= beta[j - 1]*sin(p)*cosh(q) eta_ -= beta[j - 1]*cos(p)*sinh(q) chi = asin(sin(xi_)/cosh(eta_)) latitude = chi + sum(delta[j - 1]*sin(2*j*chi) for j in range(1, 4)) longitude_ = radians(6*zone - 183) longitude = longitude_ + atan2(sinh(eta_), cos(xi_)) return degrees(latitude), degrees(longitude) def to_utm(latitude: float, longitude: float) -> (float, float, int, int): """ Convert decimal latitude and longitude coordinates to UTM coordinates. Keyword Arguments: latitude: The latitude in decimal degrees. longitude: The longitude in decimal degrees. Returns: easting: The easting in m. northing: The northing in m. zone: The zone, an integer between 1 and 60, inclusive. hemisphere: A signed number, where a negative number indicates the coordinates are located in the southern hemisphere. Raises: OverflowError: The coordinate does not exist. """ if abs(latitude) > 84: raise ValueError('Polar regions not covered') zone = 1 + floor((longitude + 180)/6) latitude, longitude = radians(latitude), radians(longitude) longitude_ = radians(6*zone - 183) p = 2*sqrt(n)/(1 + n) t = sinh(atanh(sin(latitude)) - p*atanh(p*sin(latitude))) xi_ = atan2(t, cos(longitude - longitude_)) eta_ = atanh(sin(longitude - longitude_)/hypot(1, t)) sigma, tau, u, v = 1, 0, 0, 0 for j in range(1, 4): p, q = 2*j*xi_, 2*j*eta_ sigma += 2*j*alpha[j - 1]*cos(p)*cosh(q) tau += 2*j*alpha[j - 1]*sin(p)*sinh(q) u += alpha[j - 1]*cos(p)*sinh(q) v += alpha[j - 1]*sin(p)*cosh(q) hemisphere = -1 if latitude < 0 else 1 northing_ = 10000 if hemisphere < 0 else 0 easting = easting_ + k0*A*(eta_ + 0) northing = northing_ + k0*A*(xi_ + 0) return 1000*easting, 1000*northing, zone, hemisphere def from_dms(degrees: float, minutes: float, seconds: float, sign: int =1) -> (float): """ Convert degree, minute, and second components to a decimal angle. Keyword Arguments: degrees: The number of degrees. minutes: The number of minutes. seconds: The number of seconds. sign: A positive or negative integer indicating the sign of the angle. Returns: decimal: The number of degrees as as single decimal. """ sign = -1 if sign < 0 else 1 return sign*(abs(degrees) + abs(minutes)/60.0 + abs(seconds)/3600.0) def to_dms(decimal: float) -> (float, float, float, int): """ Convert a decimal angle to degree, minute, and second components. Keyword Arguments: decimal: The number of degrees as as single decimal. Returns: degrees: The number of degrees. minutes: The number of minutes. seconds: The number of seconds. sign: A positive or negative integer indicating the sign of the angle. """ sign, decimal = (-1 if decimal < 0 else 1), abs(decimal) degrees, minutes = decimal//1.0, 60*(decimal%1.0) minutes, seconds = minutes//1.0, 60*(minutes%1.0) return degrees, minutes, seconds, sign def great_circle(latitude1: float, longitude1: float, latitude2: float, longitude2: float) -> (float): """ Calculate the angle between two points on the surface of a sphere. Multiply this angle by the sphere's radius to obtain the distance along the surface between the two points. Keyword Arguments: latitude1: The latitude of the first point, in decimal degrees. longitude1: The longitude of the first point, in decimal degrees. latitude2: The latitude of the second point, in decimal degrees. longitude2: The longitude of the second point, in decimal degrees. Returns: angle: The angle between the two points. """ latitude1, latitude2 = radians(latitude1), radians(latitude2) delta = radians(abs(longitude1 - longitude2)) p = sin(latitude1)*sin(latitude2) q = cos(latitude1)*cos(latitude2)*cos(delta) return degrees(acos(p + q)) def bounding_box(latitude: float, longitude: float, side: float) -> ( float, float, float, float): """ Calculate the southwest and northeast coordinates of a bounding box. Keyword Arguments: latitude: The latitude of the center of the box, in decimal degrees. longitude: The longitude of the center of the box, in decimal degrees. side: The length of each side of the box. Returns: south: The latitude of the southern bound of the box. west: The longitude of the western bound of the box. north: The latitude of the northern bound of the box. east: The longitude of the eastern bound of the box. """ ...
JavaScript
UTF-8
616
2.8125
3
[]
no_license
const Discord = require('discord.js') module.exports = { name: 'embed', description: 'send embed message', execute(msg, args){ if (!msg.member.hasPermission("MANAGE_MESSAGES")) return msg.channel.send("You lack the permissions to run this command"); let message1 = args.join(" "); msg.delete().catch(); const embedcmd = new Discord.MessageEmbed() .setTitle("Embeded Message") .setColor("#30BFBF") .setThumbnail(msg.author.avatarURL()) .addField("Message sent", message1) .setFooter(`Sent by ${msg.author.tag}`); msg.channel.send(embedcmd); } }
JavaScript
UTF-8
1,931
3.71875
4
[]
no_license
// 210. Course Schedule II // There are a total of n courses you have to take labelled from 0 to n - 1. // Some courses may have prerequisites, for example, if prerequisites[i] = [ai, bi] this means you must take the course bi before the course ai. // Given the total number of courses numCourses and a list of the prerequisite pairs, return the ordering of courses you should take to finish all courses. // If there are many valid answers, return any of them. If it is impossible to finish all courses, return an empty array. /** * @param {number} numCourses * @param {number[][]} prerequisites * @return {number[]} */ var findOrder = function (numCourses, prerequisites) { let adj = new Map(); // generate adj list for (let i = 0; i < prerequisites.length; i++) { let [parent, child] = prerequisites[i]; if (adj.has(parent)) { adj.get(parent).push(child); } else { adj.set(parent, [child]) } } let topoOrder = []; let tracked = new Set(); let curPath = new Set(); let dfs = node => { // onnce we checked for circle a set of nodes - we don't have to do that again if (curPath.has(node)) return true; if (tracked.has(node)) return false; tracked.add(node); curPath.add(node); let children = adj.get(node); if (children) { for (let i = 0; i < children.length; i++) { if (dfs(children[i])) return true; } } curPath.delete(node); topoOrder.push(node); return false; } for (let i = 0; i < numCourses; i++) { // dfs(i) returns true in case of existing circle if (dfs(i)) return []; } // No reverse as contition is about prerequisites, not dependencies return topoOrder; }; console.log(findOrder(2, [[0, 1], [1, 0]])); // [] console.log(findOrder(2, [[1, 0]])); // [0,1]
TypeScript
UTF-8
930
2.796875
3
[]
no_license
import jwtHelper from "../helper/JwtHelper"; const debug = console.log.bind(console); /** * Middleware: Authorization user by Token * @param {*} req * @param {*} res * @param {*} next */ const isAuth = async (req, res, next): Promise<void> => { const tokenFromClient = req?.header("Authorization")?.replace("Bearer ", ""); if (tokenFromClient) { try { req.jwtDecoded = await jwtHelper.verifyToken(tokenFromClient); console.log("req.jwtDecoded = ", req.jwtDecoded); next(); } catch (error) { if (error?.name === 'TokenExpiredError') { return res.status(401).json({ message: "Token expired", }); } debug("Error while verify token:", error); return res.status(401).json({ message: "Unauthorized.", }); } } else { return res.status(403).send({ message: "No token provided.", }); } }; export default {isAuth};
Python
UTF-8
978
3.765625
4
[]
no_license
import numpy as np # matrix with data type npa = np.array(([1,2,3],[4,5,6]), dtype=int) npb = np.array(([1,3,3],[4,7,6]), dtype=float) print(npa) print(npb) #matrix with fromfunction def kuadrat(baris,kolom): return kolom**2 def jumlah(baris,kolom): return baris+kolom hasil = np.fromfunction(kuadrat, (1,8), dtype = int) print(hasil) print("-"*50) hasil = np.fromfunction(jumlah, (3,3), dtype = float) print(hasil) print("-"*50) # from iterable iterable = (x*x for x in range (0,5)) #print(iterable) npc = np.fromiter(iterable, dtype = int) print(npc) #multitype array dtipe1 = [('nama','S255'),('tinggi',int)] data = [ ("Mario",100), ("Zelda",200), ("Luigi",80)] npd = np.array(data, dtype=dtipe1) print(npd) print(npd[1]) dtipe2 = [('nama','S255'),('tinggi',int), ('power', float)] data = [ ("Mario",100, 111.5), ("Zelda",200, 100.5), ("Luigi",80, 80)] npd = np.array(data, dtype=dtipe2) print(npd) print(npd[1])
Java
UTF-8
1,689
2.765625
3
[]
no_license
package com.android.curso.simplelist2; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity { private List<Persona> listaPersonas; private ListView lista; private ArrayAdapter<Persona> adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); listaPersonas=new ArrayList<>(); listaPersonas.add(new Persona("pepe","mora","lopez")); listaPersonas.add(new Persona("ana","gomez","perez")); lista=(ListView)findViewById(R.id.lista); adapter=new ArrayAdapter<Persona> (this, android.R.layout.simple_list_item_2, android.R.id.text1, listaPersonas) { @Override public View getView(int position, View convertView, ViewGroup parent) { View view = super.getView(position, convertView, parent); TextView text1 = (TextView) view.findViewById(android.R.id.text1); TextView text2 = (TextView) view.findViewById(android.R.id.text2); text1.setText(listaPersonas.get(position).getNombre()); text2.setText( listaPersonas.get(position).getPrimerApellido()+" "+ listaPersonas.get(position).getSegundoApellido()); return view; } }; lista.setAdapter(adapter); } }
SQL
UTF-8
2,374
3.15625
3
[]
no_license
--mysql -u root -p -- create datase oauth_admin; -- use oauth_admin; drop table if exists oauth_client_details; create table oauth_client_details ( client_id VARCHAR(255) PRIMARY KEY, resource_ids VARCHAR(255), client_secret VARCHAR(255), scope VARCHAR(255), authorized_grant_types VARCHAR(255), web_server_redirect_uri VARCHAR(255), authorities VARCHAR(255), access_token_validity INTEGER, refresh_token_validity INTEGER, additional_information VARCHAR(4096), autoapprove VARCHAR(255) ); drop table if exists oauth_client_token; create table oauth_client_token ( token_id VARCHAR(255), token LONG VARBINARY, authentication_id VARCHAR(255) PRIMARY KEY, user_name VARCHAR(255), client_id VARCHAR(255) ); drop table if exists oauth_access_token; create table oauth_access_token ( token_id VARCHAR(255), token LONG VARBINARY, authentication_id VARCHAR(255) PRIMARY KEY, user_name VARCHAR(255), client_id VARCHAR(255), authentication LONG VARBINARY, refresh_token VARCHAR(255) ); drop table if exists oauth_refresh_token; create table oauth_refresh_token ( token_id VARCHAR(255), token LONG VARBINARY, authentication LONG VARBINARY ); drop table if exists oauth_code; create table oauth_code ( code VARCHAR(255), authentication LONG VARBINARY ); drop table if exists oauth_approvals; create table oauth_approvals ( userId VARCHAR(255), clientId VARCHAR(255), scope VARCHAR(255), status VARCHAR(10), expiresAt TIMESTAMP, lastModifiedAt TIMESTAMP ); drop table if exists ClientDetails; create table ClientDetails ( appId VARCHAR(255) PRIMARY KEY, resourceIds VARCHAR(255), appSecret VARCHAR(255), scope VARCHAR(255), grantTypes VARCHAR(255), redirectUrl VARCHAR(255), authorities VARCHAR(255), access_token_validity INTEGER, refresh_token_validity INTEGER, additionalInformation VARCHAR(4096), autoApproveScopes VARCHAR(255) ); select * from oauth_client_details; select * from oauth_client_token; select * from oauth_access_token; select * from oauth_refresh_token; select * from oauth_code; select * from oauth_approvals; select * from ClientDetails; delete from oauth_client_details; delete from oauth_client_token; delete from oauth_access_token; delete from oauth_refresh_token; delete from oauth_code; delete from oauth_approvals; delete from ClientDetails;
PHP
UTF-8
2,452
2.65625
3
[]
no_license
<?php namespace Application\Service; //use Zend\ServiceManager\ServiceManager; //use Zend\ServiceManager\ServiceManagerAwareInterface; //use Application\Entity\Admin; //use Zend\Filter\StaticFilter; use User\Entity\User; use Application\Entity\Setting; use Zend\Crypt\Password\Bcrypt; /** * The AdminManager service is responsible for save settings, updating existing */ class SettingManager { /** * Entity manager. * @var $entityManager Doctrine\ORM\EntityManager; */ private $entityManager; /** * Constructor. */ public function __construct($entityManager) { $this->entityManager = $entityManager; } /** * This method adds a new post. * @var $user User\Entity\User */ public function createDefaultSetting($user) { /* @var $userData \User\Entity\User */ $userData = $user; $setting = new Setting(); $setting->setUserId($userData->getId()); $setting->setCeleJmeno("Nenastaveno"); $setting->setTelefon("Nenastaveno"); $setting->setUmisteni("Nenastaveno"); $setting->setUser($user); $setting->setEmail($userData->getEmail()); $aktualni_datum = new \DateTime("now"); $aktualni_datum->format('Y-m-d H:i:s'); $setting->setLastOnline($aktualni_datum); $this->entityManager->persist($setting); // Apply changes to database. $this->entityManager->flush(); } /** * This method allows to update data of a single post. */ public function updateAdmin(\Application\Entity\Setting $setting, $data) { /* @var $user \User\Entity\User */ $user = $this->entityManager->getRepository(User::class)->findOneById($data['id']); $setting->setCeleJmeno($data['cele_jmeno']); $setting->setUmisteni($data['umisteni']); //$setting->setEmail($data['email']); $setting->setTelefon($data['telefon']); $aktualni_datum = new \DateTime("now"); $aktualni_datum->format('Y-m-d H:i:s'); $setting->setLastOnline($aktualni_datum); $this->entityManager->flush(); if (strlen($data['heslo']) > 1) { $bcrypt = new Bcrypt(); $passwordHash = $bcrypt->create($data['heslo']); $user->setPassword($passwordHash); $this->entityManager->persist($user); $this->entityManager->flush(); } } }
TypeScript
UTF-8
86
2.796875
3
[]
no_license
export const compose = <A, B, C>(f: (b: B) => C, g: (a: A) => B) => (a: A) => f(g(a))
Shell
UTF-8
143
3.53125
4
[]
no_license
#set -x set -e data_root=$1 if [[ ! -d ${data_root} ]]; then echo "error: first arg (${data_root}) needs to be an existing directory." fi
Java
UTF-8
180
1.539063
2
[]
no_license
package com.cooksys.conversion_tracking.tx; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=false) public class TXShort { Integer num; }
Python
UTF-8
771
3.875
4
[]
no_license
def convert_time(string): print('converting %s...' % string) if 'AM' in string: print('the time is in the AM.') if string[:2] == '12': print('it starts with 12, so change it to 00 instead.') string = '00%s' % string[2:] return string[:len(string) - 2] elif 'PM' in string: print('the time is in the PM.') if string[:2] == '12': pass else: print('the time is after 12, so add 12 to get the military time.') string = '%s%s' % (str(int(string[:2]) + 12), string[2:]) return string[:len(string) - 2] print('AM tests:') print(convert_time('12:00:01AM')) print(convert_time('10:00:01AM')) print(convert_time('09:00:01AM')) print('PM tests:') print(convert_time('12:00:01PM')) print(convert_time('10:00:01PM')) print(convert_time('09:00:01PM'))
Java
UTF-8
1,101
2.828125
3
[ "MIT" ]
permissive
package com.socrata.datasync.deltaimporter2; import java.io.IOException; import java.io.InputStream; public abstract class ProgressingInputStream extends InputStream { private final InputStream underlying; private long count = 0L; private long lastSentAt = 0L; public ProgressingInputStream(InputStream underlying) { this.underlying = underlying; } @Override public int read() throws IOException { int r = underlying.read(); if(r != -1) advanceBy(1); return r; } @Override public int read(byte[] buf, int off, int len) throws IOException { int r = underlying.read(buf, off, len); if(r != -1) advanceBy(r); return r; } @Override public void close() throws IOException { underlying.close(); } private void advanceBy(int howMuch) { count += howMuch; long now = System.currentTimeMillis(); if(now >= lastSentAt + 5000) { progress(count); lastSentAt = now; } } protected abstract void progress(long count); }
Java
UTF-8
458
2.453125
2
[ "MIT" ]
permissive
package gameView.observers; import entity.restricted.IRestrictedEntity; import java.util.Observable; import java.util.Observer; public class EntityObserver implements Observer { private ObserverManager myObserverManager; public EntityObserver(ObserverManager images) { myObserverManager = images; } @Override public void update(Observable o, Object arg) { myObserverManager.updateEntity((IRestrictedEntity) o, (IRestrictedEntity) arg); } }
Java
UTF-8
7,199
1.679688
2
[ "Apache-2.0" ]
permissive
/* * Licensed to David Pilato (the "Author") under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. Author licenses this * file to you 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 fr.pilato.spring.elasticsearch.it.xml.transport; import fr.pilato.spring.elasticsearch.it.BaseTest; import fr.pilato.spring.elasticsearch.proxy.GenericInvocationHandler; import org.elasticsearch.action.admin.cluster.state.ClusterStateResponse; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.support.WriteRequest; import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MappingMetaData; import org.elasticsearch.common.transport.TransportAddress; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.aop.framework.Advised; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.lang.reflect.Proxy; import java.util.List; import java.util.concurrent.ExecutionException; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.emptyCollectionOf; import static org.hamcrest.Matchers.instanceOf; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.nullValue; import static org.junit.jupiter.api.Assertions.fail; public abstract class AbstractXmlContextModel extends BaseTest { private ConfigurableApplicationContext ctx; /** * @return list of xml files needed to be loaded for this test */ abstract String[] xmlBeans(); @BeforeEach public void startContext() { String[] xmlBeans = xmlBeans(); // Let's hack the context depending if the test cluster is running securely or not if (securityInstalled) { String[] securedXmlBeans = new String[xmlBeans.length]; for (int i = 0; i < xmlBeans.length; i++) { securedXmlBeans[i] = xmlBeans[i].replace("models/transport/", "models/transport-xpack/"); } xmlBeans = securedXmlBeans; } if (xmlBeans.length == 0) { fail("Can not start a factory without any context!"); } logger.info(" --> Starting Spring Context with [{}] file(s)", xmlBeans.length); for (String xmlBean : xmlBeans) { logger.info(" - {}", xmlBean); } ctx = new ClassPathXmlApplicationContext(xmlBeans); } @AfterEach public void stopContext() { if (ctx != null) { logger.info(" --> Closing Spring Context"); ctx.close(); } } Client checkClient(String name) { return checkClient(name, null); } Client checkClient(String name, Boolean async) { Client client; if (name != null) { client = ctx.getBean(name, Client.class); } else { client = ctx.getBean(Client.class); } if (async != null) { if (async) { assertThat(client, instanceOf(Advised.class)); assertThat(((Advised) client).getAdvisors()[0].getAdvice() , instanceOf(GenericInvocationHandler.class)); } else { try { Proxy.getInvocationHandler(client); fail("Must not be proxyfied"); } catch (IllegalArgumentException e) { // We expect that } } } assertThat(client, not(nullValue())); return client; } boolean isMappingExist(Client client, String index, String type) { ClusterState cs = client.admin().cluster().prepareState().setIndices(index).get().getState(); IndexMetaData imd = cs.getMetaData().index(index); if (imd == null) return false; MappingMetaData mdd = imd.mapping(type); return mdd != null; } @Test public void testFactoriesCreated() throws ExecutionException, InterruptedException { Client client = checkClient(beanName()); checkUseCaseSpecific(client); // If an index is expected, let's check it actually exists if (indexName() != null) { // We test how many shards and replica we have assertShardsAndReplicas(client, indexName(), expectedShards(), expectedReplicas()); client.admin().cluster().prepareState().execute().get(); // #92: prepareSearch() errors with async created TransportClient client.prepareIndex("twitter", "tweet").setSource("foo", "bar").setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get(); SearchResponse response = client.prepareSearch("twitter").get(); assertThat(response.getHits().getTotalHits(), is(1L)); } } /** * Overwrite it to implement use case specific tests * @param client Client representing bean named esClient */ protected void checkUseCaseSpecific(Client client) { } /** * Overwrite it if the number of expected shards is not 5 * @return Number of expected primaries */ protected int expectedShards() { return 5; } /** * Overwrite it if the number of expected replicas is not 1 * @return Number of expected replicas */ protected int expectedReplicas() { return 1; } protected String beanName() { return "esClient"; } void assertShardsAndReplicas(Client client, String indexName, int expectedShards, int expectedReplicas) { ClusterStateResponse response = client.admin().cluster().prepareState().execute().actionGet(); assertThat(response.getState().getMetaData().getIndices().get(indexName).getNumberOfShards(), is(expectedShards)); assertThat(response.getState().getMetaData().getIndices().get(indexName).getNumberOfReplicas(), is(expectedReplicas)); } void assertTransportClient(Client client, int expectedAdresses) { assertThat(client, instanceOf(TransportClient.class)); TransportClient tClient = (TransportClient) client; List<TransportAddress> addresses = tClient.transportAddresses(); assertThat(addresses, not(emptyCollectionOf(TransportAddress.class))); assertThat(addresses.size(), is(expectedAdresses)); } }